All files / modules/35-connectors/components/CreateConnector/commonSteps/DelegateSelectorStep/DelegateSelector DelegateSelector.tsx

93.52% Statements 101/108
86.96% Branches 60/69
86.21% Functions 25/29
95.05% Lines 96/101

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              250x 250x 250x 250x 250x 250x 250x 250x   250x 250x 250x       250x 250x 250x 250x   250x 250x 250x     250x 250x 250x 250x                               250x   250x             250x 18x 4x   14x 14x 14x   14x 28x   14x     250x 166x 148x     296x 296x                           2x                     250x               166x 148x 148x 148x 148x   148x   148x                     148x       148x 148x     148x   148x 41x 18x                       148x 41x 13x         148x 42x 2x                     148x   41x 39x   41x     148x 41x   41x 9x 9x     9x 1x   8x     41x     148x 84x 84x 84x 84x         74x   10x             148x 82x 82x 82x 73x   9x               148x   41x                                       148x 82x                         148x 84x                               148x               148x                       148x         2x                                              
/*
 * 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, useMemo, useState } from 'react'
import { useParams } from 'react-router-dom'
import { defaultTo } from 'lodash-es'
import { ButtonVariation, Container, HarnessDocTooltip, Layout, Text } from '@wings-software/uicore'
import { Color } from '@harness/design-system'
import { IOptionProps, Radio } from '@blueprintjs/core'
import { useStrings } from 'framework/strings'
import { DelegateSelectors, useToaster } from '@common/components'
import type { AccountPathProps, ProjectPathProps } from '@common/interfaces/RouteInterfaces'
import useCreateDelegateModal from '@delegates/modals/DelegateModal/useCreateDelegateModal'
import { DelegateGroupDetails, useGetDelegatesUpTheHierarchy, RestResponseDelegateGroupListing } from 'services/portal'
import {
  DelegateSelectorTable,
  DelegateSelectorTableProps
} from '@connectors/components/CreateConnector/commonSteps/DelegateSelectorStep/DelegateSelector/DelegateSelectorTable'
import { PermissionIdentifier } from '@rbac/interfaces/PermissionIdentifier'
import { ResourceType } from '@rbac/interfaces/ResourceType'
import RbacButton from '@rbac/components/Button/Button'
import css from '@connectors/components/CreateConnector/commonSteps/DelegateSelectorStep/DelegateSelector/DelegateSelector.module.scss'
 
export enum DelegateOptions {
  DelegateOptionsAny = 'DelegateOptions.DelegateOptionsAny',
  DelegateOptionsSelective = 'DelegateOptions.DelegateOptionsSelective'
}
 
export enum DelegatesFoundState {
  ActivelyConnected = 'DelegatesFoundState.ActivelyConnected',
  NotConnected = 'DelegatesFoundState.NotConnected',
  NotFound = 'DelegatesFoundState.NotFound'
}
 
export interface DelegateSelectorProps extends ProjectPathProps {
  mode: DelegateOptions
  setMode: (mode: DelegateOptions) => void
  delegateSelectors: Array<string>
  setDelegateSelectors: (delegateSelectors: Array<string>) => void
  setDelegatesFound: (delegatesFound: DelegatesFoundState) => void
  delegateSelectorMandatory: boolean
}
 
export interface DelegateGroupDetailsCustom extends DelegateGroupDetails {
  checked: boolean
}
 
const DELEGATE_POLLING_INTERVAL_IN_MS = 5000
 
const NullRenderer = () => <></>
 
interface CustomRadioGroupProps {
  items: (IOptionProps & { checked: boolean; CustomComponent?: React.ReactElement })[]
  onClick: (mode: DelegateOptions) => void
}
 
const shouldDelegateBeChecked = (delegateSelectors: Array<string>, tags: Array<string> = []) => {
  if (!delegateSelectors?.length) {
    return false
  }
  const delegateSelectorsMap = delegateSelectors.reduce((acc: Record<string, boolean>, delegateSelector) => {
    acc[delegateSelector] = false
    return acc
  }, {})
  for (const tag of tags) {
    delete delegateSelectorsMap[tag]
  }
  return !Object.keys(delegateSelectorsMap).length
}
 
const CustomRadioGroup: React.FC<CustomRadioGroupProps> = props => {
  const { items, onClick } = props
  return (
    <Container>
      {items.map((item, index) => {
        const { CustomComponent = NullRenderer } = item
        return (
          <Layout.Horizontal
            margin={{ bottom: 'medium' }}
            flex={{ alignItems: 'center', justifyContent: 'flex-start' }}
            key={index}
            data-tooltip-id={`${item.label?.split(' ').join('')}`}
          >
            <Radio
              label={item.label}
              value={item.value}
              color={Color.GREY_800}
              className={css.radio}
              checked={item.checked}
              disabled={item.disabled}
              onClick={() => onClick(item.value as DelegateOptions)}
            />
            <HarnessDocTooltip tooltipId={`${item.label?.split(' ').join('')}`} useStandAlone={true} />
            {CustomComponent}
          </Layout.Horizontal>
        )
      })}
    </Container>
  )
}
 
export const DelegateSelector: React.FC<DelegateSelectorProps> = props => {
  const {
    mode,
    setMode,
    delegateSelectors = [],
    setDelegateSelectors,
    setDelegatesFound,
    delegateSelectorMandatory = false
  } = props
  const [formattedData, setFormattedData] = useState<DelegateGroupDetailsCustom[]>([])
  const { getString } = useStrings()
  const { accountId } = useParams<AccountPathProps>()
  const { orgIdentifier, projectIdentifier } = props
 
  const scope = { projectIdentifier, orgIdentifier }
 
  const queryParams = {
    accountId,
    orgId: orgIdentifier,
    projectId: projectIdentifier
  }
 
  const {
    data: apiData,
    loading,
    error,
    refetch
  } = useGetDelegatesUpTheHierarchy({
    queryParams
  })
 
  const [data, setData] = useState(apiData)
  const { openDelegateModal } = useCreateDelegateModal({
    onClose: refetch
  })
  const { showError } = useToaster()
 
  const getParsedData = (): DelegateGroupDetailsCustom[] => {
    return ((data as RestResponseDelegateGroupListing)?.resource?.delegateGroupDetails || []).map(
      delegateGroupDetails => ({
        ...delegateGroupDetails,
        checked: shouldDelegateBeChecked(delegateSelectors, [
          ...Object.keys(defaultTo(delegateGroupDetails.groupImplicitSelectors, {})),
          ...defaultTo(delegateGroupDetails.groupCustomSelectors, [])
        ])
      })
    )
  }
 
  // used to set data only if no error occurs
  // previous data should persist in data state even if api fails while polling
  useEffect(() => {
    if (apiData) {
      setData(apiData)
    }
  }, [apiData])
 
  // show error in toast if error occurs while polling
  useEffect(() => {
    if (error && data) {
      showError(
        getString('connectors.delegate.couldNotFetch', {
          pollingInterval: `${DELEGATE_POLLING_INTERVAL_IN_MS / 1000} ${getString('common.seconds')}`
        }),
        DELEGATE_POLLING_INTERVAL_IN_MS
      )
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [error])
 
  // polling logic
  useEffect(() => {
    let id: NodeJS.Timeout
    if (!loading) {
      id = setTimeout(() => refetch(), DELEGATE_POLLING_INTERVAL_IN_MS)
    }
    return () => clearTimeout(id)
  }, [data, loading, refetch])
 
  useEffect(() => {
    const parsedData = getParsedData()
 
    parsedData.sort((parsedDataItemA, parsedDataItemB) => {
      const [checkedA, checkedB] = [parsedDataItemA.checked, parsedDataItemB.checked]
      Iif (checkedA && !checkedB) {
        return -1
      }
      if (checkedB && !checkedA) {
        return 1
      }
      return 0
    })
 
    setFormattedData(parsedData)
  }, [delegateSelectors, data])
 
  useEffect(() => {
    const totalChecked = formattedData.filter(item => item.checked).length
    const isAtleastOneActive = formattedData.filter(item => item.checked && item.activelyConnected).length > 0
    const isSaveButtonDisabled = mode === DelegateOptions.DelegateOptionsSelective && delegateSelectors.length === 0
    if (
      !loading &&
      !isSaveButtonDisabled &&
      (!formattedData.length || (mode === DelegateOptions.DelegateOptionsSelective && !totalChecked))
    ) {
      setDelegatesFound(DelegatesFoundState.NotFound)
    } else {
      setDelegatesFound(
        totalChecked && !isAtleastOneActive ? DelegatesFoundState.NotConnected : DelegatesFoundState.ActivelyConnected
      )
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [mode, formattedData])
 
  const DelegateSelectorCountComponent = useMemo(() => {
    const count = formattedData.filter(item => item.checked).length
    const total = formattedData.length
    if (!total) {
      return <></>
    }
    return (
      <Text data-name="delegateMatchingText">{`${count}/${total} ${getString(
        'connectors.delegate.matchingDelegates'
      )}`}</Text>
    )
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [formattedData])
 
  const DelegateSelectorsCustomComponent = useMemo(
    () => (
      <DelegateSelectors
        className={css.formInput}
        fill
        allowNewTag={false}
        placeholder={getString('connectors.delegate.delegateselectionPlaceholder')}
        selectedItems={delegateSelectors}
        onChange={selectors => {
          setDelegateSelectors(selectors as Array<string>)
          if (selectors.length) {
            setMode(DelegateOptions.DelegateOptionsSelective)
          }
        }}
        pollingInterval={DELEGATE_POLLING_INTERVAL_IN_MS}
        {...scope}
      ></DelegateSelectors>
    ),
    // eslint-disable-next-line react-hooks/exhaustive-deps
    [delegateSelectors]
  )
 
  const CustomComponent = useMemo(() => {
    return (
      <Layout.Horizontal
        flex={{ alignItems: 'center', justifyContent: 'flex-start' }}
        spacing="small"
        margin={{ bottom: 'medium' }}
      >
        {DelegateSelectorsCustomComponent}
        {DelegateSelectorCountComponent}
      </Layout.Horizontal>
    )
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [formattedData])
 
  const options: CustomRadioGroupProps['items'] = useMemo(
    () => [
      {
        label: getString('connectors.delegate.delegateSelectorAny'),
        value: DelegateOptions.DelegateOptionsAny,
        checked: mode === DelegateOptions.DelegateOptionsAny,
        disabled: delegateSelectorMandatory
      },
      {
        label: getString('connectors.delegate.delegateSelectorSelective'),
        value: DelegateOptions.DelegateOptionsSelective,
        checked: mode === DelegateOptions.DelegateOptionsSelective
      }
    ],
    // eslint-disable-next-line react-hooks/exhaustive-deps
    [mode, formattedData]
  )
  const delegateSelectorTableProps: DelegateSelectorTableProps = {
    data: data ? formattedData : data,
    loading,
    error,
    refetch,
    showMatchesSelectorColumn: mode === DelegateOptions.DelegateOptionsSelective
  }
 
  const permissionRequestNewDelegate = {
    resourceScope: {
      accountIdentifier: accountId,
      orgIdentifier,
      projectIdentifier
    },
    permission: PermissionIdentifier.UPDATE_DELEGATE,
    resource: {
      resourceType: ResourceType.DELEGATE
    }
  }
 
  return (
    <Layout.Vertical className={css.delegateSelectorContainer}>
      <Text color={Color.GREY_800} margin={{ top: 'xlarge', bottom: 'medium' }}>
        {getString('connectors.delegate.configure')}
      </Text>
      <CustomRadioGroup items={options} onClick={newMode => setMode(newMode)} />
      {CustomComponent}
      <Layout.Horizontal flex={{ justifyContent: 'space-between' }} margin={{ bottom: 'medium' }}>
        <Text font={{ size: 'medium', weight: 'semi-bold' }} color={Color.BLACK}>
          {getString('connectors.delegate.testDelegateConnectivity')}
        </Text>
        <RbacButton
          icon="plus"
          variation={ButtonVariation.SECONDARY}
          withoutBoxShadow
          font={{ weight: 'semi-bold' }}
          iconProps={{ margin: { right: 'xsmall' } }}
          permission={permissionRequestNewDelegate}
          onClick={() => openDelegateModal()}
          data-name="installNewDelegateButton"
        >
          {getString('connectors.testConnectionStep.installNewDelegate')}
        </RbacButton>
      </Layout.Horizontal>
      <DelegateSelectorTable {...delegateSelectorTableProps} />
    </Layout.Vertical>
  )
}