body.tsx 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300
  1. import {Fragment} from 'react';
  2. import {useTheme} from '@emotion/react';
  3. import styled from '@emotion/styled';
  4. import moment from 'moment-timezone';
  5. import {Alert} from 'sentry/components/core/alert';
  6. import * as Layout from 'sentry/components/layouts/thirds';
  7. import Link from 'sentry/components/links/link';
  8. import Panel from 'sentry/components/panels/panel';
  9. import PanelBody from 'sentry/components/panels/panelBody';
  10. import Placeholder from 'sentry/components/placeholder';
  11. import type {ChangeData} from 'sentry/components/timeRangeSelector';
  12. import {TimeRangeSelector} from 'sentry/components/timeRangeSelector';
  13. import {Tooltip} from 'sentry/components/tooltip';
  14. import {t, tct} from 'sentry/locale';
  15. import {space} from 'sentry/styles/space';
  16. import {RuleActionsCategories} from 'sentry/types/alerts';
  17. import type {Project} from 'sentry/types/project';
  18. import {shouldShowOnDemandMetricAlertUI} from 'sentry/utils/onDemandMetrics/features';
  19. import {useLocation} from 'sentry/utils/useLocation';
  20. import {useNavigate} from 'sentry/utils/useNavigate';
  21. import useOrganization from 'sentry/utils/useOrganization';
  22. import AnomalyDetectionFeedbackBanner from 'sentry/views/alerts/rules/metric/details/anomalyDetectionFeedbackBanner';
  23. import {ErrorMigrationWarning} from 'sentry/views/alerts/rules/metric/details/errorMigrationWarning';
  24. import MetricHistory from 'sentry/views/alerts/rules/metric/details/metricHistory';
  25. import type {MetricRule} from 'sentry/views/alerts/rules/metric/types';
  26. import {
  27. AlertRuleComparisonType,
  28. Dataset,
  29. TimePeriod,
  30. } from 'sentry/views/alerts/rules/metric/types';
  31. import {extractEventTypeFilterFromRule} from 'sentry/views/alerts/rules/metric/utils/getEventTypeFilter';
  32. import {isOnDemandMetricAlert} from 'sentry/views/alerts/rules/metric/utils/onDemandMetricAlert';
  33. import {getAlertRuleActionCategory} from 'sentry/views/alerts/rules/utils';
  34. import type {Anomaly, Incident} from 'sentry/views/alerts/types';
  35. import {AlertRuleStatus} from 'sentry/views/alerts/types';
  36. import {alertDetailsLink} from 'sentry/views/alerts/utils';
  37. import {isCrashFreeAlert} from '../utils/isCrashFreeAlert';
  38. import type {TimePeriodType} from './constants';
  39. import {SELECTOR_RELATIVE_PERIODS} from './constants';
  40. import MetricChart from './metricChart';
  41. import RelatedIssues from './relatedIssues';
  42. import RelatedTransactions from './relatedTransactions';
  43. import {MetricDetailsSidebar} from './sidebar';
  44. import {getFilter, getPeriodInterval} from './utils';
  45. export interface MetricDetailsBodyProps {
  46. timePeriod: TimePeriodType;
  47. anomalies?: Anomaly[];
  48. incidents?: Incident[];
  49. project?: Project;
  50. rule?: MetricRule;
  51. selectedIncident?: Incident | null;
  52. }
  53. export default function MetricDetailsBody({
  54. project,
  55. rule,
  56. incidents,
  57. timePeriod,
  58. selectedIncident,
  59. anomalies,
  60. }: MetricDetailsBodyProps) {
  61. const theme = useTheme();
  62. const organization = useOrganization();
  63. const location = useLocation();
  64. const navigate = useNavigate();
  65. const handleTimePeriodChange = (datetime: ChangeData) => {
  66. const {start, end, relative} = datetime;
  67. if (start && end) {
  68. return navigate({
  69. ...location,
  70. query: {
  71. start: moment(start).utc().format(),
  72. end: moment(end).utc().format(),
  73. },
  74. });
  75. }
  76. return navigate({
  77. ...location,
  78. query: {
  79. period: relative,
  80. },
  81. });
  82. };
  83. if (!rule || !project) {
  84. return (
  85. <Layout.Body>
  86. <Layout.Main>
  87. <Placeholder height="38px" />
  88. <ChartPanel>
  89. <PanelBody withPadding>
  90. <Placeholder height="200px" />
  91. </PanelBody>
  92. </ChartPanel>
  93. </Layout.Main>
  94. <Layout.Side>
  95. <Placeholder height="200px" />
  96. </Layout.Side>
  97. </Layout.Body>
  98. );
  99. }
  100. const {dataset, aggregate, query} = rule;
  101. const eventType = extractEventTypeFilterFromRule(rule);
  102. const queryWithTypeFilter =
  103. dataset === Dataset.EVENTS_ANALYTICS_PLATFORM
  104. ? query
  105. : (query ? `(${query}) AND (${eventType})` : eventType).trim();
  106. const relativeOptions = {
  107. ...SELECTOR_RELATIVE_PERIODS,
  108. ...(rule.timeWindow > 1 ? {[TimePeriod.FOURTEEN_DAYS]: t('Last 14 days')} : {}),
  109. ...(rule.detectionType === AlertRuleComparisonType.DYNAMIC
  110. ? {[TimePeriod.TWENTY_EIGHT_DAYS]: t('Last 28 days')}
  111. : {}),
  112. };
  113. const isSnoozed = rule.snooze;
  114. const ruleActionCategory = getAlertRuleActionCategory(rule);
  115. const showOnDemandMetricAlertUI =
  116. isOnDemandMetricAlert(dataset, aggregate, query) &&
  117. shouldShowOnDemandMetricAlertUI(organization);
  118. const formattedAggregate = aggregate;
  119. return (
  120. <Fragment>
  121. {selectedIncident?.alertRule.status === AlertRuleStatus.SNAPSHOT && (
  122. <StyledLayoutBody>
  123. <Alert type="warning" showIcon>
  124. {t('Alert Rule settings have been updated since this alert was triggered.')}
  125. </Alert>
  126. </StyledLayoutBody>
  127. )}
  128. <Layout.Body>
  129. <Layout.Main>
  130. {isSnoozed && (
  131. <Alert.Container>
  132. <Alert type="warning" showIcon>
  133. {ruleActionCategory === RuleActionsCategories.NO_DEFAULT
  134. ? tct(
  135. "[creator] muted this alert so these notifications won't be sent in the future.",
  136. {creator: rule.snoozeCreatedBy}
  137. )
  138. : tct(
  139. "[creator] muted this alert[forEveryone]so you won't get these notifications in the future.",
  140. {
  141. creator: rule.snoozeCreatedBy,
  142. forEveryone: rule.snoozeForEveryone ? ' for everyone ' : ' ',
  143. }
  144. )}
  145. </Alert>
  146. </Alert.Container>
  147. )}
  148. <StyledSubHeader>
  149. <StyledTimeRangeSelector
  150. relative={timePeriod.period ?? ''}
  151. start={(timePeriod.custom && timePeriod.start) || null}
  152. end={(timePeriod.custom && timePeriod.end) || null}
  153. onChange={handleTimePeriodChange}
  154. relativeOptions={relativeOptions}
  155. showAbsolute={false}
  156. disallowArbitraryRelativeRanges
  157. triggerLabel={
  158. timePeriod.custom
  159. ? timePeriod.label
  160. : // @ts-expect-error TS(7053): Element implicitly has an 'any' type because expre... Remove this comment to see the full error message
  161. relativeOptions[timePeriod.period ?? '']
  162. }
  163. />
  164. {selectedIncident && (
  165. <Tooltip
  166. title={`Click to clear filters`}
  167. isHoverable
  168. containerDisplayMode="inline-flex"
  169. >
  170. <Link
  171. to={{
  172. pathname: alertDetailsLink(organization, selectedIncident),
  173. }}
  174. >
  175. Remove filter on alert #{selectedIncident.identifier}
  176. </Link>
  177. </Tooltip>
  178. )}
  179. </StyledSubHeader>
  180. {selectedIncident?.alertRule.detectionType ===
  181. AlertRuleComparisonType.DYNAMIC && (
  182. <AnomalyDetectionFeedbackBanner
  183. // unique key to force re-render when incident changes
  184. key={selectedIncident.id}
  185. id={selectedIncident.id}
  186. organization={organization}
  187. selectedIncident={selectedIncident}
  188. />
  189. )}
  190. <ErrorMigrationWarning project={project} rule={rule} />
  191. <MetricChart
  192. rule={rule}
  193. incidents={incidents}
  194. anomalies={anomalies}
  195. timePeriod={timePeriod}
  196. formattedAggregate={formattedAggregate}
  197. project={project}
  198. interval={getPeriodInterval(timePeriod, rule)}
  199. query={isCrashFreeAlert(dataset) ? query : queryWithTypeFilter}
  200. filter={getFilter(rule)}
  201. isOnDemandAlert={isOnDemandMetricAlert(dataset, aggregate, query)}
  202. theme={theme}
  203. />
  204. <DetailWrapper>
  205. <ActivityWrapper>
  206. <MetricHistory incidents={incidents} />
  207. {[Dataset.METRICS, Dataset.SESSIONS, Dataset.ERRORS].includes(dataset) && (
  208. <RelatedIssues
  209. organization={organization}
  210. rule={rule}
  211. projects={[project]}
  212. timePeriod={timePeriod}
  213. query={
  214. dataset === Dataset.ERRORS
  215. ? // Not using (query) AND (event.type:x) because issues doesn't support it yet
  216. `${extractEventTypeFilterFromRule(rule)} ${query}`.trim()
  217. : isCrashFreeAlert(dataset)
  218. ? `${query} error.unhandled:true`.trim()
  219. : undefined
  220. }
  221. />
  222. )}
  223. {[Dataset.TRANSACTIONS, Dataset.GENERIC_METRICS].includes(dataset) && (
  224. <RelatedTransactions
  225. organization={organization}
  226. location={location}
  227. rule={rule}
  228. projects={[project]}
  229. timePeriod={timePeriod}
  230. filter={extractEventTypeFilterFromRule(rule)}
  231. />
  232. )}
  233. </ActivityWrapper>
  234. </DetailWrapper>
  235. </Layout.Main>
  236. <Layout.Side>
  237. <MetricDetailsSidebar
  238. rule={rule}
  239. showOnDemandMetricAlertUI={showOnDemandMetricAlertUI}
  240. />
  241. </Layout.Side>
  242. </Layout.Body>
  243. </Fragment>
  244. );
  245. }
  246. const DetailWrapper = styled('div')`
  247. display: flex;
  248. flex: 1;
  249. @media (max-width: ${p => p.theme.breakpoints.small}) {
  250. flex-direction: column-reverse;
  251. }
  252. `;
  253. const StyledLayoutBody = styled(Layout.Body)`
  254. flex-grow: 0;
  255. padding-bottom: 0 !important;
  256. @media (min-width: ${p => p.theme.breakpoints.medium}) {
  257. grid-template-columns: auto;
  258. }
  259. `;
  260. const ActivityWrapper = styled('div')`
  261. display: flex;
  262. flex: 1;
  263. flex-direction: column;
  264. width: 100%;
  265. `;
  266. const ChartPanel = styled(Panel)`
  267. margin-top: ${space(2)};
  268. `;
  269. const StyledSubHeader = styled('div')`
  270. margin-bottom: ${space(2)};
  271. display: flex;
  272. align-items: center;
  273. `;
  274. const StyledTimeRangeSelector = styled(TimeRangeSelector)`
  275. margin-right: ${space(1)};
  276. `;