index.tsx 58 KB

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