index.tsx 18 KB

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