index.tsx 55 KB

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