All files / modules/72-templates-library/components/TemplateStageSpecifications TemplateStageSpecifications.tsx

96.39% Statements 80/83
74.68% Branches 177/237
91.67% Functions 11/12
96.3% Lines 78/81

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              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                 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x 6x   6x   1x                   6x                               6x                     6x 3x 3x 3x 3x 3x   3x 3x 3x           3x 3x             6x 3x 3x     6x       6x 2x       2x 2x             2x           6x 1x 1x     6x   6x   6x             12x                                                 11x 11x 11x                                         1x                                                                                      
/*
 * 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, { useContext } from 'react'
import { debounce, defaultTo, isEqual, merge, noop, omit, set } from 'lodash-es'
import { Card, Container, Formik, FormikForm, Heading, Layout, PageError } from '@wings-software/uicore'
import * as Yup from 'yup'
import { Color } from '@harness/design-system'
import { useParams } from 'react-router-dom'
import { parse } from 'yaml'
import type { FormikProps } from 'formik'
import produce from 'immer'
import { usePipelineContext } from '@pipeline/components/PipelineStudio/PipelineContext/PipelineContext'
import type { Error, StageElementConfig } from 'services/cd-ng'
import { useStrings } from 'framework/strings'
import useRBACError from '@rbac/utils/useRBACError/useRBACError'
import { IdentifierSchema, NameSchema } from '@common/utils/Validation'
import { PageSpinner } from '@common/components'
import { getIdentifierFromValue, getScopeFromValue } from '@common/components/EntityReference/EntityReference'
import type { ProjectPathProps, GitQueryParams } from '@common/interfaces/RouteInterfaces'
import { NameId } from '@common/components/NameIdDescriptionTags/NameIdDescriptionTags'
import { useToaster } from '@common/exports'
import { useGetTemplate, useGetTemplateInputSetYaml } from 'services/template-ng'
import { StepViewType } from '@pipeline/components/AbstractSteps/Step'
import { StageForm } from '@pipeline/components/PipelineInputSetForm/PipelineInputSetForm'
import { StageErrorContext } from '@pipeline/context/StageErrorContext'
import { TemplateTabs } from '@templates-library/components/TemplateStageSetupShell/TemplateStageSetupShellUtils'
import { validateStage } from '@pipeline/components/PipelineStudio/StepUtil'
import { useGlobalEventListener, useQueryParams } from '@common/hooks'
import ErrorsStripBinded from '@pipeline/components/ErrorsStrip/ErrorsStripBinded'
import { useStageTemplateActions } from '@pipeline/utils/useStageTemplateActions'
import { TemplateBar } from '@pipeline/components/PipelineStudio/TemplateBar/TemplateBar'
import { setTemplateInputs, TEMPLATE_INPUT_PATH } from '@pipeline/utils/templateUtils'
import { getScopeBasedQueryParams } from '@templates-library/utils/templatesUtils'
import css from './TemplateStageSpecifications.module.scss'
 
declare global {
  interface WindowEventMap {
    SAVE_PIPELINE_CLICKED: CustomEvent<string>
  }
}
 
export interface TemplateStageValues extends StageElementConfig {
  inputsTemplate?: StageElementConfig
  allValues?: StageElementConfig
}
 
export const TemplateStageSpecifications = (): JSX.Element => {
  const {
    state: {
      selectionState: { selectedStageId = '' }
    },
    allowableTypes,
    updateStage,
    isReadonly,
    getStageFromPipeline
  } = usePipelineContext()
  const { stage } = getStageFromPipeline(selectedStageId)
  const queryParams = useParams<ProjectPathProps>()
  const { branch, repoIdentifier } = useQueryParams<GitQueryParams>()
  const [formValues, setFormValues] = React.useState<TemplateStageValues>(stage?.stage as TemplateStageValues)
  const templateRef = getIdentifierFromValue(defaultTo(stage?.stage?.template?.templateRef, ''))
  const scope = getScopeFromValue(defaultTo(stage?.stage?.template?.templateRef, ''))
  const { subscribeForm, unSubscribeForm } = React.useContext(StageErrorContext)
  const formikRef = React.useRef<FormikProps<unknown> | null>(null)
  const { submitFormsForTab } = useContext(StageErrorContext)
  const { showError } = useToaster()
  const { getRBACErrorMessage } = useRBACError()
  const { getString } = useStrings()
 
  const onChange = React.useCallback(
    debounce(async (values: StageElementConfig): Promise<void> => {
      await updateStage({ ...stage?.stage, ...values })
    }, 300),
    [stage?.stage, updateStage]
  )
 
  const {
    data: templateResponse,
    error: templateError,
    refetch: refetchTemplate,
    loading: templateLoading
  } = useGetTemplate({
    templateIdentifier: templateRef,
    queryParams: {
      ...getScopeBasedQueryParams(queryParams, scope),
      versionLabel: defaultTo(stage?.stage?.template?.versionLabel, ''),
      repoIdentifier,
      branch,
      getDefaultFromOtherRepo: true
    }
  })
 
  const {
    data: templateInputSetYaml,
    error: templateInputSetError,
    refetch: refetchTemplateInputSet,
    loading: templateInputSetLoading
  } = useGetTemplateInputSetYaml({
    templateIdentifier: templateRef,
    queryParams: {
      ...getScopeBasedQueryParams(queryParams, scope),
      versionLabel: defaultTo(stage?.stage?.template?.versionLabel, ''),
      repoIdentifier,
      branch,
      getDefaultFromOtherRepo: true
    }
  })
 
  React.useEffect(() => {
    Eif (!templateLoading && !templateInputSetLoading && stage?.stage && templateResponse?.data?.yaml) {
      try {
        const templateInputs = parse(defaultTo(templateInputSetYaml?.data, ''))
        const mergedTemplateInputs = merge({}, templateInputs, stage?.stage.template?.templateInputs)
        setFormValues(
          produce(stage?.stage as TemplateStageValues, draft => {
            setTemplateInputs(draft, mergedTemplateInputs)
            draft.inputsTemplate = templateInputs
            draft.allValues = {
              ...parse(defaultTo(templateResponse?.data?.yaml, '')).template.spec,
              identifier: stage.stage?.identifier
            }
          })
        )
        setTemplateInputs(stage.stage, mergedTemplateInputs)
        updateStage(stage.stage)
      } catch (error) {
        showError(getRBACErrorMessage(error), undefined, 'template.parse.inputSet.error')
      }
    }
  }, [templateLoading, templateResponse?.data && templateInputSetLoading && templateInputSetYaml?.data])
 
  React.useEffect(() => {
    subscribeForm({ tab: TemplateTabs.OVERVIEW, form: formikRef })
    return () => unSubscribeForm({ tab: TemplateTabs.OVERVIEW, form: formikRef })
  }, [subscribeForm, unSubscribeForm, formikRef])
 
  useGlobalEventListener('SAVE_PIPELINE_CLICKED', _event => {
    submitFormsForTab(TemplateTabs.OVERVIEW)
  })
 
  const validateForm = (values: TemplateStageValues) => {
    Eif (
      isEqual(values.template?.templateRef, stage?.stage?.template?.templateRef) &&
      isEqual(values.template?.versionLabel, stage?.stage?.template?.versionLabel)
    ) {
      onChange?.(omit(values, 'inputsTemplate', 'allValues'))
      const errorsResponse = validateStage({
        stage: values.template?.templateInputs as StageElementConfig,
        template: values.inputsTemplate,
        originalStage: stage?.stage?.template?.templateInputs as StageElementConfig,
        getString,
        viewType: StepViewType.DeploymentForm
      })
      return set({}, TEMPLATE_INPUT_PATH, errorsResponse)
    } else {
      return {}
    }
  }
 
  const refetch = () => {
    refetchTemplate()
    refetchTemplateInputSet()
  }
 
  const { addOrUpdateTemplate, removeTemplate } = useStageTemplateActions()
 
  const formRefDom = React.useRef<HTMLElement | undefined>()
 
  return (
    <Container className={css.serviceOverrides} height={'100%'} background={Color.FORM_BG}>
      <ErrorsStripBinded domRef={formRefDom} />
      <Layout.Vertical
        spacing={'xlarge'}
        className={css.contentSection}
        ref={ref => {
          formRefDom.current = ref as HTMLElement
        }}
      >
        {stage?.stage?.template && (
          <TemplateBar
            templateLinkConfig={stage?.stage.template}
            onRemoveTemplate={removeTemplate}
            onOpenTemplateSelector={addOrUpdateTemplate}
            className={css.templateBar}
          />
        )}
        <Formik<TemplateStageValues>
          initialValues={formValues}
          formName="templateStageOverview"
          onSubmit={noop}
          validate={validateForm}
          validationSchema={Yup.object().shape({
            name: NameSchema({
              requiredErrorMsg: getString('pipelineSteps.build.create.stageNameRequiredError')
            }),
            identifier: IdentifierSchema()
          })}
          enableReinitialize={true}
        >
          {(formik: FormikProps<TemplateStageValues>) => {
            window.dispatchEvent(new CustomEvent('UPDATE_ERRORS_STRIP', { detail: TemplateTabs.OVERVIEW }))
            formikRef.current = formik
            return (
              <FormikForm>
                <Card className={css.sectionCard}>
                  <NameId
                    identifierProps={{
                      inputLabel: getString('stageNameLabel'),
                      isIdentifierEditable: false,
                      inputGroupProps: { disabled: isReadonly }
                    }}
                    inputGroupProps={{ placeholder: getString('common.namePlaceholder') }}
                  />
                </Card>
                <Container className={css.inputsContainer}>
                  {(templateLoading || templateInputSetLoading) && <PageSpinner />}
                  {!templateLoading && !templateInputSetLoading && (templateError || templateInputSetError) && (
                    <Container height={300}>
                      <PageError
                        message={
                          defaultTo((templateError?.data as Error)?.message, templateError?.message) ||
                          defaultTo((templateInputSetError?.data as Error)?.message, templateInputSetError?.message)
                        }
                        onClick={() => refetch()}
                      />
                    </Container>
                  )}
                  {!templateLoading &&
                    !templateInputSetLoading &&
                    !templateError &&
                    !templateInputSetError &&
                    formik.values.inputsTemplate &&
                    formik.values.allValues && (
                      <Layout.Vertical
                        margin={{ top: 'medium' }}
                        padding={{ top: 'large', bottom: 'large' }}
                        spacing={'large'}
                      >
                        <Heading level={5} color={Color.BLACK}>
                          {getString('templatesLibrary.templateInputs')}
                        </Heading>
                        <StageForm
                          key={`${formik.values.template?.templateRef}-${defaultTo(
                            formik.values.template?.versionLabel,
                            ''
                          )}`}
                          template={{ stage: formik.values.inputsTemplate }}
                          allValues={{ stage: formik.values.allValues }}
                          path={TEMPLATE_INPUT_PATH}
                          readonly={isReadonly}
                          viewType={StepViewType.InputSet}
                          hideTitle={true}
                          stageClassName={css.stageCard}
                          allowableTypes={allowableTypes}
                        />
                      </Layout.Vertical>
                    )}
                </Container>
              </FormikForm>
            )
          }}
        </Formik>
      </Layout.Vertical>
    </Container>
  )
}