All files / modules/75-cf/components/FlagActivation/hooks useEditFlagDetailsModal.tsx

85.11% Statements 40/47
64.91% Branches 37/57
87.5% Functions 7/8
85.11% Lines 40/47

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              3x 3x 3x 3x 3x                 3x   3x 3x 3x 3x 3x 3x 3x                           3x 53x 53x 53x   53x 7x   7x               7x 3x 3x 3x     3x       3x       3x   3x                 3x 1x     3x 3x 3x 3x                                 7x                         81x                                                           1x 1x                       53x     3x  
/*
 * 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 { Button, Container, Formik, FormikForm as Form, FormInput, Layout, Text } from '@wings-software/uicore'
import { useModalHook } from '@harness/use-modal'
import { Dialog, Divider } from '@blueprintjs/core'
import * as yup from 'yup'
import type { MutateMethod } from 'restful-react/dist/Mutate'
import type {
  Feature,
  GitSyncErrorResponse,
  GitSyncPatchOperation,
  PatchFeaturePathParams,
  PatchFeatureQueryParams
} from 'services/cf'
import { showToaster } from '@cf/utils/CFUtils'
 
import { GIT_SYNC_ERROR_CODE, UseGitSync } from '@cf/hooks/useGitSync'
import { useGovernance } from '@cf/hooks/useGovernance'
import { useStrings } from 'framework/strings'
import { AUTO_COMMIT_MESSAGES } from '@cf/constants/GitSyncConstants'
import patch from '../../../utils/instructions'
import SaveFlagToGitSubForm from '../../SaveFlagToGitSubForm/SaveFlagToGitSubForm'
import css from '../FlagActivationDetails.module.scss'
 
interface UseEditFlagDetailsModalProps {
  featureFlag: Feature
  gitSync: UseGitSync
  submitPatch: MutateMethod<Feature, GitSyncPatchOperation, PatchFeatureQueryParams, PatchFeaturePathParams>
  refetchFlag: () => void
}
 
interface UseEditFlagDetailsModalReturn {
  openEditDetailsModal: () => void
  hideEditDetailsModal: () => void
}
 
const useEditFlagDetailsModal = (props: UseEditFlagDetailsModalProps): UseEditFlagDetailsModalReturn => {
  const { featureFlag, gitSync, refetchFlag, submitPatch } = props
  const { getString } = useStrings()
  const { handleError: handleGovernanceError, isGovernanceError } = useGovernance()
 
  const [openEditDetailsModal, hideEditDetailsModal] = useModalHook(() => {
    const gitSyncFormMeta = gitSync?.getGitSyncFormMeta(AUTO_COMMIT_MESSAGES.UPDATED_FLAG_VARIATIONS)
 
    const initialValues = {
      name: featureFlag.name.trim(),
      description: featureFlag.description,
      permanent: featureFlag.permanent,
      gitDetails: gitSyncFormMeta?.gitSyncInitialValues.gitDetails,
      autoCommit: gitSyncFormMeta?.gitSyncInitialValues.autoCommit
    }
 
    const handleSubmit = (values: typeof initialValues): void => {
      const { name, description, permanent } = values
      Eif (name !== initialValues.name) {
        patch.feature.addInstruction(patch.creators.updateName(name as string))
      }
 
      Iif (description !== initialValues.description) {
        patch.feature.addInstruction(patch.creators.updateDescription(description as string))
      }
 
      Iif (permanent !== initialValues.permanent) {
        patch.feature.addInstruction(patch.creators.updatePermanent(!!permanent))
      }
 
      patch.feature
        .onPatchAvailable(data => {
          submitPatch(
            gitSync?.isGitSyncEnabled
              ? {
                  ...data,
                  gitDetails: values.gitDetails
                }
              : data
          )
            .then(async () => {
              if (values.autoCommit) {
                await gitSync?.handleAutoCommit(values.autoCommit)
              }
 
              patch.feature.reset()
              hideEditDetailsModal()
              refetchFlag()
              showToaster(getString('cf.messages.flagUpdated'))
            })
            .catch(error => {
              if (error.status === GIT_SYNC_ERROR_CODE) {
                gitSync?.handleError(error.data as GitSyncErrorResponse)
              } else {
                if (isGovernanceError(error)) {
                  handleGovernanceError(error.data)
                } else {
                  patch.feature.reset()
                }
              }
            })
        })
        .onEmptyPatch(hideEditDetailsModal)
    }
 
    return (
      <Dialog enforceFocus={false} onClose={hideEditDetailsModal} isOpen={true} title="" className={css.editFlagModal}>
        <Formik
          enableReinitialize={true}
          initialValues={initialValues}
          validationSchema={yup.object().shape({
            name: yup.string().required(getString('cf.creationModal.aboutFlag.nameRequired')),
            gitDetails: gitSyncFormMeta.gitSyncValidationSchema
          })}
          formName="flagActivationDetails"
          onSubmit={handleSubmit}
        >
          {() => (
            <Form data-testid="edit-flag-form">
              <Layout.Vertical className={css.editDetailsModalContainer} spacing="large">
                <Text>{getString('cf.editDetails.editDetailsHeading')}</Text>
 
                <FormInput.Text name="name" label={getString('name')} />
 
                <FormInput.TextArea name="description" label={getString('description')} />
 
                <Container>
                  <FormInput.CheckBox
                    name="permanent"
                    label={getString('cf.editDetails.permaFlag')}
                    className={css.checkboxEditDetails}
                  />
                </Container>
                {gitSync?.isGitSyncEnabled && !gitSync?.isAutoCommitEnabled && (
                  <>
                    <Container>
                      <Divider />
                    </Container>
                    <SaveFlagToGitSubForm subtitle={getString('cf.gitSync.commitChanges')} hideNameField />
                  </>
                )}
 
                <Container>
                  <Button intent="primary" text={getString('save')} type="submit" />
                  <Button
                    minimal
                    text={getString('cancel')}
                    onClick={e => {
                      e.preventDefault()
                      hideEditDetailsModal()
                    }}
                  />
                </Container>
              </Layout.Vertical>
            </Form>
          )}
        </Formik>
      </Dialog>
    )
  }, [featureFlag, gitSync?.isAutoCommitEnabled, gitSync?.isGitSyncEnabled])
 
  return { openEditDetailsModal, hideEditDetailsModal }
}
 
export default useEditFlagDetailsModal