index.tsx 10 KB

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