All files / modules/35-connectors/components/CreateConnector/NewRelicConnector CreateNewRelicConnector.tsx

95.45% Statements 42/44
77.5% Branches 31/40
75% Functions 6/8
95.45% Lines 42/44

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              219x 219x 219x 219x 219x 219x 219x   219x 219x 219x 219x   219x 219x 219x 219x     27x 27x                                                   11x 10x 10x 10x 10x       10x   10x 7x 1x 6x 1x 1x 1x   5x 5x 10x 10x         5x 3x   5x     10x                       4x       27x           1x                                                                           219x          
/*
 * 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, { useState, useMemo } from 'react'
import { Layout, Button, Text, FormInput, FormikForm, Container, SelectOption, Icon } from '@wings-software/uicore'
import { Formik } from 'formik'
import * as Yup from 'yup'
import { Color } from '@harness/design-system'
import { PopoverInteractionKind, Tooltip } from '@blueprintjs/core'
import { useToaster } from '@common/exports'
import type { ConnectorConfigDTO } from 'services/cd-ng'
import { useGetNewRelicEndPoints } from 'services/cv'
import { buildNewRelicPayload } from '@connectors/pages/connectors/utils/ConnectorUtils'
import { useStrings } from 'framework/strings'
import { cvConnectorHOC } from '../CommonCVConnector/CVConnectorHOC'
import type { ConnectionConfigProps } from '../CommonCVConnector/constants'
import { StepDetailsHeader } from '../CommonCVConnector/components/CredentialsStepHeader/CredentialsStepHeader'
import { initializeNewRelicConnector } from './utils'
import { ConnectorSecretField } from '../CommonCVConnector/components/ConnectorSecretField/ConnectorSecretField'
import css from './CreateNewRelicConnector.module.scss'
 
function AccountIdTooltip(): JSX.Element {
  const { getString } = useStrings()
  return (
    <Tooltip
      interactionKind={PopoverInteractionKind.HOVER}
      hoverCloseDelay={500}
      content={
        <>
          <Text style={{ display: 'inline-block', marginRight: 'var(--spacing-xsmall)' }} color={Color.GREY_350}>
            {getString('connectors.newRelic.accountIdTooltip')}
          </Text>
          <a
            target="_blank"
            rel="noreferrer"
            href={'https://docs.newrelic.com/docs/accounts/accounts-billing/account-setup/account-id/'}
            style={{ color: 'var(--primary-7)' }}
          >
            {getString('clickHere')}
          </a>
        </>
      }
    >
      <Icon name="info" size={12} />
    </Tooltip>
  )
}
 
function NewRelicConfigStep(props: ConnectionConfigProps): JSX.Element {
  const { nextStep, prevStepData, connectorInfo, isEditMode, accountId, projectIdentifier, orgIdentifier } = props
  const { getString } = useStrings()
  const { showError, clear } = useToaster()
  const { data: endPoints, error: endPointError, loading: loadingEndpoints } = useGetNewRelicEndPoints({})
  const [initialValues, setInitialValues] = useState(
    initializeNewRelicConnector({ prevStepData, accountId, projectIdentifier, orgIdentifier })
  )
 
  const initialSecretValue = initialValues.apiKeyRef?.referenceString || initialValues.apiKeyRef
 
  const endPointOptions = useMemo(() => {
    if (loadingEndpoints) {
      return [{ label: getString('loading'), value: '' }]
    } else if (endPointError?.message) {
      clear()
      showError(endPointError?.message)
      return []
    }
    const filteredPoints: SelectOption[] = []
    for (const endPoint of endPoints?.data || []) {
      Eif (endPoint) {
        filteredPoints.push({ label: endPoint, value: endPoint })
      }
    }
 
    // set default value
    if (!isEditMode && !initialValues.url) {
      setInitialValues({ ...initialValues, url: filteredPoints[0] })
    }
    return filteredPoints
  }, [endPoints, endPointError, loadingEndpoints])
 
  return (
    <Container className={css.credentials}>
      <StepDetailsHeader connectorTypeLabel={getString('connectors.newRelicLabel')} />
      <Formik
        enableReinitialize
        initialValues={{ ...initialValues }}
        validationSchema={Yup.object().shape({
          url: Yup.string().trim().required(getString('connectors.newRelic.urlValidation')),
          newRelicAccountId: Yup.string().trim().required(getString('connectors.newRelic.accountIdValidation')),
          apiKeyRef: Yup.string().trim().required(getString('connectors.encryptedAPIKeyValidation'))
        })}
        onSubmit={(formData: ConnectorConfigDTO) => {
          nextStep?.({ ...connectorInfo, ...prevStepData, ...formData })
        }}
      >
        {formikProps => (
          <FormikForm className={css.form}>
            <Layout.Vertical spacing="large" height={400}>
              <FormInput.Select
                placeholder={loadingEndpoints ? getString('loading') : undefined}
                items={endPointOptions}
                value={(formikProps.values as any).url}
                onChange={updatedOption => formikProps.setFieldValue('url', updatedOption)}
                label={getString('connectors.newRelic.urlFieldLabel')}
                name="url"
              />
              <FormInput.Text
                label={
                  <Container className={css.identifierLabel}>
                    <Text inline>{getString('connectors.newRelic.accountIdFieldLabel')}</Text>
                    <AccountIdTooltip />
                  </Container>
                }
                name="newRelicAccountId"
              />
              <ConnectorSecretField
                accountIdentifier={accountId}
                projectIdentifier={projectIdentifier}
                orgIdentifier={orgIdentifier}
                secretFieldValue={initialSecretValue}
                secretInputProps={{
                  label: getString('connectors.encryptedAPIKeyLabel'),
                  name: 'apiKeyRef'
                }}
                onSuccessfulFetch={result => {
                  formikProps.setFieldValue('apiKeyRef', result)
                }}
              />
            </Layout.Vertical>
            <Layout.Horizontal spacing="large">
              <Button onClick={() => props.previousStep?.({ ...props.prevStepData })} text={getString('back')} />
              <Button type="submit" text={getString('continue')} intent="primary" />
            </Layout.Horizontal>
          </FormikForm>
        )}
      </Formik>
    </Container>
  )
}
 
export default cvConnectorHOC({
  connectorType: 'NewRelic',
  ConnectorCredentialsStep: NewRelicConfigStep,
  buildSubmissionPayload: buildNewRelicPayload
})