index.tsx 58 KB

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