index.tsx 17 KB

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