index.tsx 7.6 KB

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