index.tsx 13 KB

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