index.tsx 56 KB

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