index.tsx 17 KB

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