All files / modules/70-pipeline/components/PipelineSteps/Steps/Common ApprovalRejectionCriteria.tsx

70.31% Statements 45/64
44.19% Branches 19/43
52.94% Functions 9/17
71.43% Lines 45/63

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              110x 110x 110x 110x                   110x   110x 110x 110x           110x 110x 110x 110x             110x 110x                                                                                                 110x                       33x 33x 33x 33x     33x                                               33x                       20x                                                                                                                         1x                                   110x 7x 7x 7x                                       110x 40x 40x 40x 40x 40x   40x 6x 6x 6x       6x                                 6x 6x     40x 6x           40x   40x                                     1x                                  
/*
 * Copyright 2022 Harness Inc. All rights reserved.
 * Use of this source code is governed by the PolyForm Free Trial 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/05/PolyForm-Free-Trial-1.0.0.txt.
 */
 
import React, { useEffect, useState } from 'react'
import { FieldArray } from 'formik'
import { get, isEmpty } from 'lodash-es'
import {
  Button,
  FormInput,
  HarnessDocTooltip,
  Layout,
  MultiTypeInputType,
  Radio,
  SelectOption,
  Text
} from '@wings-software/uicore'
import { useStrings } from 'framework/strings'
import type { JiraFieldNG } from 'services/cd-ng'
import { FormMultiTypeTextAreaField } from '@common/components/MultiTypeTextArea/MultiTypeTextArea'
import { useVariablesExpression } from '@pipeline/components/PipelineStudio/PiplineHooks/useVariablesExpression'
import {
  ApprovalRejectionCriteriaCondition,
  ApprovalRejectionCriteriaProps,
  ConditionsInterface,
  ApprovalRejectionCriteriaType
} from '@pipeline/components/PipelineSteps/Steps/Common/types'
import { StepType } from '@pipeline/components/PipelineSteps/PipelineStepInterface'
import { errorCheck } from '@common/utils/formikHelpers'
import { isApprovalStepFieldDisabled } from './ApprovalCommons'
import {
  filterOutMultiOperators,
  handleOperatorChange,
  operatorValues,
  removeDuplicateFieldKeys,
  setAllowedValuesOptions
} from '../JiraApproval/helper'
import stepCss from '@pipeline/components/PipelineSteps/Steps/Steps.module.scss'
import css from './ApprovalRejectionCriteria.module.scss'
 
function RenderValueSelects({
  condition,
  allowedValuesForFields,
  mode,
  index,
  expressions,
  readonly
}: {
  condition: ApprovalRejectionCriteriaCondition
  allowedValuesForFields: Record<string, SelectOption[]>
  mode: string
  index: number
  expressions: string[]
  readonly?: boolean
}) {
  const { getString } = useStrings()
  if (condition.operator === 'in' || condition.operator === 'not in') {
    return (
      <FormInput.MultiSelectTypeInput
        label=""
        className={css.multiSelect}
        name={`spec.${mode}.spec.conditions[${index}].value`}
        selectItems={allowedValuesForFields[condition.key]}
        placeholder={getString('common.valuePlaceholder')}
        multiSelectTypeInputProps={{
          allowableTypes: [MultiTypeInputType.EXPRESSION, MultiTypeInputType.FIXED],
          expressions
        }}
        disabled={isApprovalStepFieldDisabled(readonly)}
      />
    )
  }
  return (
    <FormInput.MultiTypeInput
      label=""
      name={`spec.${mode}.spec.conditions[${index}].value`}
      selectItems={allowedValuesForFields[condition.key]}
      placeholder={getString('common.valuePlaceholder')}
      multiTypeInputProps={{
        allowableTypes: [MultiTypeInputType.EXPRESSION, MultiTypeInputType.FIXED],
        expressions
      }}
      disabled={isApprovalStepFieldDisabled(readonly)}
    />
  )
}
 
export function Conditions({
  values,
  onChange,
  mode,
  isFetchingFields,
  allowedValuesForFields,
  allowedFieldKeys,
  formik,
  fieldList,
  readonly,
  stepType
}: ConditionsInterface) {
  const { getString } = useStrings()
  const { expressions } = useVariablesExpression()
  const name = `spec.${mode}.spec.conditions`
  Iif (isFetchingFields) {
    return <div className={css.fetching}>{getString('pipeline.approvalCriteria.fetchingFields')}</div>
  }
  return (
    <div className={css.conditionalContent}>
      <Layout.Horizontal className={css.alignConditions} spacing="xxxlarge">
        <span>{getString('pipeline.approvalCriteria.match')}</span>
        <Radio
          onClick={() => onChange({ ...values, spec: { ...values.spec, matchAnyCondition: false } })}
          disabled={isApprovalStepFieldDisabled(readonly)}
          checked={!values.spec.matchAnyCondition}
        >
          {getString('pipeline.approvalCriteria.allConditions')}
        </Radio>
        <Radio
          onClick={() => onChange({ ...values, spec: { ...values.spec, matchAnyCondition: true } })}
          disabled={isApprovalStepFieldDisabled(readonly)}
          checked={values.spec.matchAnyCondition}
        >
          {getString('pipeline.approvalCriteria.anyCondition')}
        </Radio>
      </Layout.Horizontal>
 
      <div className={stepCss.formGroup}>
        <FieldArray
          name={name}
          render={({ push, remove }) => {
            return (
              <div className={css.criteriaRow}>
                <div className={css.headers}>
                  <span>
                    {stepType === StepType.JiraApproval
                      ? getString('pipeline.jiraApprovalStep.jiraField')
                      : getString('pipeline.approvalCriteria.field')}
                  </span>
                  <span>{getString('common.operator')}</span>
                  <span>{getString('valueLabel')}</span>
                </div>
                {values.spec.conditions?.map((condition: ApprovalRejectionCriteriaCondition, i: number) => (
                  <div className={css.headers} key={i}>
                    {isEmpty(fieldList) ? (
                      <FormInput.Text
                        disabled={isApprovalStepFieldDisabled(readonly)}
                        name={`spec.${mode}.spec.conditions[${i}].key`}
                        placeholder={getString('pipeline.keyPlaceholder')}
                      />
                    ) : (
                      <FormInput.Select
                        items={allowedFieldKeys}
                        name={`spec.${mode}.spec.conditions[${i}].key`}
                        placeholder={getString('pipeline.keyPlaceholder')}
                        disabled={isApprovalStepFieldDisabled(readonly)}
                      />
                    )}
                    <FormInput.Select
                      items={allowedValuesForFields[condition.key] ? operatorValues : filterOutMultiOperators()}
                      name={`spec.${mode}.spec.conditions[${i}].operator`}
                      placeholder={getString('pipeline.operatorPlaceholder')}
                      disabled={isApprovalStepFieldDisabled(readonly)}
                      onChange={(selectedOperator: SelectOption) => {
                        handleOperatorChange(selectedOperator, onChange, values, i)
                      }}
                    />
                    {allowedValuesForFields[condition.key] ? (
                      <RenderValueSelects
                        condition={condition}
                        allowedValuesForFields={allowedValuesForFields}
                        mode={mode}
                        index={i}
                        expressions={expressions}
                        readonly={readonly}
                      />
                    ) : (
                      <FormInput.MultiTextInput
                        label=""
                        name={`spec.${mode}.spec.conditions[${i}].value`}
                        placeholder={getString('common.valuePlaceholder')}
                        disabled={isApprovalStepFieldDisabled(readonly)}
                        multiTextInputProps={{
                          expressions,
                          allowableTypes: [MultiTypeInputType.FIXED, MultiTypeInputType.EXPRESSION]
                        }}
                      />
                    )}
 
                    <Button
                      minimal
                      disabled={isApprovalStepFieldDisabled(readonly)}
                      icon="main-trash"
                      data-testid={`remove-conditions-${i}`}
                      onClick={() => remove(i)}
                    />
                  </div>
                ))}
                <Button
                  icon="plus"
                  minimal
                  intent="primary"
                  data-testid="add-conditions"
                  disabled={isApprovalStepFieldDisabled(readonly)}
                  onClick={() => push({ key: 'Status', operator: 'equals', value: [] })}
                >
                  {getString('add')}
                </Button>
              </div>
            )
          }}
        />
      </div>
      {errorCheck(name, formik) ? (
        <Text className={css.formikError} intent="danger">
          {get(formik?.errors, name)}
        </Text>
      ) : null}
    </div>
  )
}
 
export function Jexl(props: ApprovalRejectionCriteriaProps) {
  const { getString } = useStrings()
  const { expressions } = useVariablesExpression()
  return (
    <div className={css.conditionalContentJexl}>
      <FormMultiTypeTextAreaField
        name={`spec.${props.mode}.spec.expression`}
        disabled={isApprovalStepFieldDisabled(props.readonly)}
        label={
          props.mode === 'approvalCriteria'
            ? getString('pipeline.approvalCriteria.jexlExpressionLabelApproval')
            : getString('pipeline.approvalCriteria.jexlExpressionLabelRejection')
        }
        className={css.jexlExpression}
        placeholder={getString('pipeline.jiraApprovalStep.jexlExpressionPlaceholder')}
        multiTypeTextArea={{
          expressions
        }}
      />
    </div>
  )
}
 
export function ApprovalRejectionCriteria(props: ApprovalRejectionCriteriaProps): React.ReactElement {
  const { values, onChange, title, readonly, stepType } = props
  const [type, setType] = useState<ApprovalRejectionCriteriaType>(values.type)
  const [allowedFieldKeys, setAllowedFieldKeys] = useState<SelectOption[]>([])
  const [allowedValuesForFields, setAllowedValuesForFields] = useState<Record<string, SelectOption[]>>({})
  const { getString } = useStrings()
 
  useEffect(() => {
    const allowedFieldKeysToSet: SelectOption[] = [{ label: 'Status', value: 'Status' }]
    const allowedValuesForFieldsToSet: Record<string, SelectOption[]> = {}
    Iif (!isEmpty(props.statusList)) {
      // If the status list is non empty, initialise it so that status is by default a dropdown
      allowedValuesForFieldsToSet['Status'] = props.statusList.map(status => ({ label: status.name, value: status.id }))
    }
    props.fieldList.forEach((field: JiraFieldNG) => {
      const fieldName = field.name || field.key
      if (!field.schema.array) {
        if (field.schema.type === 'string') {
          allowedFieldKeysToSet.push({
            label: fieldName,
            value: fieldName
          })
        } else if (field.allowedValues && field.schema.type === 'option' && fieldName) {
          allowedFieldKeysToSet.push({
            label: fieldName,
            value: fieldName
          })
          allowedValuesForFieldsToSet[fieldName] = setAllowedValuesOptions(field.allowedValues)
        }
      }
    })
    setAllowedFieldKeys(removeDuplicateFieldKeys(allowedFieldKeysToSet))
    setAllowedValuesForFields(allowedValuesForFieldsToSet)
  }, [props.fieldList, props.statusList])
 
  useEffect(() => {
    onChange({
      ...values,
      type
    })
  }, [type])
 
  const tooltipId = stepType === StepType.JiraApproval ? `jiraApproval${props.mode}` : `approval${props.mode}`
 
  return (
    <div className={css.box}>
      <div className="ng-tooltip-native">
        <div data-tooltip-id={tooltipId} className={stepCss.stepSubSectionHeading}>
          {title}
        </div>
        <HarnessDocTooltip tooltipId={tooltipId} useStandAlone={true} />
      </div>
 
      <div className={css.tabs}>
        <Radio
          onClick={() => setType(ApprovalRejectionCriteriaType.KeyValues)}
          disabled={isApprovalStepFieldDisabled(readonly)}
          checked={type === ApprovalRejectionCriteriaType.KeyValues}
          className={css.tab}
        >
          {getString('conditions')}
        </Radio>
        <Radio
          onClick={() => setType(ApprovalRejectionCriteriaType.Jexl)}
          disabled={isApprovalStepFieldDisabled(readonly)}
          checked={type === ApprovalRejectionCriteriaType.Jexl}
          className={css.tab}
        >
          {getString('common.jexlExpression')}
        </Radio>
      </div>
 
      {type === ApprovalRejectionCriteriaType.KeyValues ? (
        <Conditions {...props} allowedFieldKeys={allowedFieldKeys} allowedValuesForFields={allowedValuesForFields} />
      ) : (
        <Jexl {...props} />
      )}
    </div>
  )
}