index.tsx 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464
  1. import {Component, Fragment} from 'react';
  2. import {RouteComponentProps} from 'react-router';
  3. import styled from '@emotion/styled';
  4. import {LocationDescriptorObject} from 'history';
  5. import omit from 'lodash/omit';
  6. import pick from 'lodash/pick';
  7. import moment from 'moment';
  8. import {DateTimeObject} from 'sentry/components/charts/utils';
  9. import CompactSelect from 'sentry/components/compactSelect';
  10. import DatePageFilter from 'sentry/components/datePageFilter';
  11. import ErrorBoundary from 'sentry/components/errorBoundary';
  12. import HookOrDefault from 'sentry/components/hookOrDefault';
  13. import * as Layout from 'sentry/components/layouts/thirds';
  14. import ExternalLink from 'sentry/components/links/externalLink';
  15. import PageFilterBar from 'sentry/components/organizations/pageFilterBar';
  16. import PageFiltersContainer from 'sentry/components/organizations/pageFilters/container';
  17. import {normalizeDateTimeParams} from 'sentry/components/organizations/pageFilters/parse';
  18. import {ChangeData} from 'sentry/components/organizations/timeRangeSelector';
  19. import PageTimeRangeSelector from 'sentry/components/pageTimeRangeSelector';
  20. import ProjectPageFilter from 'sentry/components/projectPageFilter';
  21. import SentryDocumentTitle from 'sentry/components/sentryDocumentTitle';
  22. import {
  23. DATA_CATEGORY_NAMES,
  24. DEFAULT_RELATIVE_PERIODS,
  25. DEFAULT_STATS_PERIOD,
  26. } from 'sentry/constants';
  27. import {ALL_ACCESS_PROJECTS} from 'sentry/constants/pageFilters';
  28. import {t, tct} from 'sentry/locale';
  29. import space from 'sentry/styles/space';
  30. import {DataCategory, DateString, Organization, PageFilters, Project} from 'sentry/types';
  31. import withOrganization from 'sentry/utils/withOrganization';
  32. import withPageFilters from 'sentry/utils/withPageFilters';
  33. import HeaderTabs from 'sentry/views/organizationStats/header';
  34. import {CHART_OPTIONS_DATACATEGORY, ChartDataTransform} from './usageChart';
  35. import UsageStatsOrg from './usageStatsOrg';
  36. import UsageStatsProjects from './usageStatsProjects';
  37. const HookHeader = HookOrDefault({hookName: 'component:org-stats-banner'});
  38. export const PAGE_QUERY_PARAMS = [
  39. // From DatePageFilter
  40. 'statsPeriod',
  41. 'start',
  42. 'end',
  43. 'utc',
  44. // TODO(Leander): Remove date selector props once project-stats flag is GA
  45. 'pageEnd',
  46. 'pageStart',
  47. 'pageStatsPeriod',
  48. 'pageStatsUtc',
  49. // From data category selector
  50. 'dataCategory',
  51. // From UsageOrganizationStats
  52. 'transform',
  53. // From UsageProjectStats
  54. 'sort',
  55. 'query',
  56. 'cursor',
  57. ];
  58. type Props = {
  59. organization: Organization;
  60. selection: PageFilters;
  61. } & RouteComponentProps<{}, {}>;
  62. export class OrganizationStats extends Component<Props> {
  63. get dataCategory(): DataCategory {
  64. const dataCategory = this.props.location?.query?.dataCategory;
  65. switch (dataCategory) {
  66. case DataCategory.ERRORS:
  67. case DataCategory.TRANSACTIONS:
  68. case DataCategory.ATTACHMENTS:
  69. case DataCategory.PROFILES:
  70. case DataCategory.REPLAYS:
  71. return dataCategory as DataCategory;
  72. default:
  73. return DataCategory.ERRORS;
  74. }
  75. }
  76. get dataCategoryName(): string {
  77. const dataCategory = this.dataCategory;
  78. return DATA_CATEGORY_NAMES[dataCategory] ?? t('Unknown Data Category');
  79. }
  80. get dataDatetime(): DateTimeObject {
  81. const params = this.hasProjectStats
  82. ? this.props.selection.datetime
  83. : this.props.location?.query ?? {};
  84. const {
  85. start,
  86. end,
  87. statsPeriod,
  88. utc: utcString,
  89. } = normalizeDateTimeParams(params, {
  90. allowEmptyPeriod: true,
  91. allowAbsoluteDatetime: true,
  92. allowAbsolutePageDatetime: true,
  93. });
  94. if (!statsPeriod && !start && !end) {
  95. return {period: DEFAULT_STATS_PERIOD};
  96. }
  97. // Following getParams, statsPeriod will take priority over start/end
  98. if (statsPeriod) {
  99. return {period: statsPeriod};
  100. }
  101. const utc = utcString === 'true';
  102. if (start && end) {
  103. return utc
  104. ? {
  105. start: moment.utc(start).format(),
  106. end: moment.utc(end).format(),
  107. utc,
  108. }
  109. : {
  110. start: moment(start).utc().format(),
  111. end: moment(end).utc().format(),
  112. utc,
  113. };
  114. }
  115. return {period: DEFAULT_STATS_PERIOD};
  116. }
  117. // Validation and type-casting should be handled by chart
  118. get chartTransform(): string | undefined {
  119. return this.props.location?.query?.transform;
  120. }
  121. // Validation and type-casting should be handled by table
  122. get tableSort(): string | undefined {
  123. return this.props.location?.query?.sort;
  124. }
  125. get tableQuery(): string | undefined {
  126. return this.props.location?.query?.query;
  127. }
  128. get tableCursor(): string | undefined {
  129. return this.props.location?.query?.cursor;
  130. }
  131. // Project selection from GlobalSelectionHeader
  132. get projectIds(): number[] {
  133. const selection_projects = this.props.selection.projects.length
  134. ? this.props.selection.projects
  135. : [ALL_ACCESS_PROJECTS];
  136. return this.hasProjectStats ? selection_projects : [ALL_ACCESS_PROJECTS];
  137. }
  138. /**
  139. * Note: For now, we're checking for both project-stats and global-views to enable this new UI
  140. * This may change once we GA the project-stats feature flag. These are the planned scenarios:
  141. * - w/o global-views: Project Selector defaults to first project, hence no more 'Org Stats' w/o global-views
  142. * - w/ global-views: Project Selector defaults to 'My Projects', behaviour for 'Org Stats' is preserved
  143. */
  144. get hasProjectStats(): boolean {
  145. return ['project-stats', 'global-views'].every(flag =>
  146. this.props.organization.features.includes(flag)
  147. );
  148. }
  149. getNextLocations = (project: Project): Record<string, LocationDescriptorObject> => {
  150. const {location, organization} = this.props;
  151. const nextLocation: LocationDescriptorObject = {
  152. ...location,
  153. query: {
  154. ...location.query,
  155. project: project.id,
  156. },
  157. };
  158. // Do not leak out page-specific keys
  159. nextLocation.query = omit(nextLocation.query, PAGE_QUERY_PARAMS);
  160. return {
  161. performance: {
  162. ...nextLocation,
  163. pathname: `/organizations/${organization.slug}/performance/`,
  164. },
  165. projectDetail: {
  166. ...nextLocation,
  167. pathname: `/organizations/${organization.slug}/projects/${project.slug}/`,
  168. },
  169. issueList: {
  170. ...nextLocation,
  171. pathname: `/organizations/${organization.slug}/issues/`,
  172. },
  173. settings: {
  174. pathname: `/settings/${organization.slug}/projects/${project.slug}/`,
  175. },
  176. };
  177. };
  178. /**
  179. * See PAGE_QUERY_PARAMS for list of accepted keys on nextState
  180. */
  181. setStateOnUrl = (
  182. nextState: {
  183. cursor?: string;
  184. dataCategory?: DataCategory;
  185. // TODO(Leander): Remove date selector props once project-stats flag is GA
  186. pageEnd?: DateString;
  187. pageStart?: DateString;
  188. pageStatsPeriod?: string | null;
  189. pageStatsUtc?: string | null;
  190. pageUtc?: boolean | null;
  191. query?: string;
  192. sort?: string;
  193. transform?: ChartDataTransform;
  194. },
  195. options: {
  196. willUpdateRouter?: boolean;
  197. } = {
  198. willUpdateRouter: true,
  199. }
  200. ): LocationDescriptorObject => {
  201. const {location, router} = this.props;
  202. const nextQueryParams = pick(nextState, PAGE_QUERY_PARAMS);
  203. const nextLocation = {
  204. ...location,
  205. query: {
  206. ...location?.query,
  207. ...nextQueryParams,
  208. },
  209. };
  210. if (options.willUpdateRouter) {
  211. router.push(nextLocation);
  212. }
  213. return nextLocation;
  214. };
  215. renderProjectPageControl = () => {
  216. const {organization} = this.props;
  217. if (!this.hasProjectStats) {
  218. return null;
  219. }
  220. const hasReplay = organization.features.includes('session-replay-ui');
  221. const options = hasReplay
  222. ? CHART_OPTIONS_DATACATEGORY
  223. : CHART_OPTIONS_DATACATEGORY.filter(opt => opt.value !== DataCategory.REPLAYS);
  224. return (
  225. <PageControl>
  226. <PageFilterBar>
  227. <ProjectPageFilter />
  228. <DropdownDataCategory
  229. triggerProps={{prefix: t('Category')}}
  230. value={this.dataCategory}
  231. options={options}
  232. onChange={opt =>
  233. this.setStateOnUrl({dataCategory: opt.value as DataCategory})
  234. }
  235. />
  236. <DatePageFilter alignDropdown="left" />
  237. </PageFilterBar>
  238. </PageControl>
  239. );
  240. };
  241. // TODO(Leander): Remove the following method once the project-stats flag is GA
  242. handleUpdateDatetime = (datetime: ChangeData): LocationDescriptorObject => {
  243. const {start, end, relative, utc} = datetime;
  244. if (start && end) {
  245. const parser = utc ? moment.utc : moment;
  246. return this.setStateOnUrl({
  247. pageStatsPeriod: undefined,
  248. pageStart: parser(start).format(),
  249. pageEnd: parser(end).format(),
  250. pageUtc: utc ?? undefined,
  251. });
  252. }
  253. return this.setStateOnUrl({
  254. pageStatsPeriod: relative || undefined,
  255. pageStart: undefined,
  256. pageEnd: undefined,
  257. pageUtc: undefined,
  258. });
  259. };
  260. // TODO(Leander): Remove the following method once the project-stats flag is GA
  261. renderPageControl = () => {
  262. const {organization} = this.props;
  263. if (this.hasProjectStats) {
  264. return null;
  265. }
  266. const {start, end, period, utc} = this.dataDatetime;
  267. const hasReplay = organization.features.includes('session-replay-ui');
  268. const options = hasReplay
  269. ? CHART_OPTIONS_DATACATEGORY
  270. : CHART_OPTIONS_DATACATEGORY.filter(opt => opt.value !== DataCategory.REPLAYS);
  271. return (
  272. <Fragment>
  273. <DropdownDataCategory
  274. triggerProps={{prefix: t('Category')}}
  275. value={this.dataCategory}
  276. options={options}
  277. onChange={opt => this.setStateOnUrl({dataCategory: opt.value as DataCategory})}
  278. />
  279. <StyledPageTimeRangeSelector
  280. organization={organization}
  281. relative={period ?? ''}
  282. start={start ?? null}
  283. end={end ?? null}
  284. utc={utc ?? null}
  285. onUpdate={this.handleUpdateDatetime}
  286. relativeOptions={omit(DEFAULT_RELATIVE_PERIODS, ['1h'])}
  287. />
  288. </Fragment>
  289. );
  290. };
  291. render() {
  292. const {organization} = this.props;
  293. const hasTeamInsights = organization.features.includes('team-insights');
  294. // We only show UsageProjectStats if multiple projects are selected
  295. const shouldRenderProjectStats = this.hasProjectStats
  296. ? this.projectIds.includes(-1) || this.projectIds.length !== 1
  297. : // Always render if they don't have the proper flags
  298. true;
  299. return (
  300. <SentryDocumentTitle title="Usage Stats">
  301. <PageFiltersContainer>
  302. {hasTeamInsights ? (
  303. <HeaderTabs organization={organization} activeTab="stats" />
  304. ) : (
  305. <Layout.Header>
  306. <Layout.HeaderContent>
  307. <Layout.Title>{t('Organization Usage Stats')}</Layout.Title>
  308. <HeadingSubtitle>
  309. {tct(
  310. 'A view of the usage data that Sentry has received across your entire organization. [link: Read the docs].',
  311. {
  312. link: <ExternalLink href="https://docs.sentry.io/product/stats/" />,
  313. }
  314. )}
  315. </HeadingSubtitle>
  316. </Layout.HeaderContent>
  317. </Layout.Header>
  318. )}
  319. <Body>
  320. <Layout.Main fullWidth>
  321. <HookHeader organization={organization} />
  322. {this.renderProjectPageControl()}
  323. <PageGrid>
  324. {this.renderPageControl()}
  325. <ErrorBoundary mini>
  326. <UsageStatsOrg
  327. organization={organization}
  328. dataCategory={this.dataCategory}
  329. dataCategoryName={this.dataCategoryName}
  330. dataDatetime={this.dataDatetime}
  331. chartTransform={this.chartTransform}
  332. handleChangeState={this.setStateOnUrl}
  333. projectIds={this.projectIds}
  334. />
  335. </ErrorBoundary>
  336. </PageGrid>
  337. {shouldRenderProjectStats && (
  338. <ErrorBoundary mini>
  339. <UsageStatsProjects
  340. organization={organization}
  341. dataCategory={this.dataCategory}
  342. dataCategoryName={this.dataCategoryName}
  343. projectIds={this.projectIds}
  344. dataDatetime={this.dataDatetime}
  345. tableSort={this.tableSort}
  346. tableQuery={this.tableQuery}
  347. tableCursor={this.tableCursor}
  348. handleChangeState={this.setStateOnUrl}
  349. getNextLocations={this.getNextLocations}
  350. />
  351. </ErrorBoundary>
  352. )}
  353. </Layout.Main>
  354. </Body>
  355. </PageFiltersContainer>
  356. </SentryDocumentTitle>
  357. );
  358. }
  359. }
  360. export default withPageFilters(withOrganization(OrganizationStats));
  361. const PageGrid = styled('div')`
  362. display: grid;
  363. grid-template-columns: 1fr;
  364. gap: ${space(2)};
  365. @media (min-width: ${p => p.theme.breakpoints.small}) {
  366. grid-template-columns: repeat(2, 1fr);
  367. }
  368. @media (min-width: ${p => p.theme.breakpoints.large}) {
  369. grid-template-columns: repeat(4, 1fr);
  370. }
  371. `;
  372. const DropdownDataCategory = styled(CompactSelect)`
  373. grid-column: auto / span 1;
  374. button[aria-haspopup='listbox'] {
  375. width: 100%;
  376. height: 100%;
  377. }
  378. @media (min-width: ${p => p.theme.breakpoints.small}) {
  379. grid-column: auto / span 2;
  380. }
  381. @media (min-width: ${p => p.theme.breakpoints.large}) {
  382. grid-column: auto / span 1;
  383. }
  384. `;
  385. const StyledPageTimeRangeSelector = styled(PageTimeRangeSelector)`
  386. grid-column: auto / span 1;
  387. @media (min-width: ${p => p.theme.breakpoints.small}) {
  388. grid-column: auto / span 2;
  389. }
  390. @media (min-width: ${p => p.theme.breakpoints.large}) {
  391. grid-column: auto / span 3;
  392. }
  393. `;
  394. const Body = styled(Layout.Body)`
  395. @media (min-width: ${p => p.theme.breakpoints.medium}) {
  396. display: block;
  397. }
  398. `;
  399. const HeadingSubtitle = styled('p')`
  400. margin-top: ${space(0.5)};
  401. margin-bottom: 0;
  402. `;
  403. const PageControl = styled('div')`
  404. display: grid;
  405. width: 100%;
  406. margin-bottom: ${space(2)};
  407. grid-template-columns: minmax(0, max-content);
  408. @media (max-width: ${p => p.theme.breakpoints.small}) {
  409. grid-template-columns: minmax(0, 1fr);
  410. }
  411. `;