index.tsx 55 KB

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