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

96% Statements 48/50
75.26% Branches 73/97
77.78% Functions 7/9
95.83% Lines 46/48

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              11x 11x 11x 11x 11x 11x 11x 11x   11x 11x     11x             11x 11x 11x 11x 11x         11x   11x 11x 11x 11x 11x     11x 7x 8x     7x 7x   7x                           7x                                       11x 2x 1x 1x       1x   1x   1x                       1x                   1x 1x   1x 1x 1x                                       1x                                             1x                                   2x                           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, { useState } from 'react'
import { Container, PageHeader } from '@wings-software/uicore'
import { useHistory, useParams } from 'react-router-dom'
import { defaultTo, get } from 'lodash-es'
import moment from 'moment'
import routes from '@common/RouteDefinitions'
import { Page } from '@common/exports'
import { useStrings } from 'framework/strings'
import type { ProjectPathProps } from '@common/interfaces/RouteInterfaces'
import CardRailView from '@pipeline/components/Dashboards/CardRailView/CardRailView'
import { useGetWorkloads, useGetDeployments, CDPipelineModuleInfo, ExecutionStatusInfo } from 'services/cd-ng'
import type { CIBuildCommit, CIWebhookInfoDTO } from 'services/ci'
import type { PipelineExecutionSummary } from 'services/pipeline-ng'
import {
  ActiveStatus,
  FailedStatus,
  mapToExecutionStatus,
  useErrorHandler,
  useRefetchCall
} from '@pipeline/components/Dashboards/shared'
import { NGBreadcrumbs } from '@common/components/NGBreadcrumbs/NGBreadcrumbs'
import { useDocumentTitle } from '@common/hooks/useDocumentTitle'
import ExecutionCard from '@pipeline/components/ExecutionCard/ExecutionCard'
import { CardVariant } from '@pipeline/utils/constants'
import {
  startOfDay,
  TimeRangeSelector,
  TimeRangeSelectorProps
} from '@common/components/TimeRangeSelector/TimeRangeSelector'
import { DeploymentsTimeRangeContext } from '@cd/components/Services/common'
 
import { TitleWithToolTipId } from '@common/components/Title/TitleWithToolTipId'
import DeploymentsHealthCards from './DeploymentsHealthCards'
import DeploymentExecutionsChart from './DeploymentExecutionsChart'
import WorkloadCard from './DeploymentCards/WorkloadCard'
import styles from './CDDashboardPage.module.scss'
 
/** TODO: fix types after BE merge */
export function executionStatusInfoToExecutionSummary(info: ExecutionStatusInfo): PipelineExecutionSummary {
  const cd: CDPipelineModuleInfo = {
    serviceIdentifiers: info.serviceInfoList?.map(({ serviceName }) => defaultTo(serviceName, '')).filter(svc => !!svc)
  }
 
  const branch = get(info, 'gitInfo.targetBranch')
  const commits: CIBuildCommit[] = [{ message: get(info, 'gitInfo.commit'), id: get(info, 'gitInfo.commitID') }]
 
  const ciExecutionInfoDTO: CIWebhookInfoDTO = {
    author: info.author,
    event: get(info, 'gitInfo.eventType'),
    branch: {
      name: get(info, 'gitInfo.sourceBranch'),
      commits
    },
    pullRequest: {
      sourceBranch: get(info, 'gitInfo.sourceBranch'),
      targetBranch: branch,
      commits
    }
  }
 
  return {
    startTs: info.startTs,
    endTs: typeof info.endTs === 'number' && info.endTs > 0 ? info.endTs : undefined,
    name: info.pipelineName,
    status: mapToExecutionStatus(info.status),
    planExecutionId: info.planExecutionId,
    pipelineIdentifier: info.pipelineIdentifier,
    moduleInfo: {
      cd: cd as any,
      ci: (branch ? { ciExecutionInfoDTO, branch } : undefined) as any
    },
    executionTriggerInfo: {
      triggeredBy: {
        identifier: info.author?.name
      },
      triggerType: info.triggerType as Required<PipelineExecutionSummary>['executionTriggerInfo']['triggerType']
    }
  }
}
 
export const CDDashboardPage: React.FC = () => {
  const { projectIdentifier, orgIdentifier, accountId } = useParams<ProjectPathProps>()
  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 history = useHistory()
 
  useDocumentTitle([getString('deploymentsText'), getString('overview')])
 
  const { data, loading, error, refetch } = useGetDeployments({
    queryParams: {
      accountIdentifier: accountId,
      projectIdentifier,
      orgIdentifier
    }
  })
 
  const {
    data: workloadsData,
    loading: loadingWorkloads,
    error: workloadsError
  } = useGetWorkloads({
    queryParams: {
      accountIdentifier: accountId,
      projectIdentifier,
      orgIdentifier,
      startTime: timeRange?.range[0]?.getTime() || 0,
      endTime: timeRange?.range[1]?.getTime() || 0
    }
  })
 
  useErrorHandler(error)
  useErrorHandler(workloadsError)
 
  const refetchingDeployments = useRefetchCall(refetch, loading)
  const activeDeployments = [...(data?.data?.active ?? []), ...(data?.data?.pending ?? [])]
  return (
    <>
      <PageHeader
        title={<TitleWithToolTipId title={getString('overview')} toolTipId={'cdOverViewTitle'} />}
        breadcrumbs={<NGBreadcrumbs links={[]} />}
        toolbar={
          <>
            <TimeRangeSelector timeRange={timeRange?.range} setTimeRange={setTimeRange} minimal />
          </>
        }
      ></PageHeader>
      <Page.Body className={styles.content} loading={(loading && !refetchingDeployments) || loadingWorkloads}>
        <DeploymentsTimeRangeContext.Provider value={{ timeRange, setTimeRange }}>
          <Container className={styles.page} padding="large">
            <DeploymentsHealthCards range={timeRange} setRange={setTimeRange} title="Deployments Health" />
            <Container className={styles.executionsWrapper}>
              <DeploymentExecutionsChart range={timeRange} setRange={setTimeRange} title="Deployments" />
            </Container>
            <CardRailView contentType="WORKLOAD" isLoading={loadingWorkloads}>
              {workloadsData?.data?.workloadDeploymentInfoList?.map((workload, i) => (
                <WorkloadCard
                  key={i}
                  serviceName={workload.serviceName!}
                  lastExecuted={workload?.lastExecuted}
                  totalDeployments={workload.totalDeployments!}
                  percentSuccess={workload.percentSuccess!}
                  rateSuccess={workload.rateSuccess!}
                  workload={workload.workload}
                  serviceId={workload.serviceId}
                />
              ))}
            </CardRailView>
            <CardRailView
              contentType="FAILED_DEPLOYMENT"
              isLoading={loading && !refetchingDeployments}
              onShowAll={() =>
                history.push(
                  routes.toDeployments({ projectIdentifier, orgIdentifier, accountId, module: 'cd' }) +
                    `?filters=${JSON.stringify({ status: Object.keys(FailedStatus) })}`
                )
              }
            >
              {data?.data?.failure?.map((d, i) => (
                <ExecutionCard
                  variant={CardVariant.Minimal}
                  key={i}
                  pipelineExecution={executionStatusInfoToExecutionSummary(d)}
                />
              ))}
            </CardRailView>
            <CardRailView
              contentType="ACTIVE_DEPLOYMENT"
              isLoading={loading && !refetchingDeployments}
              onShowAll={() =>
                history.push(
                  routes.toDeployments({ projectIdentifier, orgIdentifier, accountId, module: 'cd' }) +
                    `?filters=${JSON.stringify({ status: Object.keys(ActiveStatus) })}`
                )
              }
            >
              {activeDeployments.map((d, i) => (
                <ExecutionCard
                  variant={CardVariant.Minimal}
                  key={i}
                  pipelineExecution={executionStatusInfoToExecutionSummary(d)}
                />
              ))}
            </CardRailView>
          </Container>
        </DeploymentsTimeRangeContext.Provider>
      </Page.Body>
    </>
  )
}
 
export default CDDashboardPage