index.tsx 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508
  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. 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 null;
  138. }
  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. size="xs"
  147. >
  148. {t('Learn More')}
  149. </Button>
  150. }
  151. >
  152. {t('Having rate limiting problems? Enter a channel or user ID.')}
  153. </MarginlessAlert>
  154. );
  155. }
  156. handleAddAction = () => {
  157. const {availableActions, onAdd} = this.props;
  158. const actionConfig = availableActions?.[0];
  159. if (!actionConfig) {
  160. addErrorMessage(t('There was a problem adding an action'));
  161. Sentry.captureException(new Error('Unable to add an action'));
  162. return;
  163. }
  164. const action: Action = getCleanAction(actionConfig);
  165. // Add new actions to critical by default
  166. const triggerIndex = 0;
  167. onAdd(triggerIndex, action);
  168. };
  169. handleDeleteAction = (triggerIndex: number, index: number) => {
  170. const {triggers, onChange} = this.props;
  171. const {actions} = triggers[triggerIndex];
  172. onChange(triggerIndex, triggers, removeAtArrayIndex(actions, index));
  173. };
  174. handleChangeActionLevel = (
  175. triggerIndex: number,
  176. index: number,
  177. value: SelectValue<number>
  178. ) => {
  179. const {triggers, onChange} = this.props;
  180. // Convert saved action to unsaved by removing id
  181. const {id: _, ...action} = triggers[triggerIndex].actions[index];
  182. action.unsavedId = uniqueId();
  183. triggers[value.value].actions.push(action);
  184. onChange(value.value, triggers, triggers[value.value].actions);
  185. this.handleDeleteAction(triggerIndex, index);
  186. };
  187. handleChangeActionType = (
  188. triggerIndex: number,
  189. index: number,
  190. value: SelectValue<ActionType>
  191. ) => {
  192. const {triggers, onChange, availableActions} = this.props;
  193. const {actions} = triggers[triggerIndex];
  194. const actionConfig = availableActions?.find(
  195. availableAction => getActionUniqueKey(availableAction) === value.value
  196. );
  197. if (!actionConfig) {
  198. addErrorMessage(t('There was a problem changing an action'));
  199. Sentry.captureException(new Error('Unable to change an action type'));
  200. return;
  201. }
  202. const existingDateCreated =
  203. actions[index].dateCreated ?? actions[index].unsavedDateCreated;
  204. const newAction: Action = getCleanAction(actionConfig, existingDateCreated);
  205. onChange(triggerIndex, triggers, replaceAtArrayIndex(actions, index, newAction));
  206. };
  207. handleChangeTarget = (
  208. triggerIndex: number,
  209. index: number,
  210. value: SelectValue<keyof typeof TargetLabel>
  211. ) => {
  212. const {triggers, onChange} = this.props;
  213. const {actions} = triggers[triggerIndex];
  214. const newAction = {
  215. ...actions[index],
  216. targetType: value.value,
  217. targetIdentifier: '',
  218. };
  219. onChange(triggerIndex, triggers, replaceAtArrayIndex(actions, index, newAction));
  220. };
  221. /**
  222. * Update the Trigger's Action fields from the SentryAppRuleModal together
  223. * only after the user clicks "Save Changes".
  224. * @param formData Form data
  225. */
  226. updateParentFromSentryAppRule = (
  227. triggerIndex: number,
  228. actionIndex: number,
  229. formData: {[key: string]: string}
  230. ): void => {
  231. const {triggers, onChange} = this.props;
  232. const {actions} = triggers[triggerIndex];
  233. const newAction = {
  234. ...actions[actionIndex],
  235. ...formData,
  236. };
  237. onChange(
  238. triggerIndex,
  239. triggers,
  240. replaceAtArrayIndex(actions, actionIndex, newAction)
  241. );
  242. };
  243. render() {
  244. const {
  245. availableActions,
  246. currentProject,
  247. disabled,
  248. loading,
  249. organization,
  250. projects,
  251. triggers,
  252. } = this.props;
  253. const project = projects.find(({slug}) => slug === currentProject);
  254. const items = availableActions?.map(availableAction => ({
  255. value: getActionUniqueKey(availableAction),
  256. label: getFullActionTitle(availableAction),
  257. }));
  258. const levels = [
  259. {value: 0, label: 'Critical Status'},
  260. {value: 1, label: 'Warning Status'},
  261. ];
  262. // Create single array of unsaved and saved trigger actions
  263. // Sorted by date created ascending
  264. const actions = triggers
  265. .flatMap((trigger, triggerIndex) => {
  266. return trigger.actions.map((action, actionIdx) => {
  267. const availableAction = availableActions?.find(
  268. a => getActionUniqueKey(a) === getActionUniqueKey(action)
  269. );
  270. return {
  271. dateCreated: new Date(
  272. action.dateCreated ?? action.unsavedDateCreated
  273. ).getTime(),
  274. triggerIndex,
  275. action,
  276. actionIdx,
  277. availableAction,
  278. };
  279. });
  280. })
  281. .sort((a, b) => a.dateCreated - b.dateCreated);
  282. return (
  283. <Fragment>
  284. <PerformActionsListItem>{t('Set actions')}</PerformActionsListItem>
  285. {loading && <LoadingIndicator />}
  286. {actions.map(({action, actionIdx, triggerIndex, availableAction}) => {
  287. const actionDisabled =
  288. triggers[triggerIndex].actions[actionIdx]?.disabled || disabled;
  289. return (
  290. <div key={action.id ?? action.unsavedId}>
  291. <RuleRowContainer>
  292. <PanelItemGrid>
  293. <PanelItemSelects>
  294. <SelectControl
  295. name="select-level"
  296. aria-label={t('Select a status level')}
  297. isDisabled={disabled || loading}
  298. placeholder={t('Select Level')}
  299. onChange={this.handleChangeActionLevel.bind(
  300. this,
  301. triggerIndex,
  302. actionIdx
  303. )}
  304. value={triggerIndex}
  305. options={levels}
  306. />
  307. <SelectControl
  308. name="select-action"
  309. aria-label={t('Select an Action')}
  310. isDisabled={disabled || loading}
  311. placeholder={t('Select Action')}
  312. onChange={this.handleChangeActionType.bind(
  313. this,
  314. triggerIndex,
  315. actionIdx
  316. )}
  317. value={getActionUniqueKey(action)}
  318. options={items ?? []}
  319. />
  320. {availableAction && availableAction.allowedTargetTypes.length > 1 ? (
  321. <SelectControl
  322. isDisabled={disabled || loading}
  323. value={action.targetType}
  324. options={availableAction?.allowedTargetTypes?.map(
  325. allowedType => ({
  326. value: allowedType,
  327. label: TargetLabel[allowedType],
  328. })
  329. )}
  330. onChange={this.handleChangeTarget.bind(
  331. this,
  332. triggerIndex,
  333. actionIdx
  334. )}
  335. />
  336. ) : availableAction &&
  337. availableAction.type === 'sentry_app' &&
  338. availableAction.settings ? (
  339. <Button
  340. icon={<IconSettings />}
  341. type="button"
  342. disabled={actionDisabled}
  343. onClick={() => {
  344. openModal(
  345. deps => (
  346. <SentryAppRuleModal
  347. {...deps}
  348. // Using ! for keys that will exist for sentryapps
  349. sentryAppInstallationUuid={
  350. availableAction.sentryAppInstallationUuid!
  351. }
  352. config={availableAction.settings!}
  353. appName={availableAction.sentryAppName!}
  354. onSubmitSuccess={this.updateParentFromSentryAppRule.bind(
  355. this,
  356. triggerIndex,
  357. actionIdx
  358. )}
  359. resetValues={
  360. triggers[triggerIndex].actions[actionIdx] || {}
  361. }
  362. />
  363. ),
  364. {allowClickClose: false}
  365. );
  366. }}
  367. >
  368. {t('Settings')}
  369. </Button>
  370. ) : null}
  371. <ActionTargetSelector
  372. action={action}
  373. availableAction={availableAction}
  374. disabled={disabled}
  375. loading={loading}
  376. onChange={this.handleChangeKey.bind(
  377. this,
  378. triggerIndex,
  379. actionIdx,
  380. 'targetIdentifier'
  381. )}
  382. organization={organization}
  383. project={project}
  384. />
  385. <ActionSpecificTargetSelector
  386. action={action}
  387. disabled={disabled}
  388. onChange={this.handleChangeKey.bind(
  389. this,
  390. triggerIndex,
  391. actionIdx,
  392. 'inputChannelId'
  393. )}
  394. />
  395. </PanelItemSelects>
  396. <DeleteActionButton
  397. triggerIndex={triggerIndex}
  398. index={actionIdx}
  399. onClick={this.handleDeleteAction}
  400. disabled={disabled}
  401. />
  402. </PanelItemGrid>
  403. </RuleRowContainer>
  404. {this.conditionallyRenderHelpfulBanner(triggerIndex, actionIdx)}
  405. </div>
  406. );
  407. })}
  408. <ActionSection>
  409. <Button
  410. type="button"
  411. disabled={disabled || loading}
  412. icon={<IconAdd isCircled color="gray300" />}
  413. onClick={this.handleAddAction}
  414. >
  415. {t('Add Action')}
  416. </Button>
  417. </ActionSection>
  418. </Fragment>
  419. );
  420. }
  421. }
  422. const ActionsPanelWithSpace = styled(ActionsPanel)`
  423. margin-top: ${space(4)};
  424. `;
  425. const ActionSection = styled('div')`
  426. margin-top: ${space(1)};
  427. margin-bottom: ${space(3)};
  428. `;
  429. const PanelItemGrid = styled(PanelItem)`
  430. display: flex;
  431. align-items: center;
  432. border-bottom: 0;
  433. padding: ${space(1)};
  434. `;
  435. const PanelItemSelects = styled('div')`
  436. display: flex;
  437. width: 100%;
  438. margin-right: ${space(1)};
  439. > * {
  440. flex: 0 1 200px;
  441. &:not(:last-child) {
  442. margin-right: ${space(1)};
  443. }
  444. }
  445. `;
  446. const RuleRowContainer = styled('div')`
  447. background-color: ${p => p.theme.backgroundSecondary};
  448. border: 1px ${p => p.theme.border} solid;
  449. border-radius: ${p => p.theme.borderRadius} ${p => p.theme.borderRadius} 0 0;
  450. &:last-child {
  451. border-radius: ${p => p.theme.borderRadius};
  452. }
  453. `;
  454. const StyledListItem = styled(ListItem)`
  455. margin: ${space(2)} 0 ${space(3)} 0;
  456. font-size: ${p => p.theme.fontSizeExtraLarge};
  457. `;
  458. const PerformActionsListItem = styled(StyledListItem)`
  459. margin-bottom: 0;
  460. line-height: 1.3;
  461. `;
  462. const MarginlessAlert = styled(Alert)`
  463. border-radius: 0 0 ${p => p.theme.borderRadius} ${p => p.theme.borderRadius};
  464. border: 1px ${p => p.theme.border} solid;
  465. border-top-width: 0;
  466. margin: 0;
  467. padding: ${space(1)} ${space(1)};
  468. font-size: ${p => p.theme.fontSizeSmall};
  469. `;
  470. export default withOrganization(ActionsPanelWithSpace);