issueAlertOptions.tsx 9.7 KB

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