index.tsx 55 KB

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