index.tsx 14 KB

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