ruleDetails.tsx 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388
  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 Access from 'sentry/components/acl/access';
  6. import {Alert} from 'sentry/components/alert';
  7. import SnoozeAlert from 'sentry/components/alerts/snoozeAlert';
  8. import Breadcrumbs from 'sentry/components/breadcrumbs';
  9. import {Button} from 'sentry/components/button';
  10. import ButtonBar from 'sentry/components/buttonBar';
  11. import type {DateTimeObject} from 'sentry/components/charts/utils';
  12. import ErrorBoundary from 'sentry/components/errorBoundary';
  13. import IdBadge from 'sentry/components/idBadge';
  14. import * as Layout from 'sentry/components/layouts/thirds';
  15. import Link from 'sentry/components/links/link';
  16. import LoadingError from 'sentry/components/loadingError';
  17. import LoadingIndicator from 'sentry/components/loadingIndicator';
  18. import PageFiltersContainer from 'sentry/components/organizations/pageFilters/container';
  19. import {normalizeDateTimeParams} from 'sentry/components/organizations/pageFilters/parse';
  20. import {ChangeData} from 'sentry/components/organizations/timeRangeSelector';
  21. import PageTimeRangeSelector from 'sentry/components/pageTimeRangeSelector';
  22. import SentryDocumentTitle from 'sentry/components/sentryDocumentTitle';
  23. import {IconCopy, IconEdit} from 'sentry/icons';
  24. import {t, tct} from 'sentry/locale';
  25. import {space} from 'sentry/styles/space';
  26. import type {DateString} from 'sentry/types';
  27. import type {IssueAlertRule} from 'sentry/types/alerts';
  28. import {RuleActionsCategories} from 'sentry/types/alerts';
  29. import {trackAnalytics} from 'sentry/utils/analytics';
  30. import {
  31. ApiQueryKey,
  32. setApiQueryData,
  33. useApiQuery,
  34. useQueryClient,
  35. } from 'sentry/utils/queryClient';
  36. import useRouteAnalyticsEventNames from 'sentry/utils/routeAnalytics/useRouteAnalyticsEventNames';
  37. import useRouteAnalyticsParams from 'sentry/utils/routeAnalytics/useRouteAnalyticsParams';
  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 {projects, fetching: projectIsLoading} = useProjects();
  71. const project = projects.find(({slug}) => slug === params.projectId);
  72. const {projectId: projectSlug, ruleId} = params;
  73. const {
  74. data: rule,
  75. isLoading,
  76. isError,
  77. } = useApiQuery<IssueAlertRule>(
  78. getIssueAlertDetailsQueryKey({orgSlug: organization.slug, projectSlug, ruleId}),
  79. {staleTime: 0}
  80. );
  81. useRouteAnalyticsEventNames(
  82. 'issue_alert_rule_details.viewed',
  83. 'Issue Alert Rule Details: Viewed'
  84. );
  85. useRouteAnalyticsParams({rule_id: parseInt(params.ruleId, 10)});
  86. function getDataDatetime(): DateTimeObject {
  87. const query = location?.query ?? {};
  88. const {
  89. start,
  90. end,
  91. statsPeriod,
  92. utc: utcString,
  93. } = normalizeDateTimeParams(query, {
  94. allowEmptyPeriod: true,
  95. allowAbsoluteDatetime: true,
  96. allowAbsolutePageDatetime: true,
  97. });
  98. if (!statsPeriod && !start && !end) {
  99. return {period: ALERT_DEFAULT_CHART_PERIOD};
  100. }
  101. // Following getParams, statsPeriod will take priority over start/end
  102. if (statsPeriod) {
  103. return {period: statsPeriod};
  104. }
  105. const utc = utcString === 'true';
  106. if (start && end) {
  107. return utc
  108. ? {
  109. start: moment.utc(start).format(),
  110. end: moment.utc(end).format(),
  111. utc,
  112. }
  113. : {
  114. start: moment(start).utc().format(),
  115. end: moment(end).utc().format(),
  116. utc,
  117. };
  118. }
  119. return {period: ALERT_DEFAULT_CHART_PERIOD};
  120. }
  121. function setStateOnUrl(nextState: {
  122. cursor?: string;
  123. pageEnd?: DateString;
  124. pageStart?: DateString;
  125. pageStatsPeriod?: string | null;
  126. pageUtc?: boolean | null;
  127. team?: string;
  128. }) {
  129. return router.push({
  130. ...location,
  131. query: {
  132. ...location.query,
  133. ...pick(nextState, PAGE_QUERY_PARAMS),
  134. },
  135. });
  136. }
  137. function onSnooze({
  138. snooze,
  139. snoozeCreatedBy,
  140. snoozeForEveryone,
  141. }: {
  142. snooze: boolean;
  143. snoozeCreatedBy?: string;
  144. snoozeForEveryone?: boolean;
  145. }) {
  146. setApiQueryData<IssueAlertRule>(
  147. queryClient,
  148. getIssueAlertDetailsQueryKey({orgSlug: organization.slug, projectSlug, ruleId}),
  149. alertRule => ({...alertRule, snooze, snoozeCreatedBy, snoozeForEveryone})
  150. );
  151. }
  152. function handleUpdateDatetime(datetime: ChangeData) {
  153. const {start, end, relative, utc} = datetime;
  154. if (start && end) {
  155. const parser = utc ? moment.utc : moment;
  156. return setStateOnUrl({
  157. pageStatsPeriod: undefined,
  158. pageStart: parser(start).format(),
  159. pageEnd: parser(end).format(),
  160. pageUtc: utc ?? undefined,
  161. cursor: undefined,
  162. });
  163. }
  164. return setStateOnUrl({
  165. pageStatsPeriod: relative || undefined,
  166. pageStart: undefined,
  167. pageEnd: undefined,
  168. pageUtc: undefined,
  169. cursor: undefined,
  170. });
  171. }
  172. if (isLoading || projectIsLoading) {
  173. return (
  174. <Layout.Body>
  175. <Layout.Main fullWidth>
  176. <LoadingIndicator />
  177. </Layout.Main>
  178. </Layout.Body>
  179. );
  180. }
  181. if (!rule || isError) {
  182. return (
  183. <StyledLoadingError
  184. message={t('The alert rule you were looking for was not found.')}
  185. />
  186. );
  187. }
  188. if (!project) {
  189. return (
  190. <StyledLoadingError
  191. message={t('The project you were looking for was not found.')}
  192. />
  193. );
  194. }
  195. const isSnoozed = rule.snooze;
  196. const ruleActionCategory = getRuleActionCategory(rule);
  197. const duplicateLink = {
  198. pathname: `/organizations/${organization.slug}/alerts/new/issue/`,
  199. query: {
  200. project: project.slug,
  201. duplicateRuleId: rule.id,
  202. createFromDuplicate: true,
  203. referrer: 'issue_rule_details',
  204. },
  205. };
  206. function renderIncompatibleAlert() {
  207. const incompatibleRule = findIncompatibleRules(rule);
  208. if (incompatibleRule.conditionIndices || incompatibleRule.filterIndices) {
  209. return (
  210. <Alert type="error" showIcon>
  211. {tct(
  212. 'The conditions in this alert rule conflict and might not be working properly. [link:Edit alert rule]',
  213. {
  214. link: (
  215. <Link
  216. to={`/organizations/${organization.slug}/alerts/rules/${projectSlug}/${ruleId}/`}
  217. />
  218. ),
  219. }
  220. )}
  221. </Alert>
  222. );
  223. }
  224. return null;
  225. }
  226. const {period, start, end, utc} = getDataDatetime();
  227. const {cursor} = location.query;
  228. return (
  229. <PageFiltersContainer
  230. skipInitializeUrlParams
  231. skipLoadLastUsed
  232. shouldForceProject
  233. forceProject={project}
  234. >
  235. <SentryDocumentTitle
  236. title={rule.name}
  237. orgSlug={organization.slug}
  238. projectSlug={projectSlug}
  239. />
  240. <Layout.Header>
  241. <Layout.HeaderContent>
  242. <Breadcrumbs
  243. crumbs={[
  244. {
  245. label: t('Alerts'),
  246. to: `/organizations/${organization.slug}/alerts/rules/`,
  247. },
  248. {
  249. label: rule.name,
  250. to: null,
  251. },
  252. ]}
  253. />
  254. <Layout.Title>
  255. <IdBadge
  256. project={project}
  257. avatarSize={28}
  258. hideName
  259. avatarProps={{hasTooltip: true, tooltip: project.slug}}
  260. />
  261. {rule.name}
  262. </Layout.Title>
  263. </Layout.HeaderContent>
  264. <Layout.HeaderActions>
  265. <ButtonBar gap={1}>
  266. <Access access={['alerts:write']}>
  267. {({hasAccess}) => (
  268. <SnoozeAlert
  269. isSnoozed={isSnoozed}
  270. onSnooze={onSnooze}
  271. ruleId={rule.id}
  272. projectSlug={projectSlug}
  273. ruleActionCategory={ruleActionCategory}
  274. hasAccess={hasAccess}
  275. type="issue"
  276. />
  277. )}
  278. </Access>
  279. <Button size="sm" icon={<IconCopy />} to={duplicateLink}>
  280. {t('Duplicate')}
  281. </Button>
  282. <Button
  283. size="sm"
  284. icon={<IconEdit />}
  285. to={`/organizations/${organization.slug}/alerts/rules/${projectSlug}/${ruleId}/`}
  286. onClick={() =>
  287. trackAnalytics('issue_alert_rule_details.edit_clicked', {
  288. organization,
  289. rule_id: parseInt(ruleId, 10),
  290. })
  291. }
  292. >
  293. {t('Edit Rule')}
  294. </Button>
  295. </ButtonBar>
  296. </Layout.HeaderActions>
  297. </Layout.Header>
  298. <Layout.Body>
  299. <Layout.Main>
  300. {renderIncompatibleAlert()}
  301. {isSnoozed && (
  302. <Alert showIcon>
  303. {ruleActionCategory === RuleActionsCategories.NO_DEFAULT
  304. ? tct(
  305. "[creator] muted this alert so these notifications won't be sent in the future.",
  306. {creator: rule.snoozeCreatedBy}
  307. )
  308. : tct(
  309. "[creator] muted this alert[forEveryone]so you won't get these notifications in the future.",
  310. {
  311. creator: rule.snoozeCreatedBy,
  312. forEveryone: rule.snoozeForEveryone ? ' for everyone ' : ' ',
  313. }
  314. )}
  315. </Alert>
  316. )}
  317. <StyledPageTimeRangeSelector
  318. organization={organization}
  319. relative={period ?? ''}
  320. start={start ?? null}
  321. end={end ?? null}
  322. utc={utc ?? null}
  323. onUpdate={handleUpdateDatetime}
  324. />
  325. <ErrorBoundary>
  326. <IssueAlertDetailsChart
  327. project={project}
  328. rule={rule}
  329. period={period ?? ''}
  330. start={start ?? null}
  331. end={end ?? null}
  332. utc={utc ?? null}
  333. />
  334. </ErrorBoundary>
  335. <AlertRuleIssuesList
  336. organization={organization}
  337. project={project}
  338. rule={rule}
  339. period={period ?? ''}
  340. start={start ?? null}
  341. end={end ?? null}
  342. utc={utc ?? null}
  343. cursor={cursor}
  344. />
  345. </Layout.Main>
  346. <Layout.Side>
  347. <Sidebar rule={rule} projectSlug={project.slug} teams={project.teams} />
  348. </Layout.Side>
  349. </Layout.Body>
  350. </PageFiltersContainer>
  351. );
  352. }
  353. export default AlertRuleDetails;
  354. const StyledPageTimeRangeSelector = styled(PageTimeRangeSelector)`
  355. margin-bottom: ${space(2)};
  356. `;
  357. const StyledLoadingError = styled(LoadingError)`
  358. margin: ${space(2)};
  359. `;