All files / modules/35-connectors/components/CreateConnector/CENGAwsConnector/steps CrossAccountRoleStep2.tsx

88.31% Statements 68/77
76.64% Branches 105/137
83.33% Functions 10/12
89.47% Lines 68/76

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              220x 220x 220x 220x                             220x 220x 220x 220x 220x 220x 220x 220x     220x 220x   220x 8x   6x   6x     6x 6x 6x 6x     6x     6x     6x 6x   6x 1x     6x 2x 1x           6x 2x 1x     6x 6x 6x 6x   6x         6x 1x 1x 1x 1x     1x 1x     6x 1x 1x 1x 1x     1x 1x 1x     1x           1x 1x       1x 1x         1x     6x 1x 1x     6x                                   1x                                               1x       11x                                                                                                                             220x  
/*
 * 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, { useContext, useEffect, useState } from 'react'
import { useParams } from 'react-router-dom'
import * as Yup from 'yup'
import {
  Button,
  Container,
  Formik,
  FormikForm,
  FormInput,
  Heading,
  Layout,
  ModalErrorHandler,
  ModalErrorHandlerBinding,
  getErrorInfoFromErrorObject,
  StepProps,
  Icon,
  Text
} from '@wings-software/uicore'
import { pick } from 'lodash-es'
import { useStrings } from 'framework/strings'
import { CrossAccountAccess, useCreateConnector, useUpdateConnector, Failure } from 'services/cd-ng'
import { useAwsaccountconnectiondetail } from 'services/ce/index'
import LabelWithTooltip from '@connectors/common/LabelWithTooltip/LabelWithTooltip'
import { DialogExtensionContext } from '@connectors/common/ConnectorExtention/DialogExtention'
import { CE_AWS_CONNECTOR_CREATION_EVENTS } from '@connectors/trackingConstants'
import { useStepLoadTelemetry } from '@connectors/common/useTrackStepLoad/useStepLoadTelemetry'
import type { FeaturesString } from './CrossAccountRoleStep1'
import type { CEAwsConnectorDTO } from './OverviewStep'
import CrossAccountRoleExtension from './CrossAccountRoleExtension'
import css from '../CreateCeAwsConnector.module.scss'
 
const CrossAccountRoleStep2: React.FC<StepProps<CEAwsConnectorDTO>> = props => {
  const { getString } = useStrings()
 
  useStepLoadTelemetry(CE_AWS_CONNECTOR_CREATION_EVENTS.LOAD_CREATE_CROSS_ACCOUNT_ROLE)
 
  const { accountId } = useParams<{
    accountId: string
  }>()
  const { prevStepData, nextStep, previousStep } = props
  const { triggerExtension, closeExtension } = useContext(DialogExtensionContext)
  const [externalId, setExternalId] = useState<string>('')
  const { mutate: createConnector } = useCreateConnector({
    queryParams: { accountIdentifier: accountId }
  })
  const { mutate: updateConnector } = useUpdateConnector({
    queryParams: { accountIdentifier: accountId }
  })
  const { data: awsUrlTemplateData, loading: awsUrlTemplateLoading } = useAwsaccountconnectiondetail({
    queryParams: { accountIdentifier: accountId }
  })
  const [modalErrorHandler, setModalErrorHandler] = useState<ModalErrorHandlerBinding | undefined>()
  const [isSubmitLoading, setIsSubmitLoading] = useState<boolean>(false)
 
  const randomString = (): string => {
    return Math.random().toString(36).substring(2, 8) + Math.random().toString(36).substring(2, 8)
  }
 
  useEffect(() => {
    if (awsUrlTemplateData?.status == 'SUCCESS') {
      triggerExtension(
        <CrossAccountRoleExtension previewTemplateLink={awsUrlTemplateData?.data?.cloudFormationTemplateLink} />
      )
    }
  }, [awsUrlTemplateLoading])
 
  useEffect(() => {
    if (awsUrlTemplateData?.status == 'SUCCESS' && !prevStepData?.isEditMode)
      setExternalId(awsUrlTemplateData?.data?.externalId || '')
  }, [awsUrlTemplateLoading])
 
  const featuresEnabled: FeaturesString[] = prevStepData?.spec?.featuresEnabled || []
  const curStatus = featuresEnabled.includes('BILLING')
  const visibiltyStatus = featuresEnabled.includes('VISIBILITY')
  const optimizationStatus = featuresEnabled.includes('OPTIMIZATION')
 
  const getRoleName = (roleArn: string) => {
    if (roleArn == undefined) return
    return roleArn.split('/')[1]
  }
 
  const makeTemplateUrl = () => {
    const baseurl = awsUrlTemplateData?.data?.stackLaunchTemplateLink
    const bucketName = prevStepData?.spec?.curAttributes?.s3BucketName || ''
    const rand = randomString()
    const roleName = prevStepData?.isEditMode
      ? getRoleName(prevStepData?.spec.crossAccountAccess.crossAccountRoleArn)
      : `HarnessCERole-${rand}`
    const url = `${baseurl}&param_ExternalId=${externalId}&param_BucketName=${bucketName}&param_BillingEnabled=${curStatus}&param_EventsEnabled=${visibiltyStatus}&param_OptimizationEnabled=${optimizationStatus}&param_RoleName=${roleName}`
    window.open(url)
  }
 
  const handleSubmit = async (formData: CrossAccountAccess) => {
    setIsSubmitLoading(true)
    const newspec = { ...prevStepData?.spec, crossAccountAccess: formData }
    Eif (prevStepData) {
      prevStepData.spec = newspec
    }
 
    try {
      Eif (prevStepData) {
        const connectorInfo: CEAwsConnectorDTO = {
          ...pick(prevStepData, ['name', 'identifier', 'description', 'tags', 'spec', 'type'])
        }
        Iif (prevStepData.isEditMode) {
          const response = await updateConnector({ connector: connectorInfo })
          if (response.status != 'SUCCESS') {
            throw response as Failure
          }
        } else {
          const response = await createConnector({ connector: connectorInfo })
          Iif (response.status != 'SUCCESS') {
            throw response as Failure
          }
        }
        closeExtension()
        nextStep?.(prevStepData)
      }
    } catch (e) {
      modalErrorHandler?.showDanger(getErrorInfoFromErrorObject(e))
    }
    setIsSubmitLoading(false)
  }
 
  const handleprev = () => {
    closeExtension()
    previousStep?.({ ...(prevStepData as CEAwsConnectorDTO) })
  }
 
  return (
    <Layout.Vertical className={css.stepContainer}>
      <Heading level={2} className={css.header}>
        {getString('connectors.ceAws.crossAccountRoleStep2.heading')}
        <span>{getString('connectors.ceAws.crossAccountRoleStep2.createRole')}</span>
      </Heading>
      <div style={{ marginBottom: 25 }} className={css.infobox}>
        {getString('connectors.ceAws.crossAccountRoleStep2.subHeading')}
      </div>
      <Container style={{ paddingBottom: 40 }}>
        <Layout.Vertical style={{ width: '65%' }}>
          <Button
            className={css.launchTemplateBut}
            text={getString('connectors.ceAws.crossAccountRoleStep2.launchTemplate')}
            icon="main-share"
            iconProps={{ size: 12, margin: { right: 'xsmall' } }}
            disabled={awsUrlTemplateLoading}
            onClick={() => {
              makeTemplateUrl()
            }}
          />
          <Text font="small" style={{ textAlign: 'center' }}>
            {getString('connectors.ceAws.crossAccountRoleStep2.followInstructions')}
          </Text>
        </Layout.Vertical>
      </Container>
      <div style={{ flex: 1 }}>
        <Formik<CrossAccountAccess>
          formName="crossAccountRoleStep2Form"
          initialValues={{
            crossAccountRoleArn: prevStepData?.spec.crossAccountAccess.crossAccountRoleArn || '',
            externalId: prevStepData?.spec.crossAccountAccess.externalId || externalId || ''
          }}
          validationSchema={Yup.object().shape({
            crossAccountRoleArn: Yup.string()
              .matches(
                /arn:aws:iam::[0-9]*:role\/[^$%!&*?><\s]*/,
                getString('connectors.ceAws.crossAccountRoleStep2.validation.roleArnPattern')
              )
              .required(getString('connectors.ceAws.crossAccountRoleStep2.validation.roleArnRequired'))
          })}
          onSubmit={formData => {
            handleSubmit(formData)
          }}
          enableReinitialize={true}
        >
          {() => (
            <FormikForm>
              <ModalErrorHandler bind={setModalErrorHandler} />
              <Container className={css.main}>
                <FormInput.Text
                  name="crossAccountRoleArn"
                  label={
                    <LabelWithTooltip
                      label={getString('connectors.ceAws.crossAccountRoleStep2.roleArn')}
                      extentionComponent={
                        <CrossAccountRoleExtension
                          previewTemplateLink={awsUrlTemplateData?.data?.cloudFormationTemplateLink}
                        />
                      }
                    />
                  }
                  className={css.dataFields}
                />
 
                <FormInput.Text
                  name="externalId"
                  label={
                    <LabelWithTooltip
                      label={getString('connectors.ceAws.crossAccountRoleStep2.extId')}
                      extentionComponent={
                        <CrossAccountRoleExtension
                          previewTemplateLink={awsUrlTemplateData?.data?.cloudFormationTemplateLink}
                        />
                      }
                    />
                  }
                  onChange={(e: React.ChangeEvent<HTMLInputElement>) => {
                    setExternalId(e.target.value)
                  }}
                  disabled={awsUrlTemplateLoading}
                  className={css.dataFields}
                />
              </Container>
              <a>{getString('connectors.ceAws.crossAccountRoleStep2.dontHaveAccess')}</a>
              <Layout.Horizontal className={css.buttonPanel} spacing="small">
                <Button
                  text={getString('previous')}
                  icon="chevron-left"
                  onClick={handleprev}
                  disabled={isSubmitLoading}
                ></Button>
                <Button
                  type="submit"
                  intent="primary"
                  text={getString('saveAndContinue')}
                  rightIcon="chevron-right"
                  disabled={isSubmitLoading}
                />
                {isSubmitLoading && <Icon name="spinner" size={24} color="blue500" />}
              </Layout.Horizontal>
            </FormikForm>
          )}
        </Formik>
      </div>
    </Layout.Vertical>
  )
}
 
export default CrossAccountRoleStep2