All files / modules/75-cd/components/Services/ServicesList ServicesList.tsx

78.57% Statements 99/126
47.46% Branches 56/118
62.96% Functions 17/27
78.23% Lines 97/124

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 560              3x 3x 3x   3x 3x                   3x 3x 3x 3x   3x   3x 3x     3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x   3x 3x 3x                                                                 3x 3x                                                               3x 2x 2x 2x 2x                               3x 2x 2x     3x 6x 6x 6x 6x 6x 4x   2x     6x                                                 3x 9x 6x 6x     3x 2x 2x 2x                                               2x                               3x     2x 2x 2x 1x   1x                                                                           3x     2x 2x 2x 1x     1x         1x                             3x 2x 2x 2x 2x 2x 2x 2x 2x   2x               2x                                                     2x                                             2x                                                         2x           2x           2x                                                                                                 3x 3x 3x 3x 3x   3x 3x   6x                 3x   3x                                                                                                                             3x               3x                 3x    
/*
 * 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, useMemo, useState } from 'react'
import cx from 'classnames'
import { useHistory, useParams } from 'react-router-dom'
import type { CellProps, Renderer } from 'react-table'
import ReactTimeago from 'react-timeago'
import {
  Button,
  Dialog,
  Layout,
  Popover,
  TagsPopover,
  Text,
  useConfirmationDialog,
  useToaster
} from '@wings-software/uicore'
import { useModalHook } from '@harness/use-modal'
import { Color, Intent } from '@harness/design-system'
import { Classes, Menu, Position } from '@blueprintjs/core'
import { defaultTo, pick } from 'lodash-es'
import type { TableProps } from '@harness/uicore'
import routes from '@common/RouteDefinitions'
import type { ModulePathParams, ProjectPathProps } from '@common/interfaces/RouteInterfaces'
import useRBACError, { RBACError } from '@rbac/utils/useRBACError/useRBACError'
import { DashboardList } from '@cd/components/DashboardList/DashboardList'
import type { DashboardListProps } from '@cd/components/DashboardList/DashboardList'
import type { ChangeValue } from '@cd/components/Services/DeploymentsWidget/DeploymentsWidget'
import { useStrings } from 'framework/strings'
import { Ticker } from '@common/components/Ticker/Ticker'
import { PieChart, PieChartProps } from '@cd/components/PieChart/PieChart'
import { getFixed, INVALID_CHANGE_RATE, numberFormatter } from '@cd/components/Services/common'
import { ServiceDetailsDTO, useDeleteServiceV2 } from 'services/cd-ng'
import { DeploymentTypeIcons } from '@cd/components/DeploymentTypeIcons/DeploymentTypeIcons'
import { ResourceType } from '@rbac/interfaces/ResourceType'
import { PermissionIdentifier } from '@rbac/interfaces/PermissionIdentifier'
import { NewEditServiceModal } from '@cd/components/PipelineSteps/DeployServiceStep/DeployServiceStep'
import RbacMenuItem from '@rbac/components/MenuItem/MenuItem'
import { ServiceTabs } from '@cd/components/ServiceDetails/ServiceDetailsContent/ServiceDetailsContent'
import css from '@cd/components/Services/ServicesList/ServiceList.module.scss'
 
export enum DeploymentStatus {
  SUCCESS = 'success',
  FAILED = 'failed'
}
 
export interface ServiceListItem {
  name: string
  identifier: string
  tags?: {
    [key: string]: string
  }
  deploymentTypeList: string[]
  serviceInstances: {
    count: number
    prodCount: number
    nonProdCount: number
  }
  deployments: ChangeValue
  failureRate: ChangeValue
  frequency: ChangeValue
  lastDeployment: {
    name: string
    id: string
    timestamp: number
    status: string
  }
}
 
export interface ServicesListProps {
  loading: boolean
  error: boolean
  data: ServiceDetailsDTO[]
  refetch: () => void
}
 
const transformServiceDetailsData = (data: ServiceDetailsDTO[]): ServiceListItem[] => {
  return data.map(item => ({
    name: defaultTo(item.serviceName, ''),
    identifier: defaultTo(item.serviceIdentifier, ''),
    description: defaultTo(item.description, ''),
    tags: defaultTo(item.tags, {}),
    deploymentTypeList: defaultTo(item.deploymentTypeList, []),
    serviceInstances: {
      count: defaultTo(item.instanceCountDetails?.totalInstances, 0),
      prodCount: defaultTo(item.instanceCountDetails?.prodInstances, 0),
      nonProdCount: defaultTo(item.instanceCountDetails?.nonProdInstances, 0)
    },
    deployments: {
      value: numberFormatter(item.totalDeployments),
      change: defaultTo(item.totalDeploymentChangeRate, 0)
    },
    failureRate: {
      value: numberFormatter(item.failureRate),
      change: defaultTo(item.failureRateChangeRate, 0)
    },
    frequency: {
      value: numberFormatter(item.frequency),
      change: defaultTo(item.frequencyChangeRate, 0)
    },
    lastDeployment: {
      name: defaultTo(item.lastPipelineExecuted?.name, ''),
      id: defaultTo(item.lastPipelineExecuted?.pipelineExecutionId, ''),
      timestamp: defaultTo(item.lastPipelineExecuted?.lastExecutedAt, 0),
      status: defaultTo(item.lastPipelineExecuted?.status, '')
    }
  }))
}
 
const RenderServiceName: Renderer<CellProps<ServiceListItem>> = ({ row }) => {
  const { name, identifier, tags } = row.original
  const { getString } = useStrings()
  const idLabel = getString('idLabel', { id: identifier })
  return (
    <Layout.Vertical>
      <Layout.Horizontal spacing="small">
        <Text font={{ weight: 'semi-bold' }} color={Color.GREY_700} margin={{ bottom: 'xsmall' }} lineClamp={1}>
          {name}
        </Text>
        {tags && Object.keys(tags).length ? <TagsPopover tags={tags} /> : null}
      </Layout.Horizontal>
 
      <Text font={{ size: 'small' }} color={Color.GREY_500} lineClamp={1}>
        {idLabel}
      </Text>
    </Layout.Vertical>
  )
}
 
const RenderType: Renderer<CellProps<ServiceListItem>> = ({ row }) => {
  const { deploymentTypeList } = row.original
  return <DeploymentTypeIcons deploymentTypes={deploymentTypeList} />
}
 
const TickerCard: React.FC<{ item: ChangeValue & { name: string } }> = props => {
  const { item } = props
  const value = Number(item.value)
  const isBoostMode = item.change === INVALID_CHANGE_RATE
  const color = (() => {
    if (item.name !== 'failureRate') {
      return !isBoostMode && item.change < 0 ? Color.RED_500 : Color.GREEN_500
    } else {
      return isBoostMode || item.change < 0 ? Color.GREEN_500 : Color.RED_500
    }
  })()
  return (
    <Layout.Vertical padding={'small'} key={item.name} width={'fit-content'} className={css.tickerContainer}>
      <Ticker
        value={
          isBoostMode ? (
            <></>
          ) : (
            <Text color={color} font={{ size: 'small' }}>{`${Math.abs(getFixed(item.change))}%`}</Text>
          )
        }
        decreaseMode={!isBoostMode && item.change < 0}
        boost={isBoostMode}
        color={color}
        tickerContainerStyles={css.tickerContainerStyles}
        size={isBoostMode ? 10 : 6}
      >
        <Text color={Color.BLACK} font={{ weight: 'semi-bold', size: 'medium' }} margin={{ right: 'xsmall' }}>
          {isNaN(value) ? item.value : numberFormatter(value)}
        </Text>
      </Ticker>
    </Layout.Vertical>
  )
}
 
const getRenderTickerCard: (tickerCardKey: keyof ServiceListItem) => Renderer<CellProps<ServiceListItem>> =
  tickerCardKey =>
  ({ row }) => {
    const value = row.original[tickerCardKey] as ChangeValue
    return <TickerCard item={{ ...value, name: tickerCardKey }} />
  }
 
const RenderServiceInstances: Renderer<CellProps<ServiceListItem>> = ({ row }) => {
  const { serviceInstances } = row.original
  const { getString } = useStrings()
  const pieChartProps: PieChartProps = {
    items: [
      {
        label: getString('cd.serviceDashboard.nonProd'),
        value: serviceInstances.nonProdCount,
        formattedValue: numberFormatter(serviceInstances.nonProdCount),
        color: 'var(--primary-2)'
      },
      {
        label: getString('cd.serviceDashboard.prod'),
        value: serviceInstances.prodCount,
        formattedValue: numberFormatter(serviceInstances.prodCount),
        color: 'var(--primary-7)'
      }
    ],
    size: 24,
    labelContainerStyles: css.pieChartLabelContainerStyles,
    labelStyles: css.pieChartLabelStyles,
    options: {
      tooltip: {
        enabled: false
      }
    }
  }
  return (
    <Layout.Horizontal flex={{ align: 'center-center', justifyContent: 'flex-start' }}>
      <Text
        color={Color.BLACK}
        font={{ weight: 'semi-bold', size: 'medium' }}
        margin={{ right: 'xsmall' }}
        padding={{ left: 'medium', top: 'medium', right: 'medium', bottom: 'medium' }}
        className={css.tickerContainer}
      >
        {serviceInstances.count}
      </Text>
      {serviceInstances.count ? <PieChart {...pieChartProps} /> : <></>}
    </Layout.Horizontal>
  )
}
 
const RenderLastDeployment: Renderer<CellProps<ServiceListItem>> = ({ row }) => {
  const {
    lastDeployment: { id, name, timestamp }
  } = row.original
  const { getString } = useStrings()
  if (!id) {
    return <></>
  }
  return (
    <Layout.Vertical margin={{ right: 'large' }} flex={{ alignItems: 'flex-start' }}>
      <Layout.Horizontal
        margin={{ bottom: 'xsmall' }}
        flex={{ alignItems: 'center', justifyContent: 'flex-start' }}
        width="100%"
      >
        <Text
          font={{ weight: 'semi-bold' }}
          color={Color.GREY_700}
          margin={{ right: 'xsmall' }}
          className={css.lastDeploymentText}
        >
          {name}
        </Text>
        <Text font={{ size: 'small' }} color={Color.GREY_500} className={css.lastDeploymentText}>{`(${getString(
          'cd.serviceDashboard.executionId',
          {
            id
          }
        )})`}</Text>
      </Layout.Horizontal>
      {timestamp ? (
        <ReactTimeago
          date={timestamp}
          component={val => (
            <Text font={{ size: 'small' }} color={Color.GREY_500}>
              {val.children}
            </Text>
          )}
        />
      ) : (
        <></>
      )}
    </Layout.Vertical>
  )
}
 
const RenderLastDeploymentStatus: Renderer<CellProps<ServiceListItem>> = ({ row }) => {
  const {
    lastDeployment: { id, status }
  } = row.original
  const { getString } = useStrings()
  if (!id) {
    return <></>
  }
  const [statusBackgroundColor, statusText] =
    status?.toLocaleLowerCase() === DeploymentStatus.SUCCESS
      ? [Color.GREEN_600, getString('success')]
      : status?.toLocaleLowerCase() === DeploymentStatus.FAILED
      ? [Color.RED_600, getString('failed')]
      : [Color.YELLOW_600, status]
  return (
    <Layout.Horizontal flex={{ justifyContent: 'flex-end' }}>
      <Text
        background={statusBackgroundColor}
        color={Color.WHITE}
        font={{ weight: 'semi-bold', size: 'xsmall' }}
        className={css.statusText}
        lineClamp={1}
      >
        {statusText?.toLocaleUpperCase()}
      </Text>
    </Layout.Horizontal>
  )
}
 
const RenderColumnMenu: Renderer<CellProps<any>> = ({ row, column }) => {
  const data = row.original
  const [menuOpen, setMenuOpen] = useState(false)
  const [deleteError, setDeleteError] = useState('')
  const { accountId, orgIdentifier, projectIdentifier, module } = useParams<ProjectPathProps & ModulePathParams>()
  const { showSuccess, showError } = useToaster()
  const { getRBACErrorMessage } = useRBACError()
  const { getString } = useStrings()
  const history = useHistory()
 
  const { mutate: deleteService } = useDeleteServiceV2({
    queryParams: {
      accountIdentifier: accountId,
      orgIdentifier: orgIdentifier,
      projectIdentifier: projectIdentifier
    }
  })
 
  const [showModal, hideModal] = useModalHook(
    () => (
      <Dialog
        isOpen={true}
        enforceFocus={false}
        canEscapeKeyClose
        canOutsideClickClose
        onClose={hideModal}
        title={getString('editService')}
        isCloseButtonShown
        className={cx('padded-dialog')}
      >
        <NewEditServiceModal
          data={{ ...pick(data, ['name', 'identifier', 'description', 'tags']) } || { name: '', identifier: '' }}
          isEdit={true}
          isService={false}
          onCreateOrUpdate={() => {
            ;(column as any).reload?.()
            hideModal()
          }}
          closeModal={hideModal}
        />
      </Dialog>
    ),
    [data, orgIdentifier, projectIdentifier]
  )
 
  const { openDialog: openDeleteErrorDialog } = useConfirmationDialog({
    titleText: getString('common.deleteServiceFailure'),
    contentText: deleteError,
    cancelButtonText: getString('close'),
    confirmButtonText: getString('common.viewReferences'),
    intent: Intent.DANGER,
    onCloseDialog: async isConfirmed => {
      setDeleteError('')
      if (isConfirmed) {
        history.push({
          pathname: routes.toServiceDetails({
            accountId,
            orgIdentifier,
            projectIdentifier,
            serviceId: data.identifier,
            module
          }),
          search: `tab=${ServiceTabs.REFERENCED_BY}`
        })
      }
    }
  })
 
  const { openDialog } = useConfirmationDialog({
    titleText: getString('common.deleteService'),
    contentText: getString('common.deleteServiceConfirmation', { name: data.name }),
    cancelButtonText: getString('cancel'),
    confirmButtonText: getString('confirm'),
    intent: Intent.DANGER,
    onCloseDialog: async isConfirmed => {
      if (isConfirmed) {
        try {
          const response = await deleteService(data.identifier, {
            headers: { 'content-type': 'application/json' }
          })
          if (response.status === 'SUCCESS') {
            showSuccess(getString('common.deleteServiceMessage'))
            ;(column as any).reload?.()
          }
        } catch (err) {
          if (err?.data?.code === 'ENTITY_REFERENCE_EXCEPTION') {
            // showing reference by error in modal
            setDeleteError(err?.data?.message || err?.message)
            openDeleteErrorDialog()
          } else {
            showError(getRBACErrorMessage(err as RBACError))
          }
        }
      }
    }
  })
 
  const handleEdit = (e: React.MouseEvent<HTMLElement, MouseEvent>): void => {
    e.stopPropagation()
    setMenuOpen(false)
    showModal()
  }
 
  const handleDelete = (e: React.MouseEvent<HTMLElement, MouseEvent>): void => {
    e.stopPropagation()
    setMenuOpen(false)
    openDialog()
  }
 
  return (
    <Layout.Horizontal>
      <Popover
        isOpen={menuOpen}
        onInteraction={nextOpenState => {
          setMenuOpen(nextOpenState)
        }}
        className={Classes.DARK}
        position={Position.RIGHT_TOP}
      >
        <Button
          minimal
          icon="Options"
          onClick={e => {
            e.stopPropagation()
            setMenuOpen(true)
          }}
        />
        <Menu style={{ minWidth: 'unset' }}>
          <RbacMenuItem
            icon="edit"
            text={getString('edit')}
            onClick={handleEdit}
            permission={{
              resource: {
                resourceType: ResourceType.SERVICE,
                resourceIdentifier: defaultTo(data.identifier, '')
              },
              permission: PermissionIdentifier.EDIT_SERVICE
            }}
          />
          <RbacMenuItem
            icon="trash"
            text={getString('delete')}
            onClick={handleDelete}
            permission={{
              resource: {
                resourceType: ResourceType.SERVICE,
                resourceIdentifier: defaultTo(data.identifier, '')
              },
              permission: PermissionIdentifier.DELETE_SERVICE
            }}
          />
        </Menu>
      </Popover>
    </Layout.Horizontal>
  )
}
 
export const ServicesList: React.FC<ServicesListProps> = props => {
  const { loading, data, error, refetch } = props
  const { getString } = useStrings()
  const { accountId, orgIdentifier, projectIdentifier, module } = useParams<ProjectPathProps & ModulePathParams>()
  const history = useHistory()
 
  const ServiceListHeaderCustomPrimary = useMemo(
    () => (headerProps: { total?: number }) =>
      (
        <Text font={{ size: 'medium', weight: 'semi-bold' }} color={Color.GREY_700}>
          {getString('cd.serviceDashboard.totalServices', {
            total: headerProps.total || 0
          })}
        </Text>
      ),
    // eslint-disable-next-line react-hooks/exhaustive-deps
    [data]
  )
  const columns: TableProps<ServiceListItem>['columns'] = useMemo(
    () => {
      return [
        {
          Header: getString('service').toLocaleUpperCase(),
          id: 'service',
          width: '15%',
          Cell: RenderServiceName
        },
        {
          Header: getString('typeLabel').toLocaleUpperCase(),
          id: 'type',
          width: '10%',
          Cell: RenderType
        },
        {
          Header: getString('cd.serviceDashboard.serviceInstances').toLocaleUpperCase(),
          id: 'serviceInstances',
          width: '15%',
          Cell: RenderServiceInstances
        },
        {
          Header: getString('deploymentsText').toLocaleUpperCase(),
          id: 'deployments',
          width: '10%',
          Cell: getRenderTickerCard('deployments')
        },
        {
          Header: getString('common.failureRate').toLocaleUpperCase(),
          id: 'failureRate',
          width: '10%',
          Cell: getRenderTickerCard('failureRate')
        },
        {
          Header: getString('cd.serviceDashboard.frequency').toLocaleUpperCase(),
          id: 'frequency',
          width: '10%',
          Cell: getRenderTickerCard('frequency')
        },
        {
          Header: getString('cd.serviceDashboard.lastDeployment').toLocaleUpperCase(),
          id: 'lastDeployment',
          width: '22%',
          Cell: RenderLastDeployment
        },
        {
          Header: '',
          id: 'status',
          width: '5%',
          Cell: RenderLastDeploymentStatus
        },
        {
          Header: '',
          width: '3%',
          id: 'action',
          Cell: RenderColumnMenu,
          reload: refetch,
          disableSortBy: true
        }
      ]
    },
    // eslint-disable-next-line react-hooks/exhaustive-deps
    []
  )
 
  const goToServiceDetails = useCallback(
    ({ identifier: serviceId }: ServiceListItem): void => {
      history.push(routes.toServiceDetails({ accountId, orgIdentifier, projectIdentifier, serviceId, module }))
    },
    // eslint-disable-next-line react-hooks/exhaustive-deps
    [accountId, orgIdentifier, projectIdentifier, module]
  )
 
  const dashboardListProps: DashboardListProps<ServiceListItem> = {
    columns,
    loading,
    error,
    data: transformServiceDetailsData(data),
    refetch,
    HeaderCustomPrimary: ServiceListHeaderCustomPrimary,
    onRowClick: goToServiceDetails
  }
  return <DashboardList<ServiceListItem> {...dashboardListProps} />
}