index.tsx 56 KB

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