All files / modules/75-ce/components/COAccessPointList AzureAPConfig.tsx

73.21% Statements 41/56
12.77% Branches 6/47
45.45% Functions 5/11
74.55% Lines 41/55

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              9x 9x 9x 9x   9x 9x   9x 9x 9x 9x 9x                   9x 9x 9x     9x 4x 4x   4x 4x 4x 4x   4x   4x           4x       4x       4x 1x     4x       4x 1x 1x 1x 1x 1x     4x                                       4x                                             4x                                             4x 4x     4x                                                           9x  
/*
 * 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 { useParams } from 'react-router-dom'
import { Heading } from '@wings-software/uicore'
import { AccessPoint, useCreateAccessPoint, useEditAccessPoint } from 'services/lw'
// import { useStrings } from 'framework/strings'
import { useToaster } from '@common/exports'
import { Utils } from '@ce/common/Utils'
import type { AccessPointScreenMode } from '@ce/types'
import { PROVIDER_TYPES } from '@ce/constants'
import { useStrings } from 'framework/strings'
import AzureAccessPointForm, { AzureApFormVal } from './AzureAccessPointForm'
import AzureApDnsMapping, { AzureDnsFormVal } from './AzureDnsMapping'
import css from '../COGatewayAccess/COGatewayAccess.module.scss'
 
interface AzureAPConfigProps {
  loadBalancer: AccessPoint
  cloudAccountId: string | undefined
  onClose?: (clearSelection?: boolean) => void
  onSave: (savedLoadBalancer: AccessPoint) => void
  mode: AccessPointScreenMode
}
 
enum FormStep {
  FIRST = 1,
  SECOND = 2
}
 
const AzureAPConfig: React.FC<AzureAPConfigProps> = props => {
  const { loadBalancer, cloudAccountId, mode, onSave } = props
  const isEditMode = mode === 'edit'
 
  const { getString } = useStrings()
  const { showError, showSuccess } = useToaster()
  const [currentStep, setCurrentStep] = useState<FormStep>(FormStep.FIRST)
  const [newAp, setNewAp] = useState<AccessPoint>(loadBalancer)
  // const [loadBalancerId, setLoadBalancerId] = useState<string>()
  const [lbCreationInProgress, setLbCreationInProgress] = useState<boolean>(false)
 
  const { accountId, orgIdentifier, projectIdentifier } = useParams<{
    orgIdentifier: string
    projectIdentifier: string
    accountId: string
  }>()
 
  const { mutate: createLoadBalancer } = useCreateAccessPoint({
    account_id: accountId
  })
 
  const { mutate: editLoadBalancer } = useEditAccessPoint({
    account_id: accountId
  })
 
  const moveForward = () => {
    setCurrentStep(currentStep + 1)
  }
 
  const moveBackward = () => {
    setCurrentStep(currentStep - 1)
  }
 
  const handleDnsMappingSubmission = (_values: AzureDnsFormVal) => {
    const updatedAp = { ...newAp }
    updatedAp.host_name = _values.customDomain
    updatedAp.name = _values.name
    setNewAp(updatedAp)
    moveForward()
  }
 
  const saveLb = async (lbToSave: AccessPoint): Promise<void> => {
    setLbCreationInProgress(true)
    try {
      const result = isEditMode ? await editLoadBalancer(lbToSave) : await createLoadBalancer(lbToSave) // eslint-disable-line
      if (result.response) {
        // setLoadBalancerId(result.response.id as string)
        showSuccess(
          isEditMode
            ? getString('ce.co.accessPoint.successfulEdition', { name: result.response.name })
            : getString('ce.co.accessPoint.successfulCreation')
        )
        props.onSave?.(result.response)
        props.onClose?.()
      }
    } catch (e) {
      setLbCreationInProgress(false)
      showError(e.data?.errors?.join('\n') || e.data?.message || e.message, undefined, 'ce.savelb.error')
    }
  }
 
  const handleFormSubmit = (val: AzureApFormVal) => {
    saveLb({
      ...newAp,
      org_id: orgIdentifier,
      project_id: projectIdentifier,
      cloud_account_id: props.cloudAccountId,
      region: val.region,
      subnets: val.subnet ? [val.subnet] : [],
      vpc: val.virtualNetwork,
      metadata: {
        ...newAp.metadata,
        resource_group: val.resourceGroup,
        fe_ip_id: val.ip,
        size: val.sku,
        subnet_id: val.subnet,
        ...(val.newCertificate ? { certificate: val.newCertificate } : { certificate_id: val.certificate }),
        subnet_name: val.subnet_name,
        fe_ip_name: val.fe_ip_name,
        func_region: val.func_region
      }
    })
  }
 
  const handleBackClick = (values: AzureApFormVal) => {
    setNewAp(prevAp => ({
      ...prevAp,
      region: values.region,
      ...(values.subnet && {
        subnets: [values.subnet]
      }),
      vpc: values.virtualNetwork,
      metadata: {
        ...prevAp.metadata,
        resource_group: values.resourceGroup,
        fe_ip_id: values.ip,
        size: values.sku,
        subnet_id: values.subnet,
        ...(values.newCertificate ? { certificate: values.newCertificate } : { certificate_id: values.certificate }),
        subnet_name: values.subnet_name,
        fe_ip_name: values.fe_ip_name,
        func_region: values.func_region
      }
    }))
    moveBackward()
  }
 
  const getHeading = () => {
    return Utils.getLoadBalancerModalHeader(props.mode, PROVIDER_TYPES.AZURE, loadBalancer.name)
  }
 
  return (
    <div className={css.loadBalancerDnsConfigDialog}>
      <Heading level={2} className={css.configHeading}>
        {getHeading()}
      </Heading>
      <div>
        {currentStep === FormStep.FIRST && (
          <AzureApDnsMapping
            mode={mode}
            handleSubmit={handleDnsMappingSubmission}
            loadBalancer={newAp}
            handleCancel={() => props.onClose?.(true)}
          />
        )}
        {currentStep === FormStep.SECOND && (
          <AzureAccessPointForm
            cloudAccountId={cloudAccountId as string}
            onSave={onSave}
            handlePreviousClick={handleBackClick}
            lbCreationInProgress={lbCreationInProgress}
            handleFormSubmit={handleFormSubmit}
            loadBalancer={newAp}
            mode={mode}
          />
        )}
      </div>
    </div>
  )
}
 
export default AzureAPConfig