index.tsx 17 KB

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