index.tsx 55 KB

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