All files / modules/85-cv/pages/health-source/common/CustomMetric CustomMetric.utils.ts

96.15% Statements 75/78
74.55% Branches 82/110
100% Functions 19/19
95.71% Lines 67/70

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              35x 35x               35x 35x                     35x               19x 19x 1x     18x     18x 18x 1x       17x 1x       17x 4x 4x           4x                     17x       17x     35x 8x 8x     35x       62x 55x     35x       62x 55x             35x       30x 35x           30x 35x       35x                 1x 1x 1x   1x 1x             1x       1x 1x             35x                   1x 1x 1x                     35x         63x   53x       35x         63x             35x               38x   40x 38x   38x 35x 34x   1x     38x 1x       38x 1x     38x                 38x         38x    
/*
 * 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 { v4 as uuid } from 'uuid'
import { cloneDeep, groupBy } from 'lodash-es'
import type { SelectOption } from '@harness/uicore'
import type { StringKeys, UseStringsReturn } from 'framework/strings'
import type {
  GroupedCreatedMetrics,
  GroupedMetric
} from '@cv/components/MultiItemsSideNav/components/SelectedAppsSideNav/components/GroupedSideNav/GroupedSideNav.types'
import type { BaseHealthSourceMetricInfo } from '@cv/pages/health-source/common/utils/HealthSource.types'
import { HealthSourceFieldNames } from '@cv/pages/health-source/common/utils/HealthSource.constants'
import { validateAssignComponent, validateIdentifier } from '@cv/pages/health-source/common/utils/HealthSource.utils'
import type {
  CustomMappedMetric,
  RemoveMetricInterface,
  CustomSelectedAndMappedMetrics,
  SelectMetricInerface,
  UpdateSelectedMetricsMapInterface,
  CreatedMetricsWithSelectedIndex,
  InitCustomFormData
} from './CustomMetric.types'
 
export function updateSelectedMetricsMap({
  updatedMetric,
  oldMetric,
  mappedMetrics,
  formikValues,
  initCustomForm,
  isPrimaryMetric
}: UpdateSelectedMetricsMapInterface): { selectedMetric: string; mappedMetrics: Map<string, CustomMappedMetric> } {
  const emptyName = formikValues.metricName?.length
  if (!emptyName) {
    return { selectedMetric: updatedMetric, mappedMetrics: mappedMetrics }
  }
 
  const updatedMap = new Map(mappedMetrics)
 
  const duplicateName =
    Array.from(mappedMetrics.keys()).indexOf(formikValues.metricName) > -1 && oldMetric !== formikValues?.metricName
  if (duplicateName) {
    return { selectedMetric: updatedMetric, mappedMetrics: updatedMap }
  }
 
  // in the case where user updates metric name, update the key for current value
  if (oldMetric !== formikValues?.metricName) {
    updatedMap.delete(oldMetric)
  }
 
  // if newly created metric create form object
  if (!updatedMap.has(updatedMetric)) {
    const metricIdentifier = updatedMetric.split(' ').join('_')
    const identifierObject = isPrimaryMetric
      ? {
          metricIdentifier,
          identifier: metricIdentifier
        }
      : { metricIdentifier }
    updatedMap.set(updatedMetric, {
      ...{
        _id: uuid(),
        metricName: updatedMetric,
        ...identifierObject,
        ...initCustomForm
      }
    } as any)
  }
 
  // update map with current form data
  updatedMap.set(formikValues.metricName, {
    ...formikValues
  })
 
  return { selectedMetric: updatedMetric, mappedMetrics: updatedMap }
}
 
export const defaultGroupedMetric = (getString: UseStringsReturn['getString']): SelectOption => {
  const createdMetricLabel = getString('cv.addGroupName')
  return { label: createdMetricLabel, value: createdMetricLabel }
}
 
export const initGroupedCreatedMetrics = (
  mappedMetrics: Map<string, CustomMappedMetric>,
  getString: UseStringsReturn['getString']
): GroupedCreatedMetrics =>
  groupBy(getGroupAndMetric(mappedMetrics, getString), function (item) {
    return item?.groupName?.label
  })
 
export const getGroupAndMetric = (
  mappedMetrics: Map<string, CustomMappedMetric>,
  getString: UseStringsReturn['getString']
): GroupedMetric[] => {
  return Array.from(mappedMetrics?.values()).map(item => {
    return {
      groupName: item.groupName || defaultGroupedMetric(getString),
      metricName: item.metricName
    }
  })
}
 
export const getGroupedCreatedMetrics = (
  mappedMetrics: Map<string, CustomMappedMetric>,
  getString: UseStringsReturn['getString']
): GroupedCreatedMetrics => {
  const filteredList = Array.from(mappedMetrics?.values()).map((item, index) => {
    return {
      index,
      groupName: item.groupName || defaultGroupedMetric(getString),
      metricName: item.metricName
    }
  })
  return groupBy(filteredList.reverse(), function (item) {
    return item?.groupName?.label
  })
}
 
export const onRemoveMetric = ({
  removedMetric,
  updatedMetric,
  updatedList,
  smIndex,
  setCreatedMetrics,
  setMappedMetrics,
  formikValues
}: RemoveMetricInterface): void => {
  setMappedMetrics(oldState => {
    const { selectedMetric: oldMetric, mappedMetrics: oldMappedMetric } = oldState
    const updatedMap = new Map(oldMappedMetric)
 
    Eif (updatedMap.has(removedMetric)) {
      updatedMap.delete(removedMetric)
    } else {
      // handle case where user updates the metric name for current selected metric
      updatedMap.delete(oldMetric)
    }
 
    // update map with current values
    Iif (formikValues?.metricName !== removedMetric && formikValues?.metricName === updatedMetric) {
      updatedMap.set(updatedMetric, { ...formikValues } || { metricName: updatedMetric })
    }
 
    setCreatedMetrics({ selectedMetricIndex: smIndex, createdMetrics: updatedList })
    return {
      selectedMetric: updatedMetric,
      mappedMetrics: updatedMap
    }
  })
}
 
export const onSelectMetric = ({
  newMetric,
  updatedList,
  smIndex,
  setCreatedMetrics,
  setMappedMetrics,
  formikValues,
  initCustomForm,
  isPrimaryMetric
}: SelectMetricInerface): void => {
  setMappedMetrics(oldState => {
    setCreatedMetrics({ selectedMetricIndex: smIndex, createdMetrics: updatedList })
    return updateSelectedMetricsMap({
      updatedMetric: newMetric,
      oldMetric: oldState.selectedMetric,
      mappedMetrics: oldState.mappedMetrics,
      formikValues,
      initCustomForm,
      isPrimaryMetric
    })
  })
}
 
export function initializeCreatedMetrics(
  defaultSelectedMetricName: string,
  selectedMetric: string,
  mappedMetrics: CustomSelectedAndMappedMetrics['mappedMetrics']
): CreatedMetricsWithSelectedIndex {
  return {
    createdMetrics: Array.from(mappedMetrics.keys()) || [defaultSelectedMetricName],
    selectedMetricIndex: Array.from(mappedMetrics.keys()).findIndex(metric => metric === selectedMetric)
  }
}
 
export function initializeSelectedMetricsMap(
  defaultSelectedMetricName: string,
  initCustomFormData: InitCustomFormData,
  mappedServicesAndEnvs?: Map<string, CustomMappedMetric>
): CustomSelectedAndMappedMetrics {
  return {
    selectedMetric: (Array.from(mappedServicesAndEnvs?.keys() || [])?.[0] as string) || defaultSelectedMetricName,
    mappedMetrics:
      mappedServicesAndEnvs || new Map([[defaultSelectedMetricName, initCustomFormData as CustomMappedMetric]])
  }
}
 
export const validateCommonCustomMetricFields = (
  values: BaseHealthSourceMetricInfo,
  createdMetrics: string[],
  selectedMetricIndex: number,
  errors: any,
  getString: (key: StringKeys) => string,
  mappedMetrics?: Map<string, BaseHealthSourceMetricInfo>
): ((key: string) => string) => {
  let errorsToReturn = cloneDeep(errors)
 
  const isAssignComponentValid = [values.sli, values.continuousVerification, values.healthScore].find(i => i) || false
  const isRiskCategoryValid = !!values?.riskCategory
 
  const duplicateNames = createdMetrics?.filter((metricName, index) => {
    if (index === selectedMetricIndex) {
      return false
    }
    return metricName === values.metricName
  })
 
  if (!values.groupName || !values.groupName?.value) {
    errorsToReturn[HealthSourceFieldNames.GROUP_NAME] = getString(
      'cv.monitoringSources.prometheus.validation.groupName'
    )
  }
  if (!values.metricName) {
    errorsToReturn[HealthSourceFieldNames.METRIC_NAME] = getString('cv.monitoringSources.metricNameValidation')
  }
 
  errorsToReturn = validateIdentifier(
    values,
    createdMetrics,
    selectedMetricIndex,
    errorsToReturn,
    getString,
    mappedMetrics
  )
 
  Iif (values.metricName && duplicateNames.length) {
    errorsToReturn[HealthSourceFieldNames.METRIC_NAME] = getString(
      'cv.monitoringSources.prometheus.validation.metricNameUnique'
    )
  }
  return validateAssignComponent(isAssignComponentValid, errorsToReturn, getString, values, isRiskCategoryValid)
}