index.tsx 15 KB

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