All files / modules/75-cd/components/ServiceDetails/ActiveServiceInstances ActiveServiceInstancesContent.tsx

97.4% Statements 75/77
89.61% Branches 69/77
100% Functions 19/19
97.33% Lines 73/75

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              10x 10x   10x 10x 10x 10x 10x   10x         10x 10x 10x 10x 10x   10x 10x                           10x     5x 4x   1x 1x 2x 1x     1x     10x       11x 11x 8x   3x 6x 6x 3x 3x 3x 9x               3x         3x     10x         21x                             10x           21x 21x                   1x         21x     10x         21x                             10x         21x         28x                                                   10x 12x 11x     11x   11x           11x   11x 5x     11x 1x     1x           11x 5x                                                           11x 11x       11x 8x 8x 2x           6x 2x   1x       4x                           8x     3x            
/*
 * 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, { useCallback, useEffect, useMemo, useState } from 'react'
import { useParams } from 'react-router-dom'
import type { CellProps, Renderer } from 'react-table'
import cx from 'classnames'
import { Color } from '@harness/design-system'
import { Container, Layout, Popover, Text, PageError } from '@wings-software/uicore'
import { PopoverInteractionKind } from '@blueprintjs/core'
import { PageSpinner, Table } from '@common/components'
import type { ProjectPathProps, ServicePathProps } from '@common/interfaces/RouteInterfaces'
import {
  EnvBuildIdAndInstanceCountInfo,
  GetEnvBuildInstanceCountQueryParams,
  useGetEnvBuildInstanceCount
} from 'services/cd-ng'
import { useStrings } from 'framework/strings'
import { ActiveServiceInstancePopover } from '@cd/components/ServiceDetails/ActiveServiceInstances/ActiveServiceInstancePopover'
import MostActiveServicesEmptyState from '@cd/icons/MostActiveServicesEmptyState.svg'
import { numberFormatter } from '@cd/components/Services/common'
import css from '@cd/components/ServiceDetails/ActiveServiceInstances/ActiveServiceInstances.module.scss'
 
const TOTAL_VISIBLE_BUILDS = 5
const TOTAL_VISIBLE_INSTANCES = 10
 
type VisibleBuildCount = { [key: string]: number }
 
interface TableRowData {
  envId?: string
  envName?: string
  buildId?: string
  instanceCount?: number
  remainingCount?: number
  showEnvName: boolean
}
 
// returns a map of env id and total builds count
const initVisibleBuildCount = (
  envBuildIdAndInstanceCountInfo?: EnvBuildIdAndInstanceCountInfo[]
): VisibleBuildCount => {
  if (!envBuildIdAndInstanceCountInfo) {
    return {}
  }
  const visibleBuildCount: VisibleBuildCount = {}
  envBuildIdAndInstanceCountInfo.forEach(item => {
    if (item.envId) {
      visibleBuildCount[item.envId] = TOTAL_VISIBLE_BUILDS
    }
  })
  return visibleBuildCount
}
 
const getTableData = (
  envBuildIdAndInstanceCountInfo?: EnvBuildIdAndInstanceCountInfo[],
  visibleBuildCount?: VisibleBuildCount
): TableRowData[] => {
  const tableData: TableRowData[] = []
  if (!envBuildIdAndInstanceCountInfo || !visibleBuildCount) {
    return tableData
  }
  envBuildIdAndInstanceCountInfo.forEach(item => {
    const envId = item.envId
    if (envId) {
      const visibleRowsForEnv = visibleBuildCount[envId]
      const totalAvailableBuildsForEnv = item.buildIdAndInstanceCountList?.length || 0
      item.buildIdAndInstanceCountList?.slice(0, visibleRowsForEnv).forEach((row, index) => {
        tableData.push({
          showEnvName: !index,
          envId,
          envName: item.envName,
          buildId: row.buildId,
          instanceCount: row.count
        })
      })
      Iif (visibleRowsForEnv < totalAvailableBuildsForEnv) {
        tableData.push({ envId, remainingCount: totalAvailableBuildsForEnv - visibleRowsForEnv, showEnvName: false })
      }
    }
  })
  return tableData
}
 
const RenderEnvironment: Renderer<CellProps<TableRowData>> = ({
  row: {
    original: { envName, showEnvName }
  }
}) => {
  return showEnvName ? (
    <Container className={css.paddedContainer}>
      <Text
        className={cx(css.environmentRow, css.overflow)}
        font={{ size: 'small', weight: 'bold' }}
        color={Color.WHITE}
      >
        {envName}
      </Text>
    </Container>
  ) : (
    <></>
  )
}
 
const RenderBuildName: Renderer<CellProps<TableRowData>> = ({
  row: {
    original: { envId, buildId, remainingCount }
  },
  column
}) => {
  const { getString } = useStrings()
  const component = buildId ? (
    <Text font={{ size: 'small', weight: 'semi-bold' }} className={css.overflow} color={Color.GREY_800}>
      {buildId}
    </Text>
  ) : (
    <Text
      font={{ size: 'xsmall', weight: 'semi-bold' }}
      color={Color.PRIMARY_6}
      background={Color.PRIMARY_1}
      className={css.seeMore}
      onClick={() => (column as any)?.expandBuilds?.(envId)}
    >
      {getString('cd.serviceDashboard.seeMore', { count: numberFormatter(remainingCount) })}
    </Text>
  )
  return <Container className={css.paddedContainer}>{component}</Container>
}
 
const RenderInstanceCount: Renderer<CellProps<TableRowData>> = ({
  row: {
    original: { instanceCount }
  }
}) => {
  return instanceCount ? (
    <Container className={css.paddedContainer}>
      <Text
        font={{ size: 'xsmall', weight: 'bold' }}
        background={Color.GREY_100}
        className={cx(css.instanceCount, css.overflow)}
      >
        {numberFormatter(instanceCount)}
      </Text>
    </Container>
  ) : (
    <></>
  )
}
 
const RenderInstances: Renderer<CellProps<TableRowData>> = ({
  row: {
    original: { envId, buildId, instanceCount }
  }
}) => {
  return instanceCount ? (
    <Container className={cx(css.paddedContainer, css.hexContainer)} flex={{ justifyContent: 'flex-start' }}>
      {Array(Math.min(instanceCount, TOTAL_VISIBLE_INSTANCES))
        .fill(null)
        .map((_, index) => (
          <Popover interactionKind={PopoverInteractionKind.CLICK} key={index}>
            <Container
              className={css.hex}
              width={18}
              height={18}
              background={Color.PRIMARY_3}
              margin={{ left: 'xsmall', right: 'xsmall', top: 'xsmall', bottom: 'xsmall' }}
            ></Container>
            <ActiveServiceInstancePopover buildId={buildId} envId={envId} instanceNum={index} />
          </Popover>
        ))}
      {instanceCount > TOTAL_VISIBLE_INSTANCES ? (
        <Text
          font={{ size: 'small', weight: 'semi-bold' }}
          color={Color.GREY_600}
          margin={{ left: 'xsmall' }}
        >{`+${numberFormatter(instanceCount - TOTAL_VISIBLE_INSTANCES)}`}</Text>
      ) : (
        <></>
      )}
    </Container>
  ) : (
    <></>
  )
}
 
export const ActiveServiceInstancesContent: React.FC = () => {
  const { getString } = useStrings()
  const { accountId, orgIdentifier, projectIdentifier, serviceId } = useParams<ProjectPathProps & ServicePathProps>()
 
  // this state holds how many builds are visible for each environment, it updates as we click on show more button
  const [visibleBuildCount, setVisibleBuildCount] = useState<VisibleBuildCount>({})
 
  const queryParams: GetEnvBuildInstanceCountQueryParams = {
    accountIdentifier: accountId,
    orgIdentifier,
    projectIdentifier,
    serviceId
  }
  const { loading, data, error, refetch } = useGetEnvBuildInstanceCount({ queryParams })
 
  useEffect(() => {
    setVisibleBuildCount(initVisibleBuildCount(data?.data?.envBuildIdAndInstanceCountInfoList))
  }, [data, setVisibleBuildCount])
 
  const expandBuilds = useCallback((envId?: string): void => {
    Iif (!envId) {
      return
    }
    setVisibleBuildCount(prevVisibleBuildCount => ({
      ...prevVisibleBuildCount,
      [envId]: prevVisibleBuildCount[envId] + TOTAL_VISIBLE_BUILDS
    }))
  }, [])
 
  const columns = useMemo(() => {
    return [
      {
        Header: getString('environment'),
        id: 'service',
        width: '20%',
        Cell: RenderEnvironment
      },
      {
        Header: getString('cd.serviceDashboard.buildName'),
        id: 'type',
        width: '20%',
        Cell: RenderBuildName,
        expandBuilds
      },
      {
        Header: '',
        id: 'serviceInstances',
        width: '10%',
        Cell: RenderInstanceCount
      },
      {
        Header: getString('common.instanceLabel'),
        id: 'deployments',
        width: '50%',
        Cell: RenderInstances
      }
    ]
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [])
 
  const tableData: TableRowData[] = useMemo(
    () => getTableData(data?.data?.envBuildIdAndInstanceCountInfoList, visibleBuildCount),
    [data, visibleBuildCount]
  )
 
  if (loading || error || !(data?.data?.envBuildIdAndInstanceCountInfoList || []).length) {
    const component = (() => {
      if (loading) {
        return (
          <Container data-test="ActiveServiceInstancesLoader" height="360px">
            <PageSpinner />
          </Container>
        )
      }
      if (error) {
        return (
          <Container data-test="ActiveServiceInstancesError" height="360px">
            <PageError onClick={() => refetch()} />
          </Container>
        )
      }
      return (
        <Layout.Vertical
          height="360px"
          flex={{ align: 'center-center' }}
          data-test="ActiveServiceInstancesEmpty"
          className={css.activeServiceInstancesEmpty}
        >
          <Container margin={{ bottom: 'medium' }}>
            <img width="50" height="50" src={MostActiveServicesEmptyState} style={{ alignSelf: 'center' }} />
          </Container>
          <Text color={Color.GREY_400}>{getString('cd.serviceDashboard.noActiveServiceInstances')}</Text>
        </Layout.Vertical>
      )
    })()
    return component
  }
 
  return (
    <Layout.Horizontal padding={{ top: 'medium' }}>
      <Table<TableRowData> columns={columns} data={tableData} className={css.instanceTable} />
    </Layout.Horizontal>
  )
}