index.tsx 57 KB

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