index.tsx 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422
  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 {space} from 'sentry/styles/space';
  25. import type {DataCategoryInfo, DateString, PageFilters} from 'sentry/types/core';
  26. import type {Organization} from 'sentry/types/organization';
  27. import type {Project} from 'sentry/types/project';
  28. import {hasCustomMetrics} from 'sentry/utils/metrics/features';
  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 options = CHART_OPTIONS_DATACATEGORY.filter(opt => {
  204. if (opt.value === DATA_CATEGORY_INFO.replay.plural) {
  205. return organization.features.includes('session-replay');
  206. }
  207. if (opt.value === DATA_CATEGORY_INFO.metrics.plural) {
  208. return hasCustomMetrics(organization);
  209. }
  210. if (DATA_CATEGORY_INFO.span.plural === opt.value) {
  211. return organization.features.includes('spans-usage-tracking');
  212. }
  213. if (DATA_CATEGORY_INFO.transaction.plural === opt.value) {
  214. return !organization.features.includes('spans-usage-tracking');
  215. }
  216. return true;
  217. });
  218. return (
  219. <PageControl>
  220. <PageFilterBar>
  221. <ProjectPageFilter />
  222. <DropdownDataCategory
  223. triggerProps={{prefix: t('Category')}}
  224. value={this.dataCategory}
  225. options={options}
  226. onChange={opt => this.setStateOnUrl({dataCategory: String(opt.value)})}
  227. />
  228. <DatePageFilter />
  229. </PageFilterBar>
  230. </PageControl>
  231. );
  232. };
  233. // TODO(Leander): Remove the following method once the project-stats flag is GA
  234. handleUpdateDatetime = (datetime: ChangeData): LocationDescriptorObject => {
  235. const {start, end, relative, utc} = datetime;
  236. if (start && end) {
  237. const parser = utc ? moment.utc : moment;
  238. return this.setStateOnUrl({
  239. pageStatsPeriod: undefined,
  240. pageStart: parser(start).format(),
  241. pageEnd: parser(end).format(),
  242. pageUtc: utc ?? undefined,
  243. });
  244. }
  245. return this.setStateOnUrl({
  246. pageStatsPeriod: relative || undefined,
  247. pageStart: undefined,
  248. pageEnd: undefined,
  249. pageUtc: undefined,
  250. });
  251. };
  252. /**
  253. * This method is replaced by the hook "component:enhanced-org-stats"
  254. */
  255. renderUsageStatsOrg() {
  256. const {organization, router, location, params, routes} = this.props;
  257. return (
  258. <UsageStatsOrg
  259. isSingleProject={this.isSingleProject}
  260. projectIds={this.projectIds}
  261. organization={organization}
  262. dataCategory={this.dataCategory}
  263. dataCategoryName={this.dataCategoryInfo.titleName}
  264. dataDatetime={this.dataDatetime}
  265. chartTransform={this.chartTransform}
  266. handleChangeState={this.setStateOnUrl}
  267. router={router}
  268. location={location}
  269. params={params}
  270. routes={routes}
  271. />
  272. );
  273. }
  274. render() {
  275. const {organization} = this.props;
  276. const hasTeamInsights = organization.features.includes('team-insights');
  277. return (
  278. <SentryDocumentTitle title="Usage Stats">
  279. <PageFiltersContainer>
  280. {hasTeamInsights ? (
  281. <HeaderTabs organization={organization} activeTab="stats" />
  282. ) : (
  283. <Layout.Header>
  284. <Layout.HeaderContent>
  285. <Layout.Title>{t('Organization Usage Stats')}</Layout.Title>
  286. <HeadingSubtitle>
  287. {tct(
  288. 'A view of the usage data that Sentry has received across your entire organization. [link: Read the docs].',
  289. {
  290. link: <ExternalLink href="https://docs.sentry.io/product/stats/" />,
  291. }
  292. )}
  293. </HeadingSubtitle>
  294. </Layout.HeaderContent>
  295. </Layout.Header>
  296. )}
  297. <Body>
  298. <Layout.Main fullWidth>
  299. <HookHeader organization={organization} />
  300. {this.renderProjectPageControl()}
  301. <div>
  302. <ErrorBoundary mini>{this.renderUsageStatsOrg()}</ErrorBoundary>
  303. </div>
  304. <ErrorBoundary mini>
  305. <UsageStatsProjects
  306. organization={organization}
  307. dataCategory={this.dataCategoryInfo}
  308. dataCategoryName={this.dataCategoryInfo.titleName}
  309. isSingleProject={this.isSingleProject}
  310. projectIds={this.projectIds}
  311. dataDatetime={this.dataDatetime}
  312. tableSort={this.tableSort}
  313. tableQuery={this.tableQuery}
  314. tableCursor={this.tableCursor}
  315. handleChangeState={this.setStateOnUrl}
  316. getNextLocations={this.getNextLocations}
  317. />
  318. </ErrorBoundary>
  319. </Layout.Main>
  320. </Body>
  321. </PageFiltersContainer>
  322. </SentryDocumentTitle>
  323. );
  324. }
  325. }
  326. const HookOrgStats = HookOrDefault({
  327. hookName: 'component:enhanced-org-stats',
  328. defaultComponent: OrganizationStats,
  329. });
  330. export default withPageFilters(withOrganization(HookOrgStats));
  331. const DropdownDataCategory = styled(CompactSelect)`
  332. width: auto;
  333. position: relative;
  334. grid-column: auto / span 1;
  335. button[aria-haspopup='listbox'] {
  336. width: 100%;
  337. height: 100%;
  338. }
  339. @media (min-width: ${p => p.theme.breakpoints.small}) {
  340. grid-column: auto / span 2;
  341. }
  342. @media (min-width: ${p => p.theme.breakpoints.large}) {
  343. grid-column: auto / span 1;
  344. }
  345. &::after {
  346. content: '';
  347. position: absolute;
  348. top: 0;
  349. bottom: 0;
  350. left: 0;
  351. right: 0;
  352. pointer-events: none;
  353. box-shadow: inset 0 0 0 1px ${p => p.theme.border};
  354. border-radius: ${p => p.theme.borderRadius};
  355. }
  356. `;
  357. const Body = styled(Layout.Body)`
  358. @media (min-width: ${p => p.theme.breakpoints.medium}) {
  359. display: block;
  360. }
  361. `;
  362. const HeadingSubtitle = styled('p')`
  363. margin-top: ${space(0.5)};
  364. margin-bottom: 0;
  365. `;
  366. const PageControl = styled('div')`
  367. display: grid;
  368. width: 100%;
  369. margin-bottom: ${space(2)};
  370. grid-template-columns: minmax(0, max-content);
  371. @media (max-width: ${p => p.theme.breakpoints.small}) {
  372. grid-template-columns: minmax(0, 1fr);
  373. }
  374. `;