index.tsx 7.8 KB

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