issueAlertOptions.tsx 10 KB

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