All files / modules/85-cv/pages/health-source/connectors/CustomHealthSource/components/QueryMapping QueryMapping.tsx

100% Statements 37/37
78.85% Branches 41/52
100% Functions 7/7
100% Lines 36/36

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              26x 26x 26x 26x 26x 26x 26x 26x 26x 26x   26x 26x 26x 26x   26x 26x 26x 26x   26x                   27x 27x 27x   27x 7x     27x           27x                   27x 7x     27x 20x     27x 3x                   27x             5x 3x               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, { useMemo, useEffect } from 'react'
import { useParams } from 'react-router-dom'
import { Container, FormInput, Layout, Text, Utils, Icon } from '@wings-software/uicore'
import { FontVariation } from '@harness/design-system'
import { QueryViewer } from '@cv/components/QueryViewer/QueryViewer'
import { Records } from '@cv/components/Records/Records'
import { getErrorMessage } from '@cv/utils/CommonUtils'
import { HealthSourceQueryType } from '@cv/pages/health-source/common/HealthSourceQueryType/HealthSourceQueryType'
import Button from '@rbac/components/Button/Button'
import { useStrings } from 'framework/strings'
import type { ProjectPathProps } from '@common/interfaces/RouteInterfaces'
import { HTTPRequestMethodOption } from '@connectors/components/CreateConnector/CustomHealthConnector/components/CustomHealthValidationPath/components/HTTPRequestMethod/HTTPRequestMethod'
import { useFetchSampleData } from 'services/cv'
import { useGetConnector } from 'services/cd-ng'
import { QueryType } from '@cv/pages/health-source/common/HealthSourceQueryType/HealthSourceQueryType.types'
import type { QueryMappingInterface } from './QueryMapping.types'
import { CustomHealthSourceFieldNames } from '../../CustomHealthSource.constants'
import { timeFormatOptions } from './QueryMapping.constants'
import { connectorParams, onFetchRecords } from './QueryMapping.utils'
import css from './QueryMapping.module.scss'
 
export default function QueryMapping({
  formValue,
  onValueChange,
  onFieldChange,
  connectorIdentifier,
  onFetchRecordsSuccess,
  isQueryExecuted,
  recordsData,
  setLoading
}: QueryMappingInterface): JSX.Element {
  const { getString } = useStrings()
  const sampleDataTracingId = useMemo(() => Utils.randomId(), [])
  const { projectIdentifier, orgIdentifier, accountId } = useParams<ProjectPathProps & { identifier: string }>()
 
  const connectorPayload = useMemo(
    () => connectorParams(connectorIdentifier, { projectIdentifier, orgIdentifier, accountId }),
    [connectorIdentifier, projectIdentifier, orgIdentifier, accountId]
  )
  const { data: connectorData, loading: connectorLoading, error: connectorError } = useGetConnector(connectorPayload)
 
  const {
    mutate: getSampleData,
    error: sampleDataError,
    loading: sampleDataLoading
  } = useFetchSampleData({
    queryParams: {
      accountId,
      connectorIdentifier,
      orgIdentifier,
      projectIdentifier,
      tracingId: sampleDataTracingId
    }
  })
 
  useEffect(() => {
    setLoading(sampleDataLoading)
  }, [sampleDataLoading])
 
  useEffect(() => {
    onFieldChange(CustomHealthSourceFieldNames.BASE_URL, connectorData?.data?.connector?.spec?.baseURL)
  }, [connectorData])
 
  const fetchRecords = () =>
    onFetchRecords(
      formValue?.pathURL,
      formValue?.endTime,
      formValue?.startTime,
      formValue?.requestMethod,
      formValue?.query,
      getSampleData,
      onFetchRecordsSuccess
    )
 
  return (
    <Container>
      <Text margin={{ bottom: 'medium' }}>{getString('cv.customHealthSource.Querymapping.label')}</Text>
      <Container margin={{ top: 'medium', bottom: 'medium' }} border={{ bottom: true }}>
        {onValueChange && (
          <HealthSourceQueryType
            onChange={val => {
              if (val === QueryType.HOST_BASED) {
                onValueChange({
                  ...formValue,
                  queryType: val,
                  [CustomHealthSourceFieldNames.SLI]: false,
                  [CustomHealthSourceFieldNames.HEALTH_SCORE]: false,
                  [CustomHealthSourceFieldNames.CONTINUOUS_VERIFICATION]: true
                })
              } else {
                onValueChange({
                  ...formValue,
                  queryType: val,
                  [CustomHealthSourceFieldNames.CONTINUOUS_VERIFICATION]: false
                })
              }
            }}
            value={formValue.queryType}
          />
        )}
      </Container>
 
      <Container padding={{ top: 'medium', bottom: 'medium' }}>
        {connectorError ? (
          <Text padding={{ bottom: 'medium' }} font={{ variation: FontVariation.FORM_MESSAGE_DANGER }}>
            {getErrorMessage(connectorError)}
          </Text>
        ) : connectorLoading ? (
          <Icon name="spinner" margin={{ bottom: 'medium' }} size={24} />
        ) : (
          <FormInput.Text
            label={getString('connectors.baseURL')}
            name={CustomHealthSourceFieldNames.BASE_URL}
            disabled
          />
        )}
      </Container>
 
      <HTTPRequestMethodOption value={formValue.requestMethod} />
 
      <FormInput.Text
        className={css.baseUrl}
        label={getString('common.path')}
        name={CustomHealthSourceFieldNames.PATH}
      />
 
      <Text color={'black'} font={{ size: 'medium', weight: 'bold' }} margin={{ bottom: 'small', top: 'medium' }}>
        {getString('cv.customHealthSource.Querymapping.startAndEndTimeTitle')}
      </Text>
      <hr className={css.sectionDivider} />
      <Layout.Vertical>
        <Layout.Horizontal spacing={'large'} className={css.parameterLayout}>
          <FormInput.Text
            className={css.widthHalf}
            name={'startTime.placeholder'}
            label={getString('cv.customHealthSource.Querymapping.startTimeLabel')}
          />
          <FormInput.Select
            className={css.widthHalf}
            items={timeFormatOptions}
            name="startTime.timestampFormat"
            label={getString('cv.unit')}
          />
        </Layout.Horizontal>
        <Layout.Horizontal spacing={'large'} className={css.parameterLayout}>
          <FormInput.Text
            className={css.widthHalf}
            name="endTime.placeholder"
            label={getString('cv.customHealthSource.Querymapping.endTimeLabel')}
          />
          <FormInput.Select
            className={css.widthHalf}
            items={timeFormatOptions}
            name={'endTime.timestampFormat'}
            label={getString('cv.unit')}
          />
        </Layout.Horizontal>
      </Layout.Vertical>
      <Container margin={{ top: 'medium', bottom: 'medium' }}>
        {formValue?.requestMethod === 'POST' ? (
          <QueryViewer
            queryLabel={getString('common.smtp.labelBody')}
            isQueryExecuted={isQueryExecuted}
            queryNotExecutedMessage={getString('cv.healthSource.connectors.NewRelic.submitQueryNoRecords')}
            records={recordsData ? [recordsData] : []}
            fetchRecords={fetchRecords}
            loading={sampleDataLoading}
            error={sampleDataError}
            query={formValue.query}
            fetchEntityName={getString('cv.response')}
            dataTooltipId={'customHealthSourceQuery'}
          />
        ) : (
          <>
            <Button
              intent="primary"
              text={getString('cv.monitoringSources.gcoLogs.fetchRecords')}
              onClick={fetchRecords}
              disabled={sampleDataLoading}
            />
            <Records
              fetchRecords={fetchRecords}
              loading={sampleDataLoading}
              data={[recordsData]}
              error={sampleDataError}
              query={''}
              isQueryExecuted={isQueryExecuted}
              queryNotExecutedMessage={getString('cv.customHealthSource.fetchRecordsButton')}
            />
          </>
        )}
      </Container>
    </Container>
  )
}