issueAlertOptions.tsx 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380
  1. import {Fragment} from 'react';
  2. import {css} from '@emotion/react';
  3. import styled from '@emotion/styled';
  4. import * as Sentry from '@sentry/react';
  5. import isEqual from 'lodash/isEqual';
  6. import AsyncComponent from 'sentry/components/asyncComponent';
  7. import RadioGroup from 'sentry/components/forms/controls/radioGroup';
  8. import MultipleCheckboxField from 'sentry/components/forms/MultipleCheckboxField';
  9. import SelectControl from 'sentry/components/forms/selectControl';
  10. import Input from 'sentry/components/input';
  11. import PageHeading from 'sentry/components/pageHeading';
  12. import {t} from 'sentry/locale';
  13. import space from 'sentry/styles/space';
  14. import {Organization} from 'sentry/types';
  15. import withOrganization from 'sentry/utils/withOrganization';
  16. import {PRESET_AGGREGATES} from '../alerts/rules/metric/presets';
  17. enum MetricValues {
  18. ERRORS,
  19. USERS,
  20. }
  21. enum Actions {
  22. ALERT_ON_EVERY_ISSUE,
  23. CUSTOMIZED_ALERTS,
  24. CREATE_ALERT_LATER,
  25. }
  26. const UNIQUE_USER_FREQUENCY_CONDITION =
  27. 'sentry.rules.conditions.event_frequency.EventUniqueUserFrequencyCondition';
  28. const EVENT_FREQUENCY_CONDITION =
  29. 'sentry.rules.conditions.event_frequency.EventFrequencyCondition';
  30. const NOTIFY_EVENT_ACTION = 'sentry.rules.actions.notify_event.NotifyEventAction';
  31. export const EVENT_FREQUENCY_PERCENT_CONDITION =
  32. 'sentry.rules.conditions.event_frequency.EventFrequencyPercentCondition';
  33. const METRIC_CONDITION_MAP = {
  34. [MetricValues.ERRORS]: EVENT_FREQUENCY_CONDITION,
  35. [MetricValues.USERS]: UNIQUE_USER_FREQUENCY_CONDITION,
  36. } as const;
  37. const DEFAULT_PLACEHOLDER_VALUE = '10';
  38. type StateUpdater = (updatedData: RequestDataFragment) => void;
  39. type Props = AsyncComponent['props'] & {
  40. onChange: StateUpdater;
  41. organization: Organization;
  42. };
  43. type State = AsyncComponent['state'] & {
  44. alertSetting: string;
  45. // TODO(ts): When we have alert conditional types, convert this
  46. conditions: any;
  47. interval: string;
  48. intervalChoices: [string, string][] | undefined;
  49. metric: MetricValues;
  50. metricAlertPresets: Set<string>;
  51. threshold: string;
  52. };
  53. type RequestDataFragment = {
  54. actionMatch: string;
  55. actions: {id: string}[];
  56. conditions: {id: string; interval: string; value: string}[] | undefined;
  57. defaultRules: boolean;
  58. frequency: number;
  59. metricAlertPresets: string[];
  60. name: string;
  61. shouldCreateCustomRule: boolean;
  62. };
  63. function getConditionFrom(
  64. interval: string,
  65. metricValue: MetricValues,
  66. threshold: string
  67. ): {id: string; interval: string; value: string} {
  68. let condition: string;
  69. switch (metricValue) {
  70. case MetricValues.ERRORS:
  71. condition = EVENT_FREQUENCY_CONDITION;
  72. break;
  73. case MetricValues.USERS:
  74. condition = UNIQUE_USER_FREQUENCY_CONDITION;
  75. break;
  76. default:
  77. throw new RangeError('Supplied metric value is not handled');
  78. }
  79. return {
  80. interval,
  81. id: condition,
  82. value: threshold,
  83. };
  84. }
  85. function unpackConditions(conditions: any[]) {
  86. const equalityReducer = (acc, curr) => {
  87. if (!acc || !curr || !isEqual(acc, curr)) {
  88. return null;
  89. }
  90. return acc;
  91. };
  92. const intervalChoices = conditions
  93. .map(condition => condition.formFields?.interval?.choices)
  94. .reduce(equalityReducer);
  95. return {intervalChoices, interval: intervalChoices?.[0]?.[0]};
  96. }
  97. class IssueAlertOptions extends AsyncComponent<Props, State> {
  98. getDefaultState(): State {
  99. return {
  100. ...super.getDefaultState(),
  101. conditions: [],
  102. intervalChoices: [],
  103. alertSetting: Actions.CREATE_ALERT_LATER.toString(),
  104. metric: MetricValues.ERRORS,
  105. interval: '',
  106. threshold: '',
  107. metricAlertPresets: new Set(),
  108. };
  109. }
  110. getAvailableMetricOptions() {
  111. return [
  112. {value: MetricValues.ERRORS, label: t('occurrences of')},
  113. {value: MetricValues.USERS, label: t('users affected by')},
  114. ].filter(({value}) => {
  115. return this.state.conditions?.some?.(
  116. object => object?.id === METRIC_CONDITION_MAP[value]
  117. );
  118. });
  119. }
  120. getIssueAlertsChoices(
  121. hasProperlyLoadedConditions: boolean
  122. ): [string, string | React.ReactElement][] {
  123. const options: [string, React.ReactNode][] = [
  124. [Actions.CREATE_ALERT_LATER.toString(), t("I'll create my own alerts later")],
  125. [Actions.ALERT_ON_EVERY_ISSUE.toString(), t('Alert me on every new issue')],
  126. ];
  127. if (hasProperlyLoadedConditions) {
  128. options.push([
  129. Actions.CUSTOMIZED_ALERTS.toString(),
  130. <CustomizeAlertsGrid
  131. key={Actions.CUSTOMIZED_ALERTS}
  132. onClick={e => {
  133. // XXX(epurkhiser): The `e.preventDefault` here is needed to stop
  134. // propagation of the click up to the label, causing it to focus
  135. // the radio input and lose focus on the select.
  136. e.preventDefault();
  137. const alertSetting = Actions.CUSTOMIZED_ALERTS.toString();
  138. this.setStateAndUpdateParents({alertSetting});
  139. }}
  140. >
  141. {t('When there are more than')}
  142. <InlineInput
  143. type="number"
  144. min="0"
  145. name=""
  146. placeholder={DEFAULT_PLACEHOLDER_VALUE}
  147. value={this.state.threshold}
  148. onChange={threshold =>
  149. this.setStateAndUpdateParents({threshold: threshold.target.value})
  150. }
  151. data-test-id="range-input"
  152. />
  153. <InlineSelectControl
  154. value={this.state.metric}
  155. options={this.getAvailableMetricOptions()}
  156. onChange={metric => this.setStateAndUpdateParents({metric: metric.value})}
  157. />
  158. {t('a unique error in')}
  159. <InlineSelectControl
  160. value={this.state.interval}
  161. options={this.state.intervalChoices?.map(([value, label]) => ({
  162. value,
  163. label,
  164. }))}
  165. onChange={interval =>
  166. this.setStateAndUpdateParents({interval: interval.value})
  167. }
  168. />
  169. </CustomizeAlertsGrid>,
  170. ]);
  171. }
  172. return options.map(([choiceValue, node]) => [
  173. choiceValue,
  174. <RadioItemWrapper key={choiceValue}>{node}</RadioItemWrapper>,
  175. ]);
  176. }
  177. getUpdatedData(): RequestDataFragment {
  178. let defaultRules: boolean;
  179. let shouldCreateCustomRule: boolean;
  180. const alertSetting: Actions = parseInt(this.state.alertSetting, 10);
  181. switch (alertSetting) {
  182. case Actions.ALERT_ON_EVERY_ISSUE:
  183. defaultRules = true;
  184. shouldCreateCustomRule = false;
  185. break;
  186. case Actions.CREATE_ALERT_LATER:
  187. defaultRules = false;
  188. shouldCreateCustomRule = false;
  189. break;
  190. case Actions.CUSTOMIZED_ALERTS:
  191. defaultRules = false;
  192. shouldCreateCustomRule = true;
  193. break;
  194. default:
  195. throw new RangeError('Supplied alert creation action is not handled');
  196. }
  197. return {
  198. defaultRules,
  199. shouldCreateCustomRule,
  200. name: 'Send a notification for new issues',
  201. conditions:
  202. this.state.interval.length > 0 && this.state.threshold.length > 0
  203. ? [
  204. getConditionFrom(
  205. this.state.interval,
  206. this.state.metric,
  207. this.state.threshold
  208. ),
  209. ]
  210. : undefined,
  211. actions: [{id: NOTIFY_EVENT_ACTION}],
  212. actionMatch: 'all',
  213. frequency: 5,
  214. metricAlertPresets: Array.from(this.state.metricAlertPresets),
  215. };
  216. }
  217. setStateAndUpdateParents<K extends keyof State>(
  218. state:
  219. | ((
  220. prevState: Readonly<State>,
  221. props: Readonly<Props>
  222. ) => Pick<State, K> | State | null)
  223. | Pick<State, K>
  224. | State
  225. | null
  226. ): void {
  227. this.setState(state, () => {
  228. this.props.onChange(this.getUpdatedData());
  229. });
  230. }
  231. getEndpoints(): ReturnType<AsyncComponent['getEndpoints']> {
  232. return [['conditions', `/projects/${this.props.organization.slug}/rule-conditions/`]];
  233. }
  234. onLoadAllEndpointsSuccess(): void {
  235. const conditions = this.state.conditions?.filter?.(object =>
  236. Object.values(METRIC_CONDITION_MAP).includes(object?.id)
  237. );
  238. if (!conditions || conditions.length === 0) {
  239. this.setStateAndUpdateParents({
  240. conditions: undefined,
  241. });
  242. return;
  243. }
  244. const {intervalChoices, interval} = unpackConditions(conditions);
  245. if (!intervalChoices || !interval) {
  246. Sentry.withScope(scope => {
  247. scope.setExtra('props', this.props);
  248. scope.setExtra('state', this.state);
  249. Sentry.captureException(
  250. new Error('Interval choices or sent from API endpoint is inconsistent or empty')
  251. );
  252. });
  253. this.setStateAndUpdateParents({
  254. conditions: undefined,
  255. });
  256. return;
  257. }
  258. this.setStateAndUpdateParents({
  259. conditions,
  260. intervalChoices,
  261. interval,
  262. });
  263. }
  264. renderBody(): React.ReactElement {
  265. const issueAlertOptionsChoices = this.getIssueAlertsChoices(
  266. this.state.conditions?.length > 0
  267. );
  268. const showMetricAlertSelections =
  269. !!this.props.organization.experiments.MetricAlertOnProjectCreationExperiment;
  270. return (
  271. <Fragment>
  272. <PageHeadingWithTopMargins withMargins>
  273. {t('Set your default alert settings')}
  274. </PageHeadingWithTopMargins>
  275. <Content>
  276. {showMetricAlertSelections && <Subheading>{t('Issue Alerts')}</Subheading>}
  277. <RadioGroupWithPadding
  278. choices={issueAlertOptionsChoices}
  279. label={t('Options for creating an alert')}
  280. onChange={alertSetting => this.setStateAndUpdateParents({alertSetting})}
  281. value={this.state.alertSetting}
  282. />
  283. {showMetricAlertSelections && (
  284. <Fragment>
  285. <Subheading>{t('Performance Alerts')}</Subheading>
  286. <MultipleCheckboxField
  287. size="24px"
  288. choices={PRESET_AGGREGATES.map(agg => ({
  289. title: agg.description,
  290. value: agg.id,
  291. checked: this.state.metricAlertPresets.has(agg.id),
  292. }))}
  293. css={CheckboxFieldStyles}
  294. onClick={selectedItem => {
  295. const next = new Set(this.state.metricAlertPresets);
  296. if (next.has(selectedItem)) {
  297. next.delete(selectedItem);
  298. } else {
  299. next.add(selectedItem);
  300. }
  301. this.setStateAndUpdateParents({
  302. metricAlertPresets: next,
  303. });
  304. }}
  305. />
  306. </Fragment>
  307. )}
  308. </Content>
  309. </Fragment>
  310. );
  311. }
  312. }
  313. export default withOrganization(IssueAlertOptions);
  314. const CheckboxFieldStyles = css`
  315. margin-top: ${space(1)};
  316. `;
  317. const Content = styled('div')`
  318. padding-top: ${space(2)};
  319. padding-bottom: ${space(4)};
  320. `;
  321. const CustomizeAlertsGrid = styled('div')`
  322. display: grid;
  323. grid-template-columns: repeat(5, max-content);
  324. gap: ${space(1)};
  325. align-items: center;
  326. `;
  327. const InlineInput = styled(Input)`
  328. width: 80px;
  329. `;
  330. const InlineSelectControl = styled(SelectControl)`
  331. width: 160px;
  332. `;
  333. const RadioGroupWithPadding = styled(RadioGroup)`
  334. margin-bottom: ${space(2)};
  335. `;
  336. const PageHeadingWithTopMargins = styled(PageHeading)`
  337. margin-top: 65px;
  338. margin-bottom: 0;
  339. padding-bottom: ${space(3)};
  340. border-bottom: 1px solid rgba(0, 0, 0, 0.1);
  341. `;
  342. const RadioItemWrapper = styled('div')`
  343. min-height: 35px;
  344. display: flex;
  345. flex-direction: column;
  346. justify-content: center;
  347. `;
  348. const Subheading = styled('b')`
  349. display: block;
  350. `;