issueAlertOptions.tsx 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347
  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 {t} from 'sentry/locale';
  9. import {space} from 'sentry/styles/space';
  10. import {Organization} from 'sentry/types';
  11. import {
  12. IssueAlertActionType,
  13. IssueAlertConditionType,
  14. IssueAlertRuleAction,
  15. } from 'sentry/types/alerts';
  16. import withOrganization from 'sentry/utils/withOrganization';
  17. export enum MetricValues {
  18. ERRORS,
  19. USERS,
  20. }
  21. export enum RuleAction {
  22. ALERT_ON_EVERY_ISSUE,
  23. CUSTOMIZED_ALERTS,
  24. CREATE_ALERT_LATER,
  25. }
  26. const ISSUE_ALERT_DEFAULT_ACTION: Omit<
  27. IssueAlertRuleAction,
  28. 'label' | 'name' | 'prompt'
  29. > = {
  30. id: IssueAlertActionType.NOTIFY_EMAIL,
  31. targetType: 'IssueOwners',
  32. };
  33. const METRIC_CONDITION_MAP = {
  34. [MetricValues.ERRORS]: IssueAlertConditionType.EVENT_FREQUENCY,
  35. [MetricValues.USERS]: IssueAlertConditionType.EVENT_UNIQUE_USER_FREQUENCY,
  36. } as const;
  37. type StateUpdater = (updatedData: RequestDataFragment) => void;
  38. type Props = DeprecatedAsyncComponent['props'] & {
  39. onChange: StateUpdater;
  40. organization: Organization;
  41. alertSetting?: string;
  42. interval?: string;
  43. metric?: MetricValues;
  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.ALERT_ON_EVERY_ISSUE.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. <CustomizeAlertsGrid
  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. </CustomizeAlertsGrid>,
  163. ];
  164. const options: [string, React.ReactNode][] = [
  165. [RuleAction.ALERT_ON_EVERY_ISSUE.toString(), t('Alert me on every new issue')],
  166. ...(hasProperlyLoadedConditions ? [customizedAlertOption] : []),
  167. [RuleAction.CREATE_ALERT_LATER.toString(), t("I'll create my own alerts later")],
  168. ];
  169. return options.map(([choiceValue, node]) => [
  170. choiceValue,
  171. <RadioItemWrapper key={choiceValue}>{node}</RadioItemWrapper>,
  172. ]);
  173. }
  174. getUpdatedData(): RequestDataFragment {
  175. let defaultRules: boolean;
  176. let shouldCreateCustomRule: boolean;
  177. const alertSetting: RuleAction = parseInt(this.state.alertSetting, 10);
  178. switch (alertSetting) {
  179. case RuleAction.ALERT_ON_EVERY_ISSUE:
  180. defaultRules = true;
  181. shouldCreateCustomRule = false;
  182. break;
  183. case RuleAction.CREATE_ALERT_LATER:
  184. defaultRules = false;
  185. shouldCreateCustomRule = false;
  186. break;
  187. case RuleAction.CUSTOMIZED_ALERTS:
  188. defaultRules = false;
  189. shouldCreateCustomRule = true;
  190. break;
  191. default:
  192. throw new RangeError('Supplied alert creation action is not handled');
  193. }
  194. return {
  195. defaultRules,
  196. shouldCreateCustomRule,
  197. name: 'Send a notification for new issues',
  198. conditions:
  199. this.state.interval.length > 0 && this.state.threshold.length > 0
  200. ? [
  201. getConditionFrom(
  202. this.state.interval,
  203. this.state.metric,
  204. this.state.threshold
  205. ),
  206. ]
  207. : undefined,
  208. actions: [
  209. {
  210. ...ISSUE_ALERT_DEFAULT_ACTION,
  211. ...(this.props.organization.features.includes('issue-alert-fallback-targeting')
  212. ? {fallthroughType: 'ActiveMembers'}
  213. : {}),
  214. },
  215. ],
  216. actionMatch: 'all',
  217. frequency: 5,
  218. };
  219. }
  220. setStateAndUpdateParents<K extends keyof State>(
  221. state:
  222. | ((
  223. prevState: Readonly<State>,
  224. props: Readonly<Props>
  225. ) => Pick<State, K> | State | null)
  226. | Pick<State, K>
  227. | State
  228. | null
  229. ): void {
  230. this.setState(state, () => {
  231. this.props.onChange(this.getUpdatedData());
  232. });
  233. }
  234. getEndpoints(): ReturnType<DeprecatedAsyncComponent['getEndpoints']> {
  235. return [['conditions', `/projects/${this.props.organization.slug}/rule-conditions/`]];
  236. }
  237. onLoadAllEndpointsSuccess(): void {
  238. const conditions = this.state.conditions?.filter?.(object =>
  239. Object.values(METRIC_CONDITION_MAP).includes(object?.id)
  240. );
  241. if (!conditions || conditions.length === 0) {
  242. this.setStateAndUpdateParents({
  243. conditions: undefined,
  244. });
  245. return;
  246. }
  247. const {intervalChoices, interval} = unpackConditions(conditions);
  248. if (!intervalChoices || !interval) {
  249. Sentry.withScope(scope => {
  250. scope.setExtra('props', this.props);
  251. scope.setExtra('state', this.state);
  252. Sentry.captureException(
  253. new Error('Interval choices or sent from API endpoint is inconsistent or empty')
  254. );
  255. });
  256. this.setStateAndUpdateParents({
  257. conditions: undefined,
  258. });
  259. return;
  260. }
  261. const newInterval =
  262. this.props.interval &&
  263. intervalChoices.some(intervalChoice => intervalChoice[0] === this.props.interval)
  264. ? this.props.interval
  265. : interval;
  266. this.setStateAndUpdateParents({
  267. conditions,
  268. intervalChoices,
  269. interval: newInterval,
  270. });
  271. }
  272. renderBody(): React.ReactElement {
  273. const issueAlertOptionsChoices = this.getIssueAlertsChoices(
  274. this.state.conditions?.length > 0
  275. );
  276. return (
  277. <Content>
  278. <RadioGroupWithPadding
  279. choices={issueAlertOptionsChoices}
  280. label={t('Options for creating an alert')}
  281. onChange={alertSetting => this.setStateAndUpdateParents({alertSetting})}
  282. value={this.state.alertSetting}
  283. />
  284. </Content>
  285. );
  286. }
  287. }
  288. export default withOrganization(IssueAlertOptions);
  289. const Content = styled('div')`
  290. padding-top: ${space(2)};
  291. padding-bottom: ${space(4)};
  292. `;
  293. const CustomizeAlertsGrid = styled('div')`
  294. display: grid;
  295. grid-template-columns: repeat(5, max-content);
  296. gap: ${space(1)};
  297. align-items: center;
  298. `;
  299. const InlineInput = styled(Input)`
  300. width: 80px;
  301. `;
  302. const InlineSelectControl = styled(SelectControl)`
  303. width: 160px;
  304. `;
  305. const RadioGroupWithPadding = styled(RadioGroup)`
  306. margin-bottom: ${space(2)};
  307. `;
  308. const RadioItemWrapper = styled('div')`
  309. min-height: 35px;
  310. display: flex;
  311. flex-direction: column;
  312. justify-content: center;
  313. `;