index.tsx 12 KB

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