All files / modules/70-pipeline/pages/inputSet-list InputSetList.tsx

95.89% Statements 70/73
70.52% Branches 122/173
92.31% Functions 12/13
95.89% Lines 70/73

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              2x 2x 2x 2x 2x 2x 2x 2x 2x             2x 2x 2x   2x 2x 2x 2x 2x 2x 2x 2x 2x     21x 21x 21x 21x     21x 21x 21x 21x             21x                                       21x                           21x                     21x   21x         21x 21x 10x     10x       21x         21x 21x   21x   21x   3x                                   21x                               21x   3x         1x 1x               21x 2x 2x 2x               2x                   2x     2x 2x       2x               21x                     1x           1x 1x                                                                             1x                     40x                                     4x         4x 2x   2x               2x               2x  
/*
 * Copyright 2021 Harness Inc. All rights reserved.
 * Use of this source code is governed by the PolyForm Shield 1.0.0 license
 * that can be found in the licenses directory at the root of this repository, also available at
 * https://polyformproject.org/wp-content/uploads/2020/06/PolyForm-Shield-1.0.0.txt.
 */
 
import React, { useEffect, useState } from 'react'
import { defaultTo, isEmpty, pick } from 'lodash-es'
import { Popover, Layout, TextInput, Text, ButtonVariation, useToaster } from '@wings-software/uicore'
import { useModalHook } from '@harness/use-modal'
import { Color } from '@harness/design-system'
import { Menu, MenuItem, Position } from '@blueprintjs/core'
import { useHistory, useParams } from 'react-router-dom'
import { Page } from '@common/exports'
import {
  InputSetSummaryResponse,
  useDeleteInputSetForPipeline,
  useGetInputSetsListForPipeline,
  useGetPipelineSummary,
  useGetTemplateFromPipeline
} from 'services/pipeline-ng'
import useRBACError from '@rbac/utils/useRBACError/useRBACError'
import { OverlayInputSetForm } from '@pipeline/components/OverlayInputSetForm/OverlayInputSetForm'
import routes from '@common/RouteDefinitions'
import type { GitQueryParams, PipelinePathProps, PipelineType } from '@common/interfaces/RouteInterfaces'
import { useDocumentTitle } from '@common/hooks/useDocumentTitle'
import { useStrings } from 'framework/strings'
import RbacButton from '@rbac/components/Button/Button'
import { PermissionIdentifier } from '@rbac/interfaces/PermissionIdentifier'
import { ResourceType } from '@rbac/interfaces/ResourceType'
import { usePermission } from '@rbac/hooks/usePermission'
import { useMutateAsGet, useQueryParams } from '@common/hooks'
import { InputSetListView } from './InputSetListView'
import css from './InputSetList.module.scss'
 
function InputSetList(): React.ReactElement {
  const [searchParam, setSearchParam] = React.useState('')
  const [page, setPage] = React.useState(0)
  const { repoIdentifier, branch } = useQueryParams<GitQueryParams>()
  const { projectIdentifier, orgIdentifier, accountId, pipelineIdentifier, module } = useParams<
    PipelineType<PipelinePathProps> & { accountId: string }
  >()
  const { showSuccess, showError } = useToaster()
  const { getRBACErrorMessage } = useRBACError()
  const [isLoading, setIsLoading] = useState<boolean>(false)
  const [inputSetToDelete, setInputSetToDelete] = useState<InputSetSummaryResponse>()
 
  const {
    data: inputSet,
    loading,
    refetch,
    error
  } = useGetInputSetsListForPipeline({
    queryParams: {
      accountIdentifier: accountId,
      orgIdentifier,
      projectIdentifier,
      pipelineIdentifier,
      pageIndex: page,
      pageSize: 20,
      searchTerm: searchParam,
      ...(!isEmpty(repoIdentifier) && !isEmpty(branch)
        ? {
            repoIdentifier,
            branch,
            getDefaultFromOtherRepo: true
          }
        : {})
    },
    debounce: 300
  })
 
  const { data: template } = useMutateAsGet(useGetTemplateFromPipeline, {
    queryParams: {
      accountIdentifier: accountId,
      orgIdentifier,
      pipelineIdentifier,
      projectIdentifier,
      repoIdentifier,
      branch
    },
    body: {
      stageIdentifiers: []
    }
  })
 
  const { data: pipeline } = useGetPipelineSummary({
    pipelineIdentifier,
    queryParams: {
      accountIdentifier: accountId,
      orgIdentifier,
      projectIdentifier,
      repoIdentifier,
      branch
    }
  })
 
  const isPipelineInvalid = pipeline?.data?.entityValidityDetails?.valid === false
 
  const { mutate: deleteInputSet } = useDeleteInputSetForPipeline({
    queryParams: { accountIdentifier: accountId, orgIdentifier, projectIdentifier, pipelineIdentifier }
  })
 
  // These flags will be used to disable the Add Input set buttons in the page.
  const [pipelineHasRuntimeInputs, setPipelineHasRuntimeInputs] = useState(true)
  useEffect(() => {
    Iif (!template?.data?.inputSetTemplateYaml) {
      setPipelineHasRuntimeInputs(false)
    } else {
      setPipelineHasRuntimeInputs(true)
    }
  }, [template])
 
  const [selectedInputSet, setSelectedInputSet] = React.useState<{
    identifier?: string
    repoIdentifier?: string
    branch?: string
  }>()
  const history = useHistory()
  const { getString } = useStrings()
 
  useDocumentTitle([pipeline?.data?.name || getString('pipelines'), getString('inputSetsText')])
 
  const goToInputSetForm = React.useCallback(
    (inputSetTemp?: InputSetSummaryResponse) => {
      history.push(
        routes.toInputSetForm({
          accountId,
          orgIdentifier,
          projectIdentifier,
          pipelineIdentifier,
          inputSetIdentifier: typeof inputSetTemp?.identifier !== 'string' ? '-1' : inputSetTemp.identifier,
          module,
          inputSetRepoIdentifier: inputSetTemp?.gitDetails?.repoIdentifier,
          inputSetBranch: inputSetTemp?.gitDetails?.branch,
          repoIdentifier,
          branch
        })
      )
    },
    [accountId, orgIdentifier, projectIdentifier, pipelineIdentifier, module, history, repoIdentifier, branch]
  )
 
  const [canUpdateInputSet] = usePermission(
    {
      resourceScope: {
        accountIdentifier: accountId,
        orgIdentifier,
        projectIdentifier
      },
      resource: {
        resourceType: ResourceType.PIPELINE,
        resourceIdentifier: pipelineIdentifier
      },
      permissions: [PermissionIdentifier.EDIT_PIPELINE]
    },
    [accountId, orgIdentifier, projectIdentifier, pipelineIdentifier]
  )
 
  const [showOverlayInputSetForm, hideOverlayInputSetForm] = useModalHook(
    () => (
      <OverlayInputSetForm
        identifier={selectedInputSet?.identifier}
        overlayInputSetRepoIdentifier={selectedInputSet?.repoIdentifier}
        overlayInputSetBranch={selectedInputSet?.branch}
        hideForm={() => {
          refetch()
          hideOverlayInputSetForm()
        }}
        isReadOnly={!canUpdateInputSet}
      />
    ),
    [selectedInputSet]
  )
 
  const onDeleteInputSet = async (commitMsg: string): Promise<void> => {
    try {
      setIsLoading(true)
      const gitParams = inputSetToDelete?.gitDetails?.objectId
        ? {
            ...pick(inputSetToDelete?.gitDetails, ['branch', 'repoIdentifier', 'filePath', 'rootFolder']),
            commitMsg,
            lastObjectId: inputSetToDelete?.gitDetails?.objectId
          }
        : {}
 
      const deleted = await deleteInputSet(defaultTo(inputSetToDelete?.identifier, ''), {
        queryParams: {
          accountIdentifier: accountId,
          orgIdentifier,
          projectIdentifier,
          pipelineIdentifier: defaultTo(inputSetToDelete?.pipelineIdentifier, ''),
          ...gitParams
        },
        headers: { 'content-type': 'application/json' }
      })
      setIsLoading(false)
 
      /* istanbul ignore else */
      if (deleted?.status === 'SUCCESS') {
        showSuccess(getString('inputSets.inputSetDeleted', { name: inputSetToDelete?.name }))
      } else {
        throw getString('somethingWentWrong')
      }
      refetch()
    } catch (err) {
      setIsLoading(false)
      /* istanbul ignore next */
      showError(getRBACErrorMessage(err), undefined, 'pipeline.delete.inputset.error')
    }
  }
 
  return (
    <>
      <Page.SubHeader>
        <Layout.Horizontal>
          <Popover
            minimal
            content={
              <Menu className={css.menuList}>
                <MenuItem
                  text={getString('inputSets.inputSetLabel')}
                  onClick={() => {
                    goToInputSetForm()
                  }}
                />
                <MenuItem
                  text={getString('inputSets.overlayInputSet')}
                  onClick={() => {
                    setSelectedInputSet({ identifier: '', repoIdentifier, branch })
                    showOverlayInputSetForm()
                  }}
                />
              </Menu>
            }
            position={Position.BOTTOM}
            disabled={!canUpdateInputSet || !pipelineHasRuntimeInputs || isPipelineInvalid}
          >
            <RbacButton
              text={getString('inputSets.newInputSet')}
              rightIcon="caret-down"
              variation={ButtonVariation.PRIMARY}
              permission={{
                resource: {
                  resourceType: ResourceType.PIPELINE,
                  resourceIdentifier: pipelineIdentifier
                },
                permission: PermissionIdentifier.EDIT_PIPELINE
              }}
              disabled={!pipelineHasRuntimeInputs || isPipelineInvalid}
              tooltip={
                isPipelineInvalid ? (
                  getString('pipeline.cannotAddInputSetInvalidPipeline')
                ) : !pipelineHasRuntimeInputs ? (
                  <Text padding="medium">{getString('pipeline.inputSets.noRuntimeInputsCurrently')}</Text>
                ) : undefined
              }
            />
          </Popover>
        </Layout.Horizontal>
 
        <Layout.Horizontal spacing="small">
          <TextInput
            leftIcon={'thinner-search'}
            leftIconProps={{ name: 'thinner-search', size: 14, color: Color.GREY_700 }}
            placeholder={getString('inputSets.searchInputSet')}
            wrapperClassName={css.searchWrapper}
            value={searchParam}
            onChange={(e: React.ChangeEvent<HTMLInputElement>) => {
              setSearchParam(e.target.value.trim())
            }}
          />
        </Layout.Horizontal>
      </Page.SubHeader>
 
      <Page.Body
        loading={loading || isLoading}
        error={error?.message}
        retryOnError={/* istanbul ignore next */ () => refetch()}
        noData={{
          when: () => !inputSet?.data?.content?.length,
          icon: 'yaml-builder-input-sets',
          message: getString('pipeline.inputSets.aboutInputSets'),
          buttonText: getString('inputSets.newInputSet'),
          onClick: () => goToInputSetForm(),
          buttonDisabled: !canUpdateInputSet || !pipelineHasRuntimeInputs || isPipelineInvalid,
          buttonDisabledTooltip: isPipelineInvalid
            ? getString('pipeline.cannotAddInputSetInvalidPipeline')
            : !pipelineHasRuntimeInputs
            ? getString('pipeline.inputSets.noRuntimeInputsCurrently')
            : undefined
        }}
      >
        <InputSetListView
          data={inputSet?.data}
          gotoPage={setPage}
          pipelineHasRuntimeInputs={pipelineHasRuntimeInputs}
          isPipelineInvalid={isPipelineInvalid}
          goToInputSetDetail={inputSetTemp => {
            setSelectedInputSet({
              identifier: inputSetTemp?.identifier,
              repoIdentifier: inputSetTemp?.gitDetails?.repoIdentifier,
              branch: inputSetTemp?.gitDetails?.branch
            })
            if (inputSetTemp?.inputSetType === 'INPUT_SET') {
              goToInputSetForm(inputSetTemp)
            } else {
              showOverlayInputSetForm()
            }
          }}
          refetchInputSet={refetch}
          template={template}
          canUpdate={canUpdateInputSet}
          onDeleteInputSet={onDeleteInputSet}
          onDelete={(inputSetSelected: InputSetSummaryResponse) => {
            setInputSetToDelete(inputSetSelected)
          }}
        />
      </Page.Body>
    </>
  )
}
 
export default InputSetList