All files / modules/75-ce/components/AccessPoint/GCPAccessPoint GCPAccessPointConfig.tsx

95.56% Statements 43/45
80% Branches 12/15
90% Functions 9/10
95.56% Lines 43/45

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              9x 9x 9x 9x 9x 9x 9x     9x 9x 9x 9x                     9x               9x 9x 9x   9x 9x 9x   9x   9x       9x       9x 1x     9x 2x     9x 1x 1x 1x 1x 1x                                               9x 2x               1x                           9x               9x 2x 2x     9x 9x     9x                     1x                                   9x  
/*
 * Copyright 2022 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 { defaultTo as _defaultTo } from 'lodash-es'
import { Heading, useToaster } from '@harness/uicore'
import { AccessPointFormStep, PROVIDER_TYPES } from '@ce/constants'
import { Utils } from '@ce/common/Utils'
import { AccessPoint, useCreateAccessPoint, useEditAccessPoint } from 'services/lw'
import type { AccessPointScreenMode } from '@ce/types'
import type { AccountPathProps } from '@common/interfaces/RouteInterfaces'
import { useStrings } from 'framework/strings'
import GCPDnsMapping, { GcpDnsFormVal } from './GCPDnsMapping'
import GCPAccessPointForm, { GcpApFormValue } from './GCPAccessPointForm'
import css from './GCPAccessPoint.module.scss'
 
interface GCPAccessPointConfigProps {
  loadBalancer: AccessPoint
  cloudAccountId: string | undefined
  onClose?: (clearSelection?: boolean) => void
  onSave: (savedLoadBalancer: AccessPoint) => void
  mode: AccessPointScreenMode
  step?: AccessPointFormStep
}
 
const GCPAccessPointConfig: React.FC<GCPAccessPointConfigProps> = ({
  loadBalancer,
  cloudAccountId,
  onClose,
  onSave,
  mode,
  step
}) => {
  const { getString } = useStrings()
  const { showError, showSuccess } = useToaster()
  const { accountId } = useParams<AccountPathProps>()
 
  const [currentStep, setCurrentStep] = useState<AccessPointFormStep>(_defaultTo(step, AccessPointFormStep.FIRST))
  const [lbCreationInProgress, setLbCreationInProgress] = useState<boolean>(false)
  const [newAp, setNewAp] = useState<AccessPoint>(loadBalancer)
 
  const isEditMode = mode === 'edit'
 
  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: GcpDnsFormVal) => {
    const updatedAp = { ...newAp }
    updatedAp.host_name = _values.customDomain
    updatedAp.name = _values.name
    setNewAp(updatedAp)
    moveForward()
  }
 
  /* istanbul ignore next */
  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')
        )
        onSave?.(result.response)
        onClose?.()
      }
    } catch (e) {
      setLbCreationInProgress(false)
      showError(e.data?.errors?.join('\n '))
    }
  }
 
  const getUpdatedApFromValues = (values: GcpApFormValue): AccessPoint => {
    return {
      ...newAp,
      region: values.region,
      vpc: values.vpc,
      metadata: {
        ...newAp.metadata,
        zone: values.zone,
        subnet_name: values.subnet_name,
        security_groups: values.securityGroups?.map(s => s.value) as string[],
        machine_type: values.machine_type,
        ...((values.cert_secret_id || values.key_secret_id) && {
          certificates: [
            {
              cert_secret_id: values.cert_secret_id,
              key_secret_id: values.key_secret_id
            }
          ]
        })
      }
    }
  }
 
  const handleFormSubmit = (val: AccessPoint) => {
    const lbToSave = {
      ...getUpdatedApFromValues(val),
      cloud_account_id: cloudAccountId
    }
    saveLb(lbToSave)
  }
 
  const handlePreviousClick = (values: GcpApFormValue) => {
    setNewAp(getUpdatedApFromValues(values))
    moveBackward()
  }
 
  const getHeading = () => {
    return Utils.getLoadBalancerModalHeader(mode, PROVIDER_TYPES.GCP, loadBalancer.name)
  }
 
  return (
    <div className={css.loadBalancerDnsConfigDialog}>
      <Heading level={2} className={css.configHeading}>
        {getHeading()}
      </Heading>
      <div>
        {currentStep === AccessPointFormStep.FIRST && (
          <GCPDnsMapping
            loadBalancer={newAp}
            handleSubmit={handleDnsMappingSubmission}
            mode={mode}
            handleCancel={() => onClose?.(true)}
          />
        )}
        {currentStep === AccessPointFormStep.SECOND && (
          <GCPAccessPointForm
            loadBalancer={newAp}
            cloudAccountId={cloudAccountId as string}
            handlePreviousClick={handlePreviousClick}
            isSaving={lbCreationInProgress}
            mode={mode}
            handleSubmit={handleFormSubmit}
          />
        )}
      </div>
    </div>
  )
}
 
export default GCPAccessPointConfig