index.tsx 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580
  1. import {Fragment, PureComponent} from 'react';
  2. import styled from '@emotion/styled';
  3. import * as Sentry from '@sentry/react';
  4. import {addErrorMessage} from 'sentry/actionCreators/indicator';
  5. import {openModal} from 'sentry/actionCreators/modal';
  6. import {Alert} from 'sentry/components/alert';
  7. import {Button, LinkButton} from 'sentry/components/button';
  8. import SelectControl from 'sentry/components/forms/controls/selectControl';
  9. import ListItem from 'sentry/components/list/listItem';
  10. import LoadingIndicator from 'sentry/components/loadingIndicator';
  11. import PanelItem from 'sentry/components/panels/panelItem';
  12. import {IconAdd, IconSettings} from 'sentry/icons';
  13. import {t} from 'sentry/locale';
  14. import {space} from 'sentry/styles/space';
  15. import type {SelectValue} from 'sentry/types/core';
  16. import type {Organization} from 'sentry/types/organization';
  17. import type {Project} from 'sentry/types/project';
  18. import removeAtArrayIndex from 'sentry/utils/array/removeAtArrayIndex';
  19. import replaceAtArrayIndex from 'sentry/utils/array/replaceAtArrayIndex';
  20. import {uniqueId} from 'sentry/utils/guid';
  21. import withOrganization from 'sentry/utils/withOrganization';
  22. import SentryAppRuleModal from 'sentry/views/alerts/rules/issue/sentryAppRuleModal';
  23. import ActionSpecificTargetSelector from 'sentry/views/alerts/rules/metric/triggers/actionsPanel/actionSpecificTargetSelector';
  24. import ActionTargetSelector from 'sentry/views/alerts/rules/metric/triggers/actionsPanel/actionTargetSelector';
  25. import DeleteActionButton from 'sentry/views/alerts/rules/metric/triggers/actionsPanel/deleteActionButton';
  26. import {
  27. type Action,
  28. type ActionType,
  29. AlertRuleComparisonType,
  30. type MetricActionTemplate,
  31. type Trigger,
  32. } from 'sentry/views/alerts/rules/metric/types';
  33. import {
  34. ActionLabel,
  35. DefaultPriorities,
  36. PriorityOptions,
  37. TargetLabel,
  38. } from 'sentry/views/alerts/rules/metric/types';
  39. type Props = {
  40. availableActions: MetricActionTemplate[] | null;
  41. comparisonType: AlertRuleComparisonType;
  42. currentProject: string;
  43. disabled: boolean;
  44. error: boolean;
  45. loading: boolean;
  46. onAdd: (triggerIndex: number, action: Action) => void;
  47. onChange: (triggerIndex: number, triggers: Trigger[], actions: Action[]) => void;
  48. organization: Organization;
  49. projects: Project[];
  50. triggers: Trigger[];
  51. className?: string;
  52. };
  53. /**
  54. * When a new action is added, all of its settings should be set to their default values.
  55. * @param actionConfig
  56. * @param dateCreated kept to maintain order of unsaved actions
  57. */
  58. const getCleanAction = (actionConfig, dateCreated?: string): Action => {
  59. return {
  60. unsavedId: uniqueId(),
  61. unsavedDateCreated: dateCreated ?? new Date().toISOString(),
  62. type: actionConfig.type,
  63. targetType:
  64. actionConfig?.allowedTargetTypes && actionConfig.allowedTargetTypes.length > 0
  65. ? actionConfig.allowedTargetTypes[0]
  66. : null,
  67. targetIdentifier: actionConfig.sentryAppId || '',
  68. inputChannelId: null,
  69. integrationId: actionConfig.integrationId,
  70. sentryAppId: actionConfig.sentryAppId,
  71. options: actionConfig.options || null,
  72. };
  73. };
  74. /**
  75. * Actions have a type (e.g. email, slack, etc), but only some have
  76. * an integrationId (e.g. email is null). This helper creates a unique
  77. * id based on the type and integrationId so that we know what action
  78. * a user's saved action corresponds to.
  79. */
  80. const getActionUniqueKey = ({
  81. type,
  82. integrationId,
  83. sentryAppId,
  84. }: Pick<Action, 'type' | 'integrationId' | 'sentryAppId'>) => {
  85. if (integrationId) {
  86. return `${type}-${integrationId}`;
  87. }
  88. if (sentryAppId) {
  89. return `${type}-${sentryAppId}`;
  90. }
  91. return type;
  92. };
  93. /**
  94. * Creates a human-friendly display name for the integration based on type and
  95. * server provided `integrationName`
  96. *
  97. * e.g. for slack we show that it is slack and the `integrationName` is the workspace name
  98. */
  99. const getFullActionTitle = ({
  100. type,
  101. integrationName,
  102. sentryAppName,
  103. status,
  104. }: Pick<
  105. MetricActionTemplate,
  106. 'type' | 'integrationName' | 'sentryAppName' | 'status'
  107. >) => {
  108. if (sentryAppName) {
  109. if (status && status !== 'published') {
  110. return `${sentryAppName} (${status})`;
  111. }
  112. return `${sentryAppName}`;
  113. }
  114. const label = ActionLabel[type];
  115. if (integrationName) {
  116. return `${label} - ${integrationName}`;
  117. }
  118. return label;
  119. };
  120. /**
  121. * Lists saved actions as well as control to add a new action
  122. */
  123. class ActionsPanel extends PureComponent<Props> {
  124. handleChangeKey(
  125. triggerIndex: number,
  126. index: number,
  127. key: 'targetIdentifier' | 'inputChannelId',
  128. value: string
  129. ) {
  130. const {triggers, onChange} = this.props;
  131. const {actions} = triggers[triggerIndex];
  132. const newAction = {
  133. ...actions[index],
  134. [key]: value,
  135. };
  136. onChange(triggerIndex, triggers, replaceAtArrayIndex(actions, index, newAction));
  137. }
  138. conditionallyRenderHelpfulBanner(triggerIndex: number, index: number) {
  139. const {triggers} = this.props;
  140. const {actions} = triggers[triggerIndex];
  141. const newAction = {...actions[index]};
  142. if (newAction.type === 'slack') {
  143. return (
  144. <MarginlessAlert
  145. type="info"
  146. showIcon
  147. trailingItems={
  148. <LinkButton
  149. href="https://docs.sentry.io/product/integrations/notification-incidents/slack/#rate-limiting-error"
  150. external
  151. size="xs"
  152. >
  153. {t('Learn More')}
  154. </LinkButton>
  155. }
  156. >
  157. {t('Having rate limiting problems? Enter a channel or user ID.')}
  158. </MarginlessAlert>
  159. );
  160. }
  161. if (newAction.type === 'discord') {
  162. return (
  163. <MarginlessAlert
  164. type="info"
  165. showIcon
  166. trailingItems={
  167. <LinkButton
  168. href="https://docs.sentry.io/product/accounts/early-adopter-features/discord/#issue-alerts"
  169. external
  170. size="xs"
  171. >
  172. {t('Learn More')}
  173. </LinkButton>
  174. }
  175. >
  176. {t('Note that you must enter a Discord channel ID, not a channel name.')}
  177. </MarginlessAlert>
  178. );
  179. }
  180. return null;
  181. }
  182. handleAddAction = () => {
  183. const {availableActions, onAdd} = this.props;
  184. const actionConfig = availableActions?.[0];
  185. if (!actionConfig) {
  186. addErrorMessage(t('There was a problem adding an action'));
  187. Sentry.captureException(new Error('Unable to add an action'));
  188. return;
  189. }
  190. const action: Action = getCleanAction(actionConfig);
  191. // Add new actions to critical by default
  192. const triggerIndex = 0;
  193. onAdd(triggerIndex, action);
  194. };
  195. handleDeleteAction = (triggerIndex: number, index: number) => {
  196. const {triggers, onChange} = this.props;
  197. const {actions} = triggers[triggerIndex];
  198. onChange(triggerIndex, triggers, removeAtArrayIndex(actions, index));
  199. };
  200. handleChangeActionLevel = (
  201. triggerIndex: number,
  202. index: number,
  203. value: SelectValue<number>
  204. ) => {
  205. const {triggers, onChange} = this.props;
  206. // Convert saved action to unsaved by removing id
  207. const {id: _, ...action} = triggers[triggerIndex].actions[index];
  208. action.unsavedId = uniqueId();
  209. triggers[value.value].actions.push(action);
  210. onChange(value.value, triggers, triggers[value.value].actions);
  211. this.handleDeleteAction(triggerIndex, index);
  212. };
  213. handleChangeActionType = (
  214. triggerIndex: number,
  215. index: number,
  216. value: SelectValue<ActionType>
  217. ) => {
  218. const {triggers, onChange, availableActions} = this.props;
  219. const {actions} = triggers[triggerIndex];
  220. const actionConfig = availableActions?.find(
  221. availableAction => getActionUniqueKey(availableAction) === value.value
  222. );
  223. if (!actionConfig) {
  224. addErrorMessage(t('There was a problem changing an action'));
  225. Sentry.captureException(new Error('Unable to change an action type'));
  226. return;
  227. }
  228. const existingDateCreated =
  229. actions[index].dateCreated ?? actions[index].unsavedDateCreated;
  230. const newAction: Action = getCleanAction(actionConfig, existingDateCreated);
  231. onChange(triggerIndex, triggers, replaceAtArrayIndex(actions, index, newAction));
  232. };
  233. handleChangeTarget = (
  234. triggerIndex: number,
  235. index: number,
  236. value: SelectValue<keyof typeof TargetLabel>
  237. ) => {
  238. const {triggers, onChange} = this.props;
  239. const {actions} = triggers[triggerIndex];
  240. const newAction = {
  241. ...actions[index],
  242. targetType: value.value,
  243. targetIdentifier: '',
  244. };
  245. onChange(triggerIndex, triggers, replaceAtArrayIndex(actions, index, newAction));
  246. };
  247. handleChangePriority = (
  248. triggerIndex: number,
  249. index: number,
  250. value: SelectValue<keyof typeof PriorityOptions>
  251. ) => {
  252. const {triggers, onChange} = this.props;
  253. const {actions} = triggers[triggerIndex];
  254. const newAction = {
  255. ...actions[index],
  256. priority: value.value,
  257. };
  258. onChange(triggerIndex, triggers, replaceAtArrayIndex(actions, index, newAction));
  259. };
  260. /**
  261. * Update the Trigger's Action fields from the SentryAppRuleModal together
  262. * only after the user clicks "Save Changes".
  263. * @param formData Form data
  264. */
  265. updateParentFromSentryAppRule = (
  266. triggerIndex: number,
  267. actionIndex: number,
  268. formData: {[key: string]: string}
  269. ): void => {
  270. const {triggers, onChange} = this.props;
  271. const {actions} = triggers[triggerIndex];
  272. const newAction = {
  273. ...actions[actionIndex],
  274. ...formData,
  275. };
  276. onChange(
  277. triggerIndex,
  278. triggers,
  279. replaceAtArrayIndex(actions, actionIndex, newAction)
  280. );
  281. };
  282. render() {
  283. const {
  284. availableActions,
  285. currentProject,
  286. disabled,
  287. loading,
  288. organization,
  289. projects,
  290. triggers,
  291. comparisonType,
  292. } = this.props;
  293. const project = projects.find(({slug}) => slug === currentProject);
  294. const items = availableActions?.map(availableAction => ({
  295. value: getActionUniqueKey(availableAction),
  296. label: getFullActionTitle(availableAction),
  297. }));
  298. const hasPriorityFlag = organization.features.includes(
  299. 'integrations-custom-alert-priorities'
  300. );
  301. const levels = [
  302. {value: 0, label: 'Critical Status'},
  303. {value: 1, label: 'Warning Status'},
  304. ];
  305. // NOTE: we don't support warning triggers for anomaly detection alerts yet
  306. // once we do, this can be deleted
  307. const anomalyDetectionLevels = [{value: 0, label: 'Critical Status'}];
  308. // Create single array of unsaved and saved trigger actions
  309. // Sorted by date created ascending
  310. const actions = triggers
  311. .flatMap((trigger, triggerIndex) => {
  312. return trigger.actions.map((action, actionIdx) => {
  313. const availableAction = availableActions?.find(
  314. a => getActionUniqueKey(a) === getActionUniqueKey(action)
  315. );
  316. return {
  317. dateCreated: new Date(
  318. action.dateCreated ?? action.unsavedDateCreated
  319. ).getTime(),
  320. triggerIndex,
  321. action,
  322. actionIdx,
  323. availableAction,
  324. };
  325. });
  326. })
  327. .sort((a, b) => a.dateCreated - b.dateCreated);
  328. return (
  329. <Fragment>
  330. <PerformActionsListItem>{t('Set actions')}</PerformActionsListItem>
  331. {loading && <LoadingIndicator />}
  332. {actions.map(({action, actionIdx, triggerIndex, availableAction}) => {
  333. const actionDisabled =
  334. triggers[triggerIndex].actions[actionIdx]?.disabled || disabled;
  335. return (
  336. <div key={action.id ?? action.unsavedId}>
  337. <RuleRowContainer>
  338. <PanelItemGrid>
  339. <PanelItemSelects>
  340. <SelectControl
  341. name="select-level"
  342. aria-label={t('Select a status level')}
  343. isDisabled={disabled || loading}
  344. placeholder={t('Select Level')}
  345. onChange={this.handleChangeActionLevel.bind(
  346. this,
  347. triggerIndex,
  348. actionIdx
  349. )}
  350. value={triggerIndex}
  351. options={
  352. comparisonType === AlertRuleComparisonType.DYNAMIC
  353. ? anomalyDetectionLevels
  354. : levels
  355. }
  356. />
  357. <SelectControl
  358. name="select-action"
  359. aria-label={t('Select an Action')}
  360. isDisabled={disabled || loading}
  361. placeholder={t('Select Action')}
  362. onChange={this.handleChangeActionType.bind(
  363. this,
  364. triggerIndex,
  365. actionIdx
  366. )}
  367. value={getActionUniqueKey(action)}
  368. options={items ?? []}
  369. />
  370. {availableAction && availableAction.allowedTargetTypes.length > 1 ? (
  371. <SelectControl
  372. isDisabled={disabled || loading}
  373. value={action.targetType}
  374. options={availableAction?.allowedTargetTypes?.map(
  375. allowedType => ({
  376. value: allowedType,
  377. label: TargetLabel[allowedType],
  378. })
  379. )}
  380. onChange={this.handleChangeTarget.bind(
  381. this,
  382. triggerIndex,
  383. actionIdx
  384. )}
  385. />
  386. ) : availableAction &&
  387. availableAction.type === 'sentry_app' &&
  388. availableAction.settings ? (
  389. <Button
  390. icon={<IconSettings />}
  391. disabled={actionDisabled}
  392. onClick={() => {
  393. openModal(
  394. deps => (
  395. <SentryAppRuleModal
  396. {...deps}
  397. // Using ! for keys that will exist for sentryapps
  398. sentryAppInstallationUuid={
  399. availableAction.sentryAppInstallationUuid!
  400. }
  401. config={availableAction.settings!}
  402. appName={availableAction.sentryAppName!}
  403. onSubmitSuccess={this.updateParentFromSentryAppRule.bind(
  404. this,
  405. triggerIndex,
  406. actionIdx
  407. )}
  408. resetValues={
  409. triggers[triggerIndex].actions[actionIdx] || {}
  410. }
  411. />
  412. ),
  413. {closeEvents: 'escape-key'}
  414. );
  415. }}
  416. >
  417. {t('Settings')}
  418. </Button>
  419. ) : null}
  420. <ActionTargetSelector
  421. action={action}
  422. availableAction={availableAction}
  423. disabled={disabled}
  424. loading={loading}
  425. onChange={this.handleChangeKey.bind(
  426. this,
  427. triggerIndex,
  428. actionIdx,
  429. 'targetIdentifier'
  430. )}
  431. organization={organization}
  432. project={project}
  433. />
  434. <ActionSpecificTargetSelector
  435. action={action}
  436. disabled={disabled}
  437. onChange={this.handleChangeKey.bind(
  438. this,
  439. triggerIndex,
  440. actionIdx,
  441. 'inputChannelId'
  442. )}
  443. />
  444. {hasPriorityFlag &&
  445. availableAction &&
  446. (availableAction.type === 'opsgenie' ||
  447. availableAction.type === 'pagerduty') ? (
  448. <SelectControl
  449. isDisabled={disabled || loading}
  450. value={action.priority}
  451. placeholder={
  452. DefaultPriorities[availableAction.type][triggerIndex]
  453. }
  454. options={PriorityOptions[availableAction.type].map(priority => ({
  455. value: priority,
  456. label: priority,
  457. }))}
  458. onChange={this.handleChangePriority.bind(
  459. this,
  460. triggerIndex,
  461. actionIdx
  462. )}
  463. />
  464. ) : null}
  465. </PanelItemSelects>
  466. <DeleteActionButton
  467. triggerIndex={triggerIndex}
  468. index={actionIdx}
  469. onClick={this.handleDeleteAction}
  470. disabled={disabled}
  471. />
  472. </PanelItemGrid>
  473. </RuleRowContainer>
  474. {this.conditionallyRenderHelpfulBanner(triggerIndex, actionIdx)}
  475. </div>
  476. );
  477. })}
  478. <ActionSection>
  479. <Button
  480. disabled={disabled || loading}
  481. icon={<IconAdd isCircled color="gray300" />}
  482. onClick={this.handleAddAction}
  483. >
  484. {t('Add Action')}
  485. </Button>
  486. </ActionSection>
  487. </Fragment>
  488. );
  489. }
  490. }
  491. const ActionsPanelWithSpace = styled(ActionsPanel)`
  492. margin-top: ${space(4)};
  493. `;
  494. const ActionSection = styled('div')`
  495. margin-top: ${space(1)};
  496. margin-bottom: ${space(3)};
  497. `;
  498. const PanelItemGrid = styled(PanelItem)`
  499. display: flex;
  500. align-items: center;
  501. border-bottom: 0;
  502. padding: ${space(1)};
  503. `;
  504. const PanelItemSelects = styled('div')`
  505. display: flex;
  506. width: 100%;
  507. margin-right: ${space(1)};
  508. > * {
  509. flex: 0 1 200px;
  510. &:not(:last-child) {
  511. margin-right: ${space(1)};
  512. }
  513. }
  514. `;
  515. const RuleRowContainer = styled('div')`
  516. background-color: ${p => p.theme.backgroundSecondary};
  517. border: 1px ${p => p.theme.border} solid;
  518. border-radius: ${p => p.theme.borderRadius} ${p => p.theme.borderRadius} 0 0;
  519. &:last-child {
  520. border-radius: ${p => p.theme.borderRadius};
  521. }
  522. `;
  523. const StyledListItem = styled(ListItem)`
  524. margin: ${space(2)} 0 ${space(3)} 0;
  525. font-size: ${p => p.theme.fontSizeExtraLarge};
  526. `;
  527. const PerformActionsListItem = styled(StyledListItem)`
  528. margin-bottom: 0;
  529. line-height: 1.3;
  530. `;
  531. const MarginlessAlert = styled(Alert)`
  532. border-radius: 0 0 ${p => p.theme.borderRadius} ${p => p.theme.borderRadius};
  533. border: 1px ${p => p.theme.border} solid;
  534. border-top-width: 0;
  535. margin: 0;
  536. padding: ${space(1)} ${space(1)};
  537. font-size: ${p => p.theme.fontSizeSmall};
  538. `;
  539. export default withOrganization(ActionsPanelWithSpace);