All files / modules/75-ce/components/AnomaliesAlert AnomaliesAlertDialog.tsx

100% Statements 36/36
80% Branches 16/20
100% Functions 7/7
100% Lines 34/34

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              5x 5x 5x 5x 5x 5x 5x 5x 5x   5x           5x 5x 5x   5x                                                               5x         5x   5x         20x           5x 10x           5x                       5x     1x                   14x                                                             5x 28x 27x 27x   27x             27x                                                                                                       27x   5x               27x         5x  
/*
 * 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 { Dialog, IDialogProps } from '@blueprintjs/core'
import { StepWizard, Formik, FormikForm, useToaster, getErrorInfoFromErrorObject, Color } from '@harness/uicore'
import { useModalHook } from '@harness/use-modal'
import { useParams } from 'react-router-dom'
import * as Yup from 'yup'
import { useStrings } from 'framework/strings'
import { QlceView, useFetchPerspectiveListQuery } from 'services/ce/services'
import { channelNameUrlMapping, channels } from '@ce/constants'
import type { AccountPathProps } from '@common/interfaces/RouteInterfaces'
import {
  CCMNotificationChannel,
  CCMPerspectiveNotificationChannelsDTO,
  useCreateNotificationSetting,
  useUpdateNotificationSetting
} from 'services/ce'
import PerspectiveSelection from './PerspectiveSelection'
import NotificationMethod from './NotificationMethod'
import css from './AnomaliesAlertDialog.module.scss'
 
const modalPropsLight: IDialogProps = {
  isOpen: true,
  enforceFocus: false,
  style: {
    width: 1100,
    position: 'relative',
    minHeight: 600,
    borderLeft: 0,
    paddingBottom: 0,
    overflow: 'hidden'
  }
}
 
interface AlertDialogProps {
  hideAnomaliesAlertModal: () => void
  handleSubmit: (data: FormValues) => void
  notificationData: CCMPerspectiveNotificationChannelsDTO
}
interface AnomalyAlertDialogProps {
  setRefetchingState: React.Dispatch<React.SetStateAction<boolean>>
  selectedAlert: CCMPerspectiveNotificationChannelsDTO
}
 
interface AlertsData {
  channelName?: channels
  channelUrl?: string | string[]
}
interface FormValues {
  perspective: string
  alertList: AlertsData[]
}
 
export const AnomalyAlertDialog: React.FC<AlertDialogProps> = ({
  hideAnomaliesAlertModal,
  handleSubmit,
  notificationData
}) => {
  const { getString } = useStrings()
 
  const [{ data: perspectiveData }] = useFetchPerspectiveListQuery()
 
  /* istanbul ignore next */
  const perspectiveList = (perspectiveData?.perspectives?.customerViews || []) as QlceView[]
 
  const items = perspectiveList.map(pName => ({
    label: pName.name as string,
    value: pName.id as string
  }))
 
  const channelsData =
    notificationData?.channels?.map((item: CCMNotificationChannel) => {
      return {
        channelName: item.notificationChannelType,
        channelUrl: item.channelUrls?.[0]
      }
    }) || /* istanbul ignore next */ []
 
  const validationSchema = Yup.object().shape({
    perspective: Yup.string().required(),
    alertList: Yup.array(
      Yup.object({
        channelName: Yup.string().required(
          getString('ce.anomalyDetection.notificationAlerts.channelSelectionRequiredMsg')
        ),
        channelUrl: Yup.string().required(getString('ce.anomalyDetection.notificationAlerts.channelUrlRequiredMsg'))
      })
    )
  })
 
  return (
    <Dialog onClose={hideAnomaliesAlertModal} {...modalPropsLight} canOutsideClickClose={true}>
      <Formik
        onSubmit={data => handleSubmit(data)}
        formName={'createNotificationAlert'}
        initialValues={{
          perspective: notificationData?.perspectiveId || '',
          channelName: '',
          channelUrl: '',
          alertList: channelsData || /* istanbul ignore next */ []
        }}
        validationSchema={validationSchema}
        render={formikProps => {
          return (
            <FormikForm>
              <StepWizard
                icon="right-bar-notification"
                iconProps={{
                  size: 34,
                  color: Color.WHITE
                }}
                className={css.stepWizard}
                title={getString('ce.anomalyDetection.notificationAlerts.heading')}
              >
                <PerspectiveSelection
                  name={getString('ce.anomalyDetection.notificationAlerts.overviewStep')}
                  onClose={hideAnomaliesAlertModal}
                  items={items}
                  formikProps={formikProps}
                />
                <NotificationMethod
                  name={getString('ce.anomalyDetection.notificationAlerts.notificationStep')}
                  onClose={hideAnomaliesAlertModal}
                  formikProps={formikProps}
                />
              </StepWizard>
            </FormikForm>
          )
        }}
      />
    </Dialog>
  )
}
 
const useAnomaliesAlertDialog = (props: AnomalyAlertDialogProps) => {
  const { accountId } = useParams<AccountPathProps>()
  const { showError, showSuccess } = useToaster()
  const { getString } = useStrings()
 
  const { mutate: createNotificationAlert } = useCreateNotificationSetting({
    queryParams: {
      accountIdentifier: accountId,
      perspectiveId: ''
    }
  })
 
  const { mutate: updateNotificationAlert } = useUpdateNotificationSetting({
    queryParams: {
      accountIdentifier: accountId,
      perspectiveId: ''
    }
  })
 
  /* istanbul ignore next */
  const handleSubmit = async (data: FormValues) => {
    const payload = data.alertList.map((item: AlertsData) => {
      const channel = item.channelName
 
      if (channel === 'EMAIL' && typeof item.channelUrl === 'string') {
        const emailList = item.channelUrl.split(',')
        return {
          type: channel,
          [channelNameUrlMapping[channel as keyof typeof channelNameUrlMapping]]: emailList
        }
      }
      return {
        type: channel,
        [channelNameUrlMapping[channel as keyof typeof channelNameUrlMapping]]: item.channelUrl
      }
    })
 
    const queryParams = {
      perspectiveId: data.perspective,
      accountIdentifier: accountId
    }
 
    try {
      let response
      if (props.selectedAlert && props.selectedAlert.channels?.length) {
        response = await updateNotificationAlert({ channels: payload as CCMNotificationChannel[] }, { queryParams })
      } else {
        response = await createNotificationAlert({ channels: payload as CCMNotificationChannel[] }, { queryParams })
      }
 
      hideAnomaliesAlertModal()
      props.setRefetchingState(true)
      if (response) {
        if (props.selectedAlert && props.selectedAlert.channels?.length) {
          showSuccess(getString('ce.anomalyDetection.notificationAlerts.updateAlertSuccessMsg'))
        } else {
          showSuccess(getString('ce.anomalyDetection.notificationAlerts.addAlertSuccessMsg'))
        }
      }
    } catch (error) {
      showError(getErrorInfoFromErrorObject(error))
    }
  }
 
  const [createAnomaliesAlertModal, hideAnomaliesAlertModal] = useModalHook(
    () => (
      <AnomalyAlertDialog
        hideAnomaliesAlertModal={hideAnomaliesAlertModal}
        handleSubmit={handleSubmit}
        notificationData={props.selectedAlert}
      />
    ),
    [props.selectedAlert]
  )
  return {
    openAnomaliesAlertModal: createAnomaliesAlertModal
  }
}
 
export default useAnomaliesAlertDialog