index.tsx 12 KB

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