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

85.71% Statements 60/70
43.33% Branches 78/180
68.42% Functions 13/19
85.51% Lines 59/69

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 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363              24x 24x 24x                       24x 24x   24x 24x 24x 24x 24x 24x 24x 24x 24x 24x 24x             24x 24x             24x 24x 24x 24x 24x   24x   24x                 13x 13x 13x 13x 13x 13x               13x 13x 13x                     13x           13x           13x                         13x 1x 1x 1x                         1x           13x   4x         13x 5x         13x 8x         1x                 13x 7x       13x       13x         40x                   5x                         20x                                                                                                                           1x                                                                                                                                         1x                   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, { useEffect, useState, useMemo } from 'react'
import { useParams } from 'react-router-dom'
import {
  Text,
  Container,
  Formik,
  FormikForm,
  FormInput,
  Layout,
  SelectOption,
  Utils,
  useToaster,
  Button
} from '@wings-software/uicore'
import { PopoverInteractionKind } from '@blueprintjs/core'
import { Color } from '@harness/design-system'
import type { ProjectPathProps } from '@common/interfaces/RouteInterfaces'
import { useGetNewRelicApplications, MetricPackDTO, MetricPackValidationResponse } from 'services/cv'
import { Connectors } from '@connectors/constants'
import { getErrorMessage } from '@cv/utils/CommonUtils'
import { useStrings } from 'framework/strings'
import CardWithOuterTitle from '@cv/pages/health-source/common/CardWithOuterTitle/CardWithOuterTitle'
import DrawerFooter from '@cv/pages/health-source/common/DrawerFooter/DrawerFooter'
import MetricsVerificationModal from '@cv/components/MetricsVerificationModal/MetricsVerificationModal'
import ValidationStatus from '@cv/pages/components/ValidationStatus/ValidationStatus'
import { StatusOfValidation } from '@cv/pages/components/ValidationStatus/ValidationStatus.constants'
import useGroupedSideNaveHook from '@cv/hooks/GroupedSideNaveHook/useGroupedSideNaveHook'
import {
  getOptions,
  getInputGroupProps,
  validateMetrics,
  createMetricDataFormik
} from '../MonitoredServiceConnector.utils'
 
import { HealthSoureSupportedConnectorTypes } from '../MonitoredServiceConnector.constants'
import {
  createNewRelicFormData,
  createNewRelicPayloadBeforeSubmission,
  initializeNonCustomFields,
  setNewRelicApplication,
  validateMapping
} from './NewRelicHealthSource.utils'
import CustomMetric from '../../common/CustomMetric/CustomMetric'
import MetricPackCustom from '../MetricPackCustom'
import NewRelicCustomMetricForm from './components/NewRelicCustomMetricForm/NewRelicCustomMetricForm'
import { initNewRelicCustomFormValue } from './components/NewRelicCustomMetricForm/NewRelicCustomMetricForm.utils'
import css from './NewrelicMonitoredSource.module.scss'
 
const guid = Utils.randomId()
 
export default function NewRelicHealthSource({
  data: newRelicData,
  onSubmit,
  onPrevious
}: {
  data: any
  onSubmit: (healthSourcePayload: any) => void
  onPrevious: () => void
}): JSX.Element {
  const { getString } = useStrings()
  const { showError } = useToaster()
  const defailtMetricName = getString('cv.monitoringSources.newRelic.defaultNewRelicMetricName')
  const [selectedMetricPacks, setSelectedMetricPacks] = useState<MetricPackDTO[]>([])
  const [validationResultData, setValidationResultData] = useState<MetricPackValidationResponse[]>()
  const [newRelicValidation, setNewRelicValidation] = useState<{
    status: string
    result: MetricPackValidationResponse[] | []
  }>({
    status: '',
    result: []
  })
 
  const { accountId, orgIdentifier, projectIdentifier } = useParams<ProjectPathProps>()
  const connectorIdentifier = newRelicData?.connectorRef?.connector?.identifier || newRelicData?.connectorRef
  const [showCustomMetric, setShowCustomMetric] = useState(!!Array.from(newRelicData?.mappedServicesAndEnvs)?.length)
 
  const {
    createdMetrics,
    mappedMetrics,
    selectedMetric,
    groupedCreatedMetrics,
    groupedCreatedMetricsList,
    setMappedMetrics,
    setCreatedMetrics,
    setGroupedCreatedMetrics
  } = useGroupedSideNaveHook({
    defaultCustomMetricName: defailtMetricName,
    initCustomMetricData: initNewRelicCustomFormValue(),
    mappedServicesAndEnvs: showCustomMetric ? newRelicData?.mappedServicesAndEnvs : new Map()
  })
 
  const [nonCustomFeilds, setNonCustomFeilds] = useState(initializeNonCustomFields(newRelicData))
 
  const {
    data: applicationsData,
    loading: applicationLoading,
    error: applicationError
  } = useGetNewRelicApplications({
    queryParams: {
      accountId,
      connectorIdentifier,
      orgIdentifier,
      projectIdentifier,
      offset: 0,
      pageSize: 10000,
      filter: '',
      tracingId: guid
    }
  })
 
  const onValidate = async (appName: string, appId: string, metricObject: { [key: string]: any }): Promise<void> => {
    setNewRelicValidation({ status: StatusOfValidation.IN_PROGRESS, result: [] })
    const filteredMetricPack = selectedMetricPacks?.filter(item => metricObject[item.identifier as string])
    const { validationStatus, validationResult } = await validateMetrics(
      filteredMetricPack || [],
      {
        appId,
        appName,
        accountId,
        connectorIdentifier: connectorIdentifier,
        orgIdentifier,
        projectIdentifier,
        requestGuid: guid
      },
      HealthSoureSupportedConnectorTypes.NEW_RELIC
    )
    setNewRelicValidation({
      status: validationStatus as string,
      result: validationResult as MetricPackValidationResponse[]
    })
  }
 
  const applicationOptions: SelectOption[] = useMemo(
    () =>
      getOptions(applicationLoading, applicationsData?.data, HealthSoureSupportedConnectorTypes.NEW_RELIC, getString),
    // eslint-disable-next-line react-hooks/exhaustive-deps
    [applicationLoading]
  )
 
  useEffect(() => {
    Iif (!selectedMetric && !mappedMetrics.size) {
      setShowCustomMetric(false)
    }
  }, [mappedMetrics, selectedMetric])
 
  useEffect(() => {
    if (
      newRelicData.isEdit &&
      selectedMetricPacks.length &&
      newRelicValidation.status !== StatusOfValidation.IN_PROGRESS
    ) {
      onValidate(
        newRelicData?.applicationName,
        newRelicData?.applicationId,
        createMetricDataFormik(newRelicData?.metricPacks)
      )
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [selectedMetricPacks, applicationLoading, newRelicData.isEdit])
 
  const initPayload = useMemo(
    () => createNewRelicFormData(newRelicData, mappedMetrics, selectedMetric, nonCustomFeilds, showCustomMetric),
    [newRelicData, mappedMetrics, selectedMetric, nonCustomFeilds, showCustomMetric]
  )
 
  Iif (applicationError) {
    showError(getErrorMessage(applicationError))
  }
 
  return (
    <Formik
      enableReinitialize
      formName={'newRelicHealthSourceform'}
      isInitialValid={(args: any) =>
        Object.keys(
          validateMapping(
            args.initialValues,
            groupedCreatedMetricsList,
            groupedCreatedMetricsList.indexOf(selectedMetric),
            getString
          )
        ).length === 0
      }
      validate={values => {
        return validateMapping(
          values,
          groupedCreatedMetricsList,
          groupedCreatedMetricsList.indexOf(selectedMetric),
          getString
        )
      }}
      initialValues={initPayload}
      onSubmit={async values => {
        await onSubmit(values)
      }}
    >
      {formik => {
        return (
          <FormikForm className={css.formFullheight}>
            <CardWithOuterTitle title={'Application'}>
              <Layout.Horizontal spacing={'large'} className={css.horizontalCenterAlign}>
                <Container margin={{ bottom: 'small' }} width={'300px'} color={Color.BLACK}>
                  <FormInput.Select
                    className={css.applicationDropdown}
                    onChange={item => {
                      setNonCustomFeilds({
                        ...nonCustomFeilds,
                        newRelicApplication: { label: item?.label, value: item?.value as string }
                      })
                      onValidate(
                        formik?.values?.newRelicApplication?.label,
                        formik?.values?.newRelicApplication?.value,
                        formik.values.metricData
                      )
                    }}
                    value={setNewRelicApplication(formik?.values?.newRelicApplication?.label, applicationOptions)}
                    name={'newRelicApplication'}
                    placeholder={
                      applicationLoading
                        ? getString('loading')
                        : getString('cv.healthSource.connectors.AppDynamics.applicationPlaceholder')
                    }
                    items={applicationOptions}
                    label={getString('cv.healthSource.connectors.NewRelic.applicationLabel')}
                    {...getInputGroupProps(() =>
                      setNonCustomFeilds({
                        ...nonCustomFeilds,
                        newRelicApplication: { label: '', value: '' }
                      })
                    )}
                  />
                </Container>
                <Container width={'300px'} color={Color.BLACK}>
                  {formik.values?.newRelicApplication.label && formik.values.newRelicApplication.value && (
                    <ValidationStatus
                      validationStatus={newRelicValidation?.status as StatusOfValidation}
                      onClick={
                        newRelicValidation.result?.length
                          ? () => setValidationResultData(newRelicValidation.result)
                          : undefined
                      }
                      onRetry={() =>
                        onValidate(
                          formik?.values?.newRelicApplication?.label,
                          formik?.values?.newRelicApplication?.value,
                          formik.values.metricData
                        )
                      }
                    />
                  )}
                </Container>
              </Layout.Horizontal>
            </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 => {
                      setNonCustomFeilds({
                        ...nonCustomFeilds,
                        metricData: value
                      })
                    }}
                    metricPackValue={formik.values.metricPacks}
                    metricDataValue={formik.values.metricData}
                    setSelectedMetricPacks={setSelectedMetricPacks}
                    connector={HealthSoureSupportedConnectorTypes.NEW_RELIC}
                    onChange={async metricValue => {
                      setNonCustomFeilds({
                        ...nonCustomFeilds,
                        metricData: metricValue
                      })
                      await onValidate(
                        formik?.values?.newRelicApplication?.label,
                        formik?.values?.newRelicApplication?.value,
                        metricValue
                      )
                    }}
                  />
                  {validationResultData && (
                    <MetricsVerificationModal
                      verificationData={validationResultData}
                      guid={guid}
                      onHide={setValidationResultData as () => void}
                      verificationType={Connectors.NEW_RELIC}
                    />
                  )}
                </Layout.Horizontal>
              </Layout.Vertical>
            </CardWithOuterTitle>
            {showCustomMetric ? (
              <CustomMetric
                isValidInput={formik.isValid}
                setMappedMetrics={setMappedMetrics}
                selectedMetric={selectedMetric}
                formikValues={formik.values}
                mappedMetrics={mappedMetrics}
                createdMetrics={createdMetrics}
                groupedCreatedMetrics={groupedCreatedMetrics}
                setCreatedMetrics={setCreatedMetrics}
                setGroupedCreatedMetrics={setGroupedCreatedMetrics}
                defaultMetricName={defailtMetricName}
                tooptipMessage={getString('cv.monitoringSources.gcoLogs.addQueryTooltip')}
                addFieldLabel={getString('cv.monitoringSources.addMetric')}
                initCustomForm={initNewRelicCustomFormValue()}
                shouldBeAbleToDeleteLastMetric
              >
                <NewRelicCustomMetricForm
                  connectorIdentifier={connectorIdentifier}
                  mappedMetrics={mappedMetrics}
                  selectedMetric={selectedMetric}
                  formikValues={formik.values}
                  formikSetField={formik.setFieldValue}
                />
              </CustomMetric>
            ) : (
              <CardWithOuterTitle
                title={getString('cv.healthSource.connectors.customMetrics')}
                dataTooltipId={'customMetricsTitle'}
              >
                <Button
                  icon="plus"
                  minimal
                  margin={{ left: 'medium' }}
                  intent="primary"
                  tooltip={getString('cv.healthSource.connectors.customMetricsTooltip')}
                  tooltipProps={{ interactionKind: PopoverInteractionKind.HOVER_TARGET_ONLY }}
                  onClick={() => setShowCustomMetric(true)}
                >
                  {getString('cv.monitoringSources.addMetric')}
                </Button>
              </CardWithOuterTitle>
            )}
            <DrawerFooter
              isSubmit
              onPrevious={onPrevious}
              onNext={() =>
                createNewRelicPayloadBeforeSubmission(
                  formik,
                  mappedMetrics,
                  selectedMetric,
                  groupedCreatedMetricsList.indexOf(selectedMetric),
                  groupedCreatedMetricsList,
                  getString,
                  onSubmit
                )
              }
            />
          </FormikForm>
        )
      }}
    </Formik>
  )
}