issueAlertOptions.tsx 11 KB

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