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

84.51% Statements 60/71
38.75% Branches 31/80
83.33% Functions 10/12
84.06% Lines 58/69

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              6x 6x                   6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x   6x 6x   6x 6x 6x                   6x 6x 6x     6x 37x 35x 35x 35x 35x 35x 35x 35x   35x               35x   1x                                                             35x                                             35x             2x 1x 1x     1x                                 35x 1x 1x 1x     35x 2x 2x 2x     35x         7x                 4x 4x                                                                   6x 10x   10x                                                                 6x 10x 10x                 6x  
/*
 * 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, { useState } from 'react'
import {
  Dialog,
  Button,
  Layout,
  TagsPopover,
  Text,
  useConfirmationDialog,
  useToaster,
  Container
} from '@harness/uicore'
import { Color } from '@harness/design-system'
import cx from 'classnames'
import { useHistory, useParams } from 'react-router-dom'
import { defaultTo, isEmpty, pick } from 'lodash-es'
import { useModalHook } from '@harness/use-modal'
import { Classes, Intent, Menu, Popover, Position } from '@blueprintjs/core'
import routes from '@common/RouteDefinitions'
import useRBACError from '@rbac/utils/useRBACError/useRBACError'
import { ResourceType } from '@rbac/interfaces/ResourceType'
import { PermissionIdentifier } from '@rbac/interfaces/PermissionIdentifier'
import { ServiceTabs } from '@cd/components/ServiceDetails/ServiceDetailsContent/ServiceDetailsContent'
import type { ModulePathParams, ProjectPathProps } from '@common/interfaces/RouteInterfaces'
import { useStrings } from 'framework/strings'
import { useDeleteServiceV2 } from 'services/cd-ng'
 
import RbacMenuItem from '@rbac/components/MenuItem/MenuItem'
import { NewEditServiceModal } from '@cd/components/PipelineSteps/DeployServiceStep/DeployServiceStep'
import css from './ServicesListColumns.module.scss'
 
interface ServiceRow {
  row: { original: any }
}
interface ServiceItemProps {
  data: any
  onRefresh?: () => Promise<void>
}
 
export enum DeploymentStatus {
  SUCCESS = 'success',
  FAILED = 'failed'
}
 
const ServiceMenu = (props: ServiceItemProps): React.ReactElement => {
  const { data: service, onRefresh } = props
  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', css.serviceDialogStyles)}
      >
        <Container>
          <NewEditServiceModal
            data={
              {
                ...pick(service, ['name', 'identifier', 'orgIdentifier', 'projectIdentifier', 'description', 'tags'])
              } || { name: '', identifier: '' }
            }
            isEdit={true}
            isService={false}
            onCreateOrUpdate={() => {
              hideModal()
              onRefresh && onRefresh()
            }}
            closeModal={hideModal}
          />
        </Container>
      </Dialog>
    ),
    [service, 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: service?.identifier,
            module
          }),
          search: `tab=${ServiceTabs.REFERENCED_BY}`
        })
      }
    }
  })
 
  const { openDialog } = useConfirmationDialog({
    titleText: getString('common.deleteService'),
    contentText: getString('common.deleteServiceConfirmation', { name: service?.name }),
    cancelButtonText: getString('cancel'),
    confirmButtonText: getString('confirm'),
    intent: Intent.DANGER,
    onCloseDialog: async isConfirmed => {
      if (isConfirmed) {
        try {
          const response = await deleteService(service?.identifier, {
            headers: { 'content-type': 'application/json' }
          })
          Iif (response.status === 'SUCCESS') {
            showSuccess(getString('common.deleteServiceMessage'))
            onRefresh && onRefresh()
          }
        } catch (err: any) {
          if (err?.data?.code === 'ENTITY_REFERENCE_EXCEPTION') {
            // showing reference by error in modal
            setDeleteError(err?.data?.message || err?.message)
            openDeleteErrorDialog()
          } else {
            showError(getRBACErrorMessage(err))
          }
        }
      }
    }
  })
 
  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(service?.identifier, '')
              },
              permission: PermissionIdentifier.EDIT_SERVICE
            }}
          />
          <RbacMenuItem
            icon="trash"
            text={getString('delete')}
            onClick={handleDelete}
            permission={{
              resource: {
                resourceType: ResourceType.SERVICE,
                resourceIdentifier: defaultTo(service?.identifier, '')
              },
              permission: PermissionIdentifier.DELETE_SERVICE
            }}
          />
        </Menu>
      </Popover>
    </Layout.Horizontal>
  )
}
 
const ServiceName = ({ row }: ServiceRow): React.ReactElement => {
  const service = row.original
 
  return (
    <div className={css.serviceName}>
      <Layout.Vertical>
        <Text color={Color.BLACK}>{service?.name}</Text>
 
        <Layout.Horizontal flex>
          <Text
            margin={{ top: 'xsmall', right: 'medium' }}
            color={Color.GREY_500}
            style={{
              fontSize: '12px',
              lineHeight: '24px',
              wordBreak: 'break-word'
            }}
          >
            Id: {service?.identifier}
          </Text>
 
          {!isEmpty(service?.tags) && (
            <div className={css.serviceTags}>
              <TagsPopover
                className={css.serviceTagsPopover}
                iconProps={{ size: 14, color: Color.GREY_600 }}
                tags={defaultTo(service?.tags, {})}
              />
            </div>
          )}
        </Layout.Horizontal>
      </Layout.Vertical>
    </div>
  )
}
 
const ServiceDescription = ({ row }: ServiceRow): React.ReactElement => {
  const service = row.original
  return (
    <Layout.Vertical className={css.serviceDescriptionWrapper}>
      <div className={css.serviceDescription}>
        <Text lineClamp={1}>{service?.description}</Text>
      </div>
    </Layout.Vertical>
  )
}
 
export { ServiceName, ServiceDescription, ServiceMenu }