index.tsx 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498
  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 ErrorBoundary from 'sentry/components/errorBoundary';
  11. import HookOrDefault from 'sentry/components/hookOrDefault';
  12. import * as Layout from 'sentry/components/layouts/thirds';
  13. import ExternalLink from 'sentry/components/links/externalLink';
  14. import {DatePageFilter} from 'sentry/components/organizations/datePageFilter';
  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 {ProjectPageFilter} from 'sentry/components/organizations/projectPageFilter';
  19. import SentryDocumentTitle from 'sentry/components/sentryDocumentTitle';
  20. import {ChangeData, TimeRangeSelector} from 'sentry/components/timeRangeSelector';
  21. import {
  22. DATA_CATEGORY_INFO,
  23. DEFAULT_RELATIVE_PERIODS,
  24. DEFAULT_STATS_PERIOD,
  25. } from 'sentry/constants';
  26. import {ALL_ACCESS_PROJECTS} from 'sentry/constants/pageFilters';
  27. import {t, tct} from 'sentry/locale';
  28. import {space} from 'sentry/styles/space';
  29. import {
  30. DataCategoryInfo,
  31. DateString,
  32. Organization,
  33. PageFilters,
  34. Project,
  35. } from 'sentry/types';
  36. import withOrganization from 'sentry/utils/withOrganization';
  37. import withPageFilters from 'sentry/utils/withPageFilters';
  38. import HeaderTabs from 'sentry/views/organizationStats/header';
  39. import {CHART_OPTIONS_DATACATEGORY, ChartDataTransform} from './usageChart';
  40. import UsageStatsOrg from './usageStatsOrg';
  41. import UsageStatsProjects from './usageStatsProjects';
  42. const HookHeader = HookOrDefault({hookName: 'component:org-stats-banner'});
  43. const relativeOptions = omit(DEFAULT_RELATIVE_PERIODS, ['1h']);
  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. 'spikeCursor',
  64. ];
  65. export type OrganizationStatsProps = {
  66. organization: Organization;
  67. selection: PageFilters;
  68. } & RouteComponentProps<{}, {}>;
  69. export class OrganizationStats extends Component<OrganizationStatsProps> {
  70. get dataCategoryInfo(): DataCategoryInfo {
  71. const dataCategoryPlural = this.props.location?.query?.dataCategory;
  72. const categories = Object.values(DATA_CATEGORY_INFO);
  73. const info = categories.find(c => c.plural === dataCategoryPlural);
  74. // Default to errors
  75. return info ?? DATA_CATEGORY_INFO.error;
  76. }
  77. get dataCategory() {
  78. return this.dataCategoryInfo.plural;
  79. }
  80. get dataCategoryName() {
  81. return this.dataCategoryInfo.titleName;
  82. }
  83. get dataDatetime(): DateTimeObject {
  84. const params = this.hasProjectStats
  85. ? this.props.selection.datetime
  86. : this.props.location?.query ?? {};
  87. const {
  88. start,
  89. end,
  90. statsPeriod,
  91. utc: utcString,
  92. } = normalizeDateTimeParams(params, {
  93. allowEmptyPeriod: true,
  94. allowAbsoluteDatetime: true,
  95. allowAbsolutePageDatetime: true,
  96. });
  97. if (!statsPeriod && !start && !end) {
  98. return {period: DEFAULT_STATS_PERIOD};
  99. }
  100. // Following getParams, statsPeriod will take priority over start/end
  101. if (statsPeriod) {
  102. return {period: statsPeriod};
  103. }
  104. const utc = utcString === 'true';
  105. if (start && end) {
  106. return utc
  107. ? {
  108. start: moment.utc(start).format(),
  109. end: moment.utc(end).format(),
  110. utc,
  111. }
  112. : {
  113. start: moment(start).utc().format(),
  114. end: moment(end).utc().format(),
  115. utc,
  116. };
  117. }
  118. return {period: DEFAULT_STATS_PERIOD};
  119. }
  120. // Validation and type-casting should be handled by chart
  121. get chartTransform(): string | undefined {
  122. return this.props.location?.query?.transform;
  123. }
  124. // Validation and type-casting should be handled by table
  125. get tableSort(): string | undefined {
  126. return this.props.location?.query?.sort;
  127. }
  128. get tableQuery(): string | undefined {
  129. return this.props.location?.query?.query;
  130. }
  131. get tableCursor(): string | undefined {
  132. return this.props.location?.query?.cursor;
  133. }
  134. // Project selection from GlobalSelectionHeader
  135. get projectIds(): number[] {
  136. const selection_projects = this.props.selection.projects.length
  137. ? this.props.selection.projects
  138. : [ALL_ACCESS_PROJECTS];
  139. return this.hasProjectStats ? selection_projects : [ALL_ACCESS_PROJECTS];
  140. }
  141. /**
  142. * Note: Since we're not checking for 'global-views', orgs without that flag will only ever get
  143. * the single project view. This is a trade-off of using the global project header, but creates
  144. * product consistency, since multi-project selection should be controlled by this flag.
  145. */
  146. get hasProjectStats(): boolean {
  147. return this.props.organization.features.includes('project-stats');
  148. }
  149. get isSingleProject(): boolean {
  150. return this.hasProjectStats
  151. ? this.projectIds.length === 1 && !this.projectIds.includes(-1)
  152. : false;
  153. }
  154. getNextLocations = (project: Project): Record<string, LocationDescriptorObject> => {
  155. const {location, organization} = this.props;
  156. const nextLocation: LocationDescriptorObject = {
  157. ...location,
  158. query: {
  159. ...location.query,
  160. project: project.id,
  161. },
  162. };
  163. // Do not leak out page-specific keys
  164. nextLocation.query = omit(nextLocation.query, PAGE_QUERY_PARAMS);
  165. return {
  166. performance: {
  167. ...nextLocation,
  168. pathname: `/organizations/${organization.slug}/performance/`,
  169. },
  170. projectDetail: {
  171. ...nextLocation,
  172. pathname: `/organizations/${organization.slug}/projects/${project.slug}/`,
  173. },
  174. issueList: {
  175. ...nextLocation,
  176. pathname: `/organizations/${organization.slug}/issues/`,
  177. },
  178. settings: {
  179. pathname: `/settings/${organization.slug}/projects/${project.slug}/`,
  180. },
  181. };
  182. };
  183. /**
  184. * See PAGE_QUERY_PARAMS for list of accepted keys on nextState
  185. */
  186. setStateOnUrl = (
  187. nextState: {
  188. cursor?: string;
  189. dataCategory?: DataCategoryInfo['plural'];
  190. // TODO(Leander): Remove date selector props once project-stats flag is GA
  191. pageEnd?: DateString;
  192. pageStart?: DateString;
  193. pageStatsPeriod?: string | null;
  194. pageStatsUtc?: string | null;
  195. pageUtc?: boolean | null;
  196. query?: string;
  197. sort?: string;
  198. transform?: ChartDataTransform;
  199. },
  200. options: {
  201. willUpdateRouter?: boolean;
  202. } = {
  203. willUpdateRouter: true,
  204. }
  205. ): LocationDescriptorObject => {
  206. const {location, router} = this.props;
  207. const nextQueryParams = pick(nextState, PAGE_QUERY_PARAMS);
  208. const nextLocation = {
  209. ...location,
  210. query: {
  211. ...location?.query,
  212. ...nextQueryParams,
  213. },
  214. };
  215. if (options.willUpdateRouter) {
  216. router.push(nextLocation);
  217. }
  218. return nextLocation;
  219. };
  220. renderProjectPageControl = () => {
  221. const {organization} = this.props;
  222. if (!this.hasProjectStats) {
  223. return null;
  224. }
  225. const hasReplay = organization.features.includes('session-replay');
  226. const options = hasReplay
  227. ? CHART_OPTIONS_DATACATEGORY
  228. : CHART_OPTIONS_DATACATEGORY.filter(
  229. opt => opt.value !== DATA_CATEGORY_INFO.replay.plural
  230. );
  231. return (
  232. <PageControl>
  233. <PageFilterBar>
  234. <ProjectPageFilter />
  235. <DropdownDataCategory
  236. triggerProps={{prefix: t('Category')}}
  237. value={this.dataCategory}
  238. options={options}
  239. onChange={opt => this.setStateOnUrl({dataCategory: String(opt.value)})}
  240. />
  241. <DatePageFilter />
  242. </PageFilterBar>
  243. </PageControl>
  244. );
  245. };
  246. // TODO(Leander): Remove the following method once the project-stats flag is GA
  247. handleUpdateDatetime = (datetime: ChangeData): LocationDescriptorObject => {
  248. const {start, end, relative, utc} = datetime;
  249. if (start && end) {
  250. const parser = utc ? moment.utc : moment;
  251. return this.setStateOnUrl({
  252. pageStatsPeriod: undefined,
  253. pageStart: parser(start).format(),
  254. pageEnd: parser(end).format(),
  255. pageUtc: utc ?? undefined,
  256. });
  257. }
  258. return this.setStateOnUrl({
  259. pageStatsPeriod: relative || undefined,
  260. pageStart: undefined,
  261. pageEnd: undefined,
  262. pageUtc: undefined,
  263. });
  264. };
  265. // TODO(Leander): Remove the following method once the project-stats flag is GA
  266. renderPageControl = () => {
  267. const {organization} = this.props;
  268. if (this.hasProjectStats) {
  269. return null;
  270. }
  271. const {start, end, period, utc} = this.dataDatetime;
  272. const hasReplay = organization.features.includes('session-replay');
  273. const options = hasReplay
  274. ? CHART_OPTIONS_DATACATEGORY
  275. : CHART_OPTIONS_DATACATEGORY.filter(
  276. opt => opt.value !== DATA_CATEGORY_INFO.replay.plural
  277. );
  278. return (
  279. <SelectorGrid>
  280. <DropdownDataCategory
  281. triggerProps={{prefix: t('Category')}}
  282. value={this.dataCategory}
  283. options={options}
  284. onChange={opt => this.setStateOnUrl({dataCategory: String(opt.value)})}
  285. />
  286. <StyledTimeRangeSelector
  287. relative={period ?? ''}
  288. start={start ?? null}
  289. end={end ?? null}
  290. utc={utc ?? null}
  291. onChange={this.handleUpdateDatetime}
  292. relativeOptions={relativeOptions}
  293. triggerLabel={period && relativeOptions[period]}
  294. triggerProps={{prefix: t('Date Range')}}
  295. />
  296. </SelectorGrid>
  297. );
  298. };
  299. /**
  300. * This method is replaced by the hook "component:enhanced-org-stats"
  301. */
  302. renderUsageStatsOrg() {
  303. const {organization, router} = this.props;
  304. return (
  305. <UsageStatsOrg
  306. isSingleProject={this.isSingleProject}
  307. projectIds={this.projectIds}
  308. organization={organization}
  309. dataCategory={this.dataCategory}
  310. dataCategoryName={this.dataCategoryInfo.titleName}
  311. dataDatetime={this.dataDatetime}
  312. chartTransform={this.chartTransform}
  313. handleChangeState={this.setStateOnUrl}
  314. router={router}
  315. />
  316. );
  317. }
  318. render() {
  319. const {organization} = this.props;
  320. const hasTeamInsights = organization.features.includes('team-insights');
  321. return (
  322. <SentryDocumentTitle title="Usage Stats">
  323. <PageFiltersContainer>
  324. {hasTeamInsights ? (
  325. <HeaderTabs organization={organization} activeTab="stats" />
  326. ) : (
  327. <Layout.Header>
  328. <Layout.HeaderContent>
  329. <Layout.Title>{t('Organization Usage Stats')}</Layout.Title>
  330. <HeadingSubtitle>
  331. {tct(
  332. 'A view of the usage data that Sentry has received across your entire organization. [link: Read the docs].',
  333. {
  334. link: <ExternalLink href="https://docs.sentry.io/product/stats/" />,
  335. }
  336. )}
  337. </HeadingSubtitle>
  338. </Layout.HeaderContent>
  339. </Layout.Header>
  340. )}
  341. <Body>
  342. <Layout.Main fullWidth>
  343. <HookHeader organization={organization} />
  344. {this.renderProjectPageControl()}
  345. {this.renderPageControl()}
  346. <div>
  347. <ErrorBoundary mini>{this.renderUsageStatsOrg()}</ErrorBoundary>
  348. </div>
  349. <ErrorBoundary mini>
  350. <UsageStatsProjects
  351. organization={organization}
  352. dataCategory={this.dataCategoryInfo}
  353. dataCategoryName={this.dataCategoryInfo.titleName}
  354. isSingleProject={this.isSingleProject}
  355. projectIds={this.projectIds}
  356. dataDatetime={this.dataDatetime}
  357. tableSort={this.tableSort}
  358. tableQuery={this.tableQuery}
  359. tableCursor={this.tableCursor}
  360. handleChangeState={this.setStateOnUrl}
  361. getNextLocations={this.getNextLocations}
  362. />
  363. </ErrorBoundary>
  364. </Layout.Main>
  365. </Body>
  366. </PageFiltersContainer>
  367. </SentryDocumentTitle>
  368. );
  369. }
  370. }
  371. const HookOrgStats = HookOrDefault({
  372. hookName: 'component:enhanced-org-stats',
  373. defaultComponent: OrganizationStats,
  374. });
  375. export default withPageFilters(withOrganization(HookOrgStats));
  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 StyledTimeRangeSelector = styled(TimeRangeSelector)`
  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. `;