All files / modules/75-cd/components/PipelineSteps/DeployEnvStep DeployEnvStep.tsx

81.68% Statements 223/273
58.95% Branches 293/497
75.47% Functions 40/53
81.51% Lines 216/265

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 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962              99x 99x                                       99x 99x 99x 99x 99x 99x 99x 99x 99x 99x                       99x 99x 99x 99x 99x 99x   99x 99x   99x             99x 99x 99x 99x 99x 99x 99x 99x 99x 99x 99x 99x 99x   99x                           99x                         99x   99x 5x 4x 4x 4x 4x                     99x             20x 20x 20x         20x 20x 20x         20x         20x 20x   20x 7x             20x   5x 5x 4x   4x   4x   4x   4x 2x         2x 2x 2x 2x     2x 2x 2x 2x 2x       1x           20x 7x   20x                   20x 20x 20x                 20x   1x                 1x       20x     20x             1x                   4x 4x                       39x 39x                   70x                                                                                                         1x 1x 1x     1x                                                                                               162x 124x 38x     38x     99x           47x 47x                 47x 47x         47x       47x 47x   47x           47x 3x 3x 3x             3x 16x 3x 2x   1x   3x       47x 6x                                   3x 3x                 47x 3x 3x     47x 20x 8x 58x 7x                               47x 20x 13x   92x           47x 9x 9x 9x 7x 58x                 9x 4x 17x 4x 1x                 9x       47x       47x   47x                     47x             47x   47x   47x 7x 7x     47x   47x   47x           10x     10x                       52x 52x 52x 52x                                       3x       10x 1x                                   3x 3x 2x 1x             1x       1x       1x           3x                                     99x           6x 6x                 6x 6x 6x         6x         6x       6x   6x 1x       6x                                                                       6x         6x 1x 1x 7x             6x                     6x           6x     6x                                                                                                         99x 99x 99x   97x         97x 97x 97x                                                                                         20x 20x 5x                     15x                               4x 4x 4x             4x   97x 97x 97x 97x   97x    
/*
 * 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 from 'react'
import {
  Button,
  ButtonSize,
  ButtonVariation,
  Formik,
  FormikForm,
  FormInput,
  getMultiTypeFromValue,
  IconName,
  Label,
  Dialog,
  Layout,
  MultiTypeInputType,
  SelectOption,
  ThumbnailSelect,
  VisualYamlSelectedView as SelectedView,
  VisualYamlToggle,
  getErrorInfoFromErrorObject,
  Container
} from '@wings-software/uicore'
import { useModalHook } from '@harness/use-modal'
import * as Yup from 'yup'
import { defaultTo, get, isEmpty, isNil, noop, omit, isEqual } from 'lodash-es'
import { useParams } from 'react-router-dom'
import { Classes } from '@blueprintjs/core'
import { parse } from 'yaml'
import { CompletionItemKind } from 'vscode-languageserver-types'
import { connect, FormikErrors, FormikProps } from 'formik'
import cx from 'classnames'
import {
  EnvironmentRequestDTO,
  EnvironmentResponseDTO,
  EnvironmentYaml,
  getEnvironmentListPromise,
  PipelineInfrastructure,
  useGetEnvironmentAccessList,
  useGetEnvironmentList,
  useUpsertEnvironmentV2,
  useCreateEnvironmentV2,
  useGetYamlSchema
} from 'services/cd-ng'
import { IdentifierSchema, NameSchema } from '@common/utils/Validation'
import { NameIdDescriptionTags, PageSpinner } from '@common/components'
import { useStrings } from 'framework/strings'
import { loggerFor } from 'framework/logging/logging'
import { ModuleName } from 'framework/types/ModuleName'
import { Step, StepProps, StepViewType, ValidateInputSetProps } from '@pipeline/components/AbstractSteps/Step'
import type { PipelineType } from '@common/interfaces/RouteInterfaces'
import { useToaster } from '@common/exports'
import { useVariablesExpression } from '@pipeline/components/PipelineStudio/PiplineHooks/useVariablesExpression'
 
import { StepType } from '@pipeline/components/PipelineSteps/PipelineStepInterface'
import type {
  YamlBuilderHandlerBinding,
  YamlBuilderProps,
  CompletionItemInterface
} from '@common/interfaces/YAMLBuilderProps'
 
import YAMLBuilder from '@common/components/YAMLBuilder/YamlBuilder'
import { usePermission } from '@rbac/hooks/usePermission'
import { getScopeFromDTO } from '@common/components/EntityReference/EntityReference'
import { ResourceType } from '@rbac/interfaces/ResourceType'
import { PermissionIdentifier } from '@rbac/interfaces/PermissionIdentifier'
import useRBACError from '@rbac/utils/useRBACError/useRBACError'
import { StageErrorContext } from '@pipeline/context/StageErrorContext'
import { DeployTabs } from '@cd/components/PipelineStudio/DeployStageSetupShell/DeployStageSetupShellUtils'
import { getEnvironmentRefSchema } from '@cd/components/PipelineSteps/PipelineStepsUtil'
import { useTelemetry } from '@common/hooks/useTelemetry'
import { Category, EnvironmentActions, ExitModalActions } from '@common/constants/TrackingConstants'
import ExperimentalInput from '../K8sServiceSpec/K8sServiceSpecForms/ExperimentalInput'
import css from './DeployEnvStep.module.scss'
 
const logger = loggerFor(ModuleName.CD)
export interface DeployEnvData extends Omit<PipelineInfrastructure, 'environmentRef'> {
  environmentRef?: string
}
 
export interface NewEditEnvironmentModalProps {
  isEdit: boolean
  isEnvironment: boolean
  data: EnvironmentResponseDTO
  envIdentifier?: string
  onCreateOrUpdate(data: EnvironmentRequestDTO): void
  closeModal?: () => void
}
 
const yamlBuilderReadOnlyModeProps: YamlBuilderProps = {
  fileName: `environment.yaml`,
  entityType: 'Environment',
  width: '100%',
  height: 220,
  showSnippetSection: false,
  yamlSanityConfig: {
    removeEmptyString: false,
    removeEmptyObject: false,
    removeEmptyArray: false
  }
}
// SONAR recommendation
const flexStart = 'flex-start'
 
const cleanData = (values: EnvironmentResponseDTO): EnvironmentRequestDTO => {
  const newDescription = values.description?.toString().trim()
  const newId = values.identifier?.toString().trim()
  const newName = values.name?.toString().trim()
  const newType = values.type?.toString().trim()
  return {
    name: newName,
    identifier: newId,
    orgIdentifier: values.orgIdentifier,
    projectIdentifier: values.projectIdentifier,
    description: newDescription,
    tags: values.tags,
    type: newType as 'PreProduction' | 'Production'
  }
}
 
export const NewEditEnvironmentModal: React.FC<NewEditEnvironmentModalProps> = ({
  isEdit,
  data,
  isEnvironment,
  onCreateOrUpdate,
  closeModal
}): JSX.Element => {
  const { getString } = useStrings()
  const inputRef = React.useRef<HTMLInputElement | null>(null)
  const { accountId, projectIdentifier, orgIdentifier } = useParams<{
    orgIdentifier: string
    projectIdentifier: string
    accountId: string
  }>()
  const [yamlHandler, setYamlHandler] = React.useState<YamlBuilderHandlerBinding | undefined>()
  const [selectedView, setSelectedView] = React.useState<SelectedView>(SelectedView.VISUAL)
  const { loading: createLoading, mutate: createEnvironment } = useCreateEnvironmentV2({
    queryParams: {
      accountIdentifier: accountId
    }
  })
  const { loading: updateLoading, mutate: updateEnvironment } = useUpsertEnvironmentV2({
    queryParams: {
      accountIdentifier: accountId
    }
  })
  const { showSuccess, showError, clear } = useToaster()
  const { trackEvent } = useTelemetry()
 
  React.useEffect(() => {
    !isEdit &&
      trackEvent(EnvironmentActions.StartCreateEnvironment, {
        category: Category.ENVIRONMENT
      })
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [])
 
  const onSubmit = React.useCallback(
    async (value: Required<EnvironmentRequestDTO>) => {
      try {
        const values = cleanData(value)
        Iif (!values.name) {
          showError(getString('fieldRequired', { field: 'Environment' }))
        } else Iif (!values.identifier) {
          showError(getString('common.validation.fieldIsRequired', { name: 'Identifier' }))
        } else Iif (!(isEqual(values.type, 'PreProduction') || isEqual(values.type, 'Production'))) {
          showError(getString('cd.typeError'))
        } else Iif (isEdit && id !== values.identifier) {
          showError(getString('cd.editIdError', { id: id }))
        } else if (isEdit && !isEnvironment) {
          const response = await updateEnvironment({
            ...omit(values, 'accountId', 'deleted'),
            orgIdentifier,
            projectIdentifier
          })
          Eif (response.status === 'SUCCESS') {
            clear()
            showSuccess(getString('cd.environmentUpdated'))
            onCreateOrUpdate(values)
          }
        } else {
          const response = await createEnvironment({ ...values, orgIdentifier, projectIdentifier })
          Eif (response.status === 'SUCCESS') {
            clear()
            showSuccess(getString('cd.environmentCreated'))
            onCreateOrUpdate(values)
          }
        }
      } catch (e) {
        showError(getErrorInfoFromErrorObject(e, true))
      }
    },
    // eslint-disable-next-line react-hooks/exhaustive-deps
    [onCreateOrUpdate, orgIdentifier, projectIdentifier, isEdit, isEnvironment]
  )
  React.useEffect(() => {
    inputRef.current?.focus()
  }, [])
  const typeList: { label: string; value: string }[] = [
    {
      label: getString('production'),
      value: 'Production'
    },
    {
      label: getString('cd.preProduction'),
      value: 'PreProduction'
    }
  ]
  const formikRef = React.useRef<FormikProps<EnvironmentResponseDTO>>()
  const id = data.identifier
  const { data: environmentSchema } = useGetYamlSchema({
    queryParams: {
      entityType: 'Environment',
      projectIdentifier,
      orgIdentifier,
      accountIdentifier: accountId,
      scope: getScopeFromDTO({ accountIdentifier: accountId, orgIdentifier, projectIdentifier })
    }
  })
  const handleModeSwitch = React.useCallback(
    (view: SelectedView) => {
      Iif (view === SelectedView.VISUAL) {
        const yaml = defaultTo(yamlHandler?.getLatestYaml(), '')
        const envSetYamlVisual = parse(yaml).environment as EnvironmentResponseDTO
        if (envSetYamlVisual) {
          formikRef.current?.setValues({
            ...omit(cleanData(envSetYamlVisual) as EnvironmentResponseDTO)
          })
        }
      }
      setSelectedView(view)
    },
    [yamlHandler?.getLatestYaml, data]
  )
  Iif (createLoading || updateLoading) {
    return <PageSpinner />
  }
  return (
    <>
      <Container className={css.yamlToggleEnv}>
        <Layout.Horizontal flex={{ justifyContent: flexStart }} padding={{ top: 'small' }}>
          <VisualYamlToggle
            selectedView={selectedView}
            onChange={nextMode => {
              handleModeSwitch(nextMode)
            }}
          />
        </Layout.Horizontal>
      </Container>
      <Layout.Vertical>
        <Formik<Required<EnvironmentResponseDTO>>
          initialValues={data as Required<EnvironmentResponseDTO>}
          formName="deployEnv"
          onSubmit={values => {
            onSubmit(values)
            !isEdit &&
              trackEvent(EnvironmentActions.SaveCreateEnvironment, {
                category: Category.ENVIRONMENT
              })
          }}
          validationSchema={Yup.object().shape({
            name: NameSchema({ requiredErrorMsg: getString?.('fieldRequired', { field: 'Environment' }) }),
            type: Yup.string().required(getString?.('fieldRequired', { field: 'Type' })),
            identifier: IdentifierSchema()
          })}
        >
          {formikProps => {
            formikRef.current = formikProps
            return (
              <>
                {selectedView === SelectedView.VISUAL ? (
                  <FormikForm>
                    <NameIdDescriptionTags
                      formikProps={formikProps}
                      identifierProps={{
                        inputLabel: getString('name'),
                        inputGroupProps: {
                          inputGroup: {
                            inputRef: ref => (inputRef.current = ref)
                          }
                        },
                        isIdentifierEditable: !isEdit
                      }}
                    />
                    <Layout.Vertical spacing={'small'} style={{ marginBottom: 'var(--spacing-medium)' }}>
                      <Label className={cx(Classes.LABEL, css.label)}>{getString('envType')}</Label>
                      <ThumbnailSelect className={css.thumbnailSelect} name={'type'} items={typeList} />
                    </Layout.Vertical>
                    <Layout.Horizontal spacing="small" padding={{ top: 'xlarge' }}>
                      <Button
                        variation={ButtonVariation.PRIMARY}
                        type={'submit'}
                        text={getString('save')}
                        data-id="environment-save"
                      />
                      <Button
                        variation={ButtonVariation.TERTIARY}
                        text={getString('cancel')}
                        onClick={() => {
                          !isEdit &&
                            trackEvent(ExitModalActions.ExitByCancel, {
                              category: Category.ENVIRONMENT
                            })
                          closeModal?.()
                        }}
                      />
                    </Layout.Horizontal>
                  </FormikForm>
                ) : (
                  <Container>
                    <YAMLBuilder
                      {...yamlBuilderReadOnlyModeProps}
                      existingJSON={{
                        environment: {
                          ...omit(formikProps?.values),
                          description: defaultTo(formikProps.values.description, ''),
                          tags: defaultTo(formikProps.values.tags, {}),
                          type: defaultTo(formikProps.values.type, '')
                        }
                      }}
                      schema={environmentSchema?.data}
                      bind={setYamlHandler}
                      showSnippetSection={false}
                    />
 
                    <Layout.Horizontal spacing="small" padding={{ top: 'large' }}>
                      <Button
                        variation={ButtonVariation.PRIMARY}
                        type="submit"
                        text={getString('save')}
                        onClick={() => {
                          const latestYaml = defaultTo(yamlHandler?.getLatestYaml(), '')
                          const errorMsg = yamlHandler?.getYAMLValidationErrorMap()
                          Iif (errorMsg?.size) {
                            showError(errorMsg.entries().next().value[1])
                          } else {
                            onSubmit(parse(latestYaml)?.environment)
                          }
                        }}
                      />
                      <Button
                        variation={ButtonVariation.TERTIARY}
                        onClick={() => {
                          !isEdit &&
                            trackEvent(ExitModalActions.ExitByCancel, {
                              category: Category.ENVIRONMENT
                            })
                          closeModal?.()
                        }}
                        text={getString('cancel')}
                      />
                    </Layout.Horizontal>
                  </Container>
                )}
              </>
            )
          }}
        </Formik>
      </Layout.Vertical>
    </>
  )
}
 
export interface DeployEnvironmentProps {
  initialValues: DeployEnvData
  onUpdate?: (data: DeployEnvData) => void
  stepViewType?: StepViewType
  readonly: boolean
  inputSetData?: {
    template?: DeployEnvData
    path?: string
    readonly?: boolean
  }
  allowableTypes: MultiTypeInputType[]
}
 
interface DeployEnvironmentState {
  isEdit: boolean
  isEnvironment: boolean
  formik?: FormikProps<DeployEnvData>
  data?: EnvironmentResponseDTO
}
 
function isEditEnvironment(data: DeployEnvData): boolean {
  if (getMultiTypeFromValue(data.environmentRef) !== MultiTypeInputType.RUNTIME && !isEmpty(data.environmentRef)) {
    return true
  } else Iif (data.environment && !isEmpty(data.environment.identifier)) {
    return true
  }
  return false
}
 
export const DeployEnvironmentWidget: React.FC<DeployEnvironmentProps> = ({
  initialValues,
  onUpdate,
  readonly,
  allowableTypes
}): JSX.Element => {
  const { getString } = useStrings()
  const { accountId, projectIdentifier, orgIdentifier } = useParams<
    PipelineType<{
      orgIdentifier: string
      projectIdentifier: string
      pipelineIdentifier: string
      accountId: string
    }>
  >()
 
  const { showError } = useToaster()
  const { getRBACErrorMessage } = useRBACError()
  const {
    data: environmentsResponse,
    loading,
    error
  } = useGetEnvironmentList({
    queryParams: { accountIdentifier: accountId, orgIdentifier, projectIdentifier }
  })
 
  const [environments, setEnvironments] = React.useState<EnvironmentYaml[]>()
  const [selectOptions, setSelectOptions] = React.useState<SelectOption[]>()
 
  const [state, setState] = React.useState<DeployEnvironmentState>({
    isEdit: false,
    isEnvironment: false,
    data: { name: '', identifier: '' }
  })
 
  const updateEnvironmentsList = (value: EnvironmentRequestDTO) => {
    formikRef.current?.setValues({ environmentRef: value.identifier, ...(state.isEnvironment && { environment: {} }) })
    Eif (!isNil(environments)) {
      const newEnvironment = {
        description: value.description,
        identifier: defaultTo(value.identifier, ''),
        name: value.name || '',
        tags: value.tags,
        type: value.type
      }
      const newEnvironmentsList = [...environments]
      const existingIndex = newEnvironmentsList.findIndex(item => item.identifier === value.identifier)
      if (existingIndex >= 0) {
        newEnvironmentsList.splice(existingIndex, 1, newEnvironment)
      } else {
        newEnvironmentsList.unshift(newEnvironment)
      }
      setEnvironments(newEnvironmentsList)
    }
  }
 
  const [showModal, hideModal] = useModalHook(
    () => (
      <Dialog
        isOpen={true}
        enforceFocus={false}
        onClose={onClose}
        title={state.isEdit ? getString('editEnvironment') : getString('newEnvironment')}
      >
        <NewEditEnvironmentModal
          data={{
            name: defaultTo(state.data?.name, ''),
            identifier: defaultTo(state.data?.identifier, ''),
            orgIdentifier,
            projectIdentifier,
            ...state.data
          }}
          isEnvironment={state.isEnvironment}
          isEdit={state.isEdit}
          onCreateOrUpdate={value => {
            updateEnvironmentsList(value)
            onClose.call(null)
          }}
          closeModal={onClose}
        />
      </Dialog>
    ),
    [state]
  )
 
  const onClose = React.useCallback(() => {
    setState({ isEdit: false, isEnvironment: false })
    hideModal()
  }, [hideModal])
 
  React.useEffect(() => {
    if (!isNil(selectOptions) && initialValues.environmentRef) {
      if (getMultiTypeFromValue(initialValues.environmentRef) === MultiTypeInputType.FIXED) {
        const doesExist = selectOptions.filter(env => env.value === initialValues.environmentRef).length > 0
        Iif (!doesExist) {
          if (!readonly) {
            formikRef.current?.setFieldValue('environmentRef', '')
          } else {
            const options = [...selectOptions]
            options.push({
              label: initialValues.environmentRef,
              value: initialValues.environmentRef
            })
            setSelectOptions(options)
          }
        }
      }
    }
  }, [selectOptions])
 
  React.useEffect(() => {
    if (!isNil(environments)) {
      setSelectOptions(
        environments.map(environment => {
          return { label: environment.name, value: environment.identifier }
        })
      )
    }
  }, [environments])
 
  React.useEffect(() => {
    Eif (!loading) {
      const envList: EnvironmentYaml[] = []
      if (environmentsResponse?.data?.content?.length) {
        environmentsResponse.data.content.forEach(env => {
          envList.push({
            description: env.environment?.description,
            identifier: env.environment?.identifier || '',
            name: env.environment?.name || '',
            tags: env.environment?.tags,
            type: env.environment?.type || 'PreProduction'
          })
        })
      }
      if (initialValues.environment) {
        const identifier = initialValues.environment.identifier
        const isExist = envList.filter(env => env.identifier === identifier).length > 0
        if (initialValues.environment && identifier && !isExist) {
          envList.push({
            description: initialValues.environment.description,
            identifier: initialValues.environment.identifier || '',
            name: initialValues.environment.name || '',
            tags: initialValues.environment.tags,
            type: initialValues.environment.type || 'PreProduction'
          })
        }
      }
      setEnvironments(envList)
    }
  }, [loading, environmentsResponse, environmentsResponse?.data?.content?.length])
 
  Iif (error?.message) {
    showError(getRBACErrorMessage(error), undefined, 'cd.env.list.error')
  }
 
  const { expressions } = useVariablesExpression()
 
  const [canEdit] = usePermission({
    resource: {
      resourceType: ResourceType.ENVIRONMENT,
      resourceIdentifier: environments ? (environments[0]?.identifier as string) : ''
    },
    permissions: [PermissionIdentifier.EDIT_ENVIRONMENT],
    options: {
      skipCondition: ({ resourceIdentifier }) => !resourceIdentifier
    }
  })
 
  const [canCreate] = usePermission({
    resource: {
      resourceType: ResourceType.ENVIRONMENT
    },
    permissions: [PermissionIdentifier.EDIT_ENVIRONMENT]
  })
 
  const { subscribeForm, unSubscribeForm } = React.useContext(StageErrorContext)
 
  const formikRef = React.useRef<FormikProps<unknown> | null>(null)
 
  React.useEffect(() => {
    subscribeForm({ tab: DeployTabs.INFRASTRUCTURE, form: formikRef })
    return () => unSubscribeForm({ tab: DeployTabs.INFRASTRUCTURE, form: formikRef })
  }, [])
 
  const environmentRef = initialValues?.environment?.identifier || initialValues?.environmentRef
 
  const [type, setType] = React.useState<MultiTypeInputType>(getMultiTypeFromValue(environmentRef))
 
  return (
    <>
      <Formik<DeployEnvData>
        formName="deployEnvStepForm"
        onSubmit={noop}
        validate={values => {
          Iif (!isEmpty(values.environment)) {
            onUpdate?.({ ...omit(values, 'environmentRef') })
          } else {
            onUpdate?.({ ...omit(values, 'environment'), environmentRef: values.environmentRef })
          }
        }}
        initialValues={{
          ...initialValues,
          ...{ environmentRef }
        }}
        validationSchema={Yup.object().shape({
          environmentRef: getEnvironmentRefSchema(getString)
        })}
      >
        {formik => {
          window.dispatchEvent(new CustomEvent('UPDATE_ERRORS_STRIP', { detail: DeployTabs.INFRASTRUCTURE }))
          formikRef.current = formik
          const { values, setFieldValue } = formik
          return (
            <FormikForm>
              <Layout.Horizontal
                className={css.formRow}
                spacing="medium"
                flex={{ alignItems: flexStart, justifyContent: flexStart }}
              >
                <FormInput.MultiTypeInput
                  label={getString('cd.pipelineSteps.environmentTab.specifyYourEnvironment')}
                  tooltipProps={{ dataTooltipId: 'specifyYourEnvironment' }}
                  name="environmentRef"
                  useValue
                  disabled={readonly || (type === MultiTypeInputType.FIXED && loading)}
                  placeholder={
                    loading ? getString('loading') : getString('cd.pipelineSteps.environmentTab.selectEnvironment')
                  }
                  multiTypeInputProps={{
                    onTypeChange: setType,
                    width: 300,
                    onChange: val => {
                      if (
                        values.environment?.identifier &&
                        (val as SelectOption).value !== values.environment.identifier
                      ) {
                        setEnvironments(environments?.filter(env => env.identifier !== values.environment?.identifier))
                        setFieldValue('environment', undefined)
                      }
                    },
                    selectProps: {
                      addClearBtn: !readonly,
                      items: selectOptions || []
                    },
                    expressions,
                    allowableTypes
                  }}
                  selectItems={selectOptions || []}
                />
                {type === MultiTypeInputType.FIXED && (
                  <Button
                    size={ButtonSize.SMALL}
                    variation={ButtonVariation.LINK}
                    disabled={readonly || (isEditEnvironment(values) ? !canEdit : !canCreate)}
                    onClick={() => {
                      const isEdit = isEditEnvironment(values)
                      if (isEdit) {
                        if (values.environment?.identifier) {
                          setState({
                            isEdit,
                            formik,
                            isEnvironment: true,
                            data: values.environment
                          })
                        } else {
                          setState({
                            isEdit,
                            formik,
                            isEnvironment: false,
                            data: environments?.find(env => env.identifier === values.environmentRef)
                          })
                        }
                      } else {
                        setState({
                          isEdit: false,
                          isEnvironment: false,
                          formik
                        })
                      }
                      showModal()
                    }}
                    text={
                      isEditEnvironment(values)
                        ? getString('editEnvironment')
                        : getString('cd.pipelineSteps.environmentTab.plusNewEnvironment')
                    }
                    id={isEditEnvironment(values) ? 'edit-environment' : 'add-new-environment'}
                  />
                )}
              </Layout.Horizontal>
            </FormikForm>
          )
        }}
      </Formik>
    </>
  )
}
 
const DeployEnvironmentInputStep: React.FC<DeployEnvironmentProps & { formik?: any }> = ({
  inputSetData,
  initialValues,
  formik,
  allowableTypes
}) => {
  const { getString } = useStrings()
  const { accountId, projectIdentifier, orgIdentifier } = useParams<
    PipelineType<{
      orgIdentifier: string
      projectIdentifier: string
      pipelineIdentifier: string
      accountId: string
    }>
  >()
 
  const { showError } = useToaster()
  const { getRBACErrorMessage } = useRBACError()
  const [state, setState] = React.useState<DeployEnvironmentState>({
    isEdit: false,
    isEnvironment: false,
    data: { name: '', identifier: '' }
  })
  const { expressions } = useVariablesExpression()
  const {
    data: environmentsResponse,
    error,
    refetch
  } = useGetEnvironmentAccessList({
    queryParams: { accountIdentifier: accountId, orgIdentifier, projectIdentifier },
    lazy: true
  })
  const [environments, setEnvironments] = React.useState<SelectOption[]>([])
 
  React.useEffect(() => {
    refetch()
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [])
 
  const [showModal, hideModal] = useModalHook(
    () => (
      <Dialog
        isOpen={true}
        enforceFocus={false}
        canEscapeKeyClose
        canOutsideClickClose
        onClose={onClose}
        isCloseButtonShown
        title={state.isEdit ? getString('editEnvironment') : getString('newEnvironment')}
        className={'padded-dialog'}
      >
        <NewEditEnvironmentModal
          data={{
            name: defaultTo(state.data?.name, ''),
            identifier: defaultTo(state.data?.identifier, ''),
            orgIdentifier,
            projectIdentifier,
            ...state.data
          }}
          isEnvironment={state.isEnvironment}
          isEdit={state.isEdit}
          onCreateOrUpdate={values => {
            refetch()
            formik?.setFieldValue(
              `${isEmpty(inputSetData?.path) ? '' : `${inputSetData?.path}.`}environmentRef`,
              values.identifier
            )
            onClose.call(null)
          }}
          closeModal={onClose}
        />
      </Dialog>
    ),
    [state]
  )
  const onClose = React.useCallback(() => {
    setState({ isEdit: false, isEnvironment: false })
    hideModal()
  }, [hideModal])
 
  React.useEffect(() => {
    Eif (environmentsResponse?.data?.length) {
      setEnvironments(
        environmentsResponse.data.map(env => ({
          label: env.environment?.name || env.environment?.identifier || '',
          value: env.environment?.identifier || ''
        }))
      )
    }
  }, [environmentsResponse, environmentsResponse?.data?.length])
  const [canEdit] = usePermission({
    resource: {
      resourceType: ResourceType.ENVIRONMENT,
      resourceIdentifier: environments[0]?.value as string
    },
    permissions: [PermissionIdentifier.EDIT_ENVIRONMENT],
    options: {
      skipCondition: ({ resourceIdentifier }) => !resourceIdentifier
    }
  })
 
  const [canCreate] = usePermission({
    resource: {
      resourceType: ResourceType.ENVIRONMENT
    },
    permissions: [PermissionIdentifier.EDIT_ENVIRONMENT]
  })
  Iif (error?.message) {
    showError(getRBACErrorMessage(error), undefined, 'cd.env.list.error')
  }
  return (
    <>
      {getMultiTypeFromValue(inputSetData?.template?.environmentRef) === MultiTypeInputType.RUNTIME && (
        <Layout.Horizontal spacing="medium" style={{ alignItems: 'center' }}>
          <ExperimentalInput
            label={getString('cd.pipelineSteps.environmentTab.specifyYourEnvironment')}
            tooltipProps={{ dataTooltipId: 'specifyYourEnvironment' }}
            name={`${isEmpty(inputSetData?.path) ? '' : `${inputSetData?.path}.`}environmentRef`}
            placeholder={getString('cd.pipelineSteps.environmentTab.selectEnvironment')}
            selectItems={environments}
            useValue
            multiTypeInputProps={{
              allowableTypes,
              selectProps: {
                addClearBtn: !inputSetData?.readonly,
                items: environments
              },
              expressions
            }}
            disabled={inputSetData?.readonly}
            className={css.inputWidth}
            formik={formik}
          />
          {getMultiTypeFromValue(initialValues?.environmentRef) === MultiTypeInputType.FIXED && (
            <Button
              size={ButtonSize.SMALL}
              variation={ButtonVariation.LINK}
              disabled={inputSetData?.readonly || (isEditEnvironment(initialValues) ? !canEdit : !canCreate)}
              onClick={() => {
                const isEdit = isEditEnvironment(initialValues)
                if (isEdit) {
                  setState({
                    isEdit,
                    isEnvironment: false,
                    data: environmentsResponse?.data?.filter(
                      env => env.environment?.identifier === initialValues.environmentRef
                    )?.[0]?.environment as EnvironmentResponseDTO
                  })
                }
                showModal()
              }}
              text={
                isEditEnvironment(initialValues)
                  ? getString('editEnvironment')
                  : getString('cd.pipelineSteps.environmentTab.plusNewEnvironment')
              }
            />
          )}
        </Layout.Horizontal>
      )}
    </>
  )
}
const DeployEnvironmentInputStepFormik = connect(DeployEnvironmentInputStep)
const EnvironmentRegex = /^.+stage\.spec\.infrastructure\.environmentRef$/
export class DeployEnvironmentStep extends Step<DeployEnvData> {
  lastFetched: number
  protected invocationMap: Map<
    RegExp,
    (path: string, yaml: string, params: Record<string, unknown>) => Promise<CompletionItemInterface[]>
  > = new Map()
  constructor() {
    super()
    this.lastFetched = new Date().getTime()
    this.invocationMap.set(EnvironmentRegex, this.getEnvironmentListForYaml.bind(this))
  }
 
  protected getEnvironmentListForYaml(
    path: string,
    yaml: string,
    params: Record<string, unknown>
  ): Promise<CompletionItemInterface[]> {
    let pipelineObj
    try {
      pipelineObj = parse(yaml)
    } catch (err) {
      logger.error('Error while parsing the yaml', err)
    }
    const { accountId, projectIdentifier, orgIdentifier } = params as {
      accountId: string
      orgIdentifier: string
      projectIdentifier: string
    }
    if (pipelineObj) {
      const obj = get(pipelineObj, path.replace('.spec.infrastructure.environmentRef', ''))
      if (obj.type === 'Deployment') {
        return getEnvironmentListPromise({
          queryParams: {
            accountIdentifier: accountId,
            orgIdentifier,
            projectIdentifier
          }
        }).then(response => {
          const data =
            response?.data?.content?.map(service => ({
              label: service.environment?.name || '',
              insertText: service.environment?.identifier || '',
              kind: CompletionItemKind.Field
            })) || []
          return data
        })
      }
    }
 
    return new Promise(resolve => {
      resolve([])
    })
  }
  renderStep(props: StepProps<DeployEnvData>): JSX.Element {
    const { initialValues, onUpdate, stepViewType, inputSetData, readonly = false, allowableTypes } = props
    if (stepViewType === StepViewType.InputSet || stepViewType === StepViewType.DeploymentForm) {
      return (
        <DeployEnvironmentInputStepFormik
          initialValues={initialValues}
          readonly={readonly}
          onUpdate={onUpdate}
          stepViewType={stepViewType}
          inputSetData={inputSetData}
          allowableTypes={allowableTypes}
        />
      )
    }
    return (
      <DeployEnvironmentWidget
        readonly={readonly}
        initialValues={initialValues}
        onUpdate={onUpdate}
        stepViewType={stepViewType}
        allowableTypes={allowableTypes}
      />
    )
  }
  validateInputSet({
    data,
    template,
    getString,
    viewType
  }: ValidateInputSetProps<DeployEnvData>): FormikErrors<DeployEnvData> {
    const errors: FormikErrors<DeployEnvData> = {}
    const isRequired = viewType === StepViewType.DeploymentForm || viewType === StepViewType.TriggerForm
    Iif (
      isEmpty(data?.environmentRef) &&
      isRequired &&
      getMultiTypeFromValue(template?.environmentRef) === MultiTypeInputType.RUNTIME
    ) {
      errors.environmentRef = getString?.('cd.pipelineSteps.environmentTab.environmentIsRequired')
    }
    return errors
  }
  protected stepPaletteVisible = false
  protected type = StepType.DeployEnvironment
  protected stepName = 'Deploy Environment'
  protected stepIcon: IconName = 'main-environments'
 
  protected defaultValues: DeployEnvData = {}
}