index.tsx 58 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771
  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/url/normalizeUrl';
  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 SetupMessagingIntegrationButton, {
  72. MessagingIntegrationAnalyticsView,
  73. } from 'sentry/views/alerts/rules/issue/setupMessagingIntegrationButton';
  74. import {
  75. CHANGE_ALERT_CONDITION_IDS,
  76. CHANGE_ALERT_PLACEHOLDERS_LABELS,
  77. } from 'sentry/views/alerts/utils/constants';
  78. import DeprecatedAsyncView from 'sentry/views/deprecatedAsyncView';
  79. import PermissionAlert from 'sentry/views/settings/project/permissionAlert';
  80. import {getProjectOptions} from '../utils';
  81. import RuleNodeList from './ruleNodeList';
  82. import SetupAlertIntegrationButton from './setupAlertIntegrationButton';
  83. const FREQUENCY_OPTIONS = [
  84. {value: '5', label: t('5 minutes')},
  85. {value: '10', label: t('10 minutes')},
  86. {value: '30', label: t('30 minutes')},
  87. {value: '60', label: t('60 minutes')},
  88. {value: '180', label: t('3 hours')},
  89. {value: '720', label: t('12 hours')},
  90. {value: '1440', label: t('24 hours')},
  91. {value: '10080', label: t('1 week')},
  92. {value: '43200', label: t('30 days')},
  93. ];
  94. const ACTION_MATCH_OPTIONS = [
  95. {value: 'all', label: t('all')},
  96. {value: 'any', label: t('any')},
  97. {value: 'none', label: t('none')},
  98. ];
  99. const ACTION_MATCH_OPTIONS_MIGRATED = [
  100. {value: 'all', label: t('all')},
  101. {value: 'any', label: t('any')},
  102. ];
  103. const defaultRule: UnsavedIssueAlertRule = {
  104. actionMatch: 'any',
  105. filterMatch: 'all',
  106. actions: [],
  107. // note we update the default conditions in onLoadAllEndpointsSuccess
  108. conditions: [],
  109. filters: [],
  110. name: '',
  111. frequency: 60 * 24,
  112. environment: ALL_ENVIRONMENTS_KEY,
  113. };
  114. const POLLING_MAX_TIME_LIMIT = 3 * 60000;
  115. type ConfigurationKey = keyof IssueAlertConfiguration;
  116. type RuleTaskResponse = {
  117. status: 'pending' | 'failed' | 'success';
  118. error?: string;
  119. rule?: IssueAlertRule;
  120. };
  121. type RouteParams = {projectId?: string; ruleId?: string};
  122. export type IncompatibleRule = {
  123. conditionIndices: number[] | null;
  124. filterIndices: number[] | null;
  125. };
  126. type Props = {
  127. location: Location;
  128. members: Member[] | undefined;
  129. organization: Organization;
  130. project: Project;
  131. projects: Project[];
  132. userTeamIds: string[];
  133. loadingProjects?: boolean;
  134. onChangeTitle?: (data: string) => void;
  135. } & RouteComponentProps<RouteParams, {}>;
  136. type State = DeprecatedAsyncView['state'] & {
  137. configs: IssueAlertConfiguration | null;
  138. detailedError: null | {
  139. [key: string]: string[];
  140. };
  141. environments: Environment[] | null;
  142. incompatibleConditions: number[] | null;
  143. incompatibleFilters: number[] | null;
  144. project: Project;
  145. sendingNotification: boolean;
  146. acceptedNoisyAlert?: boolean;
  147. duplicateTargetRule?: UnsavedIssueAlertRule | IssueAlertRule | null;
  148. rule?: UnsavedIssueAlertRule | IssueAlertRule | null;
  149. };
  150. function isSavedAlertRule(rule: State['rule']): rule is IssueAlertRule {
  151. return rule?.hasOwnProperty('id') ?? false;
  152. }
  153. /**
  154. * Expecting "This rule is an exact duplicate of '{duplicate_rule.label}' in this project and may not be created."
  155. */
  156. const isExactDuplicateExp = /duplicate of '(.*)'/;
  157. class IssueRuleEditor extends DeprecatedAsyncView<Props, State> {
  158. pollingTimeout: number | undefined = undefined;
  159. trackIncompatibleAnalytics = false;
  160. trackNoisyWarningViewed = false;
  161. isUnmounted = false;
  162. uuid: string | null = null;
  163. get isDuplicateRule(): boolean {
  164. const {location} = this.props;
  165. const createFromDuplicate = location?.query.createFromDuplicate === 'true';
  166. return createFromDuplicate && location?.query.duplicateRuleId;
  167. }
  168. componentDidMount() {
  169. super.componentDidMount();
  170. }
  171. componentWillUnmount() {
  172. super.componentWillUnmount();
  173. this.isUnmounted = true;
  174. window.clearTimeout(this.pollingTimeout);
  175. this.checkIncompatibleRuleDebounced.cancel();
  176. }
  177. componentDidUpdate(_prevProps: Props, prevState: State) {
  178. if (this.isRuleStateChange(prevState)) {
  179. this.setState({
  180. incompatibleConditions: null,
  181. incompatibleFilters: null,
  182. });
  183. this.checkIncompatibleRuleDebounced();
  184. }
  185. if (prevState.project.id === this.state.project.id) {
  186. return;
  187. }
  188. this.fetchEnvironments();
  189. this.refetchConfigs();
  190. }
  191. isRuleStateChange(prevState: State): boolean {
  192. const prevRule = prevState.rule;
  193. const curRule = this.state.rule;
  194. return (
  195. JSON.stringify(prevRule?.conditions) !== JSON.stringify(curRule?.conditions) ||
  196. JSON.stringify(prevRule?.filters) !== JSON.stringify(curRule?.filters) ||
  197. prevRule?.actionMatch !== curRule?.actionMatch ||
  198. prevRule?.filterMatch !== curRule?.filterMatch ||
  199. prevRule?.frequency !== curRule?.frequency ||
  200. JSON.stringify(prevState.project) !== JSON.stringify(this.state.project)
  201. );
  202. }
  203. getTitle() {
  204. const {organization} = this.props;
  205. const {rule, project} = this.state;
  206. const ruleName = rule?.name;
  207. return routeTitleGen(
  208. ruleName ? t('Alert - %s', ruleName) : t('New Alert Rule'),
  209. organization.slug,
  210. false,
  211. project?.slug
  212. );
  213. }
  214. getDefaultState() {
  215. const {userTeamIds, project} = this.props;
  216. const defaultState = {
  217. ...super.getDefaultState(),
  218. configs: null,
  219. detailedError: null,
  220. rule: {...defaultRule},
  221. environments: [],
  222. project,
  223. sendingNotification: false,
  224. incompatibleConditions: null,
  225. incompatibleFilters: null,
  226. };
  227. const projectTeamIds = new Set(project.teams.map(({id}) => id));
  228. const userTeamId = userTeamIds.find(id => projectTeamIds.has(id)) ?? null;
  229. defaultState.rule.owner = userTeamId && `team:${userTeamId}`;
  230. return defaultState;
  231. }
  232. getEndpoints(): ReturnType<DeprecatedAsyncView['getEndpoints']> {
  233. const {
  234. location: {query},
  235. params: {ruleId},
  236. } = this.props;
  237. const {organization} = this.props;
  238. // project in state isn't initialized when getEndpoints is first called
  239. const project = this.state?.project ?? this.props.project;
  240. const endpoints = [
  241. [
  242. 'environments',
  243. `/projects/${organization.slug}/${project.slug}/environments/`,
  244. {
  245. query: {
  246. visibility: 'visible',
  247. },
  248. },
  249. ],
  250. ['configs', `/projects/${organization.slug}/${project.slug}/rules/configuration/`],
  251. ];
  252. if (ruleId) {
  253. endpoints.push([
  254. 'rule',
  255. `/projects/${organization.slug}/${project.slug}/rules/${ruleId}/`,
  256. ]);
  257. }
  258. if (!ruleId && query.createFromDuplicate && query.duplicateRuleId) {
  259. endpoints.push([
  260. 'duplicateTargetRule',
  261. `/projects/${organization.slug}/${project.slug}/rules/${query.duplicateRuleId}/`,
  262. ]);
  263. }
  264. return endpoints as [string, string][];
  265. }
  266. onRequestSuccess({stateKey, data}) {
  267. if (stateKey === 'rule' && data.name) {
  268. this.props.onChangeTitle?.(data.name);
  269. }
  270. if (stateKey === 'duplicateTargetRule') {
  271. this.setState({
  272. rule: {
  273. ...omit(data, ['id']),
  274. name: data.name + ' copy',
  275. } as UnsavedIssueAlertRule,
  276. });
  277. }
  278. }
  279. onLoadAllEndpointsSuccess() {
  280. const {rule} = this.state;
  281. const {
  282. params: {ruleId},
  283. } = this.props;
  284. if (rule) {
  285. ((rule as IssueAlertRule)?.errors || []).map(({detail}) =>
  286. addErrorMessage(detail, {append: true})
  287. );
  288. }
  289. if (!ruleId && !this.isDuplicateRule) {
  290. // now that we've loaded all the possible conditions, we can populate the
  291. // value of conditions for a new alert
  292. if (this.props.organization.features.includes('priority-ga-features')) {
  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. const hasMessagingIntegrationOnboarding = organization.features.includes(
  1041. 'messaging-integration-onboarding'
  1042. );
  1043. // Note `key` on `<Form>` below is so that on initial load, we show
  1044. // the form with a loading mask on top of it, but force a re-render by using
  1045. // a different key when we have fetched the rule so that form inputs are filled in
  1046. return (
  1047. <Main fullWidth>
  1048. <PermissionAlert access={['alerts:write']} project={project} />
  1049. <StyledForm
  1050. key={isSavedAlertRule(rule) ? rule.id : undefined}
  1051. onCancel={this.handleCancel}
  1052. onSubmit={this.handleSubmit}
  1053. initialData={{
  1054. ...rule,
  1055. environment,
  1056. frequency: `${frequency}`,
  1057. projectId: project.id,
  1058. }}
  1059. submitDisabled={
  1060. disabled || incompatibleConditions !== null || incompatibleFilters !== null
  1061. }
  1062. submitLabel={t('Save Rule')}
  1063. extraButton={
  1064. isSavedAlertRule(rule) ? (
  1065. <Confirm
  1066. disabled={disabled}
  1067. priority="danger"
  1068. confirmText={t('Delete Rule')}
  1069. onConfirm={this.handleDeleteRule}
  1070. header={<h5>{t('Delete Alert Rule?')}</h5>}
  1071. message={t(
  1072. 'Are you sure you want to delete "%s"? You won\'t be able to view the history of this alert once it\'s deleted.',
  1073. rule.name
  1074. )}
  1075. >
  1076. <Button priority="danger">{t('Delete Rule')}</Button>
  1077. </Confirm>
  1078. ) : null
  1079. }
  1080. >
  1081. <List symbol="colored-numeric">
  1082. {loading && <SemiTransparentLoadingMask data-test-id="loading-mask" />}
  1083. <StyledListItem>
  1084. <StepHeader>{t('Select an environment and project')}</StepHeader>
  1085. </StyledListItem>
  1086. <ContentIndent>
  1087. <SettingsContainer>
  1088. {this.renderEnvironmentSelect(disabled)}
  1089. {this.renderProjectSelect(disabled)}
  1090. </SettingsContainer>
  1091. </ContentIndent>
  1092. <SetConditionsListItem>
  1093. <StepHeader>{t('Set conditions')}</StepHeader>{' '}
  1094. {hasMessagingIntegrationOnboarding ? (
  1095. <SetupMessagingIntegrationButton
  1096. projectSlug={project.slug}
  1097. refetchConfigs={this.refetchConfigs}
  1098. analyticsParams={{
  1099. view: MessagingIntegrationAnalyticsView.ALERT_RULE_CREATION,
  1100. }}
  1101. />
  1102. ) : (
  1103. <SetupAlertIntegrationButton
  1104. projectSlug={project.slug}
  1105. organization={organization}
  1106. refetchConfigs={this.refetchConfigs}
  1107. />
  1108. )}
  1109. </SetConditionsListItem>
  1110. <ContentIndent>
  1111. <ConditionsPanel>
  1112. <PanelBody>
  1113. <Step>
  1114. <StepConnector />
  1115. <StepContainer>
  1116. <ChevronContainer>
  1117. <IconChevron
  1118. color="gray200"
  1119. isCircled
  1120. direction="right"
  1121. size="sm"
  1122. />
  1123. </ChevronContainer>
  1124. <StepContent>
  1125. <StepLead>
  1126. {tct(
  1127. '[when:When] an event is captured by Sentry and [selector] of the following happens',
  1128. {
  1129. when: <Badge />,
  1130. selector: (
  1131. <EmbeddedWrapper>
  1132. <EmbeddedSelectField
  1133. className={classNames({
  1134. error: this.hasError('actionMatch'),
  1135. })}
  1136. styles={{
  1137. control: provided => ({
  1138. ...provided,
  1139. minHeight: '21px',
  1140. height: '21px',
  1141. }),
  1142. }}
  1143. inline={false}
  1144. isSearchable={false}
  1145. isClearable={false}
  1146. name="actionMatch"
  1147. required
  1148. flexibleControlStateSize
  1149. options={ACTION_MATCH_OPTIONS_MIGRATED}
  1150. onChange={val =>
  1151. this.handleChange('actionMatch', val)
  1152. }
  1153. size="xs"
  1154. disabled={disabled}
  1155. />
  1156. </EmbeddedWrapper>
  1157. ),
  1158. }
  1159. )}
  1160. </StepLead>
  1161. <RuleNodeList
  1162. nodes={this.getConditions()}
  1163. items={conditions ?? []}
  1164. selectType="grouped"
  1165. placeholder={t('Add optional trigger...')}
  1166. onPropertyChange={this.handleChangeConditionProperty}
  1167. onAddRow={this.handleAddCondition}
  1168. onResetRow={this.handleResetCondition}
  1169. onDeleteRow={this.handleDeleteCondition}
  1170. organization={organization}
  1171. project={project}
  1172. disabled={disabled}
  1173. error={
  1174. this.hasError('conditions') && (
  1175. <StyledAlert type="error">
  1176. {detailedError?.conditions[0]}
  1177. {(detailedError?.conditions[0] || '').startsWith(
  1178. 'You may not exceed'
  1179. ) && (
  1180. <Fragment>
  1181. {' '}
  1182. <ExternalLink href="https://docs.sentry.io/product/alerts/create-alerts/#alert-limits">
  1183. {t('View Docs')}
  1184. </ExternalLink>
  1185. </Fragment>
  1186. )}
  1187. </StyledAlert>
  1188. )
  1189. }
  1190. incompatibleRules={incompatibleConditions}
  1191. incompatibleBanner={
  1192. incompatibleFilters === null &&
  1193. incompatibleConditions !== null
  1194. ? incompatibleConditions.at(-1)
  1195. : null
  1196. }
  1197. />
  1198. </StepContent>
  1199. </StepContainer>
  1200. </Step>
  1201. <Step>
  1202. <StepConnector />
  1203. <StepContainer>
  1204. <ChevronContainer>
  1205. <IconChevron
  1206. color="gray200"
  1207. isCircled
  1208. direction="right"
  1209. size="sm"
  1210. />
  1211. </ChevronContainer>
  1212. <StepContent data-test-id="rule-filters">
  1213. <StepLead>
  1214. {tct('[if:If][selector] of these filters match', {
  1215. if: <Badge />,
  1216. selector: (
  1217. <EmbeddedWrapper>
  1218. <EmbeddedSelectField
  1219. className={classNames({
  1220. error: this.hasError('filterMatch'),
  1221. })}
  1222. styles={{
  1223. control: provided => ({
  1224. ...provided,
  1225. minHeight: '21px',
  1226. height: '21px',
  1227. }),
  1228. }}
  1229. inline={false}
  1230. isSearchable={false}
  1231. isClearable={false}
  1232. name="filterMatch"
  1233. required
  1234. flexibleControlStateSize
  1235. options={ACTION_MATCH_OPTIONS}
  1236. onChange={val => this.handleChange('filterMatch', val)}
  1237. size="xs"
  1238. disabled={disabled}
  1239. />
  1240. </EmbeddedWrapper>
  1241. ),
  1242. })}
  1243. </StepLead>
  1244. <RuleNodeList
  1245. nodes={this.state.configs?.filters ?? null}
  1246. items={filters ?? []}
  1247. placeholder={t('Add optional filter...')}
  1248. onPropertyChange={this.handleChangeFilterProperty}
  1249. onAddRow={this.handleAddFilter}
  1250. onResetRow={this.handleResetFilter}
  1251. onDeleteRow={this.handleDeleteFilter}
  1252. organization={organization}
  1253. project={project}
  1254. disabled={disabled}
  1255. error={
  1256. this.hasError('filters') && (
  1257. <StyledAlert type="error">
  1258. {detailedError?.filters[0]}
  1259. </StyledAlert>
  1260. )
  1261. }
  1262. incompatibleRules={incompatibleFilters}
  1263. incompatibleBanner={
  1264. incompatibleFilters ? incompatibleFilters.at(-1) : null
  1265. }
  1266. />
  1267. </StepContent>
  1268. </StepContainer>
  1269. </Step>
  1270. <Step>
  1271. <StepContainer>
  1272. <ChevronContainer>
  1273. <IconChevron
  1274. isCircled
  1275. color="gray200"
  1276. direction="right"
  1277. size="sm"
  1278. />
  1279. </ChevronContainer>
  1280. <StepContent>
  1281. <StepLead>
  1282. {tct('[then:Then] perform these actions', {
  1283. then: <Badge />,
  1284. })}
  1285. </StepLead>
  1286. <RuleNodeList
  1287. nodes={this.state.configs?.actions ?? null}
  1288. selectType="grouped"
  1289. items={actions ?? []}
  1290. placeholder={t('Add action...')}
  1291. onPropertyChange={this.handleChangeActionProperty}
  1292. onAddRow={this.handleAddAction}
  1293. onResetRow={this.handleResetAction}
  1294. onDeleteRow={this.handleDeleteAction}
  1295. organization={organization}
  1296. project={project}
  1297. disabled={disabled}
  1298. error={
  1299. this.hasError('actions') && (
  1300. <StyledAlert type="error">
  1301. {detailedError?.actions[0]}
  1302. </StyledAlert>
  1303. )
  1304. }
  1305. {...(hasMessagingIntegrationOnboarding && {
  1306. additionalAction: {
  1307. label: 'Notify integration\u{2026}',
  1308. option: {
  1309. label: 'Missing an integration? Click here to refresh',
  1310. value: {
  1311. enabled: true,
  1312. id: 'refresh_configs',
  1313. label: 'Refresh Integration List',
  1314. },
  1315. },
  1316. onClick: () => {
  1317. trackAnalytics(
  1318. 'onboarding.messaging_integration_steps_refreshed',
  1319. {
  1320. organization: this.props.organization,
  1321. }
  1322. );
  1323. this.refetchConfigs();
  1324. },
  1325. },
  1326. })}
  1327. />
  1328. <TestButtonWrapper>
  1329. <Button
  1330. onClick={this.testNotifications}
  1331. disabled={sendingNotification || rule?.actions?.length === 0}
  1332. >
  1333. {t('Send Test Notification')}
  1334. </Button>
  1335. </TestButtonWrapper>
  1336. </StepContent>
  1337. </StepContainer>
  1338. </Step>
  1339. </PanelBody>
  1340. </ConditionsPanel>
  1341. </ContentIndent>
  1342. <StyledListItem>
  1343. <StepHeader>{t('Set action interval')}</StepHeader>
  1344. <StyledFieldHelp>
  1345. {t('Perform the actions above once this often for an issue')}
  1346. </StyledFieldHelp>
  1347. </StyledListItem>
  1348. <ContentIndent>{this.renderActionInterval(disabled)}</ContentIndent>
  1349. <ErrorBoundary mini>
  1350. <PreviewIssues members={members} rule={rule} project={project} />
  1351. </ErrorBoundary>
  1352. <StyledListItem>
  1353. <StepHeader>{t('Add a name and owner')}</StepHeader>
  1354. <StyledFieldHelp>
  1355. {t(
  1356. 'This name will show up in notifications and the owner will give permissions to your whole team to edit and view this alert.'
  1357. )}
  1358. </StyledFieldHelp>
  1359. </StyledListItem>
  1360. <ContentIndent>
  1361. <StyledFieldWrapper>
  1362. {this.renderRuleName(disabled)}
  1363. {this.renderTeamSelect(disabled)}
  1364. </StyledFieldWrapper>
  1365. {displayDuplicateError && this.renderDuplicateErrorAlert()}
  1366. {this.displayNoConditionsWarning() &&
  1367. this.renderAcknowledgeNoConditions(disabled)}
  1368. </ContentIndent>
  1369. </List>
  1370. </StyledForm>
  1371. </Main>
  1372. );
  1373. }
  1374. }
  1375. export default withOrganization(withProjects(IssueRuleEditor));
  1376. export const findIncompatibleRules = (
  1377. rule: IssueAlertRule | UnsavedIssueAlertRule | null | undefined
  1378. ): IncompatibleRule => {
  1379. if (!rule) {
  1380. return {conditionIndices: null, filterIndices: null};
  1381. }
  1382. const {conditions, filters} = rule;
  1383. // Check for more than one 'issue state change' condition
  1384. // or 'FirstSeenEventCondition' + 'EventFrequencyCondition'
  1385. if (rule.actionMatch === 'all') {
  1386. let firstSeen = -1;
  1387. let regression = -1;
  1388. let reappeared = -1;
  1389. let eventFrequency = -1;
  1390. let userFrequency = -1;
  1391. for (let i = 0; i < conditions.length; i++) {
  1392. const id = conditions[i].id;
  1393. if (id === IssueAlertConditionType.FIRST_SEEN_EVENT) {
  1394. firstSeen = i;
  1395. } else if (id === IssueAlertConditionType.REGRESSION_EVENT) {
  1396. regression = i;
  1397. } else if (id === IssueAlertConditionType.REAPPEARED_EVENT) {
  1398. reappeared = i;
  1399. } else if (
  1400. id === IssueAlertConditionType.EVENT_FREQUENCY &&
  1401. (conditions[i].value as number) >= 1
  1402. ) {
  1403. eventFrequency = i;
  1404. } else if (
  1405. id === IssueAlertConditionType.EVENT_UNIQUE_USER_FREQUENCY &&
  1406. (conditions[i].value as number) >= 1
  1407. ) {
  1408. userFrequency = i;
  1409. }
  1410. // FirstSeenEventCondition is incompatible with all the following types
  1411. const firstSeenError =
  1412. firstSeen !== -1 &&
  1413. [regression, reappeared, eventFrequency, userFrequency].some(idx => idx !== -1);
  1414. const regressionReappearedError = regression !== -1 && reappeared !== -1;
  1415. if (firstSeenError || regressionReappearedError) {
  1416. const indices = [firstSeen, regression, reappeared, eventFrequency, userFrequency]
  1417. .filter(idx => idx !== -1)
  1418. .sort((a, b) => a - b);
  1419. return {conditionIndices: indices, filterIndices: null};
  1420. }
  1421. }
  1422. }
  1423. // Check for 'FirstSeenEventCondition' and ('IssueOccurrencesFilter' or 'AgeComparisonFilter')
  1424. // Considers the case where filterMatch is 'any' and all filters are incompatible
  1425. const firstSeen = conditions.findIndex(condition =>
  1426. condition.id.endsWith('FirstSeenEventCondition')
  1427. );
  1428. if (firstSeen !== -1 && (rule.actionMatch === 'all' || conditions.length === 1)) {
  1429. let incompatibleFilters = 0;
  1430. for (let i = 0; i < filters.length; i++) {
  1431. const filter = filters[i];
  1432. const id = filter.id;
  1433. if (id === IssueAlertFilterType.ISSUE_OCCURRENCES && filter) {
  1434. if (
  1435. (rule.filterMatch === 'all' && (filter.value as number) > 1) ||
  1436. (rule.filterMatch === 'none' && (filter.value as number) <= 1)
  1437. ) {
  1438. return {conditionIndices: [firstSeen], filterIndices: [i]};
  1439. }
  1440. if (rule.filterMatch === 'any' && (filter.value as number) > 1) {
  1441. incompatibleFilters += 1;
  1442. }
  1443. } else if (id === IssueAlertFilterType.AGE_COMPARISON) {
  1444. if (rule.filterMatch !== 'none') {
  1445. if (filter.comparison_type === 'older') {
  1446. if (rule.filterMatch === 'all') {
  1447. return {conditionIndices: [firstSeen], filterIndices: [i]};
  1448. }
  1449. incompatibleFilters += 1;
  1450. }
  1451. } else if (filter.comparison_type === 'newer' && (filter.value as number) > 0) {
  1452. return {conditionIndices: [firstSeen], filterIndices: [i]};
  1453. }
  1454. }
  1455. }
  1456. if (incompatibleFilters === filters.length && incompatibleFilters > 0) {
  1457. return {
  1458. conditionIndices: [firstSeen],
  1459. filterIndices: [...Array(filters.length).keys()],
  1460. };
  1461. }
  1462. }
  1463. return {conditionIndices: null, filterIndices: null};
  1464. };
  1465. const Main = styled(Layout.Main)`
  1466. max-width: 1000px;
  1467. `;
  1468. // TODO(ts): Understand why styled is not correctly inheriting props here
  1469. const StyledForm = styled(Form)<FormProps>`
  1470. position: relative;
  1471. `;
  1472. const ConditionsPanel = styled(Panel)`
  1473. padding-top: ${space(0.5)};
  1474. padding-bottom: ${space(2)};
  1475. `;
  1476. const StyledAlert = styled(Alert)`
  1477. margin-bottom: 0;
  1478. `;
  1479. const StyledListItem = styled(ListItem)`
  1480. margin: ${space(2)} 0 ${space(1)} 0;
  1481. font-size: ${p => p.theme.fontSizeExtraLarge};
  1482. `;
  1483. const StyledFieldHelp = styled(FieldHelp)`
  1484. margin-top: 0;
  1485. @media (max-width: ${p => p.theme.breakpoints.small}) {
  1486. margin-left: -${space(4)};
  1487. }
  1488. `;
  1489. const SetConditionsListItem = styled(StyledListItem)`
  1490. display: flex;
  1491. justify-content: space-between;
  1492. `;
  1493. const Step = styled('div')`
  1494. position: relative;
  1495. display: flex;
  1496. align-items: flex-start;
  1497. margin: ${space(4)} ${space(4)} ${space(3)} ${space(1)};
  1498. `;
  1499. const StepHeader = styled('h5')`
  1500. margin-bottom: ${space(1)};
  1501. `;
  1502. const StepContainer = styled('div')`
  1503. position: relative;
  1504. display: flex;
  1505. align-items: flex-start;
  1506. flex-grow: 1;
  1507. `;
  1508. const StepContent = styled('div')`
  1509. flex-grow: 1;
  1510. `;
  1511. const StepConnector = styled('div')`
  1512. position: absolute;
  1513. height: 100%;
  1514. top: 28px;
  1515. left: 19px;
  1516. border-right: 1px ${p => p.theme.gray200} dashed;
  1517. `;
  1518. const StepLead = styled('div')`
  1519. margin-bottom: ${space(0.5)};
  1520. display: flex;
  1521. align-items: center;
  1522. gap: ${space(0.5)};
  1523. `;
  1524. const TestButtonWrapper = styled('div')`
  1525. margin-top: ${space(1.5)};
  1526. `;
  1527. const ChevronContainer = styled('div')`
  1528. display: flex;
  1529. align-items: center;
  1530. padding: ${space(0.5)} ${space(1.5)};
  1531. `;
  1532. const Badge = styled('span')`
  1533. min-width: 56px;
  1534. background-color: ${p => p.theme.purple300};
  1535. padding: 0 ${space(0.75)};
  1536. border-radius: ${p => p.theme.borderRadius};
  1537. color: ${p => p.theme.white};
  1538. text-transform: uppercase;
  1539. text-align: center;
  1540. font-size: ${p => p.theme.fontSizeMedium};
  1541. font-weight: ${p => p.theme.fontWeightBold};
  1542. line-height: 1.5;
  1543. `;
  1544. const EmbeddedWrapper = styled('div')`
  1545. width: 80px;
  1546. `;
  1547. const EmbeddedSelectField = styled(SelectField)`
  1548. padding: 0;
  1549. font-weight: ${p => p.theme.fontWeightNormal};
  1550. text-transform: none;
  1551. `;
  1552. const SemiTransparentLoadingMask = styled(LoadingMask)`
  1553. opacity: 0.6;
  1554. z-index: 1; /* Needed so that it sits above form elements */
  1555. `;
  1556. const SettingsContainer = styled('div')`
  1557. display: grid;
  1558. grid-template-columns: 1fr 1fr;
  1559. gap: ${space(1)};
  1560. `;
  1561. const StyledField = styled(FieldGroup)`
  1562. border-bottom: none;
  1563. padding: 0;
  1564. & > div {
  1565. padding: 0;
  1566. width: 100%;
  1567. }
  1568. margin-bottom: ${space(1)};
  1569. `;
  1570. const StyledFieldWrapper = styled('div')`
  1571. @media (min-width: ${p => p.theme.breakpoints.small}) {
  1572. display: grid;
  1573. grid-template-columns: 2fr 1fr;
  1574. gap: ${space(1)};
  1575. }
  1576. `;
  1577. const ContentIndent = styled('div')`
  1578. @media (min-width: ${p => p.theme.breakpoints.small}) {
  1579. margin-left: ${space(4)};
  1580. }
  1581. `;
  1582. const AcknowledgeLabel = styled('label')`
  1583. display: flex;
  1584. align-items: center;
  1585. gap: ${space(1)};
  1586. line-height: 2;
  1587. font-weight: ${p => p.theme.fontWeightNormal};
  1588. `;
  1589. const AcknowledgeField = styled(FieldGroup)`
  1590. padding: 0;
  1591. display: flex;
  1592. align-items: center;
  1593. margin-top: ${space(1)};
  1594. & > div {
  1595. padding-left: 0;
  1596. display: flex;
  1597. align-items: baseline;
  1598. flex: unset;
  1599. gap: ${space(1)};
  1600. }
  1601. `;