All files / modules/85-cv/pages/health-source/connectors/NewRelic/components/NewRelicCustomMetricForm NewRelicCustomMetricForm.tsx

100% Statements 48/48
83.53% Branches 71/85
100% Functions 9/9
100% Lines 47/47

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              25x 25x   25x 25x 25x 25x 25x 25x 25x 25x 25x 25x 25x               25x 25x 25x   25x   25x 6x 6x 6x   6x       6x       6x 6x   6x 2x                               6x         6x   6x 2x                 6x           6x       6x 1x 1x       6x 1x           1x         6x 3x       6x       6x 6x 6x   3x     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, { useMemo, useState, useContext, useCallback } from 'react'
import { useParams } from 'react-router-dom'
import type { GetDataError } from 'restful-react'
import { Container, Accordion, SelectOption, Utils, Button } from '@wings-software/uicore'
import { SetupSourceTabsContext } from '@cv/components/CVSetupSourcesView/SetupSourceTabs/SetupSourceTabs'
import SelectHealthSourceServices from '@cv/pages/health-source/common/SelectHealthSourceServices/SelectHealthSourceServices'
import GroupName from '@cv/components/GroupName/GroupName'
import MetricLineChart from '@cv/pages/health-source/common/MetricLineChart/MetricLineChart'
import { SetupSourceCardHeader } from '@cv/components/CVSetupSourcesView/SetupSourceCardHeader/SetupSourceCardHeader'
import { QueryViewer } from '@cv/components/QueryViewer/QueryViewer'
import { InputWithDynamicModalForJson } from '@cv/components/InputWithDynamicModalForJson/InputWithDynamicModalForJson'
import { NameId } from '@common/components/NameIdDescriptionTags/NameIdDescriptionTags'
import { useStrings } from 'framework/strings'
import {
  NewRelicMetricDefinition,
  TimeSeriesSampleDTO,
  useFetchParsedSampleData,
  useGetMetricPacks,
  useGetSampleDataForNRQL
} from 'services/cv'
import type { ProjectPathProps } from '@common/interfaces/RouteInterfaces'
import { initializeGroupNames } from '@cv/pages/health-source/common/GroupName/GroupName.utils'
import { NewRelicHealthSourceFieldNames } from '../../NewRelicHealthSource.constants'
import { getOptionsForChart } from './NewRelicCustomMetricForm.utils'
import type { NewRelicCustomFormInterface } from './NewRelicCustomMetricForm.types'
import css from '../../NewrelicMonitoredSource.module.scss'
 
export default function NewRelicCustomMetricForm(props: NewRelicCustomFormInterface) {
  const { connectorIdentifier, mappedMetrics, selectedMetric, formikSetField, formikValues } = props
  const { getString } = useStrings()
  const { accountId, orgIdentifier, projectIdentifier } = useParams<ProjectPathProps>()
 
  const metricPackResponse = useGetMetricPacks({
    queryParams: { projectIdentifier, orgIdentifier, accountId, dataSourceType: 'NEW_RELIC' }
  })
 
  const [newRelicGroupName, setNewRelicGroupName] = useState<SelectOption[]>(
    initializeGroupNames(mappedMetrics, getString)
  )
 
  const [isQueryExecuted, setIsQueryExecuted] = useState(false)
  const query = useMemo(() => (formikValues?.query?.length ? formikValues.query.trim() : ''), [formikValues])
 
  const queryParamsForNRQL = useMemo(
    () => ({
      accountId,
      projectIdentifier,
      orgIdentifier,
      requestGuid: Utils.randomId(),
      connectorIdentifier,
      nrql: query
    }),
 
    [accountId, projectIdentifier, orgIdentifier, connectorIdentifier, query]
  )
  const {
    data: nrqlResponse,
    refetch: fetchRecords,
    loading,
    error
  } = useGetSampleDataForNRQL({
    queryParams: queryParamsForNRQL,
    lazy: true
  })
 
  const sampleRecord = nrqlResponse?.data as Record<string, any>
 
  const queryParamsForTimeSeriesData = useMemo(
    () => ({
      accountId,
      orgIdentifier,
      projectIdentifier
    }),
 
    [accountId, orgIdentifier, projectIdentifier]
  )
 
  const [newRelicTimeSeriesData, setNewRelicTimeSeriesData] = useState<TimeSeriesSampleDTO[] | undefined>()
 
  const {
    mutate: fetchNewRelicTimeSeriesData,
    loading: timeSeriesDataLoading,
    error: timeseriesDataError
  } = useFetchParsedSampleData({
    queryParams: queryParamsForTimeSeriesData
  })
 
  const fetchNewRelicResponse = useCallback(async () => {
    fetchRecords({ queryParams: queryParamsForNRQL })
    setIsQueryExecuted(true)
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [queryParamsForNRQL])
 
  const handleBuildChart = useCallback(() => {
    fetchNewRelicTimeSeriesData({
      groupName: formikValues?.groupName?.value,
      jsonResponse: JSON.stringify(sampleRecord),
      metricValueJSONPath: formikValues?.metricValue,
      timestampJSONPath: formikValues?.timestamp
    }).then(data => {
      setNewRelicTimeSeriesData(data.data)
    })
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [formikValues, queryParamsForTimeSeriesData])
 
  const options = useMemo(() => {
    return newRelicTimeSeriesData ? getOptionsForChart(newRelicTimeSeriesData) : []
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [newRelicTimeSeriesData])
 
  const isSelectingJsonPathDisabled = !isQueryExecuted || loading || !sampleRecord
 
  const {
    sourceData: { existingMetricDetails }
  } = useContext(SetupSourceTabsContext)
  const metricDefinitions = existingMetricDetails?.spec?.newRelicMetricDefinitions
  const currentSelectedMetricDetail = metricDefinitions?.find(
    (metricDefinition: NewRelicMetricDefinition) =>
      metricDefinition.metricName === mappedMetrics.get(selectedMetric || '')?.metricName
  )
 
  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: NewRelicHealthSourceFieldNames.METRIC_NAME,
                    idName: NewRelicHealthSourceFieldNames.METRIC_IDENTIFIER,
                    isIdentifierEditable: Boolean(!currentSelectedMetricDetail?.identifier)
                  }}
                />
                <GroupName
                  groupNames={newRelicGroupName}
                  onChange={formikSetField}
                  item={formikValues?.groupName}
                  setGroupNames={setNewRelicGroupName}
                  label={getString('cv.monitoringSources.prometheus.groupName')}
                  title={getString('cv.healthSource.connectors.NewRelic.groupName')}
                  fieldName={'groupName'}
                />
              </>
            }
          />
          <Accordion.Panel
            id="querySpecificationsAndMapping"
            summary={getString('cv.healthSource.connectors.NewRelic.queryMapping')}
            details={
              <>
                <QueryViewer
                  recordsClassName={css.recordsClassName}
                  queryLabel={getString('cv.healthSource.connectors.NewRelic.nrqlQuery')}
                  isQueryExecuted={isQueryExecuted}
                  queryNotExecutedMessage={getString('cv.healthSource.connectors.NewRelic.submitQueryNoRecords')}
                  records={[sampleRecord] as Record<string, any>[]}
                  fetchRecords={fetchNewRelicResponse}
                  loading={loading}
                  error={error}
                  query={query}
                  fetchEntityName={getString('cv.response')}
                  dataTooltipId={'newRelicQuery'}
                />
              </>
            }
          />
          <Accordion.Panel
            id="metricChart"
            summary={getString('cv.healthSource.connectors.NewRelic.metricValueAndCharts')}
            details={
              <>
                <InputWithDynamicModalForJson
                  onChange={formikSetField}
                  fieldValue={formikValues?.metricValue}
                  isQueryExecuted={isQueryExecuted}
                  isDisabled={isSelectingJsonPathDisabled}
                  sampleRecord={sampleRecord}
                  inputName={NewRelicHealthSourceFieldNames.METRIC_VALUE}
                  inputLabel={getString('cv.healthSource.connectors.NewRelic.metricFields.metricValueJsonPath.label')}
                  recordsModalHeader={getString(
                    'cv.healthSource.connectors.NewRelic.metricFields.metricValueJsonPath.recordsModalHeader'
                  )}
                  dataTooltipId={'metricValueJsonPath'}
                  showExactJsonPath={true}
                />
                <InputWithDynamicModalForJson
                  onChange={formikSetField}
                  fieldValue={formikValues?.timestamp}
                  isQueryExecuted={isQueryExecuted}
                  isDisabled={isSelectingJsonPathDisabled}
                  sampleRecord={sampleRecord}
                  inputName={NewRelicHealthSourceFieldNames.TIMESTAMP_LOCATOR}
                  inputLabel={getString('cv.healthSource.connectors.NewRelic.metricFields.timestampJsonPath.label')}
                  recordsModalHeader={getString(
                    'cv.healthSource.connectors.NewRelic.metricFields.timestampJsonPath.recordsModalHeader'
                  )}
                  dataTooltipId={'timestampJsonPath'}
                  showExactJsonPath={true}
                />
                <Button
                  intent="primary"
                  text={getString('cv.healthSource.connectors.buildChart')}
                  onClick={handleBuildChart}
                />
                <Container padding={{ top: 'small' }}>
                  <MetricLineChart
                    loading={timeSeriesDataLoading}
                    error={timeseriesDataError as GetDataError<Error>}
                    options={options}
                  />
                </Container>
              </>
            }
          />
          <Accordion.Panel
            id="riskProfile"
            summary={getString('cv.monitoringSources.assign')}
            details={
              <>
                <SelectHealthSourceServices
                  values={{
                    sli: !!formikValues?.sli,
                    riskCategory: formikValues?.riskCategory,
                    healthScore: !!formikValues?.healthScore,
                    continuousVerification: !!formikValues?.continuousVerification
                  }}
                  metricPackResponse={metricPackResponse}
                  hideServiceIdentifier={true}
                />
              </>
            }
          />
        </Accordion>
      </Container>
    </Container>
  )
}