index.tsx 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505
  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 DatePageFilter from 'sentry/components/datePageFilter';
  11. import ErrorBoundary from 'sentry/components/errorBoundary';
  12. import HookOrDefault from 'sentry/components/hookOrDefault';
  13. import * as Layout from 'sentry/components/layouts/thirds';
  14. import ExternalLink from 'sentry/components/links/externalLink';
  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 {ChangeData} from 'sentry/components/organizations/timeRangeSelector';
  19. import PageTimeRangeSelector from 'sentry/components/pageTimeRangeSelector';
  20. import ProjectPageFilter from 'sentry/components/projectPageFilter';
  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 alignDropdown="left" />
  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} = 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. />
  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.dataCategory}
  362. dataCategoryName={this.dataCategoryName}
  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 StyledPageTimeRangeSelector = styled(PageTimeRangeSelector)`
  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. `;