index.tsx 13 KB

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