All files / modules/75-cd/components/PipelineSteps/InfraProvisioning InfraProvisioningBase.tsx

56.52% Statements 52/92
25.34% Branches 37/146
44.44% Functions 8/18
56.04% Lines 51/91

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              98x 98x 98x 98x 98x 98x   98x 98x 98x 98x 98x         98x       98x 98x 98x 98x 98x   98x 98x   98x 98x   98x                               8x   8x 8x 8x 8x 8x 8x 8x 8x 8x                           8x               8x 3x 1x       8x                               8x 3x         8x                                                                                                   8x 6x     8x                 1x       1x                     6x 6x             1x               1x                             1x                                                                                                                                                                   98x  
/*
 * Copyright 2021 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, { useEffect, useRef } from 'react'
import { Spinner } from '@blueprintjs/core'
import { Field, FormikContext, FormikProps } from 'formik'
import { Container, Formik, FormikForm, FormInput } from '@wings-software/uicore'
import { cloneDeep, defaultTo, get, isEmpty, set } from 'lodash-es'
import { useParams } from 'react-router-dom'
import type { StepFormikFowardRef } from '@pipeline/components/AbstractSteps/Step'
import { usePipelineContext } from '@pipeline/components/PipelineStudio/PipelineContext/PipelineContext'
import { useStrings } from 'framework/strings'
import { DrawerTypes } from '@pipeline/components/PipelineStudio/PipelineContext/PipelineActions'
import { AdvancedPanels } from '@pipeline/components/PipelineStudio/StepCommands/StepCommandTypes'
import ExecutionGraph, {
  ExecutionGraphAddStepEvent,
  ExecutionGraphEditStepEvent,
  ExecutionGraphRefObj
} from '@pipeline/components/PipelineStudio/ExecutionGraph/ExecutionGraph'
import {
  getInitialValuesInCorrectFormat,
  getFormValuesInCorrectFormat
} from '@pipeline/components/PipelineSteps/Steps/StepsTransformValuesUtils'
import { addStepOrGroup } from '@pipeline/components/PipelineStudio/ExecutionGraph/ExecutionGraphUtil'
import { StepCategory, useGetStepsV2 } from 'services/pipeline-ng'
import { createStepNodeFromTemplate } from '@pipeline/utils/templateUtils'
import { useMutateAsGet } from '@common/hooks'
import { getStepPaletteModuleInfosFromStage } from '@pipeline/utils/stepUtils'
import type { ProjectPathProps } from '@common/interfaces/RouteInterfaces'
import { useTemplateSelector } from '@pipeline/utils/useTemplateSelector'
import useChooseProvisioner from './ChooseProvisioner'
import type { InfraProvisioningData, InfraProvisioningDataUI, InfraProvisioningProps } from './InfraProvisioning'
import { transformValuesFieldsConfig } from './InfraProvisioningFunctionConfigs'
import css from './InfraProvisioning.module.scss'
 
export const InfraProvisioningBase = (
  { initialValues, onUpdate, onChange }: InfraProvisioningProps,
  _formikRef: StepFormikFowardRef<InfraProvisioningData>
): JSX.Element => {
  const {
    stepsFactory,
    state: {
      pipelineView,
      selectionState: { selectedStageId = '' },
      templateTypes
    },
    updateStage,
    updatePipelineView,
    isReadonly,
    getStageFromPipeline,
    getStagePathFromPipeline
  } = usePipelineContext()
 
  const { getString } = useStrings()
  const { stage: selectedStage } = getStageFromPipeline(defaultTo(selectedStageId, ''))
  const stagePath = getStagePathFromPipeline(selectedStageId || '', 'pipeline.stages')
  const [allChildTypes, setAllChildTypes] = React.useState<string[]>([])
  const executionRef = React.useRef<ExecutionGraphRefObj | null>(null)
  const { getTemplate } = useTemplateSelector()
  const { accountId } = useParams<ProjectPathProps>()
  const formikRef = useRef<FormikContext<InfraProvisioningDataUI>>()
  const { showModal } = useChooseProvisioner({
    onSubmit: (data: any) => {
      onUpdate?.(data)
      //  setTypeEnabled(true)
    },
    onClose: () => {
      formikRef.current?.resetForm()
    }
  })
 
  const {
    data: stepsData,
    loading: stepsDataLoading,
    refetch: getStepTypes
  } = useMutateAsGet(useGetStepsV2, {
    queryParams: { accountId },
    body: {
      stepPalleteModuleInfos: getStepPaletteModuleInfosFromStage(selectedStage?.stage?.type, undefined, 'Provisioner')
    },
    lazy: true
  })
 
  useEffect(() => {
    if (isEmpty(allChildTypes) && initialValues.provisionerEnabled) {
      getStepTypes()
    }
  }, [initialValues.provisionerEnabled])
 
  const getStepTypesFromCategories = (stepCategories: StepCategory[]): string[] => {
    const validStepTypes: string[] = []
    stepCategories.forEach(category => {
      if (category.stepCategories?.length) {
        validStepTypes.push(...getStepTypesFromCategories(category.stepCategories))
      } else if (category.stepsData?.length) {
        category.stepsData.forEach(stepData => {
          if (stepData.type) {
            validStepTypes.push(stepData.type)
          }
        })
      }
    })
    return validStepTypes
  }
 
  React.useEffect(() => {
    Iif (stepsData?.data?.stepCategories) {
      setAllChildTypes(getStepTypesFromCategories(stepsData.data.stepCategories))
    }
  }, [stepsData?.data?.stepCategories])
 
  const addTemplate = async (event: ExecutionGraphAddStepEvent) => {
    try {
      const { template, isCopied } = await getTemplate({
        templateType: 'Step',
        allChildTypes
      })
      const newStepData = { step: createStepNodeFromTemplate(template, isCopied) }
      const { stage: pipelineStage } = cloneDeep(getStageFromPipeline(selectedStageId || ''))
      executionRef.current?.stepGroupUpdated?.(newStepData.step)
      if (pipelineStage && !get(pipelineStage?.stage, 'spec.infrastructure.infrastructureDefinition.provisioner')) {
        set(pipelineStage, 'stage.spec.infrastructure.infrastructureDefinition.provisioner', {
          steps: [],
          rollbackSteps: []
        })
      }
      const provisioner = get(pipelineStage?.stage, 'spec.infrastructure.infrastructureDefinition.provisioner')
      // set empty arrays
      if (!event.isRollback && !provisioner.steps) {
        provisioner.steps = []
      }
      if (event.isRollback && !provisioner.rollbackSteps) {
        provisioner.rollbackSteps = []
      }
 
      addStepOrGroup(event.entity, provisioner, newStepData, event.isParallel, event.isRollback)
      if (pipelineStage?.stage) {
        await updateStage(pipelineStage?.stage)
      }
      updatePipelineView({
        ...pipelineView,
        isDrawerOpened: true,
        drawerData: {
          type: DrawerTypes.ProvisionerStepConfig,
          data: {
            stepConfig: {
              node: newStepData.step,
              stepsMap: event.stepsMap,
              onUpdate: executionRef.current?.stepGroupUpdated,
              isStepGroup: false,
              addOrEdit: 'edit',
              hiddenAdvancedPanels: [AdvancedPanels.PreRequisites]
            }
          }
        }
      })
    } catch (_) {
      // Do nothing
    }
  }
 
  const isProvisionerDisabled = (provisionerSnippetLoading: boolean): boolean => {
    return isReadonly || provisionerSnippetLoading || stepsDataLoading
  }
 
  return (
    <Formik
      enableReinitialize={true}
      initialValues={getInitialValuesInCorrectFormat<InfraProvisioningData, InfraProvisioningDataUI>(
        initialValues,
        transformValuesFieldsConfig
      )}
      formName="infraProvisionerBase"
      validate={(_values: InfraProvisioningDataUI) => {
        const schemaValues = getFormValuesInCorrectFormat<InfraProvisioningDataUI, InfraProvisioningData>(
          _values,
          transformValuesFieldsConfig
        )
        onChange?.(schemaValues)
      }}
      onSubmit={(_values: InfraProvisioningDataUI) => {
        const schemaValues = getFormValuesInCorrectFormat<InfraProvisioningDataUI, InfraProvisioningData>(
          _values,
          transformValuesFieldsConfig
        )
        onUpdate?.(schemaValues)
      }}
    >
      {(formik: FormikProps<InfraProvisioningDataUI>) => {
        formikRef.current = formik
        return (
          <FormikForm className={css.provisionerForm}>
            <FormInput.CheckBox
              name={`provisionerEnabled`}
              disabled={isProvisionerDisabled(formik.values.provisionerSnippetLoading as boolean)}
              label={getString('pipelineSteps.deploy.provisioner.enableProvisionerLabel')}
              onChange={(event: React.FormEvent<HTMLInputElement>) => {
                Iif (!event.currentTarget.checked) {
                  formik.values.provisioner.stage.spec.execution = { steps: [], rollbackSteps: [] }
                  formik.setFieldValue('provisioner', formik.values.provisioner)
                  onUpdate?.({
                    provisioner: formik.values.provisioner.stage.spec.execution,
                    provisionerEnabled: event.currentTarget.checked
                  })
                } else {
                  showModal({
                    provisioner: formik.values.provisioner.stage.spec.execution,
                    provisionerEnabled: true
                  })
                }
              }}
            />
            {formik.values.provisionerSnippetLoading || stepsDataLoading ? (
              <Container>
                <Spinner />
              </Container>
            ) : formik.values.provisionerEnabled ? (
              <div className={css.graphContainer}>
                <Field name="provisioner">
                  {(_props: any) => {
                    return (
                      <ExecutionGraph
                        gridStyle={{ startX: 50, startY: 80 }}
                        rollBackPropsStyle={{ top: '10px' }}
                        rollBackBannerStyle={{ top: '10px', backgroundColor: 'rgba(0,0,0,0)' }}
                        canvasButtonsLayout={'horizontal'}
                        canvasButtonsTooltipPosition={'top'}
                        allowAddGroup={true}
                        isReadonly={isReadonly}
                        hasRollback={true}
                        hasDependencies={false}
                        stepsFactory={stepsFactory}
                        templateTypes={templateTypes}
                        stage={formik.values.provisioner as any}
                        originalStage={formik.values.originalProvisioner as any}
                        ref={executionRef}
                        updateStage={stageData => {
                          formik.setFieldValue('provisioner', stageData)
                          onUpdate?.({
                            provisioner: stageData.stage?.spec?.execution || ({} as any),
                            provisionerEnabled: formik.values.provisionerEnabled
                          })
                        }}
                        // Check and update the correct stage path here
                        pathToStage={`${stagePath}.stage.spec.execution`}
                        onAddStep={(event: ExecutionGraphAddStepEvent) => {
                          if (event.isTemplate) {
                            addTemplate(event)
                          } else {
                            updatePipelineView({
                              ...pipelineView,
                              isDrawerOpened: true,
                              drawerData: {
                                type: DrawerTypes.AddProvisionerStep,
                                data: {
                                  paletteData: {
                                    entity: event.entity,
                                    stepsMap: event.stepsMap,
                                    onUpdate: executionRef.current?.stepGroupUpdated,
                                    isRollback: event.isRollback,
                                    isParallelNodeClicked: event.isParallel,
                                    hiddenAdvancedPanels: [AdvancedPanels.PreRequisites]
                                  }
                                }
                              }
                            })
                          }
                          formik.submitForm()
                        }}
                        onEditStep={(event: ExecutionGraphEditStepEvent) => {
                          updatePipelineView({
                            ...pipelineView,
                            isDrawerOpened: true,
                            drawerData: {
                              type: DrawerTypes.ProvisionerStepConfig,
                              data: {
                                stepConfig: {
                                  node: event.node as any,
                                  stepsMap: event.stepsMap,
                                  onUpdate: executionRef.current?.stepGroupUpdated,
                                  isStepGroup: event.isStepGroup,
                                  isUnderStepGroup: event.isUnderStepGroup,
                                  addOrEdit: event.addOrEdit,
                                  hiddenAdvancedPanels: [AdvancedPanels.PreRequisites]
                                }
                              }
                            }
                          })
                        }}
                      />
                    )
                  }}
                </Field>
              </div>
            ) : null}
          </FormikForm>
        )
      }}
    </Formik>
  )
}
 
export const InfraProvisioningBaseWithRef = React.forwardRef(InfraProvisioningBase)