All files / modules/35-connectors/components/CreateConnector/CEAzureConnector/Steps/Overview AzureConnectorOverview.tsx

88.24% Statements 75/85
69.3% Branches 79/114
100% Functions 11/11
87.95% Lines 73/83

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              219x 219x                       219x 219x 219x 219x 219x                   219x 219x 219x 219x 219x 219x 219x 219x 219x 219x     219x 48x 48x                                                           219x 16x 16x 16x 16x   16x   16x 16x 16x 16x   16x             16x 16x 16x 4x               16x 3x                 16x 4x   4x 4x                             4x                                 4x 4x 4x       4x 4x 1x 1x 1x 1x     3x 3x       3x 4x 3x             16x 16x 16x               16x 8x           16x               4x                                     36x                                                                                             219x 2x 2x 2x 2x   2x 2x         2x                                   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 } from 'react'
import {
  Layout,
  Button,
  Formik,
  StepProps,
  ModalErrorHandlerBinding,
  ModalErrorHandler,
  FormikForm,
  Container,
  Heading,
  FormInput
} from '@wings-software/uicore'
import { useParams } from 'react-router-dom'
import { isEmpty, pick, get, omit } from 'lodash-es'
import cx from 'classnames'
import * as Yup from 'yup'
import {
  Failure,
  ConnectorInfoDTO,
  ResponseBoolean,
  GetConnectorListV2QueryParams,
  useGetConnectorListV2,
  ConnectorFilterProperties,
  ConnectorResponse,
  CEAzureConnector
} from 'services/cd-ng'
import { String, useStrings } from 'framework/strings'
import { Description, Tags } from '@common/components/NameIdDescriptionTags/NameIdDescriptionTags'
import { useAppStore } from 'framework/AppStore/AppStoreContext'
import { GitSyncStoreProvider } from 'framework/GitRepoStore/GitSyncStoreContext'
import GitContextForm, { GitContextProps, IGitContextFormProps } from '@common/components/GitContextForm/GitContextForm'
import { IdentifierSchema, NameSchema } from '@common/utils/Validation'
import { CE_AZURE_CONNECTOR_CREATION_EVENTS } from '@connectors/trackingConstants'
import { useStepLoadTelemetry } from '@connectors/common/useTrackStepLoad/useStepLoadTelemetry'
import ShowConnectorError from '../ShowConnectorError'
import css from '../../CreateCeAzureConnector_new.module.scss'
 
export type DetailsForm = Pick<ConnectorInfoDTO, 'name' | 'identifier' | 'description' | 'tags'> & GitContextProps
export const guidRegex = (value: string) => {
  const regex = /^[{]?[0-9a-fA-F]{8}-([0-9a-fA-F]{4}-){3}[0-9a-fA-F]{12}[}]?$/
  return regex.test(value)
}
 
interface OverviewForm extends DetailsForm {
  tenantId: string
  subscriptionId: string
}
 
export interface CEAzureDTO extends ConnectorInfoDTO {
  spec: CEAzureConnector
  existingBillingExports?: CEAzureConnector[]
  hasBilling?: boolean
  isEditMode?: boolean
}
 
interface OverviewProps {
  type: ConnectorInfoDTO['type']
  name: string
  isEditMode?: boolean
  connectorInfo?: CEAzureDTO
  gitDetails?: IGitContextFormProps
  mock?: ResponseBoolean
}
 
type Params = {
  accountId: string
  projectIdentifier: string
  orgIdentifier: string
}
 
const Overview: React.FC<StepProps<CEAzureDTO> & OverviewProps> = props => {
  const [loading, setLoading] = useState(false)
  const [isUniqueConnector, setIsUniqueConnector] = useState(true)
  const [existingConnectorDetails, setExistingConnectorDetails] = useState<ConnectorResponse | undefined>()
  const [modalErrorHandler, setModalErrorHandler] = useState<ModalErrorHandlerBinding | undefined>()
 
  useStepLoadTelemetry(CE_AZURE_CONNECTOR_CREATION_EVENTS.LOAD_OVERVIEW_STEP)
 
  const { accountId } = useParams<Params>()
  const { isGitSyncEnabled } = useAppStore()
  const { getString } = useStrings()
  const { prevStepData, nextStep, isEditMode } = props
 
  const defaultQueryParams: GetConnectorListV2QueryParams = {
    pageIndex: 0,
    pageSize: 10,
    accountIdentifier: accountId,
    getDistinctFromBranches: false
  }
 
  const { mutate } = useGetConnectorListV2({ queryParams: defaultQueryParams })
  const filterParams: ConnectorFilterProperties = { types: ['CEAzure'], filterType: 'Connector' }
  const fetchConnectors = async (formData: OverviewForm) => {
    return mutate({
      ...filterParams,
      ccmConnectorFilter: {
        azureTenantId: formData.tenantId,
        azureSubscriptionId: formData.subscriptionId
      }
    })
  }
  const fetchConnectorsWithBillingExports = async (formData: OverviewForm) => {
    return mutate({
      ...filterParams,
      ccmConnectorFilter: {
        featuresEnabled: ['BILLING'],
        azureTenantId: formData.tenantId
      }
    })
  }
 
  const handleSubmit = async (formData: OverviewForm): Promise<void> => {
    setLoading(true)
 
    const hasBilling = !!props.connectorInfo?.spec?.featuresEnabled?.includes('BILLING')
    const nextStepData: CEAzureDTO = {
      ...props.connectorInfo,
      ...omit(formData, ['tenantId', 'subscriptionId']),
      type: props.type,
      spec: {
        ...props.connectorInfo?.spec,
        ...prevStepData?.spec,
        ...pick(formData, ['tenantId', 'subscriptionId'])
      },
      hasBilling,
      isEditMode
    }
 
    // if billing is already enabled,
    // the user is in Edit mode
    Iif (hasBilling) {
      nextStep?.(nextStepData)
      return
    }
 
    // Flow:
    //
    // Make a call and check if a connector already exists for
    // this tenantId and subscriptionId combination.
    //    - If yes, throw an error and suggest user to edit the
    //      exitising connector
    //    - If no, check if a connector with BILLING feature exists for
    //      this tenantId.
    //        - If yes, move onto the next step and show all the connectors
    //          which have BILLING enabled
    //        - If no, move onto the next step and allow user to create a
    //          new billing export
    try {
      const connectors = await fetchConnectors(formData)
      Iif ('SUCCESS' !== connectors.status) {
        throw connectors as Failure
      }
 
      const hasExistingConnector = !!connectors?.data?.pageItemCount
      if (hasExistingConnector && !isEditMode) {
        setIsUniqueConnector(false)
        setExistingConnectorDetails(connectors?.data?.content?.[0])
        setLoading(false)
        return
      }
 
      const response = await fetchConnectorsWithBillingExports(formData)
      Iif ('SUCCESS' !== response.status) {
        throw response as Failure
      }
 
      const cons = response.data?.content || []
      nextStepData.existingBillingExports = cons.map(c => c.connector?.spec as CEAzureConnector)
      nextStep?.(nextStepData)
    } catch (e) {
      setLoading(false)
      modalErrorHandler?.showDanger(e.message)
    }
  }
 
  const getInitialValues = () => {
    const conInfo = props.connectorInfo
    return {
      ...pick(conInfo, ['name', 'identifier', 'description', 'tags']),
      ...pick(prevStepData, ['name', 'identifier', 'description', 'tags']),
      tenantId: get(conInfo, 'spec.tenantId') || get(prevStepData, 'spec.tenantId'),
      subscriptionId: get(conInfo, 'spec.subscriptionId') || get(prevStepData, 'spec.subscriptionId')
    }
  }
 
  const resetExistingConnectorError = () => {
    Iif (!isUniqueConnector) {
      setIsUniqueConnector(true)
      setExistingConnectorDetails(undefined)
    }
  }
 
  return (
    <Layout.Vertical className={css.stepContainer}>
      <Heading level={2} className={css.header}>
        {getString('connectors.ceAzure.overview.heading')}
      </Heading>
      <ModalErrorHandler bind={setModalErrorHandler} />
      <Formik<OverviewForm>
        onSubmit={formData => {
          handleSubmit(formData)
        }}
        formName="connectorOverviewForm"
        validationSchema={Yup.object().shape({
          name: NameSchema(),
          identifier: IdentifierSchema(),
          tenantId: Yup.string()
            .required(getString('connectors.ceAzure.validation.tenantId'))
            .test('tenantId', getString('connectors.ceAzure.guidRegexError'), guidRegex),
          subscriptionId: Yup.string()
            .required(getString('connectors.ceAzure.validation.subscriptionId'))
            .test('subscriptionId', getString('connectors.ceAzure.guidRegexError'), guidRegex)
        })}
        initialValues={{
          ...(getInitialValues() as OverviewForm),
          ...prevStepData
        }}
      >
        {formikProps => {
          return (
            <FormikForm>
              <Container style={{ minHeight: 550 }}>
                <Container className={cx(css.main, css.dataFields)}>
                  <FormInput.InputWithIdentifier
                    inputLabel={getString('connectors.name')}
                    {...{ inputName: 'name', isIdentifierEditable: !isEditMode }}
                  />
                  <FormInput.Text
                    name={'tenantId'}
                    label={getString('connectors.ceAzure.overview.tenantId')}
                    placeholder={getString('connectors.ceAzure.guidPlaceholder')}
                    onChange={resetExistingConnectorError}
                  />
                  <FormInput.Text
                    name={'subscriptionId'}
                    label={getString('connectors.ceAzure.overview.subscriptionId')}
                    placeholder={getString('connectors.ceAzure.guidPlaceholder')}
                    onChange={resetExistingConnectorError}
                  />
                  <Description descriptionProps={{}} hasValue={!!formikProps?.values.description} />
                  <Tags tagsProps={{}} isOptional={true} hasValue={!isEmpty(formikProps?.values.tags)} />
                </Container>
                {isGitSyncEnabled && (
                  <GitSyncStoreProvider>
                    <GitContextForm
                      formikProps={formikProps}
                      gitDetails={props.gitDetails}
                      className={'gitDetailsContainer'}
                    />
                  </GitSyncStoreProvider>
                )}
                {!isUniqueConnector && <ExistingConnectorMessage {...existingConnectorDetails} />}
              </Container>
              <Layout.Horizontal>
                <Button type="submit" intent="primary" rightIcon="chevron-right" disabled={loading}>
                  <String stringID="continue" />
                </Button>
              </Layout.Horizontal>
            </FormikForm>
          )
        }}
      </Formik>
    </Layout.Vertical>
  )
}
 
const ExistingConnectorMessage = (props: ConnectorResponse) => {
  const { getString } = useStrings()
  const accountId = props.connector?.spec?.tenantId
  const featuresEnabled = [...(props.connector?.spec?.featuresEnabled || [])]
  const name = props.connector?.name
 
  let featureText = featuresEnabled.join(' and ')
  Iif (featuresEnabled.length > 2) {
    featuresEnabled.push(`and ${featuresEnabled.pop()}`)
    featureText = featuresEnabled.join(', ')
  }
 
  return (
    <ShowConnectorError
      title={getString('connectors.ceAzure.overview.alreadyExist')}
      reason={getString('connectors.ceAzure.overview.existingConnectorInfo', {
        accountId,
        name,
        featureText
      })}
      suggestion={
        <>
          {getString('connectors.ceAzure.overview.editConnector')} <a href="#">{name}</a>{' '}
          {getString('connectors.ceAzure.overview.required')}
        </>
      }
    />
  )
}
 
export default Overview
 
// ALL three features enabled
// TenantId:  b229b2bb-5f33-4d22-bce0-730f6474e906
// Sub: 20d6a917-99fa-4b1b-9b2e-a3d624e9dcf0
 
// ["OPTIMIZATION", "BILLING"]
// TenantId: b229b2bb-5f33-4d22-bce1-730f6474e906
// SubId: b229b2bb-5f33-4d22-bce2-730f6474e906