index.tsx 15 KB

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