index.tsx 55 KB

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