index.tsx 56 KB

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