index.tsx 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495
  1. import {Component} 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_INFO,
  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 {
  31. DataCategoryInfo,
  32. DateString,
  33. Organization,
  34. PageFilters,
  35. Project,
  36. } from 'sentry/types';
  37. import withOrganization from 'sentry/utils/withOrganization';
  38. import withPageFilters from 'sentry/utils/withPageFilters';
  39. import HeaderTabs from 'sentry/views/organizationStats/header';
  40. import {CHART_OPTIONS_DATACATEGORY, ChartDataTransform} from './usageChart';
  41. import UsageStatsOrg from './usageStatsOrg';
  42. import UsageStatsProjects from './usageStatsProjects';
  43. const HookHeader = HookOrDefault({hookName: 'component:org-stats-banner'});
  44. export const PAGE_QUERY_PARAMS = [
  45. // From DatePageFilter
  46. 'statsPeriod',
  47. 'start',
  48. 'end',
  49. 'utc',
  50. // TODO(Leander): Remove date selector props once project-stats flag is GA
  51. 'pageEnd',
  52. 'pageStart',
  53. 'pageStatsPeriod',
  54. 'pageStatsUtc',
  55. // From data category selector
  56. 'dataCategory',
  57. // From UsageOrganizationStats
  58. 'transform',
  59. // From UsageProjectStats
  60. 'sort',
  61. 'query',
  62. 'cursor',
  63. ];
  64. type Props = {
  65. organization: Organization;
  66. selection: PageFilters;
  67. } & RouteComponentProps<{}, {}>;
  68. const UsageStatsOrganization = HookOrDefault({
  69. hookName: 'component:enhanced-org-stats',
  70. defaultComponent: UsageStatsOrg,
  71. });
  72. export class OrganizationStats extends Component<Props> {
  73. get dataCategory(): DataCategoryInfo['plural'] {
  74. const dataCategory = this.props.location?.query?.dataCategory;
  75. switch (dataCategory) {
  76. case DATA_CATEGORY_INFO.error.plural:
  77. case DATA_CATEGORY_INFO.transaction.plural:
  78. case DATA_CATEGORY_INFO.attachment.plural:
  79. case DATA_CATEGORY_INFO.profile.plural:
  80. case DATA_CATEGORY_INFO.replay.plural:
  81. return dataCategory;
  82. default:
  83. return DATA_CATEGORY_INFO.error.plural;
  84. }
  85. }
  86. get dataCategoryInfo(): DataCategoryInfo {
  87. const dataCategoryPlural = this.props.location?.query?.dataCategory;
  88. const dataCategoryInfo =
  89. Object.values(DATA_CATEGORY_INFO).find(
  90. categoryInfo => categoryInfo.plural === dataCategoryPlural
  91. ) ?? DATA_CATEGORY_INFO.error;
  92. return dataCategoryInfo;
  93. }
  94. get dataCategoryName(): string {
  95. return this.dataCategoryInfo.titleName ?? t('Unknown Data Category');
  96. }
  97. get dataDatetime(): DateTimeObject {
  98. const params = this.hasProjectStats
  99. ? this.props.selection.datetime
  100. : this.props.location?.query ?? {};
  101. const {
  102. start,
  103. end,
  104. statsPeriod,
  105. utc: utcString,
  106. } = normalizeDateTimeParams(params, {
  107. allowEmptyPeriod: true,
  108. allowAbsoluteDatetime: true,
  109. allowAbsolutePageDatetime: true,
  110. });
  111. if (!statsPeriod && !start && !end) {
  112. return {period: DEFAULT_STATS_PERIOD};
  113. }
  114. // Following getParams, statsPeriod will take priority over start/end
  115. if (statsPeriod) {
  116. return {period: statsPeriod};
  117. }
  118. const utc = utcString === 'true';
  119. if (start && end) {
  120. return utc
  121. ? {
  122. start: moment.utc(start).format(),
  123. end: moment.utc(end).format(),
  124. utc,
  125. }
  126. : {
  127. start: moment(start).utc().format(),
  128. end: moment(end).utc().format(),
  129. utc,
  130. };
  131. }
  132. return {period: DEFAULT_STATS_PERIOD};
  133. }
  134. // Validation and type-casting should be handled by chart
  135. get chartTransform(): string | undefined {
  136. return this.props.location?.query?.transform;
  137. }
  138. // Validation and type-casting should be handled by table
  139. get tableSort(): string | undefined {
  140. return this.props.location?.query?.sort;
  141. }
  142. get tableQuery(): string | undefined {
  143. return this.props.location?.query?.query;
  144. }
  145. get tableCursor(): string | undefined {
  146. return this.props.location?.query?.cursor;
  147. }
  148. // Project selection from GlobalSelectionHeader
  149. get projectIds(): number[] {
  150. const selection_projects = this.props.selection.projects.length
  151. ? this.props.selection.projects
  152. : [ALL_ACCESS_PROJECTS];
  153. return this.hasProjectStats ? selection_projects : [ALL_ACCESS_PROJECTS];
  154. }
  155. /**
  156. * Note: Since we're not checking for 'global-views', orgs without that flag will only ever get
  157. * the single project view. This is a trade-off of using the global project header, but creates
  158. * product consistency, since multi-project selection should be controlled by this flag.
  159. */
  160. get hasProjectStats(): boolean {
  161. return this.props.organization.features.includes('project-stats');
  162. }
  163. getNextLocations = (project: Project): Record<string, LocationDescriptorObject> => {
  164. const {location, organization} = this.props;
  165. const nextLocation: LocationDescriptorObject = {
  166. ...location,
  167. query: {
  168. ...location.query,
  169. project: project.id,
  170. },
  171. };
  172. // Do not leak out page-specific keys
  173. nextLocation.query = omit(nextLocation.query, PAGE_QUERY_PARAMS);
  174. return {
  175. performance: {
  176. ...nextLocation,
  177. pathname: `/organizations/${organization.slug}/performance/`,
  178. },
  179. projectDetail: {
  180. ...nextLocation,
  181. pathname: `/organizations/${organization.slug}/projects/${project.slug}/`,
  182. },
  183. issueList: {
  184. ...nextLocation,
  185. pathname: `/organizations/${organization.slug}/issues/`,
  186. },
  187. settings: {
  188. pathname: `/settings/${organization.slug}/projects/${project.slug}/`,
  189. },
  190. };
  191. };
  192. /**
  193. * See PAGE_QUERY_PARAMS for list of accepted keys on nextState
  194. */
  195. setStateOnUrl = (
  196. nextState: {
  197. cursor?: string;
  198. dataCategory?: DataCategoryInfo['plural'];
  199. // TODO(Leander): Remove date selector props once project-stats flag is GA
  200. pageEnd?: DateString;
  201. pageStart?: DateString;
  202. pageStatsPeriod?: string | null;
  203. pageStatsUtc?: string | null;
  204. pageUtc?: boolean | null;
  205. query?: string;
  206. sort?: string;
  207. transform?: ChartDataTransform;
  208. },
  209. options: {
  210. willUpdateRouter?: boolean;
  211. } = {
  212. willUpdateRouter: true,
  213. }
  214. ): LocationDescriptorObject => {
  215. const {location, router} = this.props;
  216. const nextQueryParams = pick(nextState, PAGE_QUERY_PARAMS);
  217. const nextLocation = {
  218. ...location,
  219. query: {
  220. ...location?.query,
  221. ...nextQueryParams,
  222. },
  223. };
  224. if (options.willUpdateRouter) {
  225. router.push(nextLocation);
  226. }
  227. return nextLocation;
  228. };
  229. renderProjectPageControl = () => {
  230. const {organization} = this.props;
  231. if (!this.hasProjectStats) {
  232. return null;
  233. }
  234. const hasReplay = organization.features.includes('session-replay');
  235. const options = hasReplay
  236. ? CHART_OPTIONS_DATACATEGORY
  237. : CHART_OPTIONS_DATACATEGORY.filter(
  238. opt => opt.value !== DATA_CATEGORY_INFO.replay.plural
  239. );
  240. return (
  241. <PageControl>
  242. <PageFilterBar>
  243. <ProjectPageFilter />
  244. <DropdownDataCategory
  245. triggerProps={{prefix: t('Category')}}
  246. value={this.dataCategory}
  247. options={options}
  248. onChange={opt => this.setStateOnUrl({dataCategory: String(opt.value)})}
  249. />
  250. <DatePageFilter alignDropdown="left" />
  251. </PageFilterBar>
  252. </PageControl>
  253. );
  254. };
  255. // TODO(Leander): Remove the following method once the project-stats flag is GA
  256. handleUpdateDatetime = (datetime: ChangeData): LocationDescriptorObject => {
  257. const {start, end, relative, utc} = datetime;
  258. if (start && end) {
  259. const parser = utc ? moment.utc : moment;
  260. return this.setStateOnUrl({
  261. pageStatsPeriod: undefined,
  262. pageStart: parser(start).format(),
  263. pageEnd: parser(end).format(),
  264. pageUtc: utc ?? undefined,
  265. });
  266. }
  267. return this.setStateOnUrl({
  268. pageStatsPeriod: relative || undefined,
  269. pageStart: undefined,
  270. pageEnd: undefined,
  271. pageUtc: undefined,
  272. });
  273. };
  274. // TODO(Leander): Remove the following method once the project-stats flag is GA
  275. renderPageControl = () => {
  276. const {organization} = this.props;
  277. if (this.hasProjectStats) {
  278. return null;
  279. }
  280. const {start, end, period, utc} = this.dataDatetime;
  281. const hasReplay = organization.features.includes('session-replay');
  282. const options = hasReplay
  283. ? CHART_OPTIONS_DATACATEGORY
  284. : CHART_OPTIONS_DATACATEGORY.filter(
  285. opt => opt.value !== DATA_CATEGORY_INFO.replay.plural
  286. );
  287. return (
  288. <SelectorGrid>
  289. <DropdownDataCategory
  290. triggerProps={{prefix: t('Category')}}
  291. value={this.dataCategory}
  292. options={options}
  293. onChange={opt => this.setStateOnUrl({dataCategory: String(opt.value)})}
  294. />
  295. <StyledPageTimeRangeSelector
  296. organization={organization}
  297. relative={period ?? ''}
  298. start={start ?? null}
  299. end={end ?? null}
  300. utc={utc ?? null}
  301. onUpdate={this.handleUpdateDatetime}
  302. relativeOptions={omit(DEFAULT_RELATIVE_PERIODS, ['1h'])}
  303. />
  304. </SelectorGrid>
  305. );
  306. };
  307. render() {
  308. const {organization} = this.props;
  309. const hasTeamInsights = organization.features.includes('team-insights');
  310. const isSingleProject = this.hasProjectStats
  311. ? this.projectIds.length === 1 && !this.projectIds.includes(-1)
  312. : false;
  313. return (
  314. <SentryDocumentTitle title="Usage Stats">
  315. <PageFiltersContainer>
  316. {hasTeamInsights ? (
  317. <HeaderTabs organization={organization} activeTab="stats" />
  318. ) : (
  319. <Layout.Header>
  320. <Layout.HeaderContent>
  321. <Layout.Title>{t('Organization Usage Stats')}</Layout.Title>
  322. <HeadingSubtitle>
  323. {tct(
  324. 'A view of the usage data that Sentry has received across your entire organization. [link: Read the docs].',
  325. {
  326. link: <ExternalLink href="https://docs.sentry.io/product/stats/" />,
  327. }
  328. )}
  329. </HeadingSubtitle>
  330. </Layout.HeaderContent>
  331. </Layout.Header>
  332. )}
  333. <Body>
  334. <Layout.Main fullWidth>
  335. <HookHeader organization={organization} />
  336. {this.renderProjectPageControl()}
  337. {this.renderPageControl()}
  338. <div>
  339. <ErrorBoundary mini>
  340. <UsageStatsOrganization
  341. organization={organization}
  342. dataCategory={this.dataCategory}
  343. dataCategoryName={this.dataCategoryName}
  344. dataDatetime={this.dataDatetime}
  345. chartTransform={this.chartTransform}
  346. handleChangeState={this.setStateOnUrl}
  347. projectIds={this.projectIds}
  348. isSingleProject={isSingleProject}
  349. />
  350. </ErrorBoundary>
  351. </div>
  352. {!isSingleProject && (
  353. <ErrorBoundary mini>
  354. <UsageStatsProjects
  355. organization={organization}
  356. dataCategory={this.dataCategory}
  357. dataCategoryName={this.dataCategoryName}
  358. projectIds={this.projectIds}
  359. dataDatetime={this.dataDatetime}
  360. tableSort={this.tableSort}
  361. tableQuery={this.tableQuery}
  362. tableCursor={this.tableCursor}
  363. handleChangeState={this.setStateOnUrl}
  364. getNextLocations={this.getNextLocations}
  365. />
  366. </ErrorBoundary>
  367. )}
  368. </Layout.Main>
  369. </Body>
  370. </PageFiltersContainer>
  371. </SentryDocumentTitle>
  372. );
  373. }
  374. }
  375. export default withPageFilters(withOrganization(OrganizationStats));
  376. const SelectorGrid = styled('div')`
  377. display: grid;
  378. grid-template-columns: 1fr;
  379. gap: ${space(2)};
  380. margin-bottom: ${space(2)};
  381. @media (min-width: ${p => p.theme.breakpoints.small}) {
  382. grid-template-columns: repeat(2, 1fr);
  383. }
  384. @media (min-width: ${p => p.theme.breakpoints.large}) {
  385. grid-template-columns: repeat(4, 1fr);
  386. }
  387. `;
  388. const DropdownDataCategory = styled(CompactSelect)`
  389. width: auto;
  390. position: relative;
  391. grid-column: auto / span 1;
  392. button[aria-haspopup='listbox'] {
  393. width: 100%;
  394. height: 100%;
  395. }
  396. @media (min-width: ${p => p.theme.breakpoints.small}) {
  397. grid-column: auto / span 2;
  398. }
  399. @media (min-width: ${p => p.theme.breakpoints.large}) {
  400. grid-column: auto / span 1;
  401. }
  402. &::after {
  403. content: '';
  404. position: absolute;
  405. top: 0;
  406. bottom: 0;
  407. left: 0;
  408. right: 0;
  409. pointer-events: none;
  410. box-shadow: inset 0 0 0 1px ${p => p.theme.border};
  411. border-radius: ${p => p.theme.borderRadius};
  412. }
  413. `;
  414. const StyledPageTimeRangeSelector = styled(PageTimeRangeSelector)`
  415. grid-column: auto / span 1;
  416. @media (min-width: ${p => p.theme.breakpoints.small}) {
  417. grid-column: auto / span 2;
  418. }
  419. @media (min-width: ${p => p.theme.breakpoints.large}) {
  420. grid-column: auto / span 3;
  421. }
  422. `;
  423. const Body = styled(Layout.Body)`
  424. @media (min-width: ${p => p.theme.breakpoints.medium}) {
  425. display: block;
  426. }
  427. `;
  428. const HeadingSubtitle = styled('p')`
  429. margin-top: ${space(0.5)};
  430. margin-bottom: 0;
  431. `;
  432. const PageControl = styled('div')`
  433. display: grid;
  434. width: 100%;
  435. margin-bottom: ${space(2)};
  436. grid-template-columns: minmax(0, max-content);
  437. @media (max-width: ${p => p.theme.breakpoints.small}) {
  438. grid-template-columns: minmax(0, 1fr);
  439. }
  440. `;