Skip to content

SigNoz is an open-source, OpenTelemetry-native observability platform for your team and their AI agents. Get logs, metrics, and traces in one tool with features like APM, distributed tracing, log management, infra monitoring, etc. Combined with SigNoz MCP and a native AI teammate (in SigNoz Cloud) it helps you build more resilient apps.

feat(notification-channels): move the channels UI onto the v2 API with a redesigned list (#12976)

Ashwin Bhatkaldbd456b23431
diff --git a/frontend/public/locales/en/channels.json b/frontend/public/locales/en/channels.json
index 02b050cbae..f11b166b29 100644
--- a/frontend/public/locales/en/channels.json
+++ b/frontend/public/locales/en/channels.json
@@ -8,13 +8,20 @@
"button_new_channel": "New Alert Channel",
"tooltip_notification_channels": "More details on how to setting notification channels",
"sending_channels_note": "The alerts will be sent to all the configured channels.",
+ "channel_load_failed": "This channel could not be opened",
"loading_channels_message": "Loading Channels..",
"page_title_create": "New Notification Channel",
"page_title_edit": "Edit Notification Channel",
"button_save_channel": "Save",
"button_test_channel": "Test",
"button_return": "Back",
+ "section_general": "General",
+ "section_connection": "Connection",
+ "section_message": "Message",
+ "section_advanced": "Advanced",
+ "section_recipients": "Recipients",
"field_channel_name": "Name",
+ "help_channel_name_immutable": "Renaming is blocked while alert rules and routing policies still reference a channel by name.",
"field_send_resolved": "Send resolved alerts",
"field_channel_type": "Type",
"field_webhook_url": "Webhook URL",
@@ -95,9 +102,44 @@
"placeholder_incidentio_metadata_key": "Key",
"placeholder_incidentio_metadata_value": "Value",
"button_incidentio_add_metadata": "Add metadata",
+ "button_incidentio_remove_metadata": "Remove metadata",
"field_slack_recipient": "Recipient",
"field_slack_title": "Title",
"field_slack_description": "Description",
+ "field_slack_title_link": "Title link",
+ "field_slack_color": "Color",
+ "help_slack_color": "good, warning, danger, or a hex value like #439FE0. Templates are allowed.",
+ "placeholder_slack_color": "{{ if eq .Status \"firing\" }}danger{{ else }}good{{ end }}",
+ "field_slack_pretext": "Pretext",
+ "help_slack_pretext": "Shown above the attachment block",
+ "field_slack_fallback": "Fallback text",
+ "help_slack_fallback": "Plain text shown where the attachment cannot render, such as push notifications",
+ "field_slack_footer": "Footer",
+ "field_slack_fields": "Fields",
+ "help_slack_fields": "Extra entries rendered as a table inside the attachment",
+ "placeholder_slack_field_title": "Title",
+ "placeholder_slack_field_value": "Value",
+ "field_slack_field_short": "Short",
+ "add_slack_field": "Add field",
+ "remove_slack_field": "Remove field",
+ "field_slack_actions": "Actions",
+ "help_slack_actions": "Buttons rendered under the attachment. A button with a URL links out.",
+ "label_slack_action_text": "Text",
+ "label_slack_action_url": "URL",
+ "label_slack_action_type": "Type",
+ "label_slack_action_name": "Name",
+ "label_slack_action_value": "Value",
+ "label_slack_action_style": "Style",
+ "label_slack_action_confirm": "Confirm",
+ "placeholder_slack_action_text": "Button text",
+ "placeholder_slack_action_url": "https://runbook.example.com",
+ "placeholder_slack_action_type": "button",
+ "placeholder_slack_action_name": "Name (Slack app callbacks)",
+ "placeholder_slack_action_value": "Value (Slack app callbacks)",
+ "placeholder_slack_action_style": "Style: default, primary or danger",
+ "placeholder_slack_action_confirm": "Confirmation prompt (optional)",
+ "add_slack_action": "Add action",
+ "remove_slack_action": "Remove action",
"field_opsgenie_api_key": "API Key",
"field_opsgenie_description": "Description",
"placeholder_opsgenie_description": "Description",
@@ -109,6 +151,7 @@
"placeholder_email_html": "Email body template",
"field_webhook_username": "User Name (optional)",
"field_webhook_password": "Password (optional)",
+ "field_webhook_bearer_token": "Bearer token (optional)",
"field_pager_routing_key": "Routing Key",
"field_pager_description": "Description",
"field_pager_severity": "Severity",
@@ -133,6 +176,7 @@
"help_pager_severity": "Severity of the incident, must be one of: must be one of the following: 'critical', 'warning', 'error' or 'info'",
"help_webhook_username": "Leave empty for bearer auth or when authentication is not necessary.",
"help_webhook_password": "Specify a password or bearer token",
+ "help_webhook_bearer_token": "Sent as an Authorization: Bearer header. Leave the username and password empty when using it.",
"help_pager_description": "Shows up as description in pagerduty",
"help_opsgenie_message": "Shows up as message in opsgenie",
"help_opsgenie_priority": "Priority of the incident",
@@ -148,6 +192,8 @@
"channel_test_failed": "Failed to send a test message to this channel, please confirm that the parameters are set correctly",
"channel_test_unexpected": "An unexpected error occurred while sending a message to this channel, please try again",
"webhook_url_required": "Webhook URL is mandatory",
+ "routing_key_required": "Routing Key is mandatory for creating pagerduty channel",
+ "pager_details_invalid_json": "Enter valid JSON, or clear the box to send no details",
"slack_channel_help": "Specify channel or user, use #channel-name, @username (has to be all lowercase, no whitespace)",
"api_key_required": "API Key is mandatory",
"to_required": "To field is mandatory",
diff --git a/frontend/src/components/AlertBreadcrumb/AlertBreadcrumb.module.scss b/frontend/src/components/AlertBreadcrumb/AlertBreadcrumb.module.scss
index 54a37f0742..8cf17d7961 100644
--- a/frontend/src/components/AlertBreadcrumb/AlertBreadcrumb.module.scss
+++ b/frontend/src/components/AlertBreadcrumb/AlertBreadcrumb.module.scss
@@ -1,5 +1,5 @@
.breadcrumb {
- padding-left: 16px;
+ padding: var(--spacing-4) 16px var(--spacing-2);
ol {
align-items: center;
diff --git a/frontend/src/components/AlertBreadcrumb/BreadcrumbItem.tsx b/frontend/src/components/AlertBreadcrumb/BreadcrumbItem.tsx
index 8114f8c64d..53895ac787 100644
--- a/frontend/src/components/AlertBreadcrumb/BreadcrumbItem.tsx
+++ b/frontend/src/components/AlertBreadcrumb/BreadcrumbItem.tsx
@@ -1,3 +1,4 @@
+import { ReactNode } from 'react';
import { Button } from '@signozhq/ui/button';
import { useSafeNavigate } from 'hooks/useSafeNavigate';
import { isModifierKeyPressed } from 'utils/app';
@@ -10,7 +11,7 @@ export type BreadcrumbItemConfig =
route?: string;
}
| {
- title: string | null;
+ title: ReactNode;
isLast?: true;
};
diff --git a/frontend/src/container/AllAlertChannels/__tests__/CreateAlertChannel.test.tsx b/frontend/src/container/AllAlertChannels/__tests__/CreateAlertChannel.test.tsx
deleted file mode 100644
index c9261deec9..0000000000
--- a/frontend/src/container/AllAlertChannels/__tests__/CreateAlertChannel.test.tsx
+++ /dev/null
@@ -1,914 +0,0 @@
-import CreateAlertChannels from 'container/CreateAlertChannels';
-import { ChannelType } from 'container/CreateAlertChannels/config';
-import {
- GoogleChatInitialConfig,
- IncidentIOInitialConfig,
- JiraInitialConfig,
- JsmOpsInitialConfig,
-} from 'container/CreateAlertChannels/defaults';
-import {
- googleChatDescriptionDefaultValue,
- googleChatTitleDefaultValue,
- opsGenieDescriptionDefaultValue,
- opsGenieMessageDefaultValue,
- opsGeniePriorityDefaultValue,
- pagerDutyAdditionalDetailsDefaultValue,
- pagerDutyDescriptionDefaultValue,
- pagerDutySeverityTextDefaultValue,
- slackDescriptionDefaultValue,
- slackTitleDefaultValue,
-} from 'mocks-server/__mockdata__/alerts';
-import { server } from 'mocks-server/server';
-import { rest } from 'msw';
-import {
- act,
- fireEvent,
- render,
- screen,
- userEvent,
- waitFor,
-} from 'tests/test-utils';
-
-import { testLabelInputAndHelpValue } from './testUtils';
-
-const successNotification = jest.fn();
-const errorNotification = jest.fn();
-jest.mock('hooks/useNotifications', () => ({
- __esModule: true,
- useNotifications: jest.fn(() => ({
- notifications: {
- success: successNotification,
- error: errorNotification,
- },
- })),
-}));
-const showErrorModal = jest.fn();
-jest.mock('providers/ErrorModalProvider', () => ({
- __esModule: true,
- ...jest.requireActual('providers/ErrorModalProvider'),
- useErrorModal: jest.fn(() => ({
- showErrorModal,
- })),
-}));
-
-jest.mock('components/MarkdownRenderer/MarkdownRenderer', () => ({
- MarkdownRenderer: jest.fn(() => <div>Mocked MarkdownRenderer</div>),
-}));
-
-describe('Create Alert Channel', () => {
- afterEach(() => {
- jest.clearAllMocks();
- });
- describe('Should check if the new alert channel is properly displayed with the cascading fields of slack channel', () => {
- beforeEach(() => {
- render(<CreateAlertChannels preType={ChannelType.Slack} />);
- });
- afterEach(() => {
- jest.clearAllMocks();
- });
- it('Should check if the title is "New Notification Channels"', () => {
- expect(screen.getByText('page_title_create')).toBeInTheDocument();
- });
- it('Should check if the name label and textbox are displayed properly', () => {
- testLabelInputAndHelpValue({
- labelText: 'field_channel_name',
- testId: 'channel-name-textbox',
- });
- });
- it('Should check if Send resolved alerts label and checkbox are displayed properly', () => {
- testLabelInputAndHelpValue({
- labelText: 'field_send_resolved',
- testId: 'field-send-resolved-checkbox',
- });
- });
- it('Should check if channel type label and dropdown are displayed properly', () => {
- testLabelInputAndHelpValue({
- labelText: 'field_channel_type',
- testId: 'channel-type-select',
- });
- });
- // Default Channel type (Slack) fields
- it('Should check if the selected item in the type dropdown has text "Slack"', () => {
- expect(screen.getByText('Slack')).toBeInTheDocument();
- });
- it('Should check if Webhook URL label and input are displayed properly', () => {
- testLabelInputAndHelpValue({
- labelText: 'field_webhook_url',
- testId: 'webhook-url-textbox',
- });
- });
- it('Should check if Recepient label, input, and help text are displayed properly', () => {
- testLabelInputAndHelpValue({
- labelText: 'field_slack_recipient',
- testId: 'slack-channel-textbox',
- helpText: 'slack_channel_help',
- });
- });
-
- it('Should check if Title label and text area are displayed properly', () => {
- testLabelInputAndHelpValue({
- labelText: 'field_slack_title',
- testId: 'title-textarea',
- });
- });
- it('Should check if Title contains template', () => {
- const titleTextArea = screen.getByTestId('title-textarea');
-
- expect(titleTextArea).toHaveTextContent(slackTitleDefaultValue);
- });
- it('Should check if Description label and text area are displayed properly', () => {
- testLabelInputAndHelpValue({
- labelText: 'field_slack_description',
- testId: 'description-textarea',
- });
- });
- it('Should check if Description contains template', () => {
- const descriptionTextArea = screen.getByTestId('description-textarea');
-
- expect(descriptionTextArea).toHaveTextContent(slackDescriptionDefaultValue);
- });
- it('Should check if the form buttons are displayed properly (Save, Test, Back)', () => {
- expect(screen.getByText('button_save_channel')).toBeInTheDocument();
- expect(screen.getByText('button_test_channel')).toBeInTheDocument();
- expect(screen.getByText('button_return')).toBeInTheDocument();
- });
- it('Should check if saving the form without filling the name displays error notification', async () => {
- const saveButton = screen.getByRole('button', {
- name: 'button_save_channel',
- });
-
- fireEvent.click(saveButton);
-
- await waitFor(() =>
- expect(errorNotification).toHaveBeenCalledWith({
- message: 'Error',
- description: 'channel_name_required',
- }),
- );
- });
- it('Should check if clicking on Test button shows "An alert has been sent to this channel" success message if testing passes', async () => {
- server.use(
- rest.post('http://localhost/api/v1/testChannel', (req, res, ctx) =>
- res(
- ctx.status(200),
- ctx.json({
- status: 'success',
- data: 'test alert sent',
- }),
- ),
- ),
- );
- const testButton = screen.getByRole('button', {
- name: 'button_test_channel',
- });
-
- fireEvent.click(testButton);
-
- await waitFor(() =>
- expect(successNotification).toHaveBeenCalledWith({
- message: 'Success',
- description: 'channel_test_done',
- }),
- );
- });
- it('Should check if clicking on Test button shows "Something went wrong" error message if testing fails', async () => {
- const testButton = screen.getByRole('button', {
- name: 'button_test_channel',
- });
-
- act(() => {
- fireEvent.click(testButton);
- });
-
- await waitFor(() => expect(showErrorModal).toHaveBeenCalled());
- });
- });
- describe('New Alert Channel Cascading Fields Based on Channel Type', () => {
- describe('Webhook', () => {
- beforeEach(() => {
- render(<CreateAlertChannels preType={ChannelType.Webhook} />);
- });
-
- it('Should check if the selected item in the type dropdown has text "Webhook"', () => {
- expect(screen.getByText('Webhook')).toBeInTheDocument();
- });
- it('Should check if Webhook URL label and input are displayed properly', () => {
- testLabelInputAndHelpValue({
- labelText: 'field_webhook_url',
- testId: 'webhook-url-textbox',
- });
- });
- it('Should check if Webhook User Name label, input, and help text are displayed properly', () => {
- testLabelInputAndHelpValue({
- labelText: 'field_webhook_username',
- testId: 'webhook-username-textbox',
- helpText: 'help_webhook_username',
- });
- });
- it('Should check if Password label and textbox, and help text are displayed properly', () => {
- testLabelInputAndHelpValue({
- labelText: 'Password (optional)',
- testId: 'webhook-password-textbox',
- helpText: 'help_webhook_password',
- });
- });
- });
- describe('PagerDuty', () => {
- beforeEach(() => {
- render(<CreateAlertChannels preType={ChannelType.Pagerduty} />);
- });
-
- it('Should check if the selected item in the type dropdown has text "Pagerduty"', () => {
- expect(screen.getByText('Pagerduty')).toBeInTheDocument();
- });
- it('Should check if Routing key label, required, and textbox are displayed properly', () => {
- testLabelInputAndHelpValue({
- labelText: 'field_pager_routing_key',
- testId: 'pager-routing-key-textbox',
- });
- });
- it('Should check if Description label, required, info (Shows up as description in pagerduty), and text area are displayed properly', () => {
- testLabelInputAndHelpValue({
- labelText: 'field_pager_description',
- testId: 'pager-description-textarea',
- helpText: 'help_pager_description',
- });
- });
- it('Should check if the description contains default template', () => {
- const descriptionTextArea = screen.getByTestId(
- 'pager-description-textarea',
- );
-
- expect(descriptionTextArea).toHaveTextContent(
- pagerDutyDescriptionDefaultValue,
- );
- });
- it('Should check if Severity label, info (help_pager_severity), and textbox are displayed properly', () => {
- testLabelInputAndHelpValue({
- labelText: 'field_pager_severity',
- testId: 'pager-severity-textbox',
- helpText: 'help_pager_severity',
- });
- });
- it('Should check if Severity contains the default template', () => {
- const severityTextbox = screen.getByTestId('pager-severity-textbox');
-
- expect(severityTextbox).toHaveValue(pagerDutySeverityTextDefaultValue);
- });
- it('Should check if Additional Information label, text area, and help text (help_pager_details) are displayed properly', () => {
- testLabelInputAndHelpValue({
- labelText: 'field_pager_details',
- testId: 'pager-additional-details-textarea',
- helpText: 'help_pager_details',
- });
- });
- it('Should check if Additional Information contains the default template', () => {
- const detailsTextArea = screen.getByTestId(
- 'pager-additional-details-textarea',
- );
-
- expect(detailsTextArea).toHaveValue(pagerDutyAdditionalDetailsDefaultValue);
- });
- it('Should check if Group label, text area, and info (help_pager_group) are displayed properly', () => {
- testLabelInputAndHelpValue({
- labelText: 'field_pager_group',
- testId: 'pager-group-textarea',
- helpText: 'help_pager_group',
- });
- });
- it('Should check if Class label, text area, and info (help_pager_class) are displayed properly', () => {
- testLabelInputAndHelpValue({
- labelText: 'field_pager_class',
- testId: 'pager-class-textarea',
- helpText: 'help_pager_class',
- });
- });
- it('Should check if Client label, text area, and info (Shows up as event source in Pagerduty) are displayed properly', () => {
- testLabelInputAndHelpValue({
- labelText: 'field_pager_client',
- testId: 'pager-client-textarea',
- helpText: 'help_pager_client',
- });
- });
- it('Should check if Client input contains the default value "SigNoz Alert Manager"', () => {
- const clientTextArea = screen.getByTestId('pager-client-textarea');
-
- expect(clientTextArea).toHaveValue('SigNoz Alert Manager');
- });
- it('Should check if Client URL label, text area, and info (Shows up as event source link in Pagerduty) are displayed properly', () => {
- testLabelInputAndHelpValue({
- labelText: 'field_pager_client_url',
- testId: 'pager-client-url-textarea',
- helpText: 'help_pager_client_url',
- });
- });
- it('Should check if Client URL contains the default value "https://enter-signoz-host-n-port-here/alerts"', () => {
- const clientUrlTextArea = screen.getByTestId('pager-client-url-textarea');
-
- expect(clientUrlTextArea).toHaveValue(
- 'https://enter-signoz-host-n-port-here/alerts',
- );
- });
- });
- describe('Opsgenie', () => {
- beforeEach(() => {
- render(<CreateAlertChannels preType={ChannelType.Opsgenie} />);
- });
-
- it('Should check if the selected item in the type dropdown has text "Opsgenie"', () => {
- expect(screen.getByText('Opsgenie')).toBeInTheDocument();
- });
-
- it('Should check if API key label, required, and textbox are displayed properly', () => {
- testLabelInputAndHelpValue({
- labelText: 'field_opsgenie_api_key',
- testId: 'opsgenie-api-key-textbox',
- required: true,
- });
- });
-
- it('Should check if Message label, required, info (Shows up as message in opsgenie), and text area are displayed properly', () => {
- testLabelInputAndHelpValue({
- labelText: 'field_opsgenie_message',
- testId: 'opsgenie-message-textarea',
- helpText: 'help_opsgenie_message',
- required: true,
- });
- });
-
- it('Should check if Message contains the default template', () => {
- const messageTextArea = screen.getByTestId('opsgenie-message-textarea');
-
- expect(messageTextArea).toHaveValue(opsGenieMessageDefaultValue);
- });
-
- it('Should check if Description label, required, info (Shows up as description in opsgenie), and text area are displayed properly `{{ if gt (len .Alerts.Firing) 0 -}}', () => {
- testLabelInputAndHelpValue({
- labelText: 'field_opsgenie_description',
- testId: 'opsgenie-description-textarea',
- helpText: 'help_opsgenie_description',
- required: true,
- });
- });
-
- it('Should check if Description label, required, info (Shows up as description in opsgenie), and text area are displayed properly `{{ if gt (len .Alerts.Firing) 0 -}}', () => {
- const descriptionTextArea = screen.getByTestId(
- 'opsgenie-description-textarea',
- );
-
- expect(descriptionTextArea).toHaveTextContent(
- opsGenieDescriptionDefaultValue,
- );
- });
-
- it('Should check if Priority label, required, info (help_opsgenie_priority), and text area are displayed properly', () => {
- testLabelInputAndHelpValue({
- labelText: 'field_opsgenie_priority',
- testId: 'opsgenie-priority-textarea',
- helpText: 'help_opsgenie_priority',
- required: true,
- });
- });
-
- it('Should check if Message contains the default template', () => {
- const priorityTextArea = screen.getByTestId('opsgenie-priority-textarea');
-
- expect(priorityTextArea).toHaveValue(opsGeniePriorityDefaultValue);
- });
- });
- describe('Email', () => {
- beforeEach(() => {
- render(<CreateAlertChannels preType={ChannelType.Email} />);
- });
-
- it('Should check if the selected item in the type dropdown has text "Email"', () => {
- expect(screen.getByText('Email')).toBeInTheDocument();
- });
- it('Should check if API key label, required, info(help_email_to), and textbox are displayed properly', () => {
- testLabelInputAndHelpValue({
- labelText: 'field_email_to',
- testId: 'email-to-textbox',
- helpText: 'help_email_to',
- required: true,
- });
- });
- });
- describe('Microsoft Teams', () => {
- beforeEach(() => {
- render(<CreateAlertChannels preType={ChannelType.MsTeams} />);
- });
-
- it('Should check if the selected item in the type dropdown has text "msteams"', () => {
- expect(screen.getByText('Microsoft Teams')).toBeInTheDocument();
- });
-
- it('Should check if Webhook URL label and input are displayed properly', () => {
- testLabelInputAndHelpValue({
- labelText: 'field_webhook_url',
- testId: 'webhook-url-textbox',
- });
- });
-
- it('Should check if Title label and text area are displayed properly', () => {
- testLabelInputAndHelpValue({
- labelText: 'field_slack_title',
- testId: 'title-textarea',
- });
- });
-
- it('Should check if Title contains template', () => {
- const titleTextArea = screen.getByTestId('title-textarea');
-
- expect(titleTextArea).toHaveTextContent(slackTitleDefaultValue);
- });
- it('Should check if Description label and text area are displayed properly', () => {
- testLabelInputAndHelpValue({
- labelText: 'field_slack_description',
- testId: 'description-textarea',
- });
- });
-
- it('Should check if Description contains template', () => {
- const descriptionTextArea = screen.getByTestId('description-textarea');
-
- expect(descriptionTextArea).toHaveTextContent(slackDescriptionDefaultValue);
- });
- });
- describe('Google Chat', () => {
- const validWebhookUrl =
- 'https://chat.googleapis.com/v1/spaces/AAAA/messages?key=dummy_key&token=dummy_token';
-
- beforeEach(() => {
- render(<CreateAlertChannels preType={ChannelType.GoogleChat} />);
- });
-
- // paste instead of type: a per-keystroke re-render of the whole form
- // pushes these tests past the 5s jest timeout on slower CI runners
- async function fillField(
- user: ReturnType<typeof userEvent.setup>,
- testId: string,
- value: string,
- ): Promise<void> {
- await user.click(screen.getByTestId(testId));
- await user.paste(value);
- }
-
- it('Should check if the selected item in the type dropdown has text "Google Chat"', () => {
- expect(screen.getByText('Google Chat')).toBeInTheDocument();
- });
-
- it('Should check if Webhook URL label and input are displayed properly', () => {
- testLabelInputAndHelpValue({
- labelText: 'field_webhook_url',
- testId: 'webhook-url-textbox',
- });
- });
-
- it('Should check if Title contains the google chat template', () => {
- expect(screen.getByTestId('title-textarea')).toHaveTextContent(
- googleChatTitleDefaultValue,
- );
- });
-
- it('Should check if Description contains the google chat template', () => {
- expect(screen.getByTestId('description-textarea')).toHaveTextContent(
- googleChatDescriptionDefaultValue,
- );
- });
-
- it('Should check if saving with a webhook url outside chat.googleapis.com displays error notification', async () => {
- const user = userEvent.setup();
-
- await fillField(user, 'channel-name-textbox', 'gchat-channel');
- await fillField(user, 'webhook-url-textbox', 'https://example.com/webhook');
-
- await user.click(screen.getByTestId('save-channel-button'));
-
- await waitFor(() =>
- expect(errorNotification).toHaveBeenCalledWith({
- message: 'Error',
- description: 'google_chat_webhook_url_invalid',
- }),
- );
- });
-
- it('Should check if saving sends a googlechat_configs payload', async () => {
- let requestBody: unknown;
- server.use(
- rest.post('http://localhost/api/v1/channels', async (req, res, ctx) => {
- requestBody = await req.json();
- return res(
- ctx.status(201),
- ctx.json({ status: 'success', data: 'channel created' }),
- );
- }),
- );
-
- const user = userEvent.setup();
-
- await fillField(user, 'channel-name-textbox', 'gchat-channel');
- await fillField(user, 'webhook-url-textbox', validWebhookUrl);
-
- await user.click(screen.getByTestId('save-channel-button'));
-
- await waitFor(() =>
- expect(successNotification).toHaveBeenCalledWith({
- message: 'Success',
- description: 'channel_creation_done',
- }),
- );
-
- expect(requestBody).toStrictEqual({
- name: 'gchat-channel',
- googlechat_configs: [
- {
- webhook_url: validWebhookUrl,
- title: GoogleChatInitialConfig.title,
- text: GoogleChatInitialConfig.text,
- send_resolved: true,
- },
- ],
- });
- });
- });
- describe('Jira', () => {
- const validSite = 'https://acme.atlassian.net';
-
- const fillRequired = async (
- user: ReturnType<typeof userEvent.setup>,
- site: string,
- ): Promise<void> => {
- await user.type(screen.getByTestId('channel-name-textbox'), 'jira-channel');
- await user.type(screen.getByTestId('jira-site-textbox'), site);
- await user.type(screen.getByTestId('jira-email-textbox'), '[email protected]');
- await user.type(screen.getByTestId('jira-api-token-textbox'), 'tok123');
- await user.type(screen.getByTestId('jira-project-textbox'), 'KAN');
- };
-
- beforeEach(() => {
- render(<CreateAlertChannels preType={ChannelType.Jira} />);
- });
-
- it('Should check if the selected item in the type dropdown has text "Jira"', () => {
- expect(screen.getByText('Jira')).toBeInTheDocument();
- });
-
- it('Should check if the Site URL field is displayed properly', () => {
- testLabelInputAndHelpValue({
- labelText: 'field_jira_site',
- testId: 'jira-site-textbox',
- });
- });
-
- it('Should prefill the issue type with Task', () => {
- expect(screen.getByTestId('jira-issue-type-textbox')).toHaveValue('Task');
- });
-
- it('Should show the service-account recommendation tip linking to the docs', () => {
- expect(screen.getByTestId('jira-service-account-tip')).toBeInTheDocument();
- expect(
- screen.getByRole('link', { name: 'jira_service_account_tip_link' }),
- ).toHaveAttribute(
- 'href',
- 'https://signoz.io/docs/alerts-management/notification-channel/jira/#use-a-service-account-recommended',
- );
- });
-
- it('Should display an error when the site is not an atlassian.net URL', async () => {
- const user = userEvent.setup({ delay: null });
- await fillRequired(user, 'https://example.com');
-
- await user.click(screen.getByTestId('save-channel-button'));
-
- await waitFor(() =>
- expect(errorNotification).toHaveBeenCalledWith({
- message: 'Error',
- description: 'jira_site_invalid',
- }),
- );
- }, 15000);
-
- it('Should send a jira_configs payload with basic auth', async () => {
- let requestBody: unknown;
- server.use(
- rest.post('http://localhost/api/v1/channels', async (req, res, ctx) => {
- requestBody = await req.json();
- return res(
- ctx.status(201),
- ctx.json({ status: 'success', data: 'channel created' }),
- );
- }),
- );
-
- const user = userEvent.setup({ delay: null });
- await fillRequired(user, validSite);
- await user.click(screen.getByText('jira_advanced_section'));
- await user.type(
- screen.getByTestId('jira-wont-fix-resolution-textbox'),
- "Won't Do",
- );
-
- await user.click(screen.getByTestId('save-channel-button'));
-
- await waitFor(() =>
- expect(successNotification).toHaveBeenCalledWith({
- message: 'Success',
- description: 'channel_creation_done',
- }),
- );
-
- expect(requestBody).toStrictEqual({
- name: 'jira-channel',
- jira_configs: [
- {
- site: validSite,
- project: 'KAN',
- issue_type: 'Task',
- summary: JiraInitialConfig.summary,
- description: JiraInitialConfig.description,
- send_resolved: true,
- wont_fix_resolution: "Won't Do",
- http_config: {
- basic_auth: { username: '[email protected]', password: 'tok123' },
- },
- },
- ],
- });
- }, 15000);
-
- it('Should block save when the reopen window is below the 1m minimum', async () => {
- const user = userEvent.setup({ delay: null });
- await fillRequired(user, validSite);
-
- await user.click(screen.getByText('jira_advanced_section'));
- await user.type(screen.getByTestId('jira-reopen-duration-textbox'), '30s');
-
- // the rule surfaces an inline message, not just a red border
- await expect(
- screen.findByText('jira_reopen_duration_invalid'),
- ).resolves.toBeInTheDocument();
-
- await user.click(screen.getByTestId('save-channel-button'));
-
- await waitFor(() =>
- expect(errorNotification).toHaveBeenCalledWith({
- message: 'Error',
- description: 'jira_reopen_duration_invalid',
- }),
- );
- }, 15000);
- });
- describe('JSM Ops', () => {
- beforeEach(() => {
- render(<CreateAlertChannels preType={ChannelType.JsmOps} />);
- });
-
- it('Should show "Jira Service Management Ops" as the selected type', () => {
- expect(screen.getByText('Jira Service Management Ops')).toBeInTheDocument();
- });
-
- it('Should display the API key field properly', () => {
- testLabelInputAndHelpValue({
- labelText: 'field_jsmops_api_key',
- testId: 'jsmops-api-key-textbox',
- });
- });
-
- it('Should show the tip linking to the JSM Ops docs', () => {
- expect(screen.getByTestId('jsmops-tip')).toBeInTheDocument();
- expect(
- screen.getByRole('link', { name: 'jsmops_tip_link' }),
- ).toHaveAttribute(
- 'href',
- 'https://signoz.io/docs/alerts-management/notification-channel/jsm-ops/',
- );
- });
-
- it('Should block save when the API key is missing', async () => {
- const user = userEvent.setup();
- await user.type(
- screen.getByTestId('channel-name-textbox'),
- 'jsmops-channel',
- );
-
- await user.click(screen.getByTestId('save-channel-button'));
-
- await waitFor(() =>
- expect(errorNotification).toHaveBeenCalledWith({
- message: 'Error',
- description: 'api_key_required',
- }),
- );
- });
-
- it('Should send a jsmops_configs payload with prefilled defaults', async () => {
- let requestBody: unknown;
- server.use(
- rest.post('http://localhost/api/v1/channels', async (req, res, ctx) => {
- requestBody = await req.json();
- return res(
- ctx.status(201),
- ctx.json({ status: 'success', data: 'channel created' }),
- );
- }),
- );
-
- const user = userEvent.setup();
- await user.type(
- screen.getByTestId('channel-name-textbox'),
- 'jsmops-channel',
- );
- await user.type(screen.getByTestId('jsmops-api-key-textbox'), 'key-abc');
-
- await user.click(screen.getByTestId('save-channel-button'));
-
- await waitFor(() =>
- expect(successNotification).toHaveBeenCalledWith({
- message: 'Success',
- description: 'channel_creation_done',
- }),
- );
-
- expect(requestBody).toStrictEqual({
- name: 'jsmops-channel',
- jsmops_configs: [
- {
- api_key: 'key-abc',
- send_resolved: true,
- message: JsmOpsInitialConfig.message,
- description: JsmOpsInitialConfig.description,
- priority: JsmOpsInitialConfig.priority,
- tags: JsmOpsInitialConfig.tags?.join(','),
- },
- ],
- });
- });
- });
- describe('incident.io', () => {
- const incidentIOURL =
- 'https://api.incident.io/v2/alert_events/http/01M0D1JNVBGBGVTWX053EM12XV';
-
- beforeEach(() => {
- render(<CreateAlertChannels preType={ChannelType.IncidentIO} />);
- });
-
- it('Should display the URL and token fields with the docs tip', () => {
- testLabelInputAndHelpValue({
- labelText: 'field_incidentio_url',
- testId: 'incidentio-url-textbox',
- });
- testLabelInputAndHelpValue({
- labelText: 'field_incidentio_token',
- testId: 'incidentio-token-textbox',
- });
- expect(screen.getByTestId('incidentio-tip')).toBeInTheDocument();
- expect(
- screen.getByRole('link', { name: 'incidentio_tip_link' }),
- ).toHaveAttribute(
- 'href',
- 'https://signoz.io/docs/alerts-management/notification-channel/incidentio/',
- );
- });
-
- it('Should block save when the URL or token is missing', async () => {
- const user = userEvent.setup();
- await user.type(
- screen.getByTestId('channel-name-textbox'),
- 'incidentio-channel',
- );
-
- await user.click(screen.getByTestId('save-channel-button'));
-
- await waitFor(() =>
- expect(errorNotification).toHaveBeenCalledWith({
- message: 'Error',
- description: 'incidentio_required_fields',
- }),
- );
- });
-
- it('Should display an error when the URL is not an alert events URL', async () => {
- const user = userEvent.setup();
- await user.type(
- screen.getByTestId('channel-name-textbox'),
- 'incidentio-channel',
- );
- await user.type(
- screen.getByTestId('incidentio-url-textbox'),
- 'https://api.incident.io/v2/incidents',
- );
- await user.type(screen.getByTestId('incidentio-token-textbox'), 'tok-abc');
-
- await user.click(screen.getByTestId('save-channel-button'));
-
- await waitFor(() =>
- expect(errorNotification).toHaveBeenCalledWith({
- message: 'Error',
- description: 'incidentio_url_invalid',
- }),
- );
- }, 15000);
-
- it('Should send an incidentio_configs payload with prefilled defaults', async () => {
- let requestBody: unknown;
- server.use(
- rest.post('http://localhost/api/v1/channels', async (req, res, ctx) => {
- requestBody = await req.json();
- return res(
- ctx.status(201),
- ctx.json({ status: 'success', data: 'channel created' }),
- );
- }),
- );
-
- const user = userEvent.setup();
- await user.type(
- screen.getByTestId('channel-name-textbox'),
- 'incidentio-channel',
- );
- await user.type(
- screen.getByTestId('incidentio-url-textbox'),
- incidentIOURL,
- );
- await user.type(screen.getByTestId('incidentio-token-textbox'), 'tok-abc');
-
- await user.click(screen.getByTestId('incidentio-metadata-add'));
- await user.type(screen.getByTestId('incidentio-metadata-key-0'), 'team');
- await user.type(screen.getByTestId('incidentio-metadata-value-0'), 'core');
-
- await user.click(screen.getByTestId('save-channel-button'));
-
- await waitFor(() =>
- expect(successNotification).toHaveBeenCalledWith({
- message: 'Success',
- description: 'channel_creation_done',
- }),
- );
-
- expect(requestBody).toStrictEqual({
- name: 'incidentio-channel',
- incidentio_configs: [
- {
- url: incidentIOURL,
- token: 'tok-abc',
- send_resolved: true,
- title: IncidentIOInitialConfig.title,
- description: IncidentIOInitialConfig.description,
- metadata: { team: 'core' },
- },
- ],
- });
- }, 15000);
- });
- describe('Changing the channel type', () => {
- async function selectType(
- user: ReturnType<typeof userEvent.setup>,
- optionText: string,
- ): Promise<void> {
- // the type dropdown opens on the inner search input of the antd select
- await user.click(screen.getByRole('combobox'));
- await user.click(await screen.findByTitle(optionText));
- }
-
- it('Should check if switching to Google Chat and back swaps the prefilled templates', async () => {
- const user = userEvent.setup();
- render(<CreateAlertChannels preType={ChannelType.Slack} />);
-
- await selectType(user, 'Google Chat');
-
- await waitFor(() =>
- expect(screen.getByTestId('title-textarea')).toHaveTextContent(
- googleChatTitleDefaultValue,
- ),
- );
- expect(screen.getByTestId('description-textarea')).toHaveTextContent(
- googleChatDescriptionDefaultValue,
- );
-
- await selectType(user, 'Slack');
-
- await waitFor(() =>
- expect(screen.getByTestId('title-textarea')).toHaveTextContent(
- slackTitleDefaultValue,
- ),
- );
- expect(screen.getByTestId('description-textarea')).toHaveTextContent(
- slackDescriptionDefaultValue,
- );
- });
-
- it('Should check if switching to Pagerduty prefills the pagerduty description and not the opsgenie one', async () => {
- const user = userEvent.setup();
- render(<CreateAlertChannels preType={ChannelType.Opsgenie} />);
-
- await selectType(user, 'Pagerduty');
-
- await waitFor(() =>
- expect(screen.getByTestId('pager-description-textarea')).toHaveTextContent(
- pagerDutyDescriptionDefaultValue,
- ),
- );
- });
- });
- });
-});
diff --git a/frontend/src/container/AllAlertChannels/__tests__/CreateAlertChannelNormalUser.test.tsx b/frontend/src/container/AllAlertChannels/__tests__/CreateAlertChannelNormalUser.test.tsx
deleted file mode 100644
index 119c75f8da..0000000000
--- a/frontend/src/container/AllAlertChannels/__tests__/CreateAlertChannelNormalUser.test.tsx
+++ /dev/null
@@ -1,336 +0,0 @@
-import CreateAlertChannels from 'container/CreateAlertChannels';
-import { ChannelType } from 'container/CreateAlertChannels/config';
-import {
- opsGenieDescriptionDefaultValue,
- opsGenieMessageDefaultValue,
- opsGeniePriorityDefaultValue,
- pagerDutyAdditionalDetailsDefaultValue,
- pagerDutyDescriptionDefaultValue,
- pagerDutySeverityTextDefaultValue,
- slackDescriptionDefaultValue,
- slackTitleDefaultValue,
-} from 'mocks-server/__mockdata__/alerts';
-import { render, screen } from 'tests/test-utils';
-
-import { testLabelInputAndHelpValue } from './testUtils';
-
-jest.mock('components/MarkdownRenderer/MarkdownRenderer', () => ({
- MarkdownRenderer: jest.fn(() => <div>Mocked MarkdownRenderer</div>),
-}));
-
-describe('Create Alert Channel (Normal User)', () => {
- afterEach(() => {
- jest.clearAllMocks();
- });
- describe('Should check if the new alert channel is properly displayed with the cascading fields of slack channel', () => {
- beforeEach(() => {
- render(<CreateAlertChannels preType={ChannelType.Slack} />);
- });
- it('Should check if the title is "New Notification Channels"', () => {
- expect(screen.getByText('page_title_create')).toBeInTheDocument();
- });
- it('Should check if the name label and textbox are displayed properly', () => {
- testLabelInputAndHelpValue({
- labelText: 'field_channel_name',
- testId: 'channel-name-textbox',
- });
- });
- it('Should check if Send resolved alerts label and checkbox are displayed properly', () => {
- testLabelInputAndHelpValue({
- labelText: 'field_send_resolved',
- testId: 'field-send-resolved-checkbox',
- });
- });
- it('Should check if channel type label and dropdown are displayed properly', () => {
- testLabelInputAndHelpValue({
- labelText: 'field_channel_type',
- testId: 'channel-type-select',
- });
- });
- // Default Channel type (Slack) fields
- it('Should check if the selected item in the type dropdown has text "Slack"', () => {
- expect(screen.getByText('Slack')).toBeInTheDocument();
- });
- it('Should check if Webhook URL label and input are displayed properly', () => {
- testLabelInputAndHelpValue({
- labelText: 'field_webhook_url',
- testId: 'webhook-url-textbox',
- });
- });
- it('Should check if Recepient label, input, and help text are displayed properly', () => {
- testLabelInputAndHelpValue({
- labelText: 'field_slack_recipient',
- testId: 'slack-channel-textbox',
- helpText: 'slack_channel_help',
- });
- });
-
- it('Should check if Title label and text area are displayed properly', () => {
- testLabelInputAndHelpValue({
- labelText: 'field_slack_title',
- testId: 'title-textarea',
- });
- });
- it('Should check if Title contains template', () => {
- const titleTextArea = screen.getByTestId('title-textarea');
-
- expect(titleTextArea).toHaveTextContent(slackTitleDefaultValue);
- });
- it('Should check if Description label and text area are displayed properly', () => {
- testLabelInputAndHelpValue({
- labelText: 'field_slack_description',
- testId: 'description-textarea',
- });
- });
- it('Should check if Description contains template', () => {
- const descriptionTextArea = screen.getByTestId('description-textarea');
-
- expect(descriptionTextArea).toHaveTextContent(slackDescriptionDefaultValue);
- });
- it('Should check if the form buttons are displayed properly (Save, Test, Back)', () => {
- expect(screen.getByText('button_save_channel')).toBeInTheDocument();
- expect(screen.getByText('button_test_channel')).toBeInTheDocument();
- expect(screen.getByText('button_return')).toBeInTheDocument();
- });
- });
- describe('New Alert Channel Cascading Fields Based on Channel Type', () => {
- describe('Webhook', () => {
- beforeEach(() => {
- render(<CreateAlertChannels preType={ChannelType.Webhook} />);
- });
-
- it('Should check if the selected item in the type dropdown has text "Webhook"', () => {
- expect(screen.getByText('Webhook')).toBeInTheDocument();
- });
- it('Should check if Webhook URL label and input are displayed properly', () => {
- testLabelInputAndHelpValue({
- labelText: 'field_webhook_url',
- testId: 'webhook-url-textbox',
- });
- });
- it('Should check if Webhook User Name label, input, and help text are displayed properly', () => {
- testLabelInputAndHelpValue({
- labelText: 'field_webhook_username',
- testId: 'webhook-username-textbox',
- helpText: 'help_webhook_username',
- });
- });
- it('Should check if Password label and textbox, and help text are displayed properly', () => {
- testLabelInputAndHelpValue({
- labelText: 'Password (optional)',
- testId: 'webhook-password-textbox',
- helpText: 'help_webhook_password',
- });
- });
- });
- describe('PagerDuty', () => {
- beforeEach(() => {
- render(<CreateAlertChannels preType={ChannelType.Pagerduty} />);
- });
-
- it('Should check if the selected item in the type dropdown has text "Pagerduty"', () => {
- expect(screen.getByText('Pagerduty')).toBeInTheDocument();
- });
- it('Should check if Routing key label, required, and textbox are displayed properly', () => {
- testLabelInputAndHelpValue({
- labelText: 'field_pager_routing_key',
- testId: 'pager-routing-key-textbox',
- });
- });
- it('Should check if Description label, required, info (Shows up as description in pagerduty), and text area are displayed properly', () => {
- testLabelInputAndHelpValue({
- labelText: 'field_pager_description',
- testId: 'pager-description-textarea',
- helpText: 'help_pager_description',
- });
- });
- it('Should check if the description contains default template', () => {
- const descriptionTextArea = screen.getByTestId(
- 'pager-description-textarea',
- );
-
- expect(descriptionTextArea).toHaveTextContent(
- pagerDutyDescriptionDefaultValue,
- );
- });
- it('Should check if Severity label, info (help_pager_severity), and textbox are displayed properly', () => {
- testLabelInputAndHelpValue({
- labelText: 'field_pager_severity',
- testId: 'pager-severity-textbox',
- helpText: 'help_pager_severity',
- });
- });
- it('Should check if Severity contains the default template', () => {
- const severityTextbox = screen.getByTestId('pager-severity-textbox');
-
- expect(severityTextbox).toHaveValue(pagerDutySeverityTextDefaultValue);
- });
- it('Should check if Additional Information label, text area, and help text (help_pager_details) are displayed properly', () => {
- testLabelInputAndHelpValue({
- labelText: 'field_pager_details',
- testId: 'pager-additional-details-textarea',
- helpText: 'help_pager_details',
- });
- });
- it('Should check if Additional Information contains the default template', () => {
- const detailsTextArea = screen.getByTestId(
- 'pager-additional-details-textarea',
- );
-
- expect(detailsTextArea).toHaveValue(pagerDutyAdditionalDetailsDefaultValue);
- });
- it('Should check if Group label, text area, and info (help_pager_group) are displayed properly', () => {
- testLabelInputAndHelpValue({
- labelText: 'field_pager_group',
- testId: 'pager-group-textarea',
- helpText: 'help_pager_group',
- });
- });
- it('Should check if Class label, text area, and info (help_pager_class) are displayed properly', () => {
- testLabelInputAndHelpValue({
- labelText: 'field_pager_class',
- testId: 'pager-class-textarea',
- helpText: 'help_pager_class',
- });
- });
- it('Should check if Client label, text area, and info (Shows up as event source in Pagerduty) are displayed properly', () => {
- testLabelInputAndHelpValue({
- labelText: 'field_pager_client',
- testId: 'pager-client-textarea',
- helpText: 'help_pager_client',
- });
- });
- it('Should check if Client input contains the default value "SigNoz Alert Manager"', () => {
- const clientTextArea = screen.getByTestId('pager-client-textarea');
-
- expect(clientTextArea).toHaveValue('SigNoz Alert Manager');
- });
- it('Should check if Client URL label, text area, and info (Shows up as event source link in Pagerduty) are displayed properly', () => {
- testLabelInputAndHelpValue({
- labelText: 'field_pager_client_url',
- testId: 'pager-client-url-textarea',
- helpText: 'help_pager_client_url',
- });
- });
- it('Should check if Client URL contains the default value "https://enter-signoz-host-n-port-here/alerts"', () => {
- const clientUrlTextArea = screen.getByTestId('pager-client-url-textarea');
-
- expect(clientUrlTextArea).toHaveValue(
- 'https://enter-signoz-host-n-port-here/alerts',
- );
- });
- });
- describe('Opsgenie', () => {
- beforeEach(() => {
- render(<CreateAlertChannels preType={ChannelType.Opsgenie} />);
- });
-
- it('Should check if the selected item in the type dropdown has text "Opsgenie"', () => {
- expect(screen.getByText('Opsgenie')).toBeInTheDocument();
- });
-
- it('Should check if API key label, required, and textbox are displayed properly', () => {
- testLabelInputAndHelpValue({
- labelText: 'field_opsgenie_api_key',
- testId: 'opsgenie-api-key-textbox',
- required: true,
- });
- });
-
- it('Should check if Message label, required, info (Shows up as message in opsgenie), and text area are displayed properly', () => {
- testLabelInputAndHelpValue({
- labelText: 'field_opsgenie_message',
- testId: 'opsgenie-message-textarea',
- helpText: 'help_opsgenie_message',
- required: true,
- });
- });
-
- it('Should check if Message contains the default template', () => {
- const messageTextArea = screen.getByTestId('opsgenie-message-textarea');
-
- expect(messageTextArea).toHaveValue(opsGenieMessageDefaultValue);
- });
-
- it('Should check if Description label, required, info (Shows up as description in opsgenie), and text area are displayed properly `{{ if gt (len .Alerts.Firing) 0 -}}', () => {
- testLabelInputAndHelpValue({
- labelText: 'field_opsgenie_description',
- testId: 'opsgenie-description-textarea',
- helpText: 'help_opsgenie_description',
- required: true,
- });
- });
-
- it('Should check if Description label, required, info (Shows up as description in opsgenie), and text area are displayed properly `{{ if gt (len .Alerts.Firing) 0 -}}', () => {
- const descriptionTextArea = screen.getByTestId(
- 'opsgenie-description-textarea',
- );
-
- expect(descriptionTextArea).toHaveTextContent(
- opsGenieDescriptionDefaultValue,
- );
- });
-
- it('Should check if Priority label, required, info (help_opsgenie_priority), and text area are displayed properly', () => {
- testLabelInputAndHelpValue({
- labelText: 'field_opsgenie_priority',
- testId: 'opsgenie-priority-textarea',
- helpText: 'help_opsgenie_priority',
- required: true,
- });
- });
-
- it('Should check if Message contains the default template', () => {
- const priorityTextArea = screen.getByTestId('opsgenie-priority-textarea');
-
- expect(priorityTextArea).toHaveValue(opsGeniePriorityDefaultValue);
- });
- });
- describe('Email', () => {
- beforeEach(() => {
- render(<CreateAlertChannels preType={ChannelType.Email} />);
- });
-
- it('Should check if the selected item in the type dropdown has text "Email"', () => {
- expect(screen.getByText('Email')).toBeInTheDocument();
- });
- it('Should check if API key label, required, info(help_email_to), and textbox are displayed properly', () => {
- testLabelInputAndHelpValue({
- labelText: 'field_email_to',
- testId: 'email-to-textbox',
- helpText: 'help_email_to',
- required: true,
- });
- });
- });
- describe('Microsoft Teams', () => {
- beforeEach(() => {
- render(<CreateAlertChannels preType={ChannelType.MsTeams} />);
- });
-
- it('Should check if the selected item in the type dropdown has text "Microsoft Teams"', () => {
- expect(screen.getByText('Microsoft Teams')).toBeInTheDocument();
- });
-
- it('Should check if the form buttons are displayed properly (Save, Test, Back)', () => {
- expect(
- screen.getByRole('button', { name: 'button_save_channel' }),
- ).toBeInTheDocument();
- expect(
- screen.getByRole('button', { name: 'button_test_channel' }),
- ).toBeInTheDocument();
- expect(
- screen.getByRole('button', { name: 'button_return' }),
- ).toBeInTheDocument();
- });
- it.skip('Should check if save and test buttons are disabled', () => {
- expect(
- screen.getByRole('button', { name: 'button_save_channel' }),
- ).toBeDisabled();
- expect(
- screen.getByRole('button', { name: 'button_test_channel' }),
- ).toBeDisabled();
- });
- });
- });
-});
diff --git a/frontend/src/container/AllAlertChannels/__tests__/EditAlertChannel.test.tsx b/frontend/src/container/AllAlertChannels/__tests__/EditAlertChannel.test.tsx
deleted file mode 100644
index fc2fd8f785..0000000000
--- a/frontend/src/container/AllAlertChannels/__tests__/EditAlertChannel.test.tsx
+++ /dev/null
@@ -1,120 +0,0 @@
-import EditAlertChannels from 'container/EditAlertChannels';
-import {
- editAlertChannelInitialValue,
- editSlackDescriptionDefaultValue,
- slackTitleDefaultValue,
-} from 'mocks-server/__mockdata__/alerts';
-import { render, screen } from 'tests/test-utils';
-
-import { testLabelInputAndHelpValue } from './testUtils';
-
-const successNotification = jest.fn();
-const errorNotification = jest.fn();
-jest.mock('hooks/useNotifications', () => ({
- __esModule: true,
- useNotifications: jest.fn(() => ({
- notifications: {
- success: successNotification,
- error: errorNotification,
- },
- })),
-}));
-
-jest.mock('components/MarkdownRenderer/MarkdownRenderer', () => ({
- MarkdownRenderer: jest.fn(() => <div>Mocked MarkdownRenderer</div>),
-}));
-
-describe('Should check if the edit alert channel is properly displayed', () => {
- beforeEach(() => {
- render(
- <EditAlertChannels
- channelId="3"
- initialValue={editAlertChannelInitialValue}
- />,
- );
- });
- afterEach(() => {
- jest.clearAllMocks();
- });
- it('Should check if the title is "Edit Notification Channels"', () => {
- expect(screen.getByText('page_title_edit')).toBeInTheDocument();
- });
-
- it('Should check if the name label and textbox are displayed properly', () => {
- testLabelInputAndHelpValue({
- labelText: 'field_channel_name',
- testId: 'channel-name-textbox',
- value: 'Dummy-Channel',
- });
- });
- it('Should check if Send resolved alerts label and checkbox are displayed properly and the checkbox is checked', () => {
- testLabelInputAndHelpValue({
- labelText: 'field_send_resolved',
- testId: 'field-send-resolved-checkbox',
- });
- expect(screen.getByTestId('field-send-resolved-checkbox')).toBeChecked();
- });
-
- it('Should check if channel type label and dropdown are displayed properly', () => {
- testLabelInputAndHelpValue({
- labelText: 'field_channel_type',
- testId: 'channel-type-select',
- });
- });
-
- it('Should check if the selected item in the type dropdown has text "Slack"', () => {
- expect(screen.getByText('Slack')).toBeInTheDocument();
- });
-
- it('Should check if Webhook URL label and input are displayed properly', () => {
- testLabelInputAndHelpValue({
- labelText: 'field_webhook_url',
- testId: 'webhook-url-textbox',
- value:
- 'https://discord.com/api/webhooks/dummy_webhook_id/dummy_webhook_token/slack',
- });
- });
-
- it('Should check if Recepient label, input, and help text are displayed properly', () => {
- testLabelInputAndHelpValue({
- labelText: 'field_slack_recipient',
- testId: 'slack-channel-textbox',
- helpText: 'slack_channel_help',
- value: '#dummy_channel',
- });
- });
-
- it('Should check if Title label and text area are displayed properly', () => {
- testLabelInputAndHelpValue({
- labelText: 'field_slack_title',
- testId: 'title-textarea',
- });
- });
-
- it('Should check if Title contains template', () => {
- const titleTextArea = screen.getByTestId('title-textarea');
-
- expect(titleTextArea).toHaveTextContent(slackTitleDefaultValue);
- });
-
- it('Should check if Description label and text area are displayed properly', () => {
- testLabelInputAndHelpValue({
- labelText: 'field_slack_description',
- testId: 'description-textarea',
- });
- });
-
- it('Should check if Description contains template', () => {
- const descriptionTextArea = screen.getByTestId('description-textarea');
-
- expect(descriptionTextArea).toHaveTextContent(
- editSlackDescriptionDefaultValue,
- );
- });
-
- it('Should check if the form buttons are displayed properly (Save, Test, Back)', () => {
- expect(screen.getByText('button_save_channel')).toBeInTheDocument();
- expect(screen.getByText('button_test_channel')).toBeInTheDocument();
- expect(screen.getByText('button_return')).toBeInTheDocument();
- });
-});
diff --git a/frontend/src/container/AllAlertChannels/__tests__/EditAlertChannelSave.test.tsx b/frontend/src/container/AllAlertChannels/__tests__/EditAlertChannelSave.test.tsx
deleted file mode 100644
index 87e2d17394..0000000000
--- a/frontend/src/container/AllAlertChannels/__tests__/EditAlertChannelSave.test.tsx
+++ /dev/null
@@ -1,186 +0,0 @@
-import EditAlertChannels from 'container/EditAlertChannels';
-import { editAlertChannelInitialValue } from 'mocks-server/__mockdata__/alerts';
-import { server } from 'mocks-server/server';
-import { rest } from 'msw';
-import { render, screen, userEvent, waitFor } from 'tests/test-utils';
-
-jest.mock('hooks/useNotifications', () => ({
- __esModule: true,
- useNotifications: jest.fn(() => ({
- notifications: { success: jest.fn(), error: jest.fn() },
- })),
-}));
-
-jest.mock('components/MarkdownRenderer/MarkdownRenderer', () => ({
- MarkdownRenderer: jest.fn(() => <div>Mocked MarkdownRenderer</div>),
-}));
-
-interface EditRequest {
- id: string;
- body: { name: string; slack_configs: { send_resolved: boolean }[] };
-}
-
-// Captures the PUT /channels/:id request the edit form fires, so assertions can
-// run against the real HTTP payload instead of a hand-mocked api client.
-function mockEditChannel(): { calls: EditRequest[] } {
- const result: { calls: EditRequest[] } = { calls: [] };
- server.use(
- rest.put('http://localhost/api/v1/channels/:id', async (req, res, ctx) => {
- result.calls.push({
- id: req.params.id as string,
- body: await req.json(),
- });
- return res(
- ctx.status(200),
- ctx.json({ status: 'success', data: 'channel updated' }),
- );
- }),
- );
- return result;
-}
-
-describe('EditAlertChannels save', () => {
- afterEach(() => jest.clearAllMocks());
-
- it('sends the channelId in the edit request (regression: empty id)', async () => {
- const edit = mockEditChannel();
- render(
- <EditAlertChannels
- channelId="3"
- initialValue={editAlertChannelInitialValue}
- />,
- );
-
- const user = userEvent.setup();
- await user.click(screen.getByTestId('save-channel-button'));
-
- await waitFor(() => expect(edit.calls).toHaveLength(1));
- expect(edit.calls[0].id).toBe('3');
- });
-
- it('blocks jira save when the reopen window is below the 1m minimum', async () => {
- const edit = mockEditChannel();
- const jiraInitialValue = {
- type: 'jira',
- name: 'jira-channel',
- site: 'https://acme.atlassian.net',
- username: '[email protected]',
- password: 'token',
- project: 'OPS',
- issue_type: 'Task',
- send_resolved: true,
- reopen_duration: '30s',
- };
-
- const { unmount } = render(
- <EditAlertChannels channelId="3" initialValue={jiraInitialValue} />,
- );
- const user = userEvent.setup();
- await user.click(screen.getByTestId('save-channel-button'));
- expect(edit.calls).toHaveLength(0);
- unmount();
-
- render(
- <EditAlertChannels
- channelId="3"
- initialValue={{ ...jiraInitialValue, reopen_duration: '72h' }}
- />,
- );
- await user.click(screen.getByTestId('save-channel-button'));
- await waitFor(() => expect(edit.calls).toHaveLength(1));
- });
-
- it('preserves the jira wont-fix resolution on save', async () => {
- const edit = mockEditChannel();
- render(
- <EditAlertChannels
- channelId="3"
- initialValue={{
- type: 'jira',
- name: 'jira-channel',
- site: 'https://acme.atlassian.net',
- username: '[email protected]',
- password: 'token',
- project: 'OPS',
- issue_type: 'Task',
- send_resolved: true,
- wont_fix_resolution: "Won't Do",
- }}
- />,
- );
- const user = userEvent.setup();
- await user.click(screen.getByTestId('save-channel-button'));
-
- await waitFor(() => expect(edit.calls).toHaveLength(1));
- expect(edit.calls[0].body).toStrictEqual({
- name: 'jira-channel',
- jira_configs: [
- {
- site: 'https://acme.atlassian.net',
- project: 'OPS',
- issue_type: 'Task',
- send_resolved: true,
- wont_fix_resolution: "Won't Do",
- http_config: {
- basic_auth: { username: '[email protected]', password: 'token' },
- },
- },
- ],
- });
- });
-
- it('sends an incidentio_configs payload when editing an incident.io channel', async () => {
- const edit = mockEditChannel();
- render(
- <EditAlertChannels
- channelId="4"
- initialValue={{
- type: 'incidentio',
- name: 'incidentio-channel',
- url: 'https://api.incident.io/v2/alert_events/http/01M0D1JNVBGBGVTWX053EM12XV',
- token: 'tok-abc',
- send_resolved: true,
- metadata: { env: 'prod' },
- }}
- />,
- );
-
- const user = userEvent.setup();
- await user.click(screen.getByTestId('save-channel-button'));
-
- await waitFor(() => expect(edit.calls).toHaveLength(1));
- expect(edit.calls[0].id).toBe('4');
- expect(edit.calls[0].body).toStrictEqual({
- name: 'incidentio-channel',
- incidentio_configs: [
- {
- url: 'https://api.incident.io/v2/alert_events/http/01M0D1JNVBGBGVTWX053EM12XV',
- token: 'tok-abc',
- send_resolved: true,
- metadata: { env: 'prod' },
- },
- ],
- });
- });
-
- it('persists send_resolved toggle in the edit request', async () => {
- const edit = mockEditChannel();
- render(
- <EditAlertChannels
- channelId="3"
- initialValue={editAlertChannelInitialValue}
- />,
- );
-
- const user = userEvent.setup();
- const sendResolved = screen.getByTestId('field-send-resolved-checkbox');
- expect(sendResolved).toBeChecked();
-
- await user.click(sendResolved);
- await user.click(screen.getByTestId('save-channel-button'));
-
- await waitFor(() => expect(edit.calls).toHaveLength(1));
- expect(edit.calls[0].id).toBe('3');
- expect(edit.calls[0].body.slack_configs[0].send_resolved).toBe(false);
- });
-});
diff --git a/frontend/src/container/AllAlertChannels/__tests__/testUtils.ts b/frontend/src/container/AllAlertChannels/__tests__/testUtils.ts
deleted file mode 100644
index bae773f2fb..0000000000
--- a/frontend/src/container/AllAlertChannels/__tests__/testUtils.ts
+++ /dev/null
@@ -1,31 +0,0 @@
-import { screen } from 'tests/test-utils';
-
-export const testLabelInputAndHelpValue = ({
- labelText,
- testId,
- helpText,
- required = false,
- value,
-}: {
- labelText: string;
- testId: string;
- helpText?: string;
- required?: boolean;
- value?: string;
-}): void => {
- const label = screen.getByText(labelText);
- expect(label).toBeInTheDocument();
-
- const input = screen.getByTestId(testId);
- expect(input).toBeInTheDocument();
-
- if (helpText !== undefined) {
- expect(screen.getByText(helpText)).toBeInTheDocument();
- }
- if (required) {
- expect(input).toBeRequired();
- }
- if (value) {
- expect(input).toHaveValue(value);
- }
-};
diff --git a/frontend/src/container/CreateAlertChannels/CreateAlertChannels.styles.scss b/frontend/src/container/CreateAlertChannels/CreateAlertChannels.styles.scss
deleted file mode 100644
index 4fa4f30dcd..0000000000
--- a/frontend/src/container/CreateAlertChannels/CreateAlertChannels.styles.scss
+++ /dev/null
@@ -1,13 +0,0 @@
-.create-alert-channels-container {
- width: 100%;
- border: 1px solid var(--l1-border);
- background: var(--l2-background);
- border-radius: 3px;
-
- padding: 16px;
-
- .form-alert-channels-title {
- margin-top: 0px;
- margin-bottom: 16px;
- }
-}
diff --git a/frontend/src/container/CreateAlertChannels/channelConfig.test.ts b/frontend/src/container/CreateAlertChannels/channelConfig.test.ts
new file mode 100644
index 0000000000..230f835e86
--- /dev/null
+++ b/frontend/src/container/CreateAlertChannels/channelConfig.test.ts
@@ -0,0 +1,147 @@
+import { AlertmanagertypesGettableNotificationChannelDTO } from 'api/generated/services/sigNoz.schemas';
+
+import { toChannelConfig, toPostableChannel } from './channelConfig';
+import { toChannelFormState } from './channelFormValues';
+import { ChannelFormValues, ChannelKind } from './types';
+
+const slackValues: ChannelFormValues = {
+ name: 'prod alerts',
+ apiUrl: 'https://hooks.slack.com/services/T/B/X',
+ channel: '#alerts',
+ title: 'title template',
+ titleLink: 'https://signoz.io',
+ text: 'body template',
+ pretext: 'pretext',
+ fallback: 'fallback',
+ footer: 'footer',
+ color: 'danger',
+ fields: [{ title: 'env', value: 'prod', short: true }],
+ actions: [{ type: 'button', text: 'Runbook', url: 'https://runbook' }],
+ sendResolved: true,
+};
+
+describe('toChannelConfig', () => {
+ it('sends every field the slack spec models, new ones included', () => {
+ expect(toChannelConfig(ChannelKind.slack, slackValues)).toStrictEqual({
+ kind: 'slack',
+ spec: {
+ apiUrl: 'https://hooks.slack.com/services/T/B/X',
+ channel: '#alerts',
+ title: 'title template',
+ titleLink: 'https://signoz.io',
+ text: 'body template',
+ pretext: 'pretext',
+ fallback: 'fallback',
+ footer: 'footer',
+ color: 'danger',
+ fields: [{ title: 'env', value: 'prod', short: true }],
+ actions: [{ type: 'button', text: 'Runbook', url: 'https://runbook' }],
+ sendResolved: true,
+ },
+ });
+ });
+
+ it('drops what a user left blank but keeps a false they chose', () => {
+ expect(
+ toChannelConfig(ChannelKind.webhook, {
+ url: 'https://example.com/hook',
+ username: '',
+ password: undefined,
+ bearerToken: '',
+ sendResolved: false,
+ }),
+ ).toStrictEqual({
+ kind: 'webhook',
+ spec: { url: 'https://example.com/hook', sendResolved: false },
+ });
+ });
+
+ it('drops an attachment list the user emptied instead of sending []', () => {
+ expect(
+ toChannelConfig(ChannelKind.slack, {
+ ...slackValues,
+ fields: [],
+ actions: [],
+ }).spec,
+ ).not.toHaveProperty('fields');
+ });
+
+ it.each(Object.values(ChannelKind))('stamps the config as %s', (kind) => {
+ expect(toChannelConfig(kind, slackValues).kind).toBe(kind);
+ });
+
+ it('sends only the selected kind s fields, not another kind s leftovers', () => {
+ const config = toChannelConfig(ChannelKind.msteams, {
+ webhookUrl: 'https://teams.example.com/hook',
+ title: 'shared title',
+ routingKey: 'pagerduty-key',
+ apiUrl: 'https://hooks.slack.com/services/T/B/X',
+ });
+
+ expect(config.spec).toStrictEqual({
+ webhookUrl: 'https://teams.example.com/hook',
+ title: 'shared title',
+ });
+ });
+});
+
+describe('toPostableChannel', () => {
+ it('lets the api generate the immutable name from the display name', () => {
+ expect(toPostableChannel(ChannelKind.slack, slackValues)).toMatchObject({
+ generateName: true,
+ displayName: 'prod alerts',
+ });
+ });
+
+ it('leaves the display name out of the spec', () => {
+ expect(
+ toPostableChannel(ChannelKind.slack, slackValues).config.spec,
+ ).not.toHaveProperty('name');
+ });
+});
+
+describe('toChannelFormState', () => {
+ it('round-trips a channel back into the form it was built from', () => {
+ const channel = {
+ id: '1',
+ name: 'prod-alerts',
+ displayName: 'prod alerts',
+ createdAt: '2026-09-01T00:00:00Z',
+ updatedAt: '2026-09-01T00:00:00Z',
+ config: toChannelConfig(ChannelKind.slack, slackValues),
+ } as AlertmanagertypesGettableNotificationChannelDTO;
+
+ const { kind, values } = toChannelFormState(channel);
+
+ expect(kind).toBe(ChannelKind.slack);
+ expect(toChannelConfig(kind, values)).toStrictEqual(channel.config);
+ expect(values.name).toBe('prod alerts');
+ });
+});
+
+describe('jira reopen duration', () => {
+ it.each([
+ ['72h', '3d'],
+ ['1440m', '1d'],
+ ['7d', '1w'],
+ ['90m', '1h30m'],
+ ['3d', '3d'],
+ ])('sends %s as %s, the only spelling the api accepts back', (typed, sent) => {
+ expect(
+ toChannelConfig(ChannelKind.jira, {
+ site: 'https://acme.atlassian.net',
+ project: 'OPS',
+ issueType: 'Task',
+ email: '[email protected]',
+ apiToken: 'tok',
+ reopenDuration: typed,
+ }).spec,
+ ).toMatchObject({ reopenDuration: sent });
+ });
+
+ it('leaves a duration it cannot parse for the validator to reject', () => {
+ expect(
+ toChannelConfig(ChannelKind.jira, { reopenDuration: 'tomorrow' }).spec,
+ ).toMatchObject({ reopenDuration: 'tomorrow' });
+ });
+});
diff --git a/frontend/src/container/CreateAlertChannels/channelConfig.ts b/frontend/src/container/CreateAlertChannels/channelConfig.ts
new file mode 100644
index 0000000000..25b3c34ca5
--- /dev/null
+++ b/frontend/src/container/CreateAlertChannels/channelConfig.ts
@@ -0,0 +1,247 @@
+import {
+ AlertmanagertypesChannelConfigDTO,
+ AlertmanagertypesChannelEmailConfigDTO,
+ AlertmanagertypesChannelGoogleChatConfigDTO,
+ AlertmanagertypesChannelIncidentIOConfigDTO,
+ AlertmanagertypesChannelJiraConfigDTO,
+ AlertmanagertypesChannelJSMOpsConfigDTO,
+ AlertmanagertypesChannelMSTeamsConfigDTO,
+ AlertmanagertypesChannelOpsgenieConfigDTO,
+ AlertmanagertypesChannelPagerdutyConfigDTO,
+ AlertmanagertypesChannelSlackConfigDTO,
+ AlertmanagertypesChannelTelegramConfigDTO,
+ AlertmanagertypesChannelWebhookConfigDTO,
+ AlertmanagertypesPostableNotificationChannelDTO,
+ AlertmanagertypesTestableNotificationChannelDTO,
+ AlertmanagertypesUpdatableNotificationChannelDTO,
+} from 'api/generated/services/sigNoz.schemas';
+import { omit, pick } from 'lodash-es';
+import { omitBlank } from 'utils/omitBlank';
+
+import { ChannelFormValues, ChannelKind, ChannelSpecFormValues } from './types';
+import { canonicalJiraReopenDuration, filledRows } from './utils';
+
+const SPEC_FIELDS = {
+ [ChannelKind.slack]: [
+ 'apiUrl',
+ 'channel',
+ 'title',
+ 'titleLink',
+ 'text',
+ 'pretext',
+ 'fallback',
+ 'footer',
+ 'color',
+ 'fields',
+ 'actions',
+ 'sendResolved',
+ ] as const satisfies readonly (keyof AlertmanagertypesChannelSlackConfigDTO)[],
+ [ChannelKind.webhook]: [
+ 'url',
+ 'username',
+ 'password',
+ 'bearerToken',
+ 'sendResolved',
+ ] as const satisfies readonly (keyof AlertmanagertypesChannelWebhookConfigDTO)[],
+ [ChannelKind.email]: [
+ 'to',
+ 'html',
+ 'headers',
+ 'sendResolved',
+ ] as const satisfies readonly (keyof AlertmanagertypesChannelEmailConfigDTO)[],
+ [ChannelKind.pagerduty]: [
+ 'routingKey',
+ 'client',
+ 'clientUrl',
+ 'description',
+ 'severity',
+ 'component',
+ 'group',
+ 'class',
+ 'url',
+ 'source',
+ 'details',
+ 'sendResolved',
+ ] as const satisfies readonly (keyof AlertmanagertypesChannelPagerdutyConfigDTO)[],
+ [ChannelKind.opsgenie]: [
+ 'apiKey',
+ 'apiUrl',
+ 'message',
+ 'description',
+ 'source',
+ 'priority',
+ 'details',
+ 'sendResolved',
+ ] as const satisfies readonly (keyof AlertmanagertypesChannelOpsgenieConfigDTO)[],
+ [ChannelKind.msteams]: [
+ 'webhookUrl',
+ 'title',
+ 'text',
+ 'sendResolved',
+ ] as const satisfies readonly (keyof AlertmanagertypesChannelMSTeamsConfigDTO)[],
+ [ChannelKind.googlechat]: [
+ 'webhookUrl',
+ 'title',
+ 'text',
+ 'sendResolved',
+ ] as const satisfies readonly (keyof AlertmanagertypesChannelGoogleChatConfigDTO)[],
+ [ChannelKind.jira]: [
+ 'site',
+ 'project',
+ 'issueType',
+ 'email',
+ 'apiToken',
+ 'summary',
+ 'description',
+ 'priority',
+ 'labels',
+ 'resolveTransition',
+ 'reopenTransition',
+ 'wontFixResolution',
+ 'reopenDuration',
+ 'customFields',
+ 'sendResolved',
+ ] as const satisfies readonly (keyof AlertmanagertypesChannelJiraConfigDTO)[],
+ [ChannelKind.jsmops]: [
+ 'apiKey',
+ 'message',
+ 'description',
+ 'priority',
+ 'tags',
+ 'sendResolved',
+ ] as const satisfies readonly (keyof AlertmanagertypesChannelJSMOpsConfigDTO)[],
+ [ChannelKind.incidentio]: [
+ 'url',
+ 'token',
+ 'title',
+ 'description',
+ 'metadata',
+ 'sendResolved',
+ ] as const satisfies readonly (keyof AlertmanagertypesChannelIncidentIOConfigDTO)[],
+ [ChannelKind.telegram]: [
+ 'apiUrl',
+ 'botToken',
+ 'chatId',
+ 'messageThreadId',
+ 'title',
+ 'message',
+ 'disableNotifications',
+ 'sendResolved',
+ ] as const satisfies readonly (keyof AlertmanagertypesChannelTelegramConfigDTO)[],
+} satisfies Record<ChannelKind, readonly (keyof ChannelSpecFormValues)[]>;
+
+/**
+ * `satisfies` above only proves each listed key exists on the DTO, so a field
+ * left out still compiles and is then dropped on save. This fails the build
+ * instead, and the error names the missing field.
+ */
+type MissingFrom<D, T extends readonly PropertyKey[]> = Exclude<
+ keyof D,
+ T[number]
+>;
+
+type SpecFieldsComplete = {
+ slack: MissingFrom<
+ AlertmanagertypesChannelSlackConfigDTO,
+ (typeof SPEC_FIELDS)['slack']
+ >;
+ webhook: MissingFrom<
+ AlertmanagertypesChannelWebhookConfigDTO,
+ (typeof SPEC_FIELDS)['webhook']
+ >;
+ email: MissingFrom<
+ AlertmanagertypesChannelEmailConfigDTO,
+ (typeof SPEC_FIELDS)['email']
+ >;
+ pagerduty: MissingFrom<
+ AlertmanagertypesChannelPagerdutyConfigDTO,
+ (typeof SPEC_FIELDS)['pagerduty']
+ >;
+ opsgenie: MissingFrom<
+ AlertmanagertypesChannelOpsgenieConfigDTO,
+ (typeof SPEC_FIELDS)['opsgenie']
+ >;
+ msteams: MissingFrom<
+ AlertmanagertypesChannelMSTeamsConfigDTO,
+ (typeof SPEC_FIELDS)['msteams']
+ >;
+ googlechat: MissingFrom<
+ AlertmanagertypesChannelGoogleChatConfigDTO,
+ (typeof SPEC_FIELDS)['googlechat']
+ >;
+ jira: MissingFrom<
+ AlertmanagertypesChannelJiraConfigDTO,
+ (typeof SPEC_FIELDS)['jira']
+ >;
+ jsmops: MissingFrom<
+ AlertmanagertypesChannelJSMOpsConfigDTO,
+ (typeof SPEC_FIELDS)['jsmops']
+ >;
+ incidentio: MissingFrom<
+ AlertmanagertypesChannelIncidentIOConfigDTO,
+ (typeof SPEC_FIELDS)['incidentio']
+ >;
+ telegram: MissingFrom<
+ AlertmanagertypesChannelTelegramConfigDTO,
+ (typeof SPEC_FIELDS)['telegram']
+ >;
+};
+
+// every member must be `never`; a missed field shows up here by name
+type NothingMissing<T extends Record<keyof T, never>> = T;
+export type SpecFieldsAreExhaustive = NothingMissing<SpecFieldsComplete>;
+
+export function toChannelConfig(
+ kind: ChannelKind,
+ values: ChannelFormValues,
+): AlertmanagertypesChannelConfigDTO {
+ const picked: Record<string, unknown> = pick(values, SPEC_FIELDS[kind]);
+
+ if (kind === ChannelKind.slack) {
+ picked.fields = filledRows(
+ picked.fields as AlertmanagertypesChannelSlackConfigDTO['fields'],
+ 'title',
+ );
+ picked.actions = filledRows(
+ picked.actions as AlertmanagertypesChannelSlackConfigDTO['actions'],
+ 'text',
+ ).map((action) =>
+ action.confirm?.text?.trim() ? action : omit(action, 'confirm'),
+ );
+ }
+
+ const spec: Record<string, unknown> = omitBlank(picked);
+
+ // the API answers a read with the duration prometheus would print, and
+ // rejects anything spelled differently
+ if (kind === ChannelKind.jira && typeof spec.reopenDuration === 'string') {
+ spec.reopenDuration = canonicalJiraReopenDuration(spec.reopenDuration);
+ }
+
+ return { kind, spec } as unknown as AlertmanagertypesChannelConfigDTO;
+}
+
+export function toPostableChannel(
+ kind: ChannelKind,
+ values: ChannelFormValues,
+): AlertmanagertypesPostableNotificationChannelDTO {
+ return {
+ generateName: true,
+ displayName: values.name ?? '',
+ config: toChannelConfig(kind, values),
+ };
+}
+
+export function toUpdatableChannel(
+ kind: ChannelKind,
+ values: ChannelFormValues,
+): AlertmanagertypesUpdatableNotificationChannelDTO {
+ return { config: toChannelConfig(kind, values) };
+}
+
+export function toTestableChannel(
+ kind: ChannelKind,
+ values: ChannelFormValues,
+): AlertmanagertypesTestableNotificationChannelDTO {
+ return { config: toChannelConfig(kind, values) };
+}
diff --git a/frontend/src/container/CreateAlertChannels/channelFormValues.ts b/frontend/src/container/CreateAlertChannels/channelFormValues.ts
new file mode 100644
index 0000000000..fccdebdc2c
--- /dev/null
+++ b/frontend/src/container/CreateAlertChannels/channelFormValues.ts
@@ -0,0 +1,32 @@
+import { AlertmanagertypesGettableNotificationChannelDTO } from 'api/generated/services/sigNoz.schemas';
+
+import { ChannelFormValues, ChannelKind } from './types';
+
+export interface ChannelFormState {
+ kind: ChannelKind;
+ values: ChannelFormValues;
+}
+
+/** Each union member types `kind` as its own enum, so a plain cast is unsafe. */
+function toChannelKind(kind: string): ChannelKind {
+ const known = (Object.values(ChannelKind) as string[]).includes(kind);
+
+ if (!known) {
+ throw new Error(`This build cannot render a channel of kind "${kind}".`);
+ }
+
+ return kind as ChannelKind;
+}
+
+/** The form edits the spec the API returns, so loading lifts it whole. */
+export function toChannelFormState(
+ channel: AlertmanagertypesGettableNotificationChannelDTO,
+): ChannelFormState {
+ return {
+ kind: toChannelKind(channel.config.kind),
+ values: {
+ ...channel.config.spec,
+ name: channel.displayName,
+ },
+ };
+}
diff --git a/frontend/src/container/CreateAlertChannels/channelResolver.ts b/frontend/src/container/CreateAlertChannels/channelResolver.ts
new file mode 100644
index 0000000000..940eb0a48d
--- /dev/null
+++ b/frontend/src/container/CreateAlertChannels/channelResolver.ts
@@ -0,0 +1,39 @@
+import { TFunction } from 'i18next';
+import type { FieldErrors, Resolver } from 'react-hook-form';
+import type { $ZodIssue } from 'zod/v4/core';
+
+import { channelNameSchema } from './schemas/shared';
+import { ChannelFormValues, ChannelKind } from './types';
+import { CHANNEL_SCHEMAS } from './validation';
+
+const toFieldErrors = (
+ issues: $ZodIssue[],
+ t: TFunction,
+): FieldErrors<ChannelFormValues> => {
+ const errors: Record<string, { type: string; message: string }> = {};
+
+ issues.forEach((issue) => {
+ const field = issue.path.join('.') || 'name';
+ if (!errors[field]) {
+ errors[field] = { type: 'validation', message: t(issue.message) };
+ }
+ });
+
+ return errors as FieldErrors<ChannelFormValues>;
+};
+
+export const channelResolver =
+ (kind: ChannelKind, t: TFunction): Resolver<ChannelFormValues> =>
+ async (values) => {
+ const schema = CHANNEL_SCHEMAS[kind];
+ const issues: $ZodIssue[] = [
+ ...(channelNameSchema.safeParse(values).error?.issues ?? []),
+ ...(schema ? (schema.safeParse(values).error?.issues ?? []) : []),
+ ];
+
+ if (issues.length === 0) {
+ return { values, errors: {} };
+ }
+
+ return { values: {}, errors: toFieldErrors(issues, t) };
+ };
diff --git a/frontend/src/container/CreateAlertChannels/channelRoundTrip.test.ts b/frontend/src/container/CreateAlertChannels/channelRoundTrip.test.ts
new file mode 100644
index 0000000000..1ed87eed11
--- /dev/null
+++ b/frontend/src/container/CreateAlertChannels/channelRoundTrip.test.ts
@@ -0,0 +1,132 @@
+import { AlertmanagertypesGettableNotificationChannelDTO } from 'api/generated/services/sigNoz.schemas';
+
+import { toChannelConfig, toUpdatableChannel } from './channelConfig';
+import { toChannelFormState } from './channelFormValues';
+import { ChannelKind } from './types';
+
+const SPECS: Record<string, Record<string, unknown>> = {
+ slack: {
+ apiUrl: 'https://hooks.slack.com/services/T/B/X',
+ channel: '#ops',
+ title: 'title',
+ titleLink: 'https://signoz.io',
+ text: 'body',
+ pretext: 'pre',
+ fallback: 'fall',
+ footer: 'foot',
+ color: 'danger',
+ fields: [{ title: 'env', value: 'prod', short: true }],
+ actions: [{ type: 'button', text: 'Runbook', url: 'https://runbook' }],
+ sendResolved: true,
+ },
+ webhook: {
+ url: 'https://example.com/hook',
+ username: 'u',
+ password: 'p',
+ bearerToken: 't',
+ sendResolved: true,
+ },
+ email: {
+ html: '<p>a</p>',
+ headers: { 'X-Team': 'ops' },
+ sendResolved: true,
+ },
+ pagerduty: {
+ routingKey: 'k',
+ client: 'c',
+ clientUrl: 'https://c',
+ description: 'd',
+ severity: 'critical',
+ component: 'comp',
+ group: 'grp',
+ class: 'cls',
+ url: 'https://events.pagerduty.com',
+ source: 'signoz',
+ details: { firing: '{{ .Alerts.Firing }}' },
+ sendResolved: true,
+ },
+ opsgenie: {
+ apiKey: 'k',
+ apiUrl: 'https://api.opsgenie.com',
+ message: 'm',
+ description: 'd',
+ source: 's',
+ priority: 'P1',
+ details: { env: 'prod' },
+ sendResolved: true,
+ },
+ msteams: {
+ webhookUrl: 'https://teams',
+ title: 't',
+ text: 'b',
+ sendResolved: true,
+ },
+ googlechat: {
+ webhookUrl: 'https://chat.googleapis.com/v1/spaces/A',
+ title: 't',
+ text: 'b',
+ sendResolved: true,
+ },
+ jira: {
+ site: 'https://acme.atlassian.net',
+ project: 'OPS',
+ issueType: 'Task',
+ email: '[email protected]',
+ apiToken: 'tok',
+ summary: 's',
+ description: 'd',
+ priority: 'High',
+ labels: ['one', 'two'],
+ resolveTransition: 'Done',
+ reopenTransition: 'Reopen',
+ wontFixResolution: 'WontFix',
+ reopenDuration: '3d',
+ customFields: { customfield_1: 'v' },
+ sendResolved: true,
+ },
+ jsmops: {
+ apiKey: 'k',
+ message: 'm',
+ description: 'd',
+ priority: 'P2',
+ tags: 'prod,db',
+ sendResolved: true,
+ },
+ incidentio: {
+ url: 'https://api.incident.io/v2/alert_events/http/abc',
+ token: 'tok',
+ title: 't',
+ description: 'd',
+ metadata: { team: 'ops' },
+ sendResolved: true,
+ },
+};
+
+describe('load then save round trip', () => {
+ it.each(Object.keys(SPECS))('keeps every %s field', (kind) => {
+ const channel = {
+ id: '1',
+ name: `${kind}-channel`,
+ displayName: `${kind} channel`,
+ createdAt: '2026-01-01T00:00:00Z',
+ updatedAt: '2026-01-01T00:00:00Z',
+ config: { kind, spec: SPECS[kind] },
+ } as unknown as AlertmanagertypesGettableNotificationChannelDTO;
+
+ const { kind: loadedKind, values } = toChannelFormState(channel);
+ const saved = toUpdatableChannel(loadedKind, values);
+
+ expect(loadedKind).toBe(kind as ChannelKind);
+ expect(saved.config).toStrictEqual(channel.config);
+ });
+
+ it('never sends the display name inside the spec', () => {
+ const config = toChannelConfig(ChannelKind.slack, {
+ name: 'prod alerts',
+ apiUrl: 'https://hooks.slack.com/x',
+ });
+
+ expect(config.spec).not.toHaveProperty('name');
+ });
+});
diff --git a/frontend/src/container/CreateAlertChannels/defaults.ts b/frontend/src/container/CreateAlertChannels/defaults.ts
index dda8238e63..0a9e76b242 100644
--- a/frontend/src/container/CreateAlertChannels/defaults.ts
+++ b/frontend/src/container/CreateAlertChannels/defaults.ts
@@ -1,20 +1,21 @@
import {
- ChannelType,
- EmailChannel,
- GoogleChatChannel,
- IncidentIOChannel,
- JiraChannel,
- JsmOpsChannel,
- MsTeamsChannel,
- OpsgenieChannel,
- PagerChannel,
- SlackChannel,
- WebhookChannel,
-} from './config';
+ AlertmanagertypesChannelEmailConfigDTO,
+ AlertmanagertypesChannelGoogleChatConfigDTO,
+ AlertmanagertypesChannelIncidentIOConfigDTO,
+ AlertmanagertypesChannelJiraConfigDTO,
+ AlertmanagertypesChannelJSMOpsConfigDTO,
+ AlertmanagertypesChannelOpsgenieConfigDTO,
+ AlertmanagertypesChannelPagerdutyConfigDTO,
+ AlertmanagertypesChannelSlackConfigDTO,
+ AlertmanagertypesChannelTelegramConfigDTO,
+} from 'api/generated/services/sigNoz.schemas';
+
+import { ChannelKind, ChannelSpecFormValues } from './types';
// shared by slack and ms teams, both render the same title / description boxes
-export const SlackInitialConfig: Partial<SlackChannel> = {
- text: `{{ range .Alerts -}}
+export const SlackInitialConfig: Partial<AlertmanagertypesChannelSlackConfigDTO> =
+ {
+ text: `{{ range .Alerts -}}
*Alert:* {{ .Labels.alertname }}{{ if .Labels.severity }} - {{ .Labels.severity }}{{ end }}
*Summary:* {{ .Annotations.summary }}
@@ -26,7 +27,7 @@ export const SlackInitialConfig: Partial<SlackChannel> = {
{{ range .Labels.SortedPairs }} • *{{ .Name }}:* {{ .Value }}
{{ end }}
{{ end }}`,
- title: `[{{ .Status | toUpper }}{{ if eq .Status "firing" }}:{{ .Alerts.Firing | len }}{{ end }}] {{ .CommonLabels.alertname }} for {{ .CommonLabels.job }}
+ title: `[{{ .Status | toUpper }}{{ if eq .Status "firing" }}:{{ .Alerts.Firing | len }}{{ end }}] {{ .CommonLabels.alertname }} for {{ .CommonLabels.job }}
{{- if gt (len .CommonLabels) (len .GroupLabels) -}}
{{" "}}(
{{- with .CommonLabels.Remove .GroupLabels.Names }}
@@ -37,27 +38,29 @@ export const SlackInitialConfig: Partial<SlackChannel> = {
{{- end -}}
)
{{- end }}`,
-};
+ };
// mirrors DefaultGoogleChatReceiverConfig in pkg/types/alertmanagertypes/googlechat.go,
// which the backend applies when title / text are left empty
-export const GoogleChatInitialConfig: Partial<GoogleChatChannel> = {
- title: `[{{ .Status | toUpper }}{{ if eq .Status "firing" }}:{{ .Alerts.Firing | len }}{{ end }}] {{ .CommonLabels.alertname }}`,
- text: `{{ range .Alerts -}}
+export const GoogleChatInitialConfig: Partial<AlertmanagertypesChannelGoogleChatConfigDTO> =
+ {
+ title: `[{{ .Status | toUpper }}{{ if eq .Status "firing" }}:{{ .Alerts.Firing | len }}{{ end }}] {{ .CommonLabels.alertname }}`,
+ text: `{{ range .Alerts -}}
**Alert:** {{ .Labels.alertname }}{{ if .Labels.severity }} ({{ .Labels.severity }}){{ end }}{{ if .Annotations.summary }}
**Summary:** {{ .Annotations.summary }}{{ end }}{{ if .Annotations.description }}
**Description:** {{ .Annotations.description }}{{ end }}
{{ end }}`,
-};
+ };
// mirrors DefaultJiraSummaryTemplate / DefaultJiraDescriptionTemplate in
// pkg/types/alertmanagertypes/jira.go, which the backend applies when the
// summary / description are left empty. The description is markdown here and is
// wrapped in the ADF status panel + deep-links server-side.
-export const JiraInitialConfig: Partial<JiraChannel> = {
- issue_type: 'Task',
- summary: `[{{ .Status | toUpper }}{{ if eq .Status "firing" }}:{{ .Alerts.Firing | len }}{{ end }}] {{ .CommonLabels.alertname }}`,
- description: `{{ range .Alerts -}}
+export const JiraInitialConfig: Partial<AlertmanagertypesChannelJiraConfigDTO> =
+ {
+ issueType: 'Task',
+ summary: `[{{ .Status | toUpper }}{{ if eq .Status "firing" }}:{{ .Alerts.Firing | len }}{{ end }}] {{ .CommonLabels.alertname }}`,
+ description: `{{ range .Alerts -}}
**Alert:** {{ .Labels.alertname }}{{ if .Labels.severity }} ({{ .Labels.severity }}){{ end }}
{{ if .Annotations.summary }}
**Summary:** {{ .Annotations.summary }}
@@ -65,10 +68,11 @@ export const JiraInitialConfig: Partial<JiraChannel> = {
**Description:** {{ .Annotations.description }}
{{ end }}
{{ end }}`,
-};
+ };
-export const PagerInitialConfig: Partial<PagerChannel> = {
- description: `[{{ .Status | toUpper }}{{ if eq .Status "firing" }}:{{ .Alerts.Firing | len }}{{ end }}] {{ .CommonLabels.alertname }} for {{ .CommonLabels.job }}
+export const PagerInitialConfig: Partial<AlertmanagertypesChannelPagerdutyConfigDTO> =
+ {
+ description: `[{{ .Status | toUpper }}{{ if eq .Status "firing" }}:{{ .Alerts.Firing | len }}{{ end }}] {{ .CommonLabels.alertname }} for {{ .CommonLabels.job }}
{{- if gt (len .CommonLabels) (len .GroupLabels) -}}
{{" "}}(
{{- with .CommonLabels.Remove .GroupLabels.Names }}
@@ -79,20 +83,21 @@ export const PagerInitialConfig: Partial<PagerChannel> = {
{{- end -}}
)
{{- end }}`,
- severity: '{{ (index .Alerts 0).Labels.severity }}',
- client: 'SigNoz Alert Manager',
- client_url: 'https://enter-signoz-host-n-port-here/alerts',
- details: JSON.stringify({
- firing: `{{ .Alerts.Firing | toJson }}`,
- resolved: `{{ .Alerts.Resolved | toJson }}`,
- num_firing: '{{ .Alerts.Firing | len }}',
- num_resolved: '{{ .Alerts.Resolved | len }}',
- }),
-};
+ severity: '{{ (index .Alerts 0).Labels.severity }}',
+ client: 'SigNoz Alert Manager',
+ clientUrl: 'https://enter-signoz-host-n-port-here/alerts',
+ details: {
+ firing: `{{ .Alerts.Firing | toJson }}`,
+ resolved: `{{ .Alerts.Resolved | toJson }}`,
+ num_firing: '{{ .Alerts.Firing | len }}',
+ num_resolved: '{{ .Alerts.Resolved | len }}',
+ },
+ };
-export const OpsgenieInitialConfig: Partial<OpsgenieChannel> = {
- message: '{{ .CommonLabels.alertname }}',
- description: `{{ if gt (len .Alerts.Firing) 0 -}}
+export const OpsgenieInitialConfig: Partial<AlertmanagertypesChannelOpsgenieConfigDTO> =
+ {
+ message: '{{ .CommonLabels.alertname }}',
+ description: `{{ if gt (len .Alerts.Firing) 0 -}}
Alerts Firing:
{{ range .Alerts.Firing }}
- Message: {{ .Annotations.description }}
@@ -114,19 +119,20 @@ export const OpsgenieInitialConfig: Partial<OpsgenieChannel> = {
{{ end }} Source: {{ .GeneratorURL }}
{{ end }}
{{- end }}`,
- priority:
- '{{ if eq (index .Alerts 0).Labels.severity "critical" }}P1{{ else if eq (index .Alerts 0).Labels.severity "warning" }}P2{{ else if eq (index .Alerts 0).Labels.severity "info" }}P3{{ else }}P4{{ end }}',
-};
+ priority:
+ '{{ if eq (index .Alerts 0).Labels.severity "critical" }}P1{{ else if eq (index .Alerts 0).Labels.severity "warning" }}P2{{ else if eq (index .Alerts 0).Labels.severity "info" }}P3{{ else }}P4{{ end }}',
+ };
// mirrors DefaultJSMOpsMessageTemplate / DefaultJSMOpsDescriptionTemplate in
// pkg/types/alertmanagertypes/jsmops.go, applied by the backend when message /
// description are left empty. send_resolved is seeded on so JSM alerts close on
// resolve (the backend cannot default it, see jsmops.go). priority mirrors the
// Opsgenie template mapping severity to P1-P5.
-export const JsmOpsInitialConfig: Partial<JsmOpsChannel> = {
- send_resolved: true,
- message: `[{{ .Status | toUpper }}{{ if eq .Status "firing" }}:{{ .Alerts.Firing | len }}{{ end }}] {{ .CommonLabels.alertname }}`,
- description: `{{ range .Alerts -}}
+export const JsmOpsInitialConfig: Partial<AlertmanagertypesChannelJSMOpsConfigDTO> =
+ {
+ sendResolved: true,
+ message: `[{{ .Status | toUpper }}{{ if eq .Status "firing" }}:{{ .Alerts.Firing | len }}{{ end }}] {{ .CommonLabels.alertname }}`,
+ description: `{{ range .Alerts -}}
**Alert:** {{ .Labels.alertname }}{{ if .Labels.severity }} ({{ .Labels.severity }}){{ end }}
{{ if .Annotations.summary }}**Summary:** {{ .Annotations.summary }}
@@ -140,19 +146,20 @@ export const JsmOpsInitialConfig: Partial<JsmOpsChannel> = {
{{ end }}{{ if .Annotations.related_traces }}[View related traces]({{ .Annotations.related_traces }})
{{ end }}{{ end }}`,
- priority:
- '{{ if eq (index .Alerts 0).Labels.severity "critical" }}P1{{ else if eq (index .Alerts 0).Labels.severity "warning" }}P2{{ else if eq (index .Alerts 0).Labels.severity "info" }}P3{{ else }}P4{{ end }}',
- tags: ['signoz-alert'],
-};
+ priority:
+ '{{ if eq (index .Alerts 0).Labels.severity "critical" }}P1{{ else if eq (index .Alerts 0).Labels.severity "warning" }}P2{{ else if eq (index .Alerts 0).Labels.severity "info" }}P3{{ else }}P4{{ end }}',
+ tags: 'signoz-alert',
+ };
// mirrors DefaultIncidentIOTitleTemplate / DefaultIncidentIODescriptionTemplate
// in pkg/types/alertmanagertypes/incidentio.go, applied by the backend when
// title / description are left empty. send_resolved is seeded on so incident.io
// alerts resolve with the rule (the backend cannot default it).
-export const IncidentIOInitialConfig: Partial<IncidentIOChannel> = {
- send_resolved: true,
- title: `[{{ .Status | toUpper }}{{ if eq .Status "firing" }}:{{ .Alerts.Firing | len }}{{ end }}] {{ .CommonLabels.alertname }}`,
- description: `{{ range .Alerts -}}
+export const IncidentIOInitialConfig: Partial<AlertmanagertypesChannelIncidentIOConfigDTO> =
+ {
+ sendResolved: true,
+ title: `[{{ .Status | toUpper }}{{ if eq .Status "firing" }}:{{ .Alerts.Firing | len }}{{ end }}] {{ .CommonLabels.alertname }}`,
+ description: `{{ range .Alerts -}}
**Alert:** {{ .Labels.alertname }}{{ if .Labels.severity }} ({{ .Labels.severity }}){{ end }}
{{ if .Annotations.summary }}**Summary:** {{ .Annotations.summary }}
@@ -166,11 +173,12 @@ export const IncidentIOInitialConfig: Partial<IncidentIOChannel> = {
{{ end }}{{ if .Annotations.related_traces }}[View related traces]({{ .Annotations.related_traces }})
{{ end }}{{ end }}`,
-};
+ };
-export const EmailInitialConfig: Partial<EmailChannel> = {
- send_resolved: true,
- html: `<!--
+export const EmailInitialConfig: Partial<AlertmanagertypesChannelEmailConfigDTO> =
+ {
+ sendResolved: true,
+ html: `<!--
Credits: https://github.com/mailgun/transactional-email-templates
-->
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
@@ -562,33 +570,30 @@ export const EmailInitialConfig: Partial<EmailChannel> = {
</table>
</body>
</html>`,
-};
+ };
// prefilled values of every channel type, keyed by type so the form can apply
// exactly one set of defaults and swap it when the type changes
-export const ChannelInitialConfig: Record<
- ChannelType,
- Partial<
- SlackChannel &
- WebhookChannel &
- PagerChannel &
- MsTeamsChannel &
- OpsgenieChannel &
- EmailChannel &
- GoogleChatChannel &
- JiraChannel &
- JsmOpsChannel &
- IncidentIOChannel
- >
-> = {
- [ChannelType.Slack]: SlackInitialConfig,
- [ChannelType.MsTeams]: SlackInitialConfig,
- [ChannelType.GoogleChat]: GoogleChatInitialConfig,
- [ChannelType.Jira]: JiraInitialConfig,
- [ChannelType.JsmOps]: JsmOpsInitialConfig,
- [ChannelType.IncidentIO]: IncidentIOInitialConfig,
- [ChannelType.Pagerduty]: PagerInitialConfig,
- [ChannelType.Opsgenie]: OpsgenieInitialConfig,
- [ChannelType.Email]: EmailInitialConfig,
- [ChannelType.Webhook]: {},
-};
+// `message` is left unset so the backend applies its own template; an empty
+// string would overwrite it.
+export const TelegramInitialConfig: Partial<AlertmanagertypesChannelTelegramConfigDTO> =
+ {
+ sendResolved: true,
+ };
+
+export const DEFAULT_CHANNEL_KIND = ChannelKind.slack;
+
+export const ChannelInitialConfig: Record<ChannelKind, ChannelSpecFormValues> =
+ {
+ [ChannelKind.slack]: SlackInitialConfig,
+ [ChannelKind.msteams]: SlackInitialConfig,
+ [ChannelKind.googlechat]: GoogleChatInitialConfig,
+ [ChannelKind.jira]: JiraInitialConfig,
+ [ChannelKind.jsmops]: JsmOpsInitialConfig,
+ [ChannelKind.incidentio]: IncidentIOInitialConfig,
+ [ChannelKind.pagerduty]: PagerInitialConfig,
+ [ChannelKind.opsgenie]: OpsgenieInitialConfig,
+ [ChannelKind.email]: EmailInitialConfig,
+ [ChannelKind.webhook]: {},
+ [ChannelKind.telegram]: TelegramInitialConfig,
+ };
diff --git a/frontend/src/container/CreateAlertChannels/index.tsx b/frontend/src/container/CreateAlertChannels/index.tsx
deleted file mode 100644
index 2e9691b187..0000000000
--- a/frontend/src/container/CreateAlertChannels/index.tsx
+++ /dev/null
@@ -1,818 +0,0 @@
-import { useCallback, useEffect, useState } from 'react';
-import { useTranslation } from 'react-i18next';
-import { Form } from 'antd';
-import createEmail from 'api/channels/createEmail';
-import createMsTeamsApi from 'api/channels/createMsTeams';
-import createOpsgenie from 'api/channels/createOpsgenie';
-import createPagerApi from 'api/channels/createPager';
-import createSlackApi from 'api/channels/createSlack';
-import createWebhookApi from 'api/channels/createWebhook';
-import testEmail from 'api/channels/testEmail';
-import testMsTeamsApi from 'api/channels/testMsTeams';
-import testOpsGenie from 'api/channels/testOpsgenie';
-import testPagerApi from 'api/channels/testPager';
-import testSlackApi from 'api/channels/testSlack';
-import testWebhookApi from 'api/channels/testWebhook';
-import logEvent from 'api/common/logEvent';
-import {
- useCreateChannel,
- useTestChannel,
-} from 'api/generated/services/channels';
-import { RenderErrorResponseDTO } from 'api/generated/services/sigNoz.schemas';
-import { ErrorType } from 'api/generatedAPIInstance';
-import ROUTES from 'constants/routes';
-import FormAlertChannels from 'container/FormAlertChannels';
-import { useNotifications } from 'hooks/useNotifications';
-import history from 'lib/history';
-import { useErrorModal } from 'providers/ErrorModalProvider';
-import APIError from 'types/api/error';
-import { toAPIError } from 'utils/errorUtils';
-
-import {
- ChannelType,
- EmailChannel,
- GoogleChatChannel,
- IncidentIOChannel,
- JiraChannel,
- JsmOpsChannel,
- MsTeamsChannel,
- OpsgenieChannel,
- PagerChannel,
- SlackChannel,
- ValidatePagerChannel,
- WebhookChannel,
-} from './config';
-import { ChannelInitialConfig } from './defaults';
-import {
- isChannelType,
- isValidGoogleChatWebhookURL,
- isValidIncidentIOURL,
- isValidJiraReopenDuration,
- isValidJiraSiteURL,
- prepareGoogleChatRequest,
- prepareIncidentIORequest,
- prepareJiraRequest,
- prepareJsmOpsRequest,
-} from './utils';
-
-import './CreateAlertChannels.styles.scss';
-
-function CreateAlertChannels({
- preType = ChannelType.Slack,
-}: CreateAlertChannelsProps): JSX.Element {
- // init namespace for translations
- const { t } = useTranslation('channels');
- const { showErrorModal } = useErrorModal();
-
- const [formInstance] = Form.useForm();
-
- useEffect(() => {
- logEvent('Alert Channel: Create channel page visited', {});
- }, []);
-
- const [selectedConfig, setSelectedConfig] = useState<
- Partial<
- SlackChannel &
- WebhookChannel &
- PagerChannel &
- MsTeamsChannel &
- OpsgenieChannel &
- EmailChannel &
- GoogleChatChannel &
- JiraChannel &
- JsmOpsChannel &
- IncidentIOChannel
- >
- >(() => ({
- send_resolved: true,
- ...ChannelInitialConfig[preType],
- }));
- const [savingState, setSavingState] = useState<boolean>(false);
- const [testingState, setTestingState] = useState<boolean>(false);
- const { notifications } = useNotifications();
-
- const { mutateAsync: createChannel } = useCreateChannel();
- const { mutateAsync: testChannel } = useTestChannel();
-
- const [type, setType] = useState<ChannelType>(preType);
- const onTypeChangeHandler = useCallback(
- (value: string) => {
- const nextType = value as ChannelType;
- if (nextType === type) {
- return;
- }
-
- setType(nextType);
-
- // the fields the types share (title, text, description) keep the value of
- // the type that was selected before, so the new type's defaults have to be
- // written to both the config and the form
- const defaults = ChannelInitialConfig[nextType];
- setSelectedConfig((selectedConfig) => ({ ...selectedConfig, ...defaults }));
- formInstance.setFieldsValue(defaults);
- },
- [type, formInstance],
- );
-
- const prepareSlackRequest = useCallback(
- () => ({
- api_url: selectedConfig?.api_url || '',
- channel: selectedConfig?.channel || '',
- name: selectedConfig?.name || '',
- send_resolved: selectedConfig?.send_resolved || false,
- text: selectedConfig?.text || '',
- title: selectedConfig?.title || '',
- }),
- [selectedConfig],
- );
-
- const onSlackHandler = useCallback(async () => {
- if (!selectedConfig.api_url) {
- notifications.error({
- message: 'Error',
- description: t('webhook_url_required'),
- });
- return;
- }
-
- setSavingState(true);
-
- try {
- await createSlackApi(prepareSlackRequest());
- notifications.success({
- message: 'Success',
- description: t('channel_creation_done'),
- });
- history.replace(ROUTES.ALL_CHANNELS);
- return { status: 'success', statusMessage: t('channel_creation_done') };
- } catch (error) {
- showErrorModal(error as APIError);
- return { status: 'failed', statusMessage: t('channel_creation_failed') };
- } finally {
- setSavingState(false);
- }
- }, [selectedConfig, notifications, t, prepareSlackRequest, showErrorModal]);
-
- const prepareWebhookRequest = useCallback(() => {
- // initial api request without auth params
- let request: WebhookChannel = {
- api_url: selectedConfig?.api_url || '',
- name: selectedConfig?.name || '',
- send_resolved: selectedConfig?.send_resolved || false,
- };
-
- if (selectedConfig?.username !== '' || selectedConfig?.password !== '') {
- if (selectedConfig?.username !== '') {
- // if username is not null then password must be passed
- if (selectedConfig?.password !== '') {
- request = {
- ...request,
- username: selectedConfig.username,
- password: selectedConfig.password,
- };
- } else {
- notifications.error({
- message: 'Error',
- description: t('username_no_password'),
- });
- }
- } else if (selectedConfig?.password !== '') {
- // only password entered, set bearer token
- request = {
- ...request,
- username: '',
- password: selectedConfig.password,
- };
- }
- }
- return request;
- }, [notifications, t, selectedConfig]);
-
- const onWebhookHandler = useCallback(async () => {
- if (!selectedConfig.api_url) {
- notifications.error({
- message: 'Error',
- description: t('webhook_url_required'),
- });
- return;
- }
-
- setSavingState(true);
- try {
- const request = prepareWebhookRequest();
- await createWebhookApi(request);
- notifications.success({
- message: 'Success',
- description: t('channel_creation_done'),
- });
- history.replace(ROUTES.ALL_CHANNELS);
- return { status: 'success', statusMessage: t('channel_creation_done') };
- } catch (error) {
- showErrorModal(error as APIError);
- return { status: 'failed', statusMessage: t('channel_creation_failed') };
- } finally {
- setSavingState(false);
- }
- }, [
- selectedConfig.api_url,
- notifications,
- t,
- prepareWebhookRequest,
- showErrorModal,
- ]);
-
- const preparePagerRequest = useCallback(() => {
- const validationError = ValidatePagerChannel(selectedConfig as PagerChannel);
- if (validationError !== '') {
- notifications.error({
- message: 'Error',
- description: validationError,
- });
- return null;
- }
-
- return {
- name: selectedConfig?.name || '',
- send_resolved: selectedConfig?.send_resolved || false,
- routing_key: selectedConfig?.routing_key || '',
- client: selectedConfig?.client || '',
- client_url: selectedConfig?.client_url || '',
- description: selectedConfig?.description || '',
- severity: selectedConfig?.severity || '',
- component: selectedConfig?.component || '',
- group: selectedConfig?.group || '',
- class: selectedConfig?.class || '',
- details: selectedConfig.details || '',
- detailsArray: JSON.parse(selectedConfig.details || '{}'),
- };
- }, [selectedConfig, notifications]);
-
- const onPagerHandler = useCallback(async () => {
- setSavingState(true);
- const request = preparePagerRequest();
-
- try {
- if (request) {
- await createPagerApi(request);
- notifications.success({
- message: 'Success',
- description: t('channel_creation_done'),
- });
- history.replace(ROUTES.ALL_CHANNELS);
- return { status: 'success', statusMessage: t('channel_creation_done') };
- }
- return { status: 'failed', statusMessage: t('channel_creation_failed') };
- } catch (error) {
- showErrorModal(error as APIError);
- return { status: 'failed', statusMessage: t('channel_creation_failed') };
- } finally {
- setSavingState(false);
- }
- }, [preparePagerRequest, t, notifications, showErrorModal]);
-
- const prepareOpsgenieRequest = useCallback(
- () => ({
- api_key: selectedConfig?.api_key || '',
- name: selectedConfig?.name || '',
- send_resolved: selectedConfig?.send_resolved || false,
- description: selectedConfig?.description || '',
- message: selectedConfig?.message || '',
- priority: selectedConfig?.priority || '',
- }),
- [selectedConfig],
- );
-
- const onOpsgenieHandler = useCallback(async () => {
- if (!selectedConfig.api_key) {
- notifications.error({
- message: 'Error',
- description: t('api_key_required'),
- });
- return;
- }
-
- setSavingState(true);
- try {
- await createOpsgenie(prepareOpsgenieRequest());
- notifications.success({
- message: 'Success',
- description: t('channel_creation_done'),
- });
- history.replace(ROUTES.ALL_CHANNELS);
- return { status: 'success', statusMessage: t('channel_creation_done') };
- } catch (error) {
- showErrorModal(error as APIError);
- return { status: 'failed', statusMessage: t('channel_creation_failed') };
- } finally {
- setSavingState(false);
- }
- }, [
- selectedConfig.api_key,
- notifications,
- t,
- prepareOpsgenieRequest,
- showErrorModal,
- ]);
-
- const prepareEmailRequest = useCallback(
- () => ({
- name: selectedConfig?.name || '',
- send_resolved: selectedConfig?.send_resolved || false,
- to: selectedConfig?.to || '',
- html: selectedConfig?.html || '',
- headers: selectedConfig?.headers || {},
- }),
- [selectedConfig],
- );
-
- const onEmailHandler = useCallback(async () => {
- if (!selectedConfig.to) {
- notifications.error({
- message: 'Error',
- description: t('to_required'),
- });
- return;
- }
-
- setSavingState(true);
- try {
- const request = prepareEmailRequest();
- await createEmail(request);
- notifications.success({
- message: 'Success',
- description: t('channel_creation_done'),
- });
- history.replace(ROUTES.ALL_CHANNELS);
- return { status: 'success', statusMessage: t('channel_creation_done') };
- } catch (error) {
- showErrorModal(error as APIError);
- return { status: 'failed', statusMessage: t('channel_creation_failed') };
- } finally {
- setSavingState(false);
- }
- }, [prepareEmailRequest, notifications, t, showErrorModal, selectedConfig.to]);
-
- const prepareMsTeamsRequest = useCallback(
- () => ({
- webhook_url: selectedConfig?.webhook_url || '',
- name: selectedConfig?.name || '',
- send_resolved: selectedConfig?.send_resolved || false,
- text: selectedConfig?.text || '',
- title: selectedConfig?.title || '',
- }),
- [selectedConfig],
- );
-
- const onMsTeamsHandler = useCallback(async () => {
- if (!selectedConfig.webhook_url) {
- notifications.error({
- message: 'Error',
- description: t('webhook_url_required'),
- });
- return;
- }
-
- setSavingState(true);
-
- try {
- await createMsTeamsApi(prepareMsTeamsRequest());
- notifications.success({
- message: 'Success',
- description: t('channel_creation_done'),
- });
- history.replace(ROUTES.ALL_CHANNELS);
- return { status: 'success', statusMessage: t('channel_creation_done') };
- } catch (error) {
- showErrorModal(error as APIError);
- return { status: 'failed', statusMessage: t('channel_creation_failed') };
- } finally {
- setSavingState(false);
- }
- }, [
- selectedConfig.webhook_url,
- notifications,
- t,
- prepareMsTeamsRequest,
- showErrorModal,
- ]);
-
- const validateGoogleChatConfig = useCallback((): boolean => {
- if (!selectedConfig.webhook_url) {
- notifications.error({
- message: 'Error',
- description: t('webhook_url_required'),
- });
- return false;
- }
-
- if (!isValidGoogleChatWebhookURL(selectedConfig.webhook_url)) {
- notifications.error({
- message: 'Error',
- description: t('google_chat_webhook_url_invalid'),
- });
- return false;
- }
-
- return true;
- }, [selectedConfig.webhook_url, notifications, t]);
-
- const onGoogleChatHandler = useCallback(async () => {
- if (!validateGoogleChatConfig()) {
- return { status: 'failed', statusMessage: t('channel_creation_failed') };
- }
-
- setSavingState(true);
-
- try {
- await createChannel({ data: prepareGoogleChatRequest(selectedConfig) });
- notifications.success({
- message: 'Success',
- description: t('channel_creation_done'),
- });
- history.replace(ROUTES.ALL_CHANNELS);
- return { status: 'success', statusMessage: t('channel_creation_done') };
- } catch (error) {
- showErrorModal(toAPIError(error as ErrorType<RenderErrorResponseDTO>));
- return { status: 'failed', statusMessage: t('channel_creation_failed') };
- } finally {
- setSavingState(false);
- }
- }, [
- validateGoogleChatConfig,
- createChannel,
- selectedConfig,
- notifications,
- t,
- showErrorModal,
- ]);
-
- const validateJiraConfig = useCallback((): boolean => {
- if (
- !selectedConfig.site ||
- !selectedConfig.username ||
- !selectedConfig.password ||
- !selectedConfig.project ||
- !selectedConfig.issue_type
- ) {
- notifications.error({
- message: 'Error',
- description: t('jira_required_fields'),
- });
- return false;
- }
-
- if (!isValidJiraSiteURL(selectedConfig.site)) {
- notifications.error({
- message: 'Error',
- description: t('jira_site_invalid'),
- });
- return false;
- }
-
- if (
- selectedConfig.reopen_duration &&
- !isValidJiraReopenDuration(selectedConfig.reopen_duration)
- ) {
- notifications.error({
- message: 'Error',
- description: t('jira_reopen_duration_invalid'),
- });
- return false;
- }
-
- return true;
- }, [selectedConfig, notifications, t]);
-
- const onJiraHandler = useCallback(async () => {
- if (!validateJiraConfig()) {
- return { status: 'failed', statusMessage: t('channel_creation_failed') };
- }
-
- setSavingState(true);
-
- try {
- await createChannel({ data: prepareJiraRequest(selectedConfig) });
- notifications.success({
- message: 'Success',
- description: t('channel_creation_done'),
- });
- history.replace(ROUTES.ALL_CHANNELS);
- return { status: 'success', statusMessage: t('channel_creation_done') };
- } catch (error) {
- showErrorModal(toAPIError(error as ErrorType<RenderErrorResponseDTO>));
- return { status: 'failed', statusMessage: t('channel_creation_failed') };
- } finally {
- setSavingState(false);
- }
- }, [
- validateJiraConfig,
- createChannel,
- selectedConfig,
- notifications,
- t,
- showErrorModal,
- ]);
-
- const validateJsmOpsConfig = useCallback((): boolean => {
- if (!selectedConfig.api_key) {
- notifications.error({
- message: 'Error',
- description: t('api_key_required'),
- });
- return false;
- }
- return true;
- }, [selectedConfig.api_key, notifications, t]);
-
- const onJsmOpsHandler = useCallback(async () => {
- if (!validateJsmOpsConfig()) {
- return { status: 'failed', statusMessage: t('channel_creation_failed') };
- }
-
- setSavingState(true);
-
- try {
- await createChannel({ data: prepareJsmOpsRequest(selectedConfig) });
- notifications.success({
- message: 'Success',
- description: t('channel_creation_done'),
- });
- history.replace(ROUTES.ALL_CHANNELS);
- return { status: 'success', statusMessage: t('channel_creation_done') };
- } catch (error) {
- showErrorModal(toAPIError(error as ErrorType<RenderErrorResponseDTO>));
- return { status: 'failed', statusMessage: t('channel_creation_failed') };
- } finally {
- setSavingState(false);
- }
- }, [
- validateJsmOpsConfig,
- createChannel,
- selectedConfig,
- notifications,
- t,
- showErrorModal,
- ]);
-
- const validateIncidentIOConfig = useCallback((): boolean => {
- if (!selectedConfig.url || !selectedConfig.token) {
- notifications.error({
- message: 'Error',
- description: t('incidentio_required_fields'),
- });
- return false;
- }
-
- if (!isValidIncidentIOURL(selectedConfig.url)) {
- notifications.error({
- message: 'Error',
- description: t('incidentio_url_invalid'),
- });
- return false;
- }
-
- return true;
- }, [selectedConfig.url, selectedConfig.token, notifications, t]);
-
- const onIncidentIOHandler = useCallback(async () => {
- if (!validateIncidentIOConfig()) {
- return { status: 'failed', statusMessage: t('channel_creation_failed') };
- }
-
- setSavingState(true);
-
- try {
- await createChannel({ data: prepareIncidentIORequest(selectedConfig) });
- notifications.success({
- message: 'Success',
- description: t('channel_creation_done'),
- });
- history.replace(ROUTES.ALL_CHANNELS);
- return { status: 'success', statusMessage: t('channel_creation_done') };
- } catch (error) {
- showErrorModal(toAPIError(error as ErrorType<RenderErrorResponseDTO>));
- return { status: 'failed', statusMessage: t('channel_creation_failed') };
- } finally {
- setSavingState(false);
- }
- }, [
- validateIncidentIOConfig,
- createChannel,
- selectedConfig,
- notifications,
- t,
- showErrorModal,
- ]);
-
- const onSaveHandler = useCallback(
- async (value: ChannelType) => {
- if (!selectedConfig.name) {
- notifications.error({
- message: 'Error',
- description: t('channel_name_required'),
- });
- return;
- }
-
- const functionMapper = {
- [ChannelType.Slack]: onSlackHandler,
- [ChannelType.Webhook]: onWebhookHandler,
- [ChannelType.Pagerduty]: onPagerHandler,
- [ChannelType.Opsgenie]: onOpsgenieHandler,
- [ChannelType.MsTeams]: onMsTeamsHandler,
- [ChannelType.Email]: onEmailHandler,
- [ChannelType.GoogleChat]: onGoogleChatHandler,
- [ChannelType.Jira]: onJiraHandler,
- [ChannelType.JsmOps]: onJsmOpsHandler,
- [ChannelType.IncidentIO]: onIncidentIOHandler,
- };
-
- if (isChannelType(value)) {
- const functionToCall = functionMapper[value as keyof typeof functionMapper];
-
- if (functionToCall) {
- const result = await functionToCall();
- logEvent('Alert Channel: Save channel', {
- type: value,
- sendResolvedAlert: selectedConfig?.send_resolved,
- name: selectedConfig?.name,
- new: 'true',
- status: result?.status,
- statusMessage: result?.statusMessage,
- });
- } else {
- notifications.error({
- message: 'Error',
- description: t('selected_channel_invalid'),
- });
- }
- }
- },
- // eslint-disable-next-line react-hooks/exhaustive-deps
- [
- onSlackHandler,
- onWebhookHandler,
- onPagerHandler,
- onOpsgenieHandler,
- onMsTeamsHandler,
- onEmailHandler,
- onGoogleChatHandler,
- onJiraHandler,
- onJsmOpsHandler,
- onIncidentIOHandler,
- notifications,
- t,
- ],
- );
-
- const performChannelTest = useCallback(
- async (channelType: ChannelType) => {
- setTestingState(true);
- try {
- let request;
- switch (channelType) {
- case ChannelType.Webhook:
- request = prepareWebhookRequest();
- await testWebhookApi(request);
- break;
- case ChannelType.Slack:
- request = prepareSlackRequest();
- await testSlackApi(request);
- break;
- case ChannelType.Pagerduty:
- request = preparePagerRequest();
- if (request) {
- await testPagerApi(request);
- }
- break;
- case ChannelType.MsTeams:
- request = prepareMsTeamsRequest();
- await testMsTeamsApi(request);
- break;
- case ChannelType.Opsgenie:
- request = prepareOpsgenieRequest();
- await testOpsGenie(request);
- break;
- case ChannelType.Email:
- request = prepareEmailRequest();
- await testEmail(request);
- break;
- case ChannelType.GoogleChat:
- if (!validateGoogleChatConfig()) {
- setTestingState(false);
- return;
- }
- await testChannel({ data: prepareGoogleChatRequest(selectedConfig) });
- break;
- case ChannelType.Jira:
- if (!validateJiraConfig()) {
- setTestingState(false);
- return;
- }
- await testChannel({ data: prepareJiraRequest(selectedConfig) });
- break;
- case ChannelType.JsmOps:
- if (!validateJsmOpsConfig()) {
- setTestingState(false);
- return;
- }
- await testChannel({ data: prepareJsmOpsRequest(selectedConfig) });
- break;
- case ChannelType.IncidentIO:
- if (!validateIncidentIOConfig()) {
- setTestingState(false);
- return;
- }
- await testChannel({ data: prepareIncidentIORequest(selectedConfig) });
- break;
- default:
- notifications.error({
- message: 'Error',
- description: t('test_unsupported'),
- });
- setTestingState(false);
- return;
- }
-
- notifications.success({
- message: 'Success',
- description: t('channel_test_done'),
- });
- logEvent('Alert Channel: Test notification', {
- type: channelType,
- sendResolvedAlert: selectedConfig?.send_resolved,
- name: selectedConfig?.name,
- new: 'true',
- status: 'Test success',
- });
- } catch (error) {
- showErrorModal(
- error instanceof APIError
- ? error
- : toAPIError(error as ErrorType<RenderErrorResponseDTO>),
- );
-
- logEvent('Alert Channel: Test notification', {
- type: channelType,
- sendResolvedAlert: selectedConfig?.send_resolved,
- name: selectedConfig?.name,
- new: 'true',
- status: 'Test failed',
- });
- }
-
- setTestingState(false);
- },
- // eslint-disable-next-line react-hooks/exhaustive-deps
- [
- prepareWebhookRequest,
- t,
- preparePagerRequest,
- prepareOpsgenieRequest,
- prepareSlackRequest,
- prepareMsTeamsRequest,
- prepareEmailRequest,
- validateGoogleChatConfig,
- validateJiraConfig,
- validateJsmOpsConfig,
- validateIncidentIOConfig,
- testChannel,
- notifications,
- ],
- );
-
- const onTestHandler = useCallback(
- async (value: ChannelType) => {
- performChannelTest(value);
- },
- [performChannelTest],
- );
-
- return (
- <div className="create-alert-channels-container">
- <FormAlertChannels
- {...{
- formInstance,
- onTypeChangeHandler,
- setSelectedConfig,
- type,
- onTestHandler,
- onSaveHandler,
- savingState,
- testingState,
- title: t('page_title_create'),
- initialValue: {
- type,
- ...selectedConfig,
- },
- }}
- />
- </div>
- );
-}
-
-interface CreateAlertChannelsProps {
- preType: ChannelType;
-}
-
-export default CreateAlertChannels;
diff --git a/frontend/src/container/CreateAlertChannels/schemas/email.ts b/frontend/src/container/CreateAlertChannels/schemas/email.ts
new file mode 100644
index 0000000000..adcb506aea
--- /dev/null
+++ b/frontend/src/container/CreateAlertChannels/schemas/email.ts
@@ -0,0 +1,7 @@
+import { z } from 'zod';
+
+import { requiredString } from './shared';
+
+export const emailSchema = z.object({
+ to: requiredString('to_required'),
+});
diff --git a/frontend/src/container/CreateAlertChannels/schemas/googlechat.ts b/frontend/src/container/CreateAlertChannels/schemas/googlechat.ts
new file mode 100644
index 0000000000..2eb7efc93b
--- /dev/null
+++ b/frontend/src/container/CreateAlertChannels/schemas/googlechat.ts
@@ -0,0 +1,11 @@
+import { z } from 'zod';
+
+import { isValidGoogleChatWebhookURL } from '../utils';
+import { requiredString } from './shared';
+
+export const googleChatSchema = z.object({
+ webhookUrl: requiredString('webhook_url_required').refine(
+ isValidGoogleChatWebhookURL,
+ { message: 'google_chat_webhook_url_invalid' },
+ ),
+});
diff --git a/frontend/src/container/CreateAlertChannels/schemas/incidentio.ts b/frontend/src/container/CreateAlertChannels/schemas/incidentio.ts
new file mode 100644
index 0000000000..4f74c95e73
--- /dev/null
+++ b/frontend/src/container/CreateAlertChannels/schemas/incidentio.ts
@@ -0,0 +1,13 @@
+import { z } from 'zod';
+
+import { isValidIncidentIOURL } from '../utils';
+import { requiredString } from './shared';
+
+const required = requiredString('incidentio_required_fields');
+
+export const incidentIOSchema = z.object({
+ url: required.refine(isValidIncidentIOURL, {
+ message: 'incidentio_url_invalid',
+ }),
+ token: required,
+});
diff --git a/frontend/src/container/CreateAlertChannels/schemas/jira.ts b/frontend/src/container/CreateAlertChannels/schemas/jira.ts
new file mode 100644
index 0000000000..0062dec473
--- /dev/null
+++ b/frontend/src/container/CreateAlertChannels/schemas/jira.ts
@@ -0,0 +1,20 @@
+import { z } from 'zod';
+
+import { isValidJiraReopenDuration, isValidJiraSiteURL } from '../utils';
+import { requiredString } from './shared';
+
+const required = requiredString('jira_required_fields');
+
+export const jiraSchema = z.object({
+ site: required.refine(isValidJiraSiteURL, { message: 'jira_site_invalid' }),
+ email: required,
+ apiToken: required,
+ project: required,
+ issueType: required,
+ reopenDuration: z
+ .string()
+ .optional()
+ .refine((v) => !v || isValidJiraReopenDuration(v), {
+ message: 'jira_reopen_duration_invalid',
+ }),
+});
diff --git a/frontend/src/container/CreateAlertChannels/schemas/jsmops.ts b/frontend/src/container/CreateAlertChannels/schemas/jsmops.ts
new file mode 100644
index 0000000000..bf8b16d175
--- /dev/null
+++ b/frontend/src/container/CreateAlertChannels/schemas/jsmops.ts
@@ -0,0 +1,7 @@
+import { z } from 'zod';
+
+import { requiredString } from './shared';
+
+export const jsmOpsSchema = z.object({
+ apiKey: requiredString('api_key_required'),
+});
diff --git a/frontend/src/container/CreateAlertChannels/schemas/msteams.ts b/frontend/src/container/CreateAlertChannels/schemas/msteams.ts
new file mode 100644
index 0000000000..5221f5c9a1
--- /dev/null
+++ b/frontend/src/container/CreateAlertChannels/schemas/msteams.ts
@@ -0,0 +1,7 @@
+import { z } from 'zod';
+
+import { requiredString } from './shared';
+
+export const msTeamsSchema = z.object({
+ webhookUrl: requiredString('webhook_url_required'),
+});
diff --git a/frontend/src/container/CreateAlertChannels/schemas/opsgenie.ts b/frontend/src/container/CreateAlertChannels/schemas/opsgenie.ts
new file mode 100644
index 0000000000..a1bb76d248
--- /dev/null
+++ b/frontend/src/container/CreateAlertChannels/schemas/opsgenie.ts
@@ -0,0 +1,7 @@
+import { z } from 'zod';
+
+import { requiredString } from './shared';
+
+export const opsgenieSchema = z.object({
+ apiKey: requiredString('api_key_required'),
+});
diff --git a/frontend/src/container/CreateAlertChannels/schemas/pagerduty.ts b/frontend/src/container/CreateAlertChannels/schemas/pagerduty.ts
new file mode 100644
index 0000000000..9bf7610cf4
--- /dev/null
+++ b/frontend/src/container/CreateAlertChannels/schemas/pagerduty.ts
@@ -0,0 +1,7 @@
+import { z } from 'zod';
+
+import { requiredString } from './shared';
+
+export const pagerdutySchema = z.object({
+ routingKey: requiredString('routing_key_required'),
+});
diff --git a/frontend/src/container/CreateAlertChannels/schemas/shared.ts b/frontend/src/container/CreateAlertChannels/schemas/shared.ts
new file mode 100644
index 0000000000..c029e7538b
--- /dev/null
+++ b/frontend/src/container/CreateAlertChannels/schemas/shared.ts
@@ -0,0 +1,10 @@
+import { z } from 'zod';
+
+export const requiredString = (messageKey: string): z.ZodString =>
+ // an untouched field arrives as undefined, which would otherwise report zod's
+ // own "expected string" instead of the message the form should show
+ z.string({ error: messageKey }).trim().min(1, messageKey);
+
+export const channelNameSchema = z.object({
+ name: requiredString('channel_name_required'),
+});
diff --git a/frontend/src/container/CreateAlertChannels/schemas/slack.ts b/frontend/src/container/CreateAlertChannels/schemas/slack.ts
new file mode 100644
index 0000000000..46501cb2de
--- /dev/null
+++ b/frontend/src/container/CreateAlertChannels/schemas/slack.ts
@@ -0,0 +1,7 @@
+import { z } from 'zod';
+
+import { requiredString } from './shared';
+
+export const slackSchema = z.object({
+ apiUrl: requiredString('webhook_url_required'),
+});
diff --git a/frontend/src/container/CreateAlertChannels/schemas/telegram.ts b/frontend/src/container/CreateAlertChannels/schemas/telegram.ts
new file mode 100644
index 0000000000..868e095d89
--- /dev/null
+++ b/frontend/src/container/CreateAlertChannels/schemas/telegram.ts
@@ -0,0 +1,11 @@
+import { z } from 'zod';
+
+import { requiredString } from './shared';
+
+export const telegramSchema = z.object({
+ botToken: requiredString('bot_token_required'),
+ // the backend reads 0 as missing, and omitBlank deliberately keeps 0
+ chatId: z
+ .number({ error: 'chat_id_required' })
+ .refine((value) => value !== 0, { error: 'chat_id_required' }),
+});
diff --git a/frontend/src/container/CreateAlertChannels/schemas/webhook.ts b/frontend/src/container/CreateAlertChannels/schemas/webhook.ts
new file mode 100644
index 0000000000..377c8455b0
--- /dev/null
+++ b/frontend/src/container/CreateAlertChannels/schemas/webhook.ts
@@ -0,0 +1,16 @@
+import { z } from 'zod';
+
+import { requiredString } from './shared';
+
+export const webhookSchema = z
+ .object({
+ url: requiredString('webhook_url_required'),
+ username: z.string().optional(),
+ password: z.string().optional(),
+ })
+ // the API allows bearer-only and no-auth webhooks, but a username without its
+ // password is still an incomplete basic auth pair
+ .refine((v) => !v.username || !!v.password, {
+ message: 'username_no_password',
+ path: ['password'],
+ });
diff --git a/frontend/src/container/CreateAlertChannels/types.ts b/frontend/src/container/CreateAlertChannels/types.ts
new file mode 100644
index 0000000000..e1151263fe
--- /dev/null
+++ b/frontend/src/container/CreateAlertChannels/types.ts
@@ -0,0 +1,36 @@
+import {
+ AlertmanagertypesChannelEmailConfigDTO,
+ AlertmanagertypesChannelGoogleChatConfigDTO,
+ AlertmanagertypesChannelIncidentIOConfigDTO,
+ AlertmanagertypesChannelJiraConfigDTO,
+ AlertmanagertypesChannelJSMOpsConfigDTO,
+ AlertmanagertypesChannelKindDTO,
+ AlertmanagertypesChannelMSTeamsConfigDTO,
+ AlertmanagertypesChannelOpsgenieConfigDTO,
+ AlertmanagertypesChannelPagerdutyConfigDTO,
+ AlertmanagertypesChannelSlackConfigDTO,
+ AlertmanagertypesChannelTelegramConfigDTO,
+ AlertmanagertypesChannelWebhookConfigDTO,
+} from 'api/generated/services/sigNoz.schemas';
+
+export const ChannelKind = AlertmanagertypesChannelKindDTO;
+export type ChannelKind = AlertmanagertypesChannelKindDTO;
+
+/** Merged so switching kind keeps the fields the kinds share. */
+export type ChannelSpecFormValues = Partial<
+ AlertmanagertypesChannelSlackConfigDTO &
+ AlertmanagertypesChannelWebhookConfigDTO &
+ AlertmanagertypesChannelEmailConfigDTO &
+ AlertmanagertypesChannelPagerdutyConfigDTO &
+ AlertmanagertypesChannelOpsgenieConfigDTO &
+ AlertmanagertypesChannelMSTeamsConfigDTO &
+ AlertmanagertypesChannelGoogleChatConfigDTO &
+ AlertmanagertypesChannelJiraConfigDTO &
+ AlertmanagertypesChannelJSMOpsConfigDTO &
+ AlertmanagertypesChannelIncidentIOConfigDTO &
+ AlertmanagertypesChannelTelegramConfigDTO
+>;
+
+export type ChannelFormValues = ChannelSpecFormValues & {
+ name?: string;
+};
diff --git a/frontend/src/container/CreateAlertChannels/utils.ts b/frontend/src/container/CreateAlertChannels/utils.ts
index 05512836cf..0beaa0b6a3 100644
--- a/frontend/src/container/CreateAlertChannels/utils.ts
+++ b/frontend/src/container/CreateAlertChannels/utils.ts
@@ -1,26 +1,5 @@
-import {
- AlertmanagertypesIncidentIOReceiverConfigDTO,
- AlertmanagertypesJiraReceiverConfigDTO,
- AlertmanagertypesJSMOpsReceiverConfigDTO,
- AlertmanagertypesPostableChannelDTO,
- ConfigSecretURLDTO,
- ModelDurationDTO,
-} from 'api/generated/services/sigNoz.schemas';
-
-import {
- ChannelType,
- GoogleChatChannel,
- IncidentIOChannel,
- JiraChannel,
- JsmOpsChannel,
-} from './config';
-
-export const isChannelType = (type: string): type is ChannelType =>
- Object.values(ChannelType).includes(type as ChannelType);
-
const GOOGLE_CHAT_WEBHOOK_HOST = 'chat.googleapis.com';
-// the backend enforces the same two rules, this is only for a nicer error experience
export const isValidGoogleChatWebhookURL = (url: string): boolean => {
try {
const { protocol, hostname } = new URL(url);
@@ -32,25 +11,8 @@ export const isValidGoogleChatWebhookURL = (url: string): boolean => {
}
};
-// create, update and test all send the same body shape
-export const prepareGoogleChatRequest = (
- config: Partial<GoogleChatChannel>,
-): AlertmanagertypesPostableChannelDTO => ({
- name: config.name || '',
- googlechat_configs: [
- {
- // the generated type models go's config.SecretURL as an object, the api takes a string
- webhook_url: (config.webhook_url || '') as unknown as ConfigSecretURLDTO,
- title: config.title || '',
- text: config.text || '',
- send_resolved: config.send_resolved || false,
- },
- ],
-});
-
const JIRA_CLOUD_HOST_SUFFIX = '.atlassian.net';
-// the backend enforces the same rule, this is only for a nicer error experience
export const isValidJiraSiteURL = (url: string): boolean => {
try {
const { protocol, hostname } = new URL(url);
@@ -77,8 +39,6 @@ const JIRA_DURATION_RE = /^(\d+(ms|s|m|h|d|w|y))+$/;
const JIRA_DURATION_TOKEN_RE = /(\d+)(ms|s|m|h|d|w|y)/g;
const JIRA_MIN_REOPEN_MS = 60_000;
-// backend requires the same format and a >= 1m minimum, this is only for a
-// nicer error experience. Empty and "0" defer to the backend default.
export const isValidJiraReopenDuration = (value: string): boolean => {
if (!value || value === '0') {
return true;
@@ -93,85 +53,45 @@ export const isValidJiraReopenDuration = (value: string): boolean => {
return totalMs >= JIRA_MIN_REOPEN_MS;
};
-// create, update and test all send the same body shape. Optional fields are
-// omitted when empty so the backend applies its defaults.
-export const prepareJiraRequest = (
- config: Partial<JiraChannel>,
-): AlertmanagertypesPostableChannelDTO => {
- const jira: AlertmanagertypesJiraReceiverConfigDTO = {
- site: config.site || '',
- project: config.project || '',
- issue_type: config.issue_type || '',
- send_resolved: config.send_resolved || false,
- http_config: {
- basic_auth: {
- username: config.username || '',
- password: config.password || '',
- },
- },
- };
-
- if (config.summary) {
- jira.summary = config.summary;
- }
- if (config.description) {
- jira.description = config.description;
- }
- if (config.priority) {
- jira.priority = config.priority;
- }
- if (config.labels?.length) {
- jira.labels = config.labels;
- }
- if (config.resolve_transition) {
- jira.resolve_transition = config.resolve_transition;
- }
- if (config.reopen_transition) {
- jira.reopen_transition = config.reopen_transition;
- }
- if (config.wont_fix_resolution) {
- jira.wont_fix_resolution = config.wont_fix_resolution;
- }
- if (config.reopen_duration) {
- // the generated type models go's model.Duration as a number, the api takes a
- // duration string like "72h"
- jira.reopen_duration = config.reopen_duration as unknown as ModelDurationDTO;
- }
-
- return {
- name: config.name || '',
- jira_configs: [jira],
- };
-};
-
-// create, update and test all send the same body shape. Optional fields are
-// omitted when empty so the backend applies its defaults.
-export const prepareJsmOpsRequest = (
- config: Partial<JsmOpsChannel>,
-): AlertmanagertypesPostableChannelDTO => {
- const jsmops: AlertmanagertypesJSMOpsReceiverConfigDTO = {
- api_key: config.api_key || '',
- send_resolved: config.send_resolved || false,
- };
-
- if (config.message) {
- jsmops.message = config.message;
- }
- if (config.description) {
- jsmops.description = config.description;
- }
- if (config.priority) {
- jsmops.priority = config.priority;
- }
- if (config.tags?.length) {
- // the backend takes a comma-separated string and splits it back
- jsmops.tags = config.tags.join(',');
- }
-
- return {
- name: config.name || '',
- jsmops_configs: [jsmops],
- };
+/**
+ * How prometheus `model.Duration` prints itself, the only spelling the API takes
+ * back: "72h" becomes "3d", "7d" becomes "1w".
+ */
+const JIRA_DURATION_FORMAT: { unit: string; ms: number; exact: boolean }[] = [
+ { unit: 'y', ms: JIRA_DURATION_UNIT_MS.y, exact: true },
+ { unit: 'w', ms: JIRA_DURATION_UNIT_MS.w, exact: true },
+ { unit: 'd', ms: JIRA_DURATION_UNIT_MS.d, exact: false },
+ { unit: 'h', ms: JIRA_DURATION_UNIT_MS.h, exact: false },
+ { unit: 'm', ms: JIRA_DURATION_UNIT_MS.m, exact: false },
+ { unit: 's', ms: JIRA_DURATION_UNIT_MS.s, exact: false },
+ { unit: 'ms', ms: JIRA_DURATION_UNIT_MS.ms, exact: false },
+];
+
+/** The API rejects a duration it would print differently. */
+export const canonicalJiraReopenDuration = (value: string): string => {
+ if (!value || value === '0' || !JIRA_DURATION_RE.test(value)) {
+ return value;
+ }
+
+ let remaining = 0;
+ for (const [, amount, unit] of value.matchAll(JIRA_DURATION_TOKEN_RE)) {
+ remaining += Number(amount) * JIRA_DURATION_UNIT_MS[unit];
+ }
+ if (remaining === 0) {
+ return '0s';
+ }
+
+ return JIRA_DURATION_FORMAT.reduce((canonical, { unit, ms, exact }) => {
+ if (exact && remaining % ms !== 0) {
+ return canonical;
+ }
+ const count = Math.floor(remaining / ms);
+ if (count === 0) {
+ return canonical;
+ }
+ remaining -= count * ms;
+ return `${canonical}${count}${unit}`;
+ }, '');
};
const INCIDENTIO_EVENTS_PATH_PREFIX = '/v2/alert_events/http/';
@@ -191,32 +111,8 @@ export const isValidIncidentIOURL = (url: string): boolean => {
}
};
-// create, update and test all send the same body shape. Optional fields are
-// omitted when empty so the backend applies its defaults.
-export const prepareIncidentIORequest = (
- config: Partial<IncidentIOChannel>,
-): AlertmanagertypesPostableChannelDTO => {
- const incidentio: AlertmanagertypesIncidentIOReceiverConfigDTO = {
- url: config.url || '',
- token: config.token || '',
- send_resolved: config.send_resolved || false,
- };
-
- if (config.title) {
- incidentio.title = config.title;
- }
- if (config.description) {
- incidentio.description = config.description;
- }
- const metadata = Object.fromEntries(
- Object.entries(config.metadata || {}).filter(([key]) => key.trim() !== ''),
- );
- if (Object.keys(metadata).length > 0) {
- incidentio.metadata = metadata;
- }
-
- return {
- name: config.name || '',
- incidentio_configs: [incidentio],
- };
-};
+export const filledRows = <T>(
+ rows: T[] | null | undefined,
+ required: keyof T,
+): T[] =>
+ (rows ?? []).filter((row) => String(row[required] ?? '').trim() !== '');
diff --git a/frontend/src/container/CreateAlertChannels/validation.ts b/frontend/src/container/CreateAlertChannels/validation.ts
new file mode 100644
index 0000000000..e987d7f72f
--- /dev/null
+++ b/frontend/src/container/CreateAlertChannels/validation.ts
@@ -0,0 +1,49 @@
+import { TFunction } from 'i18next';
+import type { ZodType } from 'zod';
+
+import { emailSchema } from './schemas/email';
+import { googleChatSchema } from './schemas/googlechat';
+import { incidentIOSchema } from './schemas/incidentio';
+import { jiraSchema } from './schemas/jira';
+import { jsmOpsSchema } from './schemas/jsmops';
+import { msTeamsSchema } from './schemas/msteams';
+import { opsgenieSchema } from './schemas/opsgenie';
+import { pagerdutySchema } from './schemas/pagerduty';
+import { channelNameSchema } from './schemas/shared';
+import { slackSchema } from './schemas/slack';
+import { telegramSchema } from './schemas/telegram';
+import { webhookSchema } from './schemas/webhook';
+import { ChannelFormValues, ChannelKind } from './types';
+
+export const CHANNEL_SCHEMAS: Record<ChannelKind, ZodType> = {
+ [ChannelKind.slack]: slackSchema,
+ [ChannelKind.webhook]: webhookSchema,
+ [ChannelKind.pagerduty]: pagerdutySchema,
+ [ChannelKind.opsgenie]: opsgenieSchema,
+ [ChannelKind.jsmops]: jsmOpsSchema,
+ [ChannelKind.email]: emailSchema,
+ [ChannelKind.msteams]: msTeamsSchema,
+ [ChannelKind.googlechat]: googleChatSchema,
+ [ChannelKind.jira]: jiraSchema,
+ [ChannelKind.incidentio]: incidentIOSchema,
+ [ChannelKind.telegram]: telegramSchema,
+};
+
+export function validateChannel(
+ kind: ChannelKind,
+ values: ChannelFormValues,
+ t: TFunction,
+): string | null {
+ const nameResult = channelNameSchema.safeParse(values);
+ if (!nameResult.success) {
+ return t(nameResult.error.issues[0].message);
+ }
+
+ const schema = CHANNEL_SCHEMAS[kind];
+ if (!schema) {
+ return t('selected_channel_invalid');
+ }
+
+ const result = schema.safeParse(values);
+ return result.success ? null : t(result.error.issues[0].message);
+}
diff --git a/frontend/src/container/EditAlertChannels/index.tsx b/frontend/src/container/EditAlertChannels/index.tsx
deleted file mode 100644
index 922f57b2f3..0000000000
--- a/frontend/src/container/EditAlertChannels/index.tsx
+++ /dev/null
@@ -1,863 +0,0 @@
-import { useCallback, useEffect, useState } from 'react';
-import { useTranslation } from 'react-i18next';
-import { Form } from 'antd';
-import editEmail from 'api/channels/editEmail';
-import editMsTeamsApi from 'api/channels/editMsTeams';
-import editOpsgenie from 'api/channels/editOpsgenie';
-import editPagerApi from 'api/channels/editPager';
-import editSlackApi from 'api/channels/editSlack';
-import editWebhookApi from 'api/channels/editWebhook';
-import testEmail from 'api/channels/testEmail';
-import testMsTeamsApi from 'api/channels/testMsTeams';
-import testOpsgenie from 'api/channels/testOpsgenie';
-import testPagerApi from 'api/channels/testPager';
-import testSlackApi from 'api/channels/testSlack';
-import testWebhookApi from 'api/channels/testWebhook';
-import logEvent from 'api/common/logEvent';
-import {
- useTestChannel,
- useUpdateChannelByID,
-} from 'api/generated/services/channels';
-import { RenderErrorResponseDTO } from 'api/generated/services/sigNoz.schemas';
-import { ErrorType } from 'api/generatedAPIInstance';
-import ROUTES from 'constants/routes';
-import {
- ChannelType,
- EmailChannel,
- GoogleChatChannel,
- IncidentIOChannel,
- JiraChannel,
- JsmOpsChannel,
- MsTeamsChannel,
- OpsgenieChannel,
- PagerChannel,
- SlackChannel,
- ValidatePagerChannel,
- WebhookChannel,
-} from 'container/CreateAlertChannels/config';
-import {
- isValidGoogleChatWebhookURL,
- isValidIncidentIOURL,
- isValidJiraReopenDuration,
- isValidJiraSiteURL,
- prepareGoogleChatRequest,
- prepareIncidentIORequest,
- prepareJiraRequest,
- prepareJsmOpsRequest,
-} from 'container/CreateAlertChannels/utils';
-import FormAlertChannels from 'container/FormAlertChannels';
-import { useNotifications } from 'hooks/useNotifications';
-import history from 'lib/history';
-import APIError from 'types/api/error';
-import { toAPIError } from 'utils/errorUtils';
-
-function EditAlertChannels({
- initialValue,
- channelId: id,
-}: EditAlertChannelsProps): JSX.Element {
- // init namespace for translations
- const { t } = useTranslation('channels');
-
- const [formInstance] = Form.useForm();
- const [selectedConfig, setSelectedConfig] = useState<
- Partial<
- SlackChannel &
- WebhookChannel &
- PagerChannel &
- MsTeamsChannel &
- OpsgenieChannel &
- EmailChannel &
- GoogleChatChannel &
- JiraChannel &
- JsmOpsChannel &
- IncidentIOChannel
- >
- >({
- ...initialValue,
- });
- const [savingState, setSavingState] = useState<boolean>(false);
- const [testingState, setTestingState] = useState<boolean>(false);
- const { notifications } = useNotifications();
-
- const { mutateAsync: updateChannel } = useUpdateChannelByID();
- const { mutateAsync: testChannel } = useTestChannel();
-
- const notifyError = useCallback(
- (error: unknown): APIError => {
- const apiError =
- error instanceof APIError
- ? error
- : toAPIError(error as ErrorType<RenderErrorResponseDTO>);
-
- notifications.error({
- message: apiError.getErrorCode(),
- description: apiError.getErrorMessage(),
- });
-
- return apiError;
- },
- [notifications],
- );
-
- const [type, setType] = useState<ChannelType>(
- initialValue?.type ? (initialValue.type as ChannelType) : ChannelType.Slack,
- );
-
- const onTypeChangeHandler = useCallback((value: string) => {
- setType(value as ChannelType);
- }, []);
-
- useEffect(() => {
- formInstance.setFieldsValue({
- ...initialValue,
- });
- }, [formInstance, initialValue]);
-
- const prepareSlackRequest = useCallback(
- () => ({
- api_url: selectedConfig?.api_url || '',
- channel: selectedConfig?.channel || '',
- name: selectedConfig?.name || '',
- send_resolved: selectedConfig?.send_resolved || false,
- text: selectedConfig?.text || '',
- title: selectedConfig?.title || '',
- id,
- }),
- [id, selectedConfig],
- );
-
- const onSlackEditHandler = useCallback(async () => {
- setSavingState(true);
-
- if (selectedConfig?.api_url === '') {
- notifications.error({
- message: 'Error',
- description: t('webhook_url_required'),
- });
- setSavingState(false);
- return { status: 'failed', statusMessage: t('webhook_url_required') };
- }
-
- try {
- await editSlackApi(prepareSlackRequest());
- notifications.success({
- message: 'Success',
- description: t('channel_edit_done'),
- });
-
- history.replace(ROUTES.ALL_CHANNELS);
- return { status: 'success', statusMessage: t('channel_edit_done') };
- } catch (error) {
- notifications.error({
- message: (error as APIError).getErrorCode(),
- description: (error as APIError).getErrorMessage(),
- });
- return {
- status: 'failed',
- statusMessage:
- (error as APIError).getErrorMessage() || t('channel_edit_failed'),
- };
- } finally {
- setSavingState(false);
- }
- }, [prepareSlackRequest, t, notifications, selectedConfig]);
-
- const prepareWebhookRequest = useCallback(() => {
- const { name, username, password } = selectedConfig;
- return {
- api_url: selectedConfig?.api_url || '',
- name: name || '',
- send_resolved: selectedConfig?.send_resolved || false,
- username,
- password,
- id,
- };
- }, [id, selectedConfig]);
-
- const onWebhookEditHandler = useCallback(async () => {
- setSavingState(true);
- const { username, password } = selectedConfig;
-
- const showError = (msg: string): void => {
- notifications.error({
- message: 'Error',
- description: msg,
- });
- };
-
- if (selectedConfig?.api_url === '') {
- showError(t('webhook_url_required'));
- setSavingState(false);
- return { status: 'failed', statusMessage: t('webhook_url_required') };
- }
-
- if (username && (!password || password === '')) {
- showError(t('username_no_password'));
- setSavingState(false);
- return { status: 'failed', statusMessage: t('username_no_password') };
- }
-
- try {
- await editWebhookApi(prepareWebhookRequest());
- notifications.success({
- message: 'Success',
- description: t('channel_edit_done'),
- });
-
- history.replace(ROUTES.ALL_CHANNELS);
- return { status: 'success', statusMessage: t('channel_edit_done') };
- } catch (error) {
- notifications.error({
- message: (error as APIError).getErrorCode(),
- description: (error as APIError).getErrorMessage(),
- });
- return {
- status: 'failed',
- statusMessage:
- (error as APIError).getErrorMessage() || t('channel_edit_failed'),
- };
- } finally {
- setSavingState(false);
- }
- }, [prepareWebhookRequest, t, notifications, selectedConfig]);
-
- const prepareEmailRequest = useCallback(
- () => ({
- name: selectedConfig?.name || '',
- send_resolved: selectedConfig?.send_resolved || false,
- to: selectedConfig.to || '',
- html: selectedConfig.html || '',
- headers: selectedConfig.headers || {},
- id,
- }),
- [id, selectedConfig],
- );
-
- const onEmailEditHandler = useCallback(async () => {
- setSavingState(true);
- const request = prepareEmailRequest();
-
- try {
- await editEmail(request);
- notifications.success({
- message: 'Success',
- description: t('channel_edit_done'),
- });
- history.replace(ROUTES.ALL_CHANNELS);
- return { status: 'success', statusMessage: t('channel_edit_done') };
- } catch (error) {
- notifications.error({
- message: (error as APIError).getErrorCode(),
- description: (error as APIError).getErrorMessage(),
- });
- return {
- status: 'failed',
- statusMessage:
- (error as APIError).getErrorMessage() || t('channel_edit_failed'),
- };
- } finally {
- setSavingState(false);
- }
- }, [prepareEmailRequest, t, notifications]);
-
- const preparePagerRequest = useCallback(
- () => ({
- name: selectedConfig.name || '',
- send_resolved: selectedConfig?.send_resolved || false,
- routing_key: selectedConfig.routing_key,
- client: selectedConfig.client,
- client_url: selectedConfig.client_url,
- description: selectedConfig.description,
- severity: selectedConfig.severity,
- component: selectedConfig.component,
- class: selectedConfig.class,
- group: selectedConfig.group,
- details: selectedConfig.details,
- detailsArray: JSON.parse(selectedConfig.details || '{}'),
- id,
- }),
- [id, selectedConfig],
- );
-
- const onPagerEditHandler = useCallback(async () => {
- setSavingState(true);
- const validationError = ValidatePagerChannel(selectedConfig as PagerChannel);
-
- if (validationError !== '') {
- notifications.error({
- message: 'Error',
- description: validationError,
- });
- setSavingState(false);
- return { status: 'failed', statusMessage: validationError };
- }
-
- try {
- await editPagerApi(preparePagerRequest());
- notifications.success({
- message: 'Success',
- description: t('channel_edit_done'),
- });
- history.replace(ROUTES.ALL_CHANNELS);
- return { status: 'success', statusMessage: t('channel_edit_done') };
- } catch (error) {
- notifications.error({
- message: (error as APIError).getErrorCode(),
- description: (error as APIError).getErrorMessage(),
- });
- return {
- status: 'failed',
- statusMessage:
- (error as APIError).getErrorMessage() || t('channel_edit_failed'),
- };
- } finally {
- setSavingState(false);
- }
- }, [preparePagerRequest, notifications, selectedConfig, t]);
-
- const prepareOpsgenieRequest = useCallback(
- () => ({
- name: selectedConfig.name || '',
- send_resolved: selectedConfig?.send_resolved || false,
- api_key: selectedConfig.api_key || '',
- message: selectedConfig.message || '',
- description: selectedConfig.description || '',
- priority: selectedConfig.priority || '',
- id,
- }),
- [id, selectedConfig],
- );
-
- const onOpsgenieEditHandler = useCallback(async () => {
- setSavingState(true);
-
- if (selectedConfig?.api_key === '') {
- notifications.error({
- message: 'Error',
- description: t('api_key_required'),
- });
- setSavingState(false);
- return { status: 'failed', statusMessage: t('api_key_required') };
- }
- try {
- await editOpsgenie(prepareOpsgenieRequest());
- notifications.success({
- message: 'Success',
- description: t('channel_edit_done'),
- });
- history.replace(ROUTES.ALL_CHANNELS);
- return { status: 'success', statusMessage: t('channel_edit_done') };
- } catch (error) {
- notifications.error({
- message: (error as APIError).getErrorCode(),
- description: (error as APIError).getErrorMessage(),
- });
- return {
- status: 'failed',
- statusMessage:
- (error as APIError).getErrorMessage() || t('channel_edit_failed'),
- };
- } finally {
- setSavingState(false);
- }
- }, [prepareOpsgenieRequest, t, notifications, selectedConfig]);
-
- const prepareMsTeamsRequest = useCallback(
- () => ({
- webhook_url: selectedConfig?.webhook_url || '',
- name: selectedConfig?.name || '',
- send_resolved: selectedConfig?.send_resolved || false,
- text: selectedConfig?.text || '',
- title: selectedConfig?.title || '',
- id,
- }),
- [id, selectedConfig],
- );
-
- const onMsTeamsEditHandler = useCallback(async () => {
- setSavingState(true);
-
- if (selectedConfig?.webhook_url === '') {
- notifications.error({
- message: 'Error',
- description: t('webhook_url_required'),
- });
- setSavingState(false);
- return { status: 'failed', statusMessage: t('webhook_url_required') };
- }
-
- try {
- await editMsTeamsApi(prepareMsTeamsRequest());
- notifications.success({
- message: 'Success',
- description: t('channel_edit_done'),
- });
- history.replace(ROUTES.ALL_CHANNELS);
- return { status: 'success', statusMessage: t('channel_edit_done') };
- } catch (error) {
- notifications.error({
- message: (error as APIError).getErrorCode(),
- description: (error as APIError).getErrorMessage(),
- });
- return {
- status: 'failed',
- statusMessage:
- (error as APIError).getErrorMessage() || t('channel_edit_failed'),
- };
- } finally {
- setSavingState(false);
- }
- }, [prepareMsTeamsRequest, t, notifications, selectedConfig]);
-
- const validateGoogleChatConfig = useCallback((): string => {
- if (!selectedConfig?.webhook_url) {
- return t('webhook_url_required');
- }
-
- if (!isValidGoogleChatWebhookURL(selectedConfig.webhook_url)) {
- return t('google_chat_webhook_url_invalid');
- }
-
- return '';
- }, [selectedConfig, t]);
-
- const onGoogleChatEditHandler = useCallback(async () => {
- const validationError = validateGoogleChatConfig();
-
- if (validationError !== '') {
- notifications.error({
- message: 'Error',
- description: validationError,
- });
- return { status: 'failed', statusMessage: validationError };
- }
-
- setSavingState(true);
-
- try {
- await updateChannel({
- pathParams: { id },
- data: prepareGoogleChatRequest(selectedConfig),
- });
- notifications.success({
- message: 'Success',
- description: t('channel_edit_done'),
- });
- history.replace(ROUTES.ALL_CHANNELS);
- return { status: 'success', statusMessage: t('channel_edit_done') };
- } catch (error) {
- const apiError = notifyError(error);
- return {
- status: 'failed',
- statusMessage: apiError.getErrorMessage() || t('channel_edit_failed'),
- };
- } finally {
- setSavingState(false);
- }
- }, [
- validateGoogleChatConfig,
- updateChannel,
- id,
- selectedConfig,
- notifications,
- notifyError,
- t,
- ]);
-
- const validateJiraConfig = useCallback((): string => {
- if (
- !selectedConfig.site ||
- !selectedConfig.username ||
- !selectedConfig.password ||
- !selectedConfig.project ||
- !selectedConfig.issue_type
- ) {
- return t('jira_required_fields');
- }
-
- if (!isValidJiraSiteURL(selectedConfig.site)) {
- return t('jira_site_invalid');
- }
-
- if (
- selectedConfig.reopen_duration &&
- !isValidJiraReopenDuration(selectedConfig.reopen_duration)
- ) {
- return t('jira_reopen_duration_invalid');
- }
-
- return '';
- }, [selectedConfig, t]);
-
- const onJiraEditHandler = useCallback(async () => {
- const validationError = validateJiraConfig();
-
- if (validationError !== '') {
- notifications.error({
- message: 'Error',
- description: validationError,
- });
- return { status: 'failed', statusMessage: validationError };
- }
-
- setSavingState(true);
-
- try {
- await updateChannel({
- pathParams: { id },
- data: prepareJiraRequest(selectedConfig),
- });
- notifications.success({
- message: 'Success',
- description: t('channel_edit_done'),
- });
- history.replace(ROUTES.ALL_CHANNELS);
- return { status: 'success', statusMessage: t('channel_edit_done') };
- } catch (error) {
- const apiError = notifyError(error);
- return {
- status: 'failed',
- statusMessage: apiError.getErrorMessage() || t('channel_edit_failed'),
- };
- } finally {
- setSavingState(false);
- }
- }, [
- validateJiraConfig,
- updateChannel,
- id,
- selectedConfig,
- notifications,
- notifyError,
- t,
- ]);
-
- const validateJsmOpsConfig = useCallback((): string => {
- if (!selectedConfig.api_key) {
- return t('api_key_required');
- }
- return '';
- }, [selectedConfig, t]);
-
- const onJsmOpsEditHandler = useCallback(async () => {
- const validationError = validateJsmOpsConfig();
-
- if (validationError !== '') {
- notifications.error({
- message: 'Error',
- description: validationError,
- });
- return { status: 'failed', statusMessage: validationError };
- }
-
- setSavingState(true);
-
- try {
- await updateChannel({
- pathParams: { id },
- data: prepareJsmOpsRequest(selectedConfig),
- });
- notifications.success({
- message: 'Success',
- description: t('channel_edit_done'),
- });
- history.replace(ROUTES.ALL_CHANNELS);
- return { status: 'success', statusMessage: t('channel_edit_done') };
- } catch (error) {
- const apiError = notifyError(error);
- return {
- status: 'failed',
- statusMessage: apiError.getErrorMessage() || t('channel_edit_failed'),
- };
- } finally {
- setSavingState(false);
- }
- }, [
- validateJsmOpsConfig,
- updateChannel,
- id,
- selectedConfig,
- notifications,
- notifyError,
- t,
- ]);
-
- const validateIncidentIOConfig = useCallback((): string => {
- if (!selectedConfig.url || !selectedConfig.token) {
- return t('incidentio_required_fields');
- }
-
- if (!isValidIncidentIOURL(selectedConfig.url)) {
- return t('incidentio_url_invalid');
- }
-
- return '';
- }, [selectedConfig, t]);
-
- const onIncidentIOEditHandler = useCallback(async () => {
- const validationError = validateIncidentIOConfig();
-
- if (validationError !== '') {
- notifications.error({
- message: 'Error',
- description: validationError,
- });
- return { status: 'failed', statusMessage: validationError };
- }
-
- setSavingState(true);
-
- try {
- await updateChannel({
- pathParams: { id },
- data: prepareIncidentIORequest(selectedConfig),
- });
- notifications.success({
- message: 'Success',
- description: t('channel_edit_done'),
- });
- history.replace(ROUTES.ALL_CHANNELS);
- return { status: 'success', statusMessage: t('channel_edit_done') };
- } catch (error) {
- const apiError = notifyError(error);
- return {
- status: 'failed',
- statusMessage: apiError.getErrorMessage() || t('channel_edit_failed'),
- };
- } finally {
- setSavingState(false);
- }
- }, [
- validateIncidentIOConfig,
- updateChannel,
- id,
- selectedConfig,
- notifications,
- notifyError,
- t,
- ]);
-
- const onSaveHandler = useCallback(
- async (value: ChannelType) => {
- let result;
- if (value === ChannelType.Slack) {
- result = await onSlackEditHandler();
- } else if (value === ChannelType.Webhook) {
- result = await onWebhookEditHandler();
- } else if (value === ChannelType.Pagerduty) {
- result = await onPagerEditHandler();
- } else if (value === ChannelType.MsTeams) {
- result = await onMsTeamsEditHandler();
- } else if (value === ChannelType.Opsgenie) {
- result = await onOpsgenieEditHandler();
- } else if (value === ChannelType.Email) {
- result = await onEmailEditHandler();
- } else if (value === ChannelType.GoogleChat) {
- result = await onGoogleChatEditHandler();
- } else if (value === ChannelType.Jira) {
- result = await onJiraEditHandler();
- } else if (value === ChannelType.JsmOps) {
- result = await onJsmOpsEditHandler();
- } else if (value === ChannelType.IncidentIO) {
- result = await onIncidentIOEditHandler();
- }
- logEvent('Alert Channel: Save channel', {
- type: value,
- sendResolvedAlert: selectedConfig?.send_resolved,
- name: selectedConfig?.name,
- new: 'false',
- status: result?.status,
- statusMessage: result?.statusMessage,
- });
- },
- // eslint-disable-next-line react-hooks/exhaustive-deps
- [
- onSlackEditHandler,
- onWebhookEditHandler,
- onPagerEditHandler,
- onMsTeamsEditHandler,
- onOpsgenieEditHandler,
- onEmailEditHandler,
- onGoogleChatEditHandler,
- onJiraEditHandler,
- onJsmOpsEditHandler,
- onIncidentIOEditHandler,
- ],
- );
-
- const performChannelTest = useCallback(
- // eslint-disable-next-line sonarjs/cognitive-complexity
- async (channelType: ChannelType) => {
- setTestingState(true);
- try {
- let request;
- switch (channelType) {
- case ChannelType.Webhook:
- request = prepareWebhookRequest();
- await testWebhookApi(request);
- break;
- case ChannelType.Slack:
- request = prepareSlackRequest();
- await testSlackApi(request);
- break;
- case ChannelType.Pagerduty:
- request = preparePagerRequest();
- if (request) {
- await testPagerApi(request);
- }
- break;
- case ChannelType.MsTeams:
- request = prepareMsTeamsRequest();
- if (request) {
- await testMsTeamsApi(request);
- }
- break;
- case ChannelType.Opsgenie:
- request = prepareOpsgenieRequest();
- if (request) {
- await testOpsgenie(request);
- }
- break;
- case ChannelType.Email:
- request = prepareEmailRequest();
- if (request) {
- await testEmail(request);
- }
- break;
- case ChannelType.GoogleChat: {
- const validationError = validateGoogleChatConfig();
- if (validationError !== '') {
- notifications.error({
- message: 'Error',
- description: validationError,
- });
- setTestingState(false);
- return;
- }
- await testChannel({ data: prepareGoogleChatRequest(selectedConfig) });
- break;
- }
- case ChannelType.Jira: {
- const validationError = validateJiraConfig();
- if (validationError !== '') {
- notifications.error({
- message: 'Error',
- description: validationError,
- });
- setTestingState(false);
- return;
- }
- await testChannel({ data: prepareJiraRequest(selectedConfig) });
- break;
- }
- case ChannelType.JsmOps: {
- const validationError = validateJsmOpsConfig();
- if (validationError !== '') {
- notifications.error({
- message: 'Error',
- description: validationError,
- });
- setTestingState(false);
- return;
- }
- await testChannel({ data: prepareJsmOpsRequest(selectedConfig) });
- break;
- }
- case ChannelType.IncidentIO: {
- const validationError = validateIncidentIOConfig();
- if (validationError !== '') {
- notifications.error({
- message: 'Error',
- description: validationError,
- });
- setTestingState(false);
- return;
- }
- await testChannel({ data: prepareIncidentIORequest(selectedConfig) });
- break;
- }
- default:
- notifications.error({
- message: 'Error',
- description: t('test_unsupported'),
- });
- setTestingState(false);
- return;
- }
-
- notifications.success({
- message: 'Success',
- description: t('channel_test_done'),
- });
- logEvent('Alert Channel: Test notification', {
- type: channelType,
- sendResolvedAlert: selectedConfig?.send_resolved,
- name: selectedConfig?.name,
- new: 'false',
- status: 'Test success',
- });
- } catch (error) {
- notifyError(error);
- logEvent('Alert Channel: Test notification', {
- type: channelType,
- sendResolvedAlert: selectedConfig?.send_resolved,
- name: selectedConfig?.name,
- new: 'false',
- status: 'Test failed',
- });
- }
- setTestingState(false);
- },
- // eslint-disable-next-line react-hooks/exhaustive-deps
- [
- t,
- notifyError,
- validateGoogleChatConfig,
- validateJiraConfig,
- validateJsmOpsConfig,
- validateIncidentIOConfig,
- testChannel,
- prepareWebhookRequest,
- preparePagerRequest,
- prepareSlackRequest,
- prepareMsTeamsRequest,
- prepareOpsgenieRequest,
- prepareEmailRequest,
- notifications,
- ],
- );
-
- const onTestHandler = useCallback(
- async (value: ChannelType) => {
- performChannelTest(value);
- },
- [performChannelTest],
- );
-
- return (
- <FormAlertChannels
- {...{
- formInstance,
- onTypeChangeHandler,
- setSelectedConfig,
- type,
- onTestHandler,
- onSaveHandler,
- testingState,
- savingState,
- title: t('page_title_edit'),
- initialValue,
- editing: true,
- }}
- />
- );
-}
-
-interface EditAlertChannelsProps {
- initialValue: {
- [x: string]: unknown;
- };
- channelId: string;
-}
-
-export default EditAlertChannels;
diff --git a/frontend/src/container/FormAlertChannels/FormAlertChannels.module.scss b/frontend/src/container/FormAlertChannels/FormAlertChannels.module.scss
new file mode 100644
index 0000000000..bc49be2050
--- /dev/null
+++ b/frontend/src/container/FormAlertChannels/FormAlertChannels.module.scss
@@ -0,0 +1,25 @@
+.form {
+ display: flex;
+ flex-direction: column;
+ flex: 1;
+ min-height: 0;
+}
+
+.cards {
+ display: flex;
+ flex-direction: column;
+ gap: var(--spacing-4);
+ padding-bottom: var(--spacing-6);
+ border: 0;
+ margin: 0;
+ min-width: 0;
+}
+
+.actions {
+ display: flex;
+ align-items: center;
+ justify-content: flex-start;
+ gap: var(--spacing-3);
+ padding: var(--spacing-4) 0;
+ border-top: 1px solid var(--l1-border);
+}
diff --git a/frontend/src/container/FormAlertChannels/FormCard.module.scss b/frontend/src/container/FormAlertChannels/FormCard.module.scss
new file mode 100644
index 0000000000..0552f5d67d
--- /dev/null
+++ b/frontend/src/container/FormAlertChannels/FormCard.module.scss
@@ -0,0 +1,23 @@
+.card {
+ border: 1px solid var(--l1-border);
+ border-radius: 4px;
+ background: var(--l2-background);
+}
+
+.head {
+ display: flex;
+ flex-direction: column;
+ gap: var(--spacing-1);
+ padding: var(--spacing-4) var(--spacing-5) 0;
+}
+
+.title {
+ font-weight: var(--font-weight-medium);
+}
+
+.body {
+ display: flex;
+ flex-direction: column;
+ gap: var(--spacing-4);
+ padding: var(--spacing-4) var(--spacing-5) var(--spacing-5);
+}
diff --git a/frontend/src/container/FormAlertChannels/FormCard.tsx b/frontend/src/container/FormAlertChannels/FormCard.tsx
new file mode 100644
index 0000000000..957c2820c6
--- /dev/null
+++ b/frontend/src/container/FormAlertChannels/FormCard.tsx
@@ -0,0 +1,35 @@
+import { ReactNode } from 'react';
+import { Typography } from '@signozhq/ui/typography';
+
+import styles from './FormCard.module.scss';
+
+interface FormCardProps {
+ title: string;
+ /** One line on what the group is for, where the title alone is not enough. */
+ description?: string;
+ children: ReactNode;
+}
+
+function FormCard({
+ title,
+ description,
+ children,
+}: FormCardProps): JSX.Element {
+ return (
+ <section className={styles.card}>
+ <header className={styles.head}>
+ <Typography.Text className={styles.title}>{title}</Typography.Text>
+ {!!description && (
+ <Typography.Text size="sm" color="muted">
+ {description}
+ </Typography.Text>
+ )}
+ </header>
+ <div className={styles.body}>{children}</div>
+ </section>
+ );
+}
+
+FormCard.defaultProps = { description: undefined };
+
+export default FormCard;
diff --git a/frontend/src/container/FormAlertChannels/FormField.module.scss b/frontend/src/container/FormAlertChannels/FormField.module.scss
new file mode 100644
index 0000000000..34d9ca28b3
--- /dev/null
+++ b/frontend/src/container/FormAlertChannels/FormField.module.scss
@@ -0,0 +1,31 @@
+.field {
+ display: flex;
+ flex-direction: column;
+ gap: var(--spacing-1);
+ margin-bottom: var(--spacing-4);
+}
+
+.label {
+ display: flex;
+ align-items: center;
+ gap: var(--spacing-1);
+}
+
+.hint {
+ color: var(--muted-foreground);
+ cursor: help;
+ flex-shrink: 0;
+}
+
+.required {
+ color: var(--danger-background);
+ line-height: 1;
+}
+
+/* The design system's placeholder colour is close enough to the value colour
+ that an empty field reads as a filled one. */
+.field input::placeholder,
+.field textarea::placeholder {
+ color: var(--muted-foreground);
+ opacity: 0.65;
+}
diff --git a/frontend/src/container/FormAlertChannels/FormField.tsx b/frontend/src/container/FormAlertChannels/FormField.tsx
new file mode 100644
index 0000000000..4122dca294
--- /dev/null
+++ b/frontend/src/container/FormAlertChannels/FormField.tsx
@@ -0,0 +1,61 @@
+import { ReactNode } from 'react';
+import { CircleHelp } from '@signozhq/icons';
+import { Tooltip } from '@signozhq/ui/tooltip';
+import { Typography } from '@signozhq/ui/typography';
+import { MarkdownRenderer } from 'components/MarkdownRenderer/MarkdownRenderer';
+
+import styles from './FormField.module.scss';
+
+interface FormFieldProps {
+ label?: ReactNode;
+ help?: ReactNode;
+ tooltip?: string;
+ required?: boolean;
+ error?: string;
+ htmlFor?: string;
+ children: ReactNode;
+}
+
+function FormField({
+ label,
+ help,
+ tooltip,
+ required,
+ error,
+ htmlFor,
+ children,
+}: FormFieldProps): JSX.Element {
+ const hint = tooltip ? (
+ <MarkdownRenderer markdownContent={tooltip} variables={{}} />
+ ) : (
+ help
+ );
+
+ return (
+ <div className={styles.field}>
+ {!!label && (
+ <label className={styles.label} htmlFor={htmlFor}>
+ <Typography.Text size="sm">{label}</Typography.Text>
+ {!!required && (
+ <span aria-hidden="true" className={styles.required}>
+ *
+ </span>
+ )}
+ {!!hint && (
+ <Tooltip title={hint}>
+ <CircleHelp size={12} className={styles.hint} />
+ </Tooltip>
+ )}
+ </label>
+ )}
+ {children}
+ {!!error && (
+ <Typography.Text size="sm" color="danger">
+ {error}
+ </Typography.Text>
+ )}
+ </div>
+ );
+}
+
+export default FormField;
diff --git a/frontend/src/container/FormAlertChannels/Settings/Email.tsx b/frontend/src/container/FormAlertChannels/Settings/Email.tsx
index 52d71e9674..3f71614121 100644
--- a/frontend/src/container/FormAlertChannels/Settings/Email.tsx
+++ b/frontend/src/container/FormAlertChannels/Settings/Email.tsx
@@ -1,49 +1,37 @@
-import { Dispatch, SetStateAction } from 'react';
import { useTranslation } from 'react-i18next';
+import { useFormContext } from 'react-hook-form';
import { Input } from '@signozhq/ui/input';
-import { Form } from 'antd';
-import { EmailChannel } from '../../CreateAlertChannels/config';
+import { ChannelSpecFormValues } from '../../CreateAlertChannels/types';
+import FormCard from '../FormCard';
+import FormField from '../FormField';
-function EmailForm({ setSelectedConfig }: EmailFormProps): JSX.Element {
+function EmailForm(): JSX.Element {
const { t } = useTranslation('channels');
-
- const handleInputChange =
- (field: string) =>
- (event: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement>): void => {
- setSelectedConfig((value) => ({
- ...value,
- [field]: event.target.value,
- }));
- };
+ const {
+ register,
+ formState: { errors },
+ } = useFormContext<ChannelSpecFormValues>();
return (
<>
- <Form.Item
- name="to"
- help={t('help_email_to')}
- label={t('field_email_to')}
- required
- >
- <Input
- onChange={handleInputChange('to')}
- placeholder={t('placeholder_email_to')}
- data-testid="email-to-textbox"
- />
- </Form.Item>
-
- {/* <Form.Item name="html" label={t('field_email_html')} required>
- <TextArea
- rows={4}
- onChange={handleInputChange('html')}
- placeholder={t('placeholder_email_html')}
- />
- </Form.Item> */}
+ <FormCard title={t('section_recipients')}>
+ <FormField
+ help={t('help_email_to')}
+ label={t('field_email_to')}
+ tooltip={t('tooltip_email_to')}
+ error={errors.to?.message}
+ required
+ >
+ <Input
+ {...register('to')}
+ aria-required
+ placeholder={t('placeholder_email_to')}
+ data-testid="email-to-textbox"
+ />
+ </FormField>
+ </FormCard>
</>
);
}
-interface EmailFormProps {
- setSelectedConfig: Dispatch<SetStateAction<Partial<EmailChannel>>>;
-}
-
export default EmailForm;
diff --git a/frontend/src/container/FormAlertChannels/Settings/GoogleChat.tsx b/frontend/src/container/FormAlertChannels/Settings/GoogleChat.tsx
index a1f4dcc1ea..2dba7c4e33 100644
--- a/frontend/src/container/FormAlertChannels/Settings/GoogleChat.tsx
+++ b/frontend/src/container/FormAlertChannels/Settings/GoogleChat.tsx
@@ -1,82 +1,74 @@
-import { Dispatch, SetStateAction } from 'react';
import { useTranslation } from 'react-i18next';
-import { Form, Input } from 'antd';
-import { MarkdownRenderer } from 'components/MarkdownRenderer/MarkdownRenderer';
+import { Controller, useFormContext } from 'react-hook-form';
+import { Input } from '@signozhq/ui/input';
+import { Input as AntdInput } from 'antd';
-import { GoogleChatChannel } from '../../CreateAlertChannels/config';
-import { isValidGoogleChatWebhookURL } from '../../CreateAlertChannels/utils';
+import { ChannelSpecFormValues } from '../../CreateAlertChannels/types';
+import FormCard from '../FormCard';
+import FormField from '../FormField';
-function GoogleChat({ setSelectedConfig }: GoogleChatProps): JSX.Element {
+const { TextArea } = AntdInput;
+
+function GoogleChat(): JSX.Element {
const { t } = useTranslation('channels');
+ const {
+ register,
+ control,
+ formState: { errors },
+ } = useFormContext<ChannelSpecFormValues>();
return (
<>
- <Form.Item
- name="webhook_url"
- label={t('field_webhook_url')}
- required
- rules={[
- {
- validator: (_, value: string): Promise<void> =>
- !value || isValidGoogleChatWebhookURL(value)
- ? Promise.resolve()
- : Promise.reject(new Error(t('google_chat_webhook_url_invalid'))),
- },
- ]}
- tooltip={{
- title: (
- <MarkdownRenderer
- markdownContent={t('tooltip_google_chat_url')}
- variables={{}}
- />
- ),
- overlayInnerStyle: { maxWidth: 400 },
- placement: 'right',
- }}
- >
- <Input
- onChange={(event): void => {
- setSelectedConfig((value) => ({
- ...value,
- webhook_url: event.target.value,
- }));
- }}
- data-testid="webhook-url-textbox"
- />
- </Form.Item>
+ <FormCard title={t('section_connection')}>
+ <FormField
+ label={t('field_webhook_url')}
+ tooltip={t('tooltip_google_chat_url')}
+ error={errors.webhookUrl?.message}
+ required
+ >
+ <Input
+ {...register('webhookUrl')}
+ aria-required
+ data-testid="webhook-url-textbox"
+ />
+ </FormField>
- <Form.Item name="title" label={t('field_slack_title')}>
- <Input.TextArea
- rows={4}
- onChange={(event): void =>
- setSelectedConfig((value) => ({
- ...value,
- title: event.target.value,
- }))
- }
- data-testid="title-textarea"
- />
- </Form.Item>
+ <FormField label={t('field_slack_title')} error={errors.title?.message}>
+ <Controller
+ control={control}
+ name="title"
+ render={({ field }): JSX.Element => (
+ <TextArea
+ rows={4}
+ data-testid="title-textarea"
+ value={(field.value as string) ?? ''}
+ onChange={field.onChange}
+ />
+ )}
+ />
+ </FormField>
- <Form.Item name="text" label={t('field_slack_description')}>
- <Input.TextArea
- rows={4}
- onChange={(event): void =>
- setSelectedConfig((value) => ({
- ...value,
- text: event.target.value,
- }))
- }
- data-testid="description-textarea"
- placeholder={t('placeholder_slack_description')}
- />
- </Form.Item>
+ <FormField
+ label={t('field_slack_description')}
+ error={errors.text?.message}
+ >
+ <Controller
+ control={control}
+ name="text"
+ render={({ field }): JSX.Element => (
+ <TextArea
+ rows={4}
+ data-testid="description-textarea"
+ placeholder={t('placeholder_slack_description')}
+ value={(field.value as string) ?? ''}
+ onChange={field.onChange}
+ />
+ )}
+ />
+ </FormField>
+ </FormCard>
</>
);
}
-interface GoogleChatProps {
- setSelectedConfig: Dispatch<SetStateAction<Partial<GoogleChatChannel>>>;
-}
-
export default GoogleChat;
diff --git a/frontend/src/container/FormAlertChannels/Settings/IncidentIo.tsx b/frontend/src/container/FormAlertChannels/Settings/IncidentIo.tsx
index 143ab8f3ea..b8f5fdac40 100644
--- a/frontend/src/container/FormAlertChannels/Settings/IncidentIo.tsx
+++ b/frontend/src/container/FormAlertChannels/Settings/IncidentIo.tsx
@@ -1,21 +1,33 @@
-import { Dispatch, SetStateAction, useState } from 'react';
+import { useState } from 'react';
import { useTranslation } from 'react-i18next';
+import { Controller, useFormContext } from 'react-hook-form';
import { Minus, Plus } from '@signozhq/icons';
-import { Button, Form, Input } from 'antd';
+import { Input } from '@signozhq/ui/input';
+import { Button } from '@signozhq/ui/button';
+import { Input as AntdInput } from 'antd';
import { Typography } from '@signozhq/ui/typography';
-import { IncidentIOChannel } from '../../CreateAlertChannels/config';
+import { ChannelSpecFormValues } from '../../CreateAlertChannels/types';
+import FormCard from '../FormCard';
+import FormField from '../FormField';
+import styles from './RowEditor.module.scss';
+
+const { TextArea } = AntdInput;
interface MetadataRow {
key: string;
value: string;
}
-function IncidentIOSettings({
- setSelectedConfig,
- initialMetadata,
-}: IncidentIOProps): JSX.Element {
+function IncidentIOSettings({ initialMetadata }: IncidentIOProps): JSX.Element {
const { t } = useTranslation('channels');
+ const {
+ register,
+ control,
+ setValue,
+ formState: { errors },
+ } = useFormContext<ChannelSpecFormValues>();
+
const [metadataRows, setMetadataRows] = useState<MetadataRow[]>(() =>
Object.entries(initialMetadata || {}).map(([key, value]) => ({
key,
@@ -23,145 +35,177 @@ function IncidentIOSettings({
})),
);
- const update = (patch: Partial<IncidentIOChannel>): void =>
- setSelectedConfig((value) => ({ ...value, ...patch }));
-
+ // The API models metadata as a map, so the rows are held here rather than in
+ // the form: an object loses their order and drops a key still being typed.
const syncMetadata = (rows: MetadataRow[]): void => {
setMetadataRows(rows);
- update({
- metadata: Object.fromEntries(
+ setValue(
+ 'metadata',
+ Object.fromEntries(
rows
.filter((row) => row.key.trim() !== '')
.map((row) => [row.key, row.value]),
),
- });
+ { shouldDirty: true },
+ );
};
return (
<>
- <Typography.Text
- color="muted"
- size="sm"
- testId="incidentio-tip"
- style={{ display: 'block', marginBottom: 16 }}
- >
- {t('incidentio_tip')}{' '}
- <Typography.Link
- href="https://signoz.io/docs/alerts-management/notification-channel/incidentio/"
- target="_blank"
- rel="noopener noreferrer"
+ <FormCard title={t('section_connection')}>
+ <Typography.Text
+ color="muted"
+ size="sm"
+ testId="incidentio-tip"
+ style={{ display: 'block', marginBottom: 16 }}
>
- {t('incidentio_tip_link')}
- </Typography.Link>
- </Typography.Text>
+ {t('incidentio_tip')}{' '}
+ <Typography.Link
+ href="https://signoz.io/docs/alerts-management/notification-channel/incidentio/"
+ target="_blank"
+ rel="noopener noreferrer"
+ >
+ {t('incidentio_tip_link')}
+ </Typography.Link>
+ </Typography.Text>
- <Form.Item
- name="url"
- label={t('field_incidentio_url')}
- help={t('help_incidentio_url')}
- required
- >
- <Input
- onChange={(event): void => update({ url: event.target.value })}
- data-testid="incidentio-url-textbox"
- />
- </Form.Item>
+ <FormField
+ label={t('field_incidentio_url')}
+ help={t('help_incidentio_url')}
+ error={errors.url?.message}
+ required
+ >
+ <Input
+ {...register('url')}
+ aria-required
+ data-testid="incidentio-url-textbox"
+ />
+ </FormField>
- <Form.Item
- name="token"
- label={t('field_incidentio_token')}
- help={t('help_incidentio_token')}
- required
- >
- <Input
- type="password"
- onChange={(event): void => update({ token: event.target.value })}
- data-testid="incidentio-token-textbox"
- />
- </Form.Item>
+ <FormField
+ label={t('field_incidentio_token')}
+ help={t('help_incidentio_token')}
+ error={errors.token?.message}
+ required
+ >
+ <Input
+ {...register('token')}
+ aria-required
+ type="password"
+ data-testid="incidentio-token-textbox"
+ />
+ </FormField>
- <Form.Item
- name="title"
- label={t('field_incidentio_title')}
- help={t('help_incidentio_title')}
- >
- <Input.TextArea
- rows={2}
- onChange={(event): void => update({ title: event.target.value })}
- data-testid="incidentio-title-textarea"
- />
- </Form.Item>
+ <FormField
+ label={t('field_incidentio_title')}
+ help={t('help_incidentio_title')}
+ error={errors.title?.message}
+ >
+ <Controller
+ control={control}
+ name="title"
+ render={({ field }): JSX.Element => (
+ <TextArea
+ rows={2}
+ data-testid="incidentio-title-textarea"
+ value={(field.value as string) ?? ''}
+ onChange={field.onChange}
+ />
+ )}
+ />
+ </FormField>
- <Form.Item
- name="description"
- label={t('field_incidentio_description')}
- help={t('help_incidentio_description')}
- >
- <Input.TextArea
- rows={6}
- onChange={(event): void => update({ description: event.target.value })}
- data-testid="incidentio-description-textarea"
- />
- </Form.Item>
+ <FormField
+ label={t('field_incidentio_description')}
+ help={t('help_incidentio_description')}
+ error={errors.description?.message}
+ >
+ <Controller
+ control={control}
+ name="description"
+ render={({ field }): JSX.Element => (
+ <TextArea
+ rows={6}
+ data-testid="incidentio-description-textarea"
+ value={(field.value as string) ?? ''}
+ onChange={field.onChange}
+ />
+ )}
+ />
+ </FormField>
- <Form.Item
- label={t('field_incidentio_metadata')}
- help={t('help_incidentio_metadata')}
- >
- {metadataRows.map((row, index) => (
- // rows have no stable identity beyond their position
- // eslint-disable-next-line react/no-array-index-key
- <div key={index} style={{ display: 'flex', gap: 8, marginBottom: 8 }}>
- <Input
- placeholder={t('placeholder_incidentio_metadata_key')}
- value={row.key}
- onChange={(event): void =>
- syncMetadata(
- metadataRows.map((r, i) =>
- i === index ? { ...r, key: event.target.value } : r,
- ),
- )
- }
- data-testid={`incidentio-metadata-key-${index}`}
- />
- <Input
- placeholder={t('placeholder_incidentio_metadata_value')}
- value={row.value}
- onChange={(event): void =>
- syncMetadata(
- metadataRows.map((r, i) =>
- i === index ? { ...r, value: event.target.value } : r,
- ),
- )
- }
- data-testid={`incidentio-metadata-value-${index}`}
- />
+ <FormField
+ label={t('field_incidentio_metadata')}
+ help={t('help_incidentio_metadata')}
+ >
+ {metadataRows.map((row, index) => (
+ // rows have no stable identity beyond their position
+ // eslint-disable-next-line react/no-array-index-key
+ <div key={index} className={styles.row}>
+ <div className={styles.field}>
+ <Input
+ placeholder={t('placeholder_incidentio_metadata_key')}
+ value={row.key}
+ onChange={(event): void =>
+ syncMetadata(
+ metadataRows.map((r, i) =>
+ i === index ? { ...r, key: event.target.value } : r,
+ ),
+ )
+ }
+ data-testid={`incidentio-metadata-key-${index}`}
+ />
+ </div>
+ <div className={styles.field}>
+ <Input
+ placeholder={t('placeholder_incidentio_metadata_value')}
+ value={row.value}
+ onChange={(event): void =>
+ syncMetadata(
+ metadataRows.map((r, i) =>
+ i === index ? { ...r, value: event.target.value } : r,
+ ),
+ )
+ }
+ data-testid={`incidentio-metadata-value-${index}`}
+ />
+ </div>
+ <Button
+ variant="ghost"
+ color="secondary"
+ size="sm"
+ icon
+ aria-label={t('button_incidentio_remove_metadata')}
+ onClick={(): void =>
+ syncMetadata(metadataRows.filter((_, i) => i !== index))
+ }
+ testId={`incidentio-metadata-remove-${index}`}
+ >
+ <Minus size={14} />
+ </Button>
+ </div>
+ ))}
+ <div className={styles.add}>
<Button
- icon={<Minus size={14} />}
+ variant="dashed"
+ color="secondary"
+ size="sm"
+ prefix={<Plus size={14} />}
onClick={(): void =>
- syncMetadata(metadataRows.filter((_, i) => i !== index))
+ syncMetadata([...metadataRows, { key: '', value: '' }])
}
- data-testid={`incidentio-metadata-remove-${index}`}
- />
+ testId="incidentio-metadata-add"
+ >
+ {t('button_incidentio_add_metadata')}
+ </Button>
</div>
- ))}
- <Button
- type="dashed"
- icon={<Plus size={14} />}
- onClick={(): void =>
- syncMetadata([...metadataRows, { key: '', value: '' }])
- }
- data-testid="incidentio-metadata-add"
- >
- {t('button_incidentio_add_metadata')}
- </Button>
- </Form.Item>
+ </FormField>
+ </FormCard>
</>
);
}
interface IncidentIOProps {
- setSelectedConfig: Dispatch<SetStateAction<Partial<IncidentIOChannel>>>;
initialMetadata?: Record<string, string>;
}
diff --git a/frontend/src/container/FormAlertChannels/Settings/Jira.tsx b/frontend/src/container/FormAlertChannels/Settings/Jira.tsx
index 854b394d8b..d04d089df6 100644
--- a/frontend/src/container/FormAlertChannels/Settings/Jira.tsx
+++ b/frontend/src/container/FormAlertChannels/Settings/Jira.tsx
@@ -1,256 +1,229 @@
-import { Dispatch, SetStateAction } from 'react';
import { useTranslation } from 'react-i18next';
-import { Collapse, Form, Input, Select } from 'antd';
+import { Controller, useFormContext } from 'react-hook-form';
+import { Input } from '@signozhq/ui/input';
+import { Input as AntdInput, Select } from 'antd';
import { Typography } from '@signozhq/ui/typography';
-import { MarkdownRenderer } from 'components/MarkdownRenderer/MarkdownRenderer';
-import { JiraChannel } from '../../CreateAlertChannels/config';
-import {
- isValidJiraReopenDuration,
- isValidJiraSiteURL,
-} from '../../CreateAlertChannels/utils';
+import { ChannelSpecFormValues } from '../../CreateAlertChannels/types';
+import FormCard from '../FormCard';
+import FormField from '../FormField';
-function JiraSettings({ setSelectedConfig }: JiraProps): JSX.Element {
- const { t } = useTranslation('channels');
+const { TextArea } = AntdInput;
- const update = (patch: Partial<JiraChannel>): void =>
- setSelectedConfig((value) => ({ ...value, ...patch }));
+function JiraSettings(): JSX.Element {
+ const { t } = useTranslation('channels');
+ const {
+ register,
+ control,
+ formState: { errors },
+ } = useFormContext<ChannelSpecFormValues>();
const advanced = (
<>
- <Form.Item
- name="priority"
+ <FormField
label={t('field_jira_priority')}
help={t('help_jira_priority')}
+ error={errors.priority?.message}
>
<Input
+ {...register('priority')}
placeholder={t('placeholder_jira_priority')}
- onChange={(event): void => update({ priority: event.target.value })}
data-testid="jira-priority-textbox"
/>
- </Form.Item>
+ </FormField>
- <Form.Item
- name="labels"
+ <FormField
label={t('field_jira_labels')}
help={t('help_jira_labels')}
+ error={errors.labels?.message}
>
<Select
mode="tags"
open={false}
placeholder={t('placeholder_jira_labels')}
- onChange={(value): void => update({ labels: value as string[] })}
data-testid="jira-labels-select"
/>
- </Form.Item>
+ </FormField>
- <Form.Item
- name="resolve_transition"
+ <FormField
label={t('field_jira_resolve_transition')}
help={t('help_jira_resolve_transition')}
+ error={errors.resolveTransition?.message}
>
<Input
+ {...register('resolveTransition')}
placeholder={t('placeholder_jira_resolve_transition')}
- onChange={(event): void =>
- update({ resolve_transition: event.target.value })
- }
data-testid="jira-resolve-transition-textbox"
/>
- </Form.Item>
+ </FormField>
- <Form.Item
- name="reopen_transition"
+ <FormField
label={t('field_jira_reopen_transition')}
help={t('help_jira_reopen_transition')}
+ error={errors.reopenTransition?.message}
>
<Input
+ {...register('reopenTransition')}
placeholder={t('placeholder_jira_reopen_transition')}
- onChange={(event): void =>
- update({ reopen_transition: event.target.value })
- }
data-testid="jira-reopen-transition-textbox"
/>
- </Form.Item>
+ </FormField>
- <Form.Item
- name="wont_fix_resolution"
+ <FormField
label={t('field_jira_wont_fix_resolution')}
help={t('help_jira_wont_fix_resolution')}
+ error={errors.wontFixResolution?.message}
>
<Input
+ {...register('wontFixResolution')}
placeholder={t('placeholder_jira_wont_fix_resolution')}
- onChange={(event): void =>
- update({ wont_fix_resolution: event.target.value })
- }
data-testid="jira-wont-fix-resolution-textbox"
/>
- </Form.Item>
+ </FormField>
- <Form.Item
- name="reopen_duration"
+ <FormField
label={t('field_jira_reopen_duration')}
- extra={t('help_jira_reopen_duration')}
- rules={[
- {
- validator: (_, value: string): Promise<void> =>
- isValidJiraReopenDuration(value)
- ? Promise.resolve()
- : Promise.reject(new Error(t('jira_reopen_duration_invalid'))),
- },
- ]}
- tooltip={{
- title: (
- <MarkdownRenderer
- markdownContent={t('tooltip_jira_reopen_duration')}
- variables={{}}
- />
- ),
- overlayInnerStyle: { maxWidth: 400 },
- placement: 'right',
- }}
+ tooltip={t('tooltip_jira_reopen_duration')}
+ help={t('help_jira_reopen_duration')}
+ error={errors.reopenDuration?.message}
>
<Input
+ {...register('reopenDuration')}
placeholder={t('placeholder_jira_reopen_duration')}
- onChange={(event): void => update({ reopen_duration: event.target.value })}
data-testid="jira-reopen-duration-textbox"
/>
- </Form.Item>
+ </FormField>
</>
);
return (
<>
- <Typography.Text
- color="muted"
- size="sm"
- testId="jira-service-account-tip"
- style={{ display: 'block', marginBottom: 16 }}
- >
- {t('jira_service_account_tip')}{' '}
- <Typography.Link
- href="https://signoz.io/docs/alerts-management/notification-channel/jira/#use-a-service-account-recommended"
- target="_blank"
- rel="noopener noreferrer"
+ <FormCard title={t('section_connection')}>
+ <Typography.Text
+ color="muted"
+ size="sm"
+ testId="jira-service-account-tip"
+ style={{ display: 'block', marginBottom: 16 }}
>
- {t('jira_service_account_tip_link')}
- </Typography.Link>
- </Typography.Text>
-
- <Form.Item
- name="site"
- label={t('field_jira_site')}
- required
- rules={[
- {
- validator: (_, value: string): Promise<void> =>
- !value || isValidJiraSiteURL(value)
- ? Promise.resolve()
- : Promise.reject(new Error(t('jira_site_invalid'))),
- },
- ]}
- tooltip={{
- title: (
- <MarkdownRenderer
- markdownContent={t('tooltip_jira_site')}
- variables={{}}
- />
- ),
- overlayInnerStyle: { maxWidth: 400 },
- placement: 'right',
- }}
- >
- <Input
- placeholder="https://your-domain.atlassian.net"
- onChange={(event): void => update({ site: event.target.value })}
- data-testid="jira-site-textbox"
- />
- </Form.Item>
-
- <Form.Item
- name="username"
- label={t('field_jira_email')}
- help={t('help_jira_email')}
- required
- >
- <Input
- onChange={(event): void => update({ username: event.target.value })}
- data-testid="jira-email-textbox"
- />
- </Form.Item>
-
- <Form.Item
- name="password"
- label={t('field_jira_api_token')}
- help={t('help_jira_api_token')}
- required
- >
- <Input
- type="password"
- onChange={(event): void => update({ password: event.target.value })}
- data-testid="jira-api-token-textbox"
- />
- </Form.Item>
-
- <Form.Item name="project" label={t('field_jira_project')} required>
- <Input
- placeholder="e.g. OPS"
- onChange={(event): void => update({ project: event.target.value })}
- data-testid="jira-project-textbox"
- />
- </Form.Item>
-
- <Form.Item
- name="issue_type"
- label={t('field_jira_issue_type')}
- help={t('help_jira_issue_type')}
- required
- >
- <Input
- onChange={(event): void => update({ issue_type: event.target.value })}
- data-testid="jira-issue-type-textbox"
- />
- </Form.Item>
-
- <Form.Item
- name="summary"
- label={t('field_jira_summary')}
- help={t('help_jira_summary')}
- >
- <Input.TextArea
- rows={2}
- onChange={(event): void => update({ summary: event.target.value })}
- data-testid="jira-summary-textarea"
- />
- </Form.Item>
-
- <Form.Item
- name="description"
- label={t('field_jira_description')}
- help={t('help_jira_description')}
- >
- <Input.TextArea
- rows={6}
- onChange={(event): void => update({ description: event.target.value })}
- data-testid="jira-description-textarea"
- />
- </Form.Item>
-
- <Collapse
- ghost
- items={[
- {
- key: 'advanced',
- label: t('jira_advanced_section'),
- children: advanced,
- },
- ]}
- />
+ {t('jira_service_account_tip')}{' '}
+ <Typography.Link
+ href="https://signoz.io/docs/alerts-management/notification-channel/jira/#use-a-service-account-recommended"
+ target="_blank"
+ rel="noopener noreferrer"
+ >
+ {t('jira_service_account_tip_link')}
+ </Typography.Link>
+ </Typography.Text>
+
+ <FormField
+ label={t('field_jira_site')}
+ tooltip={t('tooltip_jira_site')}
+ error={errors.site?.message}
+ required
+ >
+ <Input
+ {...register('site')}
+ aria-required
+ placeholder="https://your-domain.atlassian.net"
+ data-testid="jira-site-textbox"
+ />
+ </FormField>
+
+ <FormField
+ label={t('field_jira_email')}
+ help={t('help_jira_email')}
+ error={errors.email?.message}
+ required
+ >
+ <Input
+ {...register('email')}
+ aria-required
+ data-testid="jira-email-textbox"
+ />
+ </FormField>
+
+ <FormField
+ label={t('field_jira_api_token')}
+ help={t('help_jira_api_token')}
+ error={errors.apiToken?.message}
+ required
+ >
+ <Input
+ {...register('apiToken')}
+ aria-required
+ type="password"
+ data-testid="jira-api-token-textbox"
+ />
+ </FormField>
+
+ <FormField
+ label={t('field_jira_project')}
+ error={errors.project?.message}
+ required
+ >
+ <Input
+ {...register('project')}
+ aria-required
+ placeholder="e.g. OPS"
+ data-testid="jira-project-textbox"
+ />
+ </FormField>
+
+ <FormField
+ label={t('field_jira_issue_type')}
+ help={t('help_jira_issue_type')}
+ error={errors.issueType?.message}
+ required
+ >
+ <Input
+ {...register('issueType')}
+ aria-required
+ data-testid="jira-issue-type-textbox"
+ />
+ </FormField>
+
+ <FormField
+ label={t('field_jira_summary')}
+ help={t('help_jira_summary')}
+ error={errors.summary?.message}
+ >
+ <Controller
+ control={control}
+ name="summary"
+ render={({ field }): JSX.Element => (
+ <TextArea
+ rows={2}
+ data-testid="jira-summary-textarea"
+ value={(field.value as string) ?? ''}
+ onChange={field.onChange}
+ />
+ )}
+ />
+ </FormField>
+
+ <FormField
+ label={t('field_jira_description')}
+ help={t('help_jira_description')}
+ error={errors.description?.message}
+ >
+ <Controller
+ control={control}
+ name="description"
+ render={({ field }): JSX.Element => (
+ <TextArea
+ rows={6}
+ data-testid="jira-description-textarea"
+ value={(field.value as string) ?? ''}
+ onChange={field.onChange}
+ />
+ )}
+ />
+ </FormField>
+ </FormCard>
+
+ <FormCard title={t('section_advanced')}>{advanced}</FormCard>
</>
);
}
-interface JiraProps {
- setSelectedConfig: Dispatch<SetStateAction<Partial<JiraChannel>>>;
-}
-
export default JiraSettings;
diff --git a/frontend/src/container/FormAlertChannels/Settings/JsmOps.tsx b/frontend/src/container/FormAlertChannels/Settings/JsmOps.tsx
index c5fbafa58a..16f8eb2b19 100644
--- a/frontend/src/container/FormAlertChannels/Settings/JsmOps.tsx
+++ b/frontend/src/container/FormAlertChannels/Settings/JsmOps.tsx
@@ -1,117 +1,143 @@
-import { Dispatch, SetStateAction } from 'react';
import { useTranslation } from 'react-i18next';
-import { Collapse, Form, Input, Select } from 'antd';
+import { Controller, useFormContext } from 'react-hook-form';
+import { Input } from '@signozhq/ui/input';
+import { Input as AntdInput, Select } from 'antd';
import { Typography } from '@signozhq/ui/typography';
-import { JsmOpsChannel } from '../../CreateAlertChannels/config';
+import { ChannelSpecFormValues } from '../../CreateAlertChannels/types';
+import FormCard from '../FormCard';
+import FormField from '../FormField';
-function JsmOpsSettings({ setSelectedConfig }: JsmOpsProps): JSX.Element {
- const { t } = useTranslation('channels');
+const { TextArea } = AntdInput;
- const update = (patch: Partial<JsmOpsChannel>): void =>
- setSelectedConfig((value) => ({ ...value, ...patch }));
+function JsmOpsSettings(): JSX.Element {
+ const { t } = useTranslation('channels');
+ const {
+ register,
+ control,
+ formState: { errors },
+ } = useFormContext<ChannelSpecFormValues>();
const advanced = (
<>
- <Form.Item
- name="priority"
+ <FormField
label={t('field_jsmops_priority')}
help={t('help_jsmops_priority')}
+ error={errors.priority?.message}
>
- <Input.TextArea
- rows={2}
- onChange={(event): void => update({ priority: event.target.value })}
- data-testid="jsmops-priority-textarea"
+ <Controller
+ control={control}
+ name="priority"
+ render={({ field }): JSX.Element => (
+ <TextArea
+ rows={2}
+ data-testid="jsmops-priority-textarea"
+ value={(field.value as string) ?? ''}
+ onChange={field.onChange}
+ />
+ )}
/>
- </Form.Item>
+ </FormField>
- <Form.Item
- name="tags"
+ <FormField
label={t('field_jsmops_tags')}
help={t('help_jsmops_tags')}
+ error={errors.tags?.message}
>
- <Select
- mode="tags"
- open={false}
- placeholder={t('placeholder_jsmops_tags')}
- onChange={(value): void => update({ tags: value as string[] })}
- data-testid="jsmops-tags-select"
+ {/* the API takes one comma-separated string, the control edits chips */}
+ <Controller
+ control={control}
+ name="tags"
+ render={({ field }): JSX.Element => (
+ <Select
+ mode="tags"
+ open={false}
+ placeholder={t('placeholder_jsmops_tags')}
+ value={field.value ? String(field.value).split(',') : []}
+ onChange={(value): void => field.onChange((value as string[]).join(','))}
+ data-testid="jsmops-tags-select"
+ />
+ )}
/>
- </Form.Item>
+ </FormField>
</>
);
return (
<>
- <Typography.Text
- color="muted"
- size="sm"
- testId="jsmops-tip"
- style={{ display: 'block', marginBottom: 16 }}
- >
- {t('jsmops_tip')}{' '}
- <Typography.Link
- href="https://signoz.io/docs/alerts-management/notification-channel/jsm-ops/"
- target="_blank"
- rel="noopener noreferrer"
+ <FormCard title={t('section_connection')}>
+ <Typography.Text
+ color="muted"
+ size="sm"
+ testId="jsmops-tip"
+ style={{ display: 'block', marginBottom: 16 }}
>
- {t('jsmops_tip_link')}
- </Typography.Link>
- </Typography.Text>
+ {t('jsmops_tip')}{' '}
+ <Typography.Link
+ href="https://signoz.io/docs/alerts-management/notification-channel/jsm-ops/"
+ target="_blank"
+ rel="noopener noreferrer"
+ >
+ {t('jsmops_tip_link')}
+ </Typography.Link>
+ </Typography.Text>
- <Form.Item
- name="api_key"
- label={t('field_jsmops_api_key')}
- help={t('help_jsmops_api_key')}
- required
- >
- <Input
- type="password"
- onChange={(event): void => update({ api_key: event.target.value })}
- data-testid="jsmops-api-key-textbox"
- />
- </Form.Item>
+ <FormField
+ label={t('field_jsmops_api_key')}
+ help={t('help_jsmops_api_key')}
+ error={errors.apiKey?.message}
+ required
+ >
+ <Input
+ {...register('apiKey')}
+ aria-required
+ type="password"
+ data-testid="jsmops-api-key-textbox"
+ />
+ </FormField>
- <Form.Item
- name="message"
- label={t('field_jsmops_message')}
- help={t('help_jsmops_message')}
- >
- <Input.TextArea
- rows={2}
- onChange={(event): void => update({ message: event.target.value })}
- data-testid="jsmops-message-textarea"
- />
- </Form.Item>
+ <FormField
+ label={t('field_jsmops_message')}
+ help={t('help_jsmops_message')}
+ error={errors.message?.message}
+ >
+ <Controller
+ control={control}
+ name="message"
+ render={({ field }): JSX.Element => (
+ <TextArea
+ rows={2}
+ data-testid="jsmops-message-textarea"
+ value={(field.value as string) ?? ''}
+ onChange={field.onChange}
+ />
+ )}
+ />
+ </FormField>
- <Form.Item
- name="description"
- label={t('field_jsmops_description')}
- help={t('help_jsmops_description')}
- >
- <Input.TextArea
- rows={6}
- onChange={(event): void => update({ description: event.target.value })}
- data-testid="jsmops-description-textarea"
- />
- </Form.Item>
+ <FormField
+ label={t('field_jsmops_description')}
+ help={t('help_jsmops_description')}
+ error={errors.description?.message}
+ >
+ <Controller
+ control={control}
+ name="description"
+ render={({ field }): JSX.Element => (
+ <TextArea
+ rows={6}
+ data-testid="jsmops-description-textarea"
+ value={(field.value as string) ?? ''}
+ onChange={field.onChange}
+ />
+ )}
+ />
+ </FormField>
+ </FormCard>
- <Collapse
- ghost
- items={[
- {
- key: 'advanced',
- label: t('jsmops_advanced_section'),
- children: advanced,
- },
- ]}
- />
+ <FormCard title={t('section_advanced')}>{advanced}</FormCard>
</>
);
}
-interface JsmOpsProps {
- setSelectedConfig: Dispatch<SetStateAction<Partial<JsmOpsChannel>>>;
-}
-
export default JsmOpsSettings;
diff --git a/frontend/src/container/FormAlertChannels/Settings/MsTeams.tsx b/frontend/src/container/FormAlertChannels/Settings/MsTeams.tsx
index e45db50035..be3ba69eda 100644
--- a/frontend/src/container/FormAlertChannels/Settings/MsTeams.tsx
+++ b/frontend/src/container/FormAlertChannels/Settings/MsTeams.tsx
@@ -1,74 +1,74 @@
import React from 'react';
import { useTranslation } from 'react-i18next';
-import { Form, Input } from 'antd';
-import { MarkdownRenderer } from 'components/MarkdownRenderer/MarkdownRenderer';
+import { Controller, useFormContext } from 'react-hook-form';
+import { Input } from '@signozhq/ui/input';
+import { Input as AntdInput } from 'antd';
-import { MsTeamsChannel } from '../../CreateAlertChannels/config';
+import { ChannelSpecFormValues } from '../../CreateAlertChannels/types';
+import FormCard from '../FormCard';
+import FormField from '../FormField';
-function MsTeams({ setSelectedConfig }: MsTeamsProps): JSX.Element {
+const { TextArea } = AntdInput;
+
+function MsTeams(): JSX.Element {
const { t } = useTranslation('channels');
+ const {
+ register,
+ control,
+ formState: { errors },
+ } = useFormContext<ChannelSpecFormValues>();
return (
<>
- <Form.Item
- name="webhook_url"
- label={t('field_webhook_url')}
- tooltip={{
- title: (
- <MarkdownRenderer
- markdownContent={t('tooltip_ms_teams_url')}
- variables={{}}
- />
- ),
- overlayInnerStyle: { maxWidth: 400 },
- placement: 'right',
- }}
- >
- <Input
- onChange={(event): void => {
- setSelectedConfig((value) => ({
- ...value,
- webhook_url: event.target.value,
- }));
- }}
- data-testid="webhook-url-textbox"
- />
- </Form.Item>
+ <FormCard title={t('section_connection')}>
+ <FormField
+ label={t('field_webhook_url')}
+ tooltip={t('tooltip_ms_teams_url')}
+ error={errors.webhookUrl?.message}
+ required
+ >
+ <Input
+ {...register('webhookUrl')}
+ aria-required
+ data-testid="webhook-url-textbox"
+ />
+ </FormField>
- <Form.Item name="title" label={t('field_slack_title')}>
- <Input.TextArea
- rows={4}
- // value={`[{{ .Status | toUpper }}{{ if eq .Status \"firing\" }}:{{ .Alerts.Firing | len }}{{ end }}] {{ .CommonLabels.alertname }} for {{ .CommonLabels.job }}\n{{- if gt (len .CommonLabels) (len .GroupLabels) -}}\n{{\" \"}}(\n{{- with .CommonLabels.Remove .GroupLabels.Names }}\n {{- range $index, $label := .SortedPairs -}}\n {{ if $index }}, {{ end }}\n {{- $label.Name }}=\"{{ $label.Value -}}\"\n {{- end }}\n{{- end -}}\n)\n{{- end }}`}
- onChange={(event): void =>
- setSelectedConfig((value) => ({
- ...value,
- title: event.target.value,
- }))
- }
- data-testid="title-textarea"
- />
- </Form.Item>
+ <FormField label={t('field_slack_title')} error={errors.title?.message}>
+ <Controller
+ control={control}
+ name="title"
+ render={({ field }): JSX.Element => (
+ <TextArea
+ rows={4}
+ data-testid="title-textarea"
+ value={(field.value as string) ?? ''}
+ onChange={field.onChange}
+ />
+ )}
+ />
+ </FormField>
- <Form.Item name="text" label={t('field_slack_description')}>
- <Input.TextArea
- onChange={(event): void =>
- setSelectedConfig((value) => ({
- ...value,
- text: event.target.value,
- }))
- }
- data-testid="description-textarea"
- placeholder={t('placeholder_slack_description')}
- />
- </Form.Item>
+ <FormField
+ label={t('field_slack_description')}
+ error={errors.text?.message}
+ >
+ <Controller
+ control={control}
+ name="text"
+ render={({ field }): JSX.Element => (
+ <TextArea
+ data-testid="description-textarea"
+ placeholder={t('placeholder_slack_description')}
+ value={(field.value as string) ?? ''}
+ onChange={field.onChange}
+ />
+ )}
+ />
+ </FormField>
+ </FormCard>
</>
);
}
-interface MsTeamsProps {
- setSelectedConfig: React.Dispatch<
- React.SetStateAction<Partial<MsTeamsChannel>>
- >;
-}
-
export default MsTeams;
diff --git a/frontend/src/container/FormAlertChannels/Settings/Opsgenie.tsx b/frontend/src/container/FormAlertChannels/Settings/Opsgenie.tsx
index ee700ca42c..44e93f1018 100644
--- a/frontend/src/container/FormAlertChannels/Settings/Opsgenie.tsx
+++ b/frontend/src/container/FormAlertChannels/Settings/Opsgenie.tsx
@@ -1,95 +1,100 @@
import { useTranslation } from 'react-i18next';
-import { Form, Input } from 'antd';
-import { MarkdownRenderer } from 'components/MarkdownRenderer/MarkdownRenderer';
+import { Controller, useFormContext } from 'react-hook-form';
+import { Input } from '@signozhq/ui/input';
+import { Input as AntdInput } from 'antd';
-import { OpsgenieChannel } from '../../CreateAlertChannels/config';
+import { ChannelSpecFormValues } from '../../CreateAlertChannels/types';
+import FormCard from '../FormCard';
+import FormField from '../FormField';
-const { TextArea } = Input;
+const { TextArea } = AntdInput;
-function OpsgenieForm({ setSelectedConfig }: OpsgenieFormProps): JSX.Element {
+function OpsgenieForm(): JSX.Element {
const { t } = useTranslation('channels');
-
- const handleInputChange =
- (field: string) =>
- (event: React.ChangeEvent<HTMLInputElement | HTMLTextAreaElement>): void => {
- setSelectedConfig((value) => ({
- ...value,
- [field]: event.target.value,
- }));
- };
+ const {
+ register,
+ control,
+ formState: { errors },
+ } = useFormContext<ChannelSpecFormValues>();
return (
<>
- <Form.Item
- name="api_key"
- label={t('field_opsgenie_api_key')}
- tooltip={{
- title: (
- <MarkdownRenderer
- markdownContent={t('tooltip_opsgenie_api_key')}
- variables={{}}
- />
- ),
- overlayInnerStyle: { maxWidth: 400 },
- placement: 'right',
- }}
- required
- >
- <Input
- onChange={handleInputChange('api_key')}
- data-testid="opsgenie-api-key-textbox"
- />
- </Form.Item>
+ <FormCard title={t('section_connection')}>
+ <FormField
+ label={t('field_opsgenie_api_key')}
+ tooltip={t('tooltip_opsgenie_api_key')}
+ error={errors.apiKey?.message}
+ required
+ >
+ <Input
+ {...register('apiKey')}
+ aria-required
+ data-testid="opsgenie-api-key-textbox"
+ />
+ </FormField>
- <Form.Item
- name="message"
- help={t('help_opsgenie_message')}
- label={t('field_opsgenie_message')}
- required
- >
- <TextArea
- rows={4}
- onChange={handleInputChange('message')}
- placeholder={t('placeholder_opsgenie_message')}
- data-testid="opsgenie-message-textarea"
- />
- </Form.Item>
+ <FormField
+ help={t('help_opsgenie_message')}
+ label={t('field_opsgenie_message')}
+ error={errors.message?.message}
+ >
+ <Controller
+ control={control}
+ name="message"
+ render={({ field }): JSX.Element => (
+ <TextArea
+ rows={4}
+ placeholder={t('placeholder_opsgenie_message')}
+ data-testid="opsgenie-message-textarea"
+ value={(field.value as string) ?? ''}
+ onChange={field.onChange}
+ />
+ )}
+ />
+ </FormField>
- <Form.Item
- name="description"
- help={t('help_opsgenie_description')}
- label={t('field_opsgenie_description')}
- required
- >
- <TextArea
- rows={4}
- onChange={handleInputChange('description')}
- placeholder={t('placeholder_opsgenie_description')}
- data-testid="opsgenie-description-textarea"
- />
- </Form.Item>
+ <FormField
+ help={t('help_opsgenie_description')}
+ label={t('field_opsgenie_description')}
+ error={errors.description?.message}
+ >
+ <Controller
+ control={control}
+ name="description"
+ render={({ field }): JSX.Element => (
+ <TextArea
+ rows={4}
+ placeholder={t('placeholder_opsgenie_description')}
+ data-testid="opsgenie-description-textarea"
+ value={(field.value as string) ?? ''}
+ onChange={field.onChange}
+ />
+ )}
+ />
+ </FormField>
- <Form.Item
- name="priority"
- help={t('help_opsgenie_priority')}
- label={t('field_opsgenie_priority')}
- required
- >
- <TextArea
- rows={4}
- onChange={handleInputChange('priority')}
- placeholder={t('placeholder_opsgenie_priority')}
- data-testid="opsgenie-priority-textarea"
- />
- </Form.Item>
+ <FormField
+ help={t('help_opsgenie_priority')}
+ label={t('field_opsgenie_priority')}
+ error={errors.priority?.message}
+ >
+ <Controller
+ control={control}
+ name="priority"
+ render={({ field }): JSX.Element => (
+ <TextArea
+ rows={4}
+ placeholder={t('placeholder_opsgenie_priority')}
+ data-testid="opsgenie-priority-textarea"
+ value={(field.value as string) ?? ''}
+ onChange={field.onChange}
+ />
+ )}
+ />
+ </FormField>
+ </FormCard>
</>
);
}
-interface OpsgenieFormProps {
- setSelectedConfig: React.Dispatch<
- React.SetStateAction<Partial<OpsgenieChannel>>
- >;
-}
-
export default OpsgenieForm;
diff --git a/frontend/src/container/FormAlertChannels/Settings/Pager.tsx b/frontend/src/container/FormAlertChannels/Settings/Pager.tsx
index e816726f79..31e2508055 100644
--- a/frontend/src/container/FormAlertChannels/Settings/Pager.tsx
+++ b/frontend/src/container/FormAlertChannels/Settings/Pager.tsx
@@ -1,176 +1,112 @@
-import { Dispatch, SetStateAction } from 'react';
import { useTranslation } from 'react-i18next';
-import { Form, Input } from 'antd';
-import { MarkdownRenderer } from 'components/MarkdownRenderer/MarkdownRenderer';
+import { Controller, useFormContext } from 'react-hook-form';
+import { Input } from '@signozhq/ui/input';
+import { Input as AntdInput } from 'antd';
-import { PagerChannel } from '../../CreateAlertChannels/config';
+import { ChannelSpecFormValues } from '../../CreateAlertChannels/types';
+import FormCard from '../FormCard';
+import FormField from '../FormField';
+import PagerDetails from './PagerDetails';
-const { TextArea } = Input;
+const { TextArea } = AntdInput;
-function PagerForm({ setSelectedConfig }: PagerFormProps): JSX.Element {
+function PagerForm(): JSX.Element {
const { t } = useTranslation('channels');
+ const {
+ register,
+ control,
+ formState: { errors },
+ } = useFormContext<ChannelSpecFormValues>();
return (
<>
- <Form.Item
- name="routing_key"
- label={t('field_pager_routing_key')}
- tooltip={{
- title: (
- <MarkdownRenderer
- markdownContent={t('tooltip_pager_routing_key')}
- variables={{}}
- />
- ),
- overlayInnerStyle: { maxWidth: 400 },
- placement: 'right',
- }}
- >
- <Input
- onChange={(event): void => {
- setSelectedConfig((value) => ({
- ...value,
- routing_key: event.target.value,
- }));
- }}
- data-testid="pager-routing-key-textbox"
- />
- </Form.Item>
+ <FormCard title={t('section_connection')}>
+ <FormField
+ label={t('field_pager_routing_key')}
+ tooltip={t('tooltip_pager_routing_key')}
+ error={errors.routingKey?.message}
+ required
+ >
+ <Input
+ {...register('routingKey')}
+ aria-required
+ data-testid="pager-routing-key-textbox"
+ />
+ </FormField>
- <Form.Item
- name="description"
- help={t('help_pager_description')}
- label={t('field_pager_description')}
- required
- >
- <TextArea
- rows={4}
- onChange={(event): void =>
- setSelectedConfig((value) => ({
- ...value,
- description: event.target.value,
- }))
- }
- placeholder={t('placeholder_pager_description')}
- data-testid="pager-description-textarea"
- />
- </Form.Item>
+ <FormField
+ help={t('help_pager_description')}
+ label={t('field_pager_description')}
+ error={errors.description?.message}
+ >
+ <Controller
+ control={control}
+ name="description"
+ render={({ field }): JSX.Element => (
+ <TextArea
+ rows={4}
+ placeholder={t('placeholder_pager_description')}
+ data-testid="pager-description-textarea"
+ value={(field.value as string) ?? ''}
+ onChange={field.onChange}
+ />
+ )}
+ />
+ </FormField>
- <Form.Item
- name="severity"
- help={t('help_pager_severity')}
- label={t('field_pager_severity')}
- >
- <Input
- onChange={(event): void =>
- setSelectedConfig((value) => ({
- ...value,
- severity: event.target.value,
- }))
- }
- data-testid="pager-severity-textbox"
- />
- </Form.Item>
+ <FormField
+ help={t('help_pager_severity')}
+ label={t('field_pager_severity')}
+ error={errors.severity?.message}
+ >
+ <Input {...register('severity')} data-testid="pager-severity-textbox" />
+ </FormField>
- <Form.Item
- name="details"
- help={t('help_pager_details')}
- label={t('field_pager_details')}
- >
- <TextArea
- rows={4}
- onChange={(event): void =>
- setSelectedConfig((value) => ({
- ...value,
- details: event.target.value,
- }))
- }
- data-testid="pager-additional-details-textarea"
- />
- </Form.Item>
+ <PagerDetails />
- <Form.Item
- name="component"
- help={t('help_pager_component')}
- label={t('field_pager_component')}
- >
- <Input
- onChange={(event): void =>
- setSelectedConfig((value) => ({
- ...value,
- component: event.target.value,
- }))
- }
- />
- </Form.Item>
+ <FormField
+ help={t('help_pager_component')}
+ label={t('field_pager_component')}
+ error={errors.component?.message}
+ >
+ <Input {...register('component')} />
+ </FormField>
- <Form.Item
- name="group"
- help={t('help_pager_group')}
- label={t('field_pager_group')}
- >
- <Input
- onChange={(event): void =>
- setSelectedConfig((value) => ({
- ...value,
- group: event.target.value,
- }))
- }
- data-testid="pager-group-textarea"
- />
- </Form.Item>
+ <FormField
+ help={t('help_pager_group')}
+ label={t('field_pager_group')}
+ error={errors.group?.message}
+ >
+ <Input {...register('group')} data-testid="pager-group-textarea" />
+ </FormField>
- <Form.Item
- name="class"
- help={t('help_pager_class')}
- label={t('field_pager_class')}
- >
- <Input
- onChange={(event): void =>
- setSelectedConfig((value) => ({
- ...value,
- class: event.target.value,
- }))
- }
- data-testid="pager-class-textarea"
- />
- </Form.Item>
- <Form.Item
- name="client"
- help={t('help_pager_client')}
- label={t('field_pager_client')}
- >
- <Input
- onChange={(event): void =>
- setSelectedConfig((value) => ({
- ...value,
- client: event.target.value,
- }))
- }
- data-testid="pager-client-textarea"
- />
- </Form.Item>
+ <FormField
+ help={t('help_pager_class')}
+ label={t('field_pager_class')}
+ error={errors.class?.message}
+ >
+ <Input {...register('class')} data-testid="pager-class-textarea" />
+ </FormField>
+ <FormField
+ help={t('help_pager_client')}
+ label={t('field_pager_client')}
+ error={errors.client?.message}
+ >
+ <Input {...register('client')} data-testid="pager-client-textarea" />
+ </FormField>
- <Form.Item
- name="client_url"
- help={t('help_pager_client_url')}
- label={t('field_pager_client_url')}
- >
- <Input
- onChange={(event): void =>
- setSelectedConfig((value) => ({
- ...value,
- client_url: event.target.value,
- }))
- }
- data-testid="pager-client-url-textarea"
- />
- </Form.Item>
+ <FormField
+ help={t('help_pager_client_url')}
+ label={t('field_pager_client_url')}
+ error={errors.clientUrl?.message}
+ >
+ <Input
+ {...register('clientUrl')}
+ data-testid="pager-client-url-textarea"
+ />
+ </FormField>
+ </FormCard>
</>
);
}
-interface PagerFormProps {
- setSelectedConfig: Dispatch<SetStateAction<Partial<PagerChannel>>>;
-}
-
export default PagerForm;
diff --git a/frontend/src/container/FormAlertChannels/Settings/PagerDetails.tsx b/frontend/src/container/FormAlertChannels/Settings/PagerDetails.tsx
new file mode 100644
index 0000000000..956e605139
--- /dev/null
+++ b/frontend/src/container/FormAlertChannels/Settings/PagerDetails.tsx
@@ -0,0 +1,56 @@
+import { useState } from 'react';
+import { useTranslation } from 'react-i18next';
+import { useFormContext } from 'react-hook-form';
+import { Input as AntdInput } from 'antd';
+
+import { ChannelSpecFormValues } from '../../CreateAlertChannels/types';
+import FormField from '../FormField';
+
+const { TextArea } = AntdInput;
+
+const serialize = (details?: Record<string, string>): string =>
+ details && Object.keys(details).length > 0 ? JSON.stringify(details) : '';
+
+function PagerDetails(): JSX.Element {
+ const { t } = useTranslation('channels');
+ const { getValues, setValue } = useFormContext<ChannelSpecFormValues>();
+
+ const [text, setText] = useState<string>(() =>
+ serialize(getValues('details') ?? undefined),
+ );
+ const [error, setError] = useState<string | null>(null);
+
+ const onChange = (value: string): void => {
+ setText(value);
+
+ if (value.trim() === '') {
+ setError(null);
+ setValue('details', {}, { shouldDirty: true });
+ return;
+ }
+
+ try {
+ setValue('details', JSON.parse(value), { shouldDirty: true });
+ setError(null);
+ } catch {
+ setError(t('pager_details_invalid_json'));
+ }
+ };
+
+ return (
+ <FormField
+ error={error ?? undefined}
+ help={t('help_pager_details')}
+ label={t('field_pager_details')}
+ >
+ <TextArea
+ rows={4}
+ value={text}
+ onChange={(event): void => onChange(event.target.value)}
+ data-testid="pager-additional-details-textarea"
+ />
+ </FormField>
+ );
+}
+
+export default PagerDetails;
diff --git a/frontend/src/container/FormAlertChannels/Settings/RowEditor.module.scss b/frontend/src/container/FormAlertChannels/Settings/RowEditor.module.scss
new file mode 100644
index 0000000000..b6a352049c
--- /dev/null
+++ b/frontend/src/container/FormAlertChannels/Settings/RowEditor.module.scss
@@ -0,0 +1,37 @@
+.row {
+ display: flex;
+ align-items: center;
+ gap: var(--spacing-2);
+ margin-bottom: var(--spacing-2);
+}
+
+.field {
+ flex: 1 1 0;
+ min-width: 0;
+ max-width: 300px;
+}
+
+.row > :not(.field) {
+ flex: 0 0 auto;
+}
+
+.heading {
+ font-size: 11px;
+ letter-spacing: 0.04em;
+ text-transform: uppercase;
+ color: var(--muted-foreground);
+}
+
+.add {
+ margin-top: var(--spacing-1);
+}
+
+@media (max-width: 720px) {
+ .row {
+ flex-wrap: wrap;
+ }
+
+ .field {
+ max-width: none;
+ }
+}
diff --git a/frontend/src/container/FormAlertChannels/Settings/Slack.tsx b/frontend/src/container/FormAlertChannels/Settings/Slack.tsx
index ca5a818a64..cb053c479b 100644
--- a/frontend/src/container/FormAlertChannels/Settings/Slack.tsx
+++ b/frontend/src/container/FormAlertChannels/Settings/Slack.tsx
@@ -1,90 +1,126 @@
-import { Dispatch, SetStateAction } from 'react';
import { useTranslation } from 'react-i18next';
-import { Form, Input } from 'antd';
-import { MarkdownRenderer } from 'components/MarkdownRenderer/MarkdownRenderer';
+import { Controller, useFormContext } from 'react-hook-form';
+import { Input } from '@signozhq/ui/input';
+import { Input as AntdInput } from 'antd';
-import { SlackChannel } from '../../CreateAlertChannels/config';
+import { ChannelSpecFormValues } from '../../CreateAlertChannels/types';
+import FormCard from '../FormCard';
+import FormField from '../FormField';
+import SlackActions from './SlackActions';
+import SlackFields from './SlackFields';
-const { TextArea } = Input;
+const { TextArea } = AntdInput;
-function Slack({ setSelectedConfig }: SlackProps): JSX.Element {
+function Slack(): JSX.Element {
const { t } = useTranslation('channels');
+ const {
+ register,
+ control,
+ formState: { errors },
+ } = useFormContext<ChannelSpecFormValues>();
return (
<>
- <Form.Item
- name="api_url"
- label={t('field_webhook_url')}
- tooltip={{
- title: (
- <MarkdownRenderer
- markdownContent={t('tooltip_slack_url')}
- variables={{}}
- />
- ),
- overlayInnerStyle: { maxWidth: 400 },
- placement: 'right',
- }}
- >
- <Input
- onChange={(event): void => {
- setSelectedConfig((value) => ({
- ...value,
- api_url: event.target.value,
- }));
- }}
- data-testid="webhook-url-textbox"
- />
- </Form.Item>
+ <FormCard title={t('section_connection')}>
+ <FormField
+ label={t('field_webhook_url')}
+ tooltip={t('tooltip_slack_url')}
+ error={errors.apiUrl?.message}
+ required
+ >
+ <Input
+ {...register('apiUrl')}
+ aria-required
+ data-testid="webhook-url-textbox"
+ />
+ </FormField>
- <Form.Item
- name="channel"
- help={t('slack_channel_help')}
- label={t('field_slack_recipient')}
- >
- <Input
- onChange={(event): void =>
- setSelectedConfig((value) => ({
- ...value,
- channel: event.target.value,
- }))
- }
- data-testid="slack-channel-textbox"
- />
- </Form.Item>
+ <FormField
+ help={t('slack_channel_help')}
+ label={t('field_slack_recipient')}
+ error={errors.channel?.message}
+ >
+ <Input {...register('channel')} data-testid="slack-channel-textbox" />
+ </FormField>
- <Form.Item name="title" label={t('field_slack_title')}>
- <TextArea
- data-testid="title-textarea"
- rows={4}
- // value={`[{{ .Status | toUpper }}{{ if eq .Status \"firing\" }}:{{ .Alerts.Firing | len }}{{ end }}] {{ .CommonLabels.alertname }} for {{ .CommonLabels.job }}\n{{- if gt (len .CommonLabels) (len .GroupLabels) -}}\n{{\" \"}}(\n{{- with .CommonLabels.Remove .GroupLabels.Names }}\n {{- range $index, $label := .SortedPairs -}}\n {{ if $index }}, {{ end }}\n {{- $label.Name }}=\"{{ $label.Value -}}\"\n {{- end }}\n{{- end -}}\n)\n{{- end }}`}
- onChange={(event): void =>
- setSelectedConfig((value) => ({
- ...value,
- title: event.target.value,
- }))
- }
- />
- </Form.Item>
+ <FormField label={t('field_slack_title')} error={errors.title?.message}>
+ <Controller
+ control={control}
+ name="title"
+ render={({ field }): JSX.Element => (
+ <TextArea
+ data-testid="title-textarea"
+ rows={4}
+ value={(field.value as string) ?? ''}
+ onChange={field.onChange}
+ />
+ )}
+ />
+ </FormField>
- <Form.Item name="text" label={t('field_slack_description')}>
- <TextArea
- onChange={(event): void =>
- setSelectedConfig((value) => ({
- ...value,
- text: event.target.value,
- }))
- }
- placeholder={t('placeholder_slack_description')}
- data-testid="description-textarea"
- />
- </Form.Item>
+ <FormField
+ label={t('field_slack_title_link')}
+ error={errors.titleLink?.message}
+ >
+ <Input {...register('titleLink')} data-testid="title-link-textbox" />
+ </FormField>
+
+ <FormField
+ label={t('field_slack_description')}
+ error={errors.text?.message}
+ >
+ <Controller
+ control={control}
+ name="text"
+ render={({ field }): JSX.Element => (
+ <TextArea
+ placeholder={t('placeholder_slack_description')}
+ data-testid="description-textarea"
+ value={(field.value as string) ?? ''}
+ onChange={field.onChange}
+ />
+ )}
+ />
+ </FormField>
+
+ <FormField
+ label={t('field_slack_color')}
+ help={t('help_slack_color')}
+ error={errors.color?.message}
+ >
+ <Input
+ {...register('color')}
+ placeholder={t('placeholder_slack_color')}
+ data-testid="slack-color-textbox"
+ />
+ </FormField>
+
+ <FormField
+ label={t('field_slack_pretext')}
+ help={t('help_slack_pretext')}
+ error={errors.pretext?.message}
+ >
+ <Input {...register('pretext')} data-testid="slack-pretext-textbox" />
+ </FormField>
+
+ <FormField
+ label={t('field_slack_fallback')}
+ help={t('help_slack_fallback')}
+ error={errors.fallback?.message}
+ >
+ <Input {...register('fallback')} data-testid="slack-fallback-textbox" />
+ </FormField>
+
+ <FormField label={t('field_slack_footer')} error={errors.footer?.message}>
+ <Input {...register('footer')} data-testid="slack-footer-textbox" />
+ </FormField>
+
+ <SlackFields />
+
+ <SlackActions />
+ </FormCard>
</>
);
}
-interface SlackProps {
- setSelectedConfig: Dispatch<SetStateAction<Partial<SlackChannel>>>;
-}
-
export default Slack;
diff --git a/frontend/src/container/FormAlertChannels/Settings/SlackActions.tsx b/frontend/src/container/FormAlertChannels/Settings/SlackActions.tsx
new file mode 100644
index 0000000000..47319c8034
--- /dev/null
+++ b/frontend/src/container/FormAlertChannels/Settings/SlackActions.tsx
@@ -0,0 +1,94 @@
+import { useTranslation } from 'react-i18next';
+import { useFieldArray, useFormContext } from 'react-hook-form';
+import { Minus, Plus } from '@signozhq/icons';
+import { Button } from '@signozhq/ui/button';
+import { Input } from '@signozhq/ui/input';
+import { Typography } from '@signozhq/ui/typography';
+import { AlertmanagertypesChannelSlackActionDTO } from 'api/generated/services/sigNoz.schemas';
+
+import { ChannelSpecFormValues } from '../../CreateAlertChannels/types';
+import FormField from '../FormField';
+import styles from './RowEditor.module.scss';
+
+/** `confirm` is an object on the DTO, so its one editable field is reached by path. */
+type ActionColumn =
+ | Exclude<keyof AlertmanagertypesChannelSlackActionDTO, 'confirm' | 'short'>
+ | 'confirm.text';
+
+const COLUMNS = [
+ 'text',
+ 'url',
+ 'name',
+ 'value',
+ 'style',
+ 'confirm.text',
+] as const satisfies readonly ActionColumn[];
+
+function SlackActions(): JSX.Element {
+ const { t } = useTranslation('channels');
+ const { control, register } = useFormContext<ChannelSpecFormValues>();
+ const { fields, append, remove } = useFieldArray({ control, name: 'actions' });
+
+ const labelFor = (column: ActionColumn): string =>
+ t(`label_slack_action_${column.replace('.text', '')}`);
+
+ return (
+ <FormField label={t('field_slack_actions')} help={t('help_slack_actions')}>
+ <div>
+ {fields.length > 0 && (
+ <div className={styles.row}>
+ {COLUMNS.map((column) => (
+ <div key={column} className={styles.field}>
+ <Typography.Text size="sm" className={styles.heading}>
+ {labelFor(column)}
+ </Typography.Text>
+ </div>
+ ))}
+ </div>
+ )}
+
+ {fields.map((row, index) => (
+ <div key={row.id} className={styles.row}>
+ {COLUMNS.map((column) => (
+ <div key={column} className={styles.field}>
+ <Input
+ {...register(`actions.${index}.${column}` as const)}
+ placeholder={t(
+ `placeholder_slack_action_${column.replace('.text', '')}`,
+ )}
+ testId={`slack-action-${column.replace('.text', '')}-${index}`}
+ />
+ </div>
+ ))}
+ <Button
+ variant="ghost"
+ color="secondary"
+ size="sm"
+ icon
+ aria-label={t('remove_slack_action')}
+ onClick={(): void => remove(index)}
+ testId={`slack-action-remove-${index}`}
+ >
+ <Minus size={14} />
+ </Button>
+ </div>
+ ))}
+ </div>
+
+ <div className={styles.add}>
+ <Button
+ variant="dashed"
+ color="secondary"
+ size="sm"
+ prefix={<Plus size={14} />}
+ onClick={(): void => append({ type: 'button', text: '', url: '' })}
+ testId="slack-action-add"
+ >
+ {t('add_slack_action')}
+ </Button>
+ </div>
+ </FormField>
+ );
+}
+
+export default SlackActions;
diff --git a/frontend/src/container/FormAlertChannels/Settings/SlackFields.tsx b/frontend/src/container/FormAlertChannels/Settings/SlackFields.tsx
new file mode 100644
index 0000000000..9e0ca5c914
--- /dev/null
+++ b/frontend/src/container/FormAlertChannels/Settings/SlackFields.tsx
@@ -0,0 +1,85 @@
+import { useTranslation } from 'react-i18next';
+import { Controller, useFieldArray, useFormContext } from 'react-hook-form';
+import { Minus, Plus } from '@signozhq/icons';
+import { Button } from '@signozhq/ui/button';
+import { Checkbox } from '@signozhq/ui/checkbox';
+import { Input } from '@signozhq/ui/input';
+import { Typography } from '@signozhq/ui/typography';
+
+import { ChannelSpecFormValues } from '../../CreateAlertChannels/types';
+import FormField from '../FormField';
+import styles from './RowEditor.module.scss';
+
+// Slack renders these as the attachment's table of short or full-width entries.
+function SlackFields(): JSX.Element {
+ const { t } = useTranslation('channels');
+ const { control, register } = useFormContext<ChannelSpecFormValues>();
+ const { fields, append, remove } = useFieldArray({ control, name: 'fields' });
+
+ return (
+ <FormField label={t('field_slack_fields')} help={t('help_slack_fields')}>
+ <div>
+ {fields.map((row, index) => (
+ <div key={row.id} className={styles.row}>
+ <div className={styles.field}>
+ <Input
+ {...register(`fields.${index}.title`)}
+ placeholder={t('placeholder_slack_field_title')}
+ testId={`slack-field-title-${index}`}
+ />
+ </div>
+ <div className={styles.field}>
+ <Input
+ {...register(`fields.${index}.value`)}
+ placeholder={t('placeholder_slack_field_value')}
+ testId={`slack-field-value-${index}`}
+ />
+ </div>
+ <Controller
+ control={control}
+ name={`fields.${index}.short`}
+ render={({ field }): JSX.Element => (
+ <Checkbox
+ color="primary"
+ value={!!field.value}
+ onChange={(checked): void => field.onChange(checked === true)}
+ testId={`slack-field-short-${index}`}
+ >
+ <Typography.Text size="sm">
+ {t('field_slack_field_short')}
+ </Typography.Text>
+ </Checkbox>
+ )}
+ />
+ <Button
+ variant="ghost"
+ color="secondary"
+ size="sm"
+ icon
+ aria-label={t('remove_slack_field')}
+ onClick={(): void => remove(index)}
+ testId={`slack-field-remove-${index}`}
+ >
+ <Minus size={14} />
+ </Button>
+ </div>
+ ))}
+ </div>
+
+ <div className={styles.add}>
+ <Button
+ variant="dashed"
+ color="secondary"
+ size="sm"
+ prefix={<Plus size={14} />}
+ onClick={(): void => append({ title: '', value: '', short: false })}
+ testId="slack-field-add"
+ >
+ {t('add_slack_field')}
+ </Button>
+ </div>
+ </FormField>
+ );
+}
+
+export default SlackFields;
diff --git a/frontend/src/container/FormAlertChannels/Settings/Webhook.tsx b/frontend/src/container/FormAlertChannels/Settings/Webhook.tsx
index 2d1bdb4b94..b99576c2ff 100644
--- a/frontend/src/container/FormAlertChannels/Settings/Webhook.tsx
+++ b/frontend/src/container/FormAlertChannels/Settings/Webhook.tsx
@@ -1,77 +1,65 @@
-import { Dispatch, SetStateAction } from 'react';
import { useTranslation } from 'react-i18next';
+import { useFormContext } from 'react-hook-form';
import { Input } from '@signozhq/ui/input';
-import { Form } from 'antd';
-import { MarkdownRenderer } from 'components/MarkdownRenderer/MarkdownRenderer';
-import { WebhookChannel } from '../../CreateAlertChannels/config';
+import { ChannelSpecFormValues } from '../../CreateAlertChannels/types';
+import FormCard from '../FormCard';
+import FormField from '../FormField';
-function WebhookSettings({ setSelectedConfig }: WebhookProps): JSX.Element {
+function WebhookSettings(): JSX.Element {
const { t } = useTranslation('channels');
+ const {
+ register,
+ formState: { errors },
+ } = useFormContext<ChannelSpecFormValues>();
return (
<>
- <Form.Item
- name="api_url"
- label={t('field_webhook_url')}
- tooltip={{
- title: (
- <MarkdownRenderer
- markdownContent={t('tooltip_webhook_url')}
- variables={{}}
- />
- ),
- overlayInnerStyle: { maxWidth: 400 },
- placement: 'right',
- }}
- >
- <Input
- onChange={(event): void => {
- setSelectedConfig((value) => ({
- ...value,
- api_url: event.target.value,
- }));
- }}
- data-testid="webhook-url-textbox"
- />
- </Form.Item>
- <Form.Item
- name="username"
- label={t('field_webhook_username')}
- help={t('help_webhook_username')}
- >
- <Input
- onChange={(event): void => {
- setSelectedConfig((value) => ({
- ...value,
- username: event.target.value,
- }));
- }}
- data-testid="webhook-username-textbox"
- />
- </Form.Item>
- <Form.Item
- name="password"
- label="Password (optional)"
- help={t('help_webhook_password')}
- >
- <Input
- type="password"
- onChange={(event): void => {
- setSelectedConfig((value) => ({
- ...value,
- password: event.target.value,
- }));
- }}
- data-testid="webhook-password-textbox"
- />
- </Form.Item>
+ <FormCard title={t('section_connection')}>
+ <FormField
+ label={t('field_webhook_url')}
+ tooltip={t('tooltip_webhook_url')}
+ error={errors.url?.message}
+ required
+ >
+ <Input
+ {...register('url')}
+ aria-required
+ data-testid="webhook-url-textbox"
+ />
+ </FormField>
+ <FormField
+ label={t('field_webhook_username')}
+ help={t('help_webhook_username')}
+ error={errors.username?.message}
+ >
+ <Input {...register('username')} data-testid="webhook-username-textbox" />
+ </FormField>
+ <FormField
+ label="Password (optional)"
+ help={t('help_webhook_password')}
+ error={errors.password?.message}
+ >
+ <Input
+ {...register('password')}
+ type="password"
+ data-testid="webhook-password-textbox"
+ />
+ </FormField>
+ <FormField
+ label={t('field_webhook_bearer_token')}
+ help={t('help_webhook_bearer_token')}
+ error={errors.bearerToken?.message}
+ >
+ <Input
+ {...register('bearerToken')}
+ type="password"
+ data-testid="webhook-bearer-token-textbox"
+ />
+ </FormField>
+ </FormCard>
</>
);
}
-interface WebhookProps {
- setSelectedConfig: Dispatch<SetStateAction<Partial<WebhookChannel>>>;
-}
-
export default WebhookSettings;
diff --git a/frontend/src/container/FormAlertChannels/__tests__/FormAlertChannels.test.tsx b/frontend/src/container/FormAlertChannels/__tests__/FormAlertChannels.test.tsx
index f13ae8c07d..16ba0c5a03 100644
--- a/frontend/src/container/FormAlertChannels/__tests__/FormAlertChannels.test.tsx
+++ b/frontend/src/container/FormAlertChannels/__tests__/FormAlertChannels.test.tsx
@@ -1,5 +1,8 @@
-import { Form } from 'antd';
-import { ChannelType } from 'container/CreateAlertChannels/config';
+import { useForm } from 'react-hook-form';
+import {
+ ChannelFormValues,
+ ChannelKind,
+} from 'container/CreateAlertChannels/types';
import { act, render, renderHook, screen } from 'tests/test-utils';
import FormAlertChannels from '..';
@@ -10,31 +13,28 @@ jest.mock('components/MarkdownRenderer/MarkdownRenderer', () => ({
describe('FormAlertChannels', () => {
it('keeps the send resolved switch in sync when the value arrives after mount', () => {
- const {
- result: {
- current: [formInstance],
- },
- } = renderHook(() => Form.useForm());
+ const { result } = renderHook(() =>
+ useForm<ChannelFormValues>({ defaultValues: { name: 'Dummy-Channel' } }),
+ );
+
render(
<FormAlertChannels
- formInstance={formInstance}
- type={ChannelType.Slack}
- setSelectedConfig={jest.fn()}
+ form={result.current}
+ type={ChannelKind.slack}
onTypeChangeHandler={jest.fn()}
onSaveHandler={jest.fn()}
onTestHandler={jest.fn()}
testingState={false}
savingState={false}
- title="Edit"
- initialValue={{ name: 'Dummy-Channel', type: ChannelType.Slack }}
editing
/>,
);
+
const sendResolvedSwitch = screen.getByTestId('field-send-resolved-checkbox');
expect(sendResolvedSwitch).not.toBeChecked();
act(() => {
- formInstance.setFieldsValue({ send_resolved: true });
+ result.current.setValue('sendResolved', true);
});
expect(sendResolvedSwitch).toBeChecked();
diff --git a/frontend/src/container/FormAlertChannels/index.tsx b/frontend/src/container/FormAlertChannels/index.tsx
index 09cd277818..d7d767ac95 100644
--- a/frontend/src/container/FormAlertChannels/index.tsx
+++ b/frontend/src/container/FormAlertChannels/index.tsx
@@ -1,24 +1,13 @@
-import { Dispatch, ReactElement, SetStateAction } from 'react';
+import { ReactElement } from 'react';
import { useTranslation } from 'react-i18next';
+import { Controller, FormProvider, UseFormReturn } from 'react-hook-form';
import { Input } from '@signozhq/ui/input';
+import { SelectSimple } from '@signozhq/ui/select';
import { Switch } from '@signozhq/ui/switch';
-import { Form, FormInstance, Select } from 'antd';
-import { Typography } from '@signozhq/ui/typography';
-import type { Store } from 'antd/lib/form/interface';
-import ROUTES from 'constants/routes';
import {
- ChannelType,
- EmailChannel,
- GoogleChatChannel,
- IncidentIOChannel,
- JiraChannel,
- JsmOpsChannel,
- OpsgenieChannel,
- PagerChannel,
- SlackChannel,
- WebhookChannel,
-} from 'container/CreateAlertChannels/config';
-import history from 'lib/history';
+ ChannelFormValues,
+ ChannelKind,
+} from 'container/CreateAlertChannels/types';
import EmailSettings from './Settings/Email';
import GoogleChatSettings from './Settings/GoogleChat';
@@ -30,214 +19,156 @@ import OpsgenieSettings from './Settings/Opsgenie';
import PagerSettings from './Settings/Pager';
import SlackSettings from './Settings/Slack';
import WebhookSettings from './Settings/Webhook';
-import { Button } from './styles';
+import { Button } from '@signozhq/ui/button';
+
+import FormCard from './FormCard';
+import FormField from './FormField';
+import styles from './FormAlertChannels.module.scss';
+
+const CHANNEL_TYPE_OPTIONS = [
+ { value: ChannelKind.slack, label: 'Slack' },
+ { value: ChannelKind.webhook, label: 'Webhook' },
+ { value: ChannelKind.pagerduty, label: 'Pagerduty' },
+ { value: ChannelKind.opsgenie, label: 'Opsgenie' },
+ { value: ChannelKind.email, label: 'Email' },
+ { value: ChannelKind.msteams, label: 'Microsoft Teams' },
+ { value: ChannelKind.googlechat, label: 'Google Chat' },
+ { value: ChannelKind.jira, label: 'Jira' },
+ { value: ChannelKind.jsmops, label: 'Jira Service Management Ops' },
+ { value: ChannelKind.incidentio, label: 'incident.io' },
+];
function FormAlertChannels({
- formInstance,
+ form,
type,
- setSelectedConfig,
onTypeChangeHandler,
onTestHandler,
onSaveHandler,
savingState,
testingState,
- title,
- initialValue,
editing = false,
}: FormAlertChannelsProps): JSX.Element {
const { t } = useTranslation('channels');
+ const {
+ register,
+ control,
+ formState: { errors },
+ } = form;
const renderSettings = (): ReactElement | null => {
switch (type) {
- case ChannelType.Slack:
- return <SlackSettings setSelectedConfig={setSelectedConfig} />;
- case ChannelType.Webhook:
- return <WebhookSettings setSelectedConfig={setSelectedConfig} />;
- case ChannelType.Pagerduty:
- return <PagerSettings setSelectedConfig={setSelectedConfig} />;
- case ChannelType.MsTeams:
- return <MsTeamsSettings setSelectedConfig={setSelectedConfig} />;
- case ChannelType.GoogleChat:
- return <GoogleChatSettings setSelectedConfig={setSelectedConfig} />;
- case ChannelType.Jira:
- return <JiraSettings setSelectedConfig={setSelectedConfig} />;
- case ChannelType.JsmOps:
- return <JsmOpsSettings setSelectedConfig={setSelectedConfig} />;
- case ChannelType.IncidentIO:
- return (
- <IncidentIOSettings
- setSelectedConfig={setSelectedConfig}
- initialMetadata={initialValue?.metadata as Record<string, string>}
- />
- );
- case ChannelType.Opsgenie:
- return <OpsgenieSettings setSelectedConfig={setSelectedConfig} />;
- case ChannelType.Email:
- return <EmailSettings setSelectedConfig={setSelectedConfig} />;
+ case ChannelKind.slack:
+ return <SlackSettings />;
+ case ChannelKind.webhook:
+ return <WebhookSettings />;
+ case ChannelKind.pagerduty:
+ return <PagerSettings />;
+ case ChannelKind.msteams:
+ return <MsTeamsSettings />;
+ case ChannelKind.googlechat:
+ return <GoogleChatSettings />;
+ case ChannelKind.jira:
+ return <JiraSettings />;
+ case ChannelKind.jsmops:
+ return <JsmOpsSettings />;
+ case ChannelKind.incidentio:
+ return <IncidentIOSettings />;
+ case ChannelKind.opsgenie:
+ return <OpsgenieSettings />;
+ case ChannelKind.email:
+ return <EmailSettings />;
default:
return null;
}
};
return (
- <>
- <Typography.Title level={4} className="form-alert-channels-title">
- {title}
- </Typography.Title>
-
- <Form initialValues={initialValue} layout="vertical" form={formInstance}>
- <Form.Item label={t('field_channel_name')} labelAlign="left" name="name">
- <Input
- data-testid="channel-name-textbox"
- disabled={editing}
- onChange={(event): void => {
- setSelectedConfig((state) => ({
- ...state,
- name: event.target.value,
- }));
- }}
- />
- </Form.Item>
-
- <Form.Item
- label={t('field_send_resolved')}
- labelAlign="left"
- name="send_resolved"
- getValueProps={(value): { value: boolean } => ({ value: !!value })}
- >
- <Switch
- color="primary"
- textPlacement="right"
- testId="field-send-resolved-checkbox"
- onChange={(value): void => {
- setSelectedConfig((state) => ({
- ...state,
- send_resolved: value,
- }));
- }}
- />
- </Form.Item>
-
- <Form.Item label={t('field_channel_type')} labelAlign="left" name="type">
- <Select
- disabled={editing}
- onChange={onTypeChangeHandler}
- value={type}
- data-testid="channel-type-select"
- >
- <Select.Option value="slack" key="slack" data-testid="select-option">
- Slack
- </Select.Option>
- <Select.Option value="webhook" key="webhook" data-testid="select-option">
- Webhook
- </Select.Option>
- <Select.Option
- value="pagerduty"
- key="pagerduty"
- data-testid="select-option"
+ <FormProvider {...form}>
+ <form className={styles.form}>
+ <div className={styles.cards}>
+ <FormCard title={t('section_general')}>
+ <FormField
+ label={t('field_channel_name')}
+ help={editing ? t('help_channel_name_immutable') : undefined}
+ error={errors.name?.message}
+ htmlFor="channel-name"
+ required
>
- Pagerduty
- </Select.Option>
- <Select.Option
- value="opsgenie"
- key="opsgenie"
- data-testid="select-option"
- >
- Opsgenie
- </Select.Option>
- <Select.Option value="email" key="email" data-testid="select-option">
- Email
- </Select.Option>
-
- <Select.Option value="msteams" key="msteams" data-testid="select-option">
- Microsoft Teams
- </Select.Option>
-
- <Select.Option
- value="googlechat"
- key="googlechat"
- data-testid="select-option"
- >
- Google Chat
- </Select.Option>
-
- <Select.Option value="jira" key="jira" data-testid="select-option">
- Jira
- </Select.Option>
-
- <Select.Option value="jsmops" key="jsmops" data-testid="select-option">
- Jira Service Management Ops
- </Select.Option>
-
- <Select.Option
- value="incidentio"
- key="incidentio"
- data-testid="select-option"
- >
- incident.io
- </Select.Option>
- </Select>
- </Form.Item>
-
- <Form.Item>{renderSettings()}</Form.Item>
-
- <Form.Item>
+ <Input
+ id="channel-name"
+ data-testid="channel-name-textbox"
+ disabled={editing}
+ aria-required
+ {...register('name')}
+ />
+ </FormField>
+
+ <FormField label={t('field_send_resolved')}>
+ <Controller
+ control={control}
+ name="sendResolved"
+ render={({ field }): JSX.Element => (
+ <Switch
+ color="primary"
+ textPlacement="right"
+ testId="field-send-resolved-checkbox"
+ value={!!field.value}
+ onChange={field.onChange}
+ />
+ )}
+ />
+ </FormField>
+
+ <FormField label={t('field_channel_type')} htmlFor="channel-type">
+ <SelectSimple
+ id="channel-type"
+ items={CHANNEL_TYPE_OPTIONS}
+ value={type}
+ disabled={editing}
+ onChange={(value): void => onTypeChangeHandler(value as ChannelKind)}
+ testId="channel-type-select"
+ />
+ </FormField>
+ </FormCard>
+
+ {renderSettings()}
+ </div>
+
+ <div className={styles.actions}>
<Button
- data-testid="save-channel-button"
- disabled={savingState}
+ variant="solid"
+ color="primary"
+ size="md"
+ testId="save-channel-button"
loading={savingState}
- type="primary"
- onClick={(): void => onSaveHandler(type)}
+ onClick={onSaveHandler}
>
{t('button_save_channel')}
</Button>
<Button
- data-testid="test-channel-button"
- disabled={testingState}
+ variant="outlined"
+ color="secondary"
+ size="md"
+ testId="test-channel-button"
loading={testingState}
- onClick={(): void => onTestHandler(type)}
+ onClick={onTestHandler}
>
{t('button_test_channel')}
</Button>
- <Button
- data-testid="return-button"
- onClick={(): void => {
- history.replace(ROUTES.ALL_CHANNELS);
- }}
- >
- {t('button_return')}
- </Button>
- </Form.Item>
- </Form>
- </>
+ </div>
+ </form>
+ </FormProvider>
);
}
interface FormAlertChannelsProps {
- formInstance: FormInstance;
- type: ChannelType;
- setSelectedConfig: Dispatch<
- SetStateAction<
- Partial<
- SlackChannel &
- WebhookChannel &
- PagerChannel &
- OpsgenieChannel &
- EmailChannel &
- GoogleChatChannel &
- JiraChannel &
- JsmOpsChannel &
- IncidentIOChannel
- >
- >
- >;
- onTypeChangeHandler: (value: ChannelType) => void;
- onSaveHandler: (props: ChannelType) => void;
- onTestHandler: (props: ChannelType) => void;
+ form: UseFormReturn<ChannelFormValues>;
+ type: ChannelKind;
+ onTypeChangeHandler: (value: ChannelKind) => void;
+ onSaveHandler: () => void;
+ onTestHandler: () => void;
testingState: boolean;
savingState: boolean;
- title: string;
- initialValue: Store;
// editing indicates if the form is opened in edit mode
editing?: boolean;
}
diff --git a/frontend/src/pages/AlertList/ChannelsEdit/stories/ChannelsEdit.stories.mocks.tsx b/frontend/src/pages/AlertList/ChannelsEdit/stories/ChannelsEdit.stories.mocks.tsx
index 4e728bf2d1..2fc105175d 100644
--- a/frontend/src/pages/AlertList/ChannelsEdit/stories/ChannelsEdit.stories.mocks.tsx
+++ b/frontend/src/pages/AlertList/ChannelsEdit/stories/ChannelsEdit.stories.mocks.tsx
@@ -13,7 +13,7 @@ import {
CHANNEL_ACTION_OUTCOMES,
channelActionError,
CHANNEL_TYPES,
- channelResponse,
+ notificationChannelResponse,
type ChannelActionOutcome,
type ChannelType,
} from '../../stories/__story_mockdata__/alerts';
@@ -51,21 +51,21 @@ export const channelsEditMocks = defineStoryMocks({
},
handlers: (values, response) => [
rest.get(
- 'http://localhost/api/v1/channels/:id',
+ 'http://localhost/api/v2/notification_channels/:id',
response.json((req) =>
- channelResponse(String(req.params.id), values.channelType),
+ notificationChannelResponse(String(req.params.id), values.channelType),
),
),
rest.put(
- 'http://localhost/api/v1/channels/:id',
+ 'http://localhost/api/v2/notification_channels/:id',
values.saveOutcome === 'fails'
? rejectChannelAction
: resolveChannelActionSuccess,
),
rest.post(
- 'http://localhost/api/v1/testChannel',
+ 'http://localhost/api/v2/notification_channels/test',
values.testOutcome === 'fails'
? rejectChannelAction
: resolveChannelActionSuccess,
diff --git a/frontend/src/pages/AlertList/ChannelsEdit/stories/ChannelsEdit.stories.tsx b/frontend/src/pages/AlertList/ChannelsEdit/stories/ChannelsEdit.stories.tsx
index f2cde2336c..cd174a7062 100644
--- a/frontend/src/pages/AlertList/ChannelsEdit/stories/ChannelsEdit.stories.tsx
+++ b/frontend/src/pages/AlertList/ChannelsEdit/stories/ChannelsEdit.stories.tsx
@@ -1,5 +1,5 @@
import type { Meta, StoryObj } from '@storybook/react-vite';
-import { screen, userEvent, within } from 'storybook/test';
+import { expect, screen, userEvent, within } from 'storybook/test';
import { storyMocks } from '@/storybook/controls/defineStoryMocks';
import type { PageStoryArgs } from '@/storybook/runtime/resolveStory';
@@ -142,6 +142,17 @@ export const GoogleChat: Story = {
*/
export const Jira: Story = {
args: { channelType: 'jira' },
+ play: async ({ canvasElement }): Promise<void> => {
+ // the advanced fields have their own card now, so nothing has to be
+ // expanded before they can be read
+ await expect(
+ await within(canvasElement).findByTestId(
+ 'jira-reopen-duration-textbox',
+ undefined,
+ { timeout: 15_000 },
+ ),
+ ).toBeVisible();
+ },
};
/**
diff --git a/frontend/src/pages/AlertList/ChannelsNew/stories/ChannelsNew.stories.mocks.tsx b/frontend/src/pages/AlertList/ChannelsNew/stories/ChannelsNew.stories.mocks.tsx
index f61b61155f..56bd11f036 100644
--- a/frontend/src/pages/AlertList/ChannelsNew/stories/ChannelsNew.stories.mocks.tsx
+++ b/frontend/src/pages/AlertList/ChannelsNew/stories/ChannelsNew.stories.mocks.tsx
@@ -46,12 +46,12 @@ export const channelsNewMocks = defineStoryMocks({
},
handlers: (values) => [
rest.post(
- 'http://localhost/api/v1/channels',
+ 'http://localhost/api/v2/notification_channels',
values.saveOutcome === 'fails' ? rejectChannelAction : resolveChannelCreated,
),
rest.post(
- 'http://localhost/api/v1/testChannel',
+ 'http://localhost/api/v2/notification_channels/test',
values.testOutcome === 'fails' ? rejectChannelAction : resolveChannelTested,
),
],
diff --git a/frontend/src/pages/AlertList/ChannelsNew/stories/ChannelsNew.stories.tsx b/frontend/src/pages/AlertList/ChannelsNew/stories/ChannelsNew.stories.tsx
index 2bdd242d5e..280f1fe3d5 100644
--- a/frontend/src/pages/AlertList/ChannelsNew/stories/ChannelsNew.stories.tsx
+++ b/frontend/src/pages/AlertList/ChannelsNew/stories/ChannelsNew.stories.tsx
@@ -1,5 +1,5 @@
import type { Meta, StoryObj } from '@storybook/react-vite';
-import { screen, userEvent, within } from 'storybook/test';
+import { expect, screen, userEvent, within } from 'storybook/test';
import { storyMocks } from '@/storybook/controls/defineStoryMocks';
import type { PageStoryArgs } from '@/storybook/runtime/resolveStory';
@@ -29,22 +29,17 @@ export default meta;
type Story = StoryObj<ChannelsNewArgs>;
-/**
- * The type is an antd Select: clicking the element carrying the test id does
- * nothing, the combobox inside it is what opens the list.
- */
const selectChannelType = async (
canvasElement: HTMLElement,
label: RegExp,
): Promise<void> => {
- const canvas = within(canvasElement);
- const select = await canvas.findByTestId('channel-type-select');
-
- await userEvent.click(within(select).getByRole('combobox'));
- await userEvent.click(await screen.findByTitle(label));
- // The form under the Select swaps a render after the option is taken, so the
- // Select's own value is what says the story is on the type it names.
- await within(select).findByTitle(label);
+ const trigger = await within(canvasElement).findByTestId(
+ 'channel-type-select',
+ );
+
+ await userEvent.click(trigger);
+ await userEvent.click(await screen.findByRole('option', { name: label }));
+ await within(trigger).findByText(label);
};
/** A new notification channel, on the Slack form the page opens with. */
@@ -53,11 +48,9 @@ export const Default: Story = {};
/** Interaction: the channel-type Select opens its real portal-backed option list. */
export const ChannelTypeSelectOpen: Story = {
play: async ({ canvasElement }): Promise<void> => {
- const select = await within(canvasElement).findByTestId(
- 'channel-type-select',
+ await userEvent.click(
+ await within(canvasElement).findByTestId('channel-type-select'),
);
-
- await userEvent.click(within(select).getByRole('combobox'));
await screen.findByRole('listbox');
},
};
@@ -79,9 +72,17 @@ export const TestChannelFailure: Story = {
// the point of the story, not a regression.
parameters: { allowConsoleErrors: true },
play: async ({ canvasElement }): Promise<void> => {
- await userEvent.click(
- await within(canvasElement).findByTestId('test-channel-button'),
+ const canvas = within(canvasElement);
+
+ await userEvent.type(
+ await canvas.findByTestId('channel-name-textbox'),
+ 'Storybook channel',
+ );
+ await userEvent.type(
+ await canvas.findByTestId('webhook-url-textbox'),
+ 'https://hooks.slack.com/services/storybook',
);
+ await userEvent.click(await canvas.findByTestId('test-channel-button'));
await screen.findByText('Storybook forced channel failure');
},
};
@@ -176,3 +177,25 @@ export const IncidentIO: Story = {
await selectChannelType(canvasElement, /^incident\.io$/);
},
};
+
+/**
+ * The fields the API rejects a save without are marked before anything is
+ * submitted, so a long form does not have to be guessed at.
+ */
+export const RequiredFields: Story = {
+ play: async ({ canvasElement }): Promise<void> => {
+ const canvas = within(canvasElement);
+
+ await expect(
+ await canvas.findByTestId('channel-name-textbox', undefined, {
+ timeout: 15_000,
+ }),
+ ).toHaveAttribute('aria-required', 'true');
+ // slack is the kind the form opens on, and its webhook URL is its one
+ // required spec field
+ await expect(canvas.getByTestId('webhook-url-textbox')).toHaveAttribute(
+ 'aria-required',
+ 'true',
+ );
+ },
+};
diff --git a/frontend/src/pages/AlertList/NotificationChannels/__tests__/ChannelForm.test.tsx b/frontend/src/pages/AlertList/NotificationChannels/__tests__/ChannelForm.test.tsx
new file mode 100644
index 0000000000..102b160fd1
--- /dev/null
+++ b/frontend/src/pages/AlertList/NotificationChannels/__tests__/ChannelForm.test.tsx
@@ -0,0 +1,28 @@
+import { server } from 'mocks-server/server';
+import { render, screen } from 'tests/test-utils';
+
+import ChannelForm from '../components/ChannelForm/ChannelForm';
+
+const FIND = { timeout: 5000 };
+
+describe('ChannelForm', () => {
+ beforeEach(() => {
+ window.history.replaceState({}, '', '/');
+ });
+
+ afterEach(() => {
+ jest.restoreAllMocks();
+ server.resetHandlers();
+ });
+
+ it('prefills the channel it was opened on', async () => {
+ render(<ChannelForm channelId="3" onDone={jest.fn()} />);
+
+ const name = await screen.findByTestId('channel-name-textbox', {}, FIND);
+ expect(name).toHaveValue('Dummy-Channel');
+
+ expect(screen.getByTestId('webhook-url-textbox')).toHaveValue(
+ 'https://hooks.slack.com/services/dummy',
+ );
+ }, 20000);
+});
diff --git a/frontend/src/pages/AlertList/NotificationChannels/__tests__/ChannelFormPrefill.test.tsx b/frontend/src/pages/AlertList/NotificationChannels/__tests__/ChannelFormPrefill.test.tsx
new file mode 100644
index 0000000000..64581a0cf7
--- /dev/null
+++ b/frontend/src/pages/AlertList/NotificationChannels/__tests__/ChannelFormPrefill.test.tsx
@@ -0,0 +1,236 @@
+import { server } from 'mocks-server/server';
+import { rest } from 'msw';
+import { render, screen } from 'tests/test-utils';
+
+import ChannelForm from '../components/ChannelForm/ChannelForm';
+
+const FIND = { timeout: 5000 };
+
+interface PrefillCase {
+ kind: string;
+ spec: Record<string, unknown>;
+ fields: [string, string][];
+}
+
+const CASES: PrefillCase[] = [
+ {
+ kind: 'slack',
+ spec: {
+ apiUrl: 'https://hooks.slack.com/services/T/B/X',
+ channel: '#ops',
+ title: 'slack title',
+ titleLink: 'https://signoz.io',
+ text: 'slack body',
+ color: 'danger',
+ pretext: 'slack pretext',
+ fallback: 'slack fallback',
+ footer: 'slack footer',
+ },
+ fields: [
+ ['webhook-url-textbox', 'https://hooks.slack.com/services/T/B/X'],
+ ['slack-channel-textbox', '#ops'],
+ ['title-textarea', 'slack title'],
+ ['title-link-textbox', 'https://signoz.io'],
+ ['description-textarea', 'slack body'],
+ ['slack-color-textbox', 'danger'],
+ ['slack-pretext-textbox', 'slack pretext'],
+ ['slack-fallback-textbox', 'slack fallback'],
+ ['slack-footer-textbox', 'slack footer'],
+ ],
+ },
+ {
+ kind: 'webhook',
+ spec: {
+ url: 'https://example.com/hook',
+ username: 'hook-user',
+ password: 'hook-pass',
+ bearerToken: 'hook-token',
+ },
+ fields: [
+ ['webhook-url-textbox', 'https://example.com/hook'],
+ ['webhook-username-textbox', 'hook-user'],
+ ['webhook-password-textbox', 'hook-pass'],
+ ['webhook-bearer-token-textbox', 'hook-token'],
+ ],
+ },
+ {
+ kind: 'email',
+ spec: { to: '[email protected]', html: '<p>alert</p>' },
+ fields: [['email-to-textbox', '[email protected]']],
+ },
+ {
+ kind: 'pagerduty',
+ spec: {
+ routingKey: 'pd-routing-key',
+ description: 'pd description',
+ severity: 'critical',
+ group: 'pd group',
+ class: 'pd class',
+ client: 'pd client',
+ clientUrl: 'https://pd.example.com',
+ },
+ fields: [
+ ['pager-routing-key-textbox', 'pd-routing-key'],
+ ['pager-description-textarea', 'pd description'],
+ ['pager-severity-textbox', 'critical'],
+ ['pager-group-textarea', 'pd group'],
+ ['pager-class-textarea', 'pd class'],
+ ['pager-client-textarea', 'pd client'],
+ ['pager-client-url-textarea', 'https://pd.example.com'],
+ ],
+ },
+ {
+ kind: 'opsgenie',
+ spec: {
+ apiKey: 'og-api-key',
+ message: 'og message',
+ description: 'og description',
+ priority: 'P1',
+ },
+ fields: [
+ ['opsgenie-api-key-textbox', 'og-api-key'],
+ ['opsgenie-message-textarea', 'og message'],
+ ['opsgenie-description-textarea', 'og description'],
+ ['opsgenie-priority-textarea', 'P1'],
+ ],
+ },
+ {
+ kind: 'msteams',
+ spec: {
+ webhookUrl: 'https://teams.example.com/hook',
+ title: 'teams title',
+ text: 'teams body',
+ },
+ fields: [
+ ['webhook-url-textbox', 'https://teams.example.com/hook'],
+ ['title-textarea', 'teams title'],
+ ['description-textarea', 'teams body'],
+ ],
+ },
+ {
+ kind: 'googlechat',
+ spec: {
+ webhookUrl: 'https://chat.googleapis.com/v1/spaces/A',
+ title: 'chat title',
+ text: 'chat body',
+ },
+ fields: [
+ ['webhook-url-textbox', 'https://chat.googleapis.com/v1/spaces/A'],
+ ['title-textarea', 'chat title'],
+ ['description-textarea', 'chat body'],
+ ],
+ },
+ {
+ kind: 'jira',
+ spec: {
+ site: 'https://acme.atlassian.net',
+ project: 'OPS',
+ issueType: 'Task',
+ email: '[email protected]',
+ apiToken: 'jira-token',
+ summary: 'jira summary',
+ description: 'jira description',
+ priority: 'High',
+ resolveTransition: 'Done',
+ reopenTransition: 'Reopen',
+ wontFixResolution: "Won't Fix",
+ reopenDuration: '72h',
+ },
+ fields: [
+ ['jira-site-textbox', 'https://acme.atlassian.net'],
+ ['jira-project-textbox', 'OPS'],
+ ['jira-issue-type-textbox', 'Task'],
+ ['jira-email-textbox', '[email protected]'],
+ ['jira-api-token-textbox', 'jira-token'],
+ ['jira-summary-textarea', 'jira summary'],
+ ['jira-description-textarea', 'jira description'],
+ ['jira-priority-textbox', 'High'],
+ ['jira-resolve-transition-textbox', 'Done'],
+ ['jira-reopen-transition-textbox', 'Reopen'],
+ ['jira-wont-fix-resolution-textbox', "Won't Fix"],
+ ['jira-reopen-duration-textbox', '72h'],
+ ],
+ },
+ {
+ kind: 'jsmops',
+ spec: {
+ apiKey: 'jsm-api-key',
+ message: 'jsm message',
+ description: 'jsm description',
+ priority: 'P2',
+ tags: 'prod,db',
+ },
+ fields: [
+ ['jsmops-api-key-textbox', 'jsm-api-key'],
+ ['jsmops-message-textarea', 'jsm message'],
+ ['jsmops-description-textarea', 'jsm description'],
+ ['jsmops-priority-textarea', 'P2'],
+ ],
+ },
+ {
+ kind: 'incidentio',
+ spec: {
+ url: 'https://api.incident.io/v2/alert_events/http/abc',
+ token: 'incident-token',
+ title: 'incident title',
+ description: 'incident description',
+ },
+ fields: [
+ [
+ 'incidentio-url-textbox',
+ 'https://api.incident.io/v2/alert_events/http/abc',
+ ],
+ ['incidentio-token-textbox', 'incident-token'],
+ ['incidentio-title-textarea', 'incident title'],
+ ['incidentio-description-textarea', 'incident description'],
+ ],
+ },
+];
+
+describe('ChannelForm prefill', () => {
+ beforeEach(() => {
+ window.history.replaceState({}, '', '/');
+ });
+
+ afterEach(() => {
+ jest.restoreAllMocks();
+ server.resetHandlers();
+ });
+
+ it.each(CASES)(
+ 'prefills every $kind field from the API',
+ async ({ kind, spec, fields }) => {
+ server.use(
+ rest.get(
+ 'http://localhost/api/v2/notification_channels/:id',
+ (_, res, ctx) =>
+ res(
+ ctx.status(200),
+ ctx.json({
+ status: 'success',
+ data: {
+ id: '3',
+ name: `${kind}-channel`,
+ displayName: `${kind} channel`,
+ createdAt: '2026-01-01T00:00:00Z',
+ updatedAt: '2026-01-01T00:00:00Z',
+ config: { kind, spec: { ...spec, sendResolved: true } },
+ },
+ }),
+ ),
+ ),
+ );
+
+ render(<ChannelForm channelId="3" onDone={jest.fn()} />);
+
+ await expect(
+ screen.findByTestId('channel-name-textbox', {}, FIND),
+ ).resolves.toHaveValue(`${kind} channel`);
+
+ fields.forEach(([testId, expected]) => {
+ expect(screen.getByTestId(testId)).toHaveValue(expected);
+ });
+ },
+ 20000,
+ );
+});
diff --git a/frontend/src/pages/AlertList/NotificationChannels/__tests__/ChannelFormSave.test.tsx b/frontend/src/pages/AlertList/NotificationChannels/__tests__/ChannelFormSave.test.tsx
new file mode 100644
index 0000000000..030e988219
--- /dev/null
+++ b/frontend/src/pages/AlertList/NotificationChannels/__tests__/ChannelFormSave.test.tsx
@@ -0,0 +1,134 @@
+import { server } from 'mocks-server/server';
+import { rest } from 'msw';
+import { render, screen, userEvent, waitFor } from 'tests/test-utils';
+
+import ChannelForm from '../components/ChannelForm/ChannelForm';
+
+const FIND = { timeout: 5000 };
+const TEST_TIMEOUT = 20000;
+
+describe('ChannelForm save', () => {
+ beforeEach(() => {
+ window.history.replaceState({}, '', '/');
+ });
+
+ afterEach(() => {
+ jest.restoreAllMocks();
+ server.resetHandlers();
+ });
+
+ it(
+ 'creates with a generated name and the typed config',
+ async () => {
+ let body: Record<string, unknown> | undefined;
+ server.use(
+ rest.post(
+ 'http://localhost/api/v2/notification_channels',
+ async (req, res, ctx) => {
+ body = await req.json();
+ return res(ctx.status(201), ctx.json({ status: 'success', data: {} }));
+ },
+ ),
+ );
+
+ const onDone = jest.fn();
+ render(<ChannelForm onDone={onDone} />);
+
+ const user = userEvent.setup({ delay: null, pointerEventsCheck: 0 });
+ await user.type(
+ await screen.findByTestId('channel-name-textbox', {}, FIND),
+ 'prod alerts',
+ );
+ await user.type(
+ screen.getByTestId('webhook-url-textbox'),
+ 'https://hooks.slack.com/services/T/B/X',
+ );
+ await user.click(screen.getByTestId('save-channel-button'));
+
+ await waitFor(() => expect(onDone).toHaveBeenCalled(), FIND);
+
+ expect(body).toMatchObject({
+ generateName: true,
+ displayName: 'prod alerts',
+ config: {
+ kind: 'slack',
+ spec: { apiUrl: 'https://hooks.slack.com/services/T/B/X' },
+ },
+ });
+ // the API rejects a name alongside generateName
+ expect(body).not.toHaveProperty('name');
+ },
+ TEST_TIMEOUT,
+ );
+
+ it(
+ 'updates with the config only, since both names are immutable',
+ async () => {
+ let body: Record<string, unknown> | undefined;
+ server.use(
+ rest.put(
+ 'http://localhost/api/v2/notification_channels/:id',
+ async (req, res, ctx) => {
+ body = await req.json();
+ return res(ctx.status(200), ctx.json({ status: 'success', data: {} }));
+ },
+ ),
+ );
+
+ const onDone = jest.fn();
+ render(<ChannelForm channelId="3" onDone={onDone} />);
+
+ const channelName = await screen.findByTestId(
+ 'channel-name-textbox',
+ {},
+ FIND,
+ );
+ expect(channelName).toBeDisabled();
+
+ const user = userEvent.setup({ delay: null, pointerEventsCheck: 0 });
+ await user.clear(screen.getByTestId('slack-channel-textbox'));
+ await user.type(screen.getByTestId('slack-channel-textbox'), '#changed');
+ await user.click(screen.getByTestId('save-channel-button'));
+
+ await waitFor(() => expect(onDone).toHaveBeenCalled(), FIND);
+
+ expect(body).toStrictEqual({
+ config: {
+ kind: 'slack',
+ spec: expect.objectContaining({ channel: '#changed' }),
+ },
+ });
+ expect(body).not.toHaveProperty('displayName');
+ },
+ TEST_TIMEOUT,
+ );
+
+ it(
+ 'explains a channel the v2 API cannot model instead of showing a blank form',
+ async () => {
+ server.use(
+ rest.get(
+ 'http://localhost/api/v2/notification_channels/:id',
+ (_, res, ctx) =>
+ res(
+ ctx.status(400),
+ ctx.json({
+ status: 'error',
+ error: {
+ message: 'channel carries 2 notifier configurations',
+ },
+ }),
+ ),
+ ),
+ );
+
+ render(<ChannelForm channelId="3" onDone={jest.fn()} />);
+
+ await expect(
+ screen.findByTestId('channel-load-error', {}, FIND),
+ ).resolves.toBeInTheDocument();
+ expect(screen.queryByTestId('channel-name-textbox')).not.toBeInTheDocument();
+ },
+ TEST_TIMEOUT,
+ );
+});
diff --git a/frontend/src/pages/AlertList/NotificationChannels/components/ChannelForm/ChannelForm.module.scss b/frontend/src/pages/AlertList/NotificationChannels/components/ChannelForm/ChannelForm.module.scss
new file mode 100644
index 0000000000..7ff445cf0f
--- /dev/null
+++ b/frontend/src/pages/AlertList/NotificationChannels/components/ChannelForm/ChannelForm.module.scss
@@ -0,0 +1,3 @@
+.loadError {
+ margin: var(--spacing-5) 0;
+}
diff --git a/frontend/src/pages/AlertList/NotificationChannels/components/ChannelForm/ChannelForm.tsx b/frontend/src/pages/AlertList/NotificationChannels/components/ChannelForm/ChannelForm.tsx
new file mode 100644
index 0000000000..7a448d7933
--- /dev/null
+++ b/frontend/src/pages/AlertList/NotificationChannels/components/ChannelForm/ChannelForm.tsx
@@ -0,0 +1,45 @@
+import { useTranslation } from 'react-i18next';
+import { Callout } from '@signozhq/ui/callout';
+import Spinner from 'components/Spinner';
+
+import ChannelFormBody from './ChannelFormBody';
+import styles from './ChannelForm.module.scss';
+import { useChannelDraft } from './useChannelDraft';
+
+interface ChannelFormProps {
+ channelId?: string;
+ onDone: () => void;
+}
+
+function ChannelForm({ channelId, onDone }: ChannelFormProps): JSX.Element {
+ const { t } = useTranslation('channels');
+ const { draft, isLoading, loadError } = useChannelDraft(channelId);
+
+ if (loadError) {
+ return (
+ <Callout
+ type="error"
+ showIcon
+ title={t('channel_load_failed')}
+ className={styles.loadError}
+ testId="channel-load-error"
+ >
+ {loadError}
+ </Callout>
+ );
+ }
+
+ if (isLoading || !draft) {
+ return <Spinner tip={t('loading_channels_message')} />;
+ }
+
+ return (
+ <ChannelFormBody
+ draft={draft}
+ target={channelId ? { mode: 'edit', channelId } : { mode: 'create' }}
+ onDone={onDone}
+ />
+ );
+}
+
+export default ChannelForm;
diff --git a/frontend/src/pages/AlertList/NotificationChannels/components/ChannelForm/ChannelFormBody.tsx b/frontend/src/pages/AlertList/NotificationChannels/components/ChannelForm/ChannelFormBody.tsx
new file mode 100644
index 0000000000..1a250f8559
--- /dev/null
+++ b/frontend/src/pages/AlertList/NotificationChannels/components/ChannelForm/ChannelFormBody.tsx
@@ -0,0 +1,34 @@
+import FormAlertChannels from 'container/FormAlertChannels';
+import { ChannelFormState } from 'container/CreateAlertChannels/channelFormValues';
+
+import { ChannelFormTarget, useChannelFormState } from './useChannelFormState';
+
+interface ChannelFormBodyProps {
+ draft: ChannelFormState;
+ target: ChannelFormTarget;
+ onDone: () => void;
+}
+
+function ChannelFormBody({
+ draft,
+ target,
+ onDone,
+}: ChannelFormBodyProps): JSX.Element {
+ const { form, type, onTypeChange, onSave, onTest, isSaving, isTesting } =
+ useChannelFormState({ draft, target, onDone });
+
+ return (
+ <FormAlertChannels
+ form={form}
+ type={type}
+ onTypeChangeHandler={onTypeChange}
+ onTestHandler={onTest}
+ onSaveHandler={onSave}
+ savingState={isSaving}
+ testingState={isTesting}
+ editing={target.mode === 'edit'}
+ />
+ );
+}
+
+export default ChannelFormBody;
diff --git a/frontend/src/pages/AlertList/NotificationChannels/components/ChannelForm/useChannelDraft.ts b/frontend/src/pages/AlertList/NotificationChannels/components/ChannelForm/useChannelDraft.ts
new file mode 100644
index 0000000000..f64044b185
--- /dev/null
+++ b/frontend/src/pages/AlertList/NotificationChannels/components/ChannelForm/useChannelDraft.ts
@@ -0,0 +1,70 @@
+import { useEffect, useState } from 'react';
+import { useGetNotificationChannel } from 'api/generated/services/channels';
+import { RenderErrorResponseDTO } from 'api/generated/services/sigNoz.schemas';
+import { ErrorType } from 'api/generatedAPIInstance';
+import {
+ ChannelFormState,
+ toChannelFormState,
+} from 'container/CreateAlertChannels/channelFormValues';
+import {
+ ChannelInitialConfig,
+ DEFAULT_CHANNEL_KIND,
+} from 'container/CreateAlertChannels/defaults';
+import { toAPIError } from 'utils/errorUtils';
+
+export interface ChannelDraftResult {
+ draft: ChannelFormState | null;
+ isLoading: boolean;
+ loadError: string | null;
+}
+
+/**
+ * Kept apart from the form so the form is built once its values are known,
+ * rather than mounted empty and reset.
+ */
+export function useChannelDraft(channelId?: string): ChannelDraftResult {
+ const isEditing = !!channelId;
+
+ const { data, error: loadFailure } = useGetNotificationChannel(
+ { id: channelId ?? '' },
+ { query: { enabled: isEditing } },
+ );
+
+ const [draft, setDraft] = useState<ChannelFormState | null>(() =>
+ channelId
+ ? null
+ : {
+ kind: DEFAULT_CHANNEL_KIND,
+ values: {
+ sendResolved: true,
+ ...ChannelInitialConfig[DEFAULT_CHANNEL_KIND],
+ },
+ },
+ );
+ const [unsupportedKind, setUnsupportedKind] = useState<string | null>(null);
+
+ useEffect(() => {
+ if (!data?.data) {
+ return;
+ }
+
+ try {
+ const next = toChannelFormState(data.data);
+ setDraft((current) => current ?? next);
+ } catch (conversionError) {
+ setUnsupportedKind((conversionError as Error).message);
+ }
+ }, [data]);
+
+ return {
+ draft,
+ isLoading: isEditing && !draft && !loadFailure && !unsupportedKind,
+ loadError:
+ unsupportedKind ??
+ (loadFailure
+ ? toAPIError(
+ loadFailure as ErrorType<RenderErrorResponseDTO>,
+ ).getErrorMessage()
+ : null),
+ };
+}
diff --git a/frontend/src/pages/AlertList/NotificationChannels/components/ChannelForm/useChannelFormState.ts b/frontend/src/pages/AlertList/NotificationChannels/components/ChannelForm/useChannelFormState.ts
new file mode 100644
index 0000000000..0ad094346d
--- /dev/null
+++ b/frontend/src/pages/AlertList/NotificationChannels/components/ChannelForm/useChannelFormState.ts
@@ -0,0 +1,186 @@
+import { useCallback, useState } from 'react';
+import { useTranslation } from 'react-i18next';
+import { useQueryClient } from 'react-query';
+import { useForm, UseFormReturn } from 'react-hook-form';
+import logEvent from 'api/common/logEvent';
+import {
+ invalidateGetNotificationChannel,
+ invalidateListNotificationChannels,
+ useCreateNotificationChannel,
+ useTestNotificationChannel,
+ useUpdateNotificationChannel,
+} from 'api/generated/services/channels';
+import { RenderErrorResponseDTO } from 'api/generated/services/sigNoz.schemas';
+import { ErrorType } from 'api/generatedAPIInstance';
+import {
+ toPostableChannel,
+ toTestableChannel,
+ toUpdatableChannel,
+} from 'container/CreateAlertChannels/channelConfig';
+import { ChannelFormState } from 'container/CreateAlertChannels/channelFormValues';
+import {
+ ChannelFormValues,
+ ChannelKind,
+} from 'container/CreateAlertChannels/types';
+import { ChannelInitialConfig } from 'container/CreateAlertChannels/defaults';
+import { channelResolver } from 'container/CreateAlertChannels/channelResolver';
+import { useNotifications } from 'hooks/useNotifications';
+import { useErrorModal } from 'providers/ErrorModalProvider';
+import { toAPIError } from 'utils/errorUtils';
+
+export interface ChannelFormStateResult {
+ form: UseFormReturn<ChannelFormValues>;
+ type: ChannelKind;
+ onTypeChange: (value: string) => void;
+ onSave: () => void;
+ onTest: () => void;
+ isSaving: boolean;
+ isTesting: boolean;
+}
+
+/** Creating has no channel to address; editing always has one. */
+export type ChannelFormTarget =
+ | { mode: 'create' }
+ | { mode: 'edit'; channelId: string };
+
+interface UseChannelFormStateArgs {
+ draft: ChannelFormState;
+ target: ChannelFormTarget;
+ onDone: () => void;
+}
+
+export function useChannelFormState({
+ draft,
+ target,
+ onDone,
+}: UseChannelFormStateArgs): ChannelFormStateResult {
+ const { t } = useTranslation('channels');
+ const { notifications } = useNotifications();
+ const { showErrorModal } = useErrorModal();
+ const queryClient = useQueryClient();
+
+ const isEditing = target.mode === 'edit';
+
+ const [type, setTypeState] = useState<ChannelKind>(draft.kind);
+
+ const form = useForm<ChannelFormValues>({
+ defaultValues: draft.values,
+ resolver: channelResolver(type, t),
+ });
+
+ const { mutateAsync: createChannel, isLoading: isCreating } =
+ useCreateNotificationChannel();
+ const { mutateAsync: updateChannel, isLoading: isUpdating } =
+ useUpdateNotificationChannel();
+ const { mutateAsync: testChannel, isLoading: isTesting } =
+ useTestNotificationChannel();
+
+ const onTypeChange = useCallback(
+ (value: string) => {
+ const nextType = value as ChannelKind;
+ if (nextType === type) {
+ return;
+ }
+
+ setTypeState(nextType);
+
+ Object.entries(ChannelInitialConfig[nextType]).forEach(([field, value]) => {
+ form.setValue(
+ field as keyof ChannelFormValues,
+ value as ChannelFormValues[keyof ChannelFormValues],
+ );
+ });
+ },
+ [type, form],
+ );
+
+ const submitSave = useCallback(
+ async (values: ChannelFormValues): Promise<void> => {
+ try {
+ if (target.mode === 'edit') {
+ await updateChannel({
+ pathParams: { id: target.channelId },
+ data: toUpdatableChannel(type, values),
+ });
+ await invalidateGetNotificationChannel(queryClient, {
+ id: target.channelId,
+ });
+ } else {
+ await createChannel({ data: toPostableChannel(type, values) });
+ }
+
+ await invalidateListNotificationChannels(queryClient);
+ notifications.success({
+ message: 'Success',
+ description: isEditing
+ ? t('channel_edit_done')
+ : t('channel_creation_done'),
+ });
+ void logEvent('Alert Channel: Save channel', {
+ type: type,
+ sendResolvedAlert: values.sendResolved,
+ name: values.name,
+ new: isEditing ? 'false' : 'true',
+ status: 'success',
+ });
+ onDone();
+ } catch (error) {
+ showErrorModal(toAPIError(error as ErrorType<RenderErrorResponseDTO>));
+ void logEvent('Alert Channel: Save channel', {
+ type: type,
+ sendResolvedAlert: values.sendResolved,
+ name: values.name,
+ new: isEditing ? 'false' : 'true',
+ status: 'failed',
+ });
+ }
+ },
+ [
+ type,
+ t,
+ notifications,
+ isEditing,
+ target,
+ updateChannel,
+ queryClient,
+ createChannel,
+ onDone,
+ showErrorModal,
+ ],
+ );
+
+ const submitTest = useCallback(
+ async (values: ChannelFormValues): Promise<void> => {
+ try {
+ await testChannel({ data: toTestableChannel(type, values) });
+ notifications.success({
+ message: 'Success',
+ description: t('channel_test_done'),
+ });
+ void logEvent('Alert Channel: Test notification', {
+ type: type,
+ name: values.name,
+ status: 'Test success',
+ });
+ } catch (error) {
+ showErrorModal(toAPIError(error as ErrorType<RenderErrorResponseDTO>));
+ void logEvent('Alert Channel: Test notification', {
+ type: type,
+ name: values.name,
+ status: 'Test failed',
+ });
+ }
+ },
+ [type, t, notifications, testChannel, showErrorModal],
+ );
+
+ return {
+ form,
+ type,
+ onTypeChange,
+ onSave: form.handleSubmit(submitSave),
+ onTest: form.handleSubmit(submitTest),
+ isSaving: isCreating || isUpdating,
+ isTesting,
+ };
+}
diff --git a/frontend/src/pages/AlertList/NotificationChannels/utils/channelJson.ts b/frontend/src/pages/AlertList/NotificationChannels/utils/channelJson.ts
index a0f4fe6d6d..91d3b02b67 100644
--- a/frontend/src/pages/AlertList/NotificationChannels/utils/channelJson.ts
+++ b/frontend/src/pages/AlertList/NotificationChannels/utils/channelJson.ts
@@ -16,6 +16,7 @@ const SECRET_FIELDS_BY_KIND: Record<string, readonly string[]> = {
jira: ['apiToken'],
jsmops: ['apiKey'],
incidentio: ['token'],
+ telegram: ['botToken'],
};
export function channelToJson(
diff --git a/frontend/src/pages/ChannelsEdit/ChannelsEdit.module.scss b/frontend/src/pages/ChannelsEdit/ChannelsEdit.module.scss
new file mode 100644
index 0000000000..78ac1ffaef
--- /dev/null
+++ b/frontend/src/pages/ChannelsEdit/ChannelsEdit.module.scss
@@ -0,0 +1,9 @@
+.content {
+ padding: 0 var(--spacing-6) var(--spacing-6);
+}
+
+.crumbName {
+ display: inline-flex;
+ align-items: center;
+ gap: var(--spacing-1);
+}
diff --git a/frontend/src/pages/ChannelsEdit/ChannelsEdit.styles.scss b/frontend/src/pages/ChannelsEdit/ChannelsEdit.styles.scss
deleted file mode 100644
index 90ea6adb02..0000000000
--- a/frontend/src/pages/ChannelsEdit/ChannelsEdit.styles.scss
+++ /dev/null
@@ -1,14 +0,0 @@
-.edit-alert-channels-container {
- margin: 12px;
-
- border: 1px solid var(--l1-border);
- background: var(--l2-background);
- border-radius: 3px;
-
- padding: 16px;
-
- .form-alert-channels-title {
- margin-top: 0px;
- margin-bottom: 16px;
- }
-}
diff --git a/frontend/src/pages/ChannelsEdit/ChannelsEditPage.tsx b/frontend/src/pages/ChannelsEdit/ChannelsEditPage.tsx
new file mode 100644
index 0000000000..c218d1bdcd
--- /dev/null
+++ b/frontend/src/pages/ChannelsEdit/ChannelsEditPage.tsx
@@ -0,0 +1,55 @@
+import { toast } from '@signozhq/ui/sonner';
+import { useGetNotificationChannel } from 'api/generated/services/channels';
+import AlertBreadcrumb from 'components/AlertBreadcrumb';
+import ROUTES from 'constants/routes';
+import history from 'lib/history';
+import ChannelForm from 'pages/AlertList/NotificationChannels/components/ChannelForm/ChannelForm';
+import CopyButton from 'periscope/components/CopyButton/CopyButton';
+
+import styles from './ChannelsEdit.module.scss';
+
+interface ChannelsEditPageProps {
+ channelId: string;
+}
+
+function ChannelsEditPage({ channelId }: ChannelsEditPageProps): JSX.Element {
+ const { data } = useGetNotificationChannel({ id: channelId });
+
+ return (
+ <>
+ <AlertBreadcrumb
+ items={[
+ { title: 'Channels', route: ROUTES.ALL_CHANNELS },
+ {
+ title: (
+ <span className={styles.crumbName}>
+ <span className="translate-safe">
+ {data?.data?.displayName || 'Edit Channel'}
+ </span>
+ <CopyButton
+ value={channelId}
+ ariaLabel="Copy channel ID"
+ testId="copy-channel-id"
+ onCopy={(): void => {
+ toast.success('Channel ID copied to clipboard');
+ }}
+ />
+ </span>
+ ),
+ isLast: true,
+ },
+ ]}
+ />
+ <div className={styles.content}>
+ <ChannelForm
+ channelId={channelId}
+ onDone={(): void => {
+ history.replace(ROUTES.ALL_CHANNELS);
+ }}
+ />
+ </div>
+ </>
+ );
+}
+
+export default ChannelsEditPage;
diff --git a/frontend/src/pages/ChannelsEdit/index.tsx b/frontend/src/pages/ChannelsEdit/index.tsx
index 4e415610b0..e165dae64b 100644
--- a/frontend/src/pages/ChannelsEdit/index.tsx
+++ b/frontend/src/pages/ChannelsEdit/index.tsx
@@ -1,235 +1,19 @@
-/* eslint-disable sonarjs/cognitive-complexity */
-
-import { useTranslation } from 'react-i18next';
-import { useQuery } from 'react-query';
-import { matchPath, useLocation } from 'react-router-dom';
-import { Typography } from '@signozhq/ui/typography';
-import get from 'api/channels/get';
-import AlertBreadcrumb from 'components/AlertBreadcrumb';
-import Spinner from 'components/Spinner';
+import { matchPath, Redirect, useLocation } from 'react-router-dom';
import ROUTES from 'constants/routes';
-import {
- ChannelType,
- GoogleChatChannel,
- IncidentIOChannel,
- JiraChannel,
- JsmOpsChannel,
- MsTeamsChannel,
- PagerChannel,
- SlackChannel,
- WebhookChannel,
-} from 'container/CreateAlertChannels/config';
-import EditAlertChannels from 'container/EditAlertChannels';
-import { SuccessResponseV2 } from 'types/api';
-import { Channels } from 'types/api/channels/getAll';
-import APIError from 'types/api/error';
-import './ChannelsEdit.styles.scss';
+import ChannelsEditPage from './ChannelsEditPage';
function ChannelsEdit(): JSX.Element {
- const { t } = useTranslation();
-
const { pathname } = useLocation();
const channelId = matchPath<{ channelId: string }>(pathname, {
path: ROUTES.CHANNELS_EDIT,
})?.params?.channelId;
- const { isFetching, isError, data, error } = useQuery<
- SuccessResponseV2<Channels>,
- APIError
- >(['getChannel', channelId], {
- queryFn: () =>
- get({
- id: channelId || '',
- }),
- enabled: !!channelId,
- });
-
- if (isError) {
- return (
- <Typography>
- {error?.getErrorMessage() || t('something_went_wrong')}
- </Typography>
- );
- }
-
- if (isFetching || !data?.data) {
- return <Spinner tip="Loading Channels..." />;
+ if (!channelId) {
+ return <Redirect to={ROUTES.ALL_CHANNELS} />;
}
- const { data: ChannelData } = data.data;
-
- const value = JSON.parse(ChannelData);
-
- const prepChannelConfig = (): {
- type: string;
- channel: Partial<
- SlackChannel &
- WebhookChannel &
- PagerChannel &
- MsTeamsChannel &
- GoogleChatChannel &
- JiraChannel &
- JsmOpsChannel &
- IncidentIOChannel
- >;
- } => {
- let channel: Partial<
- SlackChannel &
- WebhookChannel &
- PagerChannel &
- MsTeamsChannel &
- GoogleChatChannel &
- JiraChannel &
- JsmOpsChannel &
- IncidentIOChannel
- > = {
- name: '',
- };
-
- if (value && 'slack_configs' in value) {
- const slackConfig = value.slack_configs[0];
- channel = slackConfig;
- return {
- type: ChannelType.Slack,
- channel,
- };
- }
-
- if (value && 'msteamsv2_configs' in value) {
- const msteamsConfig = value.msteamsv2_configs[0];
- channel = msteamsConfig;
- return {
- type: ChannelType.MsTeams,
- channel,
- };
- }
-
- if (value && 'googlechat_configs' in value) {
- const [googleChatConfig] = value.googlechat_configs;
- channel = googleChatConfig;
- return {
- type: ChannelType.GoogleChat,
- channel,
- };
- }
-
- if (value && 'jira_configs' in value) {
- const [jiraConfig] = value.jira_configs;
- channel = jiraConfig;
- if (jiraConfig.http_config?.basic_auth) {
- channel.username = jiraConfig.http_config.basic_auth.username;
- channel.password = jiraConfig.http_config.basic_auth.password;
- }
- return {
- type: ChannelType.Jira,
- channel,
- };
- }
-
- if (value && 'pagerduty_configs' in value) {
- const pagerConfig = value.pagerduty_configs[0];
- channel = pagerConfig;
- channel.details = JSON.stringify(pagerConfig.details);
- channel.detailsArray = { ...pagerConfig.details };
- return {
- type: ChannelType.Pagerduty,
- channel,
- };
- }
-
- if (value && 'incidentio_configs' in value) {
- const [incidentIOConfig] = value.incidentio_configs;
- channel = incidentIOConfig;
- return {
- type: ChannelType.IncidentIO,
- channel,
- };
- }
-
- if (value && 'jsmops_configs' in value) {
- const [jsmopsConfig] = value.jsmops_configs;
- channel = jsmopsConfig;
- // backend stores tags as a comma-separated string; the form uses chips
- channel.tags = jsmopsConfig.tags
- ? String(jsmopsConfig.tags)
- .split(',')
- .map((tag: string) => tag.trim())
- .filter(Boolean)
- : [];
- return {
- type: ChannelType.JsmOps,
- channel,
- };
- }
-
- if (value && 'opsgenie_configs' in value) {
- const opsgenieConfig = value.opsgenie_configs[0];
- channel = opsgenieConfig;
- return {
- type: ChannelType.Opsgenie,
- channel,
- };
- }
-
- if (value && 'email_configs' in value) {
- const emailConfig = value.email_configs[0];
- channel = emailConfig;
- return {
- type: ChannelType.Email,
- channel,
- };
- }
-
- if (value && 'webhook_configs' in value) {
- const webhookConfig = value.webhook_configs[0];
- channel = webhookConfig;
- channel.api_url = webhookConfig.url;
-
- if ('http_config' in webhookConfig) {
- const httpConfig = webhookConfig.http_config;
- if ('basic_auth' in httpConfig) {
- channel.username = webhookConfig.http_config?.basic_auth?.username;
- channel.password = webhookConfig.http_config?.basic_auth?.password;
- } else if ('authorization' in httpConfig) {
- channel.password = webhookConfig.http_config?.authorization?.credentials;
- }
- }
- return {
- type: ChannelType.Webhook,
- channel,
- };
- }
- return {
- type: ChannelType.Slack,
- channel,
- };
- };
-
- const target = prepChannelConfig();
-
- return (
- <>
- <AlertBreadcrumb
- items={[
- { title: 'Channels', route: ROUTES.ALL_CHANNELS },
- { title: value.name || 'Edit Channel', isLast: true },
- ]}
- />
- <div className="edit-alert-channels-container">
- <EditAlertChannels
- {...{
- channelId: channelId || '',
- initialValue: {
- ...target.channel,
- type: target.type,
- name: value.name,
- },
- }}
- />
- </div>
- </>
- );
+ return <ChannelsEditPage channelId={channelId} />;
}
export default ChannelsEdit;
diff --git a/frontend/src/pages/ChannelsNew/index.tsx b/frontend/src/pages/ChannelsNew/index.tsx
index 1470f6eabb..c4984543b1 100644
--- a/frontend/src/pages/ChannelsNew/index.tsx
+++ b/frontend/src/pages/ChannelsNew/index.tsx
@@ -1,7 +1,8 @@
import AlertBreadcrumb from 'components/AlertBreadcrumb';
import ROUTES from 'constants/routes';
-import CreateAlertChannels from 'container/CreateAlertChannels';
-import { ChannelType } from 'container/CreateAlertChannels/config';
+import history from 'lib/history';
+import ChannelForm from 'pages/AlertList/NotificationChannels/components/ChannelForm/ChannelForm';
+
import styles from './styles.module.scss';
function ChannelsNew(): JSX.Element {
@@ -10,11 +11,15 @@ function ChannelsNew(): JSX.Element {
<AlertBreadcrumb
items={[
{ title: 'Channels', route: ROUTES.ALL_CHANNELS },
- { title: 'New Channel', isLast: true },
+ { title: 'New channel', isLast: true },
]}
/>
<div className={styles.content}>
- <CreateAlertChannels preType={ChannelType.Slack} />
+ <ChannelForm
+ onDone={(): void => {
+ history.replace(ROUTES.ALL_CHANNELS);
+ }}
+ />
</div>
</>
);
diff --git a/frontend/src/pages/ChannelsNew/styles.module.scss b/frontend/src/pages/ChannelsNew/styles.module.scss
index e423c91424..473750049f 100644
--- a/frontend/src/pages/ChannelsNew/styles.module.scss
+++ b/frontend/src/pages/ChannelsNew/styles.module.scss
@@ -1,4 +1,3 @@
.content {
- padding: var(--spacing-8);
- padding-top: 0px;
+ padding: 0 var(--spacing-6) var(--spacing-6);
}
diff --git a/frontend/src/utils/__tests__/omitBlank.test.ts b/frontend/src/utils/__tests__/omitBlank.test.ts
new file mode 100644
index 0000000000..143e09c304
--- /dev/null
+++ b/frontend/src/utils/__tests__/omitBlank.test.ts
@@ -0,0 +1,24 @@
+import { omitBlank } from '../omitBlank';
+
+describe('omitBlank', () => {
+ it.each([
+ ['an empty string', ''],
+ ['null', null],
+ ['undefined', undefined],
+ ['an empty array', []],
+ ['an empty object', {}],
+ ])('drops %s', (_label, blank) => {
+ expect(omitBlank({ kept: 'value', dropped: blank })).toStrictEqual({
+ kept: 'value',
+ });
+ });
+
+ it.each([
+ ['false', false],
+ ['zero', 0],
+ ['an array with an entry', [1]],
+ ['an object with a key', { a: 1 }],
+ ])('keeps %s', (_label, value) => {
+ expect(omitBlank({ value })).toStrictEqual({ value });
+ });
+});
diff --git a/frontend/src/utils/omitBlank.ts b/frontend/src/utils/omitBlank.ts
new file mode 100644
index 0000000000..97f652925b
--- /dev/null
+++ b/frontend/src/utils/omitBlank.ts
@@ -0,0 +1,17 @@
+import { isEmpty, isNil, omitBy } from 'lodash-es';
+
+/**
+ * Drops the keys a user never filled in. `false` and `0` are kept: they are
+ * choices, not blanks.
+ */
+export function omitBlank<T extends Record<string, unknown>>(
+ source: T,
+): Partial<T> {
+ return omitBy(
+ source,
+ (value) =>
+ isNil(value) ||
+ value === '' ||
+ ((Array.isArray(value) || typeof value === 'object') && isEmpty(value)),
+ ) as Partial<T>;
+}
diff --git a/tests/e2e/tests/alerts/channels/edit.spec.ts b/tests/e2e/tests/alerts/channels/edit.spec.ts
index bb4c39adf9..bec11a3d1f 100644
--- a/tests/e2e/tests/alerts/channels/edit.spec.ts
+++ b/tests/e2e/tests/alerts/channels/edit.spec.ts
@@ -10,6 +10,9 @@ test.describe('Notification channels — edit', () => {
// channel id out of the old pathname, so every save PUT went to an empty id
// and no edit ever persisted. Nothing in the suite navigated into the edit
// page, so the whole class of "edits silently do nothing" was invisible.
+ //
+ // The screen now reads and writes through /api/v2/notification_channels; the
+ // seed helper still posts the v1 shape, which the same store backs.
test('TC-01 an edited recipient persists after reload', async ({
authedPage: page,
}) => {
@@ -29,7 +32,8 @@ test.describe('Notification channels — edit', () => {
await Promise.all([
page.waitForResponse(
(r) =>
- r.url().includes('/api/v1/channels') && r.request().method() === 'PUT',
+ r.url().includes('/api/v2/notification_channels') &&
+ r.request().method() === 'PUT',
),
page.getByTestId('save-channel-button').click(),
]);