All files / modules/75-cd/pages/gitops/NativeArgo/ProviderOverviewStep ProviderOverviewStep.tsx

91.78% Statements 67/73
67.86% Branches 57/84
80% Functions 8/10
91.78% Lines 67/73

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 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289              3x 3x                             3x 3x 3x 3x               3x 3x 3x 3x 3x   3x 3x 3x                   3x 37x 37x 37x         37x 37x 37x 37x   37x 37x 37x 37x 37x   37x     37x       37x 2x 2x   2x                           37x   37x         37x 2x           2x   2x                     2x 2x         37x 5x 5x 1x 1x   4x 4x 4x               3x   3x 1x 1x   2x 1x   1x               1x 1x       37x 37x 6x   31x                       37x                                 5x                                       65x 65x                                                                                                                                   3x  
/*
 * 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, { useRef, useState } from 'react'
import {
  Layout,
  Button,
  Formik,
  ModalErrorHandlerBinding,
  Text,
  Icon,
  ModalErrorHandler,
  FormikForm,
  FormInput,
  Container,
  ButtonVariation,
  shouldShowError
} from '@wings-software/uicore'
 
import { useParams } from 'react-router-dom'
import * as Yup from 'yup'
import { pick } from 'lodash-es'
import {
  GitOpsProvider,
  validateProviderIdentifierIsUniquePromise,
  Failure,
  useCreateGitOpsProvider,
  useUpdateGitOpsProvider,
  CreateGitOpsProviderQueryParams
} from 'services/cd-ng'
import { String, useStrings } from 'framework/strings'
import { NameIdDescriptionTags, PageSpinner, useToaster } from '@common/components'
import { saveCurrentStepData } from '@connectors/pages/connectors/utils/ConnectorUtils'
import { IdentifierSchema, NameSchema } from '@common/utils/Validation'
import useRBACError from '@rbac/utils/useRBACError/useRBACError'
import type { BaseProviderStepProps } from '../../types'
import aboutHarnessAdapterIllustration from '../../images/aboutHarnessAdapterIllustration.svg'
const aboutHarnessAdapterURL = `https://ngdocs.harness.io/article/ptlvh7c6z2-harness-argo-cd-git-ops-quickstart`
import css from './ProviderOverviewStep.module.scss'
 
export type ProviderOverviewStepProps = BaseProviderStepProps
 
type Params = {
  accountId: string
  projectIdentifier: string
  orgIdentifier: string
}
 
const ProviderOverviewStep: React.FC<ProviderOverviewStepProps> = props => {
  const { prevStepData, nextStep, provider } = props
  const { getRBACErrorMessage } = useRBACError()
  const { showSuccess, showError } = useToaster()
  const {
    accountId,
    projectIdentifier: projectIdentifierFromUrl,
    orgIdentifier: orgIdentifierFromUrl
  } = useParams<Params>()
  const projectIdentifier = provider ? provider.projectIdentifier : projectIdentifierFromUrl
  const orgIdentifier = provider ? provider.orgIdentifier : orgIdentifierFromUrl
  const [providerName, setProviderName] = useState(props?.provider?.name)
 
  const mounted = useRef(false)
  const [modalErrorHandler, setModalErrorHandler] = useState<ModalErrorHandlerBinding | undefined>()
  const [loading, setLoading] = useState(false)
  const isEdit = props.isEditMode
  const { getString } = useStrings()
 
  const { mutate: createConnector, loading: creating } = useCreateGitOpsProvider({
    queryParams: { accountIdentifier: accountId }
  })
  const { mutate: updateConnector, loading: updating } = useUpdateGitOpsProvider({
    queryParams: { accountIdentifier: accountId }
  })
 
  const handleCreateOrEdit = async (payload: GitOpsProvider): Promise<any> => {
    modalErrorHandler?.hide()
    const queryParams: CreateGitOpsProviderQueryParams = {}
 
    const response = props.isEditMode
      ? await updateConnector(payload, {
          queryParams: {
            ...queryParams
          }
        })
      : await createConnector(payload, { queryParams: queryParams })
 
    return {
      status: response.status,
      nextCallback: afterSuccessHandler.bind(null, response)
    }
  }
 
  const isSaveButtonDisabled = creating || updating
 
  const afterSuccessHandler = (response: any): void => {
    props.onUpdateMode?.(true)
    nextStep?.({ ...props.provider, ...response?.data })
  }
 
  const handleSave = (formData: GitOpsProvider): void => {
    const data: GitOpsProvider = {
      ...formData,
      projectIdentifier: projectIdentifier,
      orgIdentifier: orgIdentifier
    }
 
    setProviderName(formData.name)
 
    handleCreateOrEdit(data)
      .then(res => {
        if (res.status === 'SUCCESS') {
          props.isEditMode
            ? showSuccess(getString('cd.updatedSuccessfully'))
            : showSuccess(getString('cd.createdSuccessfully'))
 
          res.nextCallback?.()
        }
      })
      .catch(e => {
        Eif (shouldShowError(e)) {
          showError(getRBACErrorMessage(e))
        }
      })
  }
 
  const handleSubmit = async (formData: GitOpsProvider): Promise<void> => {
    mounted.current = true
    if (isEdit) {
      handleSave(formData)
      return
    }
    setLoading(true)
    try {
      const response = await validateProviderIdentifierIsUniquePromise({
        queryParams: {
          identifier: formData.identifier,
          accountIdentifier: accountId,
          orgIdentifier: orgIdentifier,
          projectIdentifier: projectIdentifier
        }
      })
      setLoading(false)
 
      if ('SUCCESS' !== response.status) {
        modalErrorHandler?.showDanger((response as Failure)?.message || '')
        return
      }
      if (response.data) {
        handleSave(formData)
      } else {
        modalErrorHandler?.showDanger(
          getString('cd.duplicateIdError', {
            providerName: formData.name,
            providerIdentifier: formData.identifier
          })
        )
      }
    } catch (error) {
      setLoading(false)
      modalErrorHandler?.showDanger(error.message)
    }
  }
 
  const getInitialValues = (): GitOpsProvider => {
    if (isEdit) {
      return pick(props.provider, ['name', 'identifier', 'description', 'tags', 'spec']) as GitOpsProvider
    } else {
      return {
        name: '',
        description: '',
        identifier: '',
        tags: {},
        spec: {
          type: 'CONNECTED_ARGO_PROVIDER'
        }
      }
    }
  }
 
  return (
    <>
      {creating || updating ? (
        <PageSpinner
          message={
            creating
              ? getString('cd.creating', { name: providerName })
              : getString('cd.updating', { name: providerName })
          }
        />
      ) : null}
 
      <Layout.Vertical spacing="xxlarge" className={css.stepContainer}>
        <div className={css.heading}>{getString('overview')}</div>
        <Container className={css.connectorForm}>
          <Formik<GitOpsProvider>
            onSubmit={formData => {
              handleSubmit(formData)
            }}
            enableReinitialize={true}
            formName={`GitOpsProviderStepForm${provider?.spec?.type}`}
            validationSchema={Yup.object().shape({
              name: NameSchema(),
              identifier: IdentifierSchema(),
              spec: Yup.object().shape({
                adapterUrl: Yup.string()
                  .trim()
                  .url('Please enter a valid Adapter URL')
                  .required('Please enter a valid Adapter URL')
              })
            })}
            initialValues={{
              ...getInitialValues(),
              ...prevStepData
            }}
          >
            {formikProps => {
              saveCurrentStepData(props.getCurrentStepData, formikProps.values)
              return (
                <FormikForm>
                  <Container className={css.mainContainer} style={{ minHeight: 460, maxHeight: 460 }}>
                    <ModalErrorHandler
                      bind={setModalErrorHandler}
                      style={{
                        maxWidth: '740px',
                        marginBottom: '20px',
                        borderRadius: '3px',
                        borderColor: 'transparent'
                      }}
                    />
                    <div className={css.contentContainer}>
                      <div className={css.formContainer}>
                        <NameIdDescriptionTags
                          className={css.formElm}
                          formikProps={formikProps}
                          identifierProps={{ inputName: 'name', isIdentifierEditable: !isEdit }}
                          tooltipProps={{
                            dataTooltipId: `GitOpsProviderStepFormNameIdDescriptionTags`
                          }}
                        />
 
                        <FormInput.Text className={css.adapterUrl} name="spec.adapterUrl" label={'Adapter URL'} />
                      </div>
 
                      <div className={css.aboutHarnessAdapterContainer}>
                        <Text className={css.aboutHarnessAdapterQuestion} margin={{ bottom: 'small' }}>
                          {getString('cd.whatIsHarnessAdapter')}
                        </Text>
                        <Text className={css.aboutHarnessAdapterAnswer} margin={{ top: 'small', bottom: 'small' }}>
                          {getString('cd.aboutHarnessAdapter')}
                        </Text>
 
                        <img src={aboutHarnessAdapterIllustration} className={css.aboutHarnessAdapterIllustration} />
 
                        <div className={css.aboutHarnessAdapterUrl}>
                          <Icon intent="primary" style={{ marginRight: '8px' }} size={16} name="info" />
 
                          <a href={aboutHarnessAdapterURL} rel="noreferrer" target="_blank">
                            {getString('cd.learnMoreAboutHarnessAdapter')}
                          </a>
                        </div>
                      </div>
                    </div>
                  </Container>
                  <Layout.Horizontal>
                    <Button
                      type="submit"
                      variation={ButtonVariation.PRIMARY}
                      rightIcon="chevron-right"
                      disabled={loading || isSaveButtonDisabled}
                    >
                      <String stringID="saveAndContinue" />
                    </Button>
                  </Layout.Horizontal>
                </FormikForm>
              )
            }}
          </Formik>
        </Container>
      </Layout.Vertical>
    </>
  )
}
 
export default ProviderOverviewStep