All files / modules/75-cf/components/CreateFlagWizard FlagWizard.tsx

62.9% Statements 39/62
11.11% Branches 4/36
20% Functions 1/5
62.9% Lines 39/62

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              5x 5x 5x 5x           5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x                           5x 3x 2x 2x       2x 2x 2x 2x 2x 2x 2x     2x 2x   2x               2x   2x                                                                                                             2x                                                                       5x  
/*
 * 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, { useState } from 'react'
import { useHistory, useParams } from 'react-router-dom'
import { StepWizard, SelectOption, ModalErrorHandlerBinding } from '@wings-software/uicore'
import {
  useCreateFeatureFlag,
  FeatureFlagRequestRequestBody,
  CreateFeatureFlagQueryParams,
  GitSyncErrorResponse
} from 'services/cf'
import { useAppStore } from 'framework/AppStore/AppStoreContext'
import routes from '@common/RouteDefinitions'
import { useToaster } from '@common/exports'
import { useStrings } from 'framework/strings'
import { getErrorMessage, showToaster, FeatureFlagMutivariateKind } from '@cf/utils/CFUtils'
import useActiveEnvironment from '@cf/hooks/useActiveEnvironment'
import { useFeatureFlagTelemetry } from '@cf/hooks/useFeatureFlagTelemetry'
import { PageSpinner } from '@common/components'
import { GIT_SYNC_ERROR_CODE, useGitSync } from '@cf/hooks/useGitSync'
import { useGovernance } from '@cf/hooks/useGovernance'
import { AUTO_COMMIT_MESSAGES } from '@cf/constants/GitSyncConstants'
import FlagElemAbout from './FlagElemAbout'
import FlagElemBoolean from './FlagElemBoolean'
import FlagElemMultivariate from './FlagElemMultivariate'
import { FlagTypeVariations } from '../CreateFlagDialog/FlagDialogUtils'
import SaveFlagRepoStep from './SaveFlagRepoStep'
import css from './FlagWizard.module.scss'
 
interface FlagWizardProps {
  flagTypeView: string
  environmentIdentifier: string
  toggleFlagType: (newFlag: string) => void
  hideModal: () => void
  goBackToTypeSelections: () => void
}
 
export interface FlagWizardFormValues extends FeatureFlagRequestRequestBody {
  autoCommit: boolean
}
 
const FlagWizard: React.FC<FlagWizardProps> = props => {
  const { getString } = useStrings()
  const { currentUserInfo } = useAppStore()
  const flagTypeOptions: SelectOption[] = [
    { label: getString('cf.boolean'), value: FlagTypeVariations.booleanFlag },
    { label: getString('cf.multivariate'), value: FeatureFlagMutivariateKind.string }
  ]
  const { flagTypeView, environmentIdentifier, toggleFlagType, hideModal, goBackToTypeSelections } = props
  const [modalErrorHandler, setModalErrorHandler] = useState<ModalErrorHandlerBinding | undefined>()
  const { showError } = useToaster()
  const { projectIdentifier, orgIdentifier, accountId: accountIdentifier } = useParams<Record<string, string>>()
  const history = useHistory()
  const { activeEnvironment, withActiveEnvironment } = useActiveEnvironment()
  const { handleError: handleGovernanceError, isGovernanceError } = useGovernance()
 
  const { isAutoCommitEnabled, isGitSyncEnabled, gitSyncLoading, handleAutoCommit, getGitSyncFormMeta, handleError } =
    useGitSync()
  const { gitSyncInitialValues } = getGitSyncFormMeta(AUTO_COMMIT_MESSAGES.CREATED_FLAG)
 
  const { mutate: createFeatureFlag, loading: isLoadingCreateFeatureFlag } = useCreateFeatureFlag({
    queryParams: {
      accountIdentifier,
      orgIdentifier,
      environmentIdentifier: activeEnvironment
    } as CreateFeatureFlagQueryParams
  })
 
  const events = useFeatureFlagTelemetry()
 
  const onWizardSubmit = (formData: FlagWizardFormValues | undefined): void => {
    modalErrorHandler?.hide()
 
    if (formData) {
      const valTags: any = formData?.tags?.map(elem => {
        return { name: elem, value: elem }
      })
      formData.tags = valTags
      // Note: Currently there's no official way to get current user. Rely on old token from
      // current gen login
      formData.owner = currentUserInfo.email || 'unknown'
      formData.project = projectIdentifier
 
      if (isAutoCommitEnabled) {
        formData.gitDetails = gitSyncInitialValues.gitDetails
      }
    }
 
    if (formData) {
      createFeatureFlag(formData)
        .then(async () => {
          if (!isAutoCommitEnabled && formData.autoCommit) {
            await handleAutoCommit(formData.autoCommit)
          }
          events.createFeatureFlagCompleted()
          hideModal()
          history.push(
            withActiveEnvironment(
              routes.toCFFeatureFlagsDetail({
                orgIdentifier: orgIdentifier as string,
                projectIdentifier: projectIdentifier as string,
                featureFlagIdentifier: formData.identifier,
                accountId: accountIdentifier
              }),
              environmentIdentifier
            )
          )
          showToaster(getString('cf.messages.flagCreated'))
        })
        .catch(error => {
          if (error.status === GIT_SYNC_ERROR_CODE) {
            handleError(error.data as GitSyncErrorResponse)
          } else {
            if (isGovernanceError(error)) {
              handleGovernanceError(error.data)
            } else {
              showError(getErrorMessage(error), 0, 'cf.savegw.error')
            }
          }
        })
    } else {
      hideModal()
    }
  }
 
  return (
    <StepWizard className={css.flagWizardContainer} onCompleteWizard={onWizardSubmit}>
      {gitSyncLoading ? <PageSpinner /> : null}
 
      <FlagElemAbout
        name={getString('cf.creationModal.aboutFlag.aboutFlagHeading')}
        goBackToTypeSelections={goBackToTypeSelections}
      />
      {flagTypeView === FlagTypeVariations.booleanFlag ? (
        <FlagElemBoolean
          name={getString('cf.creationModal.variationSettingsHeading')}
          toggleFlagType={toggleFlagType}
          flagTypeOptions={flagTypeOptions}
          setModalErrorHandler={setModalErrorHandler}
          isLoadingCreateFeatureFlag={isLoadingCreateFeatureFlag}
        />
      ) : (
        <FlagElemMultivariate
          name={getString('cf.creationModal.variationSettingsHeading')}
          toggleFlagType={toggleFlagType}
          flagTypeOptions={flagTypeOptions}
          setModalErrorHandler={setModalErrorHandler}
          isLoadingCreateFeatureFlag={isLoadingCreateFeatureFlag}
        />
      )}
 
      {isGitSyncEnabled && !isAutoCommitEnabled ? (
        <SaveFlagRepoStep
          name={getString('common.gitSync.gitRepositoryDetails')}
          isLoadingCreateFeatureFlag={isLoadingCreateFeatureFlag}
        />
      ) : null}
    </StepWizard>
  )
}
 
export default FlagWizard