index.tsx 9.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335
  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 {Button} from 'sentry/components/button';
  8. import CreateAlertButton from 'sentry/components/createAlertButton';
  9. import DeprecatedAsyncComponent from 'sentry/components/deprecatedAsyncComponent';
  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/panelTable';
  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 DeprecatedAsyncComponent<
  46. Props,
  47. State & DeprecatedAsyncComponent['state']
  48. > {
  49. getEndpoints(): ReturnType<DeprecatedAsyncComponent['getEndpoints']> {
  50. const {organization, location} = this.props;
  51. const {query} = location;
  52. const status = getQueryStatus(query.status);
  53. return [
  54. [
  55. 'incidentList',
  56. `/organizations/${organization.slug}/incidents/`,
  57. {
  58. query: {
  59. ...query,
  60. status: status === 'all' ? undefined : status,
  61. team: getTeamParams(query.team),
  62. expand: ['original_alert_rule'],
  63. },
  64. },
  65. ],
  66. ];
  67. }
  68. /**
  69. * If our incidentList is empty, determine if we've configured alert rules or
  70. * if the user has seen the welcome prompt.
  71. */
  72. async onLoadAllEndpointsSuccess() {
  73. const {incidentList} = this.state;
  74. if (!incidentList || incidentList.length !== 0) {
  75. this.setState({hasAlertRule: true, firstVisitShown: false});
  76. return;
  77. }
  78. this.setState({loading: true});
  79. // Check if they have rules or not, to know which empty state message to
  80. // display
  81. const {location, organization} = this.props;
  82. const alertRules = await this.api.requestPromise(
  83. `/organizations/${organization.slug}/alert-rules/`,
  84. {
  85. method: 'GET',
  86. query: location.query,
  87. }
  88. );
  89. const hasAlertRule = alertRules.length > 0;
  90. // We've already configured alert rules, no need to check if we should show
  91. // the "first time welcome" prompt
  92. if (hasAlertRule) {
  93. this.setState({hasAlertRule, firstVisitShown: false, loading: false});
  94. return;
  95. }
  96. // Check if they have already seen the prompt for the alert stream
  97. const prompt = await promptsCheck(this.api, {
  98. organizationId: organization.id,
  99. feature: 'alert_stream',
  100. });
  101. const firstVisitShown = !prompt?.dismissedTime;
  102. if (firstVisitShown) {
  103. // Prompt has not been seen, mark the prompt as seen immediately so they
  104. // don't see it again
  105. promptsUpdate(this.api, {
  106. feature: 'alert_stream',
  107. organizationId: organization.id,
  108. status: 'dismissed',
  109. });
  110. }
  111. this.setState({hasAlertRule, firstVisitShown, loading: false});
  112. }
  113. get projectsFromIncidents() {
  114. const {incidentList} = this.state;
  115. return [...new Set(incidentList?.map(({projects}) => projects).flat())];
  116. }
  117. handleChangeSearch = (title: string) => {
  118. const {router, location} = this.props;
  119. const {cursor: _cursor, page: _page, ...currentQuery} = location.query;
  120. router.push({
  121. pathname: location.pathname,
  122. query: {
  123. ...currentQuery,
  124. title,
  125. },
  126. });
  127. };
  128. handleChangeFilter = (activeFilters: string[]) => {
  129. const {router, location} = this.props;
  130. const {cursor: _cursor, page: _page, ...currentQuery} = location.query;
  131. router.push({
  132. pathname: location.pathname,
  133. query: {
  134. ...currentQuery,
  135. // Preserve empty team query parameter
  136. team: activeFilters.length > 0 ? activeFilters : '',
  137. },
  138. });
  139. };
  140. handleChangeStatus = (value: string): void => {
  141. const {router, location} = this.props;
  142. const {cursor: _cursor, page: _page, ...currentQuery} = location.query;
  143. router.push({
  144. pathname: location.pathname,
  145. query: {
  146. ...currentQuery,
  147. status: value === 'all' ? undefined : value,
  148. },
  149. });
  150. };
  151. tryRenderOnboarding() {
  152. const {firstVisitShown} = this.state;
  153. const {organization} = this.props;
  154. if (!firstVisitShown) {
  155. return null;
  156. }
  157. const actions = (
  158. <Fragment>
  159. <Button size="sm" external href={DOCS_URL}>
  160. {t('View Features')}
  161. </Button>
  162. <CreateAlertButton
  163. organization={organization}
  164. iconProps={{size: 'xs'}}
  165. size="sm"
  166. priority="primary"
  167. referrer="alert_stream"
  168. >
  169. {t('Create Alert')}
  170. </CreateAlertButton>
  171. </Fragment>
  172. );
  173. return <Onboarding actions={actions} />;
  174. }
  175. renderLoading() {
  176. return this.renderBody();
  177. }
  178. renderList() {
  179. const {loading, incidentList, incidentListPageLinks, hasAlertRule} = this.state;
  180. const {organization} = 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={organization.slug} 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 {organization, router, location} = this.props;
  228. return (
  229. <SentryDocumentTitle title={t('Alerts')} orgSlug={organization.slug}>
  230. <PageFiltersContainer>
  231. <AlertHeader router={router} activeTab="stream" />
  232. <Layout.Body>
  233. <Layout.Main fullWidth>
  234. {!this.tryRenderOnboarding() && (
  235. <Fragment>
  236. <StyledAlert showIcon>
  237. {t('This page only shows metric alerts.')}
  238. </StyledAlert>
  239. <FilterBar
  240. location={location}
  241. onChangeFilter={this.handleChangeFilter}
  242. onChangeSearch={this.handleChangeSearch}
  243. onChangeStatus={this.handleChangeStatus}
  244. hasStatusFilters
  245. />
  246. </Fragment>
  247. )}
  248. {this.renderList()}
  249. </Layout.Main>
  250. </Layout.Body>
  251. </PageFiltersContainer>
  252. </SentryDocumentTitle>
  253. );
  254. }
  255. }
  256. function IncidentsListContainer(props: Props) {
  257. useEffect(() => {
  258. trackAnalytics('alert_stream.viewed', {
  259. organization: props.organization,
  260. });
  261. // eslint-disable-next-line react-hooks/exhaustive-deps
  262. }, []);
  263. const renderDisabled = () => (
  264. <Layout.Body>
  265. <Layout.Main fullWidth>
  266. <Alert type="warning">{t("You don't have access to this feature")}</Alert>
  267. </Layout.Main>
  268. </Layout.Body>
  269. );
  270. return (
  271. <Feature
  272. features={['incidents']}
  273. hookName="feature-disabled:alerts-page"
  274. renderDisabled={renderDisabled}
  275. >
  276. <IncidentsList {...props} />
  277. </Feature>
  278. );
  279. }
  280. const StyledPanelTable = styled(PanelTable)`
  281. font-size: ${p => p.theme.fontSizeMedium};
  282. & > div {
  283. padding: ${space(1.5)} ${space(2)};
  284. }
  285. `;
  286. const StyledAlert = styled(Alert)`
  287. margin-bottom: ${space(1.5)};
  288. `;
  289. const EmptyStateAction = styled('p')`
  290. font-size: ${p => p.theme.fontSizeLarge};
  291. `;
  292. export default IncidentsListContainer;