index.tsx 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419
  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 organization.features.includes('continuous-profiling-stats');
  227. }
  228. if (DATA_CATEGORY_INFO.profile.plural === opt.value) {
  229. return !organization.features.includes('continuous-profiling-stats');
  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. /**
  249. * This method is replaced by the hook "component:enhanced-org-stats"
  250. */
  251. renderUsageStatsOrg() {
  252. const {organization, router, location, params, routes} = this.props;
  253. return (
  254. <UsageStatsOrg
  255. isSingleProject={this.isSingleProject}
  256. projectIds={this.projectIds}
  257. organization={organization}
  258. dataCategory={this.dataCategory}
  259. dataCategoryName={this.dataCategoryInfo.titleName}
  260. dataCategoryApiName={this.dataCategoryInfo.apiName}
  261. dataDatetime={this.dataDatetime}
  262. chartTransform={this.chartTransform}
  263. clientDiscard={this.clientDiscard}
  264. handleChangeState={this.setStateOnUrl}
  265. router={router}
  266. location={location}
  267. params={params}
  268. routes={routes}
  269. />
  270. );
  271. }
  272. render() {
  273. const {organization} = this.props;
  274. const hasTeamInsights = organization.features.includes('team-insights');
  275. return (
  276. <SentryDocumentTitle title="Usage Stats">
  277. <PageFiltersContainer>
  278. {hasTeamInsights ? (
  279. <HeaderTabs organization={organization} activeTab="stats" />
  280. ) : (
  281. <Layout.Header>
  282. <Layout.HeaderContent>
  283. <Layout.Title>{t('Organization Usage Stats')}</Layout.Title>
  284. <HeadingSubtitle>
  285. {tct(
  286. 'A view of the usage data that Sentry has received across your entire organization. [link: Read the docs].',
  287. {
  288. link: <ExternalLink href="https://docs.sentry.io/product/stats/" />,
  289. }
  290. )}
  291. </HeadingSubtitle>
  292. </Layout.HeaderContent>
  293. </Layout.Header>
  294. )}
  295. <Body>
  296. <Layout.Main fullWidth>
  297. <HookHeader organization={organization} />
  298. {this.renderProjectPageControl()}
  299. <div>
  300. <ErrorBoundary mini>{this.renderUsageStatsOrg()}</ErrorBoundary>
  301. </div>
  302. <ErrorBoundary mini>
  303. <UsageStatsProjects
  304. organization={organization}
  305. dataCategory={this.dataCategoryInfo}
  306. dataCategoryName={this.dataCategoryInfo.titleName}
  307. isSingleProject={this.isSingleProject}
  308. projectIds={this.projectIds}
  309. dataDatetime={this.dataDatetime}
  310. tableSort={this.tableSort}
  311. tableQuery={this.tableQuery}
  312. tableCursor={this.tableCursor}
  313. handleChangeState={this.setStateOnUrl}
  314. getNextLocations={this.getNextLocations}
  315. />
  316. </ErrorBoundary>
  317. </Layout.Main>
  318. </Body>
  319. </PageFiltersContainer>
  320. </SentryDocumentTitle>
  321. );
  322. }
  323. }
  324. const HookOrgStats = HookOrDefault({
  325. hookName: 'component:enhanced-org-stats',
  326. defaultComponent: OrganizationStats,
  327. });
  328. export default withPageFilters(withOrganization(HookOrgStats));
  329. const DropdownDataCategory = styled(CompactSelect)`
  330. width: auto;
  331. position: relative;
  332. grid-column: auto / span 1;
  333. button[aria-haspopup='listbox'] {
  334. width: 100%;
  335. height: 100%;
  336. }
  337. @media (min-width: ${p => p.theme.breakpoints.small}) {
  338. grid-column: auto / span 2;
  339. }
  340. @media (min-width: ${p => p.theme.breakpoints.large}) {
  341. grid-column: auto / span 1;
  342. }
  343. &::after {
  344. content: '';
  345. position: absolute;
  346. top: 0;
  347. bottom: 0;
  348. left: 0;
  349. right: 0;
  350. pointer-events: none;
  351. box-shadow: inset 0 0 0 1px ${p => p.theme.border};
  352. border-radius: ${p => p.theme.borderRadius};
  353. }
  354. `;
  355. const Body = styled(Layout.Body)`
  356. @media (min-width: ${p => p.theme.breakpoints.medium}) {
  357. display: block;
  358. }
  359. `;
  360. const HeadingSubtitle = styled('p')`
  361. margin-top: ${space(0.5)};
  362. margin-bottom: 0;
  363. `;
  364. const PageControl = styled('div')`
  365. display: grid;
  366. width: 100%;
  367. margin-bottom: ${space(2)};
  368. grid-template-columns: minmax(0, max-content);
  369. @media (max-width: ${p => p.theme.breakpoints.small}) {
  370. grid-template-columns: minmax(0, 1fr);
  371. }
  372. `;