All files / modules/85-cv/pages/health-source/connectors/Dynatrace/components/DynatraceMetricPacksToService DynatraceMetricPacksToService.tsx

95.65% Statements 44/46
80.85% Branches 38/47
83.33% Functions 10/12
95.45% Lines 42/44

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              24x 24x 24x 24x 24x 24x 24x 24x 24x         24x 24x 24x 24x 24x 24x     24x 24x   24x 22x 22x 22x 22x 22x 22x   22x               22x                 22x 9x     22x 3x 3x 3x                     3x         22x 10x         1x     22x                                                                   6x     1x                                 1x                   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, { useEffect, useMemo, useState } from 'react'
import { useParams } from 'react-router-dom'
import { Container, FormInput, Layout, Text, Utils } from '@wings-software/uicore'
import { Color } from '@harness/design-system'
import { useStrings } from 'framework/strings'
import CardWithOuterTitle from '@cv/pages/health-source/common/CardWithOuterTitle/CardWithOuterTitle'
import { HealthSoureSupportedConnectorTypes } from '@cv/pages/health-source/connectors/MonitoredServiceConnector.constants'
import { mapServiceListToOptions } from '@cv/pages/health-source/connectors/Dynatrace/DynatraceHealthSource.utils'
import {
  createMetricDataFormik,
  getInputGroupProps,
  validateMetrics
} from '@cv/pages/health-source/connectors/MonitoredServiceConnector.utils'
import ValidationStatus from '@cv/pages/components/ValidationStatus/ValidationStatus'
import { StatusOfValidation } from '@cv/pages/components/ValidationStatus/ValidationStatus.constants'
import MetricPackCustom from '@cv/pages/health-source/connectors/MetricPackCustom'
import MetricsVerificationModal from '@cv/components/MetricsVerificationModal/MetricsVerificationModal'
import { Connectors } from '@connectors/constants'
import { MetricPackDTO, MetricPackValidationResponse, useGetDynatraceServices } from 'services/cv'
import type { ProjectPathProps } from '@common/interfaces/RouteInterfaces'
import type { DynatraceMetricPacksToServiceProps } from './DynatraceMetricPacksToService.types'
import { extractServiceMethods } from './DynatraceMetricPacksToService.utils'
import css from '@cv/pages/health-source/connectors/Dynatrace/DynatraceHealthSource.module.scss'
 
export default function DynatraceMetricPacksToService(props: DynatraceMetricPacksToServiceProps): JSX.Element {
  const { connectorIdentifier, dynatraceMetricData, setDynatraceMetricData, metricValues } = props
  const { getString } = useStrings()
  const { accountId, orgIdentifier, projectIdentifier } = useParams<ProjectPathProps>()
  const [servicesTracingId, validationTracingId] = useMemo(() => [Utils.randomId(), Utils.randomId()], [])
  const [validationResultData, setValidationResultData] = useState<MetricPackValidationResponse[]>()
  const [selectedMetricPacks, setSelectedMetricPacks] = useState<MetricPackDTO[]>([])
 
  const [dynatraceValidation, setDynatraceValidation] = useState<{
    status: string
    result: MetricPackValidationResponse[] | []
  }>({
    status: '',
    result: []
  })
 
  const { data: servicesListData, loading: servicesListLoading } = useGetDynatraceServices({
    queryParams: {
      accountId,
      connectorIdentifier,
      orgIdentifier,
      projectIdentifier,
      tracingId: servicesTracingId
    }
  })
  const dynatraceServiceOptions = useMemo(() => {
    return mapServiceListToOptions(servicesListData?.data || [])
  }, [servicesListData?.data])
 
  const onValidate = async (serviceMethods: string[], metricObject: { [key: string]: any }): Promise<void> => {
    setDynatraceValidation({ status: StatusOfValidation.IN_PROGRESS, result: [] })
    const filteredMetricPack = selectedMetricPacks.filter(item => metricObject[item.identifier as string])
    const { validationStatus, validationResult } = await validateMetrics(
      { metricPacks: filteredMetricPack, serviceMethodsIds: serviceMethods },
      {
        accountId,
        connectorIdentifier: connectorIdentifier,
        orgIdentifier,
        projectIdentifier,
        tracingId: validationTracingId
      },
      HealthSoureSupportedConnectorTypes.DYNATRACE
    )
    setDynatraceValidation({
      status: validationStatus as string,
      result: validationResult as MetricPackValidationResponse[]
    })
  }
  useEffect(() => {
    if (
      dynatraceMetricData.selectedService.value &&
      selectedMetricPacks.length &&
      dynatraceValidation.status !== StatusOfValidation.IN_PROGRESS
    ) {
      onValidate(dynatraceMetricData.serviceMethods || [], createMetricDataFormik(selectedMetricPacks))
    }
  }, [selectedMetricPacks, dynatraceMetricData.selectedService, dynatraceMetricData.serviceMethods])
  return (
    <>
      <CardWithOuterTitle title={'Services'}>
        <Layout.Horizontal spacing={'large'} className={css.horizontalCenterAlign}>
          <Container margin={{ bottom: 'small' }} width={'400px'} color={Color.BLACK}>
            <FormInput.Select
              className={css.applicationDropdown}
              onChange={item => {
                setDynatraceMetricData({
                  ...metricValues,
                  selectedService: { ...item },
                  serviceMethods: extractServiceMethods(servicesListData?.data || [], item.value as string)
                })
              }}
              value={dynatraceMetricData.selectedService}
              name={'dynatraceService'}
              placeholder={
                servicesListLoading
                  ? getString('loading')
                  : getString('cv.healthSource.connectors.Dynatrace.servicePlaceholder')
              }
              items={dynatraceServiceOptions}
              label={getString('cv.healthSource.connectors.Dynatrace.servicesLabel')}
              {...getInputGroupProps(() =>
                setDynatraceMetricData({ ...metricValues, selectedService: { label: '', value: '' } })
              )}
            />
          </Container>
          <Container width={'300px'} color={Color.BLACK}>
            {metricValues.selectedService?.value && (
              <ValidationStatus
                validationStatus={dynatraceValidation?.status as StatusOfValidation}
                onClick={
                  dynatraceValidation.result?.length
                    ? () => setValidationResultData(dynatraceValidation.result)
                    : undefined
                }
                onRetry={() => onValidate(metricValues.serviceMethods || [], metricValues.metricData)}
              />
            )}
          </Container>
        </Layout.Horizontal>
        <Container>
          <Text icon="warning-sign" iconProps={{ size: 14 }}>
            {getString('cv.healthSource.connectors.Dynatrace.keyRequestRequiredLabel')}
          </Text>
        </Container>
      </CardWithOuterTitle>
      <CardWithOuterTitle title={getString('metricPacks')}>
        <Layout.Vertical>
          <Text color={Color.BLACK}>{getString('cv.healthSource.connectors.AppDynamics.metricPackLabel')}</Text>
          <Layout.Horizontal spacing={'large'} className={css.horizontalCenterAlign}>
            <MetricPackCustom
              setMetricDataValue={value => {
                setDynatraceMetricData({
                  ...metricValues,
                  metricData: value
                })
              }}
              metricPackValue={metricValues.metricPacks}
              metricDataValue={metricValues.metricData}
              setSelectedMetricPacks={setSelectedMetricPacks}
              connector={HealthSoureSupportedConnectorTypes.DYNATRACE}
              onChange={async metricValue => {
                setDynatraceMetricData({
                  ...metricValues,
                  metricData: metricValue
                })
                await onValidate(metricValues.serviceMethods || [], metricValue)
              }}
            />
            {validationResultData && (
              <MetricsVerificationModal
                verificationData={validationResultData}
                guid={validationTracingId}
                onHide={setValidationResultData as () => void}
                verificationType={Connectors.DYNATRACE}
              />
            )}
          </Layout.Horizontal>
        </Layout.Vertical>
      </CardWithOuterTitle>
    </>
  )
}