All files / modules/70-pipeline/components/PipelineSteps/Steps/JiraApproval helper.ts

92.38% Statements 97/105
69.53% Branches 89/128
87.5% Functions 21/24
94.19% Lines 81/86

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              115x   115x   115x             115x   5x   2x   3x   2x     2x     115x 7x   115x       6x               5x                     6x 1x 1x 5x 5x   6x     115x 1x                                             115x             4x 4x   4x   4x                                 280x               115x           10x     10x         4x                         115x   4x                                                   115x 6x 6x 6x     6x 6x       115x                                     115x 152x   115x 135x 135x 135x 34x 34x           135x     115x 3x 1x 1x 1x 1x 1x   3x 1x 1x 1x 1x   3x 1x 1x 1x       115x       113x   77x   36x   6x   30x     115x 1x         115x           8x   6x 6x 6x 6x 6x        
/*
 * Copyright 2021 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 { getMultiTypeFromValue, MultiSelectOption, MultiTypeInputType, SelectOption } from '@wings-software/uicore'
import type { FormikProps } from 'formik'
import { isEmpty } from 'lodash-es'
import type { JiraFieldAllowedValueNG, JiraFieldNG, JiraIssueTypeNG, JiraStatusNG } from 'services/cd-ng'
import {
  ApprovalRejectionCriteria,
  ApprovalRejectionCriteriaCondition,
  ApprovalRejectionCriteriaType
} from '@pipeline/components/PipelineSteps/Steps/Common/types'
import type { JiraApprovalData, JiraProjectSelectOption } from './types'
 
const getApprovalRejectionConditionValuesForSubmit = (values: string | SelectOption | MultiSelectOption[]): string => {
  // The selected values can be string, selectoption or multiselect options
  if (typeof values === 'string') {
    // Simple text input
    return values
  }
  if (Array.isArray(values)) {
    // Multi select
    return values.map(v => v.value?.toString()).join(',')
  }
  // Single select
  return values.value.toString()
}
 
export const filterNonEmptyConditions = (condition: ApprovalRejectionCriteriaCondition) =>
  condition.key && condition.value
 
export const getApprovalRejectionCriteriaForSubmit = (
  criteria: ApprovalRejectionCriteria
): ApprovalRejectionCriteria => {
  // Convert the approval/rejection criteria 'value' field to string/string[], from selectoption
  const criteriaToReturn: ApprovalRejectionCriteria = {
    type: criteria.type,
    spec: {
      matchAnyCondition: criteria.spec.matchAnyCondition,
      expression: criteria.spec.expression,
      conditions: criteria.spec.conditions
        ?.filter(filterNonEmptyConditions)
        .map((condition: ApprovalRejectionCriteriaCondition) => {
          return {
            key: condition.key,
            operator: condition.operator,
            value:
              getMultiTypeFromValue(condition.value) !== MultiTypeInputType.EXPRESSION
                ? getApprovalRejectionConditionValuesForSubmit(condition.value)
                : condition.value
          }
        })
    }
  }
  if (criteriaToReturn.type === ApprovalRejectionCriteriaType.Jexl) {
    delete criteriaToReturn.spec.conditions
    delete criteriaToReturn.spec.matchAnyCondition
  } else Eif (criteriaToReturn.type === ApprovalRejectionCriteriaType.KeyValues) {
    delete criteriaToReturn.spec.expression
  }
  return criteriaToReturn
}
 
export const processFormData = (values: JiraApprovalData): JiraApprovalData => {
  return {
    ...values,
    spec: {
      ...values.spec,
      connectorRef:
        getMultiTypeFromValue(values.spec.connectorRef as SelectOption) === MultiTypeInputType.FIXED
          ? (values.spec.connectorRef as SelectOption)?.value?.toString()
          : values.spec.connectorRef,
      projectKey:
        getMultiTypeFromValue(values.spec.projectKey as JiraProjectSelectOption) === MultiTypeInputType.FIXED
          ? (values.spec.projectKey as JiraProjectSelectOption)?.key?.toString()
          : values.spec.projectKey,
      issueType:
        getMultiTypeFromValue(values.spec.issueType as JiraProjectSelectOption) === MultiTypeInputType.FIXED
          ? (values.spec.issueType as JiraProjectSelectOption)?.key?.toString()
          : values.spec.issueType,
      issueKey: values.spec.issueKey,
      approvalCriteria: getApprovalRejectionCriteriaForSubmit(values.spec.approvalCriteria),
      rejectionCriteria: getApprovalRejectionCriteriaForSubmit(values.spec.rejectionCriteria)
    }
  }
}
 
const getInitialApprovalRejectionConditionValues = (
  condition: ApprovalRejectionCriteriaCondition,
  statusList: JiraStatusNG[] = [],
  fieldList: JiraFieldNG[] = []
): string | SelectOption | MultiSelectOption[] => {
  // The value in YAML is always a string.
  // We'll figure out the component from operator and key
  const { operator, value, key } = condition
  const list = key === 'Status' ? statusList : fieldList.find(field => field.name === key)?.allowedValues
 
  Eif (isEmpty(list)) {
    // Simple text input
    return value?.toString()
  }
 
  if ((operator === 'in' || operator === 'not in') && typeof value === 'string') {
    // Multi select
    return value.split(',').map(each => ({
      label: each,
      value: each
    }))
  }
  // Single select
  return {
    label: value.toString(),
    value: value.toString()
  }
}
 
export const getDefaultCriterias = (): ApprovalRejectionCriteria => ({
  type: ApprovalRejectionCriteriaType.KeyValues,
  spec: {
    matchAnyCondition: true,
    conditions: []
  }
})
 
export const getApprovalRejectionCriteriaForInitialValues = (
  criteria: ApprovalRejectionCriteria,
  statusList: JiraStatusNG[] = [],
  fieldList: JiraFieldNG[] = []
): ApprovalRejectionCriteria => {
  // Convert the approval/rejection criteria 'value' field to selectoption, from string/string[]
  Iif (!criteria) {
    return getDefaultCriterias()
  }
  return {
    ...criteria,
    spec: {
      ...criteria.spec,
      conditions: Array.isArray(criteria.spec.conditions)
        ? criteria.spec.conditions?.map((condition: ApprovalRejectionCriteriaCondition) => ({
            key: condition.key,
            operator: condition.operator,
            value:
              getMultiTypeFromValue(condition.value) === MultiTypeInputType.FIXED
                ? getInitialApprovalRejectionConditionValues(condition, statusList, fieldList)
                : condition.value
          }))
        : []
    }
  }
}
 
export const processInitialValues = (values: JiraApprovalData): JiraApprovalData => {
  // Convert string values in approval/rejection criteria condition to SelectOption, so that it's populated in edit
  return {
    ...values,
    spec: {
      ...values.spec,
      projectKey:
        values.spec.projectKey && getMultiTypeFromValue(values.spec.projectKey) === MultiTypeInputType.FIXED
          ? {
              label: values.spec.projectKey.toString(),
              value: values.spec.projectKey.toString(),
              key: values.spec.projectKey.toString()
            }
          : values.spec.projectKey,
      issueType:
        values.spec.issueType && getMultiTypeFromValue(values.spec.issueType) === MultiTypeInputType.FIXED
          ? {
              label: values.spec.issueType.toString(),
              value: values.spec.issueType.toString(),
              key: values.spec.issueType.toString()
            }
          : values.spec.issueType,
      approvalCriteria: getApprovalRejectionCriteriaForInitialValues(values.spec.approvalCriteria),
      rejectionCriteria: getApprovalRejectionCriteriaForInitialValues(values.spec.rejectionCriteria)
    }
  }
}
 
export const removeDuplicateFieldKeys = (fieldKeys: SelectOption[]) => {
  const labelMap: Record<string, boolean> = {}
  return fieldKeys.filter(keyy => {
    Iif (labelMap[keyy.label]) {
      return false
    }
    labelMap[keyy.label] = true
    return true
  })
}
 
export const operatorValues: SelectOption[] = [
  {
    label: '=',
    value: 'equals'
  },
  {
    label: '!=',
    value: 'not equals'
  },
  {
    label: 'in',
    value: 'in'
  },
  {
    label: 'not in',
    value: 'not in'
  }
]
 
export const filterOutMultiOperators = (): SelectOption[] =>
  operatorValues.filter(opValue => opValue.value === 'equals' || opValue.value === 'not equals')
 
export const setIssueTypeOptions = (issuetypes: { [key: string]: JiraIssueTypeNG } = {}): JiraProjectSelectOption[] => {
  const keys = Object.keys(issuetypes)
  const toReturn: JiraProjectSelectOption[] = []
  keys.forEach(keyy => {
    const issueTypeObject = issuetypes[keyy]
    toReturn.push({
      label: issueTypeObject.name,
      value: issueTypeObject.name,
      key: keyy
    })
  })
  return toReturn
}
 
export const resetForm = (formik: FormikProps<JiraApprovalData>, parent: string) => {
  if (parent === 'connectorRef') {
    formik.setFieldValue('spec.projectKey', '')
    formik.setFieldValue('spec.issueType', '')
    formik.setFieldValue('spec.issueKey', '')
    formik.setFieldValue('spec.approvalCriteria', getDefaultCriterias())
    formik.setFieldValue('spec.rejectionCriteria', getDefaultCriterias())
  }
  if (parent === 'projectKey') {
    formik.setFieldValue('spec.issueType', '')
    formik.setFieldValue('spec.issueKey', '')
    formik.setFieldValue('spec.approvalCriteria', getDefaultCriterias())
    formik.setFieldValue('spec.rejectionCriteria', getDefaultCriterias())
  }
  if (parent === 'issueType') {
    formik.setFieldValue('spec.issueKey', '')
    formik.setFieldValue('spec.approvalCriteria', getDefaultCriterias())
    formik.setFieldValue('spec.rejectionCriteria', getDefaultCriterias())
  }
}
 
export const getGenuineValue = (value: SelectOption | JiraProjectSelectOption | string): string | undefined => {
  // This function returns true if the value is fixed
  // i.e. selected from dropdown
  // We'll use this value to make API calls for depedent fields
  if (typeof value === 'object') {
    // Either SelectOption or JiraProjectSelectOption - the value has been selected from the form
    return value.value.toString()
  }
  if (getMultiTypeFromValue(value) === MultiTypeInputType.FIXED && value) {
    // Value is present as string and supplied as initialValues
    return value
  }
  return undefined
}
 
export const setAllowedValuesOptions = (allowedValues: JiraFieldAllowedValueNG[]): MultiSelectOption[] =>
  allowedValues.map(allowedValue => ({
    label: allowedValue.value || allowedValue.name || allowedValue.id || '',
    value: allowedValue.value || allowedValue.name || allowedValue.id || ''
  }))
 
export const handleOperatorChange = (
  selectedOperator: SelectOption,
  onChange: (values: ApprovalRejectionCriteria) => void,
  values: ApprovalRejectionCriteria,
  i: number
) => {
  if (selectedOperator?.value === 'in' || selectedOperator?.value === 'not in') {
    // When we swiatch from sigle select to mmultiselect, flush the already selected value
    Eif (values.spec.conditions) {
      const tobeUpdatedConditions = [...values.spec.conditions]
      tobeUpdatedConditions[i].operator = selectedOperator.value
      tobeUpdatedConditions[i].value = []
      onChange({ ...values, spec: { ...values.spec, conditions: tobeUpdatedConditions } })
    }
  }
}