All files / modules/40-gitsync/components/GitConnection GitConnection.tsx

82.46% Statements 47/57
58.82% Branches 20/34
54.55% Functions 6/11
82.46% Lines 47/57

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              5x 5x 5x 5x 5x 5x 5x 5x 5x 5x   5x 5x 5x 5x                     5x 5x 5x     5x 6x 6x 6x 6x 6x 6x 6x 6x   6x       6x         6x             6x 1x           1x 1x 1x 1x               6x 1x     6x 1x 1x 1x                         1x 1x                     1x   1x     6x                                                                                                                                                       5x  
/*
 * 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 } from 'react'
import cx from 'classnames'
import { useParams } from 'react-router-dom'
import { Radio } from '@blueprintjs/core'
import { Button, Card, Container, Layout, StepProps, Text } from '@wings-software/uicore'
import { defaultTo, pick } from 'lodash-es'
import { Color } from '@harness/design-system'
import { useStrings } from 'framework/strings'
import { GitSyncConfig, ResponseSaasGitDTO, useIsSaasGit, usePostGitSync, usePostGitSyncSetting } from 'services/cd-ng'
import { useToaster } from '@common/exports'
import type { ProjectPathProps } from '@common/interfaces/RouteInterfaces'
import DelegatesGit from '@gitsync/icons/DelegatesGit.svg'
import PlatformGit from '@gitsync/icons/PlatformGit.svg'
import useRBACError from '@rbac/utils/useRBACError/useRBACError'
import css from './GitConnection.module.scss'
 
interface GitConnectionStepProps {
  repo: string
}
 
interface GitConnectionProps {
  onSuccess: (data?: GitSyncConfig) => void
  isLastStep: boolean
}
 
enum Agent {
  Manager = 'Manager',
  Delegate = 'Delegate'
}
 
const GitConnection: React.FC<StepProps<GitConnectionStepProps> & GitConnectionProps> = props => {
  const { accountId, projectIdentifier, orgIdentifier } = useParams<ProjectPathProps>()
  const { getRBACErrorMessage } = useRBACError()
  const { prevStepData, onSuccess, isLastStep } = props
  const [isSaaS, setIsSaaS] = useState<boolean | undefined>()
  const [loading, setLoading] = useState<boolean>(true)
  const [agent, setAgent] = useState<Agent | undefined>()
  const { getString } = useStrings()
  const { showError, showSuccess } = useToaster()
 
  const { mutate: createGitSyncRepo } = usePostGitSync({
    queryParams: { accountIdentifier: accountId }
  })
 
  const { mutate: registerAgent } = usePostGitSyncSetting({
    queryParams: { accountIdentifier: accountId },
    requestOptions: { headers: { accept: 'application/json' } }
  })
 
  const { mutate: isSaasGit, loading: checkingIsSaasGit } = useIsSaasGit({
    queryParams: {},
    requestOptions: {
      headers: { 'content-type': 'application/json' }
    }
  })
 
  React.useEffect(() => {
    isSaasGit(undefined, {
      queryParams: {
        repoURL: encodeURIComponent(defaultTo(prevStepData?.repo, ''))
      }
    })
      .then((res: ResponseSaasGitDTO) => {
        const { saasGit } = defaultTo(res?.data, {})
        Eif (typeof saasGit !== 'undefined') {
          setAgent(saasGit ? Agent.Manager : Agent.Delegate)
          setIsSaaS(saasGit)
        }
      })
      .catch(e => {
        showError(getRBACErrorMessage(e))
      })
  }, [prevStepData?.repo])
 
  React.useEffect(() => {
    setLoading(checkingIsSaasGit)
  }, [checkingIsSaasGit])
 
  const onSubmit = async (): Promise<void> => {
    setLoading(true)
    try {
      const params = {
        ...pick(props.prevStepData as GitSyncConfig, [
          'gitConnectorType',
          'branch',
          'name',
          'identifier',
          'repo',
          'gitConnectorRef',
          'gitSyncFolderConfigDTOs',
          'projectIdentifier',
          'orgIdentifier'
        ])
      } as GitSyncConfig
      await createGitSyncRepo(params)
      const { status } = await registerAgent({
        projectIdentifier,
        orgIdentifier,
        executeOnDelegate: agent === Agent.Delegate
      })
      if (status === 'SUCCESS') {
        showSuccess(getString('gitsync.successfullySavedConnectivityMode'))
        onSuccess()
        props.nextStep?.(prevStepData)
      }
    } catch (e) {
      showError(getRBACErrorMessage(e))
    }
    setLoading(false)
  }
 
  return (
    <Layout.Vertical
      padding={{ top: 'huge', bottom: 'xxlarge', left: 'xxlarge', right: 'xxlarge' }}
      spacing="huge"
      flex={{ alignItems: 'flex-start', justifyContent: 'space-between' }}
      style={{ minHeight: '720px' }}
    >
      <Container>
        <Text font={{ size: 'medium', weight: 'bold' }} color={Color.BLACK}>
          {getString('gitsync.connectToGitProvider')}
        </Text>
        <Layout.Horizontal spacing="xlarge" padding={{ top: 'large' }}>
          <Card
            disabled={!isSaaS}
            className={cx(css.card, { [css.selected]: agent === Agent.Manager })}
            onClick={() => {
              if (isSaaS) {
                setAgent(Agent.Manager)
              }
            }}
          >
            <Layout.Horizontal flex>
              <Text font={{ size: 'normal', weight: 'bold' }} padding={{ bottom: 'medium' }} color={Color.PRIMARY_6}>
                {getString('gitsync.connectThroughManagerLabel')}
              </Text>
              <Radio
                onClick={() => setAgent(Agent.Manager)}
                checked={agent === Agent.Manager}
                disabled={loading || !isSaaS}
              />
            </Layout.Horizontal>
            <Text font="small" style={{ lineHeight: 'var(--spacing-large' }}>
              {getString('gitsync.connectThroughManager')}
            </Text>
            <img src={PlatformGit} width="100%" className={css.img} />
          </Card>
          <Card
            disabled={loading}
            className={cx(css.card, { [css.selected]: agent === Agent.Delegate })}
            onClick={() => setAgent(Agent.Delegate)}
          >
            <Layout.Horizontal flex>
              <Text font={{ size: 'normal', weight: 'bold' }} padding={{ bottom: 'medium' }} color={Color.PRIMARY_6}>
                {getString('gitsync.connectThroughDelegateLabel')}
              </Text>
              <Radio
                onClick={() => setAgent(Agent.Delegate)}
                checked={!isSaaS || agent === Agent.Delegate}
                disabled={loading}
              />
            </Layout.Horizontal>
            <Text font="small" padding={{ bottom: 'huge' }} style={{ lineHeight: 'var(--spacing-large' }}>
              {getString('gitsync.connectThroughDelegate')}
            </Text>
            <img src={DelegatesGit} width="100%" className={css.img} />
          </Card>
        </Layout.Horizontal>
        {/* <Layout.Horizontal padding={{ top: 'xxlarge' }} spacing="small">
          <Icon name="info" size={16} />
          <Link to={'/'}>{getString('gitsync.learnMore')}</Link>
        </Layout.Horizontal> */}
      </Container>
      <Layout.Horizontal className={css.btnWrapper}>
        <Button
          type="submit"
          intent="primary"
          text={isLastStep ? getString('save') : getString('saveAndContinue')}
          rightIcon="chevron-right"
          disabled={loading || !agent}
          onClick={onSubmit}
        />
      </Layout.Horizontal>
    </Layout.Vertical>
  )
}
 
export default GitConnection