index.tsx 9.5 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 {trackAnalytics} from 'sentry/utils/analytics';
  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<{}, {}> & {
  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 {organization, location} = this.props;
  48. const {query} = location;
  49. const status = getQueryStatus(query.status);
  50. return [
  51. [
  52. 'incidentList',
  53. `/organizations/${organization.slug}/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 {location, organization} = this.props;
  79. const alertRules = await this.api.requestPromise(
  80. `/organizations/${organization.slug}/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 {organization} = this.props;
  178. const checkingForAlertRules =
  179. incidentList?.length === 0 && hasAlertRule === undefined;
  180. const showLoadingIndicator = loading || checkingForAlertRules;
  181. return (
  182. <Fragment>
  183. {this.tryRenderOnboarding() ?? (
  184. <StyledPanelTable
  185. isLoading={showLoadingIndicator}
  186. isEmpty={incidentList?.length === 0}
  187. emptyMessage={t('No incidents exist for the current query.')}
  188. emptyAction={
  189. <EmptyStateAction>
  190. {tct('Learn more about [link:Metric Alerts]', {
  191. link: <ExternalLink href={DOCS_URL} />,
  192. })}
  193. </EmptyStateAction>
  194. }
  195. headers={[
  196. t('Alert Rule'),
  197. t('Triggered'),
  198. t('Duration'),
  199. t('Project'),
  200. t('Alert ID'),
  201. t('Team'),
  202. ]}
  203. >
  204. <Projects orgId={organization.slug} slugs={this.projectsFromIncidents}>
  205. {({initiallyLoaded, projects}) =>
  206. incidentList.map(incident => (
  207. <AlertListRow
  208. key={incident.id}
  209. projectsLoaded={initiallyLoaded}
  210. projects={projects as Project[]}
  211. incident={incident}
  212. organization={organization}
  213. />
  214. ))
  215. }
  216. </Projects>
  217. </StyledPanelTable>
  218. )}
  219. <Pagination pageLinks={incidentListPageLinks} />
  220. </Fragment>
  221. );
  222. }
  223. renderBody() {
  224. const {organization, router, location} = this.props;
  225. return (
  226. <SentryDocumentTitle title={t('Alerts')} orgSlug={organization.slug}>
  227. <PageFiltersContainer>
  228. <AlertHeader router={router} activeTab="stream" />
  229. <Layout.Body>
  230. <Layout.Main fullWidth>
  231. {!this.tryRenderOnboarding() && (
  232. <Fragment>
  233. <StyledAlert showIcon>
  234. {t('This page only shows metric alerts.')}
  235. </StyledAlert>
  236. <FilterBar
  237. location={location}
  238. onChangeFilter={this.handleChangeFilter}
  239. onChangeSearch={this.handleChangeSearch}
  240. onChangeStatus={this.handleChangeStatus}
  241. hasStatusFilters
  242. />
  243. </Fragment>
  244. )}
  245. {this.renderList()}
  246. </Layout.Main>
  247. </Layout.Body>
  248. </PageFiltersContainer>
  249. </SentryDocumentTitle>
  250. );
  251. }
  252. }
  253. function IncidentsListContainer(props: Props) {
  254. useEffect(() => {
  255. trackAnalytics('alert_stream.viewed', {
  256. organization: props.organization,
  257. });
  258. // eslint-disable-next-line react-hooks/exhaustive-deps
  259. }, []);
  260. const renderDisabled = () => (
  261. <Layout.Body>
  262. <Layout.Main fullWidth>
  263. <Alert type="warning">{t("You don't have access to this feature")}</Alert>
  264. </Layout.Main>
  265. </Layout.Body>
  266. );
  267. return (
  268. <Feature
  269. features={['incidents']}
  270. hookName="feature-disabled:alerts-page"
  271. renderDisabled={renderDisabled}
  272. >
  273. <IncidentsList {...props} />
  274. </Feature>
  275. );
  276. }
  277. const StyledPanelTable = styled(PanelTable)`
  278. font-size: ${p => p.theme.fontSizeMedium};
  279. & > div {
  280. padding: ${space(1.5)} ${space(2)};
  281. }
  282. `;
  283. const StyledAlert = styled(Alert)`
  284. margin-bottom: ${space(1.5)};
  285. `;
  286. const EmptyStateAction = styled('p')`
  287. font-size: ${p => p.theme.fontSizeLarge};
  288. `;
  289. export default IncidentsListContainer;