ruleNodeList.tsx 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340
  1. import type React from 'react';
  2. import {Component, Fragment, type ReactNode} from 'react';
  3. import styled from '@emotion/styled';
  4. import SelectControl from 'sentry/components/forms/controls/selectControl';
  5. import {t} from 'sentry/locale';
  6. import {space} from 'sentry/styles/space';
  7. import type {
  8. IssueAlertConfiguration,
  9. IssueAlertGenericConditionConfig,
  10. IssueAlertRuleAction,
  11. IssueAlertRuleActionTemplate,
  12. IssueAlertRuleCondition,
  13. IssueAlertRuleConditionTemplate,
  14. } from 'sentry/types/alerts';
  15. import {IssueAlertActionType, IssueAlertConditionType} from 'sentry/types/alerts';
  16. import type {Organization} from 'sentry/types/organization';
  17. import type {Project} from 'sentry/types/project';
  18. import {
  19. CHANGE_ALERT_CONDITION_IDS,
  20. COMPARISON_INTERVAL_CHOICES,
  21. COMPARISON_TYPE_CHOICE_VALUES,
  22. COMPARISON_TYPE_CHOICES,
  23. } from 'sentry/views/alerts/utils/constants';
  24. import {AlertRuleComparisonType} from '../metric/types';
  25. import RuleNode from './ruleNode';
  26. type Props = {
  27. disabled: boolean;
  28. error: React.ReactNode;
  29. /**
  30. * actions/conditions that have been added to the rule
  31. */
  32. items: IssueAlertRuleAction[] | IssueAlertRuleCondition[];
  33. /**
  34. * All available actions or conditions
  35. */
  36. nodes: IssueAlertConfiguration[keyof IssueAlertConfiguration] | null;
  37. onAddRow: (
  38. value: IssueAlertRuleActionTemplate | IssueAlertRuleConditionTemplate
  39. ) => void;
  40. onDeleteRow: (ruleIndex: number) => void;
  41. onPropertyChange: (ruleIndex: number, prop: string, val: string) => void;
  42. onResetRow: (ruleIndex: number, name: string, value: string) => void;
  43. organization: Organization;
  44. /**
  45. * Placeholder for select control
  46. */
  47. placeholder: string;
  48. project: Project;
  49. additionalAction?: {
  50. label: ReactNode;
  51. onClick: () => void;
  52. option: {
  53. label: ReactNode;
  54. value: IssueAlertRuleActionTemplate;
  55. };
  56. };
  57. incompatibleBanner?: number | null;
  58. incompatibleRules?: number[] | null;
  59. selectType?: 'grouped';
  60. };
  61. const createSelectOptions = (
  62. actions: IssueAlertRuleActionTemplate[]
  63. ): Array<{
  64. label: React.ReactNode;
  65. value: IssueAlertRuleActionTemplate;
  66. }> => {
  67. return actions.map(node => {
  68. if (node.id === IssueAlertActionType.NOTIFY_EMAIL) {
  69. const label = t('Suggested Assignees, Team, or Member');
  70. return {
  71. value: node,
  72. label,
  73. };
  74. }
  75. if (node.id === IssueAlertConditionType.REAPPEARED_EVENT) {
  76. const label = t('The issue changes state from archived to escalating');
  77. return {
  78. value: node,
  79. label,
  80. };
  81. }
  82. return {
  83. value: node,
  84. label: node.prompt ?? node.label,
  85. };
  86. });
  87. };
  88. const groupLabels = {
  89. notify: t('Send notification to\u{2026}'),
  90. notifyIntegration: t('Notify integration\u{2026}'),
  91. ticket: t('Create new\u{2026}'),
  92. change: t('Issue state change'),
  93. frequency: t('Issue frequency'),
  94. };
  95. /**
  96. * Group options by category
  97. */
  98. const groupSelectOptions = (actions: IssueAlertRuleActionTemplate[]) => {
  99. const grouped = actions.reduce<
  100. Record<
  101. keyof typeof groupLabels,
  102. IssueAlertRuleActionTemplate[] | IssueAlertRuleConditionTemplate[]
  103. >
  104. >(
  105. (acc, curr) => {
  106. if (curr.actionType === 'ticket') {
  107. acc.ticket.push(curr);
  108. } else if (curr.id.includes('event_frequency')) {
  109. acc.frequency.push(curr);
  110. } else if (
  111. curr.id.includes('sentry.rules.conditions') &&
  112. !curr.id.includes('event_frequency')
  113. ) {
  114. acc.change.push(curr);
  115. } else if (curr.id.includes('sentry.integrations')) {
  116. acc.notifyIntegration.push(curr);
  117. } else if (curr.id.includes('notify_event')) {
  118. acc.notifyIntegration.push(curr);
  119. } else {
  120. acc.notify.push(curr);
  121. }
  122. return acc;
  123. },
  124. {
  125. notify: [],
  126. notifyIntegration: [],
  127. ticket: [],
  128. change: [],
  129. frequency: [],
  130. }
  131. );
  132. return Object.entries(grouped)
  133. .filter(([_, values]) => values.length)
  134. .map(([key, values]) => {
  135. return {
  136. // @ts-expect-error TS(7053): Element implicitly has an 'any' type because expre... Remove this comment to see the full error message
  137. label: groupLabels[key],
  138. options: createSelectOptions(values),
  139. };
  140. });
  141. };
  142. class RuleNodeList extends Component<Props> {
  143. componentWillUnmount() {
  144. window.clearTimeout(this.propertyChangeTimeout);
  145. }
  146. propertyChangeTimeout: number | undefined = undefined;
  147. getNode = (
  148. template: IssueAlertRuleAction | IssueAlertRuleCondition,
  149. itemIdx: number
  150. ): IssueAlertConfiguration[keyof IssueAlertConfiguration][number] | null => {
  151. const {nodes, items, organization, onPropertyChange} = this.props;
  152. const node = nodes?.find((n: any) => {
  153. if ('sentryAppInstallationUuid' in n) {
  154. // Match more than just the id for sentryApp actions, they share the same id
  155. return (
  156. n.id === template.id &&
  157. n.sentryAppInstallationUuid === template.sentryAppInstallationUuid
  158. );
  159. }
  160. return n.id === template.id;
  161. });
  162. if (!node) {
  163. return null;
  164. }
  165. if (
  166. !organization.features.includes('change-alerts') ||
  167. !CHANGE_ALERT_CONDITION_IDS.includes(node.id)
  168. ) {
  169. return node;
  170. }
  171. const item = items[itemIdx]!;
  172. let changeAlertNode: IssueAlertGenericConditionConfig = {
  173. ...(node as IssueAlertGenericConditionConfig),
  174. label: node.label.replace('...', ' {comparisonType}'),
  175. formFields: {
  176. ...(node.formFields as IssueAlertGenericConditionConfig['formFields']),
  177. comparisonType: {
  178. type: 'choice',
  179. choices: COMPARISON_TYPE_CHOICES,
  180. // give an initial value from not among choices so selector starts with none selected
  181. initial: 'select',
  182. },
  183. },
  184. };
  185. // item.comparison type isn't backfilled and is missing for old alert rules
  186. // this is a problem when an old alert is being edited, need to initialize it
  187. if (!item.comparisonType && item.value && item.name) {
  188. item.comparisonType = item.comparisonInterval === undefined ? 'count' : 'percent';
  189. }
  190. if (item.comparisonType) {
  191. changeAlertNode = {
  192. ...changeAlertNode,
  193. label: changeAlertNode.label.replace(
  194. '{comparisonType}',
  195. // @ts-expect-error TS(7053): Element implicitly has an 'any' type because expre... Remove this comment to see the full error message
  196. COMPARISON_TYPE_CHOICE_VALUES[item.comparisonType]
  197. ),
  198. };
  199. if (item.comparisonType === AlertRuleComparisonType.PERCENT) {
  200. if (!item.comparisonInterval) {
  201. // comparisonInterval value in IssueRuleEditor state
  202. // is undefined even if initial value is defined
  203. // can't directly call onPropertyChange, because
  204. // getNode is called during render
  205. window.clearTimeout(this.propertyChangeTimeout);
  206. this.propertyChangeTimeout = window.setTimeout(() =>
  207. onPropertyChange(itemIdx, 'comparisonInterval', '1w')
  208. );
  209. }
  210. changeAlertNode = {
  211. ...changeAlertNode,
  212. formFields: {
  213. ...changeAlertNode.formFields,
  214. comparisonInterval: {
  215. type: 'choice',
  216. choices: COMPARISON_INTERVAL_CHOICES,
  217. initial: '1w',
  218. },
  219. },
  220. };
  221. }
  222. }
  223. return changeAlertNode;
  224. };
  225. render() {
  226. const {
  227. onAddRow,
  228. onResetRow,
  229. onDeleteRow,
  230. onPropertyChange,
  231. additionalAction,
  232. nodes,
  233. placeholder,
  234. items,
  235. organization,
  236. project,
  237. disabled,
  238. error,
  239. selectType,
  240. incompatibleRules,
  241. incompatibleBanner,
  242. } = this.props;
  243. const enabledNodes = nodes ? nodes.filter(({enabled}: any) => enabled) : [];
  244. let options: any[];
  245. if (selectType === 'grouped') {
  246. options = groupSelectOptions(enabledNodes);
  247. if (additionalAction) {
  248. const optionToModify = options.find(
  249. option => option.label === additionalAction.label
  250. );
  251. if (optionToModify) {
  252. optionToModify.options.push(additionalAction.option);
  253. }
  254. }
  255. } else {
  256. options = createSelectOptions(enabledNodes);
  257. }
  258. return (
  259. <Fragment>
  260. <RuleNodes>
  261. {error}
  262. {items.map(
  263. (item: IssueAlertRuleAction | IssueAlertRuleCondition, idx: number) => (
  264. <RuleNode
  265. key={idx}
  266. index={idx}
  267. node={this.getNode(item, idx)}
  268. onDelete={onDeleteRow}
  269. onPropertyChange={onPropertyChange}
  270. onReset={onResetRow}
  271. data={item}
  272. organization={organization}
  273. project={project}
  274. disabled={disabled}
  275. incompatibleRule={incompatibleRules?.includes(idx)}
  276. incompatibleBanner={incompatibleBanner === idx}
  277. />
  278. )
  279. )}
  280. </RuleNodes>
  281. <StyledSelectControl
  282. placeholder={placeholder}
  283. value={null}
  284. onChange={(obj: any) => {
  285. if (additionalAction && obj === additionalAction.option) {
  286. additionalAction.onClick();
  287. } else {
  288. onAddRow(obj.value);
  289. }
  290. }}
  291. options={options}
  292. disabled={disabled}
  293. />
  294. </Fragment>
  295. );
  296. }
  297. }
  298. export default RuleNodeList;
  299. const StyledSelectControl = styled(SelectControl)`
  300. width: 100%;
  301. `;
  302. const RuleNodes = styled('div')`
  303. display: grid;
  304. margin-bottom: ${space(1)};
  305. gap: ${space(1)};
  306. @media (max-width: ${p => p.theme.breakpoints.medium}) {
  307. grid-auto-flow: row;
  308. }
  309. `;