All files / modules/70-pipeline/pages/pipelines PipelinesPage.tsx

72.36% Statements 178/246
49.49% Branches 194/392
60.61% Functions 20/33
72.36% Lines 178/246

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 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829              2x 2x                               2x 2x 2x   2x 2x 2x 2x                             2x         2x   2x 2x   2x     2x 2x 2x           2x           2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x   2x 2x 2x     2x 2x 2x 2x 2x 2x               78x 78x                                     78x 78x 78x 78x 78x 78x   78x 78x 78x     78x 78x 78x 78x   78x 78x 78x 78x 78x 78x 78x 78x 78x   78x               78x 78x 78x 78x 78x 78x 78x           78x 78x 78x   78x                                 78x   6x                             78x                               78x           78x               78x   19x 19x 19x 19x           19x 19x 19x               19x 19x         78x   78x                   78x                       78x     78x       78x 15x     78x 15x 15x     78x       78x       78x           78x                                         78x                             78x         78x 78x   78x 15x 15x 30x 30x       15x                 78x                 78x         78x 15x 15x     78x 15x     78x                                                                                                                                                                                                           78x                                 78x 78x 78x 78x 78x 78x 78x 78x 78x 78x 78x 78x 78x 78x   78x         78x                   78x 17x 17x 17x                           78x 48x 5x 2x   3x     3x   43x     78x 2x 2x 2x               2x                 2x     2x 2x       2x               78x 2x     76x                                           1x                               1x 1x                             1x 1x                                                                                                                                                                                                                                           1x                     1x                       2x  
/*
 * 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, { useCallback, useEffect, useRef, useState } from 'react'
import {
  ExpandingSearchInput,
  HarnessDocTooltip,
  Icon,
  Layout,
  OverlaySpinner,
  SelectOption,
  Text,
  GridListToggle,
  Views,
  ButtonVariation,
  DropDown,
  shouldShowError,
  PageSpinner,
  ExpandingSearchInputHandle
} from '@wings-software/uicore'
import { Color } from '@harness/design-system'
import { useModalHook } from '@harness/use-modal'
import { useHistory, useParams } from 'react-router-dom'
import type { FormikProps } from 'formik'
import { defaultTo, isEmpty, pick } from 'lodash-es'
import { Page, StringUtils, useToaster } from '@common/exports'
import routes from '@common/RouteDefinitions'
import {
  FilterDTO,
  GetFilterListQueryParams,
  GetPipelineListQueryParams,
  PagePMSPipelineSummaryResponse,
  PipelineFilterProperties,
  PMSPipelineSummaryResponse,
  ResponsePagePMSPipelineSummaryResponse,
  useDeleteFilter,
  useGetFilterList,
  useGetPipelineList,
  usePostFilter,
  useSoftDeletePipeline,
  useUpdateFilter
} from 'services/pipeline-ng'
import {
  useGetServiceListForProject,
  useGetEnvironmentListForProject,
  useGetServiceDefinitionTypes
} from 'services/cd-ng'
import { useDocumentTitle } from '@common/hooks/useDocumentTitle'
import type { UseGetMockData } from '@common/utils/testUtils'
import { String, useStrings } from 'framework/strings'
import { useAppStore } from 'framework/AppStore/AppStoreContext'
import type { PipelineType } from '@common/interfaces/RouteInterfaces'
import { Filter, FilterRef } from '@common/components/Filter/Filter'
import type { FilterDataInterface, FilterInterface } from '@common/components/Filter/Constants'
import type { CrudOperation } from '@common/components/Filter/FilterCRUD/FilterCRUD'
import FilterSelector from '@common/components/Filter/FilterSelector/FilterSelector'
import { getBuildType, getFilterByIdentifier } from '@pipeline/utils/PipelineExecutionFilterRequestUtils'
import {
  createRequestBodyPayload,
  getValidFilterArguments,
  PipelineFormType,
  getMultiSelectFormOptions
} from '@pipeline/utils/PipelineFilterRequestUtils'
import {
  isObjectEmpty,
  UNSAVED_FILTER,
  removeNullAndEmpty,
  flattenObject
} from '@common/components/Filter/utils/FilterUtils'
import { PermissionIdentifier } from '@rbac/interfaces/PermissionIdentifier'
import RbacButton from '@rbac/components/Button/Button'
import { ResourceType } from '@rbac/interfaces/ResourceType'
import GitFilters, { GitFilterScope } from '@common/components/GitFilters/GitFilters'
import { NavigatedToPage } from '@common/constants/TrackingConstants'
import { useTelemetry } from '@common/hooks/useTelemetry'
import { GitSyncStoreProvider } from 'framework/GitRepoStore/GitSyncStoreContext'
import { NGBreadcrumbs } from '@common/components/NGBreadcrumbs/NGBreadcrumbs'
import { useFeatureFlag, useFeatureFlags } from '@common/hooks/useFeatureFlag'
import { FeatureFlag } from '@common/featureFlags'
import useRBACError from '@rbac/utils/useRBACError/useRBACError'
import { NewPipelinePopover } from '@pipeline/pages/pipelines/views/NewPipelinePopover/NewPipelinePopover'
import { PipelineGridView } from './views/PipelineGridView'
import { PipelineListView } from './views/PipelineListView'
import PipelineFilterForm from '../pipeline-deployment-list/PipelineFilterForm/PipelineFilterForm'
import pipelineIllustration from './images/deploypipeline-illustration.svg'
import buildpipelineIllustration from './images/buildpipeline-illustration.svg'
import flagpipelineIllustration from './images/flagpipeline-illustration.svg'
import { deploymentTypeLabel } from './PipelineListUtils'
import css from './PipelinesPage.module.scss'
 
export enum Sort {
  DESC = 'DESC',
  ASC = 'ASC'
}
 
export enum SortFields {
  LastUpdatedAt = 'lastUpdatedAt',
  RecentActivity = 'executionSummaryInfo.lastExecutionTs',
  AZ09 = 'AZ09',
  ZA90 = 'ZA90',
  Name = 'name'
}
 
export interface CDPipelinesPageProps {
  mockData?: UseGetMockData<ResponsePagePMSPipelineSummaryResponse>
}
 
function PipelinesPage({ mockData }: CDPipelinesPageProps): React.ReactElement {
  const { getString } = useStrings()
  const sortOptions: SelectOption[] = [
    {
      label: getString('recentActivity'),
      value: SortFields.RecentActivity
    },
    {
      label: getString('lastUpdatedSort'),
      value: SortFields.LastUpdatedAt
    },
    {
      label: getString('AZ09'),
      value: SortFields.AZ09
    },
    {
      label: getString('ZA90'),
      value: SortFields.ZA90
    }
  ]
 
  const filterRef = useRef<FilterRef<FilterDTO> | null>(null)
  const [appliedFilter, setAppliedFilter] = useState<FilterDTO | null>()
  const [filters, setFilters] = useState<FilterDTO[]>()
  const [isRefreshingFilters, setIsRefreshingFilters] = useState<boolean>(false)
  const [gitFilter, setGitFilter] = useState<GitFilterScope | null>(null)
  const [error, setError] = useState<Error | null>(null)
 
  const [page, setPage] = useState(0)
  const [view, setView] = useState<Views>(Views.GRID)
  const [sort, setStort] = useState<string[]>([SortFields.LastUpdatedAt, Sort.DESC])
 
  // Set Default to LastUpdated
  const [selectedSort, setSelectedSort] = useState<SelectOption>(sortOptions[1])
  const [searchParam, setSearchParam] = useState('')
  const [pipelineList, setPipelineList] = useState<PagePMSPipelineSummaryResponse | undefined>()
  const [isFetchingMetaData, setIsFetchingMetaData] = useState<boolean>(false)
 
  const { trackEvent } = useTelemetry()
  const history = useHistory()
  const { getRBACErrorMessage } = useRBACError()
  const { showSuccess, showError } = useToaster()
  const { selectedProject, isGitSyncEnabled } = useAppStore()
  const [isLoading, setIsLoading] = useState<boolean>(false)
  const [isReseting, setIsReseting] = useState<boolean>(false)
  const [isDeleting, setIsDeleting] = useState<boolean>(false)
  const [pipelineToDelete, setPipelineToDelete] = useState<PMSPipelineSummaryResponse>()
 
  const { projectIdentifier, orgIdentifier, accountId, module } = useParams<
    PipelineType<{
      projectIdentifier: string
      orgIdentifier: string
      accountId: string
    }>
  >()
 
  const isCDEnabled = (selectedProject?.modules && selectedProject.modules?.indexOf('CD') > -1) || false
  const isCIEnabled = (selectedProject?.modules && selectedProject.modules?.indexOf('CI') > -1) || false
  const isCIModule = module === 'ci'
  const isCFModule = module === 'cf'
  const searchRef = useRef<ExpandingSearchInputHandle>({} as ExpandingSearchInputHandle)
  const { NG_NATIVE_HELM } = useFeatureFlags()
  const emptyStagePipelineImage = isCIModule
    ? buildpipelineIllustration
    : isCFModule
    ? flagpipelineIllustration
    : pipelineIllustration
 
  const templatesFeatureFlagEnabled = useFeatureFlag(FeatureFlag.NG_TEMPLATES)
  const pipelineTemplatesFeatureFlagEnabled = useFeatureFlag(FeatureFlag.NG_PIPELINE_TEMPLATE)
  const isPipelineTemplateEnabled = templatesFeatureFlagEnabled && pipelineTemplatesFeatureFlagEnabled
 
  const goToPipelineDetail = useCallback(
    (/* istanbul ignore next */ pipeline?: PMSPipelineSummaryResponse) => {
      history.push(
        routes.toPipelineDeploymentList({
          projectIdentifier,
          orgIdentifier,
          pipelineIdentifier: pipeline?.identifier || '-1',
          accountId,
          module,
          branch: pipeline?.gitDetails?.branch,
          repoIdentifier: pipeline?.gitDetails?.repoIdentifier
        })
      )
    },
    [projectIdentifier, orgIdentifier, history, accountId]
  )
 
  const goToPipeline = useCallback(
    (pipeline?: PMSPipelineSummaryResponse) => {
      history.push(
        routes.toPipelineStudio({
          projectIdentifier,
          orgIdentifier,
          pipelineIdentifier: pipeline?.identifier || '-1',
          accountId,
          module,
          branch: pipeline?.gitDetails?.branch,
          repoIdentifier: pipeline?.gitDetails?.repoIdentifier
        })
      )
    },
    [projectIdentifier, orgIdentifier, history, accountId]
  )
 
  const defaultQueryParamsForPiplines = {
    accountIdentifier: accountId,
    projectIdentifier,
    module,
    orgIdentifier,
    searchTerm: searchParam,
    page,
    sort,
    size: 20,
    ...(gitFilter?.repo &&
      gitFilter.branch && {
        repoIdentifier: gitFilter.repo,
        branch: gitFilter.branch
      })
  }
 
  const { mutate: reloadPipelines, cancel } = useGetPipelineList({
    queryParams: defaultQueryParamsForPiplines,
    queryParamStringifyOptions: { arrayFormat: 'comma' },
    mock: mockData
  })
 
  const { mutate: deletePipeline } = useSoftDeletePipeline({
    queryParams: {
      accountIdentifier: accountId,
      orgIdentifier,
      projectIdentifier
    }
  })
 
  const fetchPipelines = useCallback(
    async (params?: GetPipelineListQueryParams, formData?: PipelineFilterProperties): Promise<void> => {
      try {
        cancel()
        setError(null)
        const filter = Object.assign(
          {
            filterType: 'PipelineSetup'
          },
          isObjectEmpty(formData || {}) ? appliedFilter?.filterProperties : formData
        ) as PipelineFilterProperties
        const { status, data } = await reloadPipelines(filter, { queryParams: params })
        Eif (status === 'SUCCESS') {
          setPipelineList(data)
        }
      } catch (e) {
        if (shouldShowError(e)) {
          showError(getRBACErrorMessage(e), undefined, 'pipeline.fetch.pipeline.error')
          setError(e)
        }
      }
      setIsLoading(false)
      setIsReseting(false)
    },
    [reloadPipelines, showError, cancel, appliedFilter]
  )
 
  useDocumentTitle([getString('pipelines')])
 
  const reset = (): void => {
    searchRef.current.clear()
    setAppliedFilter(null)
    setGitFilter(null)
    setError(null)
    setSearchParam('')
    setIsReseting(true)
  }
 
  /* #region FIlter CRUD operations */
  const defaultQueryParamsForFilters: GetFilterListQueryParams = {
    accountIdentifier: accountId,
    projectIdentifier,
    orgIdentifier,
    type: 'PipelineSetup'
  }
 
  const {
    loading: isFetchingFilters,
    data: fetchedFilterResponse,
    error: errorFetchingFilters,
    refetch: refetchFilterList
  } = useGetFilterList({
    queryParams: defaultQueryParamsForFilters
  })
  Iif (errorFetchingFilters && shouldShowError(errorFetchingFilters)) {
    showError(getRBACErrorMessage(errorFetchingFilters), undefined, 'pipeline.fetch.filter.error')
  }
 
  useEffect(() => {
    trackEvent(NavigatedToPage.PipelinesPage, {})
  }, [])
 
  useEffect(() => {
    setFilters(fetchedFilterResponse?.data?.content || [])
    setIsRefreshingFilters(isFetchingFilters)
  }, [fetchedFilterResponse])
 
  const { mutate: createFilter } = usePostFilter({
    queryParams: defaultQueryParamsForFilters
  })
 
  const { mutate: updateFilter } = useUpdateFilter({
    queryParams: defaultQueryParamsForFilters
  })
 
  const { mutate: deleteFilter } = useDeleteFilter({
    queryParams: defaultQueryParamsForFilters
  })
  /* #endregion */
 
  /* #region Filter interaction callback handlers */
  const handleSaveOrUpdate = async (
    isUpdate: boolean,
    // eslint-disable-next-line @typescript-eslint/no-shadow
    data: FilterDataInterface<PipelineFormType, FilterInterface>
  ): Promise<void> => {
    setIsRefreshingFilters(true)
    const requestBodyPayload = createRequestBodyPayload({
      isUpdate,
      data,
      projectIdentifier,
      orgIdentifier
    })
    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)
  }
 
  /* #endregion CRUD filter interactions */
 
  const unsavedFilter = {
    name: UNSAVED_FILTER,
    identifier: StringUtils.getIdentifierFromName(UNSAVED_FILTER)
  }
 
  const { data: deploymentTypeResponse, loading: isFetchingDeploymentTypes } = useGetServiceDefinitionTypes({})
  const [deploymentTypeSelectOptions, setDeploymentTypeSelectOptions] = React.useState<SelectOption[]>([])
 
  React.useEffect(() => {
    Eif (!isEmpty(deploymentTypeResponse?.data) && deploymentTypeResponse?.data) {
      const options: SelectOption[] = deploymentTypeResponse.data
        .filter(deploymentType => deploymentType in deploymentTypeLabel)
        .map(type => ({
          label: getString(deploymentTypeLabel[type]),
          value: type as string
        }))
      setDeploymentTypeSelectOptions(options)
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [deploymentTypeResponse?.data])
 
  const {
    data: servicesResponse,
    loading: isFetchingServices,
    refetch: fetchServices
  } = useGetServiceListForProject({
    queryParams: { accountId, orgIdentifier, projectIdentifier },
    lazy: true
  })
 
  const {
    data: environmentsResponse,
    loading: isFetchingEnvironments,
    refetch: fetchEnvironments
  } = useGetEnvironmentListForProject({
    queryParams: { accountId, orgIdentifier, projectIdentifier },
    lazy: true
  })
 
  useEffect(() => {
    fetchServices()
    fetchEnvironments()
  }, [projectIdentifier])
 
  useEffect(() => {
    setIsFetchingMetaData(isFetchingDeploymentTypes && isFetchingServices && isFetchingEnvironments)
  }, [isFetchingDeploymentTypes, isFetchingServices, isFetchingEnvironments])
 
  const [openFilterDrawer, hideFilterDrawer] = useModalHook(() => {
    const onApply = (inputFormData: FormikProps<PipelineFormType>['values']) => {
      if (!isObjectEmpty(inputFormData)) {
        const filterFromFormData = getValidFilterArguments({ ...inputFormData })
        setAppliedFilter({ ...unsavedFilter, filterProperties: filterFromFormData || {} })
        hideFilterDrawer()
      } else {
        showError(getString('filters.invalidCriteria'), undefined, 'pipeline.invalid.criteria.error')
      }
    }
 
    const handleFilterClick = (identifier: string): void => {
      if (identifier !== unsavedFilter.identifier) {
        const selectedFilter = getFilterByIdentifier(identifier, filters)
        setAppliedFilter(selectedFilter)
      }
    }
 
    const {
      name: pipelineName,
      pipelineTags: _pipelineTags,
      moduleProperties,
      description
    } = (appliedFilter?.filterProperties as PipelineFilterProperties) || {}
    const { name = '', filterVisibility, identifier = '' } = appliedFilter || {}
    const { ci, cd } = moduleProperties || {}
    const { branch, tag, ciExecutionInfoDTO, repoName } = ci || {}
    const { deploymentTypes, environmentNames, infrastructureTypes, serviceNames } = cd || {}
    const { sourceBranch, targetBranch } = ciExecutionInfoDTO?.pullRequest || {}
    // eslint-disable-next-line @typescript-eslint/no-shadow
    const buildType = getBuildType(moduleProperties || {})
 
    return isFetchingFilters && isFetchingMetaData ? (
      <div style={{ position: 'relative', height: 'calc(100vh - 128px)' }}>
        <OverlaySpinner show={true} className={css.loading}>
          <></>
        </OverlaySpinner>
      </div>
    ) : (
      <Filter<PipelineFormType, FilterDTO>
        formFields={
          <PipelineFilterForm<PipelineFormType>
            isCDEnabled={isCDEnabled}
            isCIEnabled={isCIEnabled}
            initialValues={{
              environments: getMultiSelectFormOptions(environmentsResponse?.data?.content),
              services: getMultiSelectFormOptions(servicesResponse?.data?.content),
              deploymentType: NG_NATIVE_HELM
                ? deploymentTypeSelectOptions
                : deploymentTypeSelectOptions.filter(deploymentType => deploymentType.value !== 'NativeHelm')
            }}
            type="PipelineSetup"
          />
        }
        initialFilter={{
          formValues: {
            name: pipelineName,
            pipelineTags: _pipelineTags?.reduce((obj, item) => Object.assign(obj, { [item.key]: item.value }), {}),
            description,
            branch,
            tag,
            sourceBranch,
            targetBranch,
            buildType,
            repositoryName: repoName ? repoName[0] : undefined,
            deploymentType: deploymentTypes,
            infrastructureType: infrastructureTypes ? infrastructureTypes[0] : undefined,
            services: getMultiSelectFormOptions(serviceNames),
            environments: getMultiSelectFormOptions(environmentNames)
          },
          metadata: { name, filterVisibility, identifier, filterProperties: {} }
        }}
        filters={filters}
        isRefreshingFilters={isRefreshingFilters || isFetchingMetaData}
        onApply={onApply}
        onClose={() => hideFilterDrawer()}
        onSaveOrUpdate={handleSaveOrUpdate}
        onDelete={handleDelete}
        onFilterSelect={handleFilterClick}
        onClear={reset}
        ref={filterRef}
        dataSvcConfig={
          new Map<CrudOperation, (...rest: any[]) => Promise<any>>([
            ['ADD', createFilter],
            ['UPDATE', updateFilter],
            ['DELETE', deleteFilter]
          ])
        }
        onSuccessfulCrudOperation={refetchFilterList}
      />
    )
  }, [
    isRefreshingFilters,
    appliedFilter,
    filters,
    module,
    environmentsResponse?.data?.content,
    servicesResponse?.data?.content
  ])
 
  /* #region Filter Selection */
 
  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(), filters)
      const aggregatedFilter = selectedFilter?.filterProperties || {}
      const combinedFilter = Object.assign(selectedFilter, { filterProperties: aggregatedFilter })
      setAppliedFilter(combinedFilter)
    } else {
      reset()
    }
  }
 
  const fieldToLabelMapping = new Map<string, string>()
  fieldToLabelMapping.set('name', getString('name'))
  fieldToLabelMapping.set('description', getString('description'))
  fieldToLabelMapping.set('pipelineTags', getString('tagsLabel'))
  fieldToLabelMapping.set('sourceBranch', getString('common.sourceBranch'))
  fieldToLabelMapping.set('targetBranch', getString('common.targetBranch'))
  fieldToLabelMapping.set('branch', getString('pipelineSteps.deploy.inputSet.branch'))
  fieldToLabelMapping.set('tag', getString('tagLabel'))
  fieldToLabelMapping.set('repoNames', getString('common.repositoryName'))
  fieldToLabelMapping.set('buildType', getString('filters.executions.buildType'))
  fieldToLabelMapping.set('deploymentTypes', getString('deploymentTypeText'))
  fieldToLabelMapping.set('infrastructureTypes', getString('infrastructureTypeText'))
  fieldToLabelMapping.set('serviceNames', getString('services'))
  fieldToLabelMapping.set('environmentNames', getString('environments'))
 
  const filterWithValidFields = removeNullAndEmpty(
    pick(flattenObject(appliedFilter?.filterProperties || {}), ...fieldToLabelMapping.keys())
  )
 
  const filterWithValidFieldsWithMetaInfo =
    filterWithValidFields.sourceBranch && filterWithValidFields.targetBranch
      ? Object.assign(filterWithValidFields, { buildType: getString('filters.executions.pullOrMergeRequest') })
      : filterWithValidFields.branch
      ? Object.assign(filterWithValidFields, { buildType: getString('pipelineSteps.deploy.inputSet.branch') })
      : filterWithValidFields.tag
      ? Object.assign(filterWithValidFields, { buildType: getString('tagLabel') })
      : filterWithValidFields
 
  /* #endregion */
 
  useEffect(() => {
    cancel()
    setIsLoading(true)
    fetchPipelines(defaultQueryParamsForPiplines, appliedFilter?.filterProperties)
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [
    page,
    accountId,
    projectIdentifier,
    orgIdentifier,
    appliedFilter?.filterProperties,
    module,
    searchParam,
    sort,
    gitFilter
  ])
 
  const shouldRenderFilterSelector = (): boolean => {
    if (isGitSyncEnabled) {
      if (pipelineList?.content?.length) {
        return true
      }
      Iif (appliedFilter || searchParam) {
        return true
      }
      return false
    }
    return true
  }
 
  const onDeletePipeline = async (commitMsg: string): Promise<void> => {
    try {
      setIsDeleting(true)
      const gitParams = pipelineToDelete?.gitDetails?.objectId
        ? {
            ...pick(pipelineToDelete?.gitDetails, ['branch', 'repoIdentifier', 'filePath', 'rootFolder']),
            commitMsg,
            lastObjectId: pipelineToDelete?.gitDetails?.objectId
          }
        : {}
 
      const deleted = await deletePipeline(defaultTo(pipelineToDelete?.identifier, ''), {
        queryParams: {
          accountIdentifier: accountId,
          orgIdentifier,
          projectIdentifier,
          ...gitParams
        },
        headers: { 'content-type': 'application/json' }
      })
      setIsDeleting(false)
 
      /* istanbul ignore else */
      if (deleted?.status === 'SUCCESS') {
        showSuccess(getString('pipeline-list.pipelineDeleted', { name: pipelineToDelete?.name }))
      } else {
        throw getString('somethingWentWrong')
      }
      fetchPipelines()
    } catch (err) {
      setIsDeleting(false)
      /* istanbul ignore next */
      showError(getRBACErrorMessage(err), undefined, 'pipeline.delete.pipeline.error')
    }
  }
 
  if (isDeleting) {
    return <PageSpinner />
  }
 
  return (
    <>
      <Page.Header
        title={
          <div className="ng-tooltip-native">
            <h2 data-tooltip-id="pipelinesPageHeading"> {getString('pipelines')}</h2>
            <HarnessDocTooltip tooltipId="pipelinesPageHeading" useStandAlone={true} />
          </div>
        }
        breadcrumbs={<NGBreadcrumbs links={[]} />}
      ></Page.Header>
      {(isReseting || !!pipelineList?.content?.length || appliedFilter || isGitSyncEnabled || searchParam) && (
        <Page.SubHeader>
          <Layout.Horizontal>
            {isPipelineTemplateEnabled ? (
              <NewPipelinePopover />
            ) : (
              <RbacButton
                variation={ButtonVariation.PRIMARY}
                data-testid="add-pipeline"
                icon="plus"
                text={getString('pipeline.newPipelineText')}
                onClick={() => goToPipeline()}
                tooltipProps={{
                  dataTooltipId: 'addPipeline'
                }}
                permission={{
                  permission: PermissionIdentifier.EDIT_PIPELINE,
                  resource: {
                    resourceType: ResourceType.PIPELINE
                  }
                }}
              />
            )}
            {isGitSyncEnabled && (
              <GitSyncStoreProvider>
                <GitFilters
                  onChange={filter => {
                    setGitFilter(filter)
                    setPage(0)
                  }}
                  className={css.gitFilter}
                  defaultValue={gitFilter || undefined}
                />
              </GitSyncStoreProvider>
            )}
          </Layout.Horizontal>
          <Layout.Horizontal spacing="small" style={{ alignItems: 'center' }}>
            <>
              <ExpandingSearchInput
                alwaysExpanded
                width={200}
                placeholder={getString('search')}
                onChange={(text: string) => {
                  setIsReseting(true)
                  setSearchParam(text)
                }}
                ref={searchRef}
                className={css.expandSearch}
              />
              {shouldRenderFilterSelector() && (
                <Layout.Horizontal padding={{ left: 'small', right: 'small' }}>
                  <FilterSelector<FilterDTO>
                    appliedFilter={appliedFilter}
                    filters={filters}
                    onFilterBtnClick={openFilterDrawer}
                    onFilterSelect={handleFilterSelection}
                    fieldToLabelMapping={fieldToLabelMapping}
                    filterWithValidFields={filterWithValidFieldsWithMetaInfo}
                  />
                </Layout.Horizontal>
              )}
            </>
            <GridListToggle initialSelectedView={Views.GRID} onViewToggle={setView} />
          </Layout.Horizontal>
        </Page.SubHeader>
      )}
      <Page.Body
        className={css.pageBody}
        error={error?.message}
        retryOnError={/* istanbul ignore next */ () => fetchPipelines()}
      >
        {!!pipelineList?.content?.length && (
          <Layout.Horizontal
            spacing="large"
            margin={{ left: 'large', top: 'large', bottom: 'large', right: 'large' }}
            className={css.topHeaderFields}
          >
            <Text color={Color.GREY_800} iconProps={{ size: 14 }}>
              {getString('total')}: {pipelineList?.totalElements}
            </Text>
            <DropDown
              items={sortOptions}
              value={selectedSort.value.toString()}
              filterable={false}
              width={180}
              icon={'main-sort'}
              iconProps={{ size: 16, color: Color.GREY_400 }}
              onChange={item => {
                if (item.value === SortFields.AZ09) {
                  setStort([SortFields.Name, Sort.ASC])
                } else if (item.value === SortFields.ZA90) {
                  setStort([SortFields.Name, Sort.DESC])
                } else if (item.value === SortFields.LastUpdatedAt) {
                  setStort([SortFields.LastUpdatedAt, Sort.DESC])
                } else if (item.value === SortFields.RecentActivity) {
                  setStort([SortFields.RecentActivity, Sort.DESC])
                }
                setPage(0)
                setSelectedSort(item)
              }}
            />
          </Layout.Horizontal>
        )}
        {isLoading ? (
          <PageSpinner />
        ) : !pipelineList?.content?.length ? (
          <div className={css.noPipelineSection}>
            {appliedFilter || searchParam ? (
              <Layout.Vertical spacing="small" flex>
                <Icon size={50} name={isCIModule ? 'ci-main' : 'cd-main'} margin={{ bottom: 'large' }} />
                <Text
                  margin={{ top: 'large', bottom: 'small' }}
                  font={{ weight: 'bold', size: 'medium' }}
                  color={Color.GREY_800}
                >
                  {getString('common.filters.noMatchingFilterData')}
                </Text>
                <String stringID="common.filters.clearFilters" className={css.clearFilterText} onClick={reset} />
              </Layout.Vertical>
            ) : (
              <Layout.Vertical spacing="small" flex={{ justifyContent: 'center', alignItems: 'center' }} width={720}>
                <img src={emptyStagePipelineImage} className={css.image} />
                <Text className={css.noPipelineText} margin={{ top: 'medium', bottom: 'small' }}>
                  {getString('pipeline.noPipelineText')}
                </Text>
                <Text className={css.aboutPipeline} margin={{ top: 'xsmall', bottom: 'xlarge' }}>
                  {getString('pipeline-list.aboutPipeline')}
                </Text>
                {isPipelineTemplateEnabled ? (
                  <NewPipelinePopover text={getString('common.createPipeline')} />
                ) : (
                  <RbacButton
                    variation={ButtonVariation.PRIMARY}
                    onClick={() => goToPipeline()}
                    text={getString('common.createPipeline')}
                    permission={{
                      permission: PermissionIdentifier.EDIT_PIPELINE,
                      resource: {
                        resourceType: ResourceType.PIPELINE
                      },
                      resourceScope: {
                        accountIdentifier: accountId,
                        orgIdentifier,
                        projectIdentifier
                      }
                    }}
                  />
                )}
              </Layout.Vertical>
            )}
          </div>
        ) : (
          <GitSyncStoreProvider>
            {view === Views.GRID ? (
              <PipelineGridView
                gotoPage={/* istanbul ignore next */ pageNumber => setPage(pageNumber)}
                data={pipelineList}
                goToPipelineDetail={goToPipelineDetail}
                goToPipelineStudio={goToPipeline}
                refetchPipeline={fetchPipelines}
                onDeletePipeline={onDeletePipeline}
                onDelete={(pipeline: PMSPipelineSummaryResponse) => {
                  setPipelineToDelete(pipeline)
                }}
              />
            ) : (
              <PipelineListView
                gotoPage={/* istanbul ignore next */ pageNumber => setPage(pageNumber)}
                data={pipelineList}
                goToPipelineDetail={goToPipelineDetail}
                goToPipelineStudio={goToPipeline}
                refetchPipeline={fetchPipelines}
                onDelete={(pipeline: PMSPipelineSummaryResponse) => {
                  setPipelineToDelete(pipeline)
                }}
                onDeletePipeline={onDeletePipeline}
              />
            )}
          </GitSyncStoreProvider>
        )}
      </Page.Body>
    </>
  )
}
 
export default PipelinesPage