All files / modules/70-pipeline/pages/pipelines/views/PipelineCard PipelineCard.tsx

82.28% Statements 65/79
53.76% Branches 143/266
65% Functions 13/20
82.05% Lines 64/78

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 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559              2x 2x                         2x 2x 2x 2x 2x 2x 2x     2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x   2x                                                                         10x 10x   10x                               10x 1x     10x           10x   10x 1x           1x 1x               1x                                                   1x 1x 1x             2x                                   2x 78x     78x   78x                                                                           2x               117x             117x 117x 117x 117x                             117x 819x   117x 1x     117x           117x 117x 117x   117x 2x                                                 156x                                                                                                                                                                                                                                                                                                                                                                                                                                                                             1x 1x                                              
/*
 * 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 from 'react'
import {
  Card,
  Text,
  Container,
  Layout,
  SparkChart,
  CardBody,
  Icon,
  Button,
  ButtonVariation,
  ButtonSize,
  IconName
} from '@wings-software/uicore'
import { Color } from '@harness/design-system'
import { Classes, Intent, Menu, Popover, PopoverInteractionKind, Position } from '@blueprintjs/core'
import { useParams, useHistory } from 'react-router-dom'
import { isEmpty } from 'lodash-es'
import cx from 'classnames'
import { isExecutionComplete } from '@pipeline/utils/statusHelpers'
import { TimeAgoPopover } from '@common/exports'
import type { PipelineType } from '@common/interfaces/RouteInterfaces'
import type { PMSPipelineSummaryResponse } from 'services/pipeline-ng'
import { useStrings } from 'framework/strings'
import { useGitSyncStore } from 'framework/GitRepoStore/GitSyncStoreContext'
import { TagsPopover } from '@common/components'
import routes from '@common/RouteDefinitions'
import { getRepoDetailsByIndentifier } from '@common/utils/gitSyncUtils'
import { PermissionIdentifier } from '@rbac/interfaces/PermissionIdentifier'
import { usePermission } from '@rbac/hooks/usePermission'
import { ResourceType } from '@rbac/interfaces/ResourceType'
import RbacButton from '@rbac/components/Button/Button'
import useDeleteConfirmationDialog from '@pipeline/pages/utils/DeleteConfirmDialog'
import { Badge } from '@pipeline/pages/utils/Badge/Badge'
import { formatCount } from '@common/utils/utils'
import { useRunPipelineModal } from '@pipeline/components/RunPipelineModal/useRunPipelineModal'
import { getFeaturePropsForRunPipelineButton } from '@pipeline/utils/runPipelineUtils'
import { getIconsForPipeline } from '../../PipelineListUtils'
 
import css from './PipelineCard.module.scss'
 
interface PipelineDTO extends PMSPipelineSummaryResponse {
  status?: string
}
export interface PipelineCardProps {
  pipeline: PipelineDTO
  goToPipelineDetail: (pipeline?: PMSPipelineSummaryResponse) => void
  goToPipelineStudio: (pipeline?: PMSPipelineSummaryResponse) => void
  refetchPipeline: () => void
  onDeletePipeline: (commitMsg: string) => Promise<void>
  onDelete: (pipeline: PMSPipelineSummaryResponse) => void
}
 
interface ContextMenuProps {
  pipeline: PMSPipelineSummaryResponse
  goToPipelineStudio: (pipeline?: PMSPipelineSummaryResponse) => void
  goToPipelineDetail: (pipeline?: PMSPipelineSummaryResponse) => void
  refetchPipeline: () => void
  projectIdentifier: string
  orgIdentifier: string
  accountIdentifier: string
  isGitSyncEnabled: boolean
  onDeletePipeline: (commitMsg: string) => Promise<void>
  onDelete: (pipeline: PMSPipelineSummaryResponse) => void
}
 
function ContextMenu({
  pipeline,
  goToPipelineStudio,
  goToPipelineDetail,
  projectIdentifier,
  orgIdentifier,
  accountIdentifier,
  onDeletePipeline,
  onDelete
}: ContextMenuProps): React.ReactElement {
  const { getString } = useStrings()
  const { confirmDelete } = useDeleteConfirmationDialog(pipeline, 'pipeline', onDeletePipeline)
 
  const [canDelete, canRun] = usePermission(
    {
      resourceScope: {
        accountIdentifier,
        orgIdentifier,
        projectIdentifier
      },
      resource: {
        resourceType: ResourceType.PIPELINE,
        resourceIdentifier: pipeline.identifier as string
      },
      permissions: [PermissionIdentifier.DELETE_PIPELINE, PermissionIdentifier.EXECUTE_PIPELINE]
    },
    [orgIdentifier, projectIdentifier, accountIdentifier, pipeline.identifier]
  )
 
  const runPipeline = (): void => {
    openRunPipelineModal()
  }
 
  const { openRunPipelineModal } = useRunPipelineModal({
    pipelineIdentifier: (pipeline.identifier || '') as string,
    repoIdentifier: pipeline?.gitDetails?.repoIdentifier,
    branch: pipeline?.gitDetails?.branch
  })
 
  const isPipelineInvalid = pipeline?.entityValidityDetails?.valid === false
 
  return (
    <Menu style={{ minWidth: 'unset' }} onClick={e => e.stopPropagation()}>
      <Menu.Item
        icon="play"
        text={getString('runPipelineText')}
        disabled={!canRun || isPipelineInvalid}
        onClick={(e: React.MouseEvent) => {
          e.stopPropagation()
          runPipeline()
        }}
      />
      {/* </RunPipelineModal> */}
      <Menu.Item
        icon="cog"
        text={getString('launchStudio')}
        onClick={() => {
          goToPipelineStudio(pipeline)
        }}
      />
      <Menu.Item
        icon="list-detail-view"
        text={getString('viewExecutions')}
        onClick={(e: React.MouseEvent) => {
          e.stopPropagation()
          goToPipelineDetail(pipeline)
        }}
      />
      <Menu.Divider />
      {/* <Menu.Item
        icon="duplicate"
        text={getString('projectCard.clone')}
        disabled
        onClick={(e: React.MouseEvent) => {
          e.stopPropagation()
          return false
        }}
      /> */}
      <Menu.Item
        icon="trash"
        text={getString('delete')}
        disabled={!canDelete}
        onClick={(e: React.MouseEvent) => {
          e.stopPropagation()
          onDelete(pipeline)
          confirmDelete()
        }}
      />
    </Menu>
  )
}
 
const LEFT_COLUMN_WIDTH = 80
 
function AdditionalEntitiesCountPopUp(props: { entityList: string[]; iconName?: IconName }) {
  const { entityList, iconName } = props
  return (
    <Layout.Vertical style={{ padding: 'var(--spacing-4)' }}>
      {entityList.map(entity => (
        <Container key={entity} flex={{ justifyContent: 'flex-start' }}>
          {iconName && <Icon name={iconName} style={{ height: 'var(--spacing-5)', marginRight: 'var(--spacing-3)' }} />}
          <Text font="small" color={Color.WHITE} style={{ lineHeight: '22px' }}>
            {entity}
          </Text>
        </Container>
      ))}
    </Layout.Vertical>
  )
}
 
const renderEntityWithAdditionalCountInfo = (entityList: string[], iconName?: IconName) => {
  Iif (!entityList?.length) {
    return null
  }
  const [firstElement, ...otherElements] = entityList
 
  return (
    <Layout.Horizontal>
      {firstElement && (
        <Text
          font="small"
          className={css.firstEntity}
          lineClamp={1}
          tooltip={
            <Container style={{ padding: 'var(--spacing-4)' }}>
              <Text font="small" color={Color.WHITE} style={{ lineHeight: '22px' }}>
                {firstElement}
              </Text>
            </Container>
          }
          tooltipProps={{ isDark: true }}
        >
          {firstElement}
        </Text>
      )}
      {otherElements && otherElements.length > 0 && (
        <Popover
          interactionKind={PopoverInteractionKind.HOVER}
          position={Position.RIGHT}
          usePortal={true}
          className={Classes.DARK}
          content={<AdditionalEntitiesCountPopUp entityList={otherElements} iconName={iconName} />}
        >
          <Text
            font="small"
            color={Color.GREY_600}
            style={{ marginLeft: 'var(--spacing-4)' }}
          >{`+${otherElements.length}`}</Text>
        </Popover>
      )}
    </Layout.Horizontal>
  )
}
 
export function PipelineCard({
  pipeline,
  goToPipelineDetail,
  goToPipelineStudio,
  refetchPipeline,
  onDeletePipeline,
  onDelete
}: PipelineCardProps): React.ReactElement {
  const { accountId, projectIdentifier, orgIdentifier, module } = useParams<
    PipelineType<{
      orgIdentifier: string
      projectIdentifier: string
      accountId: string
    }>
  >()
  const { isGitSyncEnabled } = { isGitSyncEnabled: true }
  const { gitSyncRepos, loadingRepos } = useGitSyncStore()
  const history = useHistory()
  const goToExecutionPipelineView = (executionId: string | undefined): void => {
    if (executionId && pipeline.identifier) {
      history.push(
        routes.toExecutionPipelineView({
          orgIdentifier,
          pipelineIdentifier: pipeline.identifier,
          projectIdentifier,
          executionIdentifier: executionId,
          accountId,
          module
        })
      )
    }
  }
 
  const { getString } = useStrings()
  const deployments = pipeline.executionSummaryInfo?.deployments?.reduce((acc, val) => acc + val, 0) || 0
 
  const runPipeline = (): void => {
    openRunPipelineModal()
  }
 
  const { openRunPipelineModal } = useRunPipelineModal({
    pipelineIdentifier: (pipeline.identifier || '') as string,
    repoIdentifier: pipeline?.gitDetails?.repoIdentifier,
    branch: pipeline?.gitDetails?.branch
  })
 
  const pipelineIcons = getIconsForPipeline(pipeline)
  const status = pipeline.executionSummaryInfo?.lastExecutionStatus
  const isPipelineInvalid = pipeline?.entityValidityDetails?.valid === false
 
  return (
    <Card className={css.pipelineCard} interactive onClick={() => goToPipelineStudio(pipeline)}>
      <Container padding={'xlarge'} border={{ bottom: true }}>
        <CardBody.Menu
          menuContent={
            <ContextMenu
              pipeline={pipeline}
              goToPipelineStudio={goToPipelineStudio}
              goToPipelineDetail={goToPipelineDetail}
              refetchPipeline={refetchPipeline}
              projectIdentifier={projectIdentifier}
              accountIdentifier={accountId}
              orgIdentifier={orgIdentifier}
              isGitSyncEnabled
              onDeletePipeline={onDeletePipeline}
              onDelete={onDelete}
            />
          }
          menuPopoverProps={{
            className: Classes.DARK
          }}
        />
        <Container>
          <Layout.Horizontal spacing={'small'} margin={{ bottom: 'small' }} flex>
            <Container>
              {!isEmpty(pipelineIcons) &&
                pipelineIcons.map(iconObj => <Icon key={iconObj.icon} name={iconObj.icon} size={16} />)}
            </Container>
            {isPipelineInvalid && (
              <Badge
                text={'common.invalid'}
                iconName="error-outline"
                showTooltip={true}
                entityName={pipeline.name}
                entityType={'Pipeline'}
                showInvalidText={true}
              />
            )}
          </Layout.Horizontal>
          <Layout.Horizontal spacing={'medium'} flex={{ justifyContent: 'flex-start', alignItems: 'flex-start' }}>
            <Container>
              <Text lineClamp={1} font={{ weight: 'bold' }} color={Color.GREY_800} data-testid={pipeline.identifier}>
                {pipeline.name}
              </Text>
              <Text font="small" lineClamp={1} color={Color.GREY_600} margin={{ top: 'xsmall' }}>
                {getString('idLabel', { id: pipeline.identifier })}
              </Text>
            </Container>
            {!isEmpty(pipeline.tags) && pipeline.tags && (
              <TagsPopover
                className={css.tagsPopover}
                iconProps={{ size: 14, color: Color.GREY_600 }}
                tags={pipeline.tags}
              />
            )}
          </Layout.Horizontal>
        </Container>
      </Container>
      <Container padding={{ left: 'xlarge', right: 'xlarge' }}>
        {pipeline.stageNames && !isEmpty(pipeline.stageNames) && (
          <Container border={{ bottom: true }} padding={{ top: 'medium', bottom: 'medium' }}>
            <Layout.Horizontal flex={{ justifyContent: 'flex-start' }} spacing={'small'}>
              <Text className={css.label} font="small" width={LEFT_COLUMN_WIDTH} color={Color.GREY_700}>
                {getString('stages')}
              </Text>
              {renderEntityWithAdditionalCountInfo(pipeline.stageNames)}
            </Layout.Horizontal>
          </Container>
        )}
        <Container
          className={css.infoContainer}
          border={{ bottom: true }}
          padding={{ top: 'medium', bottom: 'medium' }}
        >
          {(module === 'ci' || !!pipeline.filters?.ci?.repoNames?.length) && (
            <Layout.Horizontal flex={{ justifyContent: 'flex-start' }} spacing={'small'}>
              <Text className={css.label} font="small" width={LEFT_COLUMN_WIDTH} color={Color.GREY_700}>
                {getString('pipeline.buildRepo')}
              </Text>
              {pipeline.filters?.ci?.repoNames?.length ? (
                <Text font="small" color={Color.BLACK} lineClamp={1}>
                  {pipeline.filters?.ci?.repoNames.join(', ')}
                </Text>
              ) : (
                <Text font="small" color={Color.GREY_500}>
                  {getString('none')}
                </Text>
              )}
            </Layout.Horizontal>
          )}
          {(module === 'cd' || !!pipeline.filters?.cd?.serviceNames?.length) && (
            <Layout.Horizontal flex={{ justifyContent: 'flex-start' }} spacing={'small'}>
              <Text className={css.label} font="small" width={LEFT_COLUMN_WIDTH} color={Color.GREY_700}>
                {getString('services')}
              </Text>
              {pipeline.filters?.cd?.serviceNames?.length ? (
                renderEntityWithAdditionalCountInfo(pipeline.filters?.cd?.serviceNames as string[], 'infrastructure')
              ) : (
                <Text font="small" color={Color.GREY_500}>
                  {getString('none')}
                </Text>
              )}
            </Layout.Horizontal>
          )}
        </Container>
 
        {isGitSyncEnabled && !!pipeline.gitDetails?.repoIdentifier && !!pipeline.gitDetails.branch && (
          <Container
            className={css.infoContainer}
            border={{ bottom: true }}
            padding={{ top: 'medium', bottom: 'medium' }}
          >
            <Layout.Horizontal flex={{ justifyContent: 'flex-start' }}>
              <Text className={css.label} font="small" width={LEFT_COLUMN_WIDTH} color={Color.GREY_700}>
                {getString('pipeline.gitRepo')}
              </Text>
              <Layout.Horizontal style={{ alignItems: 'center' }} spacing={'small'}>
                <Icon name="repository" size={10} color={Color.GREY_600} />
                <Text
                  font={{ size: 'small' }}
                  color={Color.BLACK}
                  title={pipeline?.gitDetails?.repoIdentifier}
                  lineClamp={1}
                  width={90}
                >
                  {(!loadingRepos &&
                    getRepoDetailsByIndentifier(pipeline.gitDetails.repoIdentifier, gitSyncRepos)?.name) ||
                    ''}
                </Text>
              </Layout.Horizontal>
            </Layout.Horizontal>
 
            <Layout.Horizontal flex={{ justifyContent: 'flex-start' }}>
              <Text className={css.label} font="small" width={LEFT_COLUMN_WIDTH} color={Color.GREY_700}>
                {getString('pipelineSteps.deploy.inputSet.branch')}
              </Text>
              <Layout.Horizontal style={{ alignItems: 'center' }} spacing={'small'}>
                <Icon name="git-new-branch" size={10} color={Color.GREY_500} />
                <Text
                  font={{ size: 'small' }}
                  color={Color.BLACK}
                  title={pipeline?.gitDetails?.branch}
                  lineClamp={1}
                  width={90}
                >
                  {pipeline.gitDetails.branch}
                </Text>
              </Layout.Horizontal>
            </Layout.Horizontal>
          </Container>
        )}
 
        <Container className={css.infoContainer} padding={{ top: 'medium', bottom: 'xlarge' }}>
          {pipeline.executionSummaryInfo?.lastExecutionTs && (
            <>
              <Layout.Horizontal flex={{ justifyContent: 'flex-start' }}>
                <Text className={css.label} font="small" width={LEFT_COLUMN_WIDTH} color={Color.GREY_700}>
                  {getString('lastRunAtDate')}
                </Text>
                <Layout.Horizontal flex spacing={'small'}>
                  <TimeAgoPopover
                    font="small"
                    color={Color.BLACK}
                    onClick={event => {
                      event.stopPropagation()
                      goToExecutionPipelineView(pipeline.executionSummaryInfo?.lastExecutionId)
                    }}
                    time={pipeline.executionSummaryInfo?.lastExecutionTs}
                  />
                  {isExecutionComplete(status) ? (
                    <Icon
                      name={
                        pipeline.executionSummaryInfo?.lastExecutionStatus === 'Success'
                          ? 'deployment-success-legacy'
                          : 'warning-sign'
                      }
                      intent={
                        pipeline.executionSummaryInfo?.lastExecutionStatus !== 'Success' ? Intent.DANGER : Intent.NONE
                      }
                      size={12}
                    />
                  ) : null}
                </Layout.Horizontal>
              </Layout.Horizontal>
              <Layout.Horizontal
                margin={{ top: deployments ? 'xsmall' : 0 }}
                flex={{ justifyContent: 'flex-start', alignItems: deployments ? 'flex-end' : 'center' }}
              >
                <Container className={css.label} width={LEFT_COLUMN_WIDTH}>
                  <Text color={Color.GREY_700} font="small">
                    {getString('executionsText')}
                  </Text>
                  <Text color={Color.GREY_500} font="xsmall">
                    {getString('pipeline.lastSevenDays')}
                  </Text>
                </Container>
                <Layout.Horizontal spacing={'small'} flex={{ alignItems: 'flex-end' }}>
                  {deployments ? (
                    <>
                      <SparkChart
                        data={pipeline.executionSummaryInfo?.deployments || []}
                        data2={pipeline.executionSummaryInfo?.numOfErrors || []}
                        color={Color.PRIMARY_4}
                        color2={Color.RED_600}
                        className={css.sparkChart}
                      />
                      <Text
                        color={Color.PRIMARY_7}
                        font={{ size: 'medium', weight: 'semi-bold' }}
                        iconProps={{ size: 18 }}
                        className={css.deploymentsCount}
                        onClick={event => {
                          event.stopPropagation()
                          goToPipelineDetail(pipeline)
                        }}
                      >
                        {formatCount(deployments)}
                      </Text>
                    </>
                  ) : (
                    <Text color={Color.GREY_500} font={{ size: 'small' }}>
                      {getString('none')}
                    </Text>
                  )}
                </Layout.Horizontal>
              </Layout.Horizontal>
            </>
          )}
          <Layout.Horizontal
            margin={{ top: pipeline.executionSummaryInfo?.lastExecutionTs ? 'small' : 0 }}
            spacing={'small'}
            flex
          >
            {!pipeline.executionSummaryInfo?.lastExecutionTs && (
              <Text font={{ size: 'xsmall', weight: 'semi-bold' }} color={Color.GREY_400}>
                {getString('pipeline.neverRan')}
              </Text>
            )}
            <RbacButton
              withoutCurrentColor
              data-testid="card-run-pipeline"
              icon="command-start"
              variation={ButtonVariation.SECONDARY}
              size={ButtonSize.SMALL}
              intent="success"
              iconProps={{ size: 9, color: Color.SUCCESS }}
              className={cx(css.cardBtns, css.runBtn)}
              text={getString('runPipelineText')}
              permission={{
                resource: {
                  resourceType: ResourceType.PIPELINE,
                  resourceIdentifier: pipeline.identifier as string
                },
                permission: PermissionIdentifier.EXECUTE_PIPELINE
              }}
              featuresProps={getFeaturePropsForRunPipelineButton({ modules: pipeline.modules, getString })}
              onClick={e => {
                e.stopPropagation()
                runPipeline()
              }}
              disabled={isPipelineInvalid}
              tooltip={isPipelineInvalid ? getString('pipeline.cannotRunInvalidPipeline') : ''}
            />
            {pipeline.executionSummaryInfo?.lastExecutionTs && (
              <Button
                variation={ButtonVariation.SECONDARY}
                size={ButtonSize.SMALL}
                className={cx(css.cardBtns, css.viewExecutionsBtn)}
                text={getString('viewExecutions')}
                onClick={(e: React.MouseEvent) => {
                  e.stopPropagation()
                  goToPipelineDetail(pipeline)
                }}
              />
            )}
          </Layout.Horizontal>
        </Container>
      </Container>
    </Card>
  )
}