ruleDetails.tsx 15 KB

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