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

88.52% Statements 108/122
83.97% Branches 131/156
86.96% Functions 20/23
88.24% Lines 105/119

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              6x 6x 6x 6x 6x 6x 6x 6x 6x   6x 6x 6x     6x 6x 6x                   6x 6x                             6x                     6x       61x 61x 61x   61x 2x 2x 2x   2x                                                                                   61x         6x 61x 61x 61x 61x 61x 61x 61x 61x   61x 61x 61x 61x 61x 61x           61x                 61x         61x 16x 3x   13x 12x 12x           61x 16x 16x       16x 16x 15x     16x     16x     61x 32x 32x     61x 50x     50x 50x 2x       61x 18x 16x   2x         2x       61x                         2x     2x 2x       2x 2x 2x   2x 2x   2x               61x 2x           2x       61x           61x 2x 2x         2x       2x       61x 2x 2x 2x 2x             2x             61x 2x 2x 2x     61x                                           2x 2x                                           6x  
/*
 * 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 { defaultTo as _defaultTo, isEmpty as _isEmpty, values as _values } from 'lodash-es'
import { Button, Container, Heading, Layout, Select, SelectOption, Text, useToaster } from '@wings-software/uicore'
import { Color } from '@harness/design-system'
import { Dialog, IDialogProps } from '@blueprintjs/core'
import { useModalHook } from '@harness/use-modal'
import { Utils } from '@ce/common/Utils'
import { useGatewayContext } from '@ce/context/GatewayContext'
import type { AccountPathProps } from '@common/interfaces/RouteInterfaces'
import { useStrings } from 'framework/strings'
import { AccessPoint, AccessPointCore, useAccessPointResources, useListAccessPoints } from 'services/lw'
import { useTelemetry } from '@common/hooks/useTelemetry'
import type { AccessPointScreenMode } from '@ce/types'
import type { GatewayDetails } from '../COCreateGateway/models'
import LoadBalancerDnsConfig from './LoadBalancerDnsConfig'
import AzureAPConfig from '../COAccessPointList/AzureAPConfig'
import {
  getAccessPointFetchQueryParams,
  getApSelectionList,
  getDummyResource,
  getSupportedResourcesQueryParams,
  getLoadBalancerToEdit,
  getMatchingLoadBalancer,
  getLinkedAccessPoint,
  isValidLoadBalancer
} from './helper'
import GCPAccessPointConfig from '../AccessPoint/GCPAccessPoint/GCPAccessPointConfig'
import css from './COGatewayAccess.module.scss'
 
interface LoadBalancerSelectionProps {
  gatewayDetails: GatewayDetails
  setGatewayDetails: (details: GatewayDetails) => void
}
 
interface UseLoadBalancerProps {
  gatewayDetails: GatewayDetails
  loadBalancer: AccessPoint
  handleClose: (clearStatus?: boolean) => void
  mode: AccessPointScreenMode
  handleSave: (lb: AccessPoint) => void
}
 
const modalPropsLight: IDialogProps = {
  isOpen: true,
  enforceFocus: false,
  style: {
    width: 860,
    padding: 40,
    position: 'relative',
    minHeight: 500
  }
}
 
const useLoadBalancerModal = (
  { gatewayDetails, loadBalancer, handleClose, mode, handleSave }: UseLoadBalancerProps,
  deps: any[] = []
) => {
  const isAwsProvider = Utils.isProviderAws(gatewayDetails.provider)
  const isAzureProvider = Utils.isProviderAzure(gatewayDetails.provider)
  const isGcpProvider = Utils.isProviderGcp(gatewayDetails.provider)
 
  const [openLoadBalancerModal, hideLoadBalancerModal] = useModalHook(() => {
    const onClose = (clearStatus = false) => {
      handleClose(clearStatus)
      hideLoadBalancerModal()
    }
    return (
      <Dialog onClose={hideLoadBalancerModal} {...modalPropsLight}>
        {isAwsProvider && (
          <LoadBalancerDnsConfig
            loadBalancer={loadBalancer}
            cloudAccountId={gatewayDetails.cloudAccount.id}
            onClose={onClose}
            mode={mode}
            onSave={handleSave}
          />
        )}
        {isAzureProvider && (
          <AzureAPConfig
            cloudAccountId={gatewayDetails.cloudAccount.id}
            onSave={handleSave}
            mode={mode}
            onClose={onClose}
            loadBalancer={loadBalancer}
          />
        )}
        {isGcpProvider && (
          <GCPAccessPointConfig
            cloudAccountId={gatewayDetails.cloudAccount.id}
            onSave={handleSave}
            mode={mode}
            onClose={onClose}
            loadBalancer={loadBalancer}
          />
        )}
        <Button
          minimal
          icon="cross"
          iconProps={{ size: 18 }}
          onClick={() => {
            onClose(true)
          }}
          style={{ position: 'absolute', right: 'var(--spacing-large)', top: 'var(--spacing-large)' }}
          data-testid={'close-instance-modal'}
        />
      </Dialog>
    )
  }, deps)
  return {
    openLoadBalancerModal
  }
}
 
const LoadBalancerSelection: React.FC<LoadBalancerSelectionProps> = ({ gatewayDetails, setGatewayDetails }) => {
  const { accountId } = useParams<AccountPathProps>()
  const { getString } = useStrings()
  const { isEditFlow } = useGatewayContext()
  const { showError } = useToaster()
  const { trackEvent } = useTelemetry()
  const isAwsProvider = Utils.isProviderAws(gatewayDetails.provider)
  const isAzureProvider = Utils.isProviderAzure(gatewayDetails.provider)
  const isGcpProvider = Utils.isProviderGcp(gatewayDetails.provider)
 
  const [apCoreList, setApCoreList] = useState<SelectOption[]>([])
  const [selectedApCore, setSelectedApCore] = useState<SelectOption>()
  const [apCoreResponseList, setApCoreResponseList] = useState<AccessPointCore[]>([])
  const [selectedLoadBalancer, setSelectedLoadBalancer] = useState<AccessPointCore>()
  const [accessPoint, setAccessPoint] = useState<AccessPoint>()
  const [isCreateMode, setIsCreateMode] = useState<boolean>(false)
 
  const {
    data: accessPoints,
    loading: accessPointsLoading,
    refetch: refetchAccessPoints
  } = useListAccessPoints({
    account_id: accountId,
    queryParams: getAccessPointFetchQueryParams({ gatewayDetails: gatewayDetails, accountId }, isAwsProvider)
  })
 
  const {
    data: apCoresResponse,
    loading: apCoresLoading,
    refetch: apCoresRefetch
  } = useAccessPointResources({
    account_id: accountId,
    queryParams: getSupportedResourcesQueryParams({ gatewayDetails: gatewayDetails, accountId })
  })
 
  useEffect(() => {
    if (accessPoints?.response?.length === 0) {
      return
    }
    if (gatewayDetails.accessPointID) {
      const targetAp = accessPoints?.response?.find(_ap => _ap.id === gatewayDetails.accessPointID)
      Iif (targetAp) {
        setAccessPoint(targetAp)
      }
    }
  }, [accessPoints?.response])
 
  useEffect(() => {
    const submittedAccessPoints = accessPoints?.response?.filter(_item => _item.status === 'submitted')
    Iif (apCoresResponse?.response?.length === 0 && _isEmpty(submittedAccessPoints)) {
      return
    }
 
    const apCoresResponseMap: Record<string, AccessPointCore> = {}
    apCoresResponse?.response?.forEach(_item => {
      apCoresResponseMap[_item.details?.name as string] = _item
    })
 
    submittedAccessPoints?.forEach(_item => {
      apCoresResponseMap[_item.name as string] = getDummyResource(_item, { isAwsProvider, isAzureProvider })
    })
    setApCoreResponseList(_values(apCoresResponseMap))
  }, [apCoresResponse?.response, accessPoints?.response])
 
  useEffect(() => {
    const loaded = getApSelectionList(apCoreResponseList, { isAwsProvider, isAzureProvider, isGcpProvider })
    setApCoreList(loaded)
  }, [apCoreResponseList])
 
  useEffect(() => {
    const resourceId = isAwsProvider
      ? accessPoint?.metadata?.albArn
      : _defaultTo(accessPoint?.metadata?.app_gateway_id, accessPoint?.id) // handled case for "submitted" state access points
    const selectedResource = resourceId && apCoreList.find(_item => _item.value === resourceId)
    if (selectedResource) {
      setSelectedApCore(selectedResource)
    }
  }, [accessPoint, apCoreList])
 
  useEffect(() => {
    if (!accessPoint || !accessPoint.id) {
      return
    }
    const updatedGatewayDetails = {
      ...gatewayDetails,
      accessPointID: accessPoint.id,
      accessPointData: accessPoint
    }
    setGatewayDetails(updatedGatewayDetails)
    // setGeneratedHostName(generateHostName(accessPoint.host_name as string))
  }, [accessPoint])
 
  const { openLoadBalancerModal } = useLoadBalancerModal(
    {
      gatewayDetails: gatewayDetails,
      mode: Utils.getConditionalResult(isCreateMode, 'create', 'import'),
      loadBalancer: getLoadBalancerToEdit(
        {
          lbDetails: selectedLoadBalancer,
          gatewayDetails: gatewayDetails,
          accountId
        },
        { isAwsProvider, isAzureProvider, isCreateMode, isGcpProvider }
      ),
      handleClose: clearStatus => {
        Iif (clearStatus && !isCreateMode) {
          clearAPData()
        }
        Eif (isCreateMode) {
          setIsCreateMode(false)
        }
      },
      handleSave: savedLb => {
        setAccessPoint(savedLb)
        Eif (isCreateMode) {
          setIsCreateMode(false)
        }
        Eif (isAwsProvider) {
          apCoresRefetch()
        }
        Iif (isAzureProvider || isGcpProvider) {
          refetchAccessPoints()
        }
      }
    },
    [selectedLoadBalancer, isCreateMode]
  )
 
  const updateLoadBalancerDetails = (_accessPointDetails?: AccessPoint) => {
    const updatedGatewayDetails = {
      ...gatewayDetails,
      accessPointID: _defaultTo(_accessPointDetails?.id, ''),
      accessPointData: _accessPointDetails
      // hostName: generateHostName(_accessPointDetails?.host_name || '')
    }
    setGatewayDetails(updatedGatewayDetails)
    // setGeneratedHostName(updatedGatewayDetails.hostName || getString('ce.co.dnsSetup.autoURL'))
  }
 
  const clearAPData = () => {
    setSelectedApCore({ label: '', value: '' })
    updateLoadBalancerDetails()
    setSelectedLoadBalancer(undefined)
  }
 
  const handleLoadBalancerUpdation = (lb: AccessPointCore) => {
    let linkedAccessPoint = getLinkedAccessPoint(_defaultTo(accessPoints?.response, []), isAwsProvider, lb)
    Iif (!linkedAccessPoint) {
      linkedAccessPoint = accessPoint
    }
 
    // Use only those Access Points which are not in errored state.
    Iif (linkedAccessPoint?.status === 'errored') {
      showError(getString('ce.co.autoStoppingRule.setupAccess.erroredAccessPointSelectionText'))
      clearAPData()
    } else {
      updateLoadBalancerDetails(linkedAccessPoint)
    }
  }
 
  const handleLoadBalancerSelection = (item: SelectOption) => {
    setSelectedApCore(item)
    const matchedLb = getMatchingLoadBalancer(item, apCoreResponseList, { isAwsProvider })
    setSelectedLoadBalancer(matchedLb)
    Eif (
      isValidLoadBalancer(matchedLb as AccessPointCore, _defaultTo(accessPoints?.response, []), accessPoint, {
        isAwsProvider,
        isAzureProvider,
        isGcpProvider
      })
    ) {
      handleLoadBalancerUpdation(matchedLb as AccessPointCore)
    } else {
      isCreateMode && setIsCreateMode(false)
      openLoadBalancerModal()
    }
  }
 
  const handleCreateNewLb = () => {
    setIsCreateMode(true)
    trackEvent('MadeNewAccessPoint', {})
    openLoadBalancerModal()
  }
 
  return (
    <Container className={css.dnsLinkContainer}>
      <Heading level={3} font={{ weight: 'bold' }} className={css.header}>
        {getString(
          Utils.getConditionalResult(
            isAwsProvider || isGcpProvider,
            'ce.co.autoStoppingRule.setupAccess.selectLb',
            'ce.co.autoStoppingRule.setupAccess.selectAppGateway'
          )
        )}
      </Heading>
      <Layout.Horizontal className={css.selectLoadBalancerContainer}>
        {/* <img src={loadBalancerSvg} className={css.helperImage} /> */}
        <div>
          <Text className={css.helpText}>{getString('ce.co.autoStoppingRule.setupAccess.selectLbHelpText')}</Text>
          <Layout.Horizontal flex={{ alignItems: 'center', justifyContent: 'flex-start' }}>
            <Select
              name="accessPoint"
              // label={getString('ce.co.autoStoppingRule.setupAccess.chooseLbText')}
              items={apCoreList}
              onChange={e => {
                // formik.setFieldValue('accessPoint', e.value)
                handleLoadBalancerSelection(e)
                trackEvent('SelectingAccessPoint', {})
              }}
              value={selectedApCore}
              disabled={isEditFlow || accessPointsLoading || apCoresLoading}
              className={css.loadBalancerSelector}
            />
            {!isEditFlow && _isEmpty(gatewayDetails.routing.container_svc) && (
              <Text color={Color.PRIMARY_6} onClick={handleCreateNewLb} style={{ cursor: 'pointer' }}>
                {`+${Utils.getConditionalResult(
                  isAwsProvider || isGcpProvider,
                  getString('ce.co.accessPoint.new'),
                  getString('ce.co.accessPoint.newAppGateway')
                )}`}
              </Text>
            )}
          </Layout.Horizontal>
        </div>
      </Layout.Horizontal>
    </Container>
  )
}
 
export default LoadBalancerSelection