issueAlertOptions.tsx 11 KB

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