ruleDetails.tsx 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507
  1. import type {RouteComponentProps} from 'react-router';
  2. import styled from '@emotion/styled';
  3. import pick from 'lodash/pick';
  4. import moment from 'moment';
  5. import {addErrorMessage, addSuccessMessage} from 'sentry/actionCreators/indicator';
  6. import Access from 'sentry/components/acl/access';
  7. import {Alert} from 'sentry/components/alert';
  8. import SnoozeAlert from 'sentry/components/alerts/snoozeAlert';
  9. import {Breadcrumbs} from 'sentry/components/breadcrumbs';
  10. import {Button, LinkButton} from 'sentry/components/button';
  11. import ButtonBar from 'sentry/components/buttonBar';
  12. import type {DateTimeObject} from 'sentry/components/charts/utils';
  13. import ErrorBoundary from 'sentry/components/errorBoundary';
  14. import IdBadge from 'sentry/components/idBadge';
  15. import * as Layout from 'sentry/components/layouts/thirds';
  16. import ExternalLink from 'sentry/components/links/externalLink';
  17. import Link from 'sentry/components/links/link';
  18. import LoadingError from 'sentry/components/loadingError';
  19. import LoadingIndicator from 'sentry/components/loadingIndicator';
  20. import PageFiltersContainer from 'sentry/components/organizations/pageFilters/container';
  21. import {normalizeDateTimeParams} from 'sentry/components/organizations/pageFilters/parse';
  22. import SentryDocumentTitle from 'sentry/components/sentryDocumentTitle';
  23. import type {ChangeData} from 'sentry/components/timeRangeSelector';
  24. import {TimeRangeSelector} from 'sentry/components/timeRangeSelector';
  25. import TimeSince from 'sentry/components/timeSince';
  26. import {IconCopy, IconEdit} from 'sentry/icons';
  27. import {t, tct} from 'sentry/locale';
  28. import {space} from 'sentry/styles/space';
  29. import type {IssueAlertRule} from 'sentry/types/alerts';
  30. import {RuleActionsCategories} from 'sentry/types/alerts';
  31. import type {DateString} from 'sentry/types/core';
  32. import {trackAnalytics} from 'sentry/utils/analytics';
  33. import type {ApiQueryKey} from 'sentry/utils/queryClient';
  34. import {setApiQueryData, useApiQuery, useQueryClient} from 'sentry/utils/queryClient';
  35. import useRouteAnalyticsEventNames from 'sentry/utils/routeAnalytics/useRouteAnalyticsEventNames';
  36. import useRouteAnalyticsParams from 'sentry/utils/routeAnalytics/useRouteAnalyticsParams';
  37. import useApi from 'sentry/utils/useApi';
  38. import useOrganization from 'sentry/utils/useOrganization';
  39. import useProjects from 'sentry/utils/useProjects';
  40. import {findIncompatibleRules} from 'sentry/views/alerts/rules/issue';
  41. import {ALERT_DEFAULT_CHART_PERIOD} from 'sentry/views/alerts/rules/metric/details/constants';
  42. import {getRuleActionCategory} from 'sentry/views/alerts/rules/utils';
  43. import {IssueAlertDetailsChart} from './alertChart';
  44. import AlertRuleIssuesList from './issuesList';
  45. import Sidebar from './sidebar';
  46. interface AlertRuleDetailsProps
  47. extends RouteComponentProps<{projectId: string; ruleId: string}, {}> {}
  48. const PAGE_QUERY_PARAMS = [
  49. 'pageStatsPeriod',
  50. 'pageStart',
  51. 'pageEnd',
  52. 'pageUtc',
  53. 'cursor',
  54. ];
  55. const getIssueAlertDetailsQueryKey = ({
  56. orgSlug,
  57. projectSlug,
  58. ruleId,
  59. }: {
  60. orgSlug: string;
  61. projectSlug: string;
  62. ruleId: string;
  63. }): ApiQueryKey => [
  64. `/projects/${orgSlug}/${projectSlug}/rules/${ruleId}/`,
  65. {query: {expand: 'lastTriggered'}},
  66. ];
  67. function AlertRuleDetails({params, location, router}: AlertRuleDetailsProps) {
  68. const queryClient = useQueryClient();
  69. const organization = useOrganization();
  70. const api = useApi();
  71. const {projects, fetching: projectIsLoading} = useProjects();
  72. const project = projects.find(({slug}) => slug === params.projectId);
  73. const {projectId: projectSlug, ruleId} = params;
  74. const {
  75. data: rule,
  76. isLoading,
  77. isError,
  78. } = useApiQuery<IssueAlertRule>(
  79. getIssueAlertDetailsQueryKey({orgSlug: organization.slug, projectSlug, ruleId}),
  80. {staleTime: 0}
  81. );
  82. useRouteAnalyticsEventNames(
  83. 'issue_alert_rule_details.viewed',
  84. 'Issue Alert Rule Details: Viewed'
  85. );
  86. useRouteAnalyticsParams({rule_id: parseInt(params.ruleId, 10)});
  87. function getDataDatetime(): DateTimeObject {
  88. const query = location?.query ?? {};
  89. const {
  90. start,
  91. end,
  92. statsPeriod,
  93. utc: utcString,
  94. } = normalizeDateTimeParams(query, {
  95. allowEmptyPeriod: true,
  96. allowAbsoluteDatetime: true,
  97. allowAbsolutePageDatetime: true,
  98. });
  99. if (!statsPeriod && !start && !end) {
  100. return {period: ALERT_DEFAULT_CHART_PERIOD};
  101. }
  102. // Following getParams, statsPeriod will take priority over start/end
  103. if (statsPeriod) {
  104. return {period: statsPeriod};
  105. }
  106. const utc = utcString === 'true';
  107. if (start && end) {
  108. return utc
  109. ? {
  110. start: moment.utc(start).format(),
  111. end: moment.utc(end).format(),
  112. utc,
  113. }
  114. : {
  115. start: moment(start).utc().format(),
  116. end: moment(end).utc().format(),
  117. utc,
  118. };
  119. }
  120. return {period: ALERT_DEFAULT_CHART_PERIOD};
  121. }
  122. function setStateOnUrl(nextState: {
  123. cursor?: string;
  124. pageEnd?: DateString;
  125. pageStart?: DateString;
  126. pageStatsPeriod?: string | null;
  127. pageUtc?: boolean | null;
  128. team?: string;
  129. }) {
  130. return router.push({
  131. ...location,
  132. query: {
  133. ...location.query,
  134. ...pick(nextState, PAGE_QUERY_PARAMS),
  135. },
  136. });
  137. }
  138. function onSnooze({
  139. snooze,
  140. snoozeCreatedBy,
  141. snoozeForEveryone,
  142. }: {
  143. snooze: boolean;
  144. snoozeCreatedBy?: string;
  145. snoozeForEveryone?: boolean;
  146. }) {
  147. setApiQueryData<IssueAlertRule>(
  148. queryClient,
  149. getIssueAlertDetailsQueryKey({orgSlug: organization.slug, projectSlug, ruleId}),
  150. alertRule => ({...alertRule, snooze, snoozeCreatedBy, snoozeForEveryone})
  151. );
  152. }
  153. async function handleKeepAlertAlive() {
  154. try {
  155. await api.requestPromise(
  156. `/projects/${organization.slug}/${projectSlug}/rules/${ruleId}/`,
  157. {
  158. method: 'PUT',
  159. data: {
  160. ...rule,
  161. optOutExplicit: true,
  162. },
  163. }
  164. );
  165. // Update alert rule to remove disableDate
  166. setApiQueryData<IssueAlertRule>(
  167. queryClient,
  168. getIssueAlertDetailsQueryKey({orgSlug: organization.slug, projectSlug, ruleId}),
  169. alertRule => ({...alertRule, disableDate: undefined})
  170. );
  171. addSuccessMessage(t('Successfully updated'));
  172. } catch (err) {
  173. addErrorMessage(t('Unable to update alert rule'));
  174. }
  175. }
  176. async function handleReEnable() {
  177. try {
  178. await api.requestPromise(
  179. `/projects/${organization.slug}/${projectSlug}/rules/${ruleId}/enable/`,
  180. {method: 'PUT'}
  181. );
  182. // Update alert rule to remove disableDate
  183. setApiQueryData<IssueAlertRule>(
  184. queryClient,
  185. getIssueAlertDetailsQueryKey({orgSlug: organization.slug, projectSlug, ruleId}),
  186. alertRule => ({...alertRule, disableDate: undefined, status: 'active'})
  187. );
  188. addSuccessMessage(t('Successfully re-enabled'));
  189. } catch (err) {
  190. addErrorMessage(
  191. typeof err.responseJSON?.detail === 'string'
  192. ? err.responseJSON.detail
  193. : t('Unable to update alert rule')
  194. );
  195. }
  196. }
  197. function handleUpdateDatetime(datetime: ChangeData) {
  198. const {start, end, relative, utc} = datetime;
  199. if (start && end) {
  200. const parser = utc ? moment.utc : moment;
  201. return setStateOnUrl({
  202. pageStatsPeriod: undefined,
  203. pageStart: parser(start).format(),
  204. pageEnd: parser(end).format(),
  205. pageUtc: utc ?? undefined,
  206. cursor: undefined,
  207. });
  208. }
  209. return setStateOnUrl({
  210. pageStatsPeriod: relative || undefined,
  211. pageStart: undefined,
  212. pageEnd: undefined,
  213. pageUtc: undefined,
  214. cursor: undefined,
  215. });
  216. }
  217. if (isLoading || projectIsLoading) {
  218. return (
  219. <Layout.Body>
  220. <Layout.Main fullWidth>
  221. <LoadingIndicator />
  222. </Layout.Main>
  223. </Layout.Body>
  224. );
  225. }
  226. if (!rule || isError) {
  227. return (
  228. <StyledLoadingError
  229. message={t('The alert rule you were looking for was not found.')}
  230. />
  231. );
  232. }
  233. if (!project) {
  234. return (
  235. <StyledLoadingError
  236. message={t('The project you were looking for was not found.')}
  237. />
  238. );
  239. }
  240. const isSnoozed = rule.snooze;
  241. const ruleActionCategory = getRuleActionCategory(rule);
  242. const duplicateLink = {
  243. pathname: `/organizations/${organization.slug}/alerts/new/issue/`,
  244. query: {
  245. project: project.slug,
  246. duplicateRuleId: rule.id,
  247. createFromDuplicate: true,
  248. referrer: 'issue_rule_details',
  249. },
  250. };
  251. function renderIncompatibleAlert() {
  252. const incompatibleRule = findIncompatibleRules(rule);
  253. if (incompatibleRule.conditionIndices || incompatibleRule.filterIndices) {
  254. return (
  255. <Alert type="error" showIcon>
  256. {tct(
  257. 'The conditions in this alert rule conflict and might not be working properly. [link:Edit alert rule]',
  258. {
  259. link: (
  260. <Link
  261. to={`/organizations/${organization.slug}/alerts/rules/${projectSlug}/${ruleId}/`}
  262. />
  263. ),
  264. }
  265. )}
  266. </Alert>
  267. );
  268. }
  269. return null;
  270. }
  271. function renderDisabledAlertBanner() {
  272. // Rule has been disabled and has a disabled date indicating it was disabled due to lack of activity
  273. if (rule?.status === 'disabled' && moment(new Date()).isAfter(rule.disableDate)) {
  274. return (
  275. <Alert type="warning" showIcon>
  276. {tct(
  277. 'This alert was disabled due to lack of activity. Please [keepAlive] to enable this alert.',
  278. {
  279. keepAlive: (
  280. <BoldButton priority="link" size="sm" onClick={handleReEnable}>
  281. {t('click here')}
  282. </BoldButton>
  283. ),
  284. }
  285. )}
  286. </Alert>
  287. );
  288. }
  289. // Generic rule disabled banner
  290. if (rule?.status === 'disabled') {
  291. return (
  292. <Alert type="warning" showIcon>
  293. {rule.actions?.length === 0
  294. ? t(
  295. 'This alert is disabled due to missing actions. Please edit the alert rule to enable this alert.'
  296. )
  297. : t(
  298. 'This alert is disabled due to its configuration and needs to be edited to be enabled.'
  299. )}
  300. </Alert>
  301. );
  302. }
  303. // Rule to be disabled soon
  304. if (rule?.disableDate && moment(rule.disableDate).isAfter(new Date())) {
  305. return (
  306. <Alert type="warning" showIcon>
  307. {tct(
  308. 'This alert is scheduled to be disabled [date] due to lack of activity. Please [keepAlive] to keep this alert active. [docs:Learn more]',
  309. {
  310. date: <TimeSince date={rule.disableDate} />,
  311. keepAlive: (
  312. <BoldButton priority="link" size="sm" onClick={handleKeepAlertAlive}>
  313. {t('click here')}
  314. </BoldButton>
  315. ),
  316. docs: (
  317. <ExternalLink href="https://docs.sentry.io/product/alerts/#disabled-alerts" />
  318. ),
  319. }
  320. )}
  321. </Alert>
  322. );
  323. }
  324. return null;
  325. }
  326. const {period, start, end, utc} = getDataDatetime();
  327. const {cursor} = location.query;
  328. return (
  329. <PageFiltersContainer
  330. skipInitializeUrlParams
  331. skipLoadLastUsed
  332. shouldForceProject
  333. forceProject={project}
  334. >
  335. <SentryDocumentTitle
  336. title={rule.name}
  337. orgSlug={organization.slug}
  338. projectSlug={projectSlug}
  339. />
  340. <Layout.Header>
  341. <Layout.HeaderContent>
  342. <Breadcrumbs
  343. crumbs={[
  344. {
  345. label: t('Alerts'),
  346. to: `/organizations/${organization.slug}/alerts/rules/`,
  347. },
  348. {
  349. label: rule.name,
  350. to: null,
  351. },
  352. ]}
  353. />
  354. <Layout.Title>
  355. <IdBadge
  356. project={project}
  357. avatarSize={28}
  358. hideName
  359. avatarProps={{hasTooltip: true, tooltip: project.slug}}
  360. />
  361. {rule.name}
  362. </Layout.Title>
  363. </Layout.HeaderContent>
  364. <Layout.HeaderActions>
  365. <ButtonBar gap={1}>
  366. <Access access={['alerts:write']}>
  367. {({hasAccess}) => (
  368. <SnoozeAlert
  369. isSnoozed={isSnoozed}
  370. onSnooze={onSnooze}
  371. ruleId={rule.id}
  372. projectSlug={projectSlug}
  373. ruleActionCategory={ruleActionCategory}
  374. hasAccess={hasAccess}
  375. type="issue"
  376. disabled={rule.status === 'disabled'}
  377. />
  378. )}
  379. </Access>
  380. <LinkButton
  381. size="sm"
  382. icon={<IconCopy />}
  383. to={duplicateLink}
  384. disabled={rule.status === 'disabled'}
  385. >
  386. {t('Duplicate')}
  387. </LinkButton>
  388. <Button
  389. size="sm"
  390. icon={<IconEdit />}
  391. to={`/organizations/${organization.slug}/alerts/rules/${projectSlug}/${ruleId}/`}
  392. onClick={() =>
  393. trackAnalytics('issue_alert_rule_details.edit_clicked', {
  394. organization,
  395. rule_id: parseInt(ruleId, 10),
  396. })
  397. }
  398. >
  399. {rule.status === 'disabled' ? t('Edit to enable') : t('Edit Rule')}
  400. </Button>
  401. </ButtonBar>
  402. </Layout.HeaderActions>
  403. </Layout.Header>
  404. <Layout.Body>
  405. <Layout.Main>
  406. {renderIncompatibleAlert()}
  407. {renderDisabledAlertBanner()}
  408. {isSnoozed && (
  409. <Alert showIcon>
  410. {ruleActionCategory === RuleActionsCategories.NO_DEFAULT
  411. ? tct(
  412. "[creator] muted this alert so these notifications won't be sent in the future.",
  413. {creator: rule.snoozeCreatedBy}
  414. )
  415. : tct(
  416. "[creator] muted this alert[forEveryone]so you won't get these notifications in the future.",
  417. {
  418. creator: rule.snoozeCreatedBy,
  419. forEveryone: rule.snoozeForEveryone ? ' for everyone ' : ' ',
  420. }
  421. )}
  422. </Alert>
  423. )}
  424. <StyledTimeRangeSelector
  425. relative={period ?? ''}
  426. start={start ?? null}
  427. end={end ?? null}
  428. utc={utc ?? null}
  429. onChange={handleUpdateDatetime}
  430. />
  431. <ErrorBoundary>
  432. <IssueAlertDetailsChart
  433. project={project}
  434. rule={rule}
  435. period={period ?? ''}
  436. start={start ?? null}
  437. end={end ?? null}
  438. utc={utc ?? null}
  439. />
  440. </ErrorBoundary>
  441. <AlertRuleIssuesList
  442. project={project}
  443. rule={rule}
  444. period={period ?? ''}
  445. start={start ?? null}
  446. end={end ?? null}
  447. utc={utc ?? null}
  448. cursor={cursor}
  449. />
  450. </Layout.Main>
  451. <Layout.Side>
  452. <Sidebar rule={rule} projectSlug={project.slug} teams={project.teams} />
  453. </Layout.Side>
  454. </Layout.Body>
  455. </PageFiltersContainer>
  456. );
  457. }
  458. export default AlertRuleDetails;
  459. const StyledTimeRangeSelector = styled(TimeRangeSelector)`
  460. margin-bottom: ${space(2)};
  461. `;
  462. const StyledLoadingError = styled(LoadingError)`
  463. margin: ${space(2)};
  464. `;
  465. const BoldButton = styled(Button)`
  466. font-weight: 600;
  467. `;