All files / modules/10-common/modals/HarnessEnvironmentModal HarnessEnvironmentModal.tsx

92.86% Statements 52/56
49.06% Branches 26/53
90% Functions 9/10
92.59% Lines 50/54

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              17x 17x 17x 17x 17x 17x 17x 17x 17x 17x 17x 17x 17x     17x               7x 7x 7x           7x           7x         7x   7x   2x 2x 1x         1x 1x 1x 1x 1x     1x 1x 1x 1x 1x 1x                   7x 5x   7x                     7x     7x             2x                 24x                         48x                         3x                           17x     9x 9x 9x   2x                                     9x          
/*
 * 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 * as Yup from 'yup'
import cx from 'classnames'
import { omit } from 'lodash-es'
import { useParams } from 'react-router-dom'
import { Dialog, Classes } from '@blueprintjs/core'
import { Formik, Layout, ThumbnailSelect, Label, Button, Container } from '@wings-software/uicore'
import { useModalHook } from '@harness/use-modal'
import { useToaster } from '@common/exports'
import { NameIdDescriptionTags, PageSpinner } from '@common/components'
import { NameSchema, IdentifierSchema } from '@common/utils/Validation'
import { useStrings } from 'framework/strings'
import { useCreateEnvironmentV2, useUpsertEnvironmentV2, EnvironmentResponseDTO } from 'services/cd-ng'
import type { HarnessEnvironmentModalProps } from './HarnessEnvironmentModal.types'
 
export const HarnessEnvironmentModal: React.FC<HarnessEnvironmentModalProps> = ({
  isEdit,
  data,
  isEnvironment,
  formik,
  onCreateOrUpdate,
  closeModal
}) => {
  const { getString } = useStrings()
  const inputRef = React.useRef<HTMLInputElement | null>(null)
  const { accountId, projectIdentifier, orgIdentifier } = useParams<{
    orgIdentifier: string
    projectIdentifier: string
    accountId: string
  }>()
 
  const { loading: createLoading, mutate: createEnvironment } = useCreateEnvironmentV2({
    queryParams: {
      accountIdentifier: accountId
    }
  })
 
  const { loading: updateLoading, mutate: updateEnvironment } = useUpsertEnvironmentV2({
    queryParams: {
      accountIdentifier: accountId
    }
  })
  const { showSuccess, showError, clear } = useToaster()
 
  const onSubmit = React.useCallback(
    async (values: Required<EnvironmentResponseDTO>) => {
      try {
        if (isEdit && !isEnvironment) {
          const response = await updateEnvironment({
            ...omit(values, 'accountId', 'deleted'),
            orgIdentifier,
            projectIdentifier
          })
          Eif (response.status === 'SUCCESS') {
            clear()
            showSuccess(getString('common.environmentUpdated'))
            formik?.setFieldValue('environmentRef', values.identifier)
            onCreateOrUpdate(values)
          }
        } else {
          const response = await createEnvironment({ ...values, orgIdentifier, projectIdentifier })
          Eif (response.status === 'SUCCESS') {
            clear()
            showSuccess(getString('common.environmentCreated'))
            formik?.setFieldValue('environmentRef', values.identifier)
            onCreateOrUpdate(values)
          }
        }
      } catch (e) {
        showError(e?.data?.message || e?.message || getString('commonError'))
      }
    },
    // 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('nonProduction'),
      value: 'PreProduction'
    }
  ]
 
  Iif (createLoading || updateLoading) {
    return <PageSpinner />
  }
  return (
    <Layout.Vertical>
      <Formik<Required<EnvironmentResponseDTO>>
        initialValues={data as Required<EnvironmentResponseDTO>}
        enableReinitialize={false}
        formName="deployEnv"
        onSubmit={values => {
          onSubmit(values)
        }}
        validationSchema={Yup.object().shape({
          name: NameSchema({ requiredErrorMsg: getString?.('fieldRequired', { field: 'Environment' }) }),
          type: Yup.string().required(getString?.('fieldRequired', { field: 'Type' })),
          identifier: IdentifierSchema()
        })}
      >
        {formikProps => (
          <Layout.Vertical
            onKeyDown={e => {
              if (e.key === 'Enter') {
                formikProps.handleSubmit()
              }
            }}
          >
            <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 style={{ fontSize: 13, fontWeight: 'normal' }}>{getString('envType')}</Label>
              <ThumbnailSelect name={'type'} items={typeList} />
            </Layout.Vertical>
            <Container padding={{ top: 'xlarge' }}>
              <Button
                data-id="environment-save"
                onClick={() => formikProps.submitForm()}
                intent="primary"
                text={getString('save')}
              />
              &nbsp; &nbsp;
              <Button text={getString('cancel')} onClick={closeModal} />
            </Container>
          </Layout.Vertical>
        )}
      </Formik>
    </Layout.Vertical>
  )
}
 
export const useHarnessEnvironmentModal = (
  props: HarnessEnvironmentModalProps
): { openHarnessEnvironmentModal: () => void; closeHarnessEnvironmentModal: () => void } => {
  const { getString } = useStrings()
  const { data, isEnvironment, isEdit, formik, onClose, onCreateOrUpdate, className, modalTitle } = props
  const [showModal, hideModal] = useModalHook(
    () => (
      <Dialog
        isOpen
        title={modalTitle || getString('newEnvironment')}
        onClose={hideModal}
        enforceFocus={false}
        className={cx('padded-dialog', className, Classes.DIALOG)}
      >
        <HarnessEnvironmentModal
          data={data}
          isEdit={isEdit}
          formik={formik}
          isEnvironment={isEnvironment}
          onCreateOrUpdate={onCreateOrUpdate}
          closeModal={onClose ? onClose : hideModal}
        />
      </Dialog>
    ),
    []
  )
  return {
    openHarnessEnvironmentModal: showModal,
    closeHarnessEnvironmentModal: hideModal
  }
}