index.tsx 56 KB

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