index.tsx 54 KB

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