index.tsx 58 KB

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