index.tsx 56 KB

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