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

49.59% Statements 60/121
45.92% Branches 90/196
40% Functions 12/30
52.17% Lines 60/115

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 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415              1x   1x 1x 1x                     1x       1x                 1x 1x 1x                       1x 4x         4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x   4x                     4x                 4x                         4x                         4x                     4x 2x       2x 2x         2x     4x 2x               4x 2x     4x 2x       2x 2x         2x     4x 4x 4x                       4x 2x       2x 2x         2x     4x 2x                     4x                             4x   4x                     4x                                                           4x                                                                                                                                                                                                                                                                                                     1x  
/*
 * 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 * as Yup from 'yup'
import {
  Layout,
  Button,
  Formik,
  FormikForm,
  FormInput,
  Heading,
  StepProps,
  SelectOption,
  Container
} from '@wings-software/uicore'
import {
  ConnectorReferenceField,
  ConnectorReferenceFieldProps
} from '@connectors/components/ConnectorReferenceField/ConnectorReferenceField'
import {
  AccessPoint,
  useAllCertificates,
  useAllRegions,
  useAllSecurityGroups,
  useAllVPCs,
  useAccessPointResources,
  ALBAccessPointCore
} from 'services/lw'
import { useStrings } from 'framework/strings'
import { Scope } from '@common/interfaces/SecretsInterface'
import css from './COGatewayAccess.module.scss'
 
interface Props extends StepProps<any> {
  name: string
  accessPoint: AccessPoint
  closeModal: () => void
  refreshAccessPoints: () => void
  setAccessPoint?: (ap: AccessPoint) => void
  isEditMod?: boolean
  isRuleCreationMode?: boolean
}
 
const CreateTunnelStep: React.FC<StepProps<any> & Props> = props => {
  const { accountId } = useParams<{
    accountId: string
    orgIdentifier: string
    projectIdentifier: string
  }>()
  const [accessPoint, setAccessPoint] = useState<AccessPoint>(props.accessPoint)
  const [regionOptions, setRegionOptions] = useState<SelectOption[]>([])
  const [vpcOptions, setvpcOptions] = useState<SelectOption[]>([])
  const [sgOptions, setSGOptions] = useState<SelectOption[]>([])
  const [certificateOptions, setCertificateOptions] = useState<SelectOption[]>([])
  const [selectedCloudAccount, setSelectedCloudAccount] = useState<string>(props.accessPoint.cloud_account_id as string)
  const [selectedRegion, setSelectedRegion] = useState<string>(props.accessPoint.region as string)
  const [selectedVpc, setSelectedVpc] = useState<string | undefined>(props.accessPoint.vpc as string)
  const [apCoreOptions, setApCoreOptions] = useState<SelectOption[]>([])
  const [selectedAPCore, setSelectedAPCore] = useState<string | undefined>()
  const [useExistingALB, setUseExistingALB] = useState<boolean>(false)
  const [createOrExisting, setCreateOrExisting] = useState<string>()
  const { getString } = useStrings()
  const { nextStep } = props
 
  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: apCoresResponse, refetch: apCoresReload } = useAccessPointResources({
    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 (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(() => {
    Iif (selectedRegion) {
      vpcsReload()
      certificatesReload()
      apCoresReload()
      setAccessPointMeta('', [], '')
    }
  }, [selectedRegion])
 
  useEffect(() => {
    Iif (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])
 
  useEffect(() => {
    Iif (apCoresResponse?.response?.length) {
      const apCores: SelectOption[] = apCoresResponse?.response
        .filter(core => !selectedVpc || (core.details as ALBAccessPointCore)?.vpc === selectedVpc)
        .map(core => ({
          label: core.details?.name as string,
          value: (core.details as ALBAccessPointCore)?.albARN as string
        }))
      setApCoreOptions(apCores)
    }
  }, [apCoresResponse])
 
  const setAccessPointMeta = (vpc: string | undefined, sg: string[] | undefined, albARN: string | undefined) => {
    const ap = props.accessPoint
    if (!props.isRuleCreationMode) {
      ap.vpc = vpc
      setSelectedVpc(vpc)
    }
    setSelectedAPCore(albARN)
    ap.metadata = {
      ...ap.metadata,
      security_groups: sg, // eslint-disable-line
      albArn: albARN
    }
    setAccessPoint(ap)
  }
 
  const clearAccessPointMeta = () => setAccessPointMeta(undefined, undefined, undefined)
 
  const onApCoreChange = (val: string) => {
    if (!val) return
    const core = apCoresResponse?.response?.find(c => (c.details as ALBAccessPointCore)?.albARN === val)
    if (!core) return
    setAccessPointMeta(
      (core.details as ALBAccessPointCore)?.vpc as string,
      (core.details as ALBAccessPointCore)?.security_groups || [],
      (core.details as ALBAccessPointCore)?.albARN as string
    )
  }
 
  return (
    <Layout.Vertical style={{ minHeight: '640px', width: '55%' }} padding="large" spacing="medium">
      <Heading level={2}>{props.name}</Heading>
      <Formik
        enableReinitialize
        formName="createAccessPt"
        initialValues={{
          cloudConnector: {
            label: '',
            value: accessPoint.cloud_account_id // eslint-disable-line
          },
          accessPointName: accessPoint.host_name,
          accessPointRegion: accessPoint.region,
          vpc: selectedVpc,
          securityGroups: accessPoint.metadata?.security_groups?.map(x => {
            return {
              value: x,
              label: x
            }
          }), // eslint-disable-line
          certificate: accessPoint.metadata?.certificate_id, // eslint-disable-line
          albSelector: createOrExisting,
          apCores: selectedAPCore
        }}
        onSubmit={_ => {
          nextStep?.({
            accessPoint: accessPoint
          })
        }}
        render={formik => (
          <FormikForm>
            <Layout.Vertical spacing="medium" height="640px">
              <FormInput.Text
                name="accessPointName"
                label={getString('ce.co.accessPoint.enterDomain')}
                placeholder={getString('ce.co.accessPoint.domainName')}
                onChange={(e: React.ChangeEvent<HTMLInputElement>) => {
                  props.accessPoint.host_name = e.target.value // eslint-disable-line
                  props.accessPoint.name = e.target.value // eslint-disable-line
                  setAccessPoint(props.accessPoint)
                  formik.setFieldValue('accessPointName', e.target.value)
                }}
                disabled={props.isEditMod}
              />
              {!props.isRuleCreationMode ? (
                <ConnectorReferenceField
                  name="cloudConnector"
                  placeholder={getString('ce.co.accessPoint.select.account')}
                  selected={accessPoint.cloud_account_id as ConnectorReferenceFieldProps['selected']} // eslint-disable-line
                  onChange={(record, scope) => {
                    props.accessPoint.cloud_account_id = record?.identifier // eslint-disable-line
                    setAccessPoint(props.accessPoint)
                    setSelectedCloudAccount(props.accessPoint.cloud_account_id as string) // eslint-disable-line
                    formik.setFieldValue('cloudConnector', {
                      label: record.name || '',
                      value: `${scope !== Scope.PROJECT ? `${scope}.` : ''}${record.identifier}`,
                      scope: scope
                    })
                  }}
                  accountIdentifier={accountId}
                  label={getString('ce.co.accessPoint.select.connector')}
                  category={'CLOUD_COST'}
                  disabled={props.isEditMod}
                />
              ) : null}
              {!props.isRuleCreationMode ? (
                <FormInput.Select
                  name="accessPointRegion"
                  label={getString('ce.co.accessPoint.select.regionToInstall')}
                  placeholder={getString('pipeline.regionPlaceholder')}
                  items={regionOptions}
                  onChange={e => {
                    props.accessPoint.region = e.value as string
                    setAccessPoint(props.accessPoint)
                    setSelectedRegion(props.accessPoint.region)
                    formik.setFieldValue('accessPointRegion', e.value)
                  }}
                  disabled={regionsLoading || regionOptions.length == 0 || props.isEditMod}
                />
              ) : null}
              <Container>
                <Layout.Horizontal>
                  <FormInput.RadioGroup
                    name="albSelector"
                    items={[
                      { label: getString('ce.co.accessPoint.createNewALB'), value: 'new' },
                      { label: '', value: '' }
                    ]}
                    style={{ fontSize: '24px' }}
                    radioGroup={{ inline: true, className: css.radioFont }}
                    disabled={regionsLoading || regionOptions.length == 0 || !selectedRegion}
                    onChange={e => {
                      setUseExistingALB(e.currentTarget.value !== 'new')
                      setCreateOrExisting(e.currentTarget.value)
                      clearAccessPointMeta()
                    }}
                    className={css.radioFont}
                  />
                  <FormInput.Select
                    name="apCores"
                    items={apCoreOptions}
                    disabled={regionsLoading || !selectedRegion || !useExistingALB}
                    onChange={e => {
                      onApCoreChange(e.value as string)
                    }}
                    style={{ width: '220px' }}
                    placeholder={getString('ce.co.accessPoint.select.existingALB')}
                  />
                </Layout.Horizontal>
              </Container>
              <FormInput.Select
                name="certificate"
                label={getString('ce.co.accessPoint.select.aCertificate')}
                placeholder={getString('ce.co.accessPoint.select.certificate')}
                items={certificateOptions}
                onChange={e => {
                  formik.setFieldValue('certificate', e)
                  if (props.accessPoint.metadata) props.accessPoint.metadata.certificate_id = e.value as string // eslint-disable-line
                  setAccessPoint(props.accessPoint)
                }}
                disabled={certificatesLoading || certificateOptions.length == 0}
              />
              {!props.isRuleCreationMode && !useExistingALB ? (
                <FormInput.Select
                  name="vpc"
                  label={getString('ce.co.accessPoint.select.vpc')}
                  placeholder={getString('ce.co.accessPoint.select.vpc')}
                  items={vpcOptions}
                  onChange={e => {
                    formik.setFieldValue('vpc', e.value)
                    props.accessPoint.vpc = e.value as string
                    setAccessPoint(props.accessPoint)
                    setSelectedVpc(props.accessPoint.vpc)
                  }}
                  disabled={vpcsLoading || vpcOptions.length == 0 || props.isEditMod}
                />
              ) : null}
              <FormInput.MultiSelect
                name="securityGroups"
                label={getString('ce.co.accessPoint.select.securityGroups')}
                placeholder={getString('ce.co.accessPoint.select.securityGroups')}
                items={sgOptions}
                onChange={e => {
                  formik.setFieldValue('securityGroups', e)
                  // eslint-disable-next-line
                  if (props.accessPoint.metadata) {
                    // eslint-disable-next-line
                    props.accessPoint.metadata.security_groups = e.map(x => {
                      return x.value as string
                    })
                    setAccessPoint(props.accessPoint)
                  }
                }}
                disabled={sgsLoading || sgOptions.length == 0}
              />
              <Button
                intent="primary"
                text={getString('ce.co.accessPoint.proceed')}
                onClick={formik.submitForm}
                style={{ position: 'absolute', bottom: 0 }}
              ></Button>
            </Layout.Vertical>
          </FormikForm>
        )}
        validationSchema={Yup.object().shape({
          cloudConnector: Yup.string().required(getString('ce.co.accessPoint.validation.connector')),
          accessPointName: Yup.string().required(getString('ce.co.accessPoint.validation.name')),
          accessPointRegion: Yup.string().required(getString('validation.regionRequired')),
          vpc: Yup.string().required(getString('ce.co.accessPoint.validation.vpc')),
          subnets: Yup.array(Yup.string()).min(2, getString('ce.co.accessPoint.validation.subnets')),
          securityGroups: Yup.array(Yup.string()).min(1, getString('ce.co.accessPoint.validation.securityGroup'))
        })}
      ></Formik>
    </Layout.Vertical>
  )
}
 
export default CreateTunnelStep