All files / modules/72-templates-library/components/PipelineSteps/TemplateStep/TemplateStepWidget TemplateStepWidget.tsx

85.25% Statements 52/61
43.12% Branches 47/109
50% Functions 4/8
85.25% Lines 52/61

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              2x 2x                   2x 2x 2x   2x 2x 2x 2x 2x 2x 2x 2x       2x 2x 2x 2x   2x 2x 2x 2x 2x 2x 2x                                           2x 2x 2x 2x 2x 2x 2x 2x 2x             2x                               2x                     2x 1x 1x 1x 1x 1x   1x 1x 1x     1x 1x             2x                             2x         2x                               3x 3x                                                                                                                             2x  
/*
 * 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.
 */
 
import React from 'react'
import {
  Container,
  Formik,
  FormikForm,
  FormInput,
  Layout,
  MultiTypeInputType,
  Heading,
  PageError
} from '@wings-software/uicore'
import * as Yup from 'yup'
import { Color } from '@harness/design-system'
import cx from 'classnames'
import type { FormikProps } from 'formik'
import { useParams } from 'react-router-dom'
import { parse } from 'yaml'
import { defaultTo, get, isEmpty, merge, noop, set } from 'lodash-es'
import produce from 'immer'
import useRBACError from '@rbac/utils/useRBACError/useRBACError'
import { IdentifierSchema, NameSchema } from '@common/utils/Validation'
import { setFormikRef, StepViewType, StepFormikFowardRef } from '@pipeline/components/AbstractSteps/Step'
import { useStrings } from 'framework/strings'
import type { AbstractStepFactory } from '@pipeline/components/AbstractSteps/AbstractStepFactory'
import type { Error, StepElementConfig } from 'services/cd-ng'
import type { ProjectPathProps, GitQueryParams } from '@common/interfaces/RouteInterfaces'
import { useGetTemplate, useGetTemplateInputSetYaml } from 'services/template-ng'
import { useToaster } from '@common/exports'
import { PageSpinner } from '@common/components'
import { getIdentifierFromValue, getScopeFromValue } from '@common/components/EntityReference/EntityReference'
import type { TemplateStepNode } from 'services/pipeline-ng'
import { validateStep } from '@pipeline/components/PipelineStudio/StepUtil'
import { StepForm } from '@pipeline/components/PipelineInputSetForm/StageInputSetForm'
import { setTemplateInputs, TEMPLATE_INPUT_PATH } from '@pipeline/utils/templateUtils'
import { getScopeBasedQueryParams } from '@templates-library/utils/templatesUtils'
import { useQueryParams } from '@common/hooks'
import stepCss from '@pipeline/components/PipelineSteps/Steps/Steps.module.scss'
import css from './TemplateStepWidget.module.scss'
 
export interface TemplateStepWidgetProps {
  initialValues: TemplateStepNode
  isNewStep?: boolean
  isDisabled?: boolean
  onUpdate?: (data: TemplateStepNode) => void
  stepViewType?: StepViewType
  readonly?: boolean
  factory: AbstractStepFactory
  allowableTypes: MultiTypeInputType[]
}
 
export interface TemplateStepValues extends TemplateStepNode {
  inputsTemplate?: StepElementConfig
  allValues?: StepElementConfig
}
 
function TemplateStepWidget(
  props: TemplateStepWidgetProps,
  formikRef: StepFormikFowardRef<TemplateStepNode>
): React.ReactElement {
  const { initialValues, onUpdate, isNewStep, readonly, allowableTypes } = props
  const [formValues, setFormValues] = React.useState<TemplateStepValues>(initialValues)
  const { getString } = useStrings()
  const queryParams = useParams<ProjectPathProps>()
  const { branch, repoIdentifier } = useQueryParams<GitQueryParams>()
  const { showError } = useToaster()
  const { getRBACErrorMessage } = useRBACError()
  const stepTemplateRef = getIdentifierFromValue(initialValues.template.templateRef)
  const scope = getScopeFromValue(initialValues.template.templateRef)
 
  const {
    data: stepTemplateResponse,
    error: stepTemplateError,
    refetch: refetchStepTemplate,
    loading: stepTemplateLoading
  } = useGetTemplate({
    templateIdentifier: stepTemplateRef,
    queryParams: {
      ...getScopeBasedQueryParams(queryParams, scope),
      versionLabel: defaultTo(initialValues.template.versionLabel, ''),
      repoIdentifier,
      branch,
      getDefaultFromOtherRepo: true
    }
  })
 
  const {
    data: stepTemplateInputSetYaml,
    error: stepTemplateInputSetError,
    refetch: refetchStepTemplateInputSet,
    loading: stepTemplateInputSetLoading
  } = useGetTemplateInputSetYaml({
    templateIdentifier: stepTemplateRef,
    queryParams: {
      ...getScopeBasedQueryParams(queryParams, scope),
      versionLabel: defaultTo(initialValues.template.versionLabel, ''),
      repoIdentifier,
      branch,
      getDefaultFromOtherRepo: true
    }
  })
 
  React.useEffect(() => {
    Eif (!stepTemplateLoading && !stepTemplateInputSetLoading && stepTemplateResponse?.data?.yaml) {
      try {
        const templateInputs = parse(defaultTo(stepTemplateInputSetYaml?.data, ''))
        const mergedTemplateInputs = merge({}, templateInputs, initialValues.template?.templateInputs)
        setFormValues(
          produce(initialValues as TemplateStepValues, draft => {
            setTemplateInputs(draft, mergedTemplateInputs)
            draft.inputsTemplate = templateInputs
            draft.allValues = parse(defaultTo(stepTemplateResponse?.data?.yaml, '')).template.spec
          })
        )
        setTemplateInputs(initialValues, mergedTemplateInputs)
        onUpdate?.(initialValues)
      } catch (error) {
        showError(getRBACErrorMessage(error), undefined, 'template.parse.inputSet.error')
      }
    }
  }, [stepTemplateLoading, stepTemplateResponse?.data && stepTemplateInputSetLoading && stepTemplateInputSetYaml?.data])
 
  const validateForm = (values: TemplateStepValues) => {
    const errorsResponse = validateStep({
      step: values.template?.templateInputs as StepElementConfig,
      template: values.inputsTemplate,
      originalStep: { step: formValues?.template?.templateInputs as StepElementConfig },
      getString,
      viewType: StepViewType.DeploymentForm
    })
    if (!isEmpty(errorsResponse)) {
      return set({}, TEMPLATE_INPUT_PATH, get(errorsResponse, 'step'))
    } else {
      return errorsResponse
    }
  }
 
  const refetch = () => {
    refetchStepTemplate()
    refetchStepTemplateInputSet()
  }
 
  return (
    <div className={stepCss.stepPanel}>
      <Formik<TemplateStepValues>
        onSubmit={values => {
          onUpdate?.(values)
        }}
        initialValues={formValues}
        formName="templateStepWidget"
        validationSchema={Yup.object().shape({
          name: NameSchema({ requiredErrorMsg: getString('pipelineSteps.stepNameRequired') }),
          identifier: IdentifierSchema()
        })}
        validate={validateForm}
        enableReinitialize={true}
      >
        {(formik: FormikProps<TemplateStepValues>) => {
          setFormikRef(formikRef, formik)
          return (
            <FormikForm>
              <div className={cx(stepCss.formGroup, stepCss.md)}>
                <FormInput.InputWithIdentifier
                  isIdentifierEditable={isNewStep && !readonly}
                  inputLabel={getString('name')}
                  inputGroupProps={{ disabled: readonly }}
                />
              </div>
              <Container className={css.inputsContainer}>
                {(stepTemplateLoading || stepTemplateInputSetLoading) && <PageSpinner />}
                {!stepTemplateLoading &&
                  !stepTemplateInputSetLoading &&
                  (stepTemplateError || stepTemplateInputSetError) && (
                    <Container height={300}>
                      <PageError
                        message={
                          defaultTo((stepTemplateError?.data as Error)?.message, stepTemplateError?.message) ||
                          defaultTo(
                            (stepTemplateInputSetError?.data as Error)?.message,
                            stepTemplateInputSetError?.message
                          )
                        }
                        onClick={() => refetch()}
                      />
                    </Container>
                  )}
                {!stepTemplateLoading &&
                  !stepTemplateInputSetLoading &&
                  !stepTemplateError &&
                  !stepTemplateInputSetError &&
                  formik.values.inputsTemplate &&
                  formik.values.allValues && (
                    <Layout.Vertical padding={{ top: 'large', bottom: 'large' }} spacing={'large'}>
                      <Heading level={5} color={Color.BLACK}>
                        {getString('templatesLibrary.templateInputs')}
                      </Heading>
                      <StepForm
                        key={`${formik.values.template.templateRef}-${defaultTo(
                          formik.values.template.versionLabel,
                          ''
                        )}`}
                        template={{ step: formik.values.inputsTemplate }}
                        values={{ step: formik.values.template?.templateInputs as StepElementConfig }}
                        allValues={{ step: formik.values.allValues }}
                        readonly={readonly}
                        viewType={StepViewType.InputSet}
                        path={TEMPLATE_INPUT_PATH}
                        allowableTypes={allowableTypes}
                        onUpdate={noop}
                        hideTitle={true}
                      />
                    </Layout.Vertical>
                  )}
              </Container>
            </FormikForm>
          )
        }}
      </Formik>
    </div>
  )
}
 
export const TemplateStepWidgetWithRef = React.forwardRef(TemplateStepWidget)