index.tsx 11 KB

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