import axios from 'axios'; import { Field, Form, Formik } from 'formik'; import React from 'react'; import { defineMessages, useIntl } from 'react-intl'; import { useToasts } from 'react-toast-notifications'; import useSWR from 'swr'; import * as Yup from 'yup'; import globalMessages from '../../../../i18n/globalMessages'; import Alert from '../../../Common/Alert'; import Button from '../../../Common/Button'; import LoadingSpinner from '../../../Common/LoadingSpinner'; import NotificationTypeSelector from '../../../NotificationTypeSelector'; const messages = defineMessages({ agentenabled: 'Enable Agent', webhookUrl: 'Webhook URL', slacksettingssaved: 'Slack notification settings saved successfully!', slacksettingsfailed: 'Slack notification settings failed to save.', testsent: 'Slack test notification sent!', settingupslack: 'Setting Up Slack Notifications', settingupslackDescription: 'To configure Slack notifications, you will need to create an Incoming Webhook integration and enter the webhook URL below.', validationWebhookUrl: 'You must provide a valid URL', }); const NotificationsSlack: React.FC = () => { const intl = useIntl(); const { addToast } = useToasts(); const { data, error, revalidate } = useSWR( '/api/v1/settings/notifications/slack' ); const NotificationsSlackSchema = Yup.object().shape({ webhookUrl: Yup.string() .when('enabled', { is: true, then: Yup.string() .nullable() .required(intl.formatMessage(messages.validationWebhookUrl)), otherwise: Yup.string().nullable(), }) .url(intl.formatMessage(messages.validationWebhookUrl)), }); if (!data && !error) { return ; } return ( <> {intl.formatMessage(messages.settingupslackDescription, { WebhookLink: function WebhookLink(msg) { return ( {msg} ); }, })} { try { await axios.post('/api/v1/settings/notifications/slack', { enabled: values.enabled, types: values.types, options: { webhookUrl: values.webhookUrl, }, }); addToast(intl.formatMessage(messages.slacksettingssaved), { appearance: 'success', autoDismiss: true, }); } catch (e) { addToast(intl.formatMessage(messages.slacksettingsfailed), { appearance: 'error', autoDismiss: true, }); } finally { revalidate(); } }} > {({ errors, touched, isSubmitting, values, isValid, setFieldValue, }) => { const testSettings = async () => { await axios.post('/api/v1/settings/notifications/slack/test', { enabled: true, types: values.types, options: { webhookUrl: values.webhookUrl, }, }); addToast(intl.formatMessage(messages.testsent), { appearance: 'info', autoDismiss: true, }); }; return ( {intl.formatMessage(messages.agentenabled)} {intl.formatMessage(messages.webhookUrl)} * {errors.webhookUrl && touched.webhookUrl && ( {errors.webhookUrl} )} setFieldValue('types', newTypes)} /> { e.preventDefault(); testSettings(); }} > {intl.formatMessage(globalMessages.test)} {isSubmitting ? intl.formatMessage(globalMessages.saving) : intl.formatMessage(globalMessages.save)} ); }} > ); }; export default NotificationsSlack;