index.tsx 55 KB

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