index.tsx 55 KB

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