issueAlertNotificationOptions.tsx 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262
  1. import {Fragment, useCallback, useEffect, useMemo, useState} from 'react';
  2. import styled from '@emotion/styled';
  3. import MultipleCheckbox from 'sentry/components/forms/controls/multipleCheckbox';
  4. import {t, tct} from 'sentry/locale';
  5. import {space} from 'sentry/styles/space';
  6. import {type IntegrationAction, IssueAlertActionType} from 'sentry/types/alerts';
  7. import type {OrganizationIntegration} from 'sentry/types/integrations';
  8. import {useApiQuery} from 'sentry/utils/queryClient';
  9. import useRouteAnalyticsParams from 'sentry/utils/routeAnalytics/useRouteAnalyticsParams';
  10. import useApi from 'sentry/utils/useApi';
  11. import useOrganization from 'sentry/utils/useOrganization';
  12. import SetupMessagingIntegrationButton, {
  13. MessagingIntegrationAnalyticsView,
  14. } from 'sentry/views/alerts/rules/issue/setupMessagingIntegrationButton';
  15. import MessagingIntegrationAlertRule from 'sentry/views/projectInstall/messagingIntegrationAlertRule';
  16. export const providerDetails = {
  17. slack: {
  18. name: t('Slack'),
  19. action: IssueAlertActionType.SLACK,
  20. placeholder: t('channel, e.g. #critical'),
  21. makeSentence: ({providerName, integrationName, target}) =>
  22. tct(
  23. 'Send [providerName] notification to the [integrationName] workspace to [target]',
  24. {
  25. providerName,
  26. integrationName,
  27. target,
  28. }
  29. ),
  30. },
  31. discord: {
  32. name: t('Discord'),
  33. action: IssueAlertActionType.DISCORD,
  34. placeholder: t('channel ID or URL'),
  35. makeSentence: ({providerName, integrationName, target}) =>
  36. tct(
  37. 'Send [providerName] notification to the [integrationName] server in the channel [target]',
  38. {
  39. providerName,
  40. integrationName,
  41. target,
  42. }
  43. ),
  44. },
  45. msteams: {
  46. name: t('MS Teams'),
  47. action: IssueAlertActionType.MS_TEAMS,
  48. placeholder: t('channel ID'),
  49. makeSentence: ({providerName, integrationName, target}) =>
  50. tct('Send [providerName] notification to the [integrationName] team to [target]', {
  51. providerName,
  52. integrationName,
  53. target,
  54. }),
  55. },
  56. };
  57. export const enum MultipleCheckboxOptions {
  58. EMAIL = 'email',
  59. INTEGRATION = 'integration',
  60. }
  61. export type IssueAlertNotificationProps = {
  62. actions: MultipleCheckboxOptions[];
  63. channel: string | undefined;
  64. integration: OrganizationIntegration | undefined;
  65. provider: string | undefined;
  66. providersToIntegrations: Record<string, OrganizationIntegration[]>;
  67. querySuccess: boolean;
  68. setActions: (action: MultipleCheckboxOptions[]) => void;
  69. setChannel: (channel: string | undefined) => void;
  70. setIntegration: (integration: OrganizationIntegration | undefined) => void;
  71. setProvider: (provider: string | undefined) => void;
  72. shouldRenderSetupButton: boolean;
  73. };
  74. export function useCreateNotificationAction() {
  75. const api = useApi();
  76. const organization = useOrganization();
  77. const messagingIntegrationsQuery = useApiQuery<OrganizationIntegration[]>(
  78. [`/organizations/${organization.slug}/integrations/?integrationType=messaging`],
  79. {staleTime: 0, refetchOnWindowFocus: true}
  80. );
  81. const providersToIntegrations = useMemo(() => {
  82. const map: Record<string, OrganizationIntegration[]> = {};
  83. if (messagingIntegrationsQuery.data) {
  84. for (const i of messagingIntegrationsQuery.data) {
  85. if (i.status === 'active') {
  86. const providerSlug = i.provider.slug;
  87. map[providerSlug] = map[providerSlug] ?? [];
  88. map[providerSlug].push(i);
  89. }
  90. }
  91. }
  92. return map;
  93. }, [messagingIntegrationsQuery.data]);
  94. const [actions, setActions] = useState<MultipleCheckboxOptions[]>([
  95. MultipleCheckboxOptions.EMAIL,
  96. ]);
  97. const [provider, setProvider] = useState<string | undefined>(undefined);
  98. const [integration, setIntegration] = useState<OrganizationIntegration | undefined>(
  99. undefined
  100. );
  101. const [channel, setChannel] = useState<string | undefined>(undefined);
  102. const [shouldRenderSetupButton, setShouldRenderSetupButton] = useState<boolean>(false);
  103. useEffect(() => {
  104. if (messagingIntegrationsQuery.isSuccess) {
  105. const providerKeys = Object.keys(providersToIntegrations);
  106. const firstProvider = providerKeys[0]! ?? undefined;
  107. const firstIntegration = providersToIntegrations[firstProvider]?.[0] ?? undefined;
  108. setProvider(firstProvider);
  109. setIntegration(firstIntegration);
  110. setShouldRenderSetupButton(!firstProvider);
  111. }
  112. }, [messagingIntegrationsQuery.isSuccess, providersToIntegrations]);
  113. type Props = {
  114. actionMatch: string | undefined;
  115. conditions: {id: string; interval: string; value: string}[] | undefined;
  116. frequency: number | undefined;
  117. name: string | undefined;
  118. projectSlug: string;
  119. shouldCreateRule: boolean | undefined;
  120. };
  121. const createNotificationAction = useCallback(
  122. ({
  123. shouldCreateRule,
  124. projectSlug,
  125. name,
  126. conditions,
  127. actionMatch,
  128. frequency,
  129. }: Props) => {
  130. const isCreatingIntegrationNotification = actions.find(
  131. action => action === MultipleCheckboxOptions.INTEGRATION
  132. );
  133. if (!shouldCreateRule || !isCreatingIntegrationNotification) {
  134. return undefined;
  135. }
  136. let integrationAction: IntegrationAction;
  137. switch (provider) {
  138. case 'slack':
  139. integrationAction = {
  140. id: IssueAlertActionType.SLACK,
  141. workspace: integration?.id,
  142. channel,
  143. };
  144. break;
  145. case 'discord':
  146. integrationAction = {
  147. id: IssueAlertActionType.DISCORD,
  148. server: integration?.id,
  149. channel_id: channel,
  150. };
  151. break;
  152. case 'msteams':
  153. integrationAction = {
  154. id: IssueAlertActionType.MS_TEAMS,
  155. team: integration?.id,
  156. channel,
  157. };
  158. break;
  159. default:
  160. return undefined;
  161. }
  162. return api.requestPromise(`/projects/${organization.slug}/${projectSlug}/rules/`, {
  163. method: 'POST',
  164. data: {
  165. name,
  166. conditions,
  167. actions: [integrationAction],
  168. actionMatch,
  169. frequency,
  170. },
  171. });
  172. },
  173. [actions, api, provider, integration, channel, organization.slug]
  174. );
  175. return {
  176. createNotificationAction,
  177. notificationProps: {
  178. actions,
  179. provider,
  180. integration,
  181. channel,
  182. setActions,
  183. setProvider,
  184. setIntegration,
  185. setChannel,
  186. providersToIntegrations,
  187. querySuccess: messagingIntegrationsQuery.isSuccess,
  188. shouldRenderSetupButton,
  189. },
  190. };
  191. }
  192. export default function IssueAlertNotificationOptions(
  193. notificationProps: IssueAlertNotificationProps
  194. ) {
  195. const {actions, setActions, querySuccess, shouldRenderSetupButton} = notificationProps;
  196. const shouldRenderNotificationConfigs = actions.some(
  197. v => v !== MultipleCheckboxOptions.EMAIL
  198. );
  199. useRouteAnalyticsParams({
  200. setup_message_integration_button_shown: shouldRenderSetupButton,
  201. });
  202. if (!querySuccess) {
  203. return null;
  204. }
  205. return (
  206. <Fragment>
  207. <MultipleCheckbox
  208. name="notification"
  209. value={actions}
  210. onChange={values => setActions(values)}
  211. >
  212. <Wrapper>
  213. <MultipleCheckbox.Item value={MultipleCheckboxOptions.EMAIL} disabled>
  214. {t('Notify via email')}
  215. </MultipleCheckbox.Item>
  216. {!shouldRenderSetupButton && (
  217. <div>
  218. <MultipleCheckbox.Item value={MultipleCheckboxOptions.INTEGRATION}>
  219. {t('Notify via integration (Slack, Discord, MS Teams, etc.)')}
  220. </MultipleCheckbox.Item>
  221. {shouldRenderNotificationConfigs && (
  222. <MessagingIntegrationAlertRule {...notificationProps} />
  223. )}
  224. </div>
  225. )}
  226. </Wrapper>
  227. </MultipleCheckbox>
  228. {shouldRenderSetupButton && (
  229. <SetupMessagingIntegrationButton
  230. analyticsView={MessagingIntegrationAnalyticsView.PROJECT_CREATION}
  231. />
  232. )}
  233. </Fragment>
  234. );
  235. }
  236. const Wrapper = styled('div')`
  237. display: flex;
  238. flex-direction: column;
  239. gap: ${space(1)};
  240. `;