ruleDetails.tsx 12 KB

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