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

100% Statements 40/40
89.47% Branches 51/57
100% Functions 6/6
100% Lines 37/37

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              10x 10x 10x 10x 10x   10x           10x 10x 10x 10x 10x 10x 10x 10x   10x 5x 5x   5x 5x                 5x   5x 5x                   5x   5x 5x 5x 3x   8x 6x     5x 1x     4x   4x   4x                                                 4x 4x   4x                                                                                                                              
/*
 * 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, { useMemo } from 'react'
import { useParams } from 'react-router-dom'
import moment from 'moment'
import { Color } from '@harness/design-system'
import { Container, Layout, Text } from '@wings-software/uicore'
import type { ProjectPathProps, ServicePathProps } from '@common/interfaces/RouteInterfaces'
import {
  GetActiveServiceInstanceSummaryQueryParams,
  GetInstanceGrowthTrendQueryParams,
  useGetActiveServiceInstanceSummary,
  useGetInstanceGrowthTrend
} from 'services/cd-ng'
import { PieChart, PieChartProps } from '@cd/components/PieChart/PieChart'
import { useStrings } from 'framework/strings'
import { INVALID_CHANGE_RATE, numberFormatter } from '@cd/components/Services/common'
import { TrendPopover } from '@cd/components/TrendPopover/TrendPopover'
import { SparklineChart } from '@common/components/SparklineChart/SparklineChart'
import { startOfDay } from '@common/components/TimeRangeSelector/TimeRangeSelector'
import { Ticker } from '@common/components/Ticker/Ticker'
import css from '@cd/components/ServiceDetails/ActiveServiceInstances/ActiveServiceInstances.module.scss'
 
export const ActiveServiceInstancesHeader: React.FC = () => {
  const { getString } = useStrings()
  const { accountId, orgIdentifier, projectIdentifier, serviceId } = useParams<ProjectPathProps & ServicePathProps>()
 
  const queryParams: GetActiveServiceInstanceSummaryQueryParams = useMemo(
    () => ({
      accountIdentifier: accountId,
      orgIdentifier,
      projectIdentifier,
      serviceId,
      timestamp: startOfDay(moment().subtract(1, 'month').add(1, 'day')).getTime()
    }),
    [accountId, orgIdentifier, projectIdentifier, serviceId]
  )
  const { data, error } = useGetActiveServiceInstanceSummary({ queryParams })
 
  const instanceGrowthTrendQueryParams: GetInstanceGrowthTrendQueryParams = useMemo(
    () => ({
      accountIdentifier: accountId,
      orgIdentifier,
      projectIdentifier,
      serviceId,
      startTime: moment().utc().startOf('day').subtract(6, 'months').toDate().getTime(),
      endTime: moment().utc().startOf('day').toDate().getTime()
    }),
    [accountId, orgIdentifier, projectIdentifier, serviceId]
  )
  const { data: instanceGrowthTrendData } = useGetInstanceGrowthTrend({ queryParams: instanceGrowthTrendQueryParams })
 
  const trendData: number[] = useMemo(() => {
    const timeValuePairList = instanceGrowthTrendData?.data?.timeValuePairList || []
    if (!timeValuePairList.length) {
      return []
    }
    timeValuePairList.sort((prev, curr) => (prev.timestamp || 0) - (curr.timestamp || 0))
    return timeValuePairList.map(timeValuePair => timeValuePair.value || 0)
  }, [instanceGrowthTrendData])
 
  if (error) {
    return <></>
  }
 
  const { nonProdInstances = 0, prodInstances = 0, totalInstances = 0 } = data?.data?.countDetails || {}
 
  const changeRate = data?.data?.changeRate || 0
 
  const pieChartProps: PieChartProps = {
    items: [
      {
        label: getString('cd.serviceDashboard.nonProd'),
        value: nonProdInstances,
        formattedValue: numberFormatter(nonProdInstances),
        color: 'var(--primary-2)'
      },
      {
        label: getString('cd.serviceDashboard.prod'),
        value: prodInstances,
        formattedValue: numberFormatter(prodInstances),
        color: 'var(--primary-7)'
      }
    ],
    size: 36,
    labelContainerStyles: css.pieChartLabelContainerStyles,
    labelStyles: css.pieChartLabelStyles,
    options: {
      tooltip: {
        enabled: false
      }
    }
  }
 
  const isBoostMode = changeRate === INVALID_CHANGE_RATE
  const tickerColor = isBoostMode || changeRate > 0 ? Color.GREEN_600 : Color.RED_500
 
  return (
    <Layout.Horizontal
      flex={{ alignItems: 'center', justifyContent: 'space-between' }}
      padding={{ bottom: 'small' }}
      className={css.activeServiceInstancesHeader}
    >
      <Layout.Horizontal>
        <Text
          font={{ weight: 'bold' }}
          color={Color.GREY_800}
          className={css.instanceCount}
          margin={{ right: 'large' }}
        >
          {numberFormatter(totalInstances)}
        </Text>
        <Layout.Vertical flex={{ alignItems: 'flex-start', justifyContent: 'flex-start' }}>
          <Ticker
            value={
              isBoostMode ? (
                <></>
              ) : (
                <Text font={{ size: 'xsmall' }} color={tickerColor}>{`${numberFormatter(Math.abs(changeRate), {
                  truncate: false
                })}%`}</Text>
              )
            }
            decreaseMode={!isBoostMode && changeRate < 0}
            boost={isBoostMode}
            color={tickerColor}
            size={isBoostMode ? 10 : 6}
          />
          <Text font={{ size: 'xsmall' }}>
            {getString('cd.serviceDashboard.in', {
              timeRange: getString('common.duration.month').toLocaleLowerCase()
            })}
          </Text>
        </Layout.Vertical>
      </Layout.Horizontal>
      <Layout.Horizontal>
        {trendData.length ? (
          <Container margin={{ right: 'medium' }}>
            <TrendPopover
              title={getString('cd.serviceDashboard.serviceInstancesInLast', {
                period: getString('common.duration.6months')
              })}
              data={trendData}
            >
              <SparklineChart
                title={getString('cd.serviceDashboard.6monthTrend')}
                data={trendData}
                options={{ chart: { width: 80, height: 50 } }}
                sparklineChartContainerStyles={css.hover}
              />
            </TrendPopover>
          </Container>
        ) : (
          <></>
        )}
        {totalInstances ? <PieChart {...pieChartProps} /> : <></>}
      </Layout.Horizontal>
    </Layout.Horizontal>
  )
}