All files / modules/15-notifications/modals/ConfigureNotificationsModal/views/ConfigureMSTeamsNotifications ConfigureMSTeamsNotifications.tsx

83.93% Statements 47/56
60.53% Branches 23/38
80% Functions 8/10
85.45% Lines 47/55

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 222 223 224 225 226 227 228 229              29x 29x                       29x 29x 29x 29x 29x 29x 29x   29x 29x 29x 29x 29x   29x                                 29x         29x 6x 6x 6x 6x 6x   6x 2x       2x 2x 2x           2x       2x 2x               6x         2x                                   4x 4x   4x   4x 2x 1x       4x                 3x                     29x   29x 3x   2x       2x                                                           4x                                                                                         29x  
/*
 * 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 {
  FormikForm,
  FormInput,
  Button,
  Layout,
  Icon,
  Text,
  ButtonProps,
  Formik,
  ButtonVariation,
  getErrorInfoFromErrorObject
} from '@wings-software/uicore'
import { useParams } from 'react-router-dom'
import * as Yup from 'yup'
import cx from 'classnames'
import { FormGroup } from '@blueprintjs/core'
import { get, isEmpty } from 'lodash-es'
import { connect, FormikContext, FormikErrors } from 'formik'
import { useToaster } from '@common/exports'
import type { AccountPathProps } from '@common/interfaces/RouteInterfaces'
import { MSTeamsNotificationConfiguration, NotificationType, TestStatus } from '@notifications/interfaces/Notifications'
import { useStrings } from 'framework/strings'
import { MSTeamSettingDTO, useTestNotificationSetting } from 'services/notifications'
import { ListInput } from '@common/components/ListInput/ListInput'
import UserGroupsInput from '@common/components/UserGroupsInput/UserGroupsInput'
 
import css from '@notifications/modals/ConfigureNotificationsModal/ConfigureNotificationsModal.module.scss'
 
interface MSTeamsNotificationsData {
  msTeamKeys: string[]
  userGroups: string[]
}
 
interface ConfigureMSTeamsNotificationsProps {
  onSuccess: (config: MSTeamsNotificationConfiguration) => void
  hideModal: () => void
  withoutHeading?: boolean
  isStep?: boolean
  onBack?: (config?: MSTeamsNotificationConfiguration) => void
  submitButtonText?: string
  config?: MSTeamsNotificationConfiguration
}
 
export const TestMSTeamsNotifications: React.FC<{
  data: MSTeamsNotificationsData
  errors: FormikErrors<MSTeamsNotificationsData>
  onClick?: () => Promise<boolean>
  buttonProps?: ButtonProps
}> = ({ data, onClick, buttonProps, errors }) => {
  const { accountId } = useParams<AccountPathProps>()
  const { getString } = useStrings()
  const [testStatus, setTestStatus] = useState<TestStatus>(TestStatus.INIT)
  const { mutate: testNotificationSetting } = useTestNotificationSetting({})
  const { showSuccess, showError } = useToaster()
 
  const handleTest = async (testData: MSTeamsNotificationsData): Promise<void> => {
    Iif (onClick) {
      const success = await onClick()
      if (!success) return
    }
    try {
      setTestStatus(TestStatus.INIT)
      const resp = await testNotificationSetting({
        accountId,
        type: 'MSTEAMS',
        recipient: testData.msTeamKeys?.join(','),
        notificationId: 'MSTeams'
      } as MSTeamSettingDTO)
      Iif (resp.status === 'SUCCESS' && resp.data) {
        showSuccess(getString('notifications.msTestSuccess'))
        setTestStatus(TestStatus.SUCCESS)
      } else {
        showError(getString('somethingWentWrong'))
        setTestStatus(TestStatus.FAILED)
      }
    } catch (err) {
      showError(getErrorInfoFromErrorObject(err))
      setTestStatus(TestStatus.ERROR)
    }
  }
 
  return (
    <>
      <Button
        text={getString('test')}
        disabled={Object.keys(errors).length > 0}
        onClick={() => handleTest(data)}
        {...buttonProps}
      />
      {testStatus === TestStatus.SUCCESS ? <Icon name="tick" className={cx(css.statusIcon, css.green)} /> : null}
      {testStatus === TestStatus.FAILED || testStatus === TestStatus.ERROR ? (
        <Icon name="cross" className={cx(css.statusIcon, css.red)} />
      ) : null}
    </>
  )
}
 
interface TeamsUrlListInputProps {
  name: string
  label: string
  formik?: FormikContext<any>
}
 
function TeamsUrlListInputInternal(props: TeamsUrlListInputProps) {
  const { name, label, formik } = props
  const { getString } = useStrings()
 
  const value = get(formik?.values, name)
 
  React.useEffect(() => {
    if (isEmpty(value)) {
      formik?.setFieldValue(name, [''])
    }
  }, [])
 
  return (
    <FormGroup label={label} labelFor={name}>
      <ListInput
        name={name}
        elementList={value}
        deleteIconProps={{
          size: 18
        }}
        listItemRenderer={(_, index: number) => (
          <FormInput.Text
            name={`${name}.${index}`}
            placeholder={getString('notifications.enterMicrosoftTeamsUrl')}
            className={css.urlInput}
          />
        )}
      />
    </FormGroup>
  )
}
 
const TeamsUrlListInput = connect(TeamsUrlListInputInternal)
 
const ConfigureMSTeamsNotifications: React.FC<ConfigureMSTeamsNotificationsProps> = props => {
  const { getString } = useStrings()
 
  const handleSubmit = (formData: MSTeamsNotificationConfiguration): void => {
    props.onSuccess(formData)
  }
 
  return (
    <div className={css.body}>
      <Layout.Vertical spacing="large">
        <Text>{getString('notifications.helpMSTeams')}</Text>
 
        <a
          href="https://ngdocs.harness.io/article/xcb28vgn82-send-notifications-to-microsoft-teams"
          rel="noreferrer"
          target="_blank"
        >
          {getString('learnMore')}
        </a>
        <Formik<MSTeamsNotificationConfiguration>
          onSubmit={handleSubmit}
          formName="configureMSTeamsNotifications"
          validationSchema={Yup.object({
            msTeamKeys: Yup.array().of(
              Yup.string()
                .url(getString('notifications.errors.invalidUrl'))
                .required(getString('notifications.errors.msTeamUrlRequired'))
            )
          })}
          initialValues={{
            msTeamKeys: [],
            userGroups: [],
            type: NotificationType.MsTeams,
            ...props.config
          }}
        >
          {formik => {
            return (
              <FormikForm>
                <TeamsUrlListInput name={'msTeamKeys'} label={getString('notifications.labelMSTeam')} />
                <Layout.Horizontal margin={{ bottom: 'xxlarge' }} style={{ alignItems: 'center' }}>
                  <TestMSTeamsNotifications data={formik.values} errors={formik.errors} />
                </Layout.Horizontal>
                <UserGroupsInput name="userGroups" label={getString('notifications.labelMSTeamsUserGroups')} />
                {props.isStep ? (
                  <Layout.Horizontal spacing="large" margin={{ bottom: 'medium' }} className={css.buttonGroupSlack}>
                    <Button
                      text={getString('back')}
                      variation={ButtonVariation.SECONDARY}
                      onClick={() => {
                        props.onBack?.(formik.values)
                      }}
                    />
                    <Button
                      text={props.submitButtonText || getString('next')}
                      variation={ButtonVariation.PRIMARY}
                      type="submit"
                    />
                  </Layout.Horizontal>
                ) : (
                  <Layout.Horizontal spacing={'medium'} margin={{ top: 'xxlarge', bottom: 'medium' }}>
                    <Button
                      type={'submit'}
                      variation={ButtonVariation.PRIMARY}
                      text={props.submitButtonText || getString('submit')}
                    />
                    <Button
                      text={getString('cancel')}
                      variation={ButtonVariation.SECONDARY}
                      onClick={props.hideModal}
                    />
                  </Layout.Horizontal>
                )}
              </FormikForm>
            )
          }}
        </Formik>
      </Layout.Vertical>
    </div>
  )
}
 
export default ConfigureMSTeamsNotifications