index.tsx 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394
  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 {DATA_CATEGORY_INFO, DEFAULT_STATS_PERIOD} from 'sentry/constants';
  21. import {ALL_ACCESS_PROJECTS} from 'sentry/constants/pageFilters';
  22. import {t, tct} from 'sentry/locale';
  23. import ConfigStore from 'sentry/stores/configStore';
  24. import {space} from 'sentry/styles/space';
  25. import type {DataCategoryInfo, PageFilters} from 'sentry/types/core';
  26. import type {Organization} from 'sentry/types/organization';
  27. import type {Project} from 'sentry/types/project';
  28. import withOrganization from 'sentry/utils/withOrganization';
  29. import withPageFilters from 'sentry/utils/withPageFilters';
  30. import HeaderTabs from 'sentry/views/organizationStats/header';
  31. import type {ChartDataTransform} from './usageChart';
  32. import {CHART_OPTIONS_DATACATEGORY} from './usageChart';
  33. import UsageStatsOrg from './usageStatsOrg';
  34. import UsageStatsProjects from './usageStatsProjects';
  35. const HookHeader = HookOrDefault({hookName: 'component:org-stats-banner'});
  36. export const PAGE_QUERY_PARAMS = [
  37. // From DatePageFilter
  38. 'statsPeriod',
  39. 'start',
  40. 'end',
  41. 'utc',
  42. // From data category selector
  43. 'dataCategory',
  44. // From UsageOrganizationStats
  45. 'transform',
  46. // From UsageProjectStats
  47. 'sort',
  48. 'query',
  49. 'cursor',
  50. 'spikeCursor',
  51. ];
  52. export type OrganizationStatsProps = {
  53. organization: Organization;
  54. selection: PageFilters;
  55. } & RouteComponentProps<{}, {}>;
  56. export class OrganizationStats extends Component<OrganizationStatsProps> {
  57. get dataCategoryInfo(): DataCategoryInfo {
  58. const dataCategoryPlural = this.props.location?.query?.dataCategory;
  59. const categories = Object.values(DATA_CATEGORY_INFO);
  60. const info = categories.find(c => c.plural === dataCategoryPlural);
  61. // Default to errors
  62. return info ?? DATA_CATEGORY_INFO.error;
  63. }
  64. get dataCategory() {
  65. return this.dataCategoryInfo.plural;
  66. }
  67. get dataCategoryName() {
  68. return this.dataCategoryInfo.titleName;
  69. }
  70. get dataDatetime(): DateTimeObject {
  71. const params = this.props.selection.datetime;
  72. const {
  73. start,
  74. end,
  75. statsPeriod,
  76. utc: utcString,
  77. } = normalizeDateTimeParams(params, {
  78. allowEmptyPeriod: true,
  79. allowAbsoluteDatetime: true,
  80. allowAbsolutePageDatetime: true,
  81. });
  82. if (!statsPeriod && !start && !end) {
  83. return {period: DEFAULT_STATS_PERIOD};
  84. }
  85. // Following getParams, statsPeriod will take priority over start/end
  86. if (statsPeriod) {
  87. return {period: statsPeriod};
  88. }
  89. const utc = utcString === 'true';
  90. if (start && end) {
  91. return utc
  92. ? {
  93. start: moment.utc(start).format(),
  94. end: moment.utc(end).format(),
  95. utc,
  96. }
  97. : {
  98. start: moment(start).utc().format(),
  99. end: moment(end).utc().format(),
  100. utc,
  101. };
  102. }
  103. return {period: DEFAULT_STATS_PERIOD};
  104. }
  105. // Validation and type-casting should be handled by chart
  106. get chartTransform(): string | undefined {
  107. return this.props.location?.query?.transform;
  108. }
  109. // Validation and type-casting should be handled by table
  110. get tableSort(): string | undefined {
  111. return this.props.location?.query?.sort;
  112. }
  113. get tableQuery(): string | undefined {
  114. return this.props.location?.query?.query;
  115. }
  116. get tableCursor(): string | undefined {
  117. return this.props.location?.query?.cursor;
  118. }
  119. // Project selection from GlobalSelectionHeader
  120. get projectIds(): number[] {
  121. const selection_projects = this.props.selection.projects.length
  122. ? this.props.selection.projects
  123. : [ALL_ACCESS_PROJECTS];
  124. return selection_projects;
  125. }
  126. get isSingleProject(): boolean {
  127. return this.projectIds.length === 1 && !this.projectIds.includes(-1);
  128. }
  129. getNextLocations = (project: Project): Record<string, LocationDescriptorObject> => {
  130. const {location, organization} = this.props;
  131. const nextLocation: LocationDescriptorObject = {
  132. ...location,
  133. query: {
  134. ...location.query,
  135. project: project.id,
  136. },
  137. };
  138. // Do not leak out page-specific keys
  139. nextLocation.query = omit(nextLocation.query, PAGE_QUERY_PARAMS);
  140. return {
  141. performance: {
  142. ...nextLocation,
  143. pathname: `/organizations/${organization.slug}/performance/`,
  144. },
  145. projectDetail: {
  146. ...nextLocation,
  147. pathname: `/organizations/${organization.slug}/projects/${project.slug}/`,
  148. },
  149. issueList: {
  150. ...nextLocation,
  151. pathname: `/organizations/${organization.slug}/issues/`,
  152. },
  153. settings: {
  154. pathname: `/settings/${organization.slug}/projects/${project.slug}/`,
  155. },
  156. };
  157. };
  158. /**
  159. * See PAGE_QUERY_PARAMS for list of accepted keys on nextState
  160. */
  161. setStateOnUrl = (
  162. nextState: {
  163. cursor?: string;
  164. dataCategory?: DataCategoryInfo['plural'];
  165. query?: string;
  166. sort?: string;
  167. transform?: ChartDataTransform;
  168. },
  169. options: {
  170. willUpdateRouter?: boolean;
  171. } = {
  172. willUpdateRouter: true,
  173. }
  174. ): LocationDescriptorObject => {
  175. const {location, router} = this.props;
  176. const nextQueryParams = pick(nextState, PAGE_QUERY_PARAMS);
  177. const nextLocation = {
  178. ...location,
  179. query: {
  180. ...location?.query,
  181. ...nextQueryParams,
  182. },
  183. };
  184. if (options.willUpdateRouter) {
  185. router.push(nextLocation);
  186. }
  187. return nextLocation;
  188. };
  189. renderProjectPageControl = () => {
  190. const {organization} = this.props;
  191. const isSelfHostedErrorsOnly = ConfigStore.get('isSelfHostedErrorsOnly');
  192. const options = CHART_OPTIONS_DATACATEGORY.filter(opt => {
  193. if (isSelfHostedErrorsOnly) {
  194. return opt.value === DATA_CATEGORY_INFO.error.plural;
  195. }
  196. if (opt.value === DATA_CATEGORY_INFO.replay.plural) {
  197. return organization.features.includes('session-replay');
  198. }
  199. if (DATA_CATEGORY_INFO.span.plural === opt.value) {
  200. return organization.features.includes('spans-usage-tracking');
  201. }
  202. if (DATA_CATEGORY_INFO.transaction.plural === opt.value) {
  203. return !organization.features.includes('spans-usage-tracking');
  204. }
  205. if (DATA_CATEGORY_INFO.profileDuration.plural === opt.value) {
  206. return organization.features.includes('continuous-profiling-stats');
  207. }
  208. if (DATA_CATEGORY_INFO.profile.plural === opt.value) {
  209. return !organization.features.includes('continuous-profiling-stats');
  210. }
  211. return true;
  212. });
  213. return (
  214. <PageControl>
  215. <PageFilterBar>
  216. <ProjectPageFilter />
  217. <DropdownDataCategory
  218. triggerProps={{prefix: t('Category')}}
  219. value={this.dataCategory}
  220. options={options}
  221. onChange={opt => this.setStateOnUrl({dataCategory: String(opt.value)})}
  222. />
  223. <DatePageFilter />
  224. </PageFilterBar>
  225. </PageControl>
  226. );
  227. };
  228. /**
  229. * This method is replaced by the hook "component:enhanced-org-stats"
  230. */
  231. renderUsageStatsOrg() {
  232. const {organization, router, location, params, routes} = this.props;
  233. return (
  234. <UsageStatsOrg
  235. isSingleProject={this.isSingleProject}
  236. projectIds={this.projectIds}
  237. organization={organization}
  238. dataCategory={this.dataCategory}
  239. dataCategoryName={this.dataCategoryInfo.titleName}
  240. dataDatetime={this.dataDatetime}
  241. chartTransform={this.chartTransform}
  242. handleChangeState={this.setStateOnUrl}
  243. router={router}
  244. location={location}
  245. params={params}
  246. routes={routes}
  247. />
  248. );
  249. }
  250. render() {
  251. const {organization} = this.props;
  252. const hasTeamInsights = organization.features.includes('team-insights');
  253. return (
  254. <SentryDocumentTitle title="Usage Stats">
  255. <PageFiltersContainer>
  256. {hasTeamInsights ? (
  257. <HeaderTabs organization={organization} activeTab="stats" />
  258. ) : (
  259. <Layout.Header>
  260. <Layout.HeaderContent>
  261. <Layout.Title>{t('Organization Usage Stats')}</Layout.Title>
  262. <HeadingSubtitle>
  263. {tct(
  264. 'A view of the usage data that Sentry has received across your entire organization. [link: Read the docs].',
  265. {
  266. link: <ExternalLink href="https://docs.sentry.io/product/stats/" />,
  267. }
  268. )}
  269. </HeadingSubtitle>
  270. </Layout.HeaderContent>
  271. </Layout.Header>
  272. )}
  273. <Body>
  274. <Layout.Main fullWidth>
  275. <HookHeader organization={organization} />
  276. {this.renderProjectPageControl()}
  277. <div>
  278. <ErrorBoundary mini>{this.renderUsageStatsOrg()}</ErrorBoundary>
  279. </div>
  280. <ErrorBoundary mini>
  281. <UsageStatsProjects
  282. organization={organization}
  283. dataCategory={this.dataCategoryInfo}
  284. dataCategoryName={this.dataCategoryInfo.titleName}
  285. isSingleProject={this.isSingleProject}
  286. projectIds={this.projectIds}
  287. dataDatetime={this.dataDatetime}
  288. tableSort={this.tableSort}
  289. tableQuery={this.tableQuery}
  290. tableCursor={this.tableCursor}
  291. handleChangeState={this.setStateOnUrl}
  292. getNextLocations={this.getNextLocations}
  293. />
  294. </ErrorBoundary>
  295. </Layout.Main>
  296. </Body>
  297. </PageFiltersContainer>
  298. </SentryDocumentTitle>
  299. );
  300. }
  301. }
  302. const HookOrgStats = HookOrDefault({
  303. hookName: 'component:enhanced-org-stats',
  304. defaultComponent: OrganizationStats,
  305. });
  306. export default withPageFilters(withOrganization(HookOrgStats));
  307. const DropdownDataCategory = styled(CompactSelect)`
  308. width: auto;
  309. position: relative;
  310. grid-column: auto / span 1;
  311. button[aria-haspopup='listbox'] {
  312. width: 100%;
  313. height: 100%;
  314. }
  315. @media (min-width: ${p => p.theme.breakpoints.small}) {
  316. grid-column: auto / span 2;
  317. }
  318. @media (min-width: ${p => p.theme.breakpoints.large}) {
  319. grid-column: auto / span 1;
  320. }
  321. &::after {
  322. content: '';
  323. position: absolute;
  324. top: 0;
  325. bottom: 0;
  326. left: 0;
  327. right: 0;
  328. pointer-events: none;
  329. box-shadow: inset 0 0 0 1px ${p => p.theme.border};
  330. border-radius: ${p => p.theme.borderRadius};
  331. }
  332. `;
  333. const Body = styled(Layout.Body)`
  334. @media (min-width: ${p => p.theme.breakpoints.medium}) {
  335. display: block;
  336. }
  337. `;
  338. const HeadingSubtitle = styled('p')`
  339. margin-top: ${space(0.5)};
  340. margin-bottom: 0;
  341. `;
  342. const PageControl = styled('div')`
  343. display: grid;
  344. width: 100%;
  345. margin-bottom: ${space(2)};
  346. grid-template-columns: minmax(0, max-content);
  347. @media (max-width: ${p => p.theme.breakpoints.small}) {
  348. grid-template-columns: minmax(0, 1fr);
  349. }
  350. `;