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

72.41% Statements 63/87
39.84% Branches 49/123
80% Functions 12/15
68.83% Lines 53/77

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              27x 27x 27x 27x   27x                               27x 27x   27x   27x                                                                                           27x 128x                   27x 67x               27x           10x 8x     14x 4x   10x         27x 4x 4x     5x 4x     27x               3x 3x 3x 3x   1x 1x 1x       1x   1x   2x 2x 2x       2x   2x                             3x       3x   4x   3x 1x 2x 1x   3x               27x     2x 2x         2x 4x           2x      
/*
 * 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 from 'react'
import { Button, IconName, SelectOption } from '@wings-software/uicore'
import isEmpty from 'lodash-es/isEmpty'
import { getErrorMessage } from '@cv/utils/CommonUtils'
import type { UseStringsReturn } from 'framework/strings'
import {
  AppdynamicsValidationResponse,
  getNewRelicMetricDataPromise,
  getAppDynamicsMetricDataPromise,
  GetNewRelicMetricDataQueryParams,
  GetAppDynamicsMetricDataQueryParams,
  MetricPackDTO,
  MetricPackDTOArrayRequestBody,
  MetricPackValidationResponse,
  ResponseMetricPackValidationResponse,
  ResponseSetAppdynamicsValidationResponse,
  HealthSource,
  GetDynatraceMetricDataQueryParams,
  getDynatraceMetricDataPromise,
  DynatraceValidateDataRequestDTO
} from 'services/cv'
import { StatusOfValidation } from '@cv/pages/components/ValidationStatus/ValidationStatus.constants'
import { StatusState, HealthSoureSupportedConnectorTypes } from './MonitoredServiceConnector.constants'
import type { UpdatedHealthSource } from '../HealthSourceDrawer/HealthSourceDrawerContent.types'
import css from './NewRelic/NewrelicMonitoredSource.module.scss'
 
export const createPayloadByConnectorType = (formData: any, connector: string): UpdatedHealthSource | null => {
  let type: HealthSource['type']
  let specPayload = {}
  switch (connector) {
    case HealthSoureSupportedConnectorTypes.APP_DYNAMICS:
      type = 'AppDynamics'
      specPayload = {
        applicationName: formData.appdApplication as string,
        tierName: formData.appDTier as string
      }
      break
    case HealthSoureSupportedConnectorTypes.NEW_RELIC:
      type = 'NewRelic'
      specPayload = {
        ...formData,
        applicationName: formData?.newRelicApplication?.label,
        applicationId: formData?.newRelicApplication?.value
      }
      break
    default:
      return null
  }
 
  const healthSourcesPayload = {
    name: formData.name || (formData.healthSourceName as string),
    identifier: formData.identifier || (formData.healthSourceIdentifier as string),
    type,
    spec: {
      ...specPayload,
      feature: formData.product?.value as string,
      connectorRef: (formData?.connectorRef?.connector?.identifier as string) || (formData.connectorRef as string),
      metricPacks: Object.entries(formData.metricData)
        .map(item => {
          return item[1]
            ? {
                identifier: item[0]
              }
            : {}
        })
        .filter(item => !isEmpty(item))
    }
  }
 
  return healthSourcesPayload
}
 
export const InputIcon = ({ icon, onClick }: { icon: IconName; onClick?: () => void }): React.ReactElement => (
  <Button
    minimal
    icon={icon}
    iconProps={{ size: 15 }}
    onClick={onClick}
    margin={{ right: 'xsmall' }}
    className={css.iconButton}
  />
)
 
export const getInputGroupProps = (onClick: () => void) => {
  return {
    inputGroup: {
      leftElement: <InputIcon icon={'search'} />,
      rightElement: <InputIcon icon={'cross'} onClick={onClick} />
    }
  }
}
 
export const getOptions = (
  loading: boolean,
  data: any,
  connector: string,
  getString: UseStringsReturn['getString']
): SelectOption[] => {
  if (!data) return []
  return loading
    ? [{ label: getString('loading'), value: '' }]
    : data.map((item: any) => {
        if (HealthSoureSupportedConnectorTypes.NEW_RELIC === connector) {
          return { value: item.applicationId as unknown as string, label: item.applicationName as string }
        } else {
          return { value: item.id as unknown as string, label: item.name as string }
        }
      }) || []
}
 
export const createMetricDataFormik = (metricPacks: MetricPackDTO[] | undefined): { [key: string]: boolean } => {
  const metricData: { [key: string]: boolean } = {}
  Iif (!metricPacks) {
    metricPacks = []
  }
  metricPacks.forEach((i: MetricPackDTO) => (metricData[i.identifier as string] = true))
  return metricData
}
 
export async function validateMetrics(
  bodyData: MetricPackDTOArrayRequestBody | DynatraceValidateDataRequestDTO,
  queryParams:
    | GetAppDynamicsMetricDataQueryParams
    | GetNewRelicMetricDataQueryParams
    | GetDynatraceMetricDataQueryParams,
  connector: string
): Promise<{ validationStatus: string | undefined; validationResult?: AppdynamicsValidationResponse[]; error?: any }> {
  try {
    let response: ResponseMetricPackValidationResponse | ResponseSetAppdynamicsValidationResponse | null = null
    let data: AppdynamicsValidationResponse[] | null | undefined = null
    switch (connector) {
      case HealthSoureSupportedConnectorTypes.APP_DYNAMICS:
        Eif (queryParams) {
          const appDQueryParam = queryParams as GetAppDynamicsMetricDataQueryParams
          response = await getAppDynamicsMetricDataPromise({
            queryParams: appDQueryParam,
            body: bodyData as MetricPackDTOArrayRequestBody
          })
          data = response?.data
        }
        break
      case HealthSoureSupportedConnectorTypes.NEW_RELIC:
        Eif (queryParams) {
          const newRelicQueryParam = queryParams as GetNewRelicMetricDataQueryParams
          response = await getNewRelicMetricDataPromise({
            queryParams: newRelicQueryParam,
            body: bodyData as MetricPackDTOArrayRequestBody
          })
          data = response?.data && transformNewRelicDataToAppd([response?.data])
        }
        break
      case HealthSoureSupportedConnectorTypes.DYNATRACE:
        if (queryParams) {
          const dynatraceQueryParam = queryParams as GetDynatraceMetricDataQueryParams
          response = await getDynatraceMetricDataPromise({
            queryParams: dynatraceQueryParam,
            body: bodyData as DynatraceValidateDataRequestDTO
          })
          data = response?.data && transformNewRelicDataToAppd(response?.data)
        }
        break
      default:
        break
    }
 
    Iif (response?.status === 'ERROR') {
      return { validationStatus: undefined, error: getErrorMessage({ data: response }) }
    }
 
    Eif (data?.length) {
      let status
      Iif (data?.some(val => val.overallStatus === StatusState.FAILED)) {
        status = StatusOfValidation.ERROR
      } else if (data?.some(val => val.overallStatus === StatusState.NO_DATA)) {
        status = StatusOfValidation.NO_DATA
      } else if (data?.every(val => val.overallStatus === StatusState.SUCCESS)) {
        status = StatusOfValidation.SUCCESS
      }
      return { validationStatus: status, validationResult: data }
    }
    return { validationStatus: undefined }
  } catch (e) {
    return { validationStatus: undefined, error: getErrorMessage(e) }
  }
}
 
export function transformNewRelicDataToAppd(
  metricData: MetricPackValidationResponse[]
): AppdynamicsValidationResponse[] {
  return metricData.map(metricDataItem => {
    const appDMeticData: AppdynamicsValidationResponse = {
      overallStatus: metricDataItem.overallStatus,
      metricPackName: metricDataItem.metricPackName,
      values: []
    }
    for (const newRelicData of metricDataItem.metricValidationResponses || []) {
      appDMeticData.values?.push({
        value: newRelicData.value,
        apiResponseStatus: newRelicData.status,
        metricName: newRelicData.metricName
      })
    }
    return appDMeticData
  })
}