All files / modules/75-ci/components/PipelineStudio/BuildStageSetupShell BuildStageSetupShell.tsx

81.63% Statements 80/98
60.16% Branches 219/364
75% Functions 12/16
81.63% Lines 80/98

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 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426              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 19x 18x 18x 18x         18x 18x                                   18x   18x 18x   18x 3x         18x     6x 6x           6x 6x                               18x 3x 3x                       18x 3x 3x 3x 3x 3x         18x   18x 3x 3x       18x 6x 6x 6x           18x 18x 18x 18x 18x 18x     18x 18x 18x 18x   18x 18x         18x                                             1x                     1x     1x                 18x                                                                                                                                                                               1x                                             1x     1x                                           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 from 'react'
import { Expander } from '@blueprintjs/core'
import { cloneDeep, isEmpty, isEqual, set } from 'lodash-es'
import produce from 'immer'
import { Tabs, Tab, Icon, Button, Layout, ButtonVariation } from '@wings-software/uicore'
import { Color } from '@harness/design-system'
import type { HarnessIconName } from '@wings-software/uicore/dist/icons/HarnessIcons'
import { useFeatureFlag } from '@common/hooks/useFeatureFlag'
import {
  PipelineContextType,
  usePipelineContext
} from '@pipeline/components/PipelineStudio/PipelineContext/PipelineContext'
import { useStrings } from 'framework/strings'
import { DrawerTypes } from '@pipeline/components/PipelineStudio/PipelineContext/PipelineActions'
import ExecutionGraph, {
  ExecutionGraphAddStepEvent,
  ExecutionGraphEditStepEvent,
  ExecutionGraphRefObj
} from '@pipeline/components/PipelineStudio/ExecutionGraph/ExecutionGraph'
import {
  generateRandomString,
  STATIC_SERVICE_GROUP_NAME,
  StepType
} from '@pipeline/components/PipelineStudio/ExecutionGraph/ExecutionGraphUtil'
import { StepType as StepsStepType } from '@pipeline/components/PipelineSteps/PipelineStepInterface'
import { AdvancedPanels } from '@pipeline/components/PipelineStudio/StepCommands/StepCommandTypes'
import { StageErrorContext } from '@pipeline/context/StageErrorContext'
import type { BuildStageElementConfig } from '@pipeline/utils/pipelineTypes'
import type { K8sDirectInfraYaml, UseFromStageInfraYaml, VmInfraYaml, VmPoolYaml } from 'services/ci'
import { FeatureFlag } from '@common/featureFlags'
import { SaveTemplateButton } from '@pipeline/components/PipelineStudio/SaveTemplateButton/SaveTemplateButton'
import { useAddStepTemplate } from '@pipeline/hooks/useAddStepTemplate'
import { isContextTypeNotStageTemplate } from '@pipeline/components/PipelineStudio/PipelineUtils'
import BuildInfraSpecifications from '../BuildInfraSpecifications/BuildInfraSpecifications'
import BuildStageSpecifications from '../BuildStageSpecifications/BuildStageSpecifications'
import BuildAdvancedSpecifications from '../BuildAdvancedSpecifications/BuildAdvancedSpecifications'
import { BuildTabs } from '../CIPipelineStagesUtils'
import css from './BuildStageSetupShell.module.scss'
 
export const MapStepTypeToIcon: { [key: string]: HarnessIconName } = {
  Deployment: 'pipeline-deploy',
  CI: 'pipeline-build-select',
  Approval: 'approval-stage-icon',
  Pipeline: 'pipeline',
  Custom: 'pipeline-custom'
}
 
interface StagesFilledStateFlags {
  specifications: boolean
  infra: boolean
  execution: boolean
}
 
export default function BuildStageSetupShell(): JSX.Element {
  const { getString } = useStrings()
  const isTemplatesEnabled = useFeatureFlag(FeatureFlag.NG_TEMPLATES)
  const [selectedTabId, setSelectedTabId] = React.useState<BuildTabs>(BuildTabs.OVERVIEW)
  const [filledUpStages, setFilledUpStages] = React.useState<StagesFilledStateFlags>({
    specifications: false,
    infra: false,
    execution: false
  })
  const layoutRef = React.useRef<HTMLDivElement>(null)
  const pipelineContext = usePipelineContext()
  const {
    state: {
      pipeline,
      originalPipeline,
      pipelineView: { isSplitViewOpen },
      pipelineView,
      selectionState: { selectedStageId = '', selectedStepId },
      templateTypes
    },
    contextType,
    stepsFactory,
    getStageFromPipeline,
    updatePipelineView,
    isReadonly,
    updateStage,
    setSelectedStepId,
    getStagePathFromPipeline
  } = pipelineContext
 
  const stagePath = getStagePathFromPipeline(selectedStageId || '', 'pipeline.stages')
  const [stageData, setStageData] = React.useState<BuildStageElementConfig | undefined>()
 
  React.useEffect(() => {
    Iif (selectedStepId) {
      setSelectedTabId(BuildTabs.EXECUTION)
    }
  }, [selectedStepId])
 
  React.useEffect(() => {
    // @TODO: add CI Codebase field check if Clone Codebase is checked
    // once it is added to BuildStageSpecifications (CI-757)
    const specifications = !!(stageData?.name && stageData?.identifier)
    const infra = !!(
      ((stageData?.spec?.infrastructure as K8sDirectInfraYaml)?.spec?.connectorRef &&
        (stageData?.spec?.infrastructure as K8sDirectInfraYaml)?.spec?.namespace) ||
      (stageData?.spec?.infrastructure as UseFromStageInfraYaml)?.useFromStage ||
      ((stageData?.spec?.infrastructure as VmInfraYaml)?.spec as VmPoolYaml)?.spec?.identifier
    )
    const execution = !!stageData?.spec?.execution?.steps?.length
    setFilledUpStages({ specifications, infra, execution })
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [
    stageData?.name,
    stageData?.identifier,
    // eslint-disable-next-line react-hooks/exhaustive-deps
    (stageData?.spec?.infrastructure as K8sDirectInfraYaml)?.spec?.connectorRef,
    // eslint-disable-next-line react-hooks/exhaustive-deps
    (stageData?.spec?.infrastructure as K8sDirectInfraYaml)?.spec?.namespace,
    // eslint-disable-next-line react-hooks/exhaustive-deps
    (stageData?.spec?.infrastructure as UseFromStageInfraYaml)?.useFromStage,
    ((stageData?.spec?.infrastructure as VmInfraYaml)?.spec as VmPoolYaml)?.spec?.identifier,
    stageData?.spec?.execution?.steps?.length
  ])
 
  /* If a stage A propagates it's infra from another stage B and number of stages in a pipeline change due to deletion of propagated stage B, then infra for stage A needs to be reset */
  React.useEffect(() => {
    const propagatedStageId = (stageData?.spec?.infrastructure as UseFromStageInfraYaml)?.useFromStage
    Iif (stageData && propagatedStageId) {
      const { stage: propagatedStage } = getStageFromPipeline<BuildStageElementConfig>(propagatedStageId)
      if (!propagatedStage) {
        // indicates propagated stage doesn't exist
        const stageWithoutInfra = set(stageData, 'spec.infrastructure', {
          useFromStage: {}
        })
        updateStage(stageWithoutInfra)
      }
    }
  }, [pipeline?.stages?.length])
 
  React.useEffect(() => {
    Eif (selectedStageId && isSplitViewOpen) {
      const { stage } = cloneDeep(getStageFromPipeline<BuildStageElementConfig>(selectedStageId))
      const key = Object.keys(stage || {})[0]
      Eif (key && stage && !isEqual(stage[key as 'stage'], stageData)) {
        setStageData(stage[key as 'stage'])
      }
    }
  }, [selectedStageId, pipeline, isSplitViewOpen])
 
  const { checkErrorsForTab } = React.useContext(StageErrorContext)
 
  const handleTabChange = (data: BuildTabs) => {
    checkErrorsForTab(selectedTabId).then(_ => {
      setSelectedTabId(data)
    })
  }
 
  React.useEffect(() => {
    Eif (layoutRef.current) {
      const parent = layoutRef.current.parentElement
      Iif (parent && parent.scrollTo) {
        parent.scrollTo(0, 0)
      }
    }
  }, [selectedTabId])
 
  const executionRef = React.useRef<ExecutionGraphRefObj | null>(null)
  const { addTemplate } = useAddStepTemplate({ executionRef: executionRef.current })
  const selectedStage = getStageFromPipeline<BuildStageElementConfig>(selectedStageId).stage
  const originalStage = getStageFromPipeline<BuildStageElementConfig>(selectedStageId, originalPipeline).stage
  const infraHasWarning = !filledUpStages.infra
  const executionHasWarning = !filledUpStages.execution
 
  // NOTE: set empty arrays, required by ExecutionGraph
  const selectedStageClone = cloneDeep(selectedStage)
  Eif (selectedStageClone) {
    Eif (!selectedStageClone.stage?.spec?.serviceDependencies) {
      set(selectedStageClone, 'stage.spec.serviceDependencies', [])
    }
    Eif (!selectedStageClone.stage?.spec?.execution?.steps) {
      set(selectedStageClone, 'stage.spec.execution.steps', [])
    }
  }
 
  const navBtns = (
    <Layout.Horizontal spacing="medium" className={css.footer}>
      {selectedTabId !== BuildTabs.OVERVIEW ? (
        <Button
          text={getString('ci.previous')}
          icon="chevron-left"
          onClick={() =>
            handleTabChange(
              selectedTabId === BuildTabs.ADVANCED
                ? BuildTabs.EXECUTION
                : selectedTabId === BuildTabs.EXECUTION
                ? BuildTabs.INFRASTRUCTURE
                : BuildTabs.OVERVIEW
            )
          }
          variation={ButtonVariation.SECONDARY}
        />
      ) : null}
      {selectedTabId === BuildTabs.ADVANCED ? (
        contextType === PipelineContextType.Pipeline ? (
          <Button
            text="Done"
            intent="primary"
            onClick={() => {
              updatePipelineView({ ...pipelineView, isSplitViewOpen: false })
            }}
            variation={ButtonVariation.PRIMARY}
          />
        ) : null
      ) : (
        <Button
          text={selectedTabId === BuildTabs.EXECUTION ? getString('ci.save') : getString('ci.next')}
          intent="primary"
          rightIcon="chevron-right"
          onClick={() => {
            Iif (selectedTabId === BuildTabs.EXECUTION) {
              updatePipelineView({ ...pipelineView, isSplitViewOpen: false, splitViewData: {} })
            } else {
              handleTabChange(selectedTabId === BuildTabs.OVERVIEW ? BuildTabs.INFRASTRUCTURE : BuildTabs.EXECUTION)
            }
          }}
          variation={ButtonVariation.PRIMARY}
        />
      )}
    </Layout.Horizontal>
  )
 
  return (
    <section className={css.setupShell} ref={layoutRef} key={selectedStageId}>
      <Tabs id="stageSetupShell" onChange={handleTabChange} selectedTabId={selectedTabId}>
        <Tab
          id={BuildTabs.OVERVIEW}
          panel={<BuildStageSpecifications>{navBtns}</BuildStageSpecifications>}
          title={
            <span className={css.tab}>
              <Icon name="ci-main" height={14} size={14} />
              Overview
            </span>
          }
          data-testid={getString('overview')}
        />
        <Icon
          name="chevron-right"
          height={20}
          size={20}
          margin={{ right: 'small', left: 'small' }}
          color={'grey400'}
          style={{ alignSelf: 'center' }}
        />
        <Tab
          id={BuildTabs.INFRASTRUCTURE}
          title={
            <span className={css.tab}>
              <Icon
                name={infraHasWarning ? 'warning-sign' : 'infrastructure'}
                size={infraHasWarning ? 16 : 20}
                color={infraHasWarning ? Color.ORANGE_500 : undefined}
              />
              {getString('ci.infraLabel')}
            </span>
          }
          panel={<BuildInfraSpecifications>{navBtns}</BuildInfraSpecifications>}
          data-testid={getString('ci.infraLabel')}
        />
        <Icon
          name="chevron-right"
          height={20}
          size={20}
          margin={{ right: 'small', left: 'small' }}
          color={'grey400'}
          style={{ alignSelf: 'center' }}
        />
        <Tab
          id={BuildTabs.EXECUTION}
          title={
            <span className={css.tab}>
              <Icon
                name={executionHasWarning ? 'warning-sign' : 'execution'}
                size={executionHasWarning ? 16 : 20}
                color={executionHasWarning ? Color.ORANGE_500 : undefined}
              />
              {getString('ci.executionLabel')}
            </span>
          }
          panel={
            selectedStageClone ? (
              <ExecutionGraph
                allowAddGroup={false}
                hasRollback={false}
                isReadonly={isReadonly}
                hasDependencies={true}
                stepsFactory={stepsFactory}
                stage={selectedStageClone}
                originalStage={originalStage}
                ref={executionRef}
                templateTypes={templateTypes}
                updateStage={newStageData => {
                  const newData = produce(newStageData, draft => {
                    // cleanup rollbackSteps (note: rollbackSteps does not exist on CI stage at all)
                    if (draft?.stage?.spec?.execution?.rollbackSteps) {
                      delete draft.stage.spec.execution.rollbackSteps
                    }
                    // delete serviceDependencies if its empty array (as serviceDependencies is optional)
                    if (draft?.stage?.spec?.serviceDependencies && isEmpty(draft?.stage?.spec?.serviceDependencies)) {
                      delete draft.stage.spec.serviceDependencies
                    }
                  })
 
                  if (newData.stage) {
                    updateStage(newData.stage)
                  }
                }}
                // Check and update the correct stage path here
                pathToStage={`${stagePath}.stage.spec.execution`}
                onAddStep={(event: ExecutionGraphAddStepEvent) => {
                  Iif (event.parentIdentifier === STATIC_SERVICE_GROUP_NAME) {
                    updatePipelineView({
                      ...pipelineView,
                      isDrawerOpened: true,
                      drawerData: {
                        type: DrawerTypes.ConfigureService,
                        data: {
                          stepConfig: {
                            node: {
                              type: StepsStepType.Dependency,
                              name: '',
                              identifier: generateRandomString(StepsStepType.Dependency)
                            },
                            stepsMap: event.stepsMap,
                            onUpdate: executionRef.current?.stepGroupUpdated,
                            addOrEdit: 'add',
                            isStepGroup: false,
                            hiddenAdvancedPanels: [AdvancedPanels.PreRequisites, AdvancedPanels.DelegateSelectors]
                          }
                        }
                      }
                    })
                  } else {
                    Iif (event.isTemplate) {
                      addTemplate(event)
                    } else {
                      updatePipelineView({
                        ...pipelineView,
                        isDrawerOpened: true,
                        drawerData: {
                          type: DrawerTypes.AddStep,
                          data: {
                            paletteData: {
                              entity: event.entity,
                              stepsMap: event.stepsMap,
                              onUpdate: executionRef.current?.stepGroupUpdated,
                              // isAddStepOverride: true,
                              isRollback: event.isRollback,
                              isParallelNodeClicked: event.isParallel,
                              hiddenAdvancedPanels: [AdvancedPanels.PreRequisites, AdvancedPanels.DelegateSelectors]
                            }
                          }
                        }
                      })
                    }
                  }
                }}
                onEditStep={(event: ExecutionGraphEditStepEvent) => {
                  updatePipelineView({
                    ...pipelineView,
                    isDrawerOpened: true,
                    drawerData: {
                      type: event.stepType === StepType.STEP ? DrawerTypes.StepConfig : DrawerTypes.ConfigureService,
                      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, AdvancedPanels.DelegateSelectors]
                        }
                      }
                    }
                  })
                }}
                onSelectStep={(stepId: string) => {
                  setSelectedStepId(stepId)
                }}
                selectedStepId={selectedStepId}
              />
            ) : undefined
          }
          data-testid={getString('ci.executionLabel')}
        />
        <Icon
          name="chevron-right"
          height={20}
          size={20}
          margin={{ right: 'small', left: 'small' }}
          color={'grey400'}
          style={{ alignSelf: 'center' }}
        />
        <Tab
          id={BuildTabs.ADVANCED}
          title={
            <span className={css.tab}>
              <Icon name="advanced" height={20} size={20} />
              {getString('ci.advancedLabel')}
            </span>
          }
          panel={<BuildAdvancedSpecifications>{navBtns}</BuildAdvancedSpecifications>}
          data-testid={getString('ci.advancedLabel')}
        />
        {isTemplatesEnabled && isContextTypeNotStageTemplate(contextType) && selectedStage?.stage && (
          <>
            <Expander />
            <SaveTemplateButton data={selectedStage?.stage} type={'Stage'} />
          </>
        )}
      </Tabs>
    </section>
  )
}