issueAlertOptions.tsx 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356
  1. import styled from '@emotion/styled';
  2. import * as Sentry from '@sentry/react';
  3. import isEqual from 'lodash/isEqual';
  4. import DeprecatedAsyncComponent from 'sentry/components/deprecatedAsyncComponent';
  5. import RadioGroup from 'sentry/components/forms/controls/radioGroup';
  6. import SelectControl from 'sentry/components/forms/controls/selectControl';
  7. import Input from 'sentry/components/input';
  8. import {SupportedLanguages} from 'sentry/components/onboarding/frameworkSuggestionModal';
  9. import {t} from 'sentry/locale';
  10. import {space} from 'sentry/styles/space';
  11. import type {IssueAlertRuleAction} from 'sentry/types/alerts';
  12. import {IssueAlertActionType, IssueAlertConditionType} from 'sentry/types/alerts';
  13. import type {Organization} from 'sentry/types/organization';
  14. import withOrganization from 'sentry/utils/withOrganization';
  15. export enum MetricValues {
  16. ERRORS = 0,
  17. USERS = 1,
  18. }
  19. export enum RuleAction {
  20. DEFAULT_ALERT = 0,
  21. CUSTOMIZED_ALERTS = 1,
  22. CREATE_ALERT_LATER = 2,
  23. }
  24. const ISSUE_ALERT_DEFAULT_ACTION: Omit<
  25. IssueAlertRuleAction,
  26. 'label' | 'name' | 'prompt'
  27. > = {
  28. id: IssueAlertActionType.NOTIFY_EMAIL,
  29. targetType: 'IssueOwners',
  30. fallthroughType: 'ActiveMembers',
  31. };
  32. const METRIC_CONDITION_MAP = {
  33. [MetricValues.ERRORS]: IssueAlertConditionType.EVENT_FREQUENCY,
  34. [MetricValues.USERS]: IssueAlertConditionType.EVENT_UNIQUE_USER_FREQUENCY,
  35. } as const;
  36. type StateUpdater = (updatedData: RequestDataFragment) => void;
  37. type Props = DeprecatedAsyncComponent['props'] & {
  38. onChange: StateUpdater;
  39. organization: Organization;
  40. alertSetting?: string;
  41. interval?: string;
  42. metric?: MetricValues;
  43. platformLanguage?: SupportedLanguages;
  44. threshold?: string;
  45. };
  46. type State = DeprecatedAsyncComponent['state'] & {
  47. alertSetting: string;
  48. // TODO(ts): When we have alert conditional types, convert this
  49. conditions: any;
  50. interval: string;
  51. intervalChoices: [string, string][] | undefined;
  52. metric: MetricValues;
  53. threshold: string;
  54. };
  55. type RequestDataFragment = {
  56. actionMatch: string;
  57. actions: Omit<IssueAlertRuleAction, 'label' | 'name' | 'prompt'>[];
  58. conditions: {id: string; interval: string; value: string}[] | undefined;
  59. defaultRules: boolean;
  60. frequency: number;
  61. name: string;
  62. shouldCreateCustomRule: boolean;
  63. };
  64. function getConditionFrom(
  65. interval: string,
  66. metricValue: MetricValues,
  67. threshold: string
  68. ): {id: string; interval: string; value: string} {
  69. let condition: string;
  70. switch (metricValue) {
  71. case MetricValues.ERRORS:
  72. condition = IssueAlertConditionType.EVENT_FREQUENCY;
  73. break;
  74. case MetricValues.USERS:
  75. condition = IssueAlertConditionType.EVENT_UNIQUE_USER_FREQUENCY;
  76. break;
  77. default:
  78. throw new RangeError('Supplied metric value is not handled');
  79. }
  80. return {
  81. interval,
  82. id: condition,
  83. value: threshold,
  84. };
  85. }
  86. function unpackConditions(conditions: any[]) {
  87. const equalityReducer = (acc, curr) => {
  88. if (!acc || !curr || !isEqual(acc, curr)) {
  89. return null;
  90. }
  91. return acc;
  92. };
  93. const intervalChoices = conditions
  94. .map(condition => condition.formFields?.interval?.choices)
  95. .reduce(equalityReducer);
  96. return {intervalChoices, interval: intervalChoices?.[0]?.[0]};
  97. }
  98. class IssueAlertOptions extends DeprecatedAsyncComponent<Props, State> {
  99. getDefaultState(): State {
  100. return {
  101. ...super.getDefaultState(),
  102. conditions: [],
  103. intervalChoices: [],
  104. alertSetting: this.props.alertSetting ?? RuleAction.DEFAULT_ALERT.toString(),
  105. metric: this.props.metric ?? MetricValues.ERRORS,
  106. interval: this.props.interval ?? '',
  107. threshold: this.props.threshold ?? '10',
  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 customizedAlertOption: [string, React.ReactNode] = [
  124. RuleAction.CUSTOMIZED_ALERTS.toString(),
  125. <CustomizeAlert
  126. key={RuleAction.CUSTOMIZED_ALERTS}
  127. onClick={e => {
  128. // XXX(epurkhiser): The `e.preventDefault` here is needed to stop
  129. // propagation of the click up to the label, causing it to focus
  130. // the radio input and lose focus on the select.
  131. e.preventDefault();
  132. const alertSetting = RuleAction.CUSTOMIZED_ALERTS.toString();
  133. this.setStateAndUpdateParents({alertSetting});
  134. }}
  135. >
  136. {t('When there are more than')}
  137. <InlineInput
  138. type="number"
  139. min="0"
  140. name=""
  141. placeholder="10"
  142. value={this.state.threshold}
  143. onChange={threshold =>
  144. this.setStateAndUpdateParents({threshold: threshold.target.value})
  145. }
  146. data-test-id="range-input"
  147. />
  148. <InlineSelectControl
  149. value={this.state.metric}
  150. options={this.getAvailableMetricOptions()}
  151. onChange={metric => this.setStateAndUpdateParents({metric: metric.value})}
  152. />
  153. {t('a unique error in')}
  154. <InlineSelectControl
  155. value={this.state.interval}
  156. options={this.state.intervalChoices?.map(([value, label]) => ({
  157. value,
  158. label,
  159. }))}
  160. onChange={interval => this.setStateAndUpdateParents({interval: interval.value})}
  161. />
  162. </CustomizeAlert>,
  163. ];
  164. const default_label = this.shouldUseNewDefaultSetting()
  165. ? t('Alert me on high priority issues')
  166. : t('Alert me on every new issue');
  167. const options: [string, React.ReactNode][] = [
  168. [RuleAction.DEFAULT_ALERT.toString(), default_label],
  169. ...(hasProperlyLoadedConditions ? [customizedAlertOption] : []),
  170. [RuleAction.CREATE_ALERT_LATER.toString(), t("I'll create my own alerts later")],
  171. ];
  172. return options.map(([choiceValue, node]) => [
  173. choiceValue,
  174. <RadioItemWrapper key={choiceValue}>{node}</RadioItemWrapper>,
  175. ]);
  176. }
  177. shouldUseNewDefaultSetting(): boolean {
  178. if (this.props.organization.features.includes('seer-based-priority')) {
  179. return true;
  180. }
  181. return (
  182. this.props.organization.features.includes('default-high-priority-alerts') &&
  183. (this.props.platformLanguage === SupportedLanguages.PYTHON ||
  184. this.props.platformLanguage === SupportedLanguages.JAVASCRIPT)
  185. );
  186. }
  187. getUpdatedData(): RequestDataFragment {
  188. let defaultRules: boolean;
  189. let shouldCreateCustomRule: boolean;
  190. const alertSetting: RuleAction = parseInt(this.state.alertSetting, 10);
  191. switch (alertSetting) {
  192. case RuleAction.DEFAULT_ALERT:
  193. defaultRules = true;
  194. shouldCreateCustomRule = false;
  195. break;
  196. case RuleAction.CREATE_ALERT_LATER:
  197. defaultRules = false;
  198. shouldCreateCustomRule = false;
  199. break;
  200. case RuleAction.CUSTOMIZED_ALERTS:
  201. defaultRules = false;
  202. shouldCreateCustomRule = true;
  203. break;
  204. default:
  205. throw new RangeError('Supplied alert creation action is not handled');
  206. }
  207. return {
  208. defaultRules,
  209. shouldCreateCustomRule,
  210. name: 'Send a notification for new issues',
  211. conditions:
  212. this.state.interval.length > 0 && this.state.threshold.length > 0
  213. ? [
  214. getConditionFrom(
  215. this.state.interval,
  216. this.state.metric,
  217. this.state.threshold
  218. ),
  219. ]
  220. : undefined,
  221. actions: [ISSUE_ALERT_DEFAULT_ACTION],
  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. <Content>
  284. <RadioGroupWithPadding
  285. choices={issueAlertOptionsChoices}
  286. label={t('Options for creating an alert')}
  287. onChange={alertSetting => this.setStateAndUpdateParents({alertSetting})}
  288. value={this.state.alertSetting}
  289. />
  290. </Content>
  291. );
  292. }
  293. }
  294. export default withOrganization(IssueAlertOptions);
  295. const Content = styled('div')`
  296. padding-top: ${space(2)};
  297. padding-bottom: ${space(4)};
  298. `;
  299. const CustomizeAlert = styled('div')`
  300. display: flex;
  301. gap: ${space(1)};
  302. flex-wrap: wrap;
  303. align-items: center;
  304. `;
  305. const InlineInput = styled(Input)`
  306. width: 80px;
  307. `;
  308. const InlineSelectControl = styled(SelectControl)`
  309. width: 160px;
  310. `;
  311. const RadioGroupWithPadding = styled(RadioGroup)`
  312. margin-bottom: ${space(2)};
  313. `;
  314. const RadioItemWrapper = styled('div')`
  315. min-height: 35px;
  316. display: flex;
  317. flex-direction: column;
  318. justify-content: center;
  319. `;