index.tsx 58 KB

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