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

98% Statements 49/50
87.8% Branches 36/41
100% Functions 9/9
98% Lines 49/50

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              5x 5x 5x 5x 5x 5x   5x 5x 5x     5x   5x 5x                   5x             35x 35x 35x 35x   35x 35x                       35x                     35x 15x       15x 6x         15x     35x 15x 1x       35x 15x                   35x   1x 1x 1x         1x 1x 1x 1x                         35x                         1x 1x 1x   1x 1x                                             1x 1x                   1x 1x                                         5x  
/*
 * 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, debounce as _debounce, defaultTo as _defaultTo } from 'lodash-es'
import { Container, FormInput, Layout, SelectOption, Text } from '@wings-software/uicore'
import { Color, FontVariation } from '@harness/design-system'
import { Radio } from '@blueprintjs/core'
import type { FormikProps } from 'formik'
import { useStrings } from 'framework/strings'
import { Utils } from '@ce/common/Utils'
import { useAllHostedZones } from 'services/lw'
import type { AccountPathProps } from '@common/interfaces/RouteInterfaces'
import type { DNSLinkSetupFormVal } from '@ce/types'
import { useGatewayContext } from '@ce/context/GatewayContext'
import type { GatewayDetails } from '../COCreateGateway/models'
import CustomDomainMapping from './CustomDomainMapping'
import css from './COGatewayAccess.module.scss'
 
interface ResourceAccessUrlSelectorProps {
  formikProps: FormikProps<DNSLinkSetupFormVal>
  gatewayDetails: GatewayDetails
  setGatewayDetails: (details: GatewayDetails) => void
  setHelpTextSections: (s: string[]) => void
  serverNames: string[]
}
 
const ResourceAccessUrlSelector: React.FC<ResourceAccessUrlSelectorProps> = ({
  gatewayDetails,
  setGatewayDetails,
  formikProps,
  setHelpTextSections,
  serverNames
}) => {
  const { accountId } = useParams<AccountPathProps>()
  const { getString } = useStrings()
  const { isEditFlow } = useGatewayContext()
  const isAwsProvider = Utils.isProviderAws(gatewayDetails.provider)
 
  const [hostedZonesList, setHostedZonesList] = useState<SelectOption[]>([])
  const [dnsProvider, setDNSProvider] = useState<string>(
    Utils.getConditionalResult(
      !_isEmpty(gatewayDetails.routing.custom_domain_providers?.route53?.hosted_zone_id),
      'route53',
      'others'
    )
  )
 
  const {
    data: hostedZones,
    loading: hostedZonesLoading,
    refetch: loadHostedZones
  } = useAllHostedZones({
    account_id: accountId, // eslint-disable-line
    queryParams: {
      cloud_account_id: gatewayDetails.cloudAccount.id, // eslint-disable-line
      region: 'us-east-1',
      domain: _defaultTo(gatewayDetails.customDomains?.[0], ''),
      accountIdentifier: accountId
    },
    lazy: !isEditFlow
  })
 
  useEffect(() => {
    Iif (hostedZonesLoading) {
      return
    }
    const loadedhostedZones: SelectOption[] =
      hostedZones?.response?.map(r => {
        return {
          label: r.name as string,
          value: r.id as string
        }
      }) || []
    setHostedZonesList(loadedhostedZones)
  }, [hostedZones, hostedZonesLoading])
 
  useEffect(() => {
    if (dnsProvider === 'route53') {
      loadHostedZones()
    }
  }, [dnsProvider])
 
  useEffect(() => {
    loadHostedZones({
      queryParams: {
        cloud_account_id: gatewayDetails.cloudAccount.id, // eslint-disable-line
        region: 'us-east-1',
        domain: _defaultTo(serverNames?.[0], ''),
        accountIdentifier: accountId
      }
    })
  }, [serverNames])
 
  const debouncedCustomDomainTextChange = React.useCallback(
    _debounce((value: string, shouldLoadHostedZones: boolean) => {
      const updatedGatewayDetails = { ...gatewayDetails }
      Eif (!updatedGatewayDetails.routing.custom_domain_providers) {
        updatedGatewayDetails.routing = {
          ...gatewayDetails.routing,
          custom_domain_providers: { others: {} } // eslint-disable-line
        }
      }
      updatedGatewayDetails.customDomains = value ? value.split(',') : []
      setGatewayDetails(updatedGatewayDetails)
      setHelpTextSections(['usingCustomDomain'])
      shouldLoadHostedZones &&
        loadHostedZones({
          queryParams: {
            cloud_account_id: gatewayDetails.cloudAccount.id, // eslint-disable-line
            region: 'us-east-1',
            domain: updatedGatewayDetails.customDomains[0],
            accountIdentifier: accountId
          }
        })
    }, 500),
    [gatewayDetails]
  )
 
  return (
    <>
      <Container className={css.dnsLinkContainer}>
        <Layout.Horizontal spacing="small" style={{ marginBottom: 'var(--spacing-xlarge)' }}>
          <Text font={{ variation: FontVariation.H6, weight: 'light' }}>
            {getString('ce.co.autoStoppingRule.setupAccess.customDomain.helpText')}
          </Text>
        </Layout.Horizontal>
        <Layout.Horizontal>
          <Radio
            value="no"
            disabled={!_isEmpty(serverNames)}
            onChange={e => {
              formikProps.setFieldValue('usingCustomDomain', e.currentTarget.value)
              Eif (e.currentTarget.value === 'no') {
                setHelpTextSections([])
              }
              formikProps.setFieldValue('customURL', '')
              setGatewayDetails({ ...gatewayDetails, customDomains: [] })
            }}
            checked={formikProps.values.usingCustomDomain === 'no'}
            data-testid="noCustomDomain"
          />
          <Layout.Vertical spacing="xsmall">
            <Text
              color={Color.GREY_500}
              style={{
                fontSize: '12px',
                fontWeight: 400,
                lineHeight: '18px',
                paddingBottom: 'var(--spacing-small)'
              }}
            >
              {getString('ce.co.autoStoppingRule.setupAccess.autogeneratedHelpText')}
            </Text>
          </Layout.Vertical>
        </Layout.Horizontal>
        <Layout.Horizontal style={{ width: '100%' }}>
          <Radio
            value="yes"
            onChange={e => {
              formikProps.setFieldValue('usingCustomDomain', e.currentTarget.value)
              debouncedCustomDomainTextChange('', false)
            }}
            checked={formikProps.values.usingCustomDomain === 'yes'}
            className={css.centerAlignedRadio}
            name={'usingCustomDomain'}
          />
          <FormInput.Text
            name="customURL"
            placeholder={getString('ce.co.dnsSetup.customURL')}
            onChange={(e: React.ChangeEvent<HTMLInputElement>) => {
              formikProps.setFieldValue('customURL', e.target.value)
              debouncedCustomDomainTextChange(e.target.value, true)
            }}
            style={{ width: '100%' }}
            disabled={formikProps.values.usingCustomDomain !== 'yes'}
          />
        </Layout.Horizontal>
      </Container>
      {!_isEmpty(formikProps.values.customURL) && isAwsProvider && (
        <CustomDomainMapping
          formikProps={formikProps}
          gatewayDetails={gatewayDetails}
          setGatewayDetails={setGatewayDetails}
          hostedZonesList={hostedZonesList}
          setDNSProvider={setDNSProvider}
          setHelpTextSections={setHelpTextSections}
        />
      )}
    </>
  )
}
 
export default ResourceAccessUrlSelector