index.tsx 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440
  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 PageFilterBar from 'sentry/components/organizations/pageFilterBar';
  15. import PageFiltersContainer from 'sentry/components/organizations/pageFilters/container';
  16. import {normalizeDateTimeParams} from 'sentry/components/organizations/pageFilters/parse';
  17. import {ChangeData} from 'sentry/components/organizations/timeRangeSelector';
  18. import PageHeading from 'sentry/components/pageHeading';
  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 {t} from 'sentry/locale';
  28. import {PageHeader} from 'sentry/styles/organization';
  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<{orgId: string}, {}>;
  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. return dataCategory as DataCategory;
  71. default:
  72. return DataCategory.ERRORS;
  73. }
  74. }
  75. get dataCategoryName(): string {
  76. const dataCategory = this.dataCategory;
  77. return DATA_CATEGORY_NAMES[dataCategory] ?? t('Unknown Data Category');
  78. }
  79. get dataDatetime(): DateTimeObject {
  80. const params = this.hasProjectStats
  81. ? this.props.selection.datetime
  82. : this.props.location?.query ?? {};
  83. const {
  84. start,
  85. end,
  86. statsPeriod,
  87. utc: utcString,
  88. } = normalizeDateTimeParams(params, {
  89. allowEmptyPeriod: true,
  90. allowAbsoluteDatetime: true,
  91. allowAbsolutePageDatetime: true,
  92. });
  93. if (!statsPeriod && !start && !end) {
  94. return {period: DEFAULT_STATS_PERIOD};
  95. }
  96. // Following getParams, statsPeriod will take priority over start/end
  97. if (statsPeriod) {
  98. return {period: statsPeriod};
  99. }
  100. const utc = utcString === 'true';
  101. if (start && end) {
  102. return utc
  103. ? {
  104. start: moment.utc(start).format(),
  105. end: moment.utc(end).format(),
  106. utc,
  107. }
  108. : {
  109. start: moment(start).utc().format(),
  110. end: moment(end).utc().format(),
  111. utc,
  112. };
  113. }
  114. return {period: DEFAULT_STATS_PERIOD};
  115. }
  116. // Validation and type-casting should be handled by chart
  117. get chartTransform(): string | undefined {
  118. return this.props.location?.query?.transform;
  119. }
  120. // Validation and type-casting should be handled by table
  121. get tableSort(): string | undefined {
  122. return this.props.location?.query?.sort;
  123. }
  124. get tableQuery(): string | undefined {
  125. return this.props.location?.query?.query;
  126. }
  127. get tableCursor(): string | undefined {
  128. return this.props.location?.query?.cursor;
  129. }
  130. // Project selection from GlobalSelectionHeader
  131. get projectIds(): number[] {
  132. return this.hasProjectStats ? this.props.selection.projects : [];
  133. }
  134. /**
  135. * Note: For now, we're checking for both project-stats and global-views to enable this new UI
  136. * This may change once we GA the project-stats feature flag. These are the planned scenarios:
  137. * - w/o global-views: Project Selector defaults to first project, hence no more 'Org Stats' w/o global-views
  138. * - w/ global-views: Project Selector defaults to 'My Projects', behaviour for 'Org Stats' is preserved
  139. */
  140. get hasProjectStats(): boolean {
  141. return ['project-stats', 'global-views'].every(flag =>
  142. this.props.organization.features.includes(flag)
  143. );
  144. }
  145. getNextLocations = (project: Project): Record<string, LocationDescriptorObject> => {
  146. const {location, organization} = this.props;
  147. const nextLocation: LocationDescriptorObject = {
  148. ...location,
  149. query: {
  150. ...location.query,
  151. project: project.id,
  152. },
  153. };
  154. // Do not leak out page-specific keys
  155. nextLocation.query = omit(nextLocation.query, PAGE_QUERY_PARAMS);
  156. return {
  157. performance: {
  158. ...nextLocation,
  159. pathname: `/organizations/${organization.slug}/performance/`,
  160. },
  161. projectDetail: {
  162. ...nextLocation,
  163. pathname: `/organizations/${organization.slug}/projects/${project.slug}/`,
  164. },
  165. issueList: {
  166. ...nextLocation,
  167. pathname: `/organizations/${organization.slug}/issues/`,
  168. },
  169. settings: {
  170. pathname: `/settings/${organization.slug}/projects/${project.slug}/`,
  171. },
  172. };
  173. };
  174. /**
  175. * See PAGE_QUERY_PARAMS for list of accepted keys on nextState
  176. */
  177. setStateOnUrl = (
  178. nextState: {
  179. cursor?: string;
  180. dataCategory?: DataCategory;
  181. // TODO(Leander): Remove date selector props once project-stats flag is GA
  182. pageEnd?: DateString;
  183. pageStart?: DateString;
  184. pageStatsPeriod?: string | null;
  185. pageStatsUtc?: string | null;
  186. pageUtc?: boolean | null;
  187. query?: string;
  188. sort?: string;
  189. transform?: ChartDataTransform;
  190. },
  191. options: {
  192. willUpdateRouter?: boolean;
  193. } = {
  194. willUpdateRouter: true,
  195. }
  196. ): LocationDescriptorObject => {
  197. const {location, router} = this.props;
  198. const nextQueryParams = pick(nextState, PAGE_QUERY_PARAMS);
  199. const nextLocation = {
  200. ...location,
  201. query: {
  202. ...location?.query,
  203. ...nextQueryParams,
  204. },
  205. };
  206. if (options.willUpdateRouter) {
  207. router.push(nextLocation);
  208. }
  209. return nextLocation;
  210. };
  211. renderProjectPageControl = () => {
  212. if (!this.hasProjectStats) {
  213. return null;
  214. }
  215. return (
  216. <PageControl>
  217. <PageFilterBar>
  218. <ProjectPageFilter />
  219. <DropdownDataCategory
  220. triggerProps={{prefix: t('Category')}}
  221. value={this.dataCategory}
  222. options={CHART_OPTIONS_DATACATEGORY}
  223. onChange={opt =>
  224. this.setStateOnUrl({dataCategory: opt.value as DataCategory})
  225. }
  226. />
  227. <DatePageFilter alignDropdown="left" />
  228. </PageFilterBar>
  229. </PageControl>
  230. );
  231. };
  232. // TODO(Leander): Remove the following method once the project-stats flag is GA
  233. handleUpdateDatetime = (datetime: ChangeData): LocationDescriptorObject => {
  234. const {start, end, relative, utc} = datetime;
  235. if (start && end) {
  236. const parser = utc ? moment.utc : moment;
  237. return this.setStateOnUrl({
  238. pageStatsPeriod: undefined,
  239. pageStart: parser(start).format(),
  240. pageEnd: parser(end).format(),
  241. pageUtc: utc ?? undefined,
  242. });
  243. }
  244. return this.setStateOnUrl({
  245. pageStatsPeriod: relative || undefined,
  246. pageStart: undefined,
  247. pageEnd: undefined,
  248. pageUtc: undefined,
  249. });
  250. };
  251. // TODO(Leander): Remove the following method once the project-stats flag is GA
  252. renderPageControl = () => {
  253. const {organization} = this.props;
  254. if (this.hasProjectStats) {
  255. return null;
  256. }
  257. const {start, end, period, utc} = this.dataDatetime;
  258. return (
  259. <Fragment>
  260. <DropdownDataCategory
  261. triggerProps={{prefix: t('Category')}}
  262. value={this.dataCategory}
  263. options={CHART_OPTIONS_DATACATEGORY}
  264. onChange={opt => this.setStateOnUrl({dataCategory: opt.value as DataCategory})}
  265. />
  266. <StyledPageTimeRangeSelector
  267. organization={organization}
  268. relative={period ?? ''}
  269. start={start ?? null}
  270. end={end ?? null}
  271. utc={utc ?? null}
  272. onUpdate={this.handleUpdateDatetime}
  273. relativeOptions={omit(DEFAULT_RELATIVE_PERIODS, ['1h'])}
  274. />
  275. </Fragment>
  276. );
  277. };
  278. render() {
  279. const {organization} = this.props;
  280. const hasTeamInsights = organization.features.includes('team-insights');
  281. // We only show UsageProjectStats if multiple projects are selected
  282. const shouldRenderProjectStats = this.hasProjectStats
  283. ? this.projectIds.includes(-1) || this.projectIds.length !== 1
  284. : // Always render if they don't have the proper flags
  285. true;
  286. return (
  287. <SentryDocumentTitle title="Usage Stats">
  288. <PageFiltersContainer>
  289. {hasTeamInsights && (
  290. <HeaderTabs organization={organization} activeTab="stats" />
  291. )}
  292. <Body>
  293. <Layout.Main fullWidth>
  294. {!hasTeamInsights && (
  295. <Fragment>
  296. <PageHeader>
  297. <PageHeading>{t('Organization Usage Stats')}</PageHeading>
  298. </PageHeader>
  299. <p>
  300. {t(
  301. 'We collect usage metrics on three categories: errors, transactions, and attachments. The charts below reflect data that Sentry has received across your entire organization. You can also find them broken down by project in the table.'
  302. )}
  303. </p>
  304. </Fragment>
  305. )}
  306. <HookHeader organization={organization} />
  307. {this.renderProjectPageControl()}
  308. <PageGrid>
  309. {this.renderPageControl()}
  310. <ErrorBoundary mini>
  311. <UsageStatsOrg
  312. organization={organization}
  313. dataCategory={this.dataCategory}
  314. dataCategoryName={this.dataCategoryName}
  315. dataDatetime={this.dataDatetime}
  316. chartTransform={this.chartTransform}
  317. handleChangeState={this.setStateOnUrl}
  318. projectIds={this.projectIds}
  319. />
  320. </ErrorBoundary>
  321. </PageGrid>
  322. {shouldRenderProjectStats && (
  323. <ErrorBoundary mini>
  324. <UsageStatsProjects
  325. organization={organization}
  326. dataCategory={this.dataCategory}
  327. dataCategoryName={this.dataCategoryName}
  328. projectIds={this.projectIds}
  329. dataDatetime={this.dataDatetime}
  330. tableSort={this.tableSort}
  331. tableQuery={this.tableQuery}
  332. tableCursor={this.tableCursor}
  333. handleChangeState={this.setStateOnUrl}
  334. getNextLocations={this.getNextLocations}
  335. />
  336. </ErrorBoundary>
  337. )}
  338. </Layout.Main>
  339. </Body>
  340. </PageFiltersContainer>
  341. </SentryDocumentTitle>
  342. );
  343. }
  344. }
  345. export default withPageFilters(withOrganization(OrganizationStats));
  346. const PageGrid = styled('div')`
  347. display: grid;
  348. grid-template-columns: 1fr;
  349. gap: ${space(2)};
  350. @media (min-width: ${p => p.theme.breakpoints.small}) {
  351. grid-template-columns: repeat(2, 1fr);
  352. }
  353. @media (min-width: ${p => p.theme.breakpoints.large}) {
  354. grid-template-columns: repeat(4, 1fr);
  355. }
  356. `;
  357. const DropdownDataCategory = styled(CompactSelect)`
  358. grid-column: auto / span 1;
  359. button[aria-haspopup='listbox'] {
  360. width: 100%;
  361. height: 100%;
  362. }
  363. @media (min-width: ${p => p.theme.breakpoints.small}) {
  364. grid-column: auto / span 2;
  365. }
  366. @media (min-width: ${p => p.theme.breakpoints.large}) {
  367. grid-column: auto / span 1;
  368. }
  369. `;
  370. const StyledPageTimeRangeSelector = styled(PageTimeRangeSelector)`
  371. grid-column: auto / span 1;
  372. @media (min-width: ${p => p.theme.breakpoints.small}) {
  373. grid-column: auto / span 2;
  374. }
  375. @media (min-width: ${p => p.theme.breakpoints.large}) {
  376. grid-column: auto / span 3;
  377. }
  378. `;
  379. const Body = styled(Layout.Body)`
  380. @media (min-width: ${p => p.theme.breakpoints.medium}) {
  381. display: block;
  382. }
  383. `;
  384. const PageControl = styled('div')`
  385. display: grid;
  386. width: 100%;
  387. margin-bottom: ${space(2)};
  388. grid-template-columns: minmax(0, max-content);
  389. @media (max-width: ${p => p.theme.breakpoints.small}) {
  390. grid-template-columns: minmax(0, 1fr);
  391. }
  392. `;