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

98.15% Statements 53/54
81.58% Branches 31/38
91.67% Functions 11/12
98.11% Lines 52/53

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              24x 24x 24x                 24x 24x   24x 24x 24x 24x 24x   24x       24x 24x 24x 24x 24x 24x   24x 11x 11x 11x 11x 11x     11x     11x 11x 11x 11x 6x                 11x 11x 6x   11x   3x 1x   2x       2x 2x       11x                   11x 6x   11x 7x   11x 6x   11x 11x                                                                                           1x                                       1x 1x   1x                             2x                                                      
/*
 * 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 { useParams } from 'react-router-dom'
import {
  Container,
  Accordion,
  SelectOption,
  Utils,
  FormInput,
  useConfirmationDialog,
  Text
} from '@wings-software/uicore'
import { useStrings } from 'framework/strings'
import { useGetAllDynatraceServiceMetrics, useGetDynatraceSampleData, useGetMetricPacks } from 'services/cv'
import type { ProjectPathProps } from '@common/interfaces/RouteInterfaces'
import { NameId } from '@common/components/NameIdDescriptionTags/NameIdDescriptionTags'
import { SetupSourceCardHeader } from '@cv/components/CVSetupSourcesView/SetupSourceCardHeader/SetupSourceCardHeader'
import SelectHealthSourceServices from '@cv/pages/health-source/common/SelectHealthSourceServices/SelectHealthSourceServices'
import { QueryContent } from '@cv/components/QueryViewer/QueryViewer'
import GroupName from '@cv/components/GroupName/GroupName'
import type { DynatraceCustomMetricsProps } from '@cv/pages/health-source/connectors/Dynatrace/components/DynatraceCustomMetrics/DynatraceCustomMetrics.types'
import {
  editQueryConfirmationDialogProps,
  mapMetricSelectorsToMetricSelectorOptions
} from '@cv/pages/health-source/connectors/Dynatrace/components/DynatraceCustomMetrics/DynatraceCustomMetrics.utils'
import { DynatraceHealthSourceFieldNames } from '@cv/pages/health-source/connectors/Dynatrace/DynatraceHealthSource.constants'
import MetricsValidationChart from '@cv/components/CloudMetricsHealthSource/components/validationChart/MetricsValidationChart'
import { getErrorMessage } from '@cv/utils/CommonUtils'
import { transformSampleDataIntoHighchartOptions } from '@cv/pages/health-source/connectors/GCOMetricsHealthSource/GCOMetricsHealthSource.utils'
import { initializeGroupNames } from '@cv/pages/health-source/common/GroupName/GroupName.utils'
import css from '@cv/pages/health-source/connectors/Dynatrace/DynatraceHealthSource.module.scss'
 
export default function DynatraceCustomMetrics(props: DynatraceCustomMetricsProps): JSX.Element {
  const { mappedMetrics } = props
  const { selectedMetric, metricValues, connectorIdentifier, selectedServiceId, formikSetField } = props
  const { getString } = useStrings()
  const { accountId, orgIdentifier, projectIdentifier } = useParams<ProjectPathProps>()
  const metricPackResponse = useGetMetricPacks({
    queryParams: { projectIdentifier, orgIdentifier, accountId, dataSourceType: 'DYNATRACE' }
  })
  const [dynatraceGroupNames, setDynatraceGroupNames] = useState<SelectOption[]>(
    initializeGroupNames(mappedMetrics, getString)
  )
  const [shouldShowChart, setShouldShowChart] = useState<boolean>(false)
  const [timeseriesData, setTimeseriesData] = useState<Highcharts.Options>()
  const dynatraceServicesTracingId = useMemo(() => Utils.randomId(), [])
  const sampleDataQueryParams = useMemo(
    () => ({
      accountId,
      projectIdentifier,
      orgIdentifier,
      tracingId: Utils.randomId(),
      connectorIdentifier
    }),
    [accountId, projectIdentifier, orgIdentifier, connectorIdentifier]
  )
  const { mutate: querySampleData, loading, error } = useGetDynatraceSampleData({ queryParams: sampleDataQueryParams })
  const timeseriesDataErrorMessage = useMemo(() => {
    return getErrorMessage(error)
  }, [error])
  const onFetchSampleData = useCallback(
    async metricSelector => {
      if (!metricSelector.length) {
        return
      }
      const sampleData = await querySampleData(
        { metricSelector: metricSelector, serviceId: selectedServiceId },
        { queryParams: sampleDataQueryParams }
      )
      setTimeseriesData(transformSampleDataIntoHighchartOptions(sampleData.data))
      setShouldShowChart(true)
    },
    [querySampleData, sampleDataQueryParams, selectedServiceId]
  )
  const { data: serviceMetrics } = useGetAllDynatraceServiceMetrics({
    queryParams: {
      accountId,
      connectorIdentifier,
      orgIdentifier,
      projectIdentifier,
      tracingId: dynatraceServicesTracingId
    }
  })
  const metricSelectorOptions: SelectOption[] =
    useMemo(() => {
      return mapMetricSelectorsToMetricSelectorOptions(serviceMetrics?.data || [])
    }, [serviceMetrics?.data]) || []
  const currentActiveMetricSelector: SelectOption = useMemo(() => {
    return { label: metricValues.metricSelector || '', value: metricValues.metricSelector || '' }
  }, [metricValues.metricSelector])
  const selectedMetricData = useMemo(() => {
    return mappedMetrics.get(selectedMetric)
  }, [selectedMetric, mappedMetrics])
  const { openDialog } = useConfirmationDialog(editQueryConfirmationDialogProps(getString, formikSetField))
  return (
    <Container className={css.main}>
      <SetupSourceCardHeader
        mainHeading={getString('cv.monitoringSources.prometheus.querySpecificationsAndMappings')}
        subHeading={getString('cv.monitoringSources.prometheus.customizeQuery')}
      />
      <Container className={css.content}>
        <Accordion activeId="metricToService" className={css.accordian}>
          <Accordion.Panel
            id="metricToService"
            summary={getString('cv.monitoringSources.mapMetricsToServices')}
            details={
              <>
                <NameId
                  nameLabel={getString('cv.monitoringSources.metricNameLabel')}
                  identifierProps={{
                    inputName: DynatraceHealthSourceFieldNames.METRIC_NAME,
                    idName: DynatraceHealthSourceFieldNames.IDENTIFIER,
                    isIdentifierEditable: Boolean(!selectedMetricData?.identifier || selectedMetricData?.isNew)
                  }}
                />
                <GroupName
                  groupNames={dynatraceGroupNames}
                  onChange={formikSetField}
                  item={metricValues.groupName}
                  setGroupNames={setDynatraceGroupNames}
                  label={getString('cv.monitoringSources.prometheus.groupName')}
                  title={'Add Dynatrace group name'}
                  fieldName={DynatraceHealthSourceFieldNames.GROUP_NAME}
                />
              </>
            }
          />
          <Accordion.Panel
            id="querySpecificationsAndMapping"
            summary={getString('cv.healthSource.connectors.NewRelic.queryMapping')}
            details={
              <>
                {metricValues.isManualQuery && (
                  <Container className={css.manualQueryWarning}>
                    <Text icon="warning-sign" iconProps={{ size: 14 }}>
                      {getString('cv.monitoringSources.prometheus.isManualQuery')}
                    </Text>
                    <Text
                      data-testid={'data-undo-manual-query-action'}
                      intent="primary"
                      onClick={() => formikSetField(DynatraceHealthSourceFieldNames.MANUAL_QUERY, false)}
                    >
                      {getString('cv.monitoringSources.prometheus.undoManualQuery')}
                    </Text>
                  </Container>
                )}
                <FormInput.Select
                  disabled={metricValues.isManualQuery}
                  name={DynatraceHealthSourceFieldNames.ACTIVE_METRIC_SELECTOR}
                  label={getString('cv.monitoringSources.metricLabel')}
                  items={metricSelectorOptions}
                  value={currentActiveMetricSelector}
                  onChange={event => {
                    formikSetField(DynatraceHealthSourceFieldNames.METRIC_SELECTOR, event.value)
                  }}
                />
                <QueryContent
                  textAreaProps={{ readOnly: !metricValues.isManualQuery }}
                  onEditQuery={!metricValues.isManualQuery ? openDialog : undefined}
                  handleFetchRecords={async () => {
                    Eif (!shouldShowChart) {
                      setShouldShowChart(true)
                    }
                    onFetchSampleData(metricValues.metricSelector)
                  }}
                  isDialogOpen={false}
                  query={metricValues.metricSelector}
                  loading={!metricValues}
                  textAreaName={DynatraceHealthSourceFieldNames.METRIC_SELECTOR}
                />
                <MetricsValidationChart
                  submitQueryText={'cv.healthSource.connectors.Dynatrace.submitQueryLabel'}
                  loading={loading}
                  error={timeseriesDataErrorMessage}
                  sampleData={timeseriesData}
                  queryValue={metricValues.metricSelector}
                  isQueryExecuted={shouldShowChart}
                  onRetry={async () => {
                    onFetchSampleData(metricValues.metricSelector)
                  }}
                />
              </>
            }
          />
          <Accordion.Panel
            id="riskProfile"
            summary={getString('cv.monitoringSources.assign')}
            details={
              <SelectHealthSourceServices
                values={{
                  sli: !!metricValues.sli,
                  healthScore: !!metricValues.healthScore,
                  riskCategory: metricValues?.riskCategory,
                  continuousVerification: !!metricValues.continuousVerification
                }}
                metricPackResponse={metricPackResponse}
                hideServiceIdentifier={true}
              />
            }
          />
        </Accordion>
      </Container>
    </Container>
  )
}