All files / modules/70-pipeline/pages/pipeline-deployment-list/PipelineDeploymentListHeader/ExecutionFilters ExecutionFilters.tsx

66.29% Statements 59/89
57.72% Branches 86/149
42.86% Functions 6/14
66.29% Lines 59/89

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                8x 8x   8x   8x   8x 8x   8x 8x         8x 8x   8x   8x                     8x 8x           8x 8x 8x 8x             8x   8x 51x 50x 50x 50x 50x 50x 50x 50x 50x 50x 50x   50x         50x       46x         46x   46x       46x       46x                 46x 13x 9x 18x 18x       9x         46x     46x                     46x 46x 46x 46x 46x 46x 46x 46x   46x                                 46x         46x                                                                                                                                                                               46x                                         58x                                                                                                          
/*
 * 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.
 */
 
/* eslint-disable @typescript-eslint/no-explicit-any */
import React from 'react'
import { useParams } from 'react-router-dom'
import type { SelectOption } from '@wings-software/uicore'
import * as Yup from 'yup'
import type { FormikProps } from 'formik'
import { isEmpty, pick } from 'lodash-es'
 
import { useStrings } from 'framework/strings'
import { useAppStore } from 'framework/AppStore/AppStoreContext'
import type { FilterDTO, PipelineExecutionFilterProperties } from 'services/pipeline-ng'
import { usePostFilter, useUpdateFilter, useDeleteFilter } from 'services/pipeline-ng'
import {
  useGetEnvironmentListForProject,
  useGetServiceDefinitionTypes,
  useGetServiceListForProject
} from 'services/cd-ng'
import { Filter, FilterRef } from '@common/components/Filter/Filter'
import FilterSelector from '@common/components/Filter/FilterSelector/FilterSelector'
import type { FilterInterface, FilterDataInterface } from '@common/components/Filter/Constants'
import { useBooleanStatus, useUpdateQueryParams } from '@common/hooks'
import type { PipelineType, PipelinePathProps } from '@common/interfaces/RouteInterfaces'
import {
  PipelineExecutionFormType,
  getMultiSelectFormOptions,
  BUILD_TYPE,
  getFilterByIdentifier,
  getBuildType,
  getValidFilterArguments,
  createRequestBodyPayload
} from '@pipeline/utils/PipelineExecutionFilterRequestUtils'
import type { CrudOperation } from '@common/components/Filter/FilterCRUD/FilterCRUD'
 
import { StringUtils } from '@common/exports'
import {
  isObjectEmpty,
  UNSAVED_FILTER,
  removeNullAndEmpty,
  flattenObject
} from '@common/components/Filter/utils/FilterUtils'
import { useFeatureFlags } from '@common/hooks/useFeatureFlag'
import { deploymentTypeLabel } from '@pipeline/pages/pipelines/PipelineListUtils'
import { useFiltersContext } from '../../FiltersContext/FiltersContext'
import PipelineFilterForm from '../../PipelineFilterForm/PipelineFilterForm'
import type { StringQueryParams } from '../../types'
 
export interface ExecutionFilterQueryParams {
  filter?: string
}
 
const UNSAVED_FILTER_IDENTIFIER = StringUtils.getIdentifierFromName(UNSAVED_FILTER)
 
export function ExecutionFilters(): React.ReactElement {
  const [loading, setLoading] = React.useState(false)
  const { accountId, projectIdentifier, orgIdentifier } = useParams<PipelineType<PipelinePathProps>>()
  const { state: isFiltersDrawerOpen, open: openFilterDrawer, close: hideFilterDrawer } = useBooleanStatus()
  const { getString } = useStrings()
  const { updateQueryParams, replaceQueryParams } = useUpdateQueryParams<StringQueryParams>()
  const { selectedProject } = useAppStore()
  const isCDEnabled = (selectedProject?.modules && selectedProject.modules?.indexOf('CD') > -1) || false
  const isCIEnabled = (selectedProject?.modules && selectedProject.modules?.indexOf('CI') > -1) || false
  const filterRef = React.useRef<FilterRef<FilterDTO> | null>(null)
  const { savedFilters: filters, isFetchingFilters, refetchFilters, queryParams } = useFiltersContext()
  const { NG_NATIVE_HELM } = useFeatureFlags()
 
  const { data: servicesResponse, loading: isFetchingServices } = useGetServiceListForProject({
    queryParams: { accountId, orgIdentifier, projectIdentifier },
    lazy: isFiltersDrawerOpen
  })
 
  const { data: deploymentTypeResponse, loading: isFetchingDeploymentTypes } = useGetServiceDefinitionTypes({
    lazy: isFiltersDrawerOpen
  })
 
  const { data: environmentsResponse, loading: isFetchingEnvironments } = useGetEnvironmentListForProject({
    queryParams: { accountId, orgIdentifier, projectIdentifier },
    lazy: isFiltersDrawerOpen
  })
 
  const [deploymentTypeSelectOptions, setDeploymentTypeSelectOptions] = React.useState<SelectOption[]>([])
 
  const { mutate: createFilter } = usePostFilter({
    queryParams: { accountIdentifier: accountId }
  })
 
  const { mutate: updateFilter } = useUpdateFilter({
    queryParams: { accountIdentifier: accountId }
  })
 
  const { mutate: deleteFilter } = useDeleteFilter({
    queryParams: {
      accountIdentifier: accountId,
      orgIdentifier,
      projectIdentifier,
      type: 'PipelineExecution'
    }
  })
 
  React.useEffect(() => {
    if (!isFetchingDeploymentTypes && !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, isFetchingDeploymentTypes])
 
  const isFetchingMetaData = isFetchingDeploymentTypes || isFetchingEnvironments || isFetchingServices
 
  const appliedFilter =
    queryParams.filterIdentifier && queryParams.filterIdentifier !== UNSAVED_FILTER_IDENTIFIER
      ? getFilterByIdentifier(queryParams.filterIdentifier, filters)
      : queryParams.filters && !isEmpty(queryParams.filters)
      ? {
          name: UNSAVED_FILTER,
          identifier: UNSAVED_FILTER_IDENTIFIER,
          filterProperties: queryParams.filters,
          filterVisibility: undefined
        }
      : null
  const { pipelineName, status, moduleProperties } =
    (appliedFilter?.filterProperties as PipelineExecutionFilterProperties) || {}
  const { name = '', filterVisibility, identifier = '' } = appliedFilter || {}
  const { ci, cd } = moduleProperties || {}
  const { serviceDefinitionTypes, infrastructureType, serviceIdentifiers, envIdentifiers } = cd || {}
  const { branch, tag, ciExecutionInfoDTO, repoName } = ci || {}
  const { sourceBranch, targetBranch } = ciExecutionInfoDTO?.pullRequest || {}
  const buildType = getBuildType(moduleProperties || {})
  const fieldToLabelMapping = React.useMemo(
    () =>
      new Map<string, string>([
        ['pipelineName', getString('filters.executions.pipelineName')],
        ['status', getString('status')],
        ['sourceBranch', getString('common.sourceBranch')],
        ['targetBranch', getString('common.targetBranch')],
        ['branch', getString('pipelineSteps.deploy.inputSet.branch')],
        ['tag', getString('tagLabel')],
        ['buildType', getString('filters.executions.buildType')],
        ['repoName', getString('common.repositoryName')],
        ['serviceDefinitionTypes', getString('deploymentTypeText')],
        ['infrastructureType', getString('infrastructureTypeText')],
        ['serviceIdentifiers', getString('services')],
        ['envIdentifiers', getString('environments')]
      ]),
    [getString]
  )
 
  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
 
  function handleFilterSelection(
    option: SelectOption,
    event?: React.SyntheticEvent<HTMLElement, Event> | undefined
  ): void {
    event?.stopPropagation()
    event?.preventDefault()
 
    if (option.value) {
      updateQueryParams({
        filterIdentifier: option.value.toString(),
        filters: [] as any /* this will remove the param */
      })
    } else {
      updateQueryParams({
        filterIdentifier: [] as any /* this will remove the param */,
        filters: [] as any /* this will remove the param */
      })
    }
  }
 
  function onApply(inputFormData: FormikProps<PipelineExecutionFormType>['values']): void {
    if (!isObjectEmpty(inputFormData)) {
      const filterFromFormData = getValidFilterArguments({ ...inputFormData })
      updateQueryParams({ page: [] as any, filters: JSON.stringify({ ...(filterFromFormData || {}) }) })
      hideFilterDrawer()
    } else {
      // showError(getString('filters.invalidCriteria'))
    }
  }
 
  async function handleSaveOrUpdate(
    isUpdate: boolean,
    data: FilterDataInterface<PipelineExecutionFormType, FilterInterface>
  ): Promise<void> {
    setLoading(true)
    const requestBodyPayload = createRequestBodyPayload({
      isUpdate,
      data,
      projectIdentifier,
      orgIdentifier
    })
 
    const saveOrUpdateHandler = filterRef.current?.saveOrUpdateFilterHandler
    if (saveOrUpdateHandler && typeof saveOrUpdateHandler === 'function') {
      const updatedFilter = await saveOrUpdateHandler(isUpdate, requestBodyPayload)
      updateQueryParams({ filters: JSON.stringify({ ...(updatedFilter || {}) }) })
    }
 
    setLoading(false)
    refetchFilters()
  }
 
  // eslint-disable-next-line @typescript-eslint/no-shadow
  async function handleDelete(identifier: string): Promise<void> {
    setLoading(true)
    const deleteHandler = filterRef.current?.deleteFilterHandler
    if (deleteHandler && typeof deleteFilter === 'function') {
      await deleteHandler(identifier)
    }
    setLoading(false)
 
    if (identifier === appliedFilter?.identifier) {
      reset()
    }
    refetchFilters()
  }
 
  function handleFilterClick(filterIdentifier: string): void {
    if (filterIdentifier !== UNSAVED_FILTER_IDENTIFIER) {
      updateQueryParams({
        filterIdentifier,
        filters: [] as any /* this will remove the param */
      })
    }
  }
 
  function reset(): void {
    replaceQueryParams({})
  }
 
  return (
    <React.Fragment>
      <FilterSelector<FilterDTO>
        appliedFilter={appliedFilter}
        filters={filters}
        onFilterBtnClick={openFilterDrawer}
        onFilterSelect={handleFilterSelection}
        fieldToLabelMapping={fieldToLabelMapping}
        filterWithValidFields={filterWithValidFieldsWithMetaInfo}
      />
      <Filter<PipelineExecutionFormType, FilterDTO>
        isOpen={isFiltersDrawerOpen}
        formFields={
          <PipelineFilterForm<PipelineExecutionFormType>
            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="PipelineExecution"
          />
        }
        initialFilter={{
          formValues: {
            pipelineName,
            repositoryName: repoName,
            status: getMultiSelectFormOptions(status),
            branch,
            tag,
            sourceBranch,
            targetBranch,
            buildType,
            deploymentType: serviceDefinitionTypes,
            infrastructureType,
            services: getMultiSelectFormOptions(serviceIdentifiers),
            environments: getMultiSelectFormOptions(envIdentifiers)
          },
          metadata: { name, filterVisibility, identifier, filterProperties: {} }
        }}
        filters={filters}
        isRefreshingFilters={isFetchingFilters || isFetchingMetaData || loading}
        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={() => refetchFilters()}
        validationSchema={Yup.object().shape({
          branch: Yup.string().when('buildType', {
            is: BUILD_TYPE.BRANCH,
            then: Yup.string()
          }),
          tag: Yup.string().when('buildType', {
            is: BUILD_TYPE.TAG,
            then: Yup.string()
          })
        })}
      />
    </React.Fragment>
  )
}