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

63.64% Statements 98/154
35.21% Branches 50/142
38.46% Functions 10/26
63.58% Lines 96/151

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 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625              9x 9x 9x   9x 9x 9x                                   9x 9x 9x   9x 9x     9x 9x                 9x             9x 9x 9x 9x             9x 9x 9x 9x   9x 9x   9x 4x 4x     9x                 1x 1x                               9x                                                   9x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x 13x       13x                           13x         13x       13x 4x 4x             13x                   13x 4x 4x     13x   13x         13x                                 13x   4x   4x                         4x 4x 4x 4x 4x                   13x                                 13x                         13x         13x           13x 3x                   13x           13x           13x                 13x 2x                                 2x 2x 2x                                                                                                       13x 8x                       8x 8x 8x 8x 8x 8x 8x 8x 8x       8x                             8x                                                                                                                                                                                                               13x   13x                                         13x                                                                                                           8x                 9x  
/*
 * 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, useCallback, useState } from 'react'
import { useParams, useHistory } from 'react-router-dom'
import moment from 'moment'
import type { FormikErrors } from 'formik'
import { pick, get, debounce } from 'lodash-es'
import { Classes, Menu } from '@blueprintjs/core'
import {
  Card,
  Text,
  Layout,
  Container,
  Button,
  FlexExpander,
  Heading,
  Utils,
  FormInput,
  SelectOption,
  MultiSelectOption,
  ExpandingSearchInput,
  PageError,
  shouldShowError,
  useToaster,
  Page
} from '@wings-software/uicore'
import { Color } from '@harness/design-system'
import { useModalHook } from '@harness/use-modal'
import { PageSpinner } from '@common/components'
import type { UseGetMockData } from '@common/utils/testUtils'
import { StringUtils } from '@common/exports'
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 FilterSelector from '@common/components/Filter/FilterSelector/FilterSelector'
import routes from '@common/RouteDefinitions'
import type {
  DelegateConfigProps,
  ProjectPathProps,
  ModulePathParams,
  AccountPathProps
} from '@common/interfaces/RouteInterfaces'
import type { ScopingRuleDetails, GetDelegateGroupsNGV2WithFilterQueryParams } from 'services/portal'
import type { FilterDTO, DelegateProfileFilterProperties, ResponsePageFilterDTO } from 'services/cd-ng'
import {
  useListDelegateConfigsNgV2WithFilter,
  usePostFilter,
  useUpdateFilter,
  useDeleteFilter,
  useGetFilterList
} from 'services/cd-ng'
import { useStrings } from 'framework/strings'
import { ContainerSpinner } from '@common/components/ContainerSpinner/ContainerSpinner'
import { TagsViewer } from '@common/components/TagsViewer/TagsViewer'
import {
  removeNullAndEmpty,
  isObjectEmpty,
  UNSAVED_FILTER,
  flattenObject
} from '@common/components/Filter/utils/FilterUtils'
/* RBAC */
import RbacMenuItem from '@rbac/components/MenuItem/MenuItem'
import { PermissionIdentifier } from '@rbac/interfaces/PermissionIdentifier'
import { ResourceType } from '@rbac/interfaces/ResourceType'
import { usePermission } from '@rbac/hooks/usePermission'
 
import useRBACError from '@rbac/utils/useRBACError/useRBACError'
import css from './DelegatesPage.module.scss'
 
const formatProfileList = (data: any) => {
  const profiles: Array<DelegateProfileDetails> = data?.resource?.response
  return profiles
}
 
export const prepareData = (
  data: FilterDataInterface<DelegateProfileFilterProperties, FilterInterface>,
  isUpdate: boolean,
  projectIdentifier?: string,
  orgIdentifier?: string
) => {
  const {
    metadata: { name: _name, filterVisibility, identifier },
    formValues: { identifier: delegateProfileIdentifier, name, description, selectors = {} }
  } = data
  return {
    name: _name,
    identifier: isUpdate ? identifier : StringUtils.getIdentifierFromName(_name),
    projectIdentifier,
    orgIdentifier,
    filterVisibility: filterVisibility,
    filterProperties: {
      filterType: 'DelegateProfile',
      identifier: delegateProfileIdentifier,
      name,
      description,
      selectors: Object.keys(selectors)
    } as DelegateProfileFilterProperties
  }
}
 
const fullSizeContentStyle: React.CSSProperties = {
  position: 'fixed',
  top: '135px',
  left: '270px',
  width: 'calc(100% - 270px)',
  height: 'calc(100% - 135px)'
}
 
interface DelegateProfileDetails {
  uuid?: string
  identifier?: string
  accountId?: string
  name?: string
  description?: string
  primary?: boolean
  approvalRequired?: boolean
  startupScript?: string
  scopingRules?: ScopingRuleDetails[]
  selectors?: string[]
  numberOfDelegates?: number
}
 
interface DelegatesListProps {
  filtersMockData?: UseGetMockData<ResponsePageFilterDTO>
}
 
export const DelegateConfigurations: React.FC<DelegatesListProps> = ({ filtersMockData }): JSX.Element => {
  const { getRBACErrorMessage } = useRBACError()
  const { getString } = useStrings()
  const [appliedFilter, setAppliedFilter] = useState<FilterDTO | null>()
  const [filters, setFilters] = useState<FilterDTO[]>()
  const [searchParam, setSearchParam] = useState('')
  const [page, setPage] = useState(0)
  const [isRefreshingFilters, setIsRefreshingFilters] = useState<boolean>(false)
  const [delegateProfiles, setDelegateProfiles] = useState<Array<DelegateProfileDetails>>([])
  const history = useHistory()
  const filterRef = React.useRef<FilterRef<FilterDTO> | null>(null)
  const { accountId, orgIdentifier, projectIdentifier, module } = useParams<
    Partial<DelegateConfigProps & ProjectPathProps & ModulePathParams> & AccountPathProps
  >()
 
  const queryParams: GetDelegateGroupsNGV2WithFilterQueryParams = {
    accountId,
    orgId: orgIdentifier,
    projectId: projectIdentifier,
    module,
    pageIndex: page,
    pageSize: 10,
    searchTerm: ''
  } as GetDelegateGroupsNGV2WithFilterQueryParams
 
  const {
    mutate: getDelegateProfiles,
    loading: isFetchingDelegateProfiles,
    error: delegateFetchError
  } = useListDelegateConfigsNgV2WithFilter({
    accountId,
    queryParams: { orgId: orgIdentifier, projectId: projectIdentifier }
  })
 
  const getFilterByIdentifier = (identifier: string): FilterDTO | undefined =>
    /* istanbul ignore if */
    filters?.find((filter: FilterDTO) => filter.identifier?.toLowerCase() === identifier.toLowerCase())
 
  useEffect(() => {
    setPage(0)
    refetchDelegateProfiles(queryParams)
  }, [projectIdentifier, orgIdentifier])
 
  const {
    loading: isFetchingFilters,
    data: fetchedFilterResponse,
    refetch: refetchFilterList
  } = useGetFilterList({
    queryParams: {
      accountIdentifier: accountId,
      projectIdentifier,
      orgIdentifier,
      type: 'DelegateProfile'
    },
    mock: filtersMockData
  })
 
  useEffect(() => {
    setFilters(fetchedFilterResponse?.data?.content || [])
    setIsRefreshingFilters(isFetchingFilters)
  }, [fetchedFilterResponse])
 
  const { showError } = useToaster()
 
  const reset = (): void => {
    refetchDelegateProfiles(queryParams)
    setAppliedFilter(undefined)
  }
 
  const debouncedDelegateProfilesSearch = useCallback(
    debounce((query: string): void => {
      const filterProps = {
        identifier: '',
        name: '',
        description: '',
        selectors: []
      }
      if (query) {
        getDelegateProfiles(filterProps)
      } else {
        page === 0 ? getDelegateProfiles(filterProps) : setPage(0)
      }
    }, 500),
    [getDelegateProfiles, appliedFilter?.filterProperties]
  )
 
  const refetchDelegateProfiles = useCallback(
    async (params: GetDelegateGroupsNGV2WithFilterQueryParams, filter?): Promise<void> => {
      const { identifier, name, description, selectors = {} } = filter || {}
 
      const requestBodyPayload = Object.assign(
        filter
          ? {
              identifier,
              name,
              description,
              selectors: Object.keys(selectors)
            }
          : {},
        {
          filterType: 'DelegateProfile'
        }
      )
      const sanitizedFilterRequest = removeNullAndEmpty(requestBodyPayload)
      try {
        const delProfilesResponse = await getDelegateProfiles(sanitizedFilterRequest, { queryParams: params })
        const delProfiles = formatProfileList(delProfilesResponse)
        setDelegateProfiles(delProfiles)
      } catch (e) {
        if (shouldShowError(e)) {
          showError(getRBACErrorMessage(e))
        }
      }
    },
    [getDelegateProfiles]
  )
 
  const handleSaveOrUpdate = async (
    isUpdate: boolean,
    data: FilterDataInterface<DelegateProfileFilterProperties, FilterInterface>
  ): Promise<void> => {
    await setIsRefreshingFilters(true)
    const saveOrUpdateHandler = filterRef.current?.saveOrUpdateFilterHandler
    if (saveOrUpdateHandler && typeof saveOrUpdateHandler === 'function') {
      const updatedFilter = await saveOrUpdateHandler(
        isUpdate,
        prepareData(data, isUpdate, projectIdentifier, orgIdentifier)
      )
      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={'name'} label={getString('delegate.delegateConfiguration')} key={'name'} />
        <FormInput.Text name={'description'} label={getString('description')} key={'description'} />
        <FormInput.KVTagInput name={'selectors'} label={getString('delegates.selectors')} key={'selectors'} />
        <FormInput.Text name={'identifier'} label={getString('identifier')} key={'identifier'} />
      </>
    )
  }
 
  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: searchParam,
          pageIndex: 0
        }
        refetchDelegateProfiles(updatedQueryParams, filterFromFormData)
        setAppliedFilter({ ...unsavedFilter, filterProperties: filterFromFormData })
        setPage(0)
        hideFilterDrawer()
      } else {
        showError(getString('filters.invalidCriteria'))
      }
    }
 
    const { name, identifier, description, selectors } = (appliedFilter?.filterProperties as any) || {}
    const { name: filterName = '', filterVisibility } = appliedFilter || {}
    return isFetchingDelegateProfiles || isFetchingFilters ? (
      <PageSpinner />
    ) : (
      <Filter<DelegateProfileFilterProperties, FilterDTO>
        onApply={onFilterApply}
        onClose={() => {
          hideFilterDrawer()
          refetchFilterList()
        }}
        filters={filters}
        initialFilter={{
          formValues: {
            name,
            identifier,
            description,
            selectors
          },
          metadata: {
            name: filterName,
            filterVisibility: filterVisibility,
            identifier: appliedFilter?.identifier || '',
            filterProperties: {}
          }
        }}
        onSaveOrUpdate={handleSaveOrUpdate}
        onDelete={handleDelete}
        onFilterSelect={handleFilterClick}
        isRefreshingFilters={isRefreshingFilters}
        formFields={<DelegateForm />}
        onValidate={(
          values: Partial<DelegateProfileFilterProperties>
        ): FormikErrors<Partial<DelegateProfileFilterProperties>> => {
          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, searchParam, queryParams])
 
  const DelegateConfigItem = ({ profile }: { profile: DelegateProfileDetails }) => {
    const gotoDetailPage = (): void => {
      history.push(
        routes.toDelegateConfigsDetails({
          accountId,
          delegateConfigIdentifier: profile.identifier as string,
          orgIdentifier,
          projectIdentifier,
          module
        })
      )
    }
 
    const lastUpdatedAt = get(profile, 'lastUpdatedAt', 0)
    let timeAgo = moment().diff(lastUpdatedAt, 'days')
    let unitAgo = 'days'
    Eif (timeAgo < 1) {
      timeAgo = moment().diff(lastUpdatedAt, 'hours')
      unitAgo = 'hours'
      Eif (timeAgo < 1) {
        timeAgo = moment().diff(lastUpdatedAt, 'minutes')
        unitAgo = 'minutes'
      }
    }
 
    const [canAccessDelegateConfig] = usePermission(
      {
        resourceScope: {
          accountIdentifier: accountId,
          orgIdentifier,
          projectIdentifier
        },
        resource: {
          resourceType: ResourceType.DELEGATECONFIGURATION
        },
        permissions: [PermissionIdentifier.VIEW_DELEGATE_CONFIGURATION]
      },
      []
    )
 
    return (
      <Card
        elevation={2}
        interactive={true}
        onClick={() => canAccessDelegateConfig && gotoDetailPage()}
        className={css.delegateProfileElements}
      >
        <div
          style={{
            width: 250,
            height: 200,
            borderRadius: '5px',
            display: 'flex',
            flexDirection: 'column'
          }}
        >
          <Layout.Horizontal>
            <Heading
              level={2}
              style={{ fontSize: '16px', fontWeight: 500, color: '#22222A' }}
              padding={{ bottom: 'medium' }}
            >
              {profile.name}
            </Heading>
            <FlexExpander />
            <Container style={{ transform: 'translate(12px, -10px)' }} onClick={Utils.stopEvent}>
              <Button
                minimal
                icon="more"
                tooltip={
                  <Menu style={{ minWidth: 'unset' }}>
                    <RbacMenuItem
                      permission={{
                        resourceScope: {
                          accountIdentifier: accountId,
                          orgIdentifier,
                          projectIdentifier
                        },
                        resource: {
                          resourceType: ResourceType.DELEGATECONFIGURATION,
                          resourceIdentifier: profile.uuid
                        },
                        permission: PermissionIdentifier.UPDATE_DELEGATE_CONFIGURATION
                      }}
                      icon="edit"
                      text={getString('edit')}
                      onClick={() => {
                        history.push({
                          pathname: routes.toEditDelegateConfigsDetails({
                            accountId,
                            projectIdentifier,
                            orgIdentifier,
                            delegateConfigIdentifier: profile.identifier as string,
                            module
                          })
                        })
                      }}
                      className={Classes.POPOVER_DISMISS}
                    />
                  </Menu>
                }
                tooltipProps={{ isDark: true, interactionKind: 'click' }}
                style={{ color: 'var(--grey-400)', transform: 'rotate(90deg)' }}
              />
            </Container>
          </Layout.Horizontal>
          <Layout.Vertical spacing="small" style={{ flexGrow: 1 }}>
            {profile.description && <Text>{profile.description}</Text>}
            <TagsViewer tags={profile.selectors} style={{ background: '#CDF4FE' }} />
          </Layout.Vertical>
          <Container
            flex
            style={{
              borderTop: '1px solid #D9DAE6',
              padding: 'var(--spacing-small) var(--spacing-medium) var(--spacing-small)'
            }}
          >
            <FlexExpander />
          </Container>
          <Layout.Horizontal style={{ justifyContent: 'space-between' }}>
            <Text
              style={{ fontSize: '8px', color: '#6B6D85', letterSpacing: '0.285714px', fontWeight: 500 }}
              margin={{ bottom: 'small' }}
            >
              <div>{getString('delegates.usedBy')}</div>
              <div>
                {profile.numberOfDelegates} {getString('delegate.delegates')}
              </div>
            </Text>
            <Text
              style={{ fontSize: '8px', color: '#6B6D85', letterSpacing: '0.285714px', fontWeight: 500 }}
              margin={{ bottom: 'small' }}
            >
              <div>{getString('delegates.lastUpdated')}</div>
              <div>
                {timeAgo} {unitAgo} ago
              </div>
            </Text>
          </Layout.Horizontal>
        </div>
      </Card>
    )
  }
 
  const fieldToLabelMapping = new Map<string, string>()
 
  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: searchParam,
        pageIndex: 0
      }
      refetchDelegateProfiles(updatedQueryParams, selectedFilter?.filterProperties)
    } else {
      reset()
    }
  }
 
  return (
    <Container background={Color.GREY_100}>
      <Layout.Horizontal className={css.header} background={Color.WHITE}>
        <Text color={Color.ORANGE_600} font={{ size: 'normal' }} margin={{ top: 'auto', bottom: 'auto' }}>
          {getString('delegates.delegateProfilesDepricated')}
        </Text>
        <FlexExpander />
        <Layout.Horizontal spacing="xsmall">
          <ExpandingSearchInput
            alwaysExpanded
            width={250}
            placeholder={getString('search')}
            throttle={200}
            onChange={text => {
              debouncedDelegateProfilesSearch(text)
              setSearchParam(text.trim())
            }}
            className={css.search}
          />
          <FilterSelector<FilterDTO>
            appliedFilter={appliedFilter}
            filters={filters}
            onFilterBtnClick={openFilterDrawer}
            onFilterSelect={handleFilterSelection}
            fieldToLabelMapping={fieldToLabelMapping}
            filterWithValidFields={removeNullAndEmpty(
              pick(flattenObject(appliedFilter?.filterProperties || {}), ...fieldToLabelMapping.keys())
            )}
          />
        </Layout.Horizontal>
      </Layout.Horizontal>
      <Container
        style={{ width: 'calc(100vw - 270px)', overflow: 'hidden', minHeight: 'calc(100vh - 205px)' }}
        padding="xxlarge"
      >
        <Page.Body>
          {isFetchingDelegateProfiles ? (
            <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>
          ) : (
            <div className={css.delegateProfilesContainer}>
              {delegateProfiles.map(profile => (
                <DelegateConfigItem key={profile.uuid} profile={profile} />
              ))}
            </div>
          )}
        </Page.Body>
      </Container>
    </Container>
  )
}
export default DelegateConfigurations