index.tsx 55 KB

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