All files / modules/75-ce/components/COGatewayAccess LBFormStepSecond.tsx

79.12% Statements 72/91
70.92% Branches 100/141
72.73% Functions 16/22
78.65% Lines 70/89

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 315 316 317 318 319 320 321 322 323 324 325 326              9x 9x 9x 9x 9x 9x           9x   9x                                               9x             9x 18x 18x 18x   18x 18x 18x 18x 18x 18x 18x 18x   18x           18x                       18x                           18x                           18x                     18x 3x                   18x 3x       3x 3x         3x     18x 4x 3x 3x         18x 4x     18x 3x       3x 3x         3x     18x 18x 18x                       18x 3x       3x 3x         3x     18x                             2x 23x                 1x 1x 1x 1x 1x                           1x 1x 1x 1x                           1x 1x 1x 1x 1x                                                                                                                     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, { useEffect, useState } from 'react'
import { useParams } from 'react-router-dom'
import { isEmpty as _isEmpty } from 'lodash-es'
import { Menu } from '@blueprintjs/core'
import { Button, Formik, FormikForm, FormInput, Icon, Layout, SelectOption } from '@wings-software/uicore'
import { AccessPoint, useAllCertificates, useAllRegions, useAllSecurityGroups, useAllVPCs } from 'services/lw'
import type { AccessPointScreenMode } from '@ce/types'
// import {
//   ConnectorReferenceField,
//   ConnectorReferenceFieldProps
// } from '@connectors/components/ConnectorReferenceField/ConnectorReferenceField'
import { useStrings } from 'framework/strings'
// import { Scope } from '@common/interfaces/SecretsInterface'
import css from './COGatewayAccess.module.scss'
 
interface LBFormStepSecondProps {
  handleSubmit?: (values: FormValue) => void
  loadBalancer: AccessPoint
  cloudAccountId: string
  setNewLoadBalancer: (lbPayload: AccessPoint) => void
  handlePreviousClick: () => void
  isSaving: boolean
  mode: AccessPointScreenMode
}
 
export interface FormValue {
  //   cloudConnector?: {
  //     label?: string
  //     value?: string
  //     scope?: Scope
  //   }
  securityGroups?: Array<SelectOption>
  accessPointRegion?: string
  certificate?: string
  vpc?: string
}
 
const lbFieldToFormFieldMap: Record<string, keyof FormValue> = {
  'metadata.security_groups': 'securityGroups',
  'metadata.certificate_id': 'certificate',
  region: 'accessPointRegion',
  vpc: 'vpc'
}
 
const LBFormStepSecond: React.FC<LBFormStepSecondProps> = props => {
  const { handleSubmit, loadBalancer, cloudAccountId, setNewLoadBalancer, handlePreviousClick, isSaving, mode } = props
  const isEditMode = mode === 'edit' || !_isEmpty(loadBalancer.id)
  const { getString } = useStrings()
 
  const [regionOptions, setRegionOptions] = useState<SelectOption[]>([])
  const [vpcOptions, setvpcOptions] = useState<SelectOption[]>([])
  const [sgOptions, setSGOptions] = useState<SelectOption[]>([])
  const [certificateOptions, setCertificateOptions] = useState<SelectOption[]>([])
  const [selectedCloudAccount] = useState<string>(cloudAccountId)
  const [selectedRegion, setSelectedRegion] = useState<string>(loadBalancer.region as string)
  const [selectedVpc, setSelectedVpc] = useState<string | undefined>(loadBalancer.vpc as string)
  const [editableFieldsMap, setEditableFieldsMap] = useState<Record<string, boolean>>({})
 
  const { accountId } = useParams<{
    accountId: string
    orgIdentifier: string
    projectIdentifier: string
  }>()
 
  const { data: regions, loading: regionsLoading } = useAllRegions({
    account_id: accountId, // eslint-disable-line
    queryParams: {
      cloud_account_id: selectedCloudAccount, // eslint-disable-line
      accountIdentifier: accountId
    }
  })
 
  const {
    data: vpcs,
    loading: vpcsLoading,
    refetch: vpcsReload
  } = useAllVPCs({
    account_id: accountId, // eslint-disable-line
    queryParams: {
      region: selectedRegion,
      cloud_account_id: selectedCloudAccount, // eslint-disable-line
      accountIdentifier: accountId
    },
    lazy: true
  })
 
  const {
    data: certificates,
    loading: certificatesLoading,
    refetch: certificatesReload
  } = useAllCertificates({
    account_id: accountId, // eslint-disable-line
    queryParams: {
      cloud_account_id: selectedCloudAccount, // eslint-disable-line
      region: selectedRegion,
      accountIdentifier: accountId
    },
    lazy: true
  })
 
  const {
    data: securityGroups,
    loading: sgsLoading,
    refetch: sgsReload
  } = useAllSecurityGroups({
    account_id: accountId, // eslint-disable-line
    queryParams: {
      region: selectedRegion,
      vpc_id: selectedVpc as string, // eslint-disable-line
      cloud_account_id: selectedCloudAccount, // eslint-disable-line
      accountIdentifier: accountId
    },
    lazy: true
  })
 
  useEffect(() => {
    Iif (mode !== 'create') {
      const editMap: Record<string, boolean> = {}
      loadBalancer.editables?.forEach(field => {
        const key = lbFieldToFormFieldMap[field]
        editMap[key] = true
      })
      setEditableFieldsMap(editMap)
    }
  }, [])
 
  useEffect(() => {
    Iif (regions?.response?.length === 0) {
      return
    }
    const loaded: SelectOption[] =
      regions?.response?.map(r => {
        return {
          label: r.label as string,
          value: r.name as string
        }
      }) || []
    setRegionOptions(loaded)
  }, [regions])
 
  useEffect(() => {
    if (selectedRegion) {
      vpcsReload()
      certificatesReload()
      //   setAccessPointMeta('', [], '')
    }
  }, [selectedRegion])
 
  useEffect(() => {
    if (selectedVpc) sgsReload()
  }, [selectedVpc])
 
  useEffect(() => {
    Iif (vpcs?.response?.length === 0) {
      return
    }
    const loaded: SelectOption[] =
      vpcs?.response?.map(v => {
        return {
          label: v.name as string,
          value: v.id as string
        }
      }) || []
    setvpcOptions(loaded)
  }, [vpcs])
 
  useEffect(() => {
    Eif (securityGroups?.response?.length === 0) {
      return
    }
    const loaded: SelectOption[] =
      securityGroups?.response?.map(v => {
        return {
          label: v.name as string,
          value: v.id as string
        }
      }) || []
    setSGOptions(loaded)
  }, [securityGroups])
 
  useEffect(() => {
    Iif (certificates?.response?.length === 0) {
      return
    }
    const loaded: SelectOption[] =
      certificates?.response?.map(v => {
        return {
          label: v.name as string,
          value: v.id as string
        }
      }) || []
    setCertificateOptions(loaded)
  }, [certificates])
 
  return (
    <Formik<FormValue>
      initialValues={{
        vpc: loadBalancer.vpc,
        accessPointRegion: loadBalancer.region,
        securityGroups:
          loadBalancer.metadata?.security_groups?.map(x => {
            return {
              value: x,
              label: x
            }
          }) || [],
        certificate: loadBalancer.metadata?.certificate_id // eslint-disable-line
      }}
      formName="lbFormSecond"
      onSubmit={values => handleSubmit?.(values)}
      render={({ submitForm, setFieldValue }) => (
        <FormikForm>
          <Layout.Horizontal className={css.formFieldRow}>
            <FormInput.Select
              name="accessPointRegion"
              label={getString('ce.co.accessPoint.select.regionToInstall')}
              placeholder={getString('pipeline.regionPlaceholder')}
              items={regionOptions}
              onChange={e => {
                const updatedLb = { ...loadBalancer }
                updatedLb.region = e.value as string
                setNewLoadBalancer(updatedLb)
                setSelectedRegion(updatedLb.region as string)
                setFieldValue('accessPointRegion', e.value)
              }}
              //   disabled={regionsLoading || regionOptions.length == 0 || props.isEditMod}
              // TODO: replace it with original one above after testing
              disabled={
                isEditMode ? !editableFieldsMap['accessPointRegion'] : regionsLoading || regionOptions.length === 0
              }
            />
            <FormInput.Select
              name="certificate"
              label={getString('ce.co.accessPoint.select.aCertificate')}
              placeholder={getString('ce.co.accessPoint.select.certificate')}
              items={certificateOptions}
              onChange={e => {
                setFieldValue('certificate', e.value)
                const updatedLb = { ...loadBalancer }
                Eif (updatedLb.metadata) updatedLb.metadata.certificate_id = e.value as string // eslint-disable-line
                setNewLoadBalancer(updatedLb)
              }}
              disabled={
                isEditMode ? !editableFieldsMap['certificate'] : certificatesLoading || certificateOptions.length === 0
              }
            />
          </Layout.Horizontal>
          <Layout.Horizontal className={css.formFieldRow}>
            <FormInput.Select
              name="vpc"
              label={getString('ce.co.accessPoint.select.vpc')}
              placeholder={getString('ce.co.accessPoint.select.vpc')}
              items={vpcOptions}
              onChange={e => {
                setFieldValue('vpc', e.value)
                const updatedLb = { ...loadBalancer }
                updatedLb.vpc = e.value as string
                setNewLoadBalancer(updatedLb)
                setSelectedVpc(updatedLb.vpc)
              }}
              //   disabled={vpcsLoading || vpcOptions.length === 0 || props.isEditMod}
              // TODO: replace it with original one above after testing
              disabled={isEditMode ? !editableFieldsMap['vpc'] : vpcsLoading || vpcOptions.length === 0}
            />
            <FormInput.MultiSelect
              name="securityGroups"
              label={getString('ce.co.accessPoint.select.securityGroups')}
              placeholder={getString('ce.co.accessPoint.select.securityGroups')}
              multiSelectProps={{
                itemRender: (_item, { handleClick }) => (
                  <Menu.Item
                    key={_item.label}
                    style={{ whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis', padding: '5px 10px' }}
                    onClick={handleClick}
                    text={_item.label}
                  />
                )
              }}
              items={sgOptions}
              onChange={e => {
                setFieldValue('securityGroups', e)
                // eslint-disable-next-line
                const updatedLb = { ...loadBalancer }
                if (updatedLb.metadata) {
                  // eslint-disable-next-line
                  updatedLb.metadata.security_groups = e.map(x => {
                    return x.value as string
                  })
                  setNewLoadBalancer(updatedLb)
                }
              }}
              disabled={isEditMode ? !editableFieldsMap['securityGroups'] : sgsLoading || sgOptions.length === 0}
            />
          </Layout.Horizontal>
          <Layout.Horizontal style={{ marginTop: 220 }}>
            <Button
              text={'Back'}
              icon={'chevron-left'}
              onClick={handlePreviousClick}
              style={{ marginRight: 'var(--spacing-large)' }}
            ></Button>
            {isSaving && <Icon name="spinner" size={24} color="blue500" style={{ alignSelf: 'center' }} />}
            {!isSaving && (
              <Button
                intent="primary"
                text={'Save Load Balancer'}
                onClick={submitForm}
                disabled={!selectedRegion && !selectedVpc && _isEmpty(loadBalancer.metadata?.security_groups)}
              ></Button>
            )}
          </Layout.Horizontal>
        </FormikForm>
      )}
    ></Formik>
  )
}
 
export default LBFormStepSecond