All files / modules/70-pipeline/components/RetryPipeline RetryPipeline.tsx

73.54% Statements 164/223
57.83% Branches 251/434
67.5% Functions 27/40
73.42% Lines 163/222

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 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824              23x 23x                           23x 23x 23x 23x 23x 23x   23x 23x 23x 23x     23x                                   23x     23x 23x 23x 23x 23x 23x 23x 23x 23x 23x   23x 23x 23x 23x 23x   23x 23x 23x   23x 23x 23x 23x   23x                                   54x 54x 54x 54x 54x     54x   54x   54x 54x 54x     54x 54x   54x 54x                         54x     54x 54x 54x 54x     54x 54x 54x 54x 54x 54x 54x 54x 54x 54x 54x 54x 54x 54x   54x 16x         54x                       54x                             54x                                                     54x                                 54x                                 54x                           54x 54x 54x                   54x                             54x   54x 8x 8x 8x       54x   8x 8x   8x 8x       54x 37x         54x 16x 8x 8x 8x       54x 8x     54x 25x     54x 16x 8x 8x                                   8x                                               8x             54x 37x   37x                                           54x                                                                                                                 54x 54x 8x       54x   2x 1x 1x   2x         54x 9x 3x   3x 4x 4x       3x 2x 2x       2x   1x   3x 3x   54x             54x     54x 54x     54x                                                     54x 53x               53x 53x 35x                                     54x   54x     54x                     8x   8x     8x 8x   7x             7x         8x   7x     7x       54x 54x                                               2x                       106x                                                                                                                                                                                                                                                                         1x 1x                                                       23x  
/*
 * 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, { FormEvent, useCallback, useEffect, useRef, useState } from 'react'
import {
  Button,
  Text,
  ButtonVariation,
  Formik,
  FormikForm,
  Heading,
  Layout,
  SelectOption,
  Checkbox,
  PageSpinner,
  VisualYamlSelectedView as SelectedView,
  VisualYamlToggle
} from '@wings-software/uicore'
import { useModalHook } from '@harness/use-modal'
import { Color } from '@harness/design-system'
import { useHistory, useParams } from 'react-router-dom'
import cx from 'classnames'
import { parse } from 'yaml'
import { isEmpty, pick } from 'lodash-es'
import type { FormikErrors } from 'formik'
import { Classes, Dialog, Tooltip } from '@blueprintjs/core'
import { useStrings } from 'framework/strings'
import { useAppStore } from 'framework/AppStore/AppStoreContext'
import { GitSyncStoreProvider } from 'framework/GitRepoStore/GitSyncStoreContext'
import type { PipelineInfoConfig } from 'services/cd-ng'
 
import {
  getInputSetForPipelinePromise,
  InputSetSummaryResponse,
  RetryGroup,
  useGetInputSetsListForPipeline,
  useGetInputsetYamlV2,
  useGetMergeInputSetFromPipelineTemplateWithListInput,
  useGetPipeline,
  useGetRetryStages,
  useRetryPipeline
} from 'services/pipeline-ng'
 
import type {
  ExecutionPathProps,
  GitQueryParams,
  PipelineType,
  RunPipelineQueryParams
} from '@common/interfaces/RouteInterfaces'
import { useExecutionContext } from '@pipeline/context/ExecutionContext'
import type { YamlBuilderHandlerBinding, YamlBuilderProps } from '@common/interfaces/YAMLBuilderProps'
 
import RbacButton from '@rbac/components/Button/Button'
import useRBACError from '@rbac/utils/useRBACError/useRBACError'
import { ResourceType } from '@rbac/interfaces/ResourceType'
import { PermissionIdentifier } from '@rbac/interfaces/PermissionIdentifier'
import { usePermission } from '@rbac/hooks/usePermission'
import { yamlStringify } from '@common/utils/YamlHelperMethods'
import { useToaster } from '@common/exports'
import routes from '@common/RouteDefinitions'
import { useQueryParams } from '@common/hooks'
import { getFeaturePropsForRunPipelineButton, mergeTemplateWithInputSetData } from '@pipeline/utils/runPipelineUtils'
import type { InputSetDTO } from '@pipeline/utils/types'
import { ErrorsStrip } from '../ErrorsStrip/ErrorsStrip'
import GitPopover from '../GitPopover/GitPopover'
import SelectStagetoRetry from './SelectStagetoRetry'
import { YamlBuilderMemo } from '../PipelineStudio/PipelineYamlView/PipelineYamlView'
import factory from '../PipelineSteps/PipelineStepFactory'
 
import { PipelineInputSetForm } from '../PipelineInputSetForm/PipelineInputSetForm'
import { StepViewType } from '../AbstractSteps/Step'
import { clearRuntimeInput, getErrorsList, validatePipeline } from '../PipelineStudio/StepUtil'
 
import SaveAsInputSet from '../RunPipelineModal/SaveAsInputSet'
import { InputSetSelector, InputSetSelectorProps } from '../InputSetSelector/InputSetSelector'
import SelectExistingInputsOrProvideNew from '../RunPipelineModal/SelectExistingOrProvide'
import { PreFlightCheckModal } from '../PreFlightCheckModal/PreFlightCheckModal'
import type { InputSetValue } from '../InputSetSelector/utils'
import css from './RetryPipeline.module.scss'
 
export interface ParallelStageOption extends SelectOption {
  isLastIndex: number
}
interface RetryPipelineProps {
  executionIdentifier: string
  pipelineIdentifier: string
  modules?: string[]
  onClose: () => void
}
 
function RetryPipeline({
  executionIdentifier: executionId,
  pipelineIdentifier: pipelineIdf,
  modules,
  onClose
}: RetryPipelineProps): React.ReactElement {
  const { isGitSyncEnabled } = useAppStore()
  const { getString } = useStrings()
  const { showSuccess, showWarning, showError } = useToaster()
  const { getRBACErrorMessage } = useRBACError()
  const history = useHistory()
 
  const { projectIdentifier, orgIdentifier, pipelineIdentifier, accountId, executionIdentifier, module } =
    useParams<PipelineType<ExecutionPathProps>>()
 
  const { pipelineExecutionDetail } = useExecutionContext()
 
  const repoIdentifier = pipelineExecutionDetail?.pipelineExecutionSummary?.gitDetails?.repoIdentifier
  const branch = pipelineExecutionDetail?.pipelineExecutionSummary?.gitDetails?.branch
  const { inputSetType, inputSetValue, inputSetLabel, inputSetRepoIdentifier, inputSetBranch } = useQueryParams<
    GitQueryParams & RunPipelineQueryParams
  >()
  const planExecutionIdentifier = executionIdentifier ?? executionId
  const pipelineId = pipelineIdf ? pipelineIdf : pipelineIdentifier
 
  const getInputSetSelected = (): InputSetValue[] => {
    Iif (inputSetType) {
      return [
        {
          type: inputSetType as InputSetSummaryResponse['inputSetType'],
          value: inputSetValue ?? '',
          label: inputSetLabel ?? '',
          gitDetails: {
            repoIdentifier: inputSetRepoIdentifier,
            branch: inputSetBranch
          }
        }
      ]
    }
    return []
  }
 
  const [selectedView, setSelectedView] = useState<SelectedView>(SelectedView.VISUAL)
  const [yamlHandler, setYamlHandler] = useState<YamlBuilderHandlerBinding | undefined>()
  const [inputSetYaml, setInputSetYaml] = useState('')
  const [currentPipeline, setCurrentPipeline] = useState<{ pipeline?: PipelineInfoConfig } | undefined>(
    inputSetYaml ? parse(inputSetYaml) : undefined
  )
  const [existingProvide, setExistingProvide] = useState('existing')
  const [formErrors, setFormErrors] = useState<FormikErrors<InputSetDTO>>({})
  const [retryClicked, setRetryClicked] = useState(false)
  const [selectedStage, setSelectedStage] = useState<ParallelStageOption | null>(null)
  const [selectedInputSets, setSelectedInputSets] = useState<InputSetSelectorProps['value']>(getInputSetSelected())
  const [isParallelStage, setIsParallelStage] = useState(false)
  const [isLastIndex, setIsLastIndex] = useState(false)
  const [isAllStage, setIsAllStage] = useState(true)
  const [inputSetTemplateYaml, setInputSetTemplateYaml] = useState('')
  const [skipPreFlightCheck, setSkipPreFlightCheck] = useState(false)
  const [notifyOnlyMe, setNotifyOnlyMe] = useState(false)
  const [triggerValidation, setTriggerValidation] = useState(false)
  const [listOfSelectedStages, setListOfSelectedStages] = useState<Array<string>>([])
  const [resolvedPipeline, setResolvedPipeline] = React.useState<PipelineInfoConfig>()
 
  const yamlTemplate = React.useMemo(() => {
    return parse(inputSetTemplateYaml || '')?.pipeline
  }, [inputSetTemplateYaml])
 
  /*------------------------------------------------API Calls------------------------------*/
 
  const { data: pipelineResponse, loading: loadingPipeline } = useGetPipeline({
    pipelineIdentifier: pipelineId,
    queryParams: {
      accountIdentifier: accountId,
      orgIdentifier,
      projectIdentifier,
      repoIdentifier,
      branch,
      getTemplatesResolvedPipeline: true
    }
  })
 
  const { data: inputSetData, loading: loadingTemplate } = useGetInputsetYamlV2({
    planExecutionId: planExecutionIdentifier,
    queryParams: {
      orgIdentifier,
      resolveExpressions: true,
      projectIdentifier,
      accountIdentifier: accountId
    },
    requestOptions: {
      headers: {
        'content-type': 'application/yaml'
      }
    }
  })
 
  const { mutate: retryPipeline, loading: loadingRetry } = useRetryPipeline({
    queryParams: {
      accountIdentifier: accountId,
      projectIdentifier,
      orgIdentifier,
      moduleType: module,
      planExecutionId: planExecutionIdentifier,
      retryStages: (!isParallelStage
        ? [selectedStage?.value]
        : (selectedStage?.value as string)?.split(' | ')) as string[],
      runAllStages: isAllStage
    },
    queryParamStringifyOptions: {
      arrayFormat: 'repeat'
    },
    identifier: pipelineId,
    requestOptions: {
      headers: {
        'content-type': 'application/yaml'
      }
    }
  })
 
  const {
    refetch: getInputSetsList,
    data: inputSetResponse,
    loading: inputSetLoading
  } = useGetInputSetsListForPipeline({
    queryParams: {
      accountIdentifier: accountId,
      orgIdentifier,
      projectIdentifier,
      pipelineIdentifier: pipelineId,
      ...(!isEmpty(repoIdentifier) && !isEmpty(branch)
        ? {
            repoIdentifier,
            branch,
            getDefaultFromOtherRepo: true
          }
        : {})
    },
    lazy: true
  })
 
  const { mutate: mergeInputSet, loading: loadingUpdate } = useGetMergeInputSetFromPipelineTemplateWithListInput({
    queryParams: {
      accountIdentifier: accountId,
      projectIdentifier,
      orgIdentifier,
      pipelineIdentifier: pipelineId,
      ...(!isEmpty(repoIdentifier) && !isEmpty(branch)
        ? {
            pipelineRepoID: repoIdentifier,
            pipelineBranch: branch,
            repoIdentifier,
            branch,
            getDefaultFromOtherRepo: true
          }
        : {})
    }
  })
  const { data: stageResponse, loading: retryStageLoading } = useGetRetryStages({
    planExecutionId: planExecutionIdentifier,
    queryParams: {
      accountIdentifier: accountId,
      orgIdentifier,
      projectIdentifier,
      pipelineIdentifier: pipelineId,
      repoIdentifier,
      branch,
      getDefaultFromOtherRepo: true
    }
  })
  /*------------------------------------------------API Calls------------------------------*/
 
  const pipeline: PipelineInfoConfig | undefined = parse(pipelineResponse?.data?.yamlPipeline || '')?.pipeline
  const valuesPipelineRef = useRef<PipelineInfoConfig>()
  const yamlBuilderReadOnlyModeProps: YamlBuilderProps = {
    fileName: `retry-pipeline.yaml`,
    entityType: 'Pipelines',
    showSnippetSection: false,
    yamlSanityConfig: {
      removeEmptyString: false,
      removeEmptyObject: false,
      removeEmptyArray: false
    }
  }
  const [canEdit] = usePermission(
    {
      resourceScope: {
        accountIdentifier: accountId,
        orgIdentifier,
        projectIdentifier
      },
      resource: {
        resourceType: ResourceType.PIPELINE,
        resourceIdentifier: pipelineId
      },
      permissions: [PermissionIdentifier.EDIT_PIPELINE]
    },
    [accountId, orgIdentifier, projectIdentifier, pipelineId]
  )
  const inputSets = inputSetResponse?.data?.content
 
  React.useEffect(() => {
    const mergedPipelineYaml = pipelineResponse?.data?.resolvedTemplatesPipelineYaml
    Eif (mergedPipelineYaml) {
      setResolvedPipeline(parse(mergedPipelineYaml)?.pipeline)
    }
  }, [pipelineResponse?.data?.resolvedTemplatesPipelineYaml])
 
  useEffect(() => {
    // Won't actually render out RunPipelineForm
    /* istanbul ignore else */ if (inputSetData?.data?.inputSetYaml) {
      setInputSetYaml(inputSetData.data?.inputSetYaml)
    }
    /* istanbul ignore else */ if (inputSetData?.data?.latestTemplateYaml) {
      setInputSetTemplateYaml(inputSetData.data.latestTemplateYaml)
    }
  }, [inputSetData])
 
  useEffect(() => {
    Iif (!inputSets?.length) {
      setExistingProvide('provide')
    }
  }, [inputSets])
 
  useEffect(() => {
    if (inputSetYaml) {
      const parsedYAML = parse(inputSetYaml)
      setExistingProvide('provide')
      setCurrentPipeline(parsedYAML)
    }
  }, [inputSetYaml])
 
  useEffect(() => {
    getInputSetsList()
  }, [])
 
  useEffect(() => {
    setTriggerValidation(true)
  }, [currentPipeline])
 
  useEffect(() => {
    if (inputSetTemplateYaml) {
      const parsedTemplate = parse(inputSetTemplateYaml) as { pipeline: PipelineInfoConfig }
      Iif ((selectedInputSets && selectedInputSets.length > 1) || selectedInputSets?.[0]?.type === 'OVERLAY_INPUT_SET') {
        const fetchData = async (): Promise<void> => {
          try {
            const data = await mergeInputSet({
              inputSetReferences: selectedInputSets.map(item => item.value as string)
            })
            if (data?.data?.pipelineYaml) {
              const inputSetPortion = parse(data.data.pipelineYaml) as {
                pipeline: PipelineInfoConfig
              }
              const toBeUpdated = mergeTemplateWithInputSetData(parsedTemplate, inputSetPortion)
              setCurrentPipeline(toBeUpdated)
            }
          } catch (e) {
            showError(getRBACErrorMessage(e), undefined, 'pipeline.feth.inputSetTemplateYaml.error')
          }
        }
        fetchData()
      } else Iif (selectedInputSets && selectedInputSets.length === 1) {
        const fetchData = async (): Promise<void> => {
          const data = await getInputSetForPipelinePromise({
            inputSetIdentifier: selectedInputSets[0].value as string,
            queryParams: {
              accountIdentifier: accountId,
              projectIdentifier,
              orgIdentifier,
              pipelineIdentifier: pipelineId,
              repoIdentifier: selectedInputSets[0]?.gitDetails?.repoIdentifier,
              branch: selectedInputSets[0]?.gitDetails?.branch
            }
          })
          if (data?.data?.inputSetYaml) {
            if (selectedInputSets[0].type === 'INPUT_SET') {
              const inputSetPortion = pick(parse(data.data.inputSetYaml)?.inputSet, 'pipeline') as {
                pipeline: PipelineInfoConfig
              }
              const toBeUpdated = mergeTemplateWithInputSetData(parsedTemplate, inputSetPortion)
              setCurrentPipeline(toBeUpdated)
            }
          }
        }
        fetchData()
      } else Iif (!selectedInputSets?.length && !inputSetYaml?.length) {
        setCurrentPipeline(parsedTemplate)
      }
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [inputSetTemplateYaml, selectedInputSets, accountId, projectIdentifier, orgIdentifier, pipelineId])
 
  useEffect(() => {
    let errors: FormikErrors<InputSetDTO> = formErrors
 
    Iif (
      triggerValidation &&
      currentPipeline?.pipeline &&
      inputSetTemplateYaml &&
      yamlTemplate &&
      pipeline &&
      retryClicked
    ) {
      errors = validatePipeline({
        pipeline: { ...clearRuntimeInput(currentPipeline.pipeline) },
        template: parse(inputSetTemplateYaml || '')?.pipeline,
        originalPipeline: currentPipeline.pipeline,
        getString,
        viewType: StepViewType.DeploymentForm
      }) as any
      setFormErrors(errors)
      // triggerValidation should be true every time 'currentPipeline' changes
      // and it needs to be set as false here so that we do not trigger it indefinitely
      setTriggerValidation(false)
    }
  }, [currentPipeline, pipeline, inputSetTemplateYaml, yamlTemplate, selectedInputSets, existingProvide])
 
  const handleRetryPipeline = useCallback(
    async (valuesPipeline?: PipelineInfoConfig, forceSkipFlightCheck = false) => {
      if (Object.keys(formErrors).length) {
        return
      }
      valuesPipelineRef.current = valuesPipeline
      if (!skipPreFlightCheck && !forceSkipFlightCheck) {
        // Not skipping pre-flight check - open the new modal
        showPreflightCheckModal()
        return
      }
 
      try {
        const response = await retryPipeline(
          !isEmpty(valuesPipelineRef.current) ? (yamlStringify({ pipeline: valuesPipelineRef.current }) as any) : ''
        )
        const retryPipelineData = response.data
        if (response.status === 'SUCCESS') {
          onClose()
          if (retryPipelineData && retryPipelineData.planExecution?.uuid) {
            showSuccess(getString('runPipelineForm.pipelineRunSuccessFully'))
            history.push(
              routes.toExecutionPipelineView({
                orgIdentifier,
                pipelineIdentifier: pipelineId,
                projectIdentifier,
                executionIdentifier: retryPipelineData?.planExecution?.uuid || '',
                accountId,
                module
              })
            )
          }
        }
      } catch (error) {
        showWarning(getRBACErrorMessage(error) || getString('runPipelineForm.runPipelineFailed'))
      }
    },
    // eslint-disable-next-line react-hooks/exhaustive-deps
    [
      retryPipeline,
      showWarning,
      showSuccess,
      pipelineId,
      history,
      orgIdentifier,
      module,
      projectIdentifier,
      onClose,
      accountId,
      skipPreFlightCheck,
      formErrors,
      isParallelStage,
      selectedStage,
      isAllStage
    ]
  )
 
  const checkIfRuntimeInputsNotPresent = (): string | undefined => {
    if (pipeline && !inputSetTemplateYaml) {
      return getString('pipeline.inputSets.noRuntimeInputsWhileExecution')
    }
  }
 
  const handleModeSwitch = useCallback(
    (view: SelectedView) => {
      if (view === SelectedView.VISUAL) {
        const presentPipeline = parse(yamlHandler?.getLatestYaml() || '') as { pipeline: PipelineInfoConfig }
        setCurrentPipeline(presentPipeline)
      }
      setSelectedView(view)
    },
    [yamlHandler?.getLatestYaml]
  )
 
  const handleStageChange = (value: ParallelStageOption): void => {
    const stagesList = stageResponse?.data?.groups?.filter((_, stageIdx) => stageIdx < value.isLastIndex)
    const listOfIds: string[] = []
 
    stagesList?.forEach(stageData => {
      stageData?.info?.forEach(stageInfo => {
        listOfIds.push(stageInfo.identifier as string)
      })
    })
 
    if (value.label.includes('|')) {
      Eif ((value as ParallelStageOption).isLastIndex === (stageResponse?.data?.groups as RetryGroup[])?.length - 1) {
        setIsLastIndex(true)
      } else {
        setIsLastIndex(false)
      }
      setIsParallelStage(true)
    } else {
      setIsParallelStage(false)
    }
    setListOfSelectedStages(listOfIds)
    setSelectedStage(value)
  }
  const handleStageType = (e: FormEvent<HTMLInputElement>): void => {
    if ((e.target as any).value === 'allparallel') {
      setIsAllStage(true)
    } else {
      setIsAllStage(false)
    }
  }
  const onExistingProvideRadioChange = (ev: FormEvent<HTMLInputElement>): void => {
    setExistingProvide((ev.target as HTMLInputElement).value)
  }
  const getRetryPipelineDisabledState = (): boolean => {
    return getErrorsList(formErrors).errorCount > 0 || !selectedStage
  }
 
  const [showPreflightCheckModal, hidePreflightCheckModal] = useModalHook(() => {
    return (
      <Dialog
        className={cx(css.preFlightCheckModal, Classes.DIALOG)}
        enforceFocus={false}
        isOpen
        onClose={hidePreflightCheckModal}
      >
        <PreFlightCheckModal
          pipeline={valuesPipelineRef.current}
          module={module}
          accountId={accountId}
          orgIdentifier={orgIdentifier}
          projectIdentifier={projectIdentifier}
          pipelineIdentifier={pipelineId}
          branch={branch}
          repoIdentifier={repoIdentifier}
          onCloseButtonClick={hidePreflightCheckModal}
          onContinuePipelineClick={() => {
            hidePreflightCheckModal()
            handleRetryPipeline(valuesPipelineRef.current, true)
          }}
        />
      </Dialog>
    )
  }, [isParallelStage, isAllStage, selectedStage])
 
  const renderPipelineInputSetForm = (): React.ReactElement | undefined => {
    Iif (loadingUpdate) {
      return (
        <PageSpinner
          className={css.inputSetsUpdatingSpinner}
          message={getString('pipeline.inputSets.applyingInputSets')}
        />
      )
    }
    const templateSource = inputSetTemplateYaml
    if (currentPipeline?.pipeline && resolvedPipeline && templateSource) {
      return (
        <>
          {existingProvide === 'existing' ? <div className={css.divider} /> : null}
          <PipelineInputSetForm
            originalPipeline={resolvedPipeline}
            template={parse(templateSource)?.pipeline}
            readonly={false}
            path=""
            viewType={StepViewType.DeploymentForm}
            isRunPipelineForm
            maybeContainerClass={existingProvide === 'provide' ? css.inputSetFormRunPipeline : ''}
            listOfSelectedStages={listOfSelectedStages}
            isRetryFormStageSelected={selectedStage !== null}
          />
        </>
      )
    }
  }
 
  const formRefDom = React.useRef<HTMLElement | undefined>()
 
  Iif (loadingPipeline || loadingTemplate || inputSetLoading || loadingRetry) {
    return <PageSpinner />
  }
  return (
    <Formik<PipelineInfoConfig>
      initialValues={
        currentPipeline?.pipeline ? clearRuntimeInput(currentPipeline.pipeline) : ({} as PipelineInfoConfig)
      }
      formName="retryPipeline"
      onSubmit={values => {
        handleRetryPipeline(values, false)
      }}
      enableReinitialize
      validate={async values => {
        let errors: FormikErrors<InputSetDTO> = formErrors
 
        setCurrentPipeline({ ...currentPipeline, pipeline: values as PipelineInfoConfig })
 
        function validateErrors(): Promise<FormikErrors<InputSetDTO>> {
          return new Promise(resolve => {
            setTimeout(() => {
              const validatedErrors =
                (validatePipeline({
                  pipeline: values as PipelineInfoConfig,
                  template: parse(inputSetTemplateYaml || '')?.pipeline,
                  originalPipeline: pipeline,
                  getString,
                  viewType: StepViewType.DeploymentForm
                }) as any) || formErrors
              resolve(validatedErrors)
            }, 300)
          })
        }
 
        errors = await validateErrors()
 
        Iif (typeof errors !== undefined && retryClicked) {
          setFormErrors(errors)
        }
        return errors
      }}
    >
      {({ submitForm, values }) => {
        const noRuntimeInputs = checkIfRuntimeInputsNotPresent()
        return (
          <Layout.Vertical>
            <>
              <div className={css.runModalHeader}>
                <Heading
                  level={2}
                  font={{ weight: 'bold' }}
                  color={Color.BLACK_100}
                  className={css.runModalHeaderTitle}
                >
                  {getString('pipeline.retryPipeline')}
                </Heading>
                {isGitSyncEnabled && (
                  <GitSyncStoreProvider>
                    <GitPopover
                      data={pipelineResponse?.data?.gitDetails ?? {}}
                      iconProps={{ margin: { left: 'small', top: 'xsmall' } }}
                    />
                  </GitSyncStoreProvider>
                )}
                <div className={css.optionBtns}>
                  <VisualYamlToggle
                    selectedView={selectedView}
                    onChange={nextMode => {
                      handleModeSwitch(nextMode)
                    }}
                    disableToggle={!inputSetTemplateYaml}
                  />
                </div>
              </div>
              <ErrorsStrip formErrors={formErrors} domRef={formRefDom} />
            </>
            {selectedView === SelectedView.VISUAL ? (
              <div
                className={css.runModalFormContent}
                ref={ref => {
                  formRefDom.current = ref as HTMLElement
                }}
              >
                <FormikForm>
                  {!retryStageLoading && stageResponse?.data && (
                    <SelectStagetoRetry
                      handleStageChange={handleStageChange}
                      selectedStage={selectedStage}
                      stageResponse={stageResponse?.data}
                      isParallelStage={isParallelStage}
                      handleStageType={handleStageType}
                      isAllStage={isAllStage}
                      isLastIndex={isLastIndex}
                    />
                  )}
                  {noRuntimeInputs ? (
                    <Layout.Horizontal padding="medium" margin="medium">
                      <Text>{noRuntimeInputs}</Text>
                    </Layout.Horizontal>
                  ) : (
                    !!inputSets?.length && (
                      <Layout.Vertical
                        className={css.pipelineHeader}
                        padding={{ top: 'xlarge', left: 'xlarge', right: 'xlarge' }}
                      >
                        <SelectExistingInputsOrProvideNew
                          existingProvide={existingProvide}
                          onExistingProvideRadioChange={onExistingProvideRadioChange}
                        />
                        {pipeline && currentPipeline && inputSetTemplateYaml && existingProvide === 'existing' && (
                          <GitSyncStoreProvider>
                            <InputSetSelector
                              pipelineIdentifier={pipelineId}
                              onChange={inputsets => {
                                setSelectedInputSets(inputsets)
                              }}
                              value={selectedInputSets}
                            />
                          </GitSyncStoreProvider>
                        )}
                      </Layout.Vertical>
                    )
                  )}
 
                  {renderPipelineInputSetForm()}
                  {existingProvide === 'existing' && selectedInputSets && selectedInputSets?.length > 0 && (
                    <div className={css.noPipelineInputSetForm} />
                  )}
                </FormikForm>
              </div>
            ) : (
              <div className={css.editor}>
                <Layout.Vertical className={css.content} padding="xlarge">
                  <YamlBuilderMemo
                    {...yamlBuilderReadOnlyModeProps}
                    existingJSON={{ pipeline: values }}
                    bind={setYamlHandler}
                    schema={{}}
                    invocationMap={factory.getInvocationMap()}
                    height="55vh"
                    width="100%"
                    showSnippetSection={false}
                    isEditModeSupported={canEdit}
                  />
                </Layout.Vertical>
              </div>
            )}
 
            <Layout.Horizontal
              margin={{ left: 'xlarge', right: 'xlarge', top: 'medium', bottom: 'medium' }}
              className={css.footerContainer}
            >
              <Checkbox
                label={getString('pre-flight-check.skipCheckBtn')}
                background={Color.GREY_100}
                color={skipPreFlightCheck ? Color.PRIMARY_8 : Color.BLACK}
                className={css.footerCheckbox}
                checked={skipPreFlightCheck}
                onChange={e => setSkipPreFlightCheck(e.currentTarget.checked)}
              />
              <Tooltip position="top" content={getString('featureNA')}>
                <Checkbox
                  background={notifyOnlyMe ? Color.PRIMARY_2 : Color.GREY_100}
                  color={notifyOnlyMe ? Color.PRIMARY_7 : Color.BLACK}
                  className={css.footerCheckbox}
                  margin={{ left: 'medium' }}
                  disabled
                  label={getString('pipeline.runPipelineForm.notifyOnlyMe')}
                  checked={notifyOnlyMe}
                  onChange={e => setNotifyOnlyMe(e.currentTarget.checked)}
                />
              </Tooltip>
            </Layout.Horizontal>
 
            <Layout.Horizontal
              padding={{ left: 'xlarge', right: 'xlarge', top: 'large', bottom: 'large' }}
              flex={{ justifyContent: 'space-between', alignItems: 'center' }}
              className={css.footer}
            >
              <Layout.Horizontal className={cx(css.actionButtons)}>
                <RbacButton
                  variation={ButtonVariation.PRIMARY}
                  intent="success"
                  type="submit"
                  text={getString('pipeline.retryPipeline')}
                  onClick={event => {
                    event.stopPropagation()
                    setRetryClicked(true)
                    if ((!selectedInputSets || selectedInputSets.length === 0) && existingProvide === 'existing') {
                      setExistingProvide('provide')
                    } else {
                      submitForm()
                    }
                  }}
                  featuresProps={getFeaturePropsForRunPipelineButton({ modules, getString })}
                  permission={{
                    resource: {
                      resourceIdentifier: pipeline?.identifier as string,
                      resourceType: ResourceType.PIPELINE
                    },
                    permission: PermissionIdentifier.EXECUTE_PIPELINE
                  }}
                  disabled={getRetryPipelineDisabledState()}
                  data-testid="retry-failed-pipeline"
                />
                <div className={css.secondaryButton}>
                  <Button
                    variation={ButtonVariation.SECONDARY}
                    id="cancel-runpipeline"
                    text={getString('cancel')}
                    margin={{ left: 'medium' }}
                    background={Color.GREY_50}
                    onClick={() => {
                      Eif (onClose) {
                        onClose()
                      }
                    }}
                  />
                </div>
              </Layout.Horizontal>
              <SaveAsInputSet
                pipeline={pipeline}
                currentPipeline={currentPipeline}
                values={values}
                template={inputSetTemplateYaml}
                canEdit={canEdit}
                accountId={accountId}
                projectIdentifier={projectIdentifier}
                orgIdentifier={orgIdentifier}
                repoIdentifier={repoIdentifier}
                branch={branch}
                isGitSyncEnabled={isGitSyncEnabled}
                setFormErrors={setFormErrors}
                refetchParentData={getInputSetsList}
              />
            </Layout.Horizontal>
          </Layout.Vertical>
        )
      }}
    </Formik>
  )
}
export default RetryPipeline