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

100% Statements 56/56
83.33% Branches 10/12
100% Functions 11/11
100% Lines 56/56

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              24x 24x 24x 24x 24x 24x 24x 24x 24x 24x             24x 24x 24x   24x 24x   24x 17x   17x 17x 17x 17x       17x             17x 17x 17x   17x         8x                   20x                         2x 2x 2x   2x 1x     1x       2x 1x   1x     2x 2x       1x 1x 1x             1x                                           1x 1x 1x 1x 1x 1x     1x 1x 1x 1x 1x 1x                                                                                               2x                                  
/*
 * 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, { useContext, useState } from 'react'
import { Container, Formik, FormikForm, Utils, Layout, Accordion, FormInput } from '@harness/uicore'
import { cloneDeep, isNil, noop } from 'lodash-es'
import { SetupSourceLayout } from '@cv/components/CVSetupSourcesView/SetupSourceLayout/SetupSourceLayout'
import { SetupSourceTabsContext } from '@cv/components/CVSetupSourcesView/SetupSourceTabs/SetupSourceTabs'
import { SetupSourceCardHeader } from '@cv/components/CVSetupSourcesView/SetupSourceCardHeader/SetupSourceCardHeader'
import { useStrings } from 'framework/strings'
import { MultiItemsSideNav } from '@cv/components/MultiItemsSideNav/MultiItemsSideNav'
import DrawerFooter from '../../common/DrawerFooter/DrawerFooter'
import {
  initializeSelectedQueryMap,
  updateSelectedMetricsMap,
  validateSetupSource,
  submitForm
} from './CustomHealthLogSource.utils'
import type { CustomHealthLogSetupSource, SelectedAndMappedQueries } from './CustomHealthLogSource.types'
import QueryMapping from '../CustomHealthSource/components/QueryMapping/QueryMapping'
import JsonPathSelection from './components/JsonPathSelection/JsonPathSelection'
import { CustomHealthLogFieldNames, DEFAULT_CUSTOM_LOG_SETUP_SOURCE } from './CustomHealthLogSource.constants'
import type { MapCustomHealthToService } from '../CustomHealthSource/CustomHealthSource.types'
import customHealthCss from '../CustomHealthSource/CustomHealthSource.module.scss'
import css from './CustomHealthLogSource.module.scss'
 
export default function CustomHealthLogSource(props: any): JSX.Element {
  const { data: sourceData, onSubmit } = props
 
  const { getString } = useStrings()
  const { onPrevious } = useContext(SetupSourceTabsContext)
  const [rerenderKey, setRerenderKey] = useState('')
  const [{ selectedQuery, mappedQueries }, setMappedQueries] = useState<SelectedAndMappedQueries>(
    initializeSelectedQueryMap(sourceData)
  )
 
  const [{ createdQueries, selectedIndex }, setCreatedQueries] = useState({
    createdQueries: Array.from(mappedQueries.keys()) || [
      getString('cv.monitoringSources.datadogLogs.datadogLogsQuery')
    ],
    selectedIndex: 0
  })
 
  const [sampleDataLoading, setSampleDataLoading] = useState(false)
  const [recordsData, setRecordsData] = useState<Record<string, unknown> | undefined>()
  const areJsonMappingFieldsDisabled = isNil(recordsData) || sampleDataLoading
 
  return (
    <Formik<CustomHealthLogSetupSource>
      key={rerenderKey}
      formName="customHealthLogSource"
      enableReinitialize={true}
      validate={data => validateSetupSource(data, getString, createdQueries, selectedIndex)}
      initialValues={
        mappedQueries.get(selectedQuery) || {
          ...cloneDeep(DEFAULT_CUSTOM_LOG_SETUP_SOURCE),
          queryName: `Custom Log ${Utils.randomId()}`
        }
      }
      onSubmit={noop}
    >
      {formikProps => {
        return (
          <FormikForm>
            <SetupSourceLayout
              leftPanelContent={
                <MultiItemsSideNav
                  defaultMetricName={selectedQuery}
                  tooptipMessage={getString('cv.monitoringSources.gcoLogs.addQueryTooltip')}
                  addFieldLabel={getString('cv.monitoringSources.addQuery')}
                  createdMetrics={createdQueries}
                  defaultSelectedMetric={selectedQuery}
                  renamedMetric={formikProps.values.queryName}
                  isValidInput={Object.keys(formikProps.errors).length === 0}
                  onRemoveMetric={(removedQuery, updatedQueryName, updatedList, selectedQueryIndex) => {
                    setMappedQueries(oldState => {
                      const { selectedQuery: oldQuery, mappedQueries: oldMappedQueries } = oldState
                      const updatedMap = new Map(oldMappedQueries)
 
                      if (updatedMap.has(removedQuery)) {
                        updatedMap.delete(removedQuery)
                      } else {
                        // handle case where user updates the metric name for current selected metric
                        updatedMap.delete(oldQuery)
                      }
 
                      // update map with current values
                      if (formikProps.values.queryName !== removedQuery) {
                        updatedMap.set(updatedQueryName, { ...formikProps.values })
                      } else {
                        setRerenderKey(Utils.randomId())
                      }
 
                      setCreatedQueries({ createdQueries: updatedList, selectedIndex: selectedQueryIndex })
                      return { selectedQuery: updatedQueryName, mappedQueries: updatedMap }
                    })
                  }}
                  onSelectMetric={(newMetric, updatedList, selectedQueryIndex) => {
                    setCreatedQueries({ createdQueries: updatedList, selectedIndex: selectedQueryIndex })
                    setMappedQueries(oldState => {
                      return updateSelectedMetricsMap({
                        updatedQueryName: newMetric,
                        oldQueryName: oldState.selectedQuery,
                        mappedQuery: oldState.mappedQueries,
                        formikProps
                      })
                    })
                    setRerenderKey(Utils.randomId())
                  }}
                />
              }
              content={
                <Container className={customHealthCss.main}>
                  <SetupSourceCardHeader
                    mainHeading={getString('cv.monitoringSources.prometheus.querySpecificationsAndMappings')}
                    subHeading={getString('cv.monitoringSources.prometheus.customizeQuery')}
                  />
                  <Layout.Horizontal className={customHealthCss.content} spacing="xlarge">
                    <Accordion activeId="querymapping" className={customHealthCss.accordian}>
                      <Accordion.Panel
                        id="querymapping"
                        summary={getString('cv.customHealthSource.Querymapping.title')}
                        details={
                          <Container>
                            <FormInput.Text
                              name={CustomHealthLogFieldNames.QUERY_NAME}
                              label={getString('cv.monitoringSources.queryName')}
                              className={css.customHealthLogFieldWidth}
                              onChange={e => {
                                const val = (e.target as any).value
                                formikProps.setFieldValue('queryName', val)
                                setCreatedQueries(oldQueries => {
                                  const updatedQueries = [...oldQueries.createdQueries]
                                  updatedQueries[oldQueries.selectedIndex] = val
                                  return { selectedIndex: oldQueries.selectedIndex, createdQueries: updatedQueries }
                                })
 
                                setMappedQueries(oldObj => {
                                  const newMap = new Map(oldObj.mappedQueries)
                                  const oldValue = newMap.get(oldObj.selectedQuery)
                                  newMap.delete(oldObj.selectedQuery)
                                  newMap.set(val, oldValue as CustomHealthLogSetupSource)
                                  return { selectedQuery: val, mappedQueries: newMap }
                                })
                              }}
                            />
                            <QueryMapping
                              onFieldChange={formikProps.setFieldValue}
                              formValue={
                                {
                                  requestMethod: formikProps.values.requestMethod,
                                  query: formikProps.values.query || '',
                                  startTime: formikProps.values.startTime,
                                  endTime: formikProps.values.endTime,
                                  pathURL: formikProps.values.pathURL
                                } as MapCustomHealthToService
                              }
                              connectorIdentifier={sourceData.connectorRef}
                              onFetchRecordsSuccess={setRecordsData}
                              setLoading={setSampleDataLoading}
                              recordsData={recordsData}
                              isQueryExecuted={!isNil(recordsData)}
                            />
                          </Container>
                        }
                      />
                      <Accordion.Panel
                        id="queryJSONPaths"
                        summary={getString('cv.customHealthSource.Querymapping.jsonPathTitle')}
                        details={
                          <JsonPathSelection
                            className={css.customHealthLogFieldWidth}
                            sampleRecord={recordsData}
                            onChange={formikProps.setFieldValue}
                            disableFields={areJsonMappingFieldsDisabled}
                            valueForQueryValueJsonPath={formikProps.values.queryValueJsonPath}
                            valueForTimestampJsonPath={formikProps.values.timestampJsonPath}
                            valueForServiceInstanceJsonPath={formikProps.values.serviceInstanceJsonPath}
                          />
                        }
                      />
                    </Accordion>
                  </Layout.Horizontal>
                </Container>
              }
            />
            <DrawerFooter
              isSubmit
              onPrevious={onPrevious}
              onNext={() =>
                submitForm({
                  formikProps,
                  onSubmit,
                  sourceData,
                  mappedQueries,
                  getString,
                  selectedIndex,
                  createdQueries
                })
              }
            />
          </FormikForm>
        )
      }}
    </Formik>
  )
}