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

93.22% Statements 55/59
50% Branches 26/52
90% Functions 9/10
92.98% Lines 53/57

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              16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x 16x   16x   16x                     7x 7x 7x 7x           7x           7x           7x 5x     7x   7x   2x 2x 2x 1x         1x 1x 1x 1x 1x     1x 1x 1x 1x 1x 1x                           7x 1x     6x           2x               18x                         36x                 3x                         16x     39x                         39x 39x   1x                                           39x          
/*
 * 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 { Layout, Container, Button, Formik } from '@wings-software/uicore'
import { useModalHook } from '@harness/use-modal'
import { NameIdDescriptionTags, PageSpinner } from '@common/components'
import { useToaster } from '@common/exports'
import { NameSchema, IdentifierSchema } from '@common/utils/Validation'
import { useStrings } from 'framework/strings'
import { useCreateServicesV2, useUpsertServiceV2, ServiceRequestDTO } from 'services/cd-ng'
import type { HarnessServicetModalProps } from './HarnessServiceModal.types'
import { getHarnessServiceModalFormDetails } from './HarnessServiceModal.utils'
 
export const HarnessServicetModal: React.FC<HarnessServicetModalProps> = ({
  isEdit,
  data,
  isService,
  formik,
  onCreateOrUpdate,
  closeModal,
  skipServiceCreateOrUpdate,
  name,
  customLoading
}): JSX.Element => {
  const { getString } = useStrings()
  const inputRef = React.useRef<HTMLInputElement | null>(null)
  const { formName, field } = getHarnessServiceModalFormDetails(name)
  const { accountId, projectIdentifier, orgIdentifier } = useParams<{
    orgIdentifier: string
    projectIdentifier: string
    accountId: string
  }>()
 
  const { loading: createLoading, mutate: createService } = useCreateServicesV2({
    queryParams: {
      accountIdentifier: accountId
    }
  })
 
  const { loading: updateLoading, mutate: updateService } = useUpsertServiceV2({
    queryParams: {
      accountIdentifier: accountId
    }
  })
 
  React.useEffect(() => {
    inputRef.current?.focus()
  }, [])
 
  const { showSuccess, showError, clear } = useToaster()
 
  const onSubmit = React.useCallback(
    async (values: ServiceRequestDTO) => {
      Eif (!skipServiceCreateOrUpdate) {
        try {
          if (isEdit && !isService) {
            const response = await updateService({
              ...omit(values, 'accountId', 'deleted'),
              orgIdentifier,
              projectIdentifier
            })
            Eif (response.status === 'SUCCESS') {
              clear()
              showSuccess(getString('common.serviceCreated'))
              formik?.setFieldValue('serviceRef', values.identifier)
              onCreateOrUpdate(values)
            }
          } else {
            const response = await createService([{ ...values, orgIdentifier, projectIdentifier }])
            Eif (response.status === 'SUCCESS') {
              clear()
              showSuccess(getString('common.serviceCreated'))
              formik?.setFieldValue('serviceRef', values.identifier)
              onCreateOrUpdate(values)
            }
          }
        } catch (e) {
          showError(e?.data?.message || e?.message || getString('commonError'))
        }
      } else {
        onCreateOrUpdate(values)
      }
    },
    // eslint-disable-next-line react-hooks/exhaustive-deps
    [skipServiceCreateOrUpdate, isEdit, isService, orgIdentifier, projectIdentifier, formik]
  )
 
  if (createLoading || updateLoading || customLoading) {
    return <PageSpinner />
  }
 
  return (
    <Formik<ServiceRequestDTO>
      initialValues={data}
      formName={formName}
      enableReinitialize={false}
      onSubmit={values => {
        onSubmit(values)
      }}
      validationSchema={Yup.object().shape({
        name: NameSchema({ requiredErrorMsg: getString?.('fieldRequired', { field }) }),
        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
            }}
          />
          <Container padding={{ top: 'xlarge' }}>
            <Button
              data-id="service-save"
              onClick={() => formikProps.submitForm()}
              intent="primary"
              text={getString('save')}
            />
            &nbsp; &nbsp;
            <Button text={getString('cancel')} onClick={closeModal} />
          </Container>
        </Layout.Vertical>
      )}
    </Formik>
  )
}
 
export const useHarnessServicetModal = (
  props: HarnessServicetModalProps
): { openHarnessServiceModal: () => void; closeHarnessServiceModal: () => void } => {
  const { getString } = useStrings()
  const {
    data,
    isService,
    isEdit,
    formik,
    onClose,
    onCreateOrUpdate,
    className,
    modalTitle,
    skipServiceCreateOrUpdate,
    name,
    customLoading
  } = props
  const [showModal, hideModal] = useModalHook(
    () => (
      <Dialog
        isOpen
        title={modalTitle || getString('newService')}
        onClose={hideModal}
        enforceFocus={false}
        className={cx('padded-dialog', className, Classes.DIALOG)}
      >
        <HarnessServicetModal
          data={data}
          isEdit={isEdit}
          formik={formik}
          isService={isService}
          onCreateOrUpdate={onCreateOrUpdate}
          closeModal={onClose ? onClose : hideModal}
          name={name}
          skipServiceCreateOrUpdate={skipServiceCreateOrUpdate}
          customLoading={customLoading}
        />
      </Dialog>
    ),
    [customLoading]
  )
  return {
    openHarnessServiceModal: showModal,
    closeHarnessServiceModal: hideModal
  }
}