index.tsx 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274
  1. import {Component, Fragment} from 'react';
  2. import type {RouteComponentProps} from 'react-router';
  3. import type {Location} from 'history';
  4. import isEqual from 'lodash/isEqual';
  5. import pick from 'lodash/pick';
  6. import moment from 'moment';
  7. import {fetchOrgMembers} from 'sentry/actionCreators/members';
  8. import type {Client, ResponseMeta} from 'sentry/api';
  9. import {Alert} from 'sentry/components/alert';
  10. import {DateTime} from 'sentry/components/dateTime';
  11. import * as Layout from 'sentry/components/layouts/thirds';
  12. import PageFiltersContainer from 'sentry/components/organizations/pageFilters/container';
  13. import SentryDocumentTitle from 'sentry/components/sentryDocumentTitle';
  14. import {t} from 'sentry/locale';
  15. import type {Organization, Project} from 'sentry/types';
  16. import {trackAnalytics} from 'sentry/utils/analytics';
  17. import {getUtcDateString} from 'sentry/utils/dates';
  18. import withApi from 'sentry/utils/withApi';
  19. import withProjects from 'sentry/utils/withProjects';
  20. import type {MetricRule} from 'sentry/views/alerts/rules/metric/types';
  21. import {TimePeriod} from 'sentry/views/alerts/rules/metric/types';
  22. import type {Incident} from 'sentry/views/alerts/types';
  23. import {
  24. fetchAlertRule,
  25. fetchIncident,
  26. fetchIncidentsForRule,
  27. } from 'sentry/views/alerts/utils/apiCalls';
  28. import MetricDetailsBody from './body';
  29. import type {TimePeriodType} from './constants';
  30. import {TIME_OPTIONS, TIME_WINDOWS} from './constants';
  31. import DetailsHeader from './header';
  32. import {buildMetricGraphDateRange} from './utils';
  33. interface Props extends RouteComponentProps<{ruleId: string}, {}> {
  34. api: Client;
  35. location: Location;
  36. organization: Organization;
  37. projects: Project[];
  38. loadingProjects?: boolean;
  39. }
  40. interface State {
  41. error: ResponseMeta | null;
  42. hasError: boolean;
  43. isLoading: boolean;
  44. selectedIncident: Incident | null;
  45. incidents?: Incident[];
  46. rule?: MetricRule;
  47. }
  48. class MetricAlertDetails extends Component<Props, State> {
  49. state: State = {isLoading: false, hasError: false, error: null, selectedIncident: null};
  50. componentDidMount() {
  51. const {api, organization} = this.props;
  52. fetchOrgMembers(api, organization.slug);
  53. this.fetchData();
  54. this.trackView();
  55. }
  56. componentDidUpdate(prevProps: Props) {
  57. const prevQuery = pick(prevProps.location.query, ['start', 'end', 'period', 'alert']);
  58. const nextQuery = pick(this.props.location.query, [
  59. 'start',
  60. 'end',
  61. 'period',
  62. 'alert',
  63. ]);
  64. if (
  65. !isEqual(prevQuery, nextQuery) ||
  66. prevProps.organization.slug !== this.props.organization.slug ||
  67. prevProps.params.ruleId !== this.props.params.ruleId
  68. ) {
  69. this.fetchData();
  70. this.trackView();
  71. }
  72. }
  73. trackView() {
  74. const {params, organization, location} = this.props;
  75. trackAnalytics('alert_rule_details.viewed', {
  76. organization,
  77. rule_id: parseInt(params.ruleId, 10),
  78. alert: (location.query.alert as string) ?? '',
  79. has_chartcuterie: organization.features
  80. .includes('metric-alert-chartcuterie')
  81. .toString(),
  82. });
  83. }
  84. getTimePeriod(selectedIncident: Incident | null): TimePeriodType {
  85. const {location} = this.props;
  86. const period = (location.query.period as string) ?? TimePeriod.SEVEN_DAYS;
  87. if (location.query.start && location.query.end) {
  88. return {
  89. start: location.query.start as string,
  90. end: location.query.end as string,
  91. period,
  92. usingPeriod: false,
  93. label: t('Custom time'),
  94. display: (
  95. <Fragment>
  96. <DateTime date={moment.utc(location.query.start)} />
  97. {' — '}
  98. <DateTime date={moment.utc(location.query.end)} />
  99. </Fragment>
  100. ),
  101. custom: true,
  102. };
  103. }
  104. if (location.query.alert && selectedIncident) {
  105. const {start, end} = buildMetricGraphDateRange(selectedIncident);
  106. return {
  107. start,
  108. end,
  109. period,
  110. usingPeriod: false,
  111. label: t('Custom time'),
  112. display: (
  113. <Fragment>
  114. <DateTime date={moment.utc(start)} />
  115. {' — '}
  116. <DateTime date={moment.utc(end)} />
  117. </Fragment>
  118. ),
  119. custom: true,
  120. };
  121. }
  122. const timeOption =
  123. TIME_OPTIONS.find(item => item.value === period) ?? TIME_OPTIONS[1];
  124. const start = getUtcDateString(
  125. moment(moment.utc().diff(TIME_WINDOWS[timeOption.value]))
  126. );
  127. const end = getUtcDateString(moment.utc());
  128. return {
  129. start,
  130. end,
  131. period,
  132. usingPeriod: true,
  133. label: timeOption.label as string,
  134. display: timeOption.label as string,
  135. };
  136. }
  137. onSnooze = ({
  138. snooze,
  139. snoozeCreatedBy,
  140. snoozeForEveryone,
  141. }: {
  142. snooze: boolean;
  143. snoozeCreatedBy?: string;
  144. snoozeForEveryone?: boolean;
  145. }) => {
  146. if (this.state.rule) {
  147. const rule = {...this.state.rule, snooze, snoozeCreatedBy, snoozeForEveryone};
  148. this.setState({rule});
  149. }
  150. };
  151. fetchData = async () => {
  152. const {
  153. api,
  154. organization,
  155. params: {ruleId},
  156. location,
  157. } = this.props;
  158. this.setState({isLoading: true, hasError: false});
  159. // Skip loading existing rule
  160. const rulePromise =
  161. ruleId === this.state.rule?.id
  162. ? Promise.resolve(this.state.rule)
  163. : fetchAlertRule(organization.slug, ruleId, {expand: 'latestIncident'});
  164. // Fetch selected incident, if it exists. We need this to set the selected date range
  165. let selectedIncident: Incident | null = null;
  166. if (location.query.alert) {
  167. try {
  168. selectedIncident = await fetchIncident(
  169. api,
  170. organization.slug,
  171. location.query.alert as string
  172. );
  173. } catch {
  174. // TODO: selectedIncident specific error
  175. }
  176. }
  177. const timePeriod = this.getTimePeriod(selectedIncident);
  178. const {start, end} = timePeriod;
  179. try {
  180. const [incidents, rule] = await Promise.all([
  181. fetchIncidentsForRule(organization.slug, ruleId, start, end),
  182. rulePromise,
  183. ]);
  184. this.setState({
  185. incidents,
  186. rule,
  187. selectedIncident,
  188. isLoading: false,
  189. hasError: false,
  190. });
  191. } catch (error) {
  192. this.setState({selectedIncident, isLoading: false, hasError: true, error});
  193. }
  194. };
  195. renderError() {
  196. const {error} = this.state;
  197. return (
  198. <Layout.Page withPadding>
  199. <Alert type="error" showIcon>
  200. {error?.status === 404
  201. ? t('This alert rule could not be found.')
  202. : t('An error occurred while fetching the alert rule.')}
  203. </Alert>
  204. </Layout.Page>
  205. );
  206. }
  207. render() {
  208. const {rule, incidents, hasError, selectedIncident} = this.state;
  209. const {organization, projects, loadingProjects} = this.props;
  210. const timePeriod = this.getTimePeriod(selectedIncident);
  211. if (hasError) {
  212. return this.renderError();
  213. }
  214. const project = projects.find(({slug}) => slug === rule?.projects[0]) as
  215. | Project
  216. | undefined;
  217. const isGlobalSelectionReady = project !== undefined && !loadingProjects;
  218. return (
  219. <PageFiltersContainer
  220. skipLoadLastUsed
  221. skipInitializeUrlParams
  222. shouldForceProject={isGlobalSelectionReady}
  223. forceProject={project}
  224. >
  225. <SentryDocumentTitle title={rule?.name ?? ''} />
  226. <DetailsHeader
  227. hasMetricRuleDetailsError={hasError}
  228. organization={organization}
  229. rule={rule}
  230. project={project}
  231. onSnooze={this.onSnooze}
  232. />
  233. <MetricDetailsBody
  234. {...this.props}
  235. rule={rule}
  236. project={project}
  237. incidents={incidents}
  238. timePeriod={timePeriod}
  239. selectedIncident={selectedIncident}
  240. />
  241. </PageFiltersContainer>
  242. );
  243. }
  244. }
  245. export default withApi(withProjects(MetricAlertDetails));