index.tsx 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332
  1. import {Fragment, useEffect} from 'react';
  2. import {RouteComponentProps} from 'react-router';
  3. import styled from '@emotion/styled';
  4. import {promptsCheck, promptsUpdate} from 'sentry/actionCreators/prompts';
  5. import Feature from 'sentry/components/acl/feature';
  6. import Alert from 'sentry/components/alert';
  7. import AsyncComponent from 'sentry/components/asyncComponent';
  8. import Button from 'sentry/components/button';
  9. import CreateAlertButton from 'sentry/components/createAlertButton';
  10. import * as Layout from 'sentry/components/layouts/thirds';
  11. import ExternalLink from 'sentry/components/links/externalLink';
  12. import PageFiltersContainer from 'sentry/components/organizations/pageFilters/container';
  13. import Pagination from 'sentry/components/pagination';
  14. import {PanelTable} from 'sentry/components/panels';
  15. import SentryDocumentTitle from 'sentry/components/sentryDocumentTitle';
  16. import {t, tct} from 'sentry/locale';
  17. import space from 'sentry/styles/space';
  18. import {Organization, Project} from 'sentry/types';
  19. import trackAdvancedAnalyticsEvent from 'sentry/utils/analytics/trackAdvancedAnalyticsEvent';
  20. import Projects from 'sentry/utils/projects';
  21. import FilterBar from '../../filterBar';
  22. import {Incident} from '../../types';
  23. import {getQueryStatus, getTeamParams} from '../../utils';
  24. import AlertHeader from '../header';
  25. import Onboarding from '../onboarding';
  26. import AlertListRow from './row';
  27. const DOCS_URL =
  28. 'https://docs.sentry.io/workflow/alerts-notifications/alerts/?_ga=2.21848383.580096147.1592364314-1444595810.1582160976';
  29. type Props = RouteComponentProps<{orgId: string}, {}> & {
  30. organization: Organization;
  31. };
  32. type State = {
  33. incidentList: Incident[];
  34. /**
  35. * User has not yet seen the 'alert_stream' welcome prompt for this
  36. * organization.
  37. */
  38. firstVisitShown?: boolean;
  39. /**
  40. * Is there at least one alert rule configured for the currently selected
  41. * projects?
  42. */
  43. hasAlertRule?: boolean;
  44. };
  45. class IncidentsList extends AsyncComponent<Props, State & AsyncComponent['state']> {
  46. getEndpoints(): ReturnType<AsyncComponent['getEndpoints']> {
  47. const {params, location} = this.props;
  48. const {query} = location;
  49. const status = getQueryStatus(query.status);
  50. return [
  51. [
  52. 'incidentList',
  53. `/organizations/${params?.orgId}/incidents/`,
  54. {
  55. query: {
  56. ...query,
  57. status: status === 'all' ? undefined : status,
  58. team: getTeamParams(query.team),
  59. expand: ['original_alert_rule'],
  60. },
  61. },
  62. ],
  63. ];
  64. }
  65. /**
  66. * If our incidentList is empty, determine if we've configured alert rules or
  67. * if the user has seen the welcome prompt.
  68. */
  69. async onLoadAllEndpointsSuccess() {
  70. const {incidentList} = this.state;
  71. if (!incidentList || incidentList.length !== 0) {
  72. this.setState({hasAlertRule: true, firstVisitShown: false});
  73. return;
  74. }
  75. this.setState({loading: true});
  76. // Check if they have rules or not, to know which empty state message to
  77. // display
  78. const {params, location, organization} = this.props;
  79. const alertRules = await this.api.requestPromise(
  80. `/organizations/${params?.orgId}/alert-rules/`,
  81. {
  82. method: 'GET',
  83. query: location.query,
  84. }
  85. );
  86. const hasAlertRule = alertRules.length > 0;
  87. // We've already configured alert rules, no need to check if we should show
  88. // the "first time welcome" prompt
  89. if (hasAlertRule) {
  90. this.setState({hasAlertRule, firstVisitShown: false, loading: false});
  91. return;
  92. }
  93. // Check if they have already seen the prompt for the alert stream
  94. const prompt = await promptsCheck(this.api, {
  95. organizationId: organization.id,
  96. feature: 'alert_stream',
  97. });
  98. const firstVisitShown = !prompt?.dismissedTime;
  99. if (firstVisitShown) {
  100. // Prompt has not been seen, mark the prompt as seen immediately so they
  101. // don't see it again
  102. promptsUpdate(this.api, {
  103. feature: 'alert_stream',
  104. organizationId: organization.id,
  105. status: 'dismissed',
  106. });
  107. }
  108. this.setState({hasAlertRule, firstVisitShown, loading: false});
  109. }
  110. get projectsFromIncidents() {
  111. const {incidentList} = this.state;
  112. return [...new Set(incidentList?.map(({projects}) => projects).flat())];
  113. }
  114. handleChangeSearch = (title: string) => {
  115. const {router, location} = this.props;
  116. const {cursor: _cursor, page: _page, ...currentQuery} = location.query;
  117. router.push({
  118. pathname: location.pathname,
  119. query: {
  120. ...currentQuery,
  121. title,
  122. },
  123. });
  124. };
  125. handleChangeFilter = (activeFilters: string[]) => {
  126. const {router, location} = this.props;
  127. const {cursor: _cursor, page: _page, ...currentQuery} = location.query;
  128. router.push({
  129. pathname: location.pathname,
  130. query: {
  131. ...currentQuery,
  132. // Preserve empty team query parameter
  133. team: activeFilters.length > 0 ? activeFilters : '',
  134. },
  135. });
  136. };
  137. handleChangeStatus = (value: string): void => {
  138. const {router, location} = this.props;
  139. const {cursor: _cursor, page: _page, ...currentQuery} = location.query;
  140. router.push({
  141. pathname: location.pathname,
  142. query: {
  143. ...currentQuery,
  144. status: value === 'all' ? undefined : value,
  145. },
  146. });
  147. };
  148. tryRenderOnboarding() {
  149. const {firstVisitShown} = this.state;
  150. const {organization} = this.props;
  151. if (!firstVisitShown) {
  152. return null;
  153. }
  154. const actions = (
  155. <Fragment>
  156. <Button size="sm" external href={DOCS_URL}>
  157. {t('View Features')}
  158. </Button>
  159. <CreateAlertButton
  160. organization={organization}
  161. iconProps={{size: 'xs'}}
  162. size="sm"
  163. priority="primary"
  164. referrer="alert_stream"
  165. >
  166. {t('Create Alert')}
  167. </CreateAlertButton>
  168. </Fragment>
  169. );
  170. return <Onboarding actions={actions} />;
  171. }
  172. renderLoading() {
  173. return this.renderBody();
  174. }
  175. renderList() {
  176. const {loading, incidentList, incidentListPageLinks, hasAlertRule} = this.state;
  177. const {
  178. params: {orgId},
  179. organization,
  180. } = this.props;
  181. const checkingForAlertRules =
  182. incidentList?.length === 0 && hasAlertRule === undefined;
  183. const showLoadingIndicator = loading || checkingForAlertRules;
  184. return (
  185. <Fragment>
  186. {this.tryRenderOnboarding() ?? (
  187. <StyledPanelTable
  188. isLoading={showLoadingIndicator}
  189. isEmpty={incidentList?.length === 0}
  190. emptyMessage={t('No incidents exist for the current query.')}
  191. emptyAction={
  192. <EmptyStateAction>
  193. {tct('Learn more about [link:Metric Alerts]', {
  194. link: <ExternalLink href={DOCS_URL} />,
  195. })}
  196. </EmptyStateAction>
  197. }
  198. headers={[
  199. t('Alert Rule'),
  200. t('Triggered'),
  201. t('Duration'),
  202. t('Project'),
  203. t('Alert ID'),
  204. t('Team'),
  205. ]}
  206. >
  207. <Projects orgId={orgId} slugs={this.projectsFromIncidents}>
  208. {({initiallyLoaded, projects}) =>
  209. incidentList.map(incident => (
  210. <AlertListRow
  211. key={incident.id}
  212. projectsLoaded={initiallyLoaded}
  213. projects={projects as Project[]}
  214. incident={incident}
  215. organization={organization}
  216. />
  217. ))
  218. }
  219. </Projects>
  220. </StyledPanelTable>
  221. )}
  222. <Pagination pageLinks={incidentListPageLinks} />
  223. </Fragment>
  224. );
  225. }
  226. renderBody() {
  227. const {params, router, location} = this.props;
  228. const {orgId} = params;
  229. return (
  230. <SentryDocumentTitle title={t('Alerts')} orgSlug={orgId}>
  231. <PageFiltersContainer>
  232. <AlertHeader router={router} activeTab="stream" />
  233. <Layout.Body>
  234. <Layout.Main fullWidth>
  235. {!this.tryRenderOnboarding() && (
  236. <Fragment>
  237. <StyledAlert showIcon>
  238. {t('This page only shows metric alerts.')}
  239. </StyledAlert>
  240. <FilterBar
  241. location={location}
  242. onChangeFilter={this.handleChangeFilter}
  243. onChangeSearch={this.handleChangeSearch}
  244. onChangeStatus={this.handleChangeStatus}
  245. hasStatusFilters
  246. />
  247. </Fragment>
  248. )}
  249. {this.renderList()}
  250. </Layout.Main>
  251. </Layout.Body>
  252. </PageFiltersContainer>
  253. </SentryDocumentTitle>
  254. );
  255. }
  256. }
  257. function IncidentsListContainer(props: Props) {
  258. useEffect(() => {
  259. trackAdvancedAnalyticsEvent('alert_stream.viewed', {
  260. organization: props.organization,
  261. });
  262. // eslint-disable-next-line react-hooks/exhaustive-deps
  263. }, []);
  264. const renderDisabled = () => (
  265. <Layout.Body>
  266. <Layout.Main fullWidth>
  267. <Alert type="warning">{t("You don't have access to this feature")}</Alert>
  268. </Layout.Main>
  269. </Layout.Body>
  270. );
  271. return (
  272. <Feature
  273. features={['incidents']}
  274. hookName="feature-disabled:alerts-page"
  275. renderDisabled={renderDisabled}
  276. >
  277. <IncidentsList {...props} />
  278. </Feature>
  279. );
  280. }
  281. const StyledPanelTable = styled(PanelTable)`
  282. font-size: ${p => p.theme.fontSizeMedium};
  283. `;
  284. const StyledAlert = styled(Alert)`
  285. margin-bottom: ${space(1.5)};
  286. `;
  287. const EmptyStateAction = styled('p')`
  288. font-size: ${p => p.theme.fontSizeLarge};
  289. `;
  290. export default IncidentsListContainer;