All files / modules/70-pipeline/components/PipelineSteps/Steps/JiraCreate JiraDynamicFieldsSelector.tsx

95.24% Statements 60/63
82.41% Branches 89/108
85% Functions 17/20
95.24% Lines 60/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 328 329 330 331              111x 111x 111x 111x                     111x     111x   111x 111x   111x 111x           111x     20x                   18x     18x 18x         18x           18x           18x 18x   18x 18x   18x 5x 4x                   18x   10x 8x 8x 8x 8x 6x 6x       6x       8x       18x 5x 4x 4x       18x                       2x                                                   2x                                                 2x                 2x 2x 2x                 11x         11x                   9x                                                     2x                   1x                             12x 10x 10x     10x                           2x                           111x   10x 8x                   8x                 8x                    
/*
 * 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 React, { useEffect, useState } from 'react'
import { FieldArray, FormikProps } from 'formik'
import { useParams } from 'react-router-dom'
import {
  Button,
  Formik,
  FormInput,
  HarnessDocTooltip,
  MultiTypeInputType,
  PageSpinner,
  Radio,
  Select,
  Text
} from '@wings-software/uicore'
import { String, useStrings } from 'framework/strings'
 
import type { AccountPathProps, PipelinePathProps, PipelineType } from '@common/interfaces/RouteInterfaces'
import { JiraFieldNG, JiraProjectNG, useGetJiraIssueCreateMetadata } from 'services/cd-ng'
 
import { useVariablesExpression } from '@pipeline/components/PipelineStudio/PiplineHooks/useVariablesExpression'
import { setIssueTypeOptions } from '../JiraApproval/helper'
import type { JiraProjectSelectOption } from '../JiraApproval/types'
import { JiraFieldSelector } from './JiraFieldSelector'
import {
  JiraCreateFieldType,
  JiraCreateFormFieldSelector,
  JiraDynamicFieldsSelectorContentInterface,
  JiraDynamicFieldsSelectorInterface
} from './types'
import css from './JiraDynamicFieldsSelector.module.scss'
 
function SelectFieldList(props: JiraDynamicFieldsSelectorContentInterface) {
  const { getString } = useStrings()
  const {
    connectorRef,
    refetchProjectMetadata,
    projectMetaResponse,
    fetchingProjectMetadata,
    showProjectDisclaimer,
    jiraType,
    selectedProjectKey: selectedProjectKeyInit,
    selectedIssueTypeKey: selectedIssueTypeKeyInit
  } = props
 
  const { accountId, projectIdentifier, orgIdentifier } =
    useParams<PipelineType<PipelinePathProps & AccountPathProps>>()
  const commonParams = {
    accountIdentifier: accountId,
    projectIdentifier,
    orgIdentifier
  }
  const [projectValue, setProjectValue] = useState<JiraProjectSelectOption>({
    key: selectedProjectKeyInit,
    value: selectedProjectKeyInit,
    label: selectedProjectKeyInit
  })
 
  const [issueTypeValue, setIssueTypeValue] = useState<JiraProjectSelectOption>({
    key: selectedIssueTypeKeyInit,
    value: selectedIssueTypeKeyInit,
    label: selectedIssueTypeKeyInit
  })
 
  const [projectMetadata, setProjectMetadata] = useState<JiraProjectNG>()
  const [fieldList, setFieldList] = useState<JiraFieldNG[]>([])
 
  const selectedProjectKey = projectValue?.key?.toString()
  const selectedIssueTypeKey = issueTypeValue?.key?.toString()
 
  useEffect(() => {
    if (connectorRef && selectedProjectKey) {
      refetchProjectMetadata({
        queryParams: {
          ...commonParams,
          connectorRef,
          projectKey: selectedProjectKey
        }
      })
    }
  }, [selectedProjectKey])
 
  useEffect(() => {
    // If issuetype changes in form, set status and field list
    if (selectedIssueTypeKey) {
      const issueTypeData = projectMetadata?.issuetypes[selectedIssueTypeKey || '']
      const fieldListToSet: JiraFieldNG[] = []
      const fieldKeys = Object.keys(issueTypeData?.fields || {})
      fieldKeys.sort().forEach(keyy => {
        Eif (issueTypeData?.fields[keyy]) {
          Eif (
            (jiraType === 'createMode' && keyy !== 'Summary' && keyy !== 'Description') ||
            jiraType === 'updateMode'
          ) {
            fieldListToSet.push(issueTypeData?.fields[keyy])
          }
        }
      })
      setFieldList(fieldListToSet)
    }
  }, [selectedIssueTypeKey, projectMetadata])
 
  useEffect(() => {
    if (selectedProjectKey && projectMetaResponse?.data?.projects) {
      const projectMD: JiraProjectNG = projectMetaResponse?.data?.projects[selectedProjectKey]
      setProjectMetadata(projectMD)
    }
  }, [projectMetaResponse?.data, selectedProjectKey])
 
  return (
    <div>
      <Text className={css.selectFieldListHelp}>{getString('pipeline.jiraCreateStep.selectFieldListHelp')}</Text>
      <div className={css.select}>
        <Text className={css.selectLabel}>{getString('pipeline.jiraApprovalStep.project')}</Text>
        <Select
          items={props.projectOptions}
          defaultSelectedItem={{
            label: selectedProjectKey,
            value: selectedProjectKey
          }}
          onChange={value => {
            setProjectValue(value as JiraProjectSelectOption)
          }}
          inputProps={{
            placeholder: getString('pipeline.jiraCreateStep.selectProject')
          }}
        />
      </div>
 
      <div className={css.select}>
        <Text className={css.selectLabel}>{getString('pipeline.jiraApprovalStep.issueType')}</Text>
        <Select
          items={
            fetchingProjectMetadata
              ? [{ label: 'Fetching Issue Types...', value: '' }]
              : setIssueTypeOptions(projectMetadata?.issuetypes)
          }
          inputProps={{
            placeholder: fetchingProjectMetadata
              ? getString('pipeline.jiraApprovalStep.fetchingIssueTypePlaceholder')
              : getString('pipeline.jiraApprovalStep.issueTypePlaceholder')
          }}
          defaultSelectedItem={{
            label: selectedIssueTypeKey,
            value: selectedIssueTypeKey
          }}
          onChange={value => {
            setIssueTypeValue(value as JiraProjectSelectOption)
          }}
        />
      </div>
 
      {fetchingProjectMetadata ? (
        <PageSpinner
          message={getString('pipeline.jiraCreateStep.fetchingFields')}
          className={css.fetchingPageSpinner}
        />
      ) : null}
 
      {!selectedIssueTypeKey ? (
        <div className={css.fieldsSelectorPlaceholder}>
          <Text>{getString('pipeline.jiraCreateStep.fieldsSelectorPlaceholder')}</Text>
        </div>
      ) : (
        <div>
          {showProjectDisclaimer ? (
            <Text intent="warning">{getString('pipeline.jiraUpdateStep.projectIssueTypeDisclaimer')}</Text>
          ) : null}
          <JiraFieldSelector
            fields={fieldList}
            selectedFields={props?.selectedFields || []}
            onCancel={props.onCancel}
            addSelectedFields={fields => props.addSelectedFields(fields, selectedProjectKey, selectedIssueTypeKey)}
          />
        </div>
      )}
    </div>
  )
}
 
function ProvideFieldList(props: JiraDynamicFieldsSelectorContentInterface) {
  const { getString } = useStrings()
  const { expressions } = useVariablesExpression()
  return (
    <Formik<JiraCreateFieldType[]>
      onSubmit={values => {
        props.provideFieldList(values)
      }}
      formName="jiraFields"
      initialValues={[]}
    >
      {(formik: FormikProps<{ fieldList: JiraCreateFieldType[] }>) => {
        return (
          <div>
            <FieldArray
              name="fieldList"
              render={({ push, remove }) => {
                return (
                  <div>
                    {formik.values.fieldList?.length ? (
                      <div className={css.headerRow}>
                        <String className={css.label} stringID="keyLabel" />
                        <String className={css.label} stringID="valueLabel" />
                      </div>
                    ) : null}
 
                    {formik.values.fieldList?.map((_unused: JiraCreateFieldType, i: number) => (
                      <div className={css.headerRow} key={i}>
                        <FormInput.Text
                          name={`fieldList[${i}].name`}
                          placeholder={getString('pipeline.keyPlaceholder')}
                        />
                        <FormInput.MultiTextInput
                          name={`fieldList[${i}].value`}
                          label=""
                          placeholder={getString('common.valuePlaceholder')}
                          multiTextInputProps={{
                            allowableTypes: [MultiTypeInputType.FIXED, MultiTypeInputType.EXPRESSION],
                            expressions
                          }}
                        />
                        <Button
                          minimal
                          icon="main-trash"
                          data-testid={`remove-fieldList-${i}`}
                          onClick={() => remove(i)}
                        />
                      </div>
                    ))}
                    <Button
                      icon="plus"
                      minimal
                      intent="primary"
                      data-testid="add-fieldList"
                      onClick={() => push({ name: '', value: '' })}
                      className={css.addFieldsButton}
                    >
                      {getString('pipeline.jiraCreateStep.addFields')}
                    </Button>
                  </div>
                )
              }}
            />
            <div className={css.buttons}>
              <Button intent="primary" type="submit" onClick={() => props.provideFieldList(formik.values.fieldList)}>
                {getString('add')}
              </Button>
              <Button className={css.secondButton} onClick={props.onCancel}>
                {getString('cancel')}
              </Button>
            </div>
          </div>
        )
      }}
    </Formik>
  )
}
 
function Content(props: JiraDynamicFieldsSelectorContentInterface) {
  const { getString } = useStrings()
  const { connectorRef } = props
  const [type, setType] = useState<JiraCreateFormFieldSelector>(
    connectorRef ? JiraCreateFormFieldSelector.FIXED : JiraCreateFormFieldSelector.EXPRESSION
  )
  return (
    <div className={css.contentWrapper}>
      <div className={css.radioGroup}>
        <Radio
          onClick={() => setType(JiraCreateFormFieldSelector.FIXED)}
          checked={type === JiraCreateFormFieldSelector.FIXED}
          disabled={!connectorRef}
        >
          <span data-tooltip-id="jiraSelectFromFieldList">
            {getString('pipeline.jiraCreateStep.selectFromFieldList')}{' '}
            <HarnessDocTooltip useStandAlone={true} tooltipId="jiraSelectFromFieldList" />
          </span>
        </Radio>
        <Radio
          onClick={() => setType(JiraCreateFormFieldSelector.EXPRESSION)}
          checked={type === JiraCreateFormFieldSelector.EXPRESSION}
        >
          <span data-tooltip-id="jiraProvideFromFieldList">
            {getString('pipeline.jiraCreateStep.provideFieldList')}{' '}
            <HarnessDocTooltip useStandAlone={true} tooltipId="jiraProvideFromFieldList" />
          </span>
        </Radio>
      </div>
      {type === JiraCreateFormFieldSelector.FIXED ? <SelectFieldList {...props} /> : <ProvideFieldList {...props} />}
    </div>
  )
}
 
export function JiraDynamicFieldsSelector(props: JiraDynamicFieldsSelectorInterface) {
  const { accountId, projectIdentifier, orgIdentifier } =
    useParams<PipelineType<PipelinePathProps & AccountPathProps>>()
  const commonParams = {
    accountIdentifier: accountId,
    projectIdentifier,
    orgIdentifier
  }
  const {
    refetch: refetchProjectMetadata,
    data: projectMetaResponse,
    error: projectMetadataFetchError,
    loading: fetchingProjectMetadata
  } = useGetJiraIssueCreateMetadata({
    lazy: true,
    queryParams: {
      ...commonParams,
      connectorRef: '',
      projectKey: ''
    }
  })
 
  return (
    <Content
      {...props}
      refetchProjectMetadata={refetchProjectMetadata}
      projectMetaResponse={projectMetaResponse}
      projectMetadataFetchError={projectMetadataFetchError}
      fetchingProjectMetadata={fetchingProjectMetadata}
    />
  )
}