index.tsx 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362
  1. import {Component, Fragment} from 'react';
  2. import {RouteComponentProps} from 'react-router';
  3. import styled from '@emotion/styled';
  4. import {LocationDescriptorObject} from 'history';
  5. import omit from 'lodash/omit';
  6. import pick from 'lodash/pick';
  7. import moment from 'moment';
  8. import {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 {normalizeDateTimeParams} from 'sentry/components/organizations/pageFilters/parse';
  14. import {ChangeData} from 'sentry/components/organizations/timeRangeSelector';
  15. import PageHeading from 'sentry/components/pageHeading';
  16. import PageTimeRangeSelector from 'sentry/components/pageTimeRangeSelector';
  17. import SentryDocumentTitle from 'sentry/components/sentryDocumentTitle';
  18. import {
  19. DATA_CATEGORY_NAMES,
  20. DEFAULT_RELATIVE_PERIODS,
  21. DEFAULT_STATS_PERIOD,
  22. } from 'sentry/constants';
  23. import {t} from 'sentry/locale';
  24. import {PageHeader} from 'sentry/styles/organization';
  25. import space from 'sentry/styles/space';
  26. import {DataCategory, DateString, Organization, Project} from 'sentry/types';
  27. import withOrganization from 'sentry/utils/withOrganization';
  28. import HeaderTabs from 'sentry/views/organizationStats/header';
  29. import {CHART_OPTIONS_DATACATEGORY, ChartDataTransform} from './usageChart';
  30. import UsageStatsOrg from './usageStatsOrg';
  31. import UsageStatsProjects from './usageStatsProjects';
  32. const HookHeader = HookOrDefault({hookName: 'component:org-stats-banner'});
  33. export const PAGE_QUERY_PARAMS = [
  34. 'pageStatsPeriod',
  35. 'pageStart',
  36. 'pageEnd',
  37. 'pageUtc',
  38. 'dataCategory',
  39. 'transform',
  40. 'sort',
  41. 'query',
  42. 'cursor',
  43. ];
  44. type Props = {
  45. organization: Organization;
  46. } & RouteComponentProps<{orgId: string}, {}>;
  47. export class OrganizationStats extends Component<Props> {
  48. get dataCategory(): DataCategory {
  49. const dataCategory = this.props.location?.query?.dataCategory;
  50. switch (dataCategory) {
  51. case DataCategory.ERRORS:
  52. case DataCategory.TRANSACTIONS:
  53. case DataCategory.ATTACHMENTS:
  54. case DataCategory.PROFILES:
  55. return dataCategory as DataCategory;
  56. default:
  57. return DataCategory.ERRORS;
  58. }
  59. }
  60. get dataCategoryName(): string {
  61. const dataCategory = this.dataCategory;
  62. return DATA_CATEGORY_NAMES[dataCategory] ?? t('Unknown Data Category');
  63. }
  64. get dataDatetime(): DateTimeObject {
  65. const query = this.props.location?.query ?? {};
  66. const {
  67. start,
  68. end,
  69. statsPeriod,
  70. utc: utcString,
  71. } = normalizeDateTimeParams(query, {
  72. allowEmptyPeriod: true,
  73. allowAbsoluteDatetime: true,
  74. allowAbsolutePageDatetime: true,
  75. });
  76. if (!statsPeriod && !start && !end) {
  77. return {period: DEFAULT_STATS_PERIOD};
  78. }
  79. // Following getParams, statsPeriod will take priority over start/end
  80. if (statsPeriod) {
  81. return {period: statsPeriod};
  82. }
  83. const utc = utcString === 'true';
  84. if (start && end) {
  85. return utc
  86. ? {
  87. start: moment.utc(start).format(),
  88. end: moment.utc(end).format(),
  89. utc,
  90. }
  91. : {
  92. start: moment(start).utc().format(),
  93. end: moment(end).utc().format(),
  94. utc,
  95. };
  96. }
  97. return {period: DEFAULT_STATS_PERIOD};
  98. }
  99. // Validation and type-casting should be handled by chart
  100. get chartTransform(): string | undefined {
  101. return this.props.location?.query?.transform;
  102. }
  103. // Validation and type-casting should be handled by table
  104. get tableSort(): string | undefined {
  105. return this.props.location?.query?.sort;
  106. }
  107. get tableQuery(): string | undefined {
  108. return this.props.location?.query?.query;
  109. }
  110. get tableCursor(): string | undefined {
  111. return this.props.location?.query?.cursor;
  112. }
  113. getNextLocations = (project: Project): Record<string, LocationDescriptorObject> => {
  114. const {location, organization} = this.props;
  115. const nextLocation: LocationDescriptorObject = {
  116. ...location,
  117. query: {
  118. ...location.query,
  119. project: project.id,
  120. },
  121. };
  122. // Do not leak out page-specific keys
  123. nextLocation.query = omit(nextLocation.query, PAGE_QUERY_PARAMS);
  124. return {
  125. performance: {
  126. ...nextLocation,
  127. pathname: `/organizations/${organization.slug}/performance/`,
  128. },
  129. projectDetail: {
  130. ...nextLocation,
  131. pathname: `/organizations/${organization.slug}/projects/${project.slug}/`,
  132. },
  133. issueList: {
  134. ...nextLocation,
  135. pathname: `/organizations/${organization.slug}/issues/`,
  136. },
  137. settings: {
  138. pathname: `/settings/${organization.slug}/projects/${project.slug}/`,
  139. },
  140. };
  141. };
  142. handleUpdateDatetime = (datetime: ChangeData): LocationDescriptorObject => {
  143. const {start, end, relative, utc} = datetime;
  144. if (start && end) {
  145. const parser = utc ? moment.utc : moment;
  146. return this.setStateOnUrl({
  147. pageStatsPeriod: undefined,
  148. pageStart: parser(start).format(),
  149. pageEnd: parser(end).format(),
  150. pageUtc: utc ?? undefined,
  151. });
  152. }
  153. return this.setStateOnUrl({
  154. pageStatsPeriod: relative || undefined,
  155. pageStart: undefined,
  156. pageEnd: undefined,
  157. pageUtc: undefined,
  158. });
  159. };
  160. /**
  161. * TODO: Enable user to set dateStart/dateEnd
  162. *
  163. * See PAGE_QUERY_PARAMS for list of accepted keys on nextState
  164. */
  165. setStateOnUrl = (
  166. nextState: {
  167. cursor?: string;
  168. dataCategory?: DataCategory;
  169. pageEnd?: DateString;
  170. pageStart?: DateString;
  171. pageStatsPeriod?: string | null;
  172. pageUtc?: boolean | null;
  173. query?: string;
  174. sort?: string;
  175. transform?: ChartDataTransform;
  176. },
  177. options: {
  178. willUpdateRouter?: boolean;
  179. } = {
  180. willUpdateRouter: true,
  181. }
  182. ): LocationDescriptorObject => {
  183. const {location, router} = this.props;
  184. const nextQueryParams = pick(nextState, PAGE_QUERY_PARAMS);
  185. const nextLocation = {
  186. ...location,
  187. query: {
  188. ...location?.query,
  189. ...nextQueryParams,
  190. },
  191. };
  192. if (options.willUpdateRouter) {
  193. router.push(nextLocation);
  194. }
  195. return nextLocation;
  196. };
  197. renderPageControl = () => {
  198. const {organization} = this.props;
  199. const {start, end, period, utc} = this.dataDatetime;
  200. return (
  201. <Fragment>
  202. <DropdownDataCategory
  203. triggerProps={{prefix: t('Category')}}
  204. value={this.dataCategory}
  205. options={CHART_OPTIONS_DATACATEGORY}
  206. onChange={opt => this.setStateOnUrl({dataCategory: opt.value as DataCategory})}
  207. />
  208. <StyledPageTimeRangeSelector
  209. organization={organization}
  210. relative={period ?? ''}
  211. start={start ?? null}
  212. end={end ?? null}
  213. utc={utc ?? null}
  214. onUpdate={this.handleUpdateDatetime}
  215. relativeOptions={omit(DEFAULT_RELATIVE_PERIODS, ['1h'])}
  216. />
  217. </Fragment>
  218. );
  219. };
  220. render() {
  221. const {organization} = this.props;
  222. const hasTeamInsights = organization.features.includes('team-insights');
  223. return (
  224. <SentryDocumentTitle title="Usage Stats">
  225. <Fragment>
  226. {hasTeamInsights && (
  227. <HeaderTabs organization={organization} activeTab="stats" />
  228. )}
  229. <Body>
  230. <Layout.Main fullWidth>
  231. {!hasTeamInsights && (
  232. <Fragment>
  233. <PageHeader>
  234. <PageHeading>{t('Organization Usage Stats')}</PageHeading>
  235. </PageHeader>
  236. <p>
  237. {t(
  238. 'We collect usage metrics on three categories: errors, transactions, and attachments. The charts below reflect data that Sentry has received across your entire organization. You can also find them broken down by project in the table.'
  239. )}
  240. </p>
  241. </Fragment>
  242. )}
  243. <HookHeader organization={organization} />
  244. <PageGrid>
  245. {this.renderPageControl()}
  246. <ErrorBoundary mini>
  247. <UsageStatsOrg
  248. organization={organization}
  249. dataCategory={this.dataCategory}
  250. dataCategoryName={this.dataCategoryName}
  251. dataDatetime={this.dataDatetime}
  252. chartTransform={this.chartTransform}
  253. handleChangeState={this.setStateOnUrl}
  254. />
  255. </ErrorBoundary>
  256. </PageGrid>
  257. <ErrorBoundary mini>
  258. <UsageStatsProjects
  259. organization={organization}
  260. dataCategory={this.dataCategory}
  261. dataCategoryName={this.dataCategoryName}
  262. dataDatetime={this.dataDatetime}
  263. tableSort={this.tableSort}
  264. tableQuery={this.tableQuery}
  265. tableCursor={this.tableCursor}
  266. handleChangeState={this.setStateOnUrl}
  267. getNextLocations={this.getNextLocations}
  268. />
  269. </ErrorBoundary>
  270. </Layout.Main>
  271. </Body>
  272. </Fragment>
  273. </SentryDocumentTitle>
  274. );
  275. }
  276. }
  277. export default withOrganization(OrganizationStats);
  278. const PageGrid = styled('div')`
  279. display: grid;
  280. grid-template-columns: 1fr;
  281. gap: ${space(2)};
  282. @media (min-width: ${p => p.theme.breakpoints.small}) {
  283. grid-template-columns: repeat(2, 1fr);
  284. }
  285. @media (min-width: ${p => p.theme.breakpoints.large}) {
  286. grid-template-columns: repeat(4, 1fr);
  287. }
  288. `;
  289. const DropdownDataCategory = styled(CompactSelect)`
  290. grid-column: auto / span 1;
  291. button[aria-haspopup='listbox'] {
  292. width: 100%;
  293. height: 100%;
  294. }
  295. @media (min-width: ${p => p.theme.breakpoints.small}) {
  296. grid-column: auto / span 2;
  297. }
  298. @media (min-width: ${p => p.theme.breakpoints.large}) {
  299. grid-column: auto / span 1;
  300. }
  301. `;
  302. const StyledPageTimeRangeSelector = styled(PageTimeRangeSelector)`
  303. grid-column: auto / span 1;
  304. @media (min-width: ${p => p.theme.breakpoints.small}) {
  305. grid-column: auto / span 2;
  306. }
  307. @media (min-width: ${p => p.theme.breakpoints.large}) {
  308. grid-column: auto / span 3;
  309. }
  310. `;
  311. const Body = styled(Layout.Body)`
  312. @media (min-width: ${p => p.theme.breakpoints.medium}) {
  313. display: block;
  314. }
  315. `;