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

91.46% Statements 75/82
74.36% Branches 87/117
87.5% Functions 14/16
90.41% Lines 66/73

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              25x                     25x     25x           52x   52x 52x 37x     52x       37x       52x 7x     52x     25x             7x   21x 7x   7x 3x 3x         7x 6x     7x       7x 6x     7x 6x     7x 6x     7x       7x 7x     25x             7x 7x 6x 1x 1x 1x     1x         7x     25x       1x                                               25x                     25x 13x 13x 13x 13x     25x 13x             25x                         8x                               25x                 3x                                     3x 3x 2x 2x   1x 1x 1x   1x 1x     25x       20x   5x  
/*
 * 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 { cloneDeep } from 'lodash-es'
import type { FormikProps } from 'formik'
import type { SelectOption } from '@wings-software/uicore'
import type { StringKeys } from 'framework/strings'
import type { MetricPackDTO } from 'services/cv'
import type {
  CreatedMetricsWithSelectedIndex,
  MapNewRelicMetric,
  NewRelicData,
  SelectedAndMappedMetrics
} from './NewRelicHealthSource.types'
import { NewRelicHealthSourceFieldNames } from './NewRelicHealthSource.constants'
import type { CustomMappedMetric } from '../../common/CustomMetric/CustomMetric.types'
 
export const validateMapping = (
  values: any,
  createdMetrics: string[],
  selectedMetricIndex: number,
  getString: (key: StringKeys) => string
): ((key: string | boolean | string[]) => string) => {
  let errors = {} as any
 
  const metricValueList = Object.values(values?.metricData).filter(val => val)
  if (!metricValueList.length) {
    errors['metricData'] = getString('cv.monitoringSources.appD.validations.selectMetricPack')
  }
 
  if (
    values?.newRelicApplication &&
    (!values.newRelicApplication.value || values.newRelicApplication.value === 'loading')
  ) {
    errors['newRelicApplication'] = getString('cv.healthSource.connectors.NewRelic.validations.application')
  }
 
  // if custom metrics are present then validate custom metrics form
  if (values?.showCustomMetric) {
    errors = validateCustomMetricFields(values, createdMetrics, selectedMetricIndex, errors, getString)
  }
 
  return errors
}
 
const validateCustomMetricFields = (
  values: any,
  createdMetrics: string[],
  selectedMetricIndex: number,
  errors: any,
  getString: (key: StringKeys) => string
): ((key: string | boolean | string[]) => string) => {
  let completErrors = cloneDeep(errors)
 
  const isAssignComponentValid = [values.sli, values.continuousVerification, values.healthScore].find(i => i)
  const isRiskCategoryValid = !!values?.riskCategory
 
  const duplicateNames = createdMetrics?.filter((metricName, index) => {
    Eif (index === selectedMetricIndex) {
      return false
    }
    return metricName === values.metricName
  })
 
  if (!values.groupName || !values.groupName?.value) {
    completErrors['groupName'] = getString('cv.monitoringSources.prometheus.validation.groupName')
  }
 
  Iif (!values.metricName) {
    completErrors['metricName'] = getString('cv.monitoringSources.metricNameValidation')
  }
 
  if (!values.query) {
    completErrors['query'] = getString('cv.healthSource.connectors.NewRelic.validations.nrql')
  }
 
  if (!values.metricValue) {
    completErrors['metricValue'] = getString('cv.healthSource.connectors.NewRelic.validations.metricValue')
  }
 
  if (!values.timestamp) {
    completErrors['timestamp'] = getString('cv.healthSource.connectors.NewRelic.validations.timestamp')
  }
 
  Iif (values.metricName && duplicateNames.length) {
    completErrors['metricName'] = getString('cv.monitoringSources.prometheus.validation.metricNameUnique')
  }
 
  completErrors = validateAssignComponent(isAssignComponentValid, completErrors, getString, values, isRiskCategoryValid)
  return completErrors
}
 
const validateAssignComponent = (
  isAssignComponentValid: boolean,
  errors: any,
  getString: (key: StringKeys) => string,
  values: any,
  isRiskCategoryValid: boolean
): ((key: string | boolean | string[]) => string) => {
  const _error = cloneDeep(errors)
  if (!isAssignComponentValid) {
    _error['sli'] = getString('cv.monitoringSources.gco.mapMetricsToServicesPage.validation.baseline')
  } else Eif (isAssignComponentValid) {
    Eif (values.continuousVerification || values.healthScore) {
      Iif (values.lowerBaselineDeviation !== true && values.higherBaselineDeviation !== true) {
        _error['lowerBaselineDeviation'] = getString('cv.monitoringSources.prometheus.validation.deviation')
      }
      Iif (!isRiskCategoryValid) {
        _error['riskCategory'] = getString('cv.monitoringSources.gco.mapMetricsToServicesPage.validation.riskCategory')
      }
    }
  }
  return _error
}
 
export function initializeSelectedMetricsMap(
  defaultSelectedMetricName: string,
  mappedServicesAndEnvs?: Map<string, MapNewRelicMetric>
): SelectedAndMappedMetrics {
  return {
    selectedMetric: (Array.from(mappedServicesAndEnvs?.keys() || [])?.[0] as string) || defaultSelectedMetricName,
    mappedMetrics:
      mappedServicesAndEnvs ||
      new Map([
        [
          defaultSelectedMetricName,
          {
            metricName: defaultSelectedMetricName,
            groupName: { label: '', value: '' },
            query: '',
            metricValue: '',
            timestamp: '',
            timestampFormat: '',
            serviceInstanceIdentifier: '',
            sli: false,
            healthScore: false,
            continuousVerification: false
          }
        ]
      ])
  }
}
 
export function initializeCreatedMetrics(
  defaultSelectedMetricName: string,
  selectedMetric: string,
  mappedMetrics: SelectedAndMappedMetrics['mappedMetrics']
): CreatedMetricsWithSelectedIndex {
  return {
    createdMetrics: Array.from(mappedMetrics.keys()) || [defaultSelectedMetricName],
    selectedMetricIndex: Array.from(mappedMetrics.keys()).findIndex(metric => metric === selectedMetric)
  }
}
 
export const convertMetricPackToMetricData = (value?: MetricPackDTO[]) => {
  const dataObject: { [key: string]: boolean } = {}
  const metricList: MetricPackDTO[] = value || []
  metricList.forEach((i: MetricPackDTO) => (dataObject[i.identifier as string] = true))
  return dataObject
}
 
export const initializeNonCustomFields = (newRelicData: NewRelicData) => {
  return {
    newRelicApplication: { label: newRelicData?.applicationName, value: newRelicData?.applicationId },
    metricPacks: newRelicData?.metricPacks || undefined,
    metricData: convertMetricPackToMetricData(newRelicData?.metricPacks)
  }
}
 
export const createNewRelicFormData = (
  newRelicData: NewRelicData,
  mappedMetrics: Map<string, CustomMappedMetric>,
  selectedMetric: string,
  nonCustomFeilds: {
    newRelicApplication: SelectOption
    metricPacks?: MetricPackDTO[]
    metricData: {
      [key: string]: boolean
    }
  },
  showCustomMetric: boolean
): any => {
  return {
    name: newRelicData.name,
    identifier: newRelicData.identifier,
    connectorRef: newRelicData.connectorRef,
    isEdit: newRelicData.isEdit,
    product: newRelicData.product,
    type: newRelicData.type,
    mappedServicesAndEnvs: newRelicData.mappedServicesAndEnvs,
    ...nonCustomFeilds,
    ...mappedMetrics.get(selectedMetric),
    metricName: selectedMetric,
    metricIdentifier: selectedMetric?.split(' ').join('_'),
    showCustomMetric
  }
}
 
export const createNewRelicPayloadBeforeSubmission = (
  formik: FormikProps<CustomMappedMetric>,
  mappedMetrics: Map<string, CustomMappedMetric>,
  selectedMetric: string,
  selectedMetricIndex: number,
  createdMetrics: string[],
  getString: (key: StringKeys) => string,
  onSubmit: (healthSourcePayload: any) => void
): void => {
  formik.setTouched({
    ...formik.touched,
    [NewRelicHealthSourceFieldNames.NEWRELIC_APPLICATION]: true,
    [NewRelicHealthSourceFieldNames.METRIC_DATA]: { Performance: true },
 
    [NewRelicHealthSourceFieldNames.METRIC_NAME]: true,
    [NewRelicHealthSourceFieldNames.GROUP_NAME]: true,
 
    [NewRelicHealthSourceFieldNames.NEWRELIC_QUERY]: true,
 
    [NewRelicHealthSourceFieldNames.METRIC_VALUE]: true,
    [NewRelicHealthSourceFieldNames.TIMESTAMP_LOCATOR]: true,
    [NewRelicHealthSourceFieldNames.TIMESTAMP_FORMAT]: true,
 
    [NewRelicHealthSourceFieldNames.SLI]: true,
    [NewRelicHealthSourceFieldNames.CONTINUOUS_VERIFICATION]: true,
    [NewRelicHealthSourceFieldNames.LOWER_BASELINE_DEVIATION]: true,
    [NewRelicHealthSourceFieldNames.RISK_CATEGORY]: true
  })
  const errors = validateMapping(formik.values, createdMetrics, selectedMetricIndex, getString)
  if (Object.keys(errors || {})?.length > 0) {
    formik.validateForm()
    return
  }
  const updatedMetric = formik.values
  Eif (updatedMetric) {
    mappedMetrics.set(selectedMetric, updatedMetric)
  }
  const updatedValues = { ...formik.values, mappedServicesAndEnvs: mappedMetrics }
  onSubmit(updatedValues)
}
 
export const setNewRelicApplication = (
  newRelicApplication: string,
  applicationOptions: SelectOption[]
): SelectOption | undefined =>
  !newRelicApplication
    ? { label: '', value: '' }
    : applicationOptions.find((item: SelectOption) => item.label === newRelicApplication)