All files / modules/35-user-profile/modals/SourceCodeManager/views SourceCodeManagerForm.tsx

70.59% Statements 60/85
56.58% Branches 43/76
66.67% Functions 10/15
70.24% Lines 59/84

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 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370              2x 2x 2x 2x                               2x 2x   2x 2x   2x   2x 2x                     2x 2x   2x 2x                                                 10x   2x 12x 10x 10x 8x   2x             6x                                                                                                               10x     2x 11x 9x 9x 9x   9x 9x 9x 9x 9x   9x 9x   9x               9x 7x             9x       9x 4x 1x 1x 1x           9x               9x                   9x                       9x                               9x 9x   9x           9x                           10x                                                                                 10x                             12x                                                   1x 1x                                           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, { useEffect, useState } from 'react'
import { useParams } from 'react-router-dom'
import { isEmpty } from 'lodash-es'
import {
  Button,
  Formik,
  FormikForm as Form,
  Layout,
  Text,
  FormInput,
  CardSelect,
  CardBody,
  Container,
  SelectOption,
  ModalErrorHandler,
  ModalErrorHandlerBinding,
  ButtonVariation,
  useToaster
} from '@wings-software/uicore'
import * as Yup from 'yup'
import { Color } from '@harness/design-system'
import type { FormikProps } from 'formik'
import { useStrings } from 'framework/strings'
import { NameSchema } from '@common/utils/Validation'
import type { AccountPathProps } from '@common/interfaces/RouteInterfaces'
import { PageSpinner } from '@common/components'
import type { SecretReference } from '@secrets/components/CreateOrSelectSecret/CreateOrSelectSecret'
import { SourceCodeManagerDTO, useSaveSourceCodeManagers, useUpdateSourceCodeManagers } from 'services/cd-ng'
import {
  AuthTypes,
  getAuthentication,
  getDefaultSCMType,
  getDefaultSelected,
  getFormDataBasedOnSCMType,
  getIconBySCM,
  SourceCodeType,
  SourceCodeTypes
} from '@user-profile/utils/utils'
import type { TextReferenceInterface } from '@secrets/components/TextReference/TextReference'
import { FeatureFlag } from '@common/featureFlags'
import { useFeatureFlag } from '@common/hooks/useFeatureFlag'
 
import Authentication from './Authentication'
import css from '../useSourceCodeManager.module.scss'
 
export interface RenderAuthSectionProps {
  selected?: SourceCodeType
  formikProps: FormikProps<SCMData>
}
 
interface SourceCodeManagerProps {
  onSubmit: () => void
  onClose: () => void
  initialValues?: SourceCodeManagerDTO
}
 
export interface SCMData {
  name: string
  authType?: AuthTypes
  username?: TextReferenceInterface
  password?: SecretReference
  sshKey?: SecretReference
  kerberosKey?: SecretReference
  accessToken?: SecretReference
  accessKey?: TextReferenceInterface
  secretKey?: SecretReference
}
 
const allowSCMChange = (isEditMode: boolean, selected?: string): boolean => Boolean(selected) && !isEditMode
 
const RenderAuthSection: React.FC<RenderAuthSectionProps> = props => {
  const { selected, formikProps } = props
  const { getString } = useStrings()
  const getAuthOptions = (type?: SourceCodeTypes): SelectOption[] => {
    switch (type) {
      case SourceCodeTypes.BITBUCKET:
        return [
          {
            label: getString('usernamePassword'),
            value: AuthTypes.USERNAME_PASSWORD
          }
        ]
      case SourceCodeTypes.GITHUB:
        return [
          // {
          //   label: getString('usernamePassword'),
          //   value: AuthTypes.USERNAME_PASSWORD
          // },
          {
            label: getString('usernameToken'),
            value: AuthTypes.USERNAME_TOKEN
          }
        ]
      case SourceCodeTypes.GITLAB:
        return [
          {
            label: getString('usernamePassword'),
            value: AuthTypes.USERNAME_PASSWORD
          },
          {
            label: getString('usernameToken'),
            value: AuthTypes.USERNAME_TOKEN
          },
          {
            label: getString('kerberos'),
            value: AuthTypes.KERBEROS
          },
          {
            label: getString('SSH_KEY'),
            value: AuthTypes.SSH_KEY
          }
        ]
      case SourceCodeTypes.AWS_CODE_COMMIT:
        return [
          {
            label: getString('userProfile.awsCredentials'),
            value: AuthTypes.AWSCredentials
          }
        ]
      case SourceCodeTypes.AZURE_DEV_OPS:
        return [
          {
            label: getString('usernamePassword'),
            value: AuthTypes.USERNAME_PASSWORD
          },
          {
            label: getString('usernameToken'),
            value: AuthTypes.USERNAME_TOKEN
          },
          {
            label: getString('SSH_KEY'),
            value: AuthTypes.SSH_KEY
          }
        ]
      default:
        return []
    }
  }
 
  return selected ? <Authentication formikProps={formikProps} authOptions={getAuthOptions(selected?.value)} /> : null
}
 
const SourceCodeManagerForm: React.FC<SourceCodeManagerProps> = props => {
  const { onSubmit, onClose, initialValues } = props
  const { getString } = useStrings()
  const { showError, showSuccess } = useToaster()
  const bitBucketSupported = useFeatureFlag(FeatureFlag.GIT_SYNC_WITH_BITBUCKET)
 
  const [modalErrorHandler, setModalErrorHandler] = useState<ModalErrorHandlerBinding>()
  const { accountId } = useParams<AccountPathProps>()
  const [data, setData] = useState({})
  const isEditMode = !isEmpty(initialValues)
  const [loading, setLoading] = useState(isEditMode)
 
  const { mutate: saveSourceCodeManager } = useSaveSourceCodeManagers({})
  const { mutate: updateSourceCodeManage } = useUpdateSourceCodeManagers({ identifier: initialValues?.id as string })
 
  const sourceCodeManagers: SourceCodeType[] = [
    {
      text: getString('common.repo_provider.githubLabel'),
      value: SourceCodeTypes.GITHUB,
      icon: getIconBySCM(SourceCodeTypes.GITHUB)
    }
  ]
 
  if (bitBucketSupported) {
    sourceCodeManagers.push({
      text: getString('common.repo_provider.bitbucketLabel'),
      value: SourceCodeTypes.BITBUCKET,
      icon: getIconBySCM(SourceCodeTypes.BITBUCKET)
    })
  }
 
  const [selected, setSelected] = useState<SourceCodeType | undefined>(
    getDefaultSCMType(sourceCodeManagers, initialValues?.type)
  )
 
  useEffect(() => {
    if (loading && initialValues) {
      getFormDataBasedOnSCMType(initialValues, accountId).then(formData => {
        formData && setData(formData)
        setLoading(false)
      })
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [loading])
 
  const selectedValueToTypeMap: Record<SourceCodeTypes, SourceCodeTypes> = {
    [SourceCodeTypes.BITBUCKET]: SourceCodeTypes.BITBUCKET,
    [SourceCodeTypes.GITHUB]: SourceCodeTypes.GITHUB,
    [SourceCodeTypes.GITLAB]: SourceCodeTypes.GITLAB,
    [SourceCodeTypes.AWS_CODE_COMMIT]: SourceCodeTypes.AWS_CODE_COMMIT,
    [SourceCodeTypes.AZURE_DEV_OPS]: SourceCodeTypes.AZURE_DEV_OPS
  }
 
  const handleCreate = async (dataToSubmit: SourceCodeManagerDTO): Promise<void> => {
    const saved = await saveSourceCodeManager(dataToSubmit)
    if (saved) {
      onSubmit()
      showSuccess(getString('userProfile.scmCreateSuccess'))
    } else {
      showError(getString('userProfile.scmCreateFail'))
    }
  }
 
  const handleUpdate = async (dataToSubmit: SourceCodeManagerDTO): Promise<void> => {
    const parsedDataToSubmit: SourceCodeManagerDTO = { ...dataToSubmit, userIdentifier: initialValues?.userIdentifier }
 
    const saved = await updateSourceCodeManage(parsedDataToSubmit)
    if (saved) {
      onSubmit()
      showSuccess(getString('userProfile.scmUpdateSuccess'))
    } else {
      showError(getString('userProfile.scmUpdateFail'))
    }
  }
 
  const handleSubmit = async (values: SCMData): Promise<void> => {
    if (!selected?.value) {
      modalErrorHandler?.showDanger(getString('userProfile.selectSCM'))
      return
    }
 
    const dataToSubmit: SourceCodeManagerDTO = {
      name: values.name,
      authentication: getAuthentication(values),
      accountIdentifier: accountId,
      type: selectedValueToTypeMap[selected.value]
    }
 
    isEditMode ? handleUpdate(dataToSubmit) : handleCreate(dataToSubmit)
  }
 
  const submitText = isEditMode ? getString('update') : getString('add')
  const availableSCMs = selected ? [selected] : sourceCodeManagers
 
  const formInitialValues = {
    name: '',
    ...{ authType: getDefaultSelected(selected?.value) },
    ...data
  }
 
  return loading ? (
    <PageSpinner />
  ) : (
    <Layout.Vertical padding="xxxlarge">
      <Layout.Vertical spacing="large">
        <Text color={Color.GREY_900} font={{ size: 'medium', weight: 'semi-bold' }}>
          {getString('userProfile.addSCM')}
        </Text>
        <Formik<SCMData>
          initialValues={formInitialValues}
          formName="sourceCodeManagerForm"
          validationSchema={Yup.object().shape({
            name: NameSchema(),
            username: Yup.string().when(['authType'], {
              is: authType => authType === AuthTypes.USERNAME_PASSWORD || authType === AuthTypes.USERNAME_TOKEN,
              then: Yup.string().trim().required(getString('validation.username')),
              otherwise: Yup.string().nullable()
            }),
            password: Yup.object().when(['authType'], {
              is: AuthTypes.USERNAME_PASSWORD,
              then: Yup.object().required(getString('validation.password')),
              otherwise: Yup.object().nullable()
            }),
            kerberosKey: Yup.object().when(['authType'], {
              is: AuthTypes.KERBEROS,
              then: Yup.object().required(getString('validation.kerberosKey')),
              otherwise: Yup.object().nullable()
            }),
            accessToken: Yup.object().when(['authType'], {
              is: AuthTypes.USERNAME_TOKEN,
              then: Yup.object().required(getString('validation.accessToken')),
              otherwise: Yup.object().nullable()
            }),
            sshKey: Yup.object().when(['authType'], {
              is: AuthTypes.SSH_KEY,
              then: Yup.object().required(getString('validation.sshKey')),
              otherwise: Yup.object().nullable()
            }),
            accessKey: Yup.string().when(['authType'], {
              is: AuthTypes.AWSCredentials,
              then: Yup.string().trim().required(getString('userProfile.scmValidation.accessKey')),
              otherwise: Yup.string().nullable()
            }),
            secretKey: Yup.object().when(['authType'], {
              is: AuthTypes.AWSCredentials,
              then: Yup.object().required(getString('userProfile.scmValidation.secretKey')),
              otherwise: Yup.object().nullable()
            })
          })}
          onSubmit={values => {
            modalErrorHandler?.hide()
            handleSubmit(values)
          }}
        >
          {formikProps => {
            return (
              <Form>
                <Layout.Vertical spacing="medium">
                  <ModalErrorHandler bind={setModalErrorHandler} />
                  <Container width={400}>
                    <FormInput.Text name="name" label={getString('name')} />
                  </Container>
                  <Text color={Color.BLACK}>{getString('userProfile.selectedSCM')}</Text>
                  <Layout.Horizontal spacing="medium" flex={{ alignItems: 'center', justifyContent: 'flex-start' }}>
                    <CardSelect
                      data={availableSCMs}
                      cornerSelected={true}
                      className={css.cardRow}
                      cardClassName={css.card}
                      renderItem={item => (
                        <CardBody.Icon icon={item.icon} iconSize={25}>
                          <Text
                            font={{
                              size: 'small',
                              align: 'center'
                            }}
                            flex={{ justifyContent: 'center' }}
                            color={Color.BLACK}
                          >
                            {item.text}
                          </Text>
                        </CardBody.Icon>
                      )}
                      onChange={value => {
                        setSelected(value)
                        modalErrorHandler?.hide()
                        formikProps.setFieldValue('authType', getDefaultSelected(value.value))
                      }}
                      selected={selected}
                    />
 
                    {allowSCMChange(isEditMode, selected?.value) ? (
                      <Button
                        text={getString('change')}
                        variation={ButtonVariation.LINK}
                        onClick={() => {
                          setSelected(undefined)
                          formikProps.setFieldValue('authType', null)
                        }}
                      />
                    ) : null}
                  </Layout.Horizontal>
                </Layout.Vertical>
 
                <RenderAuthSection selected={selected} formikProps={formikProps} />
 
                <Layout.Horizontal spacing="small" padding={{ top: 'huge' }}>
                  <Button variation={ButtonVariation.PRIMARY} text={submitText} type="submit" />
                  <Button text={getString('cancel')} onClick={onClose} variation={ButtonVariation.TERTIARY} />
                </Layout.Horizontal>
              </Form>
            )
          }}
        </Formik>
      </Layout.Vertical>
    </Layout.Vertical>
  )
}
 
export default SourceCodeManagerForm