index.tsx 56 KB

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