index.tsx 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506
  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 {ChangeData} from 'sentry/components/organizations/timeRangeSelector';
  20. import PageTimeRangeSelector from 'sentry/components/pageTimeRangeSelector';
  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. '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. <StyledPageTimeRangeSelector
  298. organization={organization}
  299. relative={period ?? ''}
  300. start={start ?? null}
  301. end={end ?? null}
  302. utc={utc ?? null}
  303. onUpdate={this.handleUpdateDatetime}
  304. relativeOptions={omit(DEFAULT_RELATIVE_PERIODS, ['1h'])}
  305. />
  306. </SelectorGrid>
  307. );
  308. };
  309. /**
  310. * This method is replaced by the hook "component:enhanced-org-stats"
  311. */
  312. renderUsageStatsOrg() {
  313. const {organization, router} = this.props;
  314. return (
  315. <UsageStatsOrg
  316. isSingleProject={this.isSingleProject}
  317. projectIds={this.projectIds}
  318. organization={organization}
  319. dataCategory={this.dataCategory}
  320. dataCategoryName={this.dataCategoryName}
  321. dataDatetime={this.dataDatetime}
  322. chartTransform={this.chartTransform}
  323. handleChangeState={this.setStateOnUrl}
  324. router={router}
  325. />
  326. );
  327. }
  328. render() {
  329. const {organization} = this.props;
  330. const hasTeamInsights = organization.features.includes('team-insights');
  331. return (
  332. <SentryDocumentTitle title="Usage Stats">
  333. <PageFiltersContainer>
  334. {hasTeamInsights ? (
  335. <HeaderTabs organization={organization} activeTab="stats" />
  336. ) : (
  337. <Layout.Header>
  338. <Layout.HeaderContent>
  339. <Layout.Title>{t('Organization Usage Stats')}</Layout.Title>
  340. <HeadingSubtitle>
  341. {tct(
  342. 'A view of the usage data that Sentry has received across your entire organization. [link: Read the docs].',
  343. {
  344. link: <ExternalLink href="https://docs.sentry.io/product/stats/" />,
  345. }
  346. )}
  347. </HeadingSubtitle>
  348. </Layout.HeaderContent>
  349. </Layout.Header>
  350. )}
  351. <Body>
  352. <Layout.Main fullWidth>
  353. <HookHeader organization={organization} />
  354. {this.renderProjectPageControl()}
  355. {this.renderPageControl()}
  356. <div>
  357. <ErrorBoundary mini>{this.renderUsageStatsOrg()}</ErrorBoundary>
  358. </div>
  359. <ErrorBoundary mini>
  360. <UsageStatsProjects
  361. organization={organization}
  362. dataCategory={this.dataCategory}
  363. dataCategoryName={this.dataCategoryName}
  364. isSingleProject={this.isSingleProject}
  365. projectIds={this.projectIds}
  366. dataDatetime={this.dataDatetime}
  367. tableSort={this.tableSort}
  368. tableQuery={this.tableQuery}
  369. tableCursor={this.tableCursor}
  370. handleChangeState={this.setStateOnUrl}
  371. getNextLocations={this.getNextLocations}
  372. />
  373. </ErrorBoundary>
  374. </Layout.Main>
  375. </Body>
  376. </PageFiltersContainer>
  377. </SentryDocumentTitle>
  378. );
  379. }
  380. }
  381. const HookOrgStats = HookOrDefault({
  382. hookName: 'component:enhanced-org-stats',
  383. defaultComponent: OrganizationStats,
  384. });
  385. export default withPageFilters(withOrganization(HookOrgStats));
  386. const SelectorGrid = styled('div')`
  387. display: grid;
  388. grid-template-columns: 1fr;
  389. gap: ${space(2)};
  390. margin-bottom: ${space(2)};
  391. @media (min-width: ${p => p.theme.breakpoints.small}) {
  392. grid-template-columns: repeat(2, 1fr);
  393. }
  394. @media (min-width: ${p => p.theme.breakpoints.large}) {
  395. grid-template-columns: repeat(4, 1fr);
  396. }
  397. `;
  398. const DropdownDataCategory = styled(CompactSelect)`
  399. width: auto;
  400. position: relative;
  401. grid-column: auto / span 1;
  402. button[aria-haspopup='listbox'] {
  403. width: 100%;
  404. height: 100%;
  405. }
  406. @media (min-width: ${p => p.theme.breakpoints.small}) {
  407. grid-column: auto / span 2;
  408. }
  409. @media (min-width: ${p => p.theme.breakpoints.large}) {
  410. grid-column: auto / span 1;
  411. }
  412. &::after {
  413. content: '';
  414. position: absolute;
  415. top: 0;
  416. bottom: 0;
  417. left: 0;
  418. right: 0;
  419. pointer-events: none;
  420. box-shadow: inset 0 0 0 1px ${p => p.theme.border};
  421. border-radius: ${p => p.theme.borderRadius};
  422. }
  423. `;
  424. const StyledPageTimeRangeSelector = styled(PageTimeRangeSelector)`
  425. grid-column: auto / span 1;
  426. @media (min-width: ${p => p.theme.breakpoints.small}) {
  427. grid-column: auto / span 2;
  428. }
  429. @media (min-width: ${p => p.theme.breakpoints.large}) {
  430. grid-column: auto / span 3;
  431. }
  432. `;
  433. const Body = styled(Layout.Body)`
  434. @media (min-width: ${p => p.theme.breakpoints.medium}) {
  435. display: block;
  436. }
  437. `;
  438. const HeadingSubtitle = styled('p')`
  439. margin-top: ${space(0.5)};
  440. margin-bottom: 0;
  441. `;
  442. const PageControl = styled('div')`
  443. display: grid;
  444. width: 100%;
  445. margin-bottom: ${space(2)};
  446. grid-template-columns: minmax(0, max-content);
  447. @media (max-width: ${p => p.theme.breakpoints.small}) {
  448. grid-template-columns: minmax(0, 1fr);
  449. }
  450. `;