index.tsx 57 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759
  1. import type {ChangeEvent, ReactNode} from 'react';
  2. import {Fragment} from 'react';
  3. import {components} from 'react-select';
  4. import styled from '@emotion/styled';
  5. import * as Sentry from '@sentry/react';
  6. import classNames from 'classnames';
  7. import type {Location} from 'history';
  8. import cloneDeep from 'lodash/cloneDeep';
  9. import debounce from 'lodash/debounce';
  10. import omit from 'lodash/omit';
  11. import set from 'lodash/set';
  12. import {
  13. addErrorMessage,
  14. addLoadingMessage,
  15. addSuccessMessage,
  16. } from 'sentry/actionCreators/indicator';
  17. import {updateOnboardingTask} from 'sentry/actionCreators/onboardingTasks';
  18. import {hasEveryAccess} from 'sentry/components/acl/access';
  19. import {Alert} from 'sentry/components/alert';
  20. import AlertLink from 'sentry/components/alertLink';
  21. import {Button} from 'sentry/components/button';
  22. import Checkbox from 'sentry/components/checkbox';
  23. import Confirm from 'sentry/components/confirm';
  24. import DeprecatedAsyncComponent from 'sentry/components/deprecatedAsyncComponent';
  25. import ErrorBoundary from 'sentry/components/errorBoundary';
  26. import SelectControl from 'sentry/components/forms/controls/selectControl';
  27. import FieldGroup from 'sentry/components/forms/fieldGroup';
  28. import FieldHelp from 'sentry/components/forms/fieldGroup/fieldHelp';
  29. import SelectField from 'sentry/components/forms/fields/selectField';
  30. import type {FormProps} from 'sentry/components/forms/form';
  31. import Form from 'sentry/components/forms/form';
  32. import FormField from 'sentry/components/forms/formField';
  33. import IdBadge from 'sentry/components/idBadge';
  34. import Input from 'sentry/components/input';
  35. import * as Layout from 'sentry/components/layouts/thirds';
  36. import ExternalLink from 'sentry/components/links/externalLink';
  37. import List from 'sentry/components/list';
  38. import ListItem from 'sentry/components/list/listItem';
  39. import LoadingMask from 'sentry/components/loadingMask';
  40. import Panel from 'sentry/components/panels/panel';
  41. import PanelBody from 'sentry/components/panels/panelBody';
  42. import SentryDocumentTitle from 'sentry/components/sentryDocumentTitle';
  43. import TeamSelector from 'sentry/components/teamSelector';
  44. import {ALL_ENVIRONMENTS_KEY} from 'sentry/constants';
  45. import {IconChevron, IconNot} from 'sentry/icons';
  46. import {t, tct, tn} from 'sentry/locale';
  47. import {space} from 'sentry/styles/space';
  48. import type {
  49. IssueAlertConfiguration,
  50. IssueAlertRule,
  51. IssueAlertRuleAction,
  52. IssueAlertRuleActionTemplate,
  53. UnsavedIssueAlertRule,
  54. } from 'sentry/types/alerts';
  55. import {
  56. IssueAlertActionType,
  57. IssueAlertConditionType,
  58. IssueAlertFilterType,
  59. } from 'sentry/types/alerts';
  60. import type {RouteComponentProps} from 'sentry/types/legacyReactRouter';
  61. import {OnboardingTaskKey} from 'sentry/types/onboarding';
  62. import type {Member, Organization, Team} from 'sentry/types/organization';
  63. import type {Environment, Project} from 'sentry/types/project';
  64. import {metric, trackAnalytics} from 'sentry/utils/analytics';
  65. import {browserHistory} from 'sentry/utils/browserHistory';
  66. import {getDisplayName} from 'sentry/utils/environment';
  67. import {isActiveSuperuser} from 'sentry/utils/isActiveSuperuser';
  68. import recreateRoute from 'sentry/utils/recreateRoute';
  69. import normalizeUrl from 'sentry/utils/url/normalizeUrl';
  70. import withOrganization from 'sentry/utils/withOrganization';
  71. import withProjects from 'sentry/utils/withProjects';
  72. import FeedbackAlertBanner from 'sentry/views/alerts/rules/issue/feedbackAlertBanner';
  73. import {PreviewIssues} from 'sentry/views/alerts/rules/issue/previewIssues';
  74. import SetupMessagingIntegrationButton, {
  75. MessagingIntegrationAnalyticsView,
  76. } from 'sentry/views/alerts/rules/issue/setupMessagingIntegrationButton';
  77. import {
  78. CHANGE_ALERT_CONDITION_IDS,
  79. CHANGE_ALERT_PLACEHOLDERS_LABELS,
  80. } from 'sentry/views/alerts/utils/constants';
  81. import PermissionAlert from 'sentry/views/settings/project/permissionAlert';
  82. import {getProjectOptions} from '../utils';
  83. import RuleNodeList from './ruleNodeList';
  84. const FREQUENCY_OPTIONS = [
  85. {value: '5', label: t('5 minutes')},
  86. {value: '10', label: t('10 minutes')},
  87. {value: '30', label: t('30 minutes')},
  88. {value: '60', label: t('60 minutes')},
  89. {value: '180', label: t('3 hours')},
  90. {value: '720', label: t('12 hours')},
  91. {value: '1440', label: t('24 hours')},
  92. {value: '10080', label: t('1 week')},
  93. {value: '43200', label: t('30 days')},
  94. ];
  95. const ACTION_MATCH_OPTIONS = [
  96. {value: 'all', label: t('all')},
  97. {value: 'any', label: t('any')},
  98. {value: 'none', label: t('none')},
  99. ];
  100. const ACTION_MATCH_OPTIONS_MIGRATED = [
  101. {value: 'all', label: t('all')},
  102. {value: 'any', label: t('any')},
  103. ];
  104. const defaultRule: UnsavedIssueAlertRule = {
  105. actionMatch: 'any',
  106. filterMatch: 'all',
  107. actions: [],
  108. // note we update the default conditions in onLoadAllEndpointsSuccess
  109. conditions: [],
  110. filters: [],
  111. name: '',
  112. frequency: 60 * 24,
  113. environment: ALL_ENVIRONMENTS_KEY,
  114. };
  115. const POLLING_MAX_TIME_LIMIT = 3 * 60000;
  116. type ConfigurationKey = keyof IssueAlertConfiguration;
  117. type RuleTaskResponse = {
  118. status: 'pending' | 'failed' | 'success';
  119. error?: string;
  120. rule?: IssueAlertRule;
  121. };
  122. type RouteParams = {projectId?: string; ruleId?: string};
  123. export type IncompatibleRule = {
  124. conditionIndices: number[] | null;
  125. filterIndices: number[] | null;
  126. };
  127. type Props = {
  128. location: Location;
  129. members: Member[] | undefined;
  130. organization: Organization;
  131. project: Project;
  132. projects: Project[];
  133. userTeamIds: string[];
  134. loadingProjects?: boolean;
  135. onChangeTitle?: (data: string) => void;
  136. } & RouteComponentProps<RouteParams, {}>;
  137. type State = DeprecatedAsyncComponent['state'] & {
  138. configs: IssueAlertConfiguration | null;
  139. detailedError: null | {
  140. [key: string]: string[];
  141. };
  142. environments: Environment[] | null;
  143. incompatibleConditions: number[] | null;
  144. incompatibleFilters: number[] | null;
  145. project: Project;
  146. sendingNotification: boolean;
  147. acceptedNoisyAlert?: boolean;
  148. duplicateTargetRule?: UnsavedIssueAlertRule | IssueAlertRule | null;
  149. rule?: UnsavedIssueAlertRule | IssueAlertRule | null;
  150. };
  151. function isSavedAlertRule(rule: State['rule']): rule is IssueAlertRule {
  152. return rule?.hasOwnProperty('id') ?? false;
  153. }
  154. /**
  155. * Expecting "This rule is an exact duplicate of '{duplicate_rule.label}' in this project and may not be created."
  156. */
  157. const isExactDuplicateExp = /duplicate of '(.*)'/;
  158. class IssueRuleEditor extends DeprecatedAsyncComponent<Props, State> {
  159. pollingTimeout: number | undefined = undefined;
  160. trackIncompatibleAnalytics = false;
  161. trackNoisyWarningViewed = false;
  162. isUnmounted = false;
  163. uuid: string | null = null;
  164. get isDuplicateRule(): boolean {
  165. const {location} = this.props;
  166. const createFromDuplicate = location?.query.createFromDuplicate === 'true';
  167. return createFromDuplicate && location?.query.duplicateRuleId;
  168. }
  169. componentDidMount() {
  170. super.componentDidMount();
  171. }
  172. componentWillUnmount() {
  173. super.componentWillUnmount();
  174. this.isUnmounted = true;
  175. window.clearTimeout(this.pollingTimeout);
  176. this.checkIncompatibleRuleDebounced.cancel();
  177. }
  178. componentDidUpdate(_prevProps: Props, prevState: State) {
  179. if (this.isRuleStateChange(prevState)) {
  180. this.setState({
  181. incompatibleConditions: null,
  182. incompatibleFilters: null,
  183. });
  184. this.checkIncompatibleRuleDebounced();
  185. }
  186. if (prevState.project.id === this.state.project.id) {
  187. return;
  188. }
  189. this.fetchEnvironments();
  190. this.refetchConfigs();
  191. }
  192. isRuleStateChange(prevState: State): boolean {
  193. const prevRule = prevState.rule;
  194. const curRule = this.state.rule;
  195. return (
  196. JSON.stringify(prevRule?.conditions) !== JSON.stringify(curRule?.conditions) ||
  197. JSON.stringify(prevRule?.filters) !== JSON.stringify(curRule?.filters) ||
  198. prevRule?.actionMatch !== curRule?.actionMatch ||
  199. prevRule?.filterMatch !== curRule?.filterMatch ||
  200. prevRule?.frequency !== curRule?.frequency ||
  201. JSON.stringify(prevState.project) !== JSON.stringify(this.state.project)
  202. );
  203. }
  204. getDefaultState() {
  205. const {userTeamIds, project} = this.props;
  206. const defaultState = {
  207. ...super.getDefaultState(),
  208. configs: null,
  209. detailedError: null,
  210. rule: {...defaultRule},
  211. environments: [],
  212. project,
  213. sendingNotification: false,
  214. incompatibleConditions: null,
  215. incompatibleFilters: null,
  216. };
  217. const projectTeamIds = new Set(project.teams.map(({id}) => id));
  218. const userTeamId = userTeamIds.find(id => projectTeamIds.has(id)) ?? null;
  219. defaultState.rule.owner = userTeamId && `team:${userTeamId}`;
  220. return defaultState;
  221. }
  222. getEndpoints(): ReturnType<DeprecatedAsyncComponent['getEndpoints']> {
  223. const {
  224. location: {query},
  225. params: {ruleId},
  226. } = this.props;
  227. const {organization} = this.props;
  228. // project in state isn't initialized when getEndpoints is first called
  229. const project = this.state?.project ?? this.props.project;
  230. const endpoints = [
  231. [
  232. 'environments',
  233. `/projects/${organization.slug}/${project.slug}/environments/`,
  234. {
  235. query: {
  236. visibility: 'visible',
  237. },
  238. },
  239. ],
  240. ['configs', `/projects/${organization.slug}/${project.slug}/rules/configuration/`],
  241. ];
  242. if (ruleId) {
  243. endpoints.push([
  244. 'rule',
  245. `/projects/${organization.slug}/${project.slug}/rules/${ruleId}/`,
  246. ]);
  247. }
  248. if (!ruleId && query.createFromDuplicate && query.duplicateRuleId) {
  249. endpoints.push([
  250. 'duplicateTargetRule',
  251. `/projects/${organization.slug}/${project.slug}/rules/${query.duplicateRuleId}/`,
  252. ]);
  253. }
  254. return endpoints as [string, string][];
  255. }
  256. onRequestSuccess({stateKey, data}) {
  257. if (stateKey === 'rule' && data.name) {
  258. this.props.onChangeTitle?.(data.name);
  259. }
  260. if (stateKey === 'duplicateTargetRule') {
  261. this.setState({
  262. rule: {
  263. ...omit(data, ['id']),
  264. name: data.name + ' copy',
  265. } as UnsavedIssueAlertRule,
  266. });
  267. }
  268. }
  269. onLoadAllEndpointsSuccess() {
  270. const {rule} = this.state;
  271. const {
  272. params: {ruleId},
  273. } = this.props;
  274. if (rule) {
  275. ((rule as IssueAlertRule)?.errors || []).map(({detail}) =>
  276. addErrorMessage(detail, {append: true})
  277. );
  278. }
  279. if (!ruleId && !this.isDuplicateRule) {
  280. // now that we've loaded all the possible conditions, we can populate the
  281. // value of conditions for a new alert
  282. this.handleChange('conditions', [{id: IssueAlertConditionType.FIRST_SEEN_EVENT}]);
  283. }
  284. }
  285. pollHandler = async (quitTime: number) => {
  286. if (Date.now() > quitTime) {
  287. addErrorMessage(t('Looking for that channel took too long :('));
  288. this.setState({loading: false});
  289. return;
  290. }
  291. const {organization} = this.props;
  292. const {project} = this.state;
  293. const origRule = this.state.rule;
  294. try {
  295. const response: RuleTaskResponse = await this.api.requestPromise(
  296. `/projects/${organization.slug}/${project.slug}/rule-task/${this.uuid}/`
  297. );
  298. const {status, rule, error} = response;
  299. if (status === 'pending') {
  300. window.clearTimeout(this.pollingTimeout);
  301. this.pollingTimeout = window.setTimeout(() => {
  302. this.pollHandler(quitTime);
  303. }, 1000);
  304. return;
  305. }
  306. if (status === 'failed') {
  307. this.setState({
  308. detailedError: {actions: [error ? error : t('An error occurred')]},
  309. loading: false,
  310. });
  311. this.handleRuleSaveFailure(t('An error occurred'));
  312. }
  313. if (rule) {
  314. const ruleId = isSavedAlertRule(origRule) ? `${origRule.id}/` : '';
  315. const isNew = !ruleId;
  316. this.handleRuleSuccess(isNew, rule);
  317. }
  318. } catch {
  319. this.handleRuleSaveFailure(t('An error occurred'));
  320. this.setState({loading: false});
  321. }
  322. };
  323. // As more incompatible combinations are added, we will need a more generic way to check for incompatibility.
  324. checkIncompatibleRuleDebounced = debounce(() => {
  325. const {conditionIndices, filterIndices} = findIncompatibleRules(this.state.rule);
  326. if (
  327. !this.trackIncompatibleAnalytics &&
  328. (conditionIndices !== null || filterIndices !== null)
  329. ) {
  330. this.trackIncompatibleAnalytics = true;
  331. trackAnalytics('edit_alert_rule.incompatible_rule', {
  332. organization: this.props.organization,
  333. });
  334. }
  335. this.setState({
  336. incompatibleConditions: conditionIndices,
  337. incompatibleFilters: filterIndices,
  338. });
  339. }, 500);
  340. fetchEnvironments() {
  341. const {organization} = this.props;
  342. const {project} = this.state;
  343. this.api
  344. .requestPromise(`/projects/${organization.slug}/${project.slug}/environments/`, {
  345. query: {
  346. visibility: 'visible',
  347. },
  348. })
  349. .then(response => this.setState({environments: response}))
  350. .catch(_err => addErrorMessage(t('Unable to fetch environments')));
  351. }
  352. refetchConfigs = () => {
  353. const {organization} = this.props;
  354. const {project} = this.state;
  355. this.api
  356. .requestPromise(
  357. `/projects/${organization.slug}/${project.slug}/rules/configuration/`
  358. )
  359. .then(response => this.setState({configs: response}))
  360. .catch(() => {
  361. // No need to alert user if this fails, can use existing data
  362. });
  363. };
  364. fetchStatus() {
  365. // pollHandler calls itself until it gets either a success
  366. // or failed status but we don't want to poll forever so we pass
  367. // in a hard stop time of 3 minutes before we bail.
  368. const quitTime = Date.now() + POLLING_MAX_TIME_LIMIT;
  369. window.clearTimeout(this.pollingTimeout);
  370. this.pollingTimeout = window.setTimeout(() => {
  371. this.pollHandler(quitTime);
  372. }, 1000);
  373. }
  374. testNotifications = () => {
  375. const {organization} = this.props;
  376. const {project, rule} = this.state;
  377. this.setState({detailedError: null, sendingNotification: true});
  378. const actions = rule?.actions ? rule?.actions.length : 0;
  379. addLoadingMessage(
  380. tn('Sending a test notification...', 'Sending test notifications...', actions)
  381. );
  382. this.api
  383. .requestPromise(`/projects/${organization.slug}/${project.slug}/rule-actions/`, {
  384. method: 'POST',
  385. data: {
  386. actions: rule?.actions ?? [],
  387. },
  388. })
  389. .then(() => {
  390. addSuccessMessage(tn('Notification sent!', 'Notifications sent!', actions));
  391. trackAnalytics('edit_alert_rule.notification_test', {
  392. organization,
  393. success: true,
  394. });
  395. })
  396. .catch(error => {
  397. addErrorMessage(tn('Notification failed', 'Notifications failed', actions));
  398. this.setState({detailedError: error.responseJSON || null});
  399. trackAnalytics('edit_alert_rule.notification_test', {
  400. organization,
  401. success: false,
  402. });
  403. })
  404. .finally(() => {
  405. this.setState({sendingNotification: false});
  406. });
  407. };
  408. handleRuleSuccess = (isNew: boolean, rule: IssueAlertRule) => {
  409. const {organization, router} = this.props;
  410. const {project} = this.state;
  411. // The onboarding task will be completed on the server side when the alert
  412. // is created
  413. updateOnboardingTask(null, organization, {
  414. task: OnboardingTaskKey.ALERT_RULE,
  415. status: 'complete',
  416. });
  417. metric.endSpan({name: 'saveAlertRule'});
  418. router.push(
  419. normalizeUrl({
  420. pathname: `/organizations/${organization.slug}/alerts/rules/${project.slug}/${rule.id}/details/`,
  421. })
  422. );
  423. addSuccessMessage(isNew ? t('Created alert rule') : t('Updated alert rule'));
  424. };
  425. handleRuleSaveFailure(msg: ReactNode) {
  426. addErrorMessage(msg);
  427. metric.endSpan({name: 'saveAlertRule'});
  428. }
  429. handleSubmit = async () => {
  430. const {project, rule} = this.state;
  431. const ruleId = isSavedAlertRule(rule) ? `${rule.id}/` : '';
  432. const isNew = !ruleId;
  433. const {organization} = this.props;
  434. const endpoint = `/projects/${organization.slug}/${project.slug}/rules/${ruleId}`;
  435. if (rule && rule.environment === ALL_ENVIRONMENTS_KEY) {
  436. delete rule.environment;
  437. }
  438. // Check conditions exist or they've accepted a noisy alert
  439. if (this.displayNoConditionsWarning() && !this.state.acceptedNoisyAlert) {
  440. this.setState({detailedError: {acceptedNoisyAlert: [t('Required')]}});
  441. return;
  442. }
  443. addLoadingMessage();
  444. await Sentry.withScope(async scope => {
  445. try {
  446. scope.setTag('type', 'issue');
  447. scope.setTag('operation', isNew ? 'create' : 'edit');
  448. if (rule) {
  449. for (const action of rule.actions) {
  450. if (action.id === IssueAlertActionType.SLACK) {
  451. scope?.setTag('SlackNotifyServiceAction', true);
  452. }
  453. // to avoid storing inconsistent data in the db, don't pass the name fields
  454. delete action.name;
  455. }
  456. for (const condition of rule.conditions) {
  457. // values of 0 must be manually changed to strings, otherwise they will be interpreted as missing by the serializer
  458. if ('value' in condition && condition.value === 0) {
  459. condition.value = '0';
  460. }
  461. delete condition.name;
  462. }
  463. for (const filter of rule.filters) {
  464. delete filter.name;
  465. }
  466. scope.setExtra('actions', rule.actions);
  467. // Check if rule is currently disabled or going to be disabled
  468. if ('status' in rule && (rule.status === 'disabled' || !!rule.disableDate)) {
  469. rule.optOutEdit = true;
  470. }
  471. }
  472. metric.startSpan({name: 'saveAlertRule'});
  473. const [data, , resp] = await this.api.requestPromise(endpoint, {
  474. includeAllArgs: true,
  475. method: isNew ? 'POST' : 'PUT',
  476. data: rule,
  477. query: {
  478. duplicateRule: this.isDuplicateRule ? 'true' : 'false',
  479. wizardV3: 'true',
  480. },
  481. });
  482. // if we get a 202 back it means that we have an async task
  483. // running to lookup and verify the channel id for Slack.
  484. if (resp?.status === 202) {
  485. this.uuid = data.uuid;
  486. this.setState({detailedError: null, loading: true});
  487. this.fetchStatus();
  488. addLoadingMessage(t('Looking through all your channels...'));
  489. } else {
  490. this.handleRuleSuccess(isNew, data);
  491. }
  492. } catch (err) {
  493. this.setState({
  494. detailedError: err.responseJSON || {__all__: 'Unknown error'},
  495. loading: false,
  496. });
  497. this.handleRuleSaveFailure(t('An error occurred'));
  498. }
  499. });
  500. };
  501. handleDeleteRule = async () => {
  502. const {project, rule} = this.state;
  503. const ruleId = isSavedAlertRule(rule) ? `${rule.id}/` : '';
  504. const isNew = !ruleId;
  505. const {organization} = this.props;
  506. if (isNew) {
  507. return;
  508. }
  509. const endpoint = `/projects/${organization.slug}/${project.slug}/rules/${ruleId}`;
  510. addLoadingMessage(t('Deleting...'));
  511. try {
  512. await this.api.requestPromise(endpoint, {
  513. method: 'DELETE',
  514. });
  515. addSuccessMessage(t('Deleted alert rule'));
  516. browserHistory.replace(
  517. recreateRoute('', {
  518. ...this.props,
  519. params: {...this.props.params, orgId: organization.slug},
  520. stepBack: -2,
  521. })
  522. );
  523. } catch (err) {
  524. this.setState({
  525. detailedError: err.responseJSON || {__all__: 'Unknown error'},
  526. });
  527. addErrorMessage(t('There was a problem deleting the alert'));
  528. }
  529. };
  530. handleCancel = () => {
  531. const {organization, router} = this.props;
  532. router.push(normalizeUrl(`/organizations/${organization.slug}/alerts/rules/`));
  533. };
  534. hasError = (field: string) => {
  535. const {detailedError} = this.state;
  536. if (!detailedError) {
  537. return false;
  538. }
  539. return detailedError.hasOwnProperty(field);
  540. };
  541. handleEnvironmentChange = (val: string) => {
  542. // If 'All Environments' is selected the value should be null
  543. if (val === ALL_ENVIRONMENTS_KEY) {
  544. this.handleChange('environment', null);
  545. } else {
  546. this.handleChange('environment', val);
  547. }
  548. };
  549. handleChange = <T extends keyof IssueAlertRule>(prop: T, val: IssueAlertRule[T]) => {
  550. this.setState(prevState => {
  551. const clonedState = cloneDeep(prevState);
  552. set(clonedState, `rule[${prop}]`, val);
  553. return {...clonedState, detailedError: omit(prevState.detailedError, prop)};
  554. });
  555. };
  556. handlePropertyChange = <T extends keyof IssueAlertRuleAction>(
  557. type: ConfigurationKey,
  558. idx: number,
  559. prop: T,
  560. val: IssueAlertRuleAction[T]
  561. ) => {
  562. this.setState(prevState => {
  563. const clonedState = cloneDeep(prevState);
  564. set(clonedState, `rule[${type}][${idx}][${prop}]`, val);
  565. return clonedState;
  566. });
  567. };
  568. getInitialValue = (
  569. type: ConfigurationKey,
  570. id: string
  571. ): IssueAlertConfiguration[ConfigurationKey] => {
  572. const configuration = this.state.configs?.[type]?.find(c => c.id === id);
  573. const hasChangeAlerts =
  574. configuration?.id &&
  575. this.props.organization.features.includes('change-alerts') &&
  576. CHANGE_ALERT_CONDITION_IDS.includes(configuration.id);
  577. return configuration?.formFields
  578. ? Object.fromEntries(
  579. Object.entries(configuration.formFields)
  580. // TODO(ts): Doesn't work if I cast formField as IssueAlertRuleFormField
  581. .map(([key, formField]: [string, any]) => [
  582. key,
  583. hasChangeAlerts && key === 'interval'
  584. ? '1h'
  585. : formField?.initial ?? formField?.choices?.[0]?.[0],
  586. ])
  587. .filter(([, initial]) => !!initial)
  588. )
  589. : {};
  590. };
  591. handleResetRow = <T extends keyof IssueAlertRuleAction>(
  592. type: ConfigurationKey,
  593. idx: number,
  594. prop: T,
  595. val: IssueAlertRuleAction[T]
  596. ) => {
  597. this.setState(prevState => {
  598. const clonedState = cloneDeep(prevState);
  599. // Set initial configuration, but also set
  600. const id = (clonedState.rule as IssueAlertRule)[type]![idx]!.id;
  601. const newRule = {
  602. ...this.getInitialValue(type, id),
  603. id,
  604. [prop]: val,
  605. };
  606. set(clonedState, `rule[${type}][${idx}]`, newRule);
  607. return clonedState;
  608. });
  609. };
  610. handleAddRow = (type: ConfigurationKey, item: IssueAlertRuleActionTemplate) => {
  611. this.setState(prevState => {
  612. const clonedState = cloneDeep(prevState);
  613. // Set initial configuration
  614. const newRule = {
  615. ...this.getInitialValue(type, item.id),
  616. id: item.id,
  617. sentryAppInstallationUuid: item.sentryAppInstallationUuid,
  618. };
  619. const newTypeList = prevState.rule ? prevState.rule[type] : [];
  620. set(clonedState, `rule[${type}]`, [...newTypeList, newRule]);
  621. return clonedState;
  622. });
  623. const {organization} = this.props;
  624. const {project} = this.state;
  625. trackAnalytics('edit_alert_rule.add_row', {
  626. organization,
  627. project_id: project.id,
  628. type,
  629. name: item.id,
  630. });
  631. };
  632. handleDeleteRow = (type: ConfigurationKey, idx: number) => {
  633. this.setState(prevState => {
  634. const clonedState = cloneDeep(prevState);
  635. const newTypeList = prevState.rule ? [...prevState.rule[type]] : [];
  636. newTypeList.splice(idx, 1);
  637. set(clonedState, `rule[${type}]`, newTypeList);
  638. const {organization} = this.props;
  639. const {project} = this.state;
  640. const deletedItem = prevState.rule ? prevState.rule[type][idx] : null;
  641. trackAnalytics('edit_alert_rule.delete_row', {
  642. organization,
  643. project_id: project.id,
  644. type,
  645. name: deletedItem?.id ?? '',
  646. });
  647. return clonedState;
  648. });
  649. };
  650. handleAddCondition = (template: IssueAlertRuleActionTemplate) =>
  651. this.handleAddRow('conditions', template);
  652. handleAddAction = (template: IssueAlertRuleActionTemplate) =>
  653. this.handleAddRow('actions', template);
  654. handleAddFilter = (template: IssueAlertRuleActionTemplate) =>
  655. this.handleAddRow('filters', template);
  656. handleDeleteCondition = (ruleIndex: number) =>
  657. this.handleDeleteRow('conditions', ruleIndex);
  658. handleDeleteAction = (ruleIndex: number) => this.handleDeleteRow('actions', ruleIndex);
  659. handleDeleteFilter = (ruleIndex: number) => this.handleDeleteRow('filters', ruleIndex);
  660. handleChangeConditionProperty = (ruleIndex: number, prop: string, val: string) =>
  661. this.handlePropertyChange('conditions', ruleIndex, prop, val);
  662. handleChangeActionProperty = (ruleIndex: number, prop: string, val: string) =>
  663. this.handlePropertyChange('actions', ruleIndex, prop, val);
  664. handleChangeFilterProperty = (ruleIndex: number, prop: string, val: string) =>
  665. this.handlePropertyChange('filters', ruleIndex, prop, val);
  666. handleResetCondition = (ruleIndex: number, prop: string, value: string) =>
  667. this.handleResetRow('conditions', ruleIndex, prop, value);
  668. handleResetAction = (ruleIndex: number, prop: string, value: string) =>
  669. this.handleResetRow('actions', ruleIndex, prop, value);
  670. handleResetFilter = (ruleIndex: number, prop: string, value: string) =>
  671. this.handleResetRow('filters', ruleIndex, prop, value);
  672. handleValidateRuleName = () => {
  673. const isRuleNameEmpty = !this.state.rule?.name.trim();
  674. if (!isRuleNameEmpty) {
  675. return;
  676. }
  677. this.setState(prevState => ({
  678. detailedError: {
  679. ...prevState.detailedError,
  680. name: [t('Field Required')],
  681. },
  682. }));
  683. };
  684. getConditions(): IssueAlertConfiguration['conditions'] | null {
  685. const {organization} = this.props;
  686. if (!organization.features.includes('change-alerts')) {
  687. return this.state.configs?.conditions ?? null;
  688. }
  689. let conditions = this.state.configs?.conditions ?? null;
  690. if (conditions === null) {
  691. return null;
  692. }
  693. if (
  694. !organization.features.includes(
  695. 'event-unique-user-frequency-condition-with-conditions'
  696. )
  697. ) {
  698. conditions = conditions?.filter(
  699. condition =>
  700. condition.id !==
  701. 'sentry.rules.conditions.event_frequency.EventUniqueUserFrequencyConditionWithConditions'
  702. );
  703. }
  704. conditions = conditions?.map(condition =>
  705. CHANGE_ALERT_CONDITION_IDS.includes(condition.id)
  706. ? {
  707. ...condition,
  708. label: `${CHANGE_ALERT_PLACEHOLDERS_LABELS[condition.id]}...`,
  709. }
  710. : condition
  711. );
  712. return conditions;
  713. }
  714. getTeamId = () => {
  715. const {rule} = this.state;
  716. const owner = rule?.owner;
  717. // ownership follows the format team:<id>, just grab the id
  718. return owner?.split(':')[1];
  719. };
  720. handleOwnerChange = ({value}: {value: string}) => {
  721. const ownerValue = value && `team:${value}`;
  722. this.handleChange('owner', ownerValue);
  723. };
  724. renderLoading() {
  725. return this.renderBody();
  726. }
  727. renderError() {
  728. return (
  729. <Alert type="error" showIcon>
  730. {t(
  731. 'Unable to access this alert rule -- check to make sure you have the correct permissions'
  732. )}
  733. </Alert>
  734. );
  735. }
  736. renderRuleName(disabled: boolean) {
  737. const {rule, detailedError} = this.state;
  738. const {name} = rule || {};
  739. // Duplicate errors display on the "name" field but we're showing them in a banner
  740. // Remove them from the name detailed error
  741. const filteredDetailedError =
  742. detailedError?.name?.filter(str => !isExactDuplicateExp.test(str)) ?? [];
  743. return (
  744. <StyledField
  745. label={null}
  746. help={null}
  747. error={filteredDetailedError[0]}
  748. disabled={disabled}
  749. required
  750. stacked
  751. flexibleControlStateSize
  752. >
  753. <Input
  754. type="text"
  755. name="name"
  756. value={name}
  757. data-test-id="alert-name"
  758. placeholder={t('Enter Alert Name')}
  759. onChange={(event: ChangeEvent<HTMLInputElement>) =>
  760. this.handleChange('name', event.target.value)
  761. }
  762. onBlur={this.handleValidateRuleName}
  763. disabled={disabled}
  764. />
  765. </StyledField>
  766. );
  767. }
  768. renderTeamSelect(disabled: boolean) {
  769. const {rule, project} = this.state;
  770. const ownerId = rule?.owner?.split(':')[1];
  771. return (
  772. <StyledField label={null} help={null} disabled={disabled} flexibleControlStateSize>
  773. <TeamSelector
  774. value={this.getTeamId()}
  775. project={project}
  776. onChange={this.handleOwnerChange}
  777. teamFilter={(team: Team) =>
  778. team.isMember || team.id === ownerId || team.access.includes('team:admin')
  779. }
  780. useId
  781. includeUnassigned
  782. disabled={disabled}
  783. />
  784. </StyledField>
  785. );
  786. }
  787. renderDuplicateErrorAlert() {
  788. const {organization} = this.props;
  789. const {detailedError, project} = this.state;
  790. const duplicateName = isExactDuplicateExp.exec(detailedError?.name?.[0] ?? '')?.[1];
  791. const duplicateRuleId = detailedError?.ruleId?.[0] ?? '';
  792. // We want this to open in a new tab to not lose the current state of the rule editor
  793. return (
  794. <AlertLink
  795. openInNewTab
  796. priority="error"
  797. icon={<IconNot color="red300" />}
  798. href={normalizeUrl(
  799. `/organizations/${organization.slug}/alerts/rules/${project.slug}/${duplicateRuleId}/details/`
  800. )}
  801. >
  802. {tct(
  803. 'This rule fully duplicates "[alertName]" in the project [projectName] and cannot be saved.',
  804. {
  805. alertName: duplicateName,
  806. projectName: project.name,
  807. }
  808. )}
  809. </AlertLink>
  810. );
  811. }
  812. displayNoConditionsWarning(): boolean {
  813. const {rule} = this.state;
  814. const acceptedNoisyActionIds: string[] = [
  815. // Webhooks
  816. IssueAlertActionType.NOTIFY_EVENT_SERVICE_ACTION,
  817. // Legacy integrations
  818. IssueAlertActionType.NOTIFY_EVENT_ACTION,
  819. ];
  820. return (
  821. !!rule &&
  822. !isSavedAlertRule(rule) &&
  823. rule.conditions.length === 0 &&
  824. rule.filters.length === 0 &&
  825. !rule.actions.every(action => acceptedNoisyActionIds.includes(action.id))
  826. );
  827. }
  828. renderAcknowledgeNoConditions(disabled: boolean) {
  829. const {detailedError, acceptedNoisyAlert} = this.state;
  830. // Bit goofy to do in render but should only track onceish
  831. if (!this.trackNoisyWarningViewed) {
  832. this.trackNoisyWarningViewed = true;
  833. trackAnalytics('alert_builder.noisy_warning_viewed', {
  834. organization: this.props.organization,
  835. });
  836. }
  837. return (
  838. <Alert type="warning" showIcon>
  839. <div>
  840. {t(
  841. 'Alerts without conditions can fire too frequently. Are you sure you want to save this alert rule?'
  842. )}
  843. </div>
  844. <AcknowledgeField
  845. label={null}
  846. help={null}
  847. error={detailedError?.acceptedNoisyAlert?.[0]}
  848. disabled={disabled}
  849. required
  850. stacked
  851. flexibleControlStateSize
  852. inline
  853. >
  854. <AcknowledgeLabel>
  855. <Checkbox
  856. size="sm"
  857. name="acceptedNoisyAlert"
  858. checked={acceptedNoisyAlert}
  859. onChange={() => {
  860. this.setState({acceptedNoisyAlert: !acceptedNoisyAlert});
  861. if (!acceptedNoisyAlert) {
  862. trackAnalytics('alert_builder.noisy_warning_agreed', {
  863. organization: this.props.organization,
  864. });
  865. }
  866. }}
  867. disabled={disabled}
  868. />
  869. {t('Yes, I don’t mind if this alert gets noisy')}
  870. </AcknowledgeLabel>
  871. </AcknowledgeField>
  872. </Alert>
  873. );
  874. }
  875. renderIdBadge(project: Project) {
  876. return (
  877. <IdBadge
  878. project={project}
  879. avatarProps={{consistentWidth: true}}
  880. avatarSize={18}
  881. disableLink
  882. hideName
  883. />
  884. );
  885. }
  886. renderEnvironmentSelect(disabled: boolean) {
  887. const {environments, rule} = this.state;
  888. const environmentOptions = [
  889. {
  890. value: ALL_ENVIRONMENTS_KEY,
  891. label: t('All Environments'),
  892. },
  893. ...(environments?.map(env => ({value: env.name, label: getDisplayName(env)})) ??
  894. []),
  895. ];
  896. const environment =
  897. !rule || !rule.environment ? ALL_ENVIRONMENTS_KEY : rule.environment;
  898. return (
  899. <FormField
  900. name="environment"
  901. inline={false}
  902. style={{padding: 0, border: 'none'}}
  903. flexibleControlStateSize
  904. className={this.hasError('environment') ? ' error' : ''}
  905. required
  906. disabled={disabled}
  907. >
  908. {({onChange, onBlur}) => (
  909. <SelectControl
  910. clearable={false}
  911. disabled={disabled}
  912. value={environment}
  913. options={environmentOptions}
  914. onChange={({value}) => {
  915. this.handleEnvironmentChange(value);
  916. onChange(value, {});
  917. onBlur(value, {});
  918. }}
  919. />
  920. )}
  921. </FormField>
  922. );
  923. }
  924. renderProjectSelect(disabled: boolean) {
  925. const {project: _selectedProject, projects, organization} = this.props;
  926. const {rule} = this.state;
  927. const projectOptions = getProjectOptions({
  928. organization,
  929. projects,
  930. isFormDisabled: disabled,
  931. });
  932. return (
  933. <FormField
  934. name="projectId"
  935. inline={false}
  936. style={{padding: 0}}
  937. flexibleControlStateSize
  938. >
  939. {({onChange, onBlur, model}) => {
  940. const selectedProject =
  941. projects.find(({id}) => id === model.getValue('projectId')) ||
  942. _selectedProject;
  943. return (
  944. <SelectControl
  945. disabled={disabled || isSavedAlertRule(rule)}
  946. value={selectedProject.id}
  947. styles={{
  948. container: (provided: {[x: string]: string | number | boolean}) => ({
  949. ...provided,
  950. marginBottom: `${space(1)}`,
  951. }),
  952. }}
  953. options={projectOptions}
  954. onChange={({value}: {value: Project['id']}) => {
  955. // if the current owner/team isn't part of project selected, update to the first available team
  956. const nextSelectedProject =
  957. projects.find(({id}) => id === value) ?? selectedProject;
  958. const ownerId: string | undefined = model
  959. .getValue('owner')
  960. ?.split(':')[1];
  961. if (
  962. ownerId &&
  963. nextSelectedProject.teams.find(({id}) => id === ownerId) ===
  964. undefined &&
  965. nextSelectedProject.teams.length
  966. ) {
  967. this.handleOwnerChange({value: nextSelectedProject.teams[0]!.id});
  968. }
  969. this.setState({project: nextSelectedProject});
  970. onChange(value, {});
  971. onBlur(value, {});
  972. }}
  973. components={{
  974. SingleValue: containerProps => (
  975. <components.ValueContainer {...containerProps}>
  976. <IdBadge
  977. project={selectedProject}
  978. avatarProps={{consistentWidth: true}}
  979. avatarSize={18}
  980. disableLink
  981. />
  982. </components.ValueContainer>
  983. ),
  984. }}
  985. />
  986. );
  987. }}
  988. </FormField>
  989. );
  990. }
  991. renderActionInterval(disabled: boolean) {
  992. const {rule} = this.state;
  993. const {frequency} = rule || {};
  994. return (
  995. <FormField
  996. name="frequency"
  997. inline={false}
  998. style={{padding: 0, border: 'none'}}
  999. label={null}
  1000. help={null}
  1001. className={this.hasError('frequency') ? ' error' : ''}
  1002. required
  1003. disabled={disabled}
  1004. flexibleControlStateSize
  1005. >
  1006. {({onChange, onBlur}) => (
  1007. <SelectControl
  1008. clearable={false}
  1009. disabled={disabled}
  1010. value={`${frequency}`}
  1011. options={FREQUENCY_OPTIONS}
  1012. onChange={({value}) => {
  1013. this.handleChange('frequency', value);
  1014. onChange(value, {});
  1015. onBlur(value, {});
  1016. }}
  1017. />
  1018. )}
  1019. </FormField>
  1020. );
  1021. }
  1022. renderBody() {
  1023. const {organization, members} = this.props;
  1024. const {
  1025. project,
  1026. rule,
  1027. detailedError,
  1028. loading,
  1029. sendingNotification,
  1030. incompatibleConditions,
  1031. incompatibleFilters,
  1032. } = this.state;
  1033. const {actions, filters, conditions, frequency} = rule || {};
  1034. const environment =
  1035. !rule || !rule.environment ? ALL_ENVIRONMENTS_KEY : rule.environment;
  1036. const canCreateAlert = hasEveryAccess(['alerts:write'], {organization, project});
  1037. const disabled = loading || !(canCreateAlert || isActiveSuperuser());
  1038. const displayDuplicateError =
  1039. detailedError?.name?.some(str => isExactDuplicateExp.test(str)) ?? false;
  1040. // Note `key` on `<Form>` below is so that on initial load, we show
  1041. // the form with a loading mask on top of it, but force a re-render by using
  1042. // a different key when we have fetched the rule so that form inputs are filled in
  1043. return (
  1044. <Main fullWidth>
  1045. <SentryDocumentTitle
  1046. title={rule ? t('Alert — %s', rule.name) : t('New Alert Rule')}
  1047. orgSlug={organization.slug}
  1048. projectSlug={project.slug}
  1049. />
  1050. <PermissionAlert access={['alerts:write']} project={project} />
  1051. <StyledForm
  1052. key={isSavedAlertRule(rule) ? rule.id : undefined}
  1053. onCancel={this.handleCancel}
  1054. onSubmit={this.handleSubmit}
  1055. initialData={{
  1056. ...rule,
  1057. environment,
  1058. frequency: `${frequency}`,
  1059. projectId: project.id,
  1060. }}
  1061. submitDisabled={
  1062. disabled || incompatibleConditions !== null || incompatibleFilters !== null
  1063. }
  1064. submitLabel={t('Save Rule')}
  1065. extraButton={
  1066. isSavedAlertRule(rule) ? (
  1067. <Confirm
  1068. disabled={disabled}
  1069. priority="danger"
  1070. confirmText={t('Delete Rule')}
  1071. onConfirm={this.handleDeleteRule}
  1072. header={<h5>{t('Delete Alert Rule?')}</h5>}
  1073. message={t(
  1074. 'Are you sure you want to delete "%s"? You won\'t be able to view the history of this alert once it\'s deleted.',
  1075. rule.name
  1076. )}
  1077. >
  1078. <Button priority="danger">{t('Delete Rule')}</Button>
  1079. </Confirm>
  1080. ) : null
  1081. }
  1082. >
  1083. <List symbol="colored-numeric">
  1084. {loading && <SemiTransparentLoadingMask data-test-id="loading-mask" />}
  1085. <StyledListItem>
  1086. <StepHeader>{t('Select an environment and project')}</StepHeader>
  1087. </StyledListItem>
  1088. <ContentIndent>
  1089. <SettingsContainer>
  1090. {this.renderEnvironmentSelect(disabled)}
  1091. {this.renderProjectSelect(disabled)}
  1092. </SettingsContainer>
  1093. </ContentIndent>
  1094. <SetConditionsListItem>
  1095. <StepHeader>{t('Set conditions')}</StepHeader>{' '}
  1096. <SetupMessagingIntegrationButton
  1097. projectId={project.id}
  1098. refetchConfigs={this.refetchConfigs}
  1099. analyticsView={MessagingIntegrationAnalyticsView.ALERT_RULE_CREATION}
  1100. />
  1101. </SetConditionsListItem>
  1102. <ContentIndent>
  1103. <ConditionsPanel>
  1104. <PanelBody>
  1105. <Step>
  1106. <StepConnector />
  1107. <StepContainer>
  1108. <ChevronContainer>
  1109. <IconChevron
  1110. color="gray200"
  1111. isCircled
  1112. direction="right"
  1113. size="sm"
  1114. />
  1115. </ChevronContainer>
  1116. <StepContent>
  1117. <StepLead>
  1118. {tct(
  1119. '[when:When] an event is captured by Sentry and [selector] of the following happens',
  1120. {
  1121. when: <Badge />,
  1122. selector: (
  1123. <EmbeddedWrapper>
  1124. <EmbeddedSelectField
  1125. className={classNames({
  1126. error: this.hasError('actionMatch'),
  1127. })}
  1128. styles={{
  1129. control: provided => ({
  1130. ...provided,
  1131. minHeight: '21px',
  1132. height: '21px',
  1133. }),
  1134. }}
  1135. inline={false}
  1136. isSearchable={false}
  1137. isClearable={false}
  1138. name="actionMatch"
  1139. required
  1140. flexibleControlStateSize
  1141. options={ACTION_MATCH_OPTIONS_MIGRATED}
  1142. onChange={val =>
  1143. this.handleChange('actionMatch', val)
  1144. }
  1145. size="xs"
  1146. disabled={disabled}
  1147. />
  1148. </EmbeddedWrapper>
  1149. ),
  1150. }
  1151. )}
  1152. </StepLead>
  1153. <RuleNodeList
  1154. nodes={this.getConditions()}
  1155. items={conditions ?? []}
  1156. selectType="grouped"
  1157. placeholder={t('Add optional trigger...')}
  1158. onPropertyChange={this.handleChangeConditionProperty}
  1159. onAddRow={this.handleAddCondition}
  1160. onResetRow={this.handleResetCondition}
  1161. onDeleteRow={this.handleDeleteCondition}
  1162. organization={organization}
  1163. project={project}
  1164. disabled={disabled}
  1165. error={
  1166. this.hasError('conditions') && (
  1167. <StyledAlert type="error">
  1168. {detailedError?.conditions![0]}
  1169. {(detailedError?.conditions![0] || '').startsWith(
  1170. 'You may not exceed'
  1171. ) && (
  1172. <Fragment>
  1173. {' '}
  1174. <ExternalLink href="https://docs.sentry.io/product/alerts/create-alerts/#alert-limits">
  1175. {t('View Docs')}
  1176. </ExternalLink>
  1177. </Fragment>
  1178. )}
  1179. </StyledAlert>
  1180. )
  1181. }
  1182. incompatibleRules={incompatibleConditions}
  1183. incompatibleBanner={
  1184. incompatibleFilters === null &&
  1185. incompatibleConditions !== null
  1186. ? incompatibleConditions.at(-1)
  1187. : null
  1188. }
  1189. />
  1190. </StepContent>
  1191. </StepContainer>
  1192. </Step>
  1193. <Step>
  1194. <StepConnector />
  1195. <StepContainer>
  1196. <ChevronContainer>
  1197. <IconChevron
  1198. color="gray200"
  1199. isCircled
  1200. direction="right"
  1201. size="sm"
  1202. />
  1203. </ChevronContainer>
  1204. <StepContent data-test-id="rule-filters">
  1205. <StepLead>
  1206. {tct('[if:If][selector] of these filters match', {
  1207. if: <Badge />,
  1208. selector: (
  1209. <EmbeddedWrapper>
  1210. <EmbeddedSelectField
  1211. className={classNames({
  1212. error: this.hasError('filterMatch'),
  1213. })}
  1214. styles={{
  1215. control: provided => ({
  1216. ...provided,
  1217. minHeight: '21px',
  1218. height: '21px',
  1219. }),
  1220. }}
  1221. inline={false}
  1222. isSearchable={false}
  1223. isClearable={false}
  1224. name="filterMatch"
  1225. required
  1226. flexibleControlStateSize
  1227. options={ACTION_MATCH_OPTIONS}
  1228. onChange={val => this.handleChange('filterMatch', val)}
  1229. size="xs"
  1230. disabled={disabled}
  1231. />
  1232. </EmbeddedWrapper>
  1233. ),
  1234. })}
  1235. </StepLead>
  1236. <RuleNodeList
  1237. nodes={this.state.configs?.filters ?? null}
  1238. items={filters ?? []}
  1239. placeholder={t('Add optional filter...')}
  1240. onPropertyChange={this.handleChangeFilterProperty}
  1241. onAddRow={this.handleAddFilter}
  1242. onResetRow={this.handleResetFilter}
  1243. onDeleteRow={this.handleDeleteFilter}
  1244. organization={organization}
  1245. project={project}
  1246. disabled={disabled}
  1247. error={
  1248. this.hasError('filters') && (
  1249. <StyledAlert type="error">
  1250. {detailedError?.filters![0]}
  1251. </StyledAlert>
  1252. )
  1253. }
  1254. incompatibleRules={incompatibleFilters}
  1255. incompatibleBanner={
  1256. incompatibleFilters ? incompatibleFilters.at(-1) : null
  1257. }
  1258. />
  1259. <FeedbackAlertBanner
  1260. filters={this.state.rule?.filters}
  1261. projectSlug={this.state.project.slug}
  1262. />
  1263. </StepContent>
  1264. </StepContainer>
  1265. </Step>
  1266. <Step>
  1267. <StepContainer>
  1268. <ChevronContainer>
  1269. <IconChevron
  1270. isCircled
  1271. color="gray200"
  1272. direction="right"
  1273. size="sm"
  1274. />
  1275. </ChevronContainer>
  1276. <StepContent>
  1277. <StepLead>
  1278. {tct('[then:Then] perform these actions', {
  1279. then: <Badge />,
  1280. })}
  1281. </StepLead>
  1282. <RuleNodeList
  1283. nodes={this.state.configs?.actions ?? null}
  1284. selectType="grouped"
  1285. items={actions ?? []}
  1286. placeholder={t('Add action...')}
  1287. onPropertyChange={this.handleChangeActionProperty}
  1288. onAddRow={this.handleAddAction}
  1289. onResetRow={this.handleResetAction}
  1290. onDeleteRow={this.handleDeleteAction}
  1291. organization={organization}
  1292. project={project}
  1293. disabled={disabled}
  1294. error={
  1295. this.hasError('actions') && (
  1296. <StyledAlert type="error">
  1297. {detailedError?.actions![0]}
  1298. </StyledAlert>
  1299. )
  1300. }
  1301. additionalAction={{
  1302. label: 'Notify integration\u{2026}',
  1303. option: {
  1304. label: 'Missing an integration? Click here to refresh',
  1305. value: {
  1306. enabled: true,
  1307. id: 'refresh_configs',
  1308. label: 'Refresh Integration List',
  1309. },
  1310. },
  1311. onClick: () => {
  1312. this.refetchConfigs();
  1313. },
  1314. }}
  1315. />
  1316. <TestButtonWrapper>
  1317. <Button
  1318. onClick={this.testNotifications}
  1319. disabled={sendingNotification || rule?.actions?.length === 0}
  1320. >
  1321. {t('Send Test Notification')}
  1322. </Button>
  1323. </TestButtonWrapper>
  1324. </StepContent>
  1325. </StepContainer>
  1326. </Step>
  1327. </PanelBody>
  1328. </ConditionsPanel>
  1329. </ContentIndent>
  1330. <StyledListItem>
  1331. <StepHeader>{t('Set action interval')}</StepHeader>
  1332. <StyledFieldHelp>
  1333. {t('Perform the actions above once this often for an issue')}
  1334. </StyledFieldHelp>
  1335. </StyledListItem>
  1336. <ContentIndent>{this.renderActionInterval(disabled)}</ContentIndent>
  1337. <ErrorBoundary mini>
  1338. <PreviewIssues members={members} rule={rule} project={project} />
  1339. </ErrorBoundary>
  1340. <StyledListItem>
  1341. <StepHeader>{t('Add a name and owner')}</StepHeader>
  1342. <StyledFieldHelp>
  1343. {t(
  1344. 'This name will show up in notifications and the owner will give permissions to your whole team to edit and view this alert.'
  1345. )}
  1346. </StyledFieldHelp>
  1347. </StyledListItem>
  1348. <ContentIndent>
  1349. <StyledFieldWrapper>
  1350. {this.renderRuleName(disabled)}
  1351. {this.renderTeamSelect(disabled)}
  1352. </StyledFieldWrapper>
  1353. {displayDuplicateError && this.renderDuplicateErrorAlert()}
  1354. {this.displayNoConditionsWarning() &&
  1355. this.renderAcknowledgeNoConditions(disabled)}
  1356. </ContentIndent>
  1357. </List>
  1358. </StyledForm>
  1359. </Main>
  1360. );
  1361. }
  1362. }
  1363. export default withOrganization(withProjects(IssueRuleEditor));
  1364. export const findIncompatibleRules = (
  1365. rule: IssueAlertRule | UnsavedIssueAlertRule | null | undefined
  1366. ): IncompatibleRule => {
  1367. if (!rule) {
  1368. return {conditionIndices: null, filterIndices: null};
  1369. }
  1370. const {conditions, filters} = rule;
  1371. // Check for more than one 'issue state change' condition
  1372. // or 'FirstSeenEventCondition' + 'EventFrequencyCondition'
  1373. if (rule.actionMatch === 'all') {
  1374. let firstSeen = -1;
  1375. let regression = -1;
  1376. let reappeared = -1;
  1377. let eventFrequency = -1;
  1378. let userFrequency = -1;
  1379. for (let i = 0; i < conditions.length; i++) {
  1380. const id = conditions[i]!.id;
  1381. if (id === IssueAlertConditionType.FIRST_SEEN_EVENT) {
  1382. firstSeen = i;
  1383. } else if (id === IssueAlertConditionType.REGRESSION_EVENT) {
  1384. regression = i;
  1385. } else if (id === IssueAlertConditionType.REAPPEARED_EVENT) {
  1386. reappeared = i;
  1387. } else if (
  1388. id === IssueAlertConditionType.EVENT_FREQUENCY &&
  1389. (conditions[i]!.value as number) >= 1
  1390. ) {
  1391. eventFrequency = i;
  1392. } else if (
  1393. id === IssueAlertConditionType.EVENT_UNIQUE_USER_FREQUENCY &&
  1394. (conditions[i]!.value as number) >= 1
  1395. ) {
  1396. userFrequency = i;
  1397. }
  1398. // FirstSeenEventCondition is incompatible with all the following types
  1399. const firstSeenError =
  1400. firstSeen !== -1 &&
  1401. [regression, reappeared, eventFrequency, userFrequency].some(idx => idx !== -1);
  1402. const regressionReappearedError = regression !== -1 && reappeared !== -1;
  1403. if (firstSeenError || regressionReappearedError) {
  1404. const indices = [firstSeen, regression, reappeared, eventFrequency, userFrequency]
  1405. .filter(idx => idx !== -1)
  1406. .sort((a, b) => a - b);
  1407. return {conditionIndices: indices, filterIndices: null};
  1408. }
  1409. }
  1410. }
  1411. // Check for 'FirstSeenEventCondition' and ('IssueOccurrencesFilter' or 'AgeComparisonFilter')
  1412. // Considers the case where filterMatch is 'any' and all filters are incompatible
  1413. const firstSeen = conditions.findIndex(condition =>
  1414. condition.id.endsWith('FirstSeenEventCondition')
  1415. );
  1416. if (firstSeen !== -1 && (rule.actionMatch === 'all' || conditions.length === 1)) {
  1417. let incompatibleFilters = 0;
  1418. for (let i = 0; i < filters.length; i++) {
  1419. const filter = filters[i]!;
  1420. const id = filter.id;
  1421. if (id === IssueAlertFilterType.ISSUE_OCCURRENCES && filter) {
  1422. if (
  1423. (rule.filterMatch === 'all' && (filter.value as number) > 1) ||
  1424. (rule.filterMatch === 'none' && (filter.value as number) <= 1)
  1425. ) {
  1426. return {conditionIndices: [firstSeen], filterIndices: [i]};
  1427. }
  1428. if (rule.filterMatch === 'any' && (filter.value as number) > 1) {
  1429. incompatibleFilters += 1;
  1430. }
  1431. } else if (id === IssueAlertFilterType.AGE_COMPARISON) {
  1432. if (rule.filterMatch !== 'none') {
  1433. if (filter.comparison_type === 'older') {
  1434. if (rule.filterMatch === 'all') {
  1435. return {conditionIndices: [firstSeen], filterIndices: [i]};
  1436. }
  1437. incompatibleFilters += 1;
  1438. }
  1439. } else if (filter.comparison_type === 'newer' && (filter.value as number) > 0) {
  1440. return {conditionIndices: [firstSeen], filterIndices: [i]};
  1441. }
  1442. }
  1443. }
  1444. if (incompatibleFilters === filters.length && incompatibleFilters > 0) {
  1445. return {
  1446. conditionIndices: [firstSeen],
  1447. filterIndices: [...Array(filters.length).keys()],
  1448. };
  1449. }
  1450. }
  1451. return {conditionIndices: null, filterIndices: null};
  1452. };
  1453. const Main = styled(Layout.Main)`
  1454. max-width: 1000px;
  1455. `;
  1456. // TODO(ts): Understand why styled is not correctly inheriting props here
  1457. const StyledForm = styled(Form)<FormProps>`
  1458. position: relative;
  1459. `;
  1460. const ConditionsPanel = styled(Panel)`
  1461. padding-top: ${space(0.5)};
  1462. padding-bottom: ${space(2)};
  1463. `;
  1464. const StyledAlert = styled(Alert)`
  1465. margin-bottom: 0;
  1466. `;
  1467. const StyledListItem = styled(ListItem)`
  1468. margin: ${space(2)} 0 ${space(1)} 0;
  1469. font-size: ${p => p.theme.fontSizeExtraLarge};
  1470. `;
  1471. const StyledFieldHelp = styled(FieldHelp)`
  1472. margin-top: 0;
  1473. @media (max-width: ${p => p.theme.breakpoints.small}) {
  1474. margin-left: -${space(4)};
  1475. }
  1476. `;
  1477. const SetConditionsListItem = styled(StyledListItem)`
  1478. display: flex;
  1479. justify-content: space-between;
  1480. `;
  1481. const Step = styled('div')`
  1482. position: relative;
  1483. display: flex;
  1484. align-items: flex-start;
  1485. margin: ${space(4)} ${space(4)} ${space(3)} ${space(1)};
  1486. `;
  1487. const StepHeader = styled('h5')`
  1488. margin-bottom: ${space(1)};
  1489. `;
  1490. const StepContainer = styled('div')`
  1491. position: relative;
  1492. display: flex;
  1493. align-items: flex-start;
  1494. flex-grow: 1;
  1495. `;
  1496. const StepContent = styled('div')`
  1497. flex-grow: 1;
  1498. `;
  1499. const StepConnector = styled('div')`
  1500. position: absolute;
  1501. height: 100%;
  1502. top: 28px;
  1503. left: 19px;
  1504. border-right: 1px ${p => p.theme.gray200} dashed;
  1505. `;
  1506. const StepLead = styled('div')`
  1507. margin-bottom: ${space(0.5)};
  1508. display: flex;
  1509. align-items: center;
  1510. gap: ${space(0.5)};
  1511. `;
  1512. const TestButtonWrapper = styled('div')`
  1513. margin-top: ${space(1.5)};
  1514. `;
  1515. const ChevronContainer = styled('div')`
  1516. display: flex;
  1517. align-items: center;
  1518. padding: ${space(0.5)} ${space(1.5)};
  1519. `;
  1520. const Badge = styled('span')`
  1521. min-width: 56px;
  1522. background-color: ${p => p.theme.purple300};
  1523. padding: 0 ${space(0.75)};
  1524. border-radius: ${p => p.theme.borderRadius};
  1525. color: ${p => p.theme.white};
  1526. text-transform: uppercase;
  1527. text-align: center;
  1528. font-size: ${p => p.theme.fontSizeMedium};
  1529. font-weight: ${p => p.theme.fontWeightBold};
  1530. line-height: 1.5;
  1531. `;
  1532. const EmbeddedWrapper = styled('div')`
  1533. width: 80px;
  1534. `;
  1535. const EmbeddedSelectField = styled(SelectField)`
  1536. padding: 0;
  1537. font-weight: ${p => p.theme.fontWeightNormal};
  1538. text-transform: none;
  1539. `;
  1540. const SemiTransparentLoadingMask = styled(LoadingMask)`
  1541. opacity: 0.6;
  1542. z-index: 1; /* Needed so that it sits above form elements */
  1543. `;
  1544. const SettingsContainer = styled('div')`
  1545. display: grid;
  1546. grid-template-columns: 1fr 1fr;
  1547. gap: ${space(1)};
  1548. `;
  1549. const StyledField = styled(FieldGroup)`
  1550. border-bottom: none;
  1551. padding: 0;
  1552. & > div {
  1553. padding: 0;
  1554. width: 100%;
  1555. }
  1556. margin-bottom: ${space(1)};
  1557. `;
  1558. const StyledFieldWrapper = styled('div')`
  1559. @media (min-width: ${p => p.theme.breakpoints.small}) {
  1560. display: grid;
  1561. grid-template-columns: 2fr 1fr;
  1562. gap: ${space(1)};
  1563. }
  1564. `;
  1565. const ContentIndent = styled('div')`
  1566. @media (min-width: ${p => p.theme.breakpoints.small}) {
  1567. margin-left: ${space(4)};
  1568. }
  1569. `;
  1570. const AcknowledgeLabel = styled('label')`
  1571. display: flex;
  1572. align-items: center;
  1573. gap: ${space(1)};
  1574. line-height: 2;
  1575. font-weight: ${p => p.theme.fontWeightNormal};
  1576. `;
  1577. const AcknowledgeField = styled(FieldGroup)`
  1578. padding: 0;
  1579. display: flex;
  1580. align-items: center;
  1581. margin-top: ${space(1)};
  1582. & > div {
  1583. padding-left: 0;
  1584. display: flex;
  1585. align-items: baseline;
  1586. flex: unset;
  1587. gap: ${space(1)};
  1588. }
  1589. `;