All files / modules/75-ce/components/COInstanceSelector COInstanceSelector.tsx

83.73% Statements 139/166
42.54% Branches 77/181
88.1% Functions 37/42
84.38% Lines 135/160

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 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594              5x 5x   5x 5x                       5x   5x 5x   5x 5x 5x 5x                                       52x             13x             5x   5x 19x 18x 18x 18x 18x 18x 18x 18x   18x 18x   18x 6x     18x 10x 4x 4x 4x   10x     18x                 18x 1x 1x               18x 1x 1x 1x 1x 1x 1x     18x 2x 2x 1x 1x   1x 1x 1x   1x     18x 6x     18x 1x     18x 1x 1x 1x               18x   18x                                                                                                                                                               5x             22x 22x 22x 22x     22x 22x     22x       22x 22x 22x   22x                         22x                   22x 6x     22x 12x 10x       22x 10x     22x 12x     22x 6x                 6x         22x 6x 6x       22x 12x     22x 6x         22x 10x 4x 4x 4x       22x 12x             22x 12x             22x 6x       6x     22x 20x                               2x                                                     2x                                     5x 8x             5x                     18x   18x 13x     18x 13x 13x 1x       18x 8x                                                                                                                         18x 14x                                     18x                                                   18x 16x 16x 14x 2x     2x   16x     18x                         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, { useState, useEffect, ReactNode } from 'react'
import { useParams } from 'react-router-dom'
import type { CellProps } from 'react-table'
import { isEmpty as _isEmpty, defaultTo as _defaultTo } from 'lodash-es'
import {
  Text,
  Container,
  ExpandingSearchInput,
  Layout,
  Checkbox,
  Button,
  Icon,
  TableV2,
  Select,
  SelectOption
} from '@wings-software/uicore'
import { Color } from '@harness/design-system'
import type { GatewayDetails, InstanceDetails } from '@ce/components/COCreateGateway/models'
import { useTelemetry } from '@common/hooks/useTelemetry'
import { ResourceGroup, useAllResourceGroups, useAllZones } from 'services/lw'
import type { AccountPathProps } from '@common/interfaces/RouteInterfaces'
import useRegionsForSelection from '@ce/common/hooks/useRegionsForSelection'
import { useStrings } from 'framework/strings'
import { Utils } from '@ce/common/Utils'
import css from './COInstanceSelector.module.scss'
 
interface COInstanceSelectorprops {
  instances: InstanceDetails[]
  selectedInstances: InstanceDetails[]
  setSelectedInstances: (selectedInstances: InstanceDetails[]) => void
  setGatewayDetails: (gatewayDetails: GatewayDetails) => void
  gatewayDetails: GatewayDetails
  onInstancesAddSuccess?: () => void
  loading: boolean
  refresh?: (tomlString?: string) => void
  isEditFlow: boolean
}
 
interface GCPFiltersProps {
  region?: SelectOption
  zone?: SelectOption
}
 
function TableCell(tableProps: CellProps<InstanceDetails>): JSX.Element {
  return (
    <Text lineClamp={3} color={Color.BLACK}>
      {tableProps.value}
    </Text>
  )
}
function NameCell(tableProps: CellProps<InstanceDetails>): JSX.Element {
  return (
    <Text lineClamp={3} color={Color.BLACK} style={{ overflowWrap: 'anywhere', paddingRight: 5 }}>
      {tableProps.value} {tableProps.row.original.id}
    </Text>
  )
}
 
const TOTAL_ITEMS_PER_PAGE = 8
 
const COInstanceSelector: React.FC<COInstanceSelectorprops> = props => {
  const { trackEvent } = useTelemetry()
  const { getString } = useStrings()
  const [filteredInstances, setFilteredInstances] = useState<InstanceDetails[]>([])
  const [selectedInstances, setSelectedInstances] = useState<InstanceDetails[]>(_defaultTo(props.selectedInstances, []))
  const [pageIndex, setPageIndex] = useState<number>(0)
  const [isLoading, setIsLoading] = useState<boolean>(false)
  const [selectedResourceGroup, setSelectedResourceGroup] = useState<SelectOption>()
  const [gcpFilters, setGcpFilters] = useState<GCPFiltersProps>()
 
  const isAzureProvider = Utils.isProviderAzure(props.gatewayDetails.provider)
  const isGcpProvider = Utils.isProviderGcp(props.gatewayDetails.provider)
 
  useEffect(() => {
    setFilteredInstances(props.instances)
  }, [props.instances])
 
  const onResourceGroupSelect = (selectedRg: SelectOption | null, resourceGroupLoading: boolean) => {
    if (selectedRg) {
      setSelectedResourceGroup(selectedRg)
      const groupText = _defaultTo(selectedRg.label, '')
      props.refresh?.(`resource_groups=['${groupText}']`)
    }
    setIsLoading(resourceGroupLoading)
  }
 
  const onGcpFiltersChange = (filters: GCPFiltersProps, loadingFilters: boolean) => {
    setGcpFilters(filters)
    if (filters.zone) {
      const filterText = `regions=['${filters.zone.label}']`
      props.refresh?.(filterText)
    }
    setIsLoading(loadingFilters)
  }
 
  const onCheckboxChange = (e: React.FormEvent<HTMLInputElement>, alreadyChecked: boolean, data: InstanceDetails) => {
    Eif (e.currentTarget.checked && !alreadyChecked) {
      setSelectedInstances([...selectedInstances, data])
    } else if (!e.currentTarget.checked && alreadyChecked) {
      const updatedInstances = [...selectedInstances]
      updatedInstances.splice(selectedInstances.indexOf(data), 1)
      setSelectedInstances(updatedInstances)
    }
  }
 
  const addInstances = () => {
    const newInstances = [...selectedInstances]
    props.setSelectedInstances(newInstances)
    const updatedGatewayDetails = { ...props.gatewayDetails, selectedInstances: newInstances }
    props.setGatewayDetails(updatedGatewayDetails)
    handleSearch('')
    props.onInstancesAddSuccess?.()
  }
 
  const handleSearch = (text: string): void => {
    pageIndex !== 0 && setPageIndex(0)
    if (!text) {
      setFilteredInstances(props.instances)
      return
    }
    text = text.toLowerCase()
    const instances = props.instances.filter(
      t => t.name.toLowerCase().indexOf(text) >= 0 || t.id.toLowerCase().indexOf(text) >= 0
    )
    setFilteredInstances(instances)
  }
 
  useEffect(() => {
    trackEvent('SelectedInstances', {})
  }, [])
 
  const refreshPageParams = () => {
    setPageIndex(0)
  }
 
  const handleRefresh = () => {
    refreshPageParams()
    Eif (isAzureProvider && selectedResourceGroup) {
      props.refresh?.(`resource_groups=['${selectedResourceGroup.label}']`)
    } else if (isGcpProvider && gcpFilters?.zone) {
      props.refresh?.(`regions=['${gcpFilters.zone.label}']`)
    } else {
      props.refresh?.()
    }
  }
 
  const hasSelectedInstances = !_isEmpty(selectedInstances)
 
  return (
    <Container>
      <Layout.Vertical spacing="large">
        <Container style={{ paddingBottom: 20, borderBottom: '1px solid #CDD3DD' }}>
          <Text font={'large'}>Select Instances</Text>
          <Text style={{ marginTop: 15 }}>
            {getString('ce.co.autoStoppingRule.configuration.instanceModal.description')}
          </Text>
        </Container>
        <Layout.Vertical
          style={{
            paddingBottom: 20,
            paddingTop: 20,
            borderBottom: '1px solid #CDD3DD'
          }}
        >
          <Layout.Horizontal
            style={{
              justifyContent: 'space-between'
            }}
          >
            <Layout.Horizontal flex={{ alignItems: 'center' }}>
              <Button
                onClick={addInstances}
                disabled={!hasSelectedInstances}
                style={{
                  backgroundColor: hasSelectedInstances ? '#0278d5' : 'inherit',
                  color: hasSelectedInstances ? '#F3F3FA' : 'inherit',
                  marginRight: 20
                }}
              >
                {`Add selected ${Utils.getConditionalResult(
                  hasSelectedInstances,
                  `(${selectedInstances.length})`,
                  ''
                )}`}
              </Button>
              <div onClick={handleRefresh}>
                <Icon name="refresh" color="primary7" size={14} />
                <span style={{ color: 'var(--primary-7)', margin: '0 5px', cursor: 'pointer' }}>Refresh</span>
              </div>
            </Layout.Horizontal>
            <ExpandingSearchInput className={css.search} onChange={handleSearch} />
          </Layout.Horizontal>
          <InstancesFilter
            gatewayDetails={props.gatewayDetails}
            onResourceGroupSelectCallback={onResourceGroupSelect}
            onGcpFiltersChangeCallback={onGcpFiltersChange}
            selectedInstances={selectedInstances}
            isEditFlow={props.isEditFlow}
          />
        </Layout.Vertical>
        <InstanceSelectorBody
          isLoading={props.loading || isLoading}
          selectedResourceGroup={selectedResourceGroup}
          instances={filteredInstances}
          pageProps={{
            index: pageIndex,
            setIndex: setPageIndex,
            totalCount: _defaultTo(props.instances.length, 0)
          }}
          onCheckboxChange={onCheckboxChange}
          selectedInstances={selectedInstances}
          isAzureSelection={isAzureProvider}
          isGcpSelection={isGcpProvider}
          selectedGcpFilters={gcpFilters}
        />
      </Layout.Vertical>
    </Container>
  )
}
 
interface InstancesFilterProps {
  gatewayDetails: GatewayDetails
  onResourceGroupSelectCallback: (resourceGroup: SelectOption | null, resourceGroupLoading: boolean) => void
  onGcpFiltersChangeCallback: (values: GCPFiltersProps, loading: boolean) => void
  selectedInstances: InstanceDetails[]
  isEditFlow: boolean
}
 
const InstancesFilter: React.FC<InstancesFilterProps> = ({
  gatewayDetails,
  onResourceGroupSelectCallback,
  onGcpFiltersChangeCallback,
  selectedInstances,
  isEditFlow
}) => {
  const { accountId } = useParams<AccountPathProps>()
  const { getString } = useStrings()
  const isAzureProvider = Utils.isProviderAzure(gatewayDetails.provider)
  const isGcpProvider = Utils.isProviderGcp(gatewayDetails.provider)
 
  // Azure filters data
  const [resourceGroupData, setResourceGroupData] = useState<SelectOption[]>([])
  const [selectedResourceGroup, setSelectedResourceGroup] = useState<SelectOption>()
 
  // GCP filters data
  const { data: regionsData, loading: regionsLoading } = useRegionsForSelection({
    cloudAccountId: gatewayDetails.cloudAccount.id,
    additionalProps: { lazy: !isGcpProvider }
  })
  const [selectedRegion, setSelectedRegion] = useState<SelectOption>()
  const [zonesData, setZonesData] = useState<SelectOption[]>([])
  const [selectedZone, setSelectedZone] = useState<SelectOption>()
 
  const { data: resourceGroups, loading: resourceGroupsLoading } = useAllResourceGroups({
    account_id: accountId, // eslint-disable-line
    queryParams: {
      cloud_account_id: gatewayDetails.cloudAccount.id, // eslint-disable-line
      accountIdentifier: accountId
    },
    lazy: !isAzureProvider
  })
 
  const {
    data: zones,
    loading: zonesLoading,
    refetch: fetchZones
  } = useAllZones({
    account_id: accountId,
    queryParams: {
      cloud_account_id: gatewayDetails.cloudAccount.id,
      accountIdentifier: accountId,
      region: ''
    },
    lazy: true
  })
 
  useEffect(() => {
    setResourceGroupDataFromResponse(resourceGroups?.response)
  }, [resourceGroups?.response])
 
  useEffect(() => {
    if (isAzureProvider) {
      handleAzureFiltersUpdate()
    }
  }, [resourceGroupData])
 
  useEffect(() => {
    onResourceGroupSelectCallback(_defaultTo(selectedResourceGroup, null), resourceGroupsLoading)
  }, [selectedResourceGroup, resourceGroupsLoading])
 
  useEffect(() => {
    handleGcpRegionsFilterUpdate()
  }, [regionsData])
 
  useEffect(() => {
    Iif (selectedRegion) {
      fetchZones({
        queryParams: {
          cloud_account_id: gatewayDetails.cloudAccount.id,
          accountIdentifier: accountId,
          region: selectedRegion.label
        }
      })
    }
    Iif (isGcpProvider) {
      onGcpFiltersChangeCallback({ region: selectedRegion }, regionsLoading)
    }
  }, [selectedRegion, regionsLoading])
 
  useEffect(() => {
    Eif (zones?.response) {
      setZonesData(zones.response.map(z => ({ label: z, value: z })))
    }
  }, [zones?.response])
 
  useEffect(() => {
    handleGcpZonesFilterUpdate()
  }, [zonesData])
 
  useEffect(() => {
    Iif (selectedRegion) {
      onGcpFiltersChangeCallback({ region: selectedRegion, zone: selectedZone }, zonesLoading)
    }
  }, [selectedZone, zonesLoading])
 
  const handleAzureFiltersUpdate = () => {
    if (!selectedResourceGroup && !_isEmpty(selectedInstances)) {
      const groupName = selectedInstances?.[0]?.metadata?.resourceGroup?.toLowerCase()
      const groupToSelect = resourceGroupData.find(d => d.label.toLowerCase() === groupName)
      setSelectedResourceGroup(groupToSelect)
    }
  }
 
  const handleGcpRegionsFilterUpdate = () => {
    Iif (isGcpProvider && !selectedRegion && !_isEmpty(selectedInstances)) {
      const region = selectedInstances?.[0]?.region?.toLowerCase()
      const regionToSelect = regionsData.find(r => r.label.toLowerCase() === region)
      setSelectedRegion(regionToSelect)
    }
  }
 
  const handleGcpZonesFilterUpdate = () => {
    Iif (isGcpProvider && !selectedZone && !_isEmpty(selectedInstances)) {
      const zone = selectedInstances?.[0]?.metadata?.availabilityZone?.toLowerCase()
      const zoneToSelect = zonesData.find(z => z.label.toLowerCase() === zone)
      setSelectedZone(zoneToSelect)
    }
  }
 
  const setResourceGroupDataFromResponse = (response: ResourceGroup[] = []) => {
    const loaded = response.map(r => ({
      label: r.name as string,
      value: r.name as string
    }))
    setResourceGroupData(loaded)
  }
 
  if (isAzureProvider) {
    return (
      <Layout.Horizontal flex={{ justifyContent: 'flex-start' }} spacing={'large'} style={{ maxWidth: '40%' }}>
        <Select
          disabled={resourceGroupsLoading}
          items={resourceGroupData}
          onChange={setSelectedResourceGroup}
          value={selectedResourceGroup}
          inputProps={{
            placeholder: getString('ce.co.selectResourceGroupPlaceholder')
          }}
          name="resourceGroupSelector"
        />
      </Layout.Horizontal>
    )
  }
 
  Iif (isGcpProvider) {
    return (
      <Layout.Horizontal flex={{ justifyContent: 'flex-start' }} spacing={'large'} style={{ maxWidth: '40%' }}>
        <Select
          disabled={regionsLoading || isEditFlow}
          items={regionsData}
          onChange={setSelectedRegion}
          value={selectedRegion}
          inputProps={{
            placeholder: 'Region'
          }}
          name="regionsSelector"
        />
        <Select
          disabled={zonesLoading || isEditFlow}
          items={zonesData}
          onChange={setSelectedZone}
          value={selectedZone}
          inputProps={{
            placeholder: 'Zone'
          }}
          name="zoneSelector"
        />
      </Layout.Horizontal>
    )
  }
 
  return null
}
 
interface InstanceSelectorBodyProps {
  isLoading: boolean
  selectedResourceGroup?: SelectOption
  instances: InstanceDetails[]
  pageProps: { index: number; setIndex: (page: number) => void; totalCount: number }
  onCheckboxChange: (e: React.FormEvent<HTMLInputElement>, alreadyChecked: boolean, data: InstanceDetails) => void
  selectedInstances: InstanceDetails[]
  isAzureSelection: boolean
  isGcpSelection: boolean
  selectedGcpFilters?: GCPFiltersProps
}
 
interface WarningMessageProps {
  messageText: string
}
 
const WarningMessage = ({ messageText }: WarningMessageProps) => {
  return (
    <Text icon={'execution-warning'} font={{ size: 'medium' }} iconProps={{ size: 20 }}>
      {messageText}
    </Text>
  )
}
 
const InstanceSelectorBody: React.FC<InstanceSelectorBodyProps> = ({
  isLoading,
  selectedResourceGroup,
  instances,
  pageProps,
  onCheckboxChange,
  selectedInstances,
  isAzureSelection,
  isGcpSelection,
  selectedGcpFilters
}) => {
  const { getString } = useStrings()
 
  const isSelectedInstance = (item: InstanceDetails): boolean => {
    return selectedInstances.findIndex(s => s.id === item.id) >= 0
  }
 
  const TableCheck = (tableProps: CellProps<InstanceDetails>): JSX.Element => {
    const alreadyChecked = isSelectedInstance(tableProps.row.original)
    return (
      <Checkbox checked={alreadyChecked} onChange={e => onCheckboxChange(e, alreadyChecked, tableProps.row.original)} />
    )
  }
 
  const renderInstancesTable = (): ReactNode => {
    return (
      <TableV2
        className={css.instancesTable}
        data={instances.slice(
          pageProps.index * TOTAL_ITEMS_PER_PAGE,
          pageProps.index * TOTAL_ITEMS_PER_PAGE + TOTAL_ITEMS_PER_PAGE
        )}
        pagination={{
          pageSize: TOTAL_ITEMS_PER_PAGE,
          pageIndex: pageProps.index,
          pageCount: Math.ceil(instances.length / TOTAL_ITEMS_PER_PAGE),
          itemCount: pageProps.totalCount,
          gotoPage: newPageIndex => pageProps.setIndex(newPageIndex)
        }}
        columns={[
          {
            Header: '',
            id: 'selected',
            Cell: TableCheck,
            width: '5%'
          },
          {
            accessor: 'name',
            Header: getString('ce.co.instanceSelector.name'),
            width: '35%',
            Cell: NameCell,
            disableSortBy: true
          },
          {
            accessor: 'ipv4',
            Header: getString('ce.co.instanceSelector.ipAddress'),
            width: '15%',
            Cell: TableCell,
            disableSortBy: true
          },
          {
            accessor: 'region',
            Header: getString('regionLabel'),
            width: '15%',
            Cell: TableCell,
            disableSortBy: true
          },
          {
            accessor: 'type',
            Header: getString('typeLabel'),
            width: '15%',
            Cell: TableCell,
            disableSortBy: true
          },
          {
            accessor: 'status',
            Header: getString('status'),
            width: '10%',
            Cell: TableCell,
            disableSortBy: true
          }
        ]}
      />
    )
  }
 
  const azureBodyRenderer = (): ReactNode => {
    return _isEmpty(selectedResourceGroup) ? (
      <Layout.Horizontal flex={{ justifyContent: 'center' }}>
        <WarningMessage
          messageText={getString('ce.co.autoStoppingRule.configuration.instanceModal.rgEmptyDescription')}
        />
      </Layout.Horizontal>
    ) : _isEmpty(instances) ? (
      <Layout.Horizontal flex={{ justifyContent: 'center' }}>
        <Text font={{ size: 'medium' }} iconProps={{ size: 20 }}>
          {getString('ce.co.autoStoppingRule.configuration.instanceModal.rgEmptyInstancesDescription', {
            region: selectedResourceGroup?.label
          })}
        </Text>
      </Layout.Horizontal>
    ) : (
      renderInstancesTable()
    )
  }
 
  const gcpBodyRenderer = (): ReactNode => {
    return _isEmpty(selectedGcpFilters?.region) ? (
      <Layout.Horizontal flex={{ justifyContent: 'center' }}>
        <WarningMessage
          messageText={getString('ce.co.autoStoppingRule.configuration.instanceModal.gcpFiltersNotSelectedDescription')}
        />
      </Layout.Horizontal>
    ) : _isEmpty(selectedGcpFilters?.zone) ? (
      <Layout.Horizontal flex={{ justifyContent: 'center' }}>
        <WarningMessage
          messageText={getString(
            'ce.co.autoStoppingRule.configuration.instanceModal.gcpZoneFilterNotSelectedDescription'
          )}
        />
      </Layout.Horizontal>
    ) : _isEmpty(instances) ? (
      <Layout.Horizontal flex={{ justifyContent: 'center' }}>
        <Text font={{ size: 'medium' }} iconProps={{ size: 20 }}>
          {getString('ce.co.autoStoppingRule.configuration.instanceModal.gcpEmptyInstancesDescription')}
        </Text>
      </Layout.Horizontal>
    ) : (
      renderInstancesTable()
    )
  }
 
  const renderBody = (): ReactNode => {
    let body = null
    if (isAzureSelection) {
      body = azureBodyRenderer()
    } else Iif (isGcpSelection) {
      body = gcpBodyRenderer()
    } else {
      body = renderInstancesTable()
    }
    return body
  }
 
  return (
    <Container style={{ minHeight: 250 }}>
      {isLoading ? (
        <Layout.Horizontal flex={{ justifyContent: 'center' }}>
          <Icon name="spinner" size={24} color="blue500" />
        </Layout.Horizontal>
      ) : (
        renderBody()
      )}
    </Container>
  )
}
 
export default COInstanceSelector