index.tsx 15 KB

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