index.tsx 12 KB

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