All files / modules/70-pipeline/pages/pipeline-deployment-list PipelineDeploymentList.tsx

91.92% Statements 91/99
66.86% Branches 113/169
72.73% Functions 16/22
91.92% Lines 91/99

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              6x 6x 6x 6x 6x 6x               6x 6x 6x 6x   6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x   6x 6x 6x   6x               6x             54x             54x     6x 54x   6x                         54x   207x             6x             54x 54x 54x 54x 23x     23x     54x     6x                     54x 31x   23x                                                       23x 23x                                                                                           6x   58x 55x 54x 54x 54x   54x   54x 54x         54x         57x                 54x   54x   54x               54x 54x 54x   54x                       54x 12x 12x     54x 54x             54x                                                               54x               54x 54x 54x           54x 12x 2x 2x 2x 2x           12x 10x         54x 12x     54x           54x   54x                                 54x   54x                                                                                                                  
/*
 * 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, { useCallback } from 'react'
import { useParams, useHistory } from 'react-router-dom'
import { Text, Icon, OverlaySpinner, Container, Layout } from '@wings-software/uicore'
import { Color } from '@harness/design-system'
import routes from '@common/RouteDefinitions'
import {
  useGetListOfExecutions,
  useGetFilterList,
  GetListOfExecutionsQueryParams,
  useGetPipelineList,
  PMSPipelineSummaryResponse,
  PagePipelineExecutionSummary
} from 'services/pipeline-ng'
import { String, useStrings, UseStringsReturn } from 'framework/strings'
import { GitSyncStoreProvider } from 'framework/GitRepoStore/GitSyncStoreContext'
import { Page, StringUtils } from '@common/exports'
import { useQueryParams, useMutateAsGet, useUpdateQueryParams } from '@common/hooks'
import type { PipelinePathProps, PipelineType } from '@common/interfaces/RouteInterfaces'
import { UNSAVED_FILTER } from '@common/components/Filter/utils/FilterUtils'
import { PermissionIdentifier } from '@rbac/interfaces/PermissionIdentifier'
import { ResourceType } from '@rbac/interfaces/ResourceType'
import RbacButton from '@rbac/components/Button/Button'
import PipelineSummaryCards from '@pipeline/components/Dashboards/PipelineSummaryCards/PipelineSummaryCards'
import PipelineBuildExecutionsChart from '@pipeline/components/Dashboards/BuildExecutionsChart/PipelineBuildExecutionsChart'
import useTabVisible from '@common/hooks/useTabVisible'
import { isCDCommunity, useLicenseStore } from 'framework/LicenseStore/LicenseStoreContext'
import ExecutionsList from './ExecutionsList/ExecutionsList'
import ExecutionsPagination from './ExecutionsPagination/ExecutionsPagination'
import { PipelineDeploymentListHeader } from './PipelineDeploymentListHeader/PipelineDeploymentListHeader'
import { FilterContextProvider } from './FiltersContext/FiltersContext'
import type { QueryParams, StringQueryParams, QuickStatusParam } from './types'
import deploymentIllustrations from './images/deployments-illustrations.svg'
import buildIllustrations from './images/builds-illustrations.svg'
import css from './PipelineDeploymentList.module.scss'
 
const pollingIntervalInMilliseconds = 5_000
 
export interface PipelineDeploymentListProps {
  onRunPipeline(): void
  showHealthAndExecution?: boolean
  isPipelineInvalid?: boolean
}
 
const renderSpinner = ({
  loading,
  pollingRequest
}: {
  loading?: boolean
  pollingRequest: boolean
}): JSX.Element | null => {
  Iif (loading && !pollingRequest) {
    return (
      <OverlaySpinner show={true} className={css.loading}>
        <div />
      </OverlaySpinner>
    )
  }
  return null
}
 
const getHasFilterIdentifier = (filterIdentifier?: string): boolean =>
  (filterIdentifier && filterIdentifier !== StringUtils.getIdentifierFromName(UNSAVED_FILTER)) || false
 
const getHasFilters = ({
  queryParams,
  filterIdentifier,
  searchTerm,
  myDeployments,
  status
}: {
  queryParams: QueryParams
  filterIdentifier?: string
  searchTerm?: string
  myDeployments?: boolean
  status: GetListOfExecutionsQueryParams['status']
}): boolean => {
  return (
    [queryParams.pipelineIdentifier, queryParams.filters, filterIdentifier, searchTerm].some(
      filter => filter !== undefined
    ) ||
    myDeployments ||
    (Array.isArray(status) && status.length > 0)
  )
}
 
const getCreateRunPipeline = ({
  pipelineExecutionSummary,
  pipelineDataElements
}: {
  pipelineExecutionSummary: PagePipelineExecutionSummary | undefined
  pipelineDataElements: number | undefined
}): { createPipeline: boolean; runPipeline: boolean } => {
  let createPipeline = false
  let runPipeline = false
  const executionPresent = !!pipelineExecutionSummary?.content?.length
  if (!executionPresent) {
    Iif (pipelineDataElements === 0) {
      createPipeline = true
    } else {
      runPipeline = true
    }
  }
  return { createPipeline, runPipeline }
}
 
const renderDeploymentListHeader = ({
  pipelineExecutionSummary,
  hasFilters,
  onRunPipeline,
  isPipelineInvalid
}: {
  pipelineExecutionSummary: PagePipelineExecutionSummary
  hasFilters: boolean
  onRunPipeline: () => void
  isPipelineInvalid?: boolean
}): JSX.Element | null => {
  if (!!pipelineExecutionSummary?.content?.length || hasFilters) {
    return <PipelineDeploymentListHeader onRunPipeline={onRunPipeline} isPipelineInvalid={isPipelineInvalid} />
  }
  return null
}
 
function NoDeployments(props: {
  hasFilters: boolean
  isCIModule: boolean
  getString: UseStringsReturn['getString']
  clearFilters: () => void
  runPipeline: boolean
  createPipeline: boolean
  goToPipeline: (pipeline?: PMSPipelineSummaryResponse | undefined) => void
  pipelineIdentifier: string
  queryParams: QueryParams
  onRunPipeline: () => void
  isPipelineInvalid?: boolean
}): JSX.Element {
  const {
    hasFilters,
    isCIModule,
    getString,
    clearFilters,
    runPipeline,
    createPipeline,
    goToPipeline,
    pipelineIdentifier,
    queryParams,
    onRunPipeline,
    isPipelineInvalid
  } = props || {}
  return (
    <div className={css.noDeploymentSection}>
      {hasFilters ? (
        <Layout.Vertical spacing="small" flex>
          <Icon size={50} name={isCIModule ? 'ci-main' : 'cd-main'} margin={{ bottom: 'large' }} />
          <Text
            margin={{ top: 'large', bottom: 'small' }}
            font={{ weight: 'bold', size: 'medium' }}
            color={Color.GREY_800}
          >
            {getString('common.filters.noMatchingFilterData')}
          </Text>
          <String stringID="common.filters.clearFilters" className={css.clearFilterText} onClick={clearFilters} />
        </Layout.Vertical>
      ) : (
        <Layout.Vertical spacing="small" flex={{ justifyContent: 'center', alignItems: 'center' }} width={720}>
          <img src={isCIModule ? buildIllustrations : deploymentIllustrations} className={css.image} />
 
          <Text className={css.noDeploymentText} margin={{ top: 'medium', bottom: 'small' }}>
            {getString(isCIModule ? 'pipeline.noBuildsText' : 'pipeline.noDeploymentText')}
          </Text>
          <Text className={css.aboutDeployment} margin={{ top: 'xsmall', bottom: 'xlarge' }}>
            {getString(runPipeline ? (isCIModule ? 'noBuildsText' : 'noDeploymentText') : 'pipeline.noPipelineText')}
          </Text>
          <RbacButton
            intent="primary"
            text={runPipeline ? getString('pipeline.runAPipeline') : getString('common.createPipeline')}
            disabled={isPipelineInvalid}
            tooltip={isPipelineInvalid ? getString('pipeline.cannotRunInvalidPipeline') : ''}
            onClick={createPipeline ? () => goToPipeline() : onRunPipeline}
            permission={{
              permission: runPipeline ? PermissionIdentifier.EXECUTE_PIPELINE : PermissionIdentifier.EDIT_PIPELINE,
              resource: {
                resourceType: ResourceType.PIPELINE,
                resourceIdentifier: pipelineIdentifier || queryParams.pipelineIdentifier
              },
              options: {
                skipCondition: ({ resourceIdentifier }) => !resourceIdentifier
              }
            }}
          />
        </Layout.Vertical>
      )}
    </div>
  )
}
export default function PipelineDeploymentList(props: PipelineDeploymentListProps): React.ReactElement {
  const { orgIdentifier, projectIdentifier, pipelineIdentifier, accountId, module } =
    useParams<PipelineType<PipelinePathProps>>()
  const [pollingRequest, setPollingRequest] = React.useState(false)
  const [pipelineDataElements, setData] = React.useState<number | undefined>()
  const history = useHistory()
  const queryParams = useQueryParams<QueryParams>({
    processQueryParams(params: StringQueryParams) {
      let filters = {}
 
      try {
        filters = params.filters ? JSON.parse(params.filters) : undefined
      } catch (_e) {
        // do nothing
      }
 
      return {
        ...params,
        page: parseInt(params.page || '1', 10),
        size: parseInt(params.size || '20', 10),
        sort: [],
        status: ((Array.isArray(params.status) ? params.status : [params.status]) as QuickStatusParam)?.filter(p => p),
        myDeployments: !!params.myDeployments,
        searchTerm: params.searchTerm,
        filters,
        repoIdentifier: params.repoIdentifier,
        branch: params.branch
      }
    }
  })
  const { replaceQueryParams } = useUpdateQueryParams<Partial<GetListOfExecutionsQueryParams>>()
 
  const { page, filterIdentifier, myDeployments, status, repoIdentifier, branch, searchTerm } = queryParams
 
  const hasFilters = getHasFilters({
    queryParams,
    filterIdentifier,
    searchTerm,
    myDeployments,
    status
  })
 
  const isCIModule = module === 'ci'
  const { getString } = useStrings()
  const hasFilterIdentifier = getHasFilterIdentifier(filterIdentifier)
 
  const { mutate: reloadPipelines, cancel } = useGetPipelineList({
    queryParams: {
      accountIdentifier: accountId,
      projectIdentifier,
      module,
      orgIdentifier,
      searchTerm,
      page,
      size: 1
    }
  })
 
  const fetchPipelines = React.useCallback(async () => {
    cancel()
    setData(await (await reloadPipelines({ filterType: 'PipelineSetup' }))?.data?.totalElements)
  }, [cancel])
 
  const { licenseInformation } = useLicenseStore()
  const isCommunityAndCDModule = module === 'cd' && isCDCommunity(licenseInformation)
 
  const {
    data,
    loading,
    refetch: fetchExecutions,
    error
  } = useMutateAsGet(useGetListOfExecutions, {
    queryParams: {
      accountIdentifier: accountId,
      projectIdentifier,
      orgIdentifier,
      module,
      size: 20,
      pipelineIdentifier: pipelineIdentifier || queryParams.pipelineIdentifier,
      page: page ? page - 1 : 0,
      filterIdentifier: hasFilterIdentifier ? filterIdentifier : undefined,
      myDeployments,
      status,
      repoIdentifier,
      branch,
      searchTerm
    },
    queryParamStringifyOptions: {
      arrayFormat: 'repeat'
    },
    body: hasFilterIdentifier
      ? // eslint-disable-next-line @typescript-eslint/no-explicit-any
        (null as any)
      : {
          ...queryParams.filters,
          filterType: 'PipelineExecution'
        }
  })
 
  const {
    data: filterData,
    loading: isFetchingFilters,
    refetch: refetchFilters
  } = useGetFilterList({
    queryParams: {
      accountIdentifier: accountId,
      projectIdentifier,
      orgIdentifier,
      type: 'PipelineExecution'
    }
  })
  const pipelineExecutionSummary = data?.data || {}
  const filters = filterData?.data?.content || []
  const visible = useTabVisible()
  /* #region Polling logic */
  //  - At any moment of time, only one polling is done
  //  - Only do polling on first page
  //  - When component is loading, wait until loading is done
  //  - When polling call (API) is being processed, wait until it's done then re-schedule
  React.useEffect(() => {
    const timeoutId = window.setTimeout(() => {
      Eif (page === 1 && !loading && visible) {
        setPollingRequest(true)
        fetchExecutions()?.then(
          () => setPollingRequest(false),
          () => setPollingRequest(false)
        )
      }
    }, pollingIntervalInMilliseconds)
 
    return () => {
      window.clearTimeout(timeoutId)
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [page, loading, visible])
 
  React.useEffect(() => {
    fetchPipelines()
  }, [projectIdentifier])
 
  const clearFilters = (): void => {
    replaceQueryParams({})
  }
 
  // for handling the description when we have no pipelines or we have pipelines but no executions
 
  const { createPipeline, runPipeline } = getCreateRunPipeline({ pipelineExecutionSummary, pipelineDataElements })
 
  const goToPipeline = useCallback(
    (pipeline?: PMSPipelineSummaryResponse) => {
      history.push(
        routes.toPipelineStudio({
          projectIdentifier,
          orgIdentifier,
          pipelineIdentifier: pipeline?.identifier || '-1',
          accountId,
          module,
          branch: pipeline?.gitDetails?.branch,
          repoIdentifier: pipeline?.gitDetails?.repoIdentifier
        })
      )
    },
    [projectIdentifier, orgIdentifier, history, accountId]
  )
 
  const spinner = renderSpinner({ loading, pollingRequest })
 
  return (
    <GitSyncStoreProvider>
      <FilterContextProvider
        savedFilters={filters}
        isFetchingFilters={isFetchingFilters}
        refetchFilters={refetchFilters}
        queryParams={queryParams}
      >
        {renderDeploymentListHeader({
          pipelineExecutionSummary,
          hasFilters,
          onRunPipeline: props.onRunPipeline,
          isPipelineInvalid: props.isPipelineInvalid
        })}
        <Page.Body
          className={css.main}
          key={pipelineIdentifier}
          error={(error?.data as Error)?.message || error?.message}
          retryOnError={() => fetchExecutions()}
        >
          {props.showHealthAndExecution && !isCommunityAndCDModule && (
            <Container className={css.healthAndExecutions}>
              <PipelineSummaryCards />
              <PipelineBuildExecutionsChart />
            </Container>
          )}
 
          {spinner ? (
            spinner
          ) : !pipelineExecutionSummary?.content?.length ? (
            <NoDeployments
              onRunPipeline={props.onRunPipeline}
              hasFilters={hasFilters}
              isCIModule={isCIModule}
              getString={getString}
              clearFilters={clearFilters}
              runPipeline={runPipeline}
              createPipeline={createPipeline}
              goToPipeline={goToPipeline}
              pipelineIdentifier={pipelineIdentifier}
              queryParams={queryParams}
              isPipelineInvalid={props.isPipelineInvalid}
            />
          ) : (
            <React.Fragment>
              <ExecutionsList
                pipelineExecutionSummary={pipelineExecutionSummary?.content}
                isPipelineInvalid={props.isPipelineInvalid}
              />
              <ExecutionsPagination pipelineExecutionSummary={pipelineExecutionSummary} />
            </React.Fragment>
          )}
        </Page.Body>
      </FilterContextProvider>
    </GitSyncStoreProvider>
  )
}