All files / modules/30-delegates/pages/delegates DelegateListing.tsx

65.93% Statements 120/182
47.06% Branches 80/170
48.39% Functions 15/31
66.11% Lines 119/180

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              10x   10x   10x 10x                     10x   10x 10x   10x 10x     10x           10x   10x 10x         10x   10x 10x 10x 10x 10x 10x 10x 10x 10x   10x   10x   10x   10x                 10x 27x 27x 27x 27x 27x 27x 27x 27x 27x 27x 27x 27x 27x 27x   27x       27x   7x                     27x 27x   27x 7x 7x             27x                   27x 7x 7x     27x 2x           2x   8x         27x   7x 7x 7x   7x                               7x 7x 7x 7x 6x 6x 6x 8x       8x   6x     1x 1x   1x   7x             27x 9x   9x 7x           9x 7x       27x                                               27x                             27x                         27x         27x           27x 2x                                           27x           27x           27x                 27x 1x                                       1x 1x 1x                                                                                                           27x             27x                           27x       27x                                           27x 27x 27x 27x 27x 27x 27x 27x   27x                       27x     27x         1x           27x                                                           1x 1x                                                                 9x                                                   10x  
/*
 * Copyright 2022 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, useCallback, useMemo } from 'react'
import type { GetDataError } from 'restful-react'
import { get, set, pick, debounce } from 'lodash-es'
import type { FormikErrors } from 'formik'
import { useParams } from 'react-router-dom'
import {
  Container,
  Layout,
  FlexExpander,
  ExpandingSearchInput,
  SelectOption,
  FormInput,
  MultiSelectOption,
  PageError,
  shouldShowError
} from '@wings-software/uicore'
import { useModalHook } from '@harness/use-modal'
 
import { Dialog } from '@blueprintjs/core'
import { PageSpinner } from '@common/components'
import type { UseGetMockData } from '@common/utils/testUtils'
import FilterSelector from '@common/components/Filter/FilterSelector/FilterSelector'
import { Filter, FilterRef } from '@common/components/Filter/Filter'
import type { CrudOperation } from '@common/components/Filter/FilterCRUD/FilterCRUD'
import type { FilterInterface, FilterDataInterface } from '@common/components/Filter/Constants'
import {
  removeNullAndEmpty,
  isObjectEmpty,
  UNSAVED_FILTER,
  flattenObject
} from '@common/components/Filter/utils/FilterUtils'
import { ContainerSpinner } from '@common/components/ContainerSpinner/ContainerSpinner'
 
import { useStrings } from 'framework/strings'
import {
  GetDelegateGroupsNGV2WithFilterQueryParams,
  useGetDelegateGroupsNGV2WithFilter,
  DelegateGroupDetails
} from 'services/portal'
import { usePostFilter, useUpdateFilter, useDeleteFilter, useGetFilterList } from 'services/cd-ng'
import type { FilterDTO, ResponsePageFilterDTO, Failure, DelegateFilterProperties } from 'services/cd-ng'
import useCreateDelegateModal from '@delegates/modals/DelegateModal/useCreateDelegateModal'
import DelegateInstallationError from '@delegates/components/CreateDelegate/components/DelegateInstallationError/DelegateInstallationError'
import { useToaster, StringUtils } from '@common/exports'
import DelegatesEmptyState from '@delegates/images/DelegatesEmptyState.svg'
import RbacButton from '@rbac/components/Button/Button'
import { PermissionIdentifier } from '@rbac/interfaces/PermissionIdentifier'
import { ResourceType } from '@rbac/interfaces/ResourceType'
import useRBACError from '@rbac/utils/useRBACError/useRBACError'
import DelegateListingItem, { DelegateListingHeader } from './DelegateListingItem'
 
import css from './DelegatesPage.module.scss'
 
const POLLING_INTERVAL = 10000
 
const statusTypes = ['ENABLED', 'WAITING_FOR_APPROVAL', 'DISABLED', 'DELETED']
 
const fullSizeContentStyle: React.CSSProperties = {
  width: '100%',
  height: '100%'
}
 
interface DelegatesListProps {
  filtersMockData?: UseGetMockData<ResponsePageFilterDTO>
}
 
export const DelegateListing: React.FC<DelegatesListProps> = ({ filtersMockData }) => {
  const { getRBACErrorMessage } = useRBACError()
  const { getString } = useStrings()
  const { accountId, projectIdentifier, orgIdentifier, module } = useParams<Record<string, string>>()
  const [searchTerm, setSearchTerm] = useState('')
  const [showDelegateLoader, setShowDelegateLoader] = useState<boolean>(true)
  const [page, setPage] = useState(0)
  const [filters, setFilters] = useState<FilterDTO[]>()
  const [appliedFilter, setAppliedFilter] = useState<FilterDTO | null>()
  const { showError } = useToaster()
  const [delegateGroups, setDelegateGroups] = useState<Array<DelegateGroupDetails>>([])
  const [delegateFetchError, setDelegateFetchError] = useState<GetDataError<Failure | Error>>()
  const [isRefreshingFilters, setIsRefreshingFilters] = useState<boolean>(false)
  const [isFilterOpen, setIsFilterOpen] = useState<boolean>(false)
  const filterRef = React.useRef<FilterRef<FilterDTO> | null>(null)
 
  const [troubleshoterOpen, setOpenTroubleshoter] = useState<{ isConnected: boolean | undefined } | undefined>(
    undefined
  )
 
  const queryParams: GetDelegateGroupsNGV2WithFilterQueryParams = useMemo(
    () =>
      ({
        accountId,
        orgId: orgIdentifier,
        projectId: projectIdentifier,
        module,
        pageIndex: page,
        pageSize: 10,
        searchTerm: ''
      } as GetDelegateGroupsNGV2WithFilterQueryParams),
    [accountId, module, orgIdentifier, projectIdentifier, page]
  )
  const { mutate: fetchDelegates, loading: isFetchingDelegates } = useGetDelegateGroupsNGV2WithFilter({ queryParams })
  const { openDelegateModal } = useCreateDelegateModal()
 
  useEffect(() => {
    setShowDelegateLoader(true)
    refetchDelegates(queryParams)
  }, [queryParams])
 
  const {
    loading: isFetchingFilters,
    data: fetchedFilterResponse,
    refetch: refetchFilterList
  } = useGetFilterList({
    queryParams: {
      accountIdentifier: accountId,
      projectIdentifier,
      orgIdentifier,
      type: 'Delegate'
    },
    mock: filtersMockData
  })
 
  useEffect(() => {
    setFilters(fetchedFilterResponse?.data?.content || [])
    setIsRefreshingFilters(isFetchingFilters)
  }, [fetchedFilterResponse])
 
  const getStatusSelectOptions = (values?: any[]): SelectOption[] => {
    const labelMap = {
      ENABLED: getString('enabledLabel'),
      DISABLED: getString('delegates.delGroupStatus.DISABLED'),
      WAITING_FOR_APPROVAL: getString('delegates.delGroupStatus.WAITING_FOR_APPROVAL'),
      DELETED: getString('deleted')
    }
    return values
      ? values.map(item => {
          return { label: get(labelMap, item, ''), value: item }
        })
      : []
  }
 
  const refetchDelegates = useCallback(
    async (params: GetDelegateGroupsNGV2WithFilterQueryParams, filter?): Promise<void> => {
      const { delegateGroupIdentifier, delegateName, delegateType, description, hostName, status, tags } = filter || {}
      Eif (params.searchTerm === '') {
        delete params.searchTerm
      }
      const requestBodyPayload = Object.assign(
        filter
          ? {
              delegateGroupIdentifier,
              delegateName,
              delegateType,
              description,
              hostName,
              status,
              tags
            }
          : {},
        {
          filterType: 'Delegate'
        }
      )
      const sanitizedFilterRequest = removeNullAndEmpty(requestBodyPayload)
      try {
        setDelegateFetchError(undefined)
        const delegateResponse = await fetchDelegates(sanitizedFilterRequest, { queryParams: params })
        const delGroups = delegateResponse?.resource?.delegateGroupDetails || []
        Eif (delGroups) {
          delGroups.forEach((delegateGroup: DelegateGroupDetails) => {
            const delName = `${get(delegateGroup, 'groupName', '')} ${getString('delegate.instancesCount', {
              count: delegateGroup?.delegateInstanceDetails?.length,
              total: ''
            })}`
            set(delegateGroup, 'delegateName', delName)
          })
          setDelegateGroups(delGroups)
        }
      } catch (e) {
        Eif (shouldShowError(e)) {
          showError(getRBACErrorMessage(e))
        }
        setDelegateFetchError(e)
      } finally {
        setShowDelegateLoader(false)
      }
    },
    [fetchDelegates]
  )
 
  // Add polling
  useEffect(() => {
    let timeoutId = 0
 
    if (!isFetchingDelegates && !delegateFetchError && !isFilterOpen) {
      timeoutId = window.setTimeout(() => {
        setShowDelegateLoader(false)
        refetchDelegates({ ...queryParams, searchTerm }, appliedFilter?.filterProperties)
      }, POLLING_INTERVAL)
    }
 
    return () => {
      clearTimeout(timeoutId)
    }
  }, [isFetchingDelegates, delegateFetchError, refetchDelegates, isFilterOpen])
 
  const formatPayload = (data: FilterDataInterface<DelegateFilterProperties, FilterInterface>, isUpdate: boolean) => {
    const {
      metadata: { name: _name, filterVisibility, identifier },
      formValues: { delegateGroupIdentifier, delegateName, delegateType, description, hostName, status, tags }
    } = data
    return {
      name: _name,
      identifier: isUpdate ? identifier : StringUtils.getIdentifierFromName(_name),
      projectIdentifier,
      orgIdentifier,
      filterVisibility: filterVisibility,
      filterProperties: {
        filterType: 'Delegate',
        delegateGroupIdentifier,
        delegateName,
        delegateType,
        description,
        hostName,
        status,
        tags
      } as DelegateFilterProperties
    }
  }
 
  const handleSaveOrUpdate = async (
    isUpdate: boolean,
    data: FilterDataInterface<DelegateFilterProperties, FilterInterface>
  ): Promise<void> => {
    await setIsRefreshingFilters(true)
    const requestBodyPayload = formatPayload(data, isUpdate)
    const saveOrUpdateHandler = filterRef.current?.saveOrUpdateFilterHandler
    if (saveOrUpdateHandler && typeof saveOrUpdateHandler === 'function') {
      const updatedFilter = await saveOrUpdateHandler(isUpdate, requestBodyPayload)
      setAppliedFilter(updatedFilter)
    }
    await refetchFilterList()
    setIsRefreshingFilters(false)
  }
 
  const handleDelete = async (identifier: string): Promise<void> => {
    setIsRefreshingFilters(true)
    const deleteHandler = filterRef.current?.deleteFilterHandler
    if (deleteHandler && typeof deleteFilter === 'function') {
      await deleteHandler(identifier)
    }
    if (identifier === appliedFilter?.identifier) {
      reset()
    }
    await refetchFilterList()
    setIsRefreshingFilters(false)
  }
 
  const unsavedFilter = {
    name: UNSAVED_FILTER,
    identifier: StringUtils.getIdentifierFromName(UNSAVED_FILTER)
  }
 
  const handleFilterClick = (identifier: string): void => {
    if (identifier !== unsavedFilter.identifier) {
      setAppliedFilter(getFilterByIdentifier(identifier))
    }
  }
 
  const DelegateForm = (): React.ReactElement => {
    return (
      <>
        <FormInput.Text name={'delegateName'} label={getString('delegate.delegateName')} key={'delegateName'} />
        <FormInput.Text name={'delegateType'} label={getString('delegate.delegateType')} key={'delegateType'} />
        <FormInput.Text name={'description'} label={getString('description')} key={'description'} />
        <FormInput.Text name={'hostName'} label={getString('delegate.hostName')} key={'hostName'} />
        <FormInput.Select
          items={getStatusSelectOptions(statusTypes)}
          name={'status'}
          label={getString('status')}
          key={'status'}
        />
        <FormInput.Text
          name={'delegateGroupIdentifier'}
          label={getString('delegates.delegateIdentifier')}
          key={'delegateGroupIdentifier'}
        />
        <FormInput.KVTagInput name="tags" label={getString('tagsLabel')} key="tags" />
      </>
    )
  }
 
  const { mutate: createFilter } = usePostFilter({
    queryParams: {
      accountIdentifier: accountId
    }
  })
 
  const { mutate: updateFilter } = useUpdateFilter({
    queryParams: {
      accountIdentifier: accountId
    }
  })
 
  const { mutate: deleteFilter } = useDeleteFilter({
    queryParams: {
      accountIdentifier: accountId,
      projectIdentifier,
      orgIdentifier,
      type: 'Delegate'
    }
  })
 
  const [openFilterDrawer, hideFilterDrawer] = useModalHook(() => {
    const onFilterApply = (formData: Record<string, any>) => {
      if (!isObjectEmpty(formData)) {
        const filterFromFormData = { ...formData }
        const updatedQueryParams = {
          ...queryParams,
          searchTerm,
          pageIndex: 0
        }
        setShowDelegateLoader(true)
        refetchDelegates(updatedQueryParams, filterFromFormData)
        setAppliedFilter({ ...unsavedFilter, filterProperties: filterFromFormData })
        setPage(0)
        hideFilterDrawer()
        setIsFilterOpen(false)
      } else {
        showError(getString('filters.invalidCriteria'))
      }
    }
 
    const { delegateName, delegateGroupIdentifier, delegateType, description, hostName, status, tags } =
      (appliedFilter?.filterProperties as any) || {}
    const { name = '', filterVisibility } = appliedFilter || {}
    return isFetchingFilters ? (
      <PageSpinner />
    ) : (
      <Filter<DelegateFilterProperties, FilterDTO>
        onApply={onFilterApply}
        onClose={() => {
          hideFilterDrawer()
          setIsFilterOpen(false)
          refetchFilterList()
        }}
        filters={filters}
        initialFilter={{
          formValues: {
            delegateName,
            delegateGroupIdentifier,
            delegateType,
            description,
            hostName,
            status,
            tags
          },
          metadata: {
            name,
            filterVisibility: filterVisibility,
            identifier: appliedFilter?.identifier || '',
            filterProperties: {}
          }
        }}
        onSaveOrUpdate={handleSaveOrUpdate}
        onDelete={handleDelete}
        onFilterSelect={handleFilterClick}
        isRefreshingFilters={isRefreshingFilters}
        formFields={<DelegateForm />}
        onValidate={(values: Partial<DelegateFilterProperties>): FormikErrors<Partial<DelegateFilterProperties>> => {
          const errors: FormikErrors<{ description?: MultiSelectOption[] }> = {}
          if (values.description === '') {
            errors.description = ''
          }
          return errors
        }}
        dataSvcConfig={
          new Map<CrudOperation, (...rest: any[]) => Promise<any>>([
            ['ADD', createFilter],
            ['UPDATE', updateFilter],
            ['DELETE', deleteFilter]
          ])
        }
        onSuccessfulCrudOperation={refetchFilterList}
        ref={filterRef}
        onClear={reset}
      />
    )
  }, [isRefreshingFilters, filters, appliedFilter, searchTerm, queryParams])
 
  const reset = (): void => {
    setShowDelegateLoader(true)
    refetchDelegates(queryParams)
    setAppliedFilter(undefined)
    setDelegateFetchError(undefined)
  }
 
  const debouncedDelegateSearch = useCallback(
    debounce((query: string): void => {
      /* For a non-empty query string, always start from first page(index 0) */
      const updatedQueryParams = {
        ...queryParams,
        searchTerm: query,
        pageIndex: 0
      }
      setShowDelegateLoader(true)
      refetchDelegates(updatedQueryParams, appliedFilter?.filterProperties)
    }, 500),
    [refetchDelegates, appliedFilter?.filterProperties]
  )
 
  const getFilterByIdentifier = (identifier: string): FilterDTO | undefined =>
    /* istanbul ignore if */
    filters?.find((filter: FilterDTO) => filter.identifier?.toLowerCase() === identifier.toLowerCase())
 
  const handleFilterSelection = (
    option: SelectOption,
    event?: React.SyntheticEvent<HTMLElement, Event> | undefined
  ): void => {
    event?.stopPropagation()
    event?.preventDefault()
    /* istanbul ignore else */
    Iif (option.value) {
      const selectedFilter = getFilterByIdentifier(option.value?.toString())
      setAppliedFilter(selectedFilter)
      const updatedQueryParams = {
        ...queryParams,
        searchTerm,
        pageIndex: 0
      }
      setShowDelegateLoader(true)
      refetchDelegates(updatedQueryParams, selectedFilter?.filterProperties)
    } else {
      reset()
    }
  }
 
  const fieldToLabelMapping = new Map<string, string>()
  fieldToLabelMapping.set('delegateGroupIdentifier', getString('delegates.delegateIdentifier'))
  fieldToLabelMapping.set('delegateName', getString('delegate.delegateName'))
  fieldToLabelMapping.set('delegateType', getString('delegate.delegateType'))
  fieldToLabelMapping.set('description', getString('description'))
  fieldToLabelMapping.set('hostName', getString('delegate.hostName'))
  fieldToLabelMapping.set('status', getString('status'))
  fieldToLabelMapping.set('tags', getString('delegate.delegateTags'))
 
  const permissionRequestNewDelegate = {
    resourceScope: {
      accountIdentifier: accountId,
      orgIdentifier,
      projectIdentifier
    },
    permission: PermissionIdentifier.UPDATE_DELEGATE,
    resource: {
      resourceType: ResourceType.DELEGATE
    }
  }
 
  const hideHeader = delegateGroups.length === 0 && !appliedFilter && !searchTerm
 
  const newDelegateBtn = (
    <RbacButton
      intent="primary"
      text={hideHeader ? getString('delegates.createDelegate') : getString('delegates.newDelegate')}
      icon="plus"
      permission={permissionRequestNewDelegate}
      onClick={() => openDelegateModal()}
      id="newDelegateBtn"
      data-testid="newDelegateButton"
    />
  )
 
  return (
    <Container height="100%">
      <Dialog
        isOpen={!!troubleshoterOpen}
        enforceFocus={false}
        style={{ width: '680px', height: '100%' }}
        onClose={() => setOpenTroubleshoter(undefined)}
      >
        <DelegateInstallationError showDelegateInstalledMessage={false} />
      </Dialog>
      {!hideHeader && (
        <Layout.Horizontal className={css.header}>
          {newDelegateBtn}
          <FlexExpander />
          <Layout.Horizontal spacing="xsmall">
            <ExpandingSearchInput
              alwaysExpanded
              width={250}
              placeholder={getString('search')}
              throttle={200}
              onChange={text => {
                debouncedDelegateSearch(text)
                setSearchTerm(text.trim())
              }}
              className={css.search}
            />
            <FilterSelector<FilterDTO>
              appliedFilter={appliedFilter}
              filters={filters}
              onFilterBtnClick={() => {
                openFilterDrawer()
                setIsFilterOpen(true)
              }}
              onFilterSelect={handleFilterSelection}
              fieldToLabelMapping={fieldToLabelMapping}
              filterWithValidFields={removeNullAndEmpty(
                pick(flattenObject(appliedFilter?.filterProperties || {}), ...fieldToLabelMapping.keys())
              )}
            />
          </Layout.Horizontal>
        </Layout.Horizontal>
      )}
      <Layout.Vertical className={css.listBody}>
        {showDelegateLoader ? (
          <Container style={fullSizeContentStyle}>
            <ContainerSpinner />
          </Container>
        ) : delegateFetchError && shouldShowError(delegateFetchError) ? (
          <div style={{ paddingTop: '200px' }}>
            <PageError
              message={(delegateFetchError?.data as Error)?.message || delegateFetchError?.message}
              onClick={(e: React.MouseEvent<Element, MouseEvent>) => {
                e.preventDefault()
                e.stopPropagation()
                reset()
              }}
            />
          </div>
        ) : (
          <Container className={css.delegateListContainer}>
            {delegateGroups.length ? (
              <Container width="100%">
                <DelegateListingHeader />
                {delegateGroups.map((delegate: DelegateGroupDetails) => (
                  <DelegateListingItem
                    key={delegate.delegateGroupIdentifier}
                    delegate={delegate}
                    setOpenTroubleshoter={setOpenTroubleshoter}
                  />
                ))}
              </Container>
            ) : (
              <div className={css.emptyStateContainer}>
                <img src={DelegatesEmptyState} />
                <div className={css.emptyStateText}>
                  {projectIdentifier
                    ? getString('delegates.noDelegatesInProject')
                    : orgIdentifier
                    ? getString('delegates.noDelegatesInOrganization')
                    : getString('delegates.noDelegatesInAccount')}
                </div>
                {hideHeader && newDelegateBtn}
              </div>
            )}
          </Container>
        )}
      </Layout.Vertical>
    </Container>
  )
}
export default DelegateListing