usageStatsProjects.tsx 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482
  1. import {Fragment} from 'react';
  2. import styled from '@emotion/styled';
  3. import * as Sentry from '@sentry/react';
  4. import type {LocationDescriptorObject} from 'history';
  5. import isEqual from 'lodash/isEqual';
  6. import type {DateTimeObject} from 'sentry/components/charts/utils';
  7. import {getSeriesApiInterval} from 'sentry/components/charts/utils';
  8. import DeprecatedAsyncComponent from 'sentry/components/deprecatedAsyncComponent';
  9. import type {Alignments, Directions} from 'sentry/components/gridEditable/sortLink';
  10. import SortLink from 'sentry/components/gridEditable/sortLink';
  11. import Pagination from 'sentry/components/pagination';
  12. import SearchBar from 'sentry/components/searchBar';
  13. import {DATA_CATEGORY_INFO, DEFAULT_STATS_PERIOD} from 'sentry/constants';
  14. import {ALL_ACCESS_PROJECTS} from 'sentry/constants/pageFilters';
  15. import {t} from 'sentry/locale';
  16. import {space} from 'sentry/styles/space';
  17. import type {DataCategoryInfo, Organization, Project} from 'sentry/types';
  18. import {Outcome} from 'sentry/types';
  19. import withProjects from 'sentry/utils/withProjects';
  20. import type {UsageSeries} from './types';
  21. import type {TableStat} from './usageTable';
  22. import UsageTable, {CellProject, CellStat} from './usageTable';
  23. import {getOffsetFromCursor, getPaginationPageLink} from './utils';
  24. type Props = {
  25. dataCategory: DataCategoryInfo;
  26. dataCategoryName: string;
  27. dataDatetime: DateTimeObject;
  28. getNextLocations: (project: Project) => Record<string, LocationDescriptorObject>;
  29. handleChangeState: (
  30. nextState: {
  31. cursor?: string;
  32. query?: string;
  33. sort?: string;
  34. },
  35. options?: {willUpdateRouter?: boolean}
  36. ) => LocationDescriptorObject;
  37. isSingleProject: boolean;
  38. loadingProjects: boolean;
  39. organization: Organization;
  40. projectIds: number[];
  41. projects: Project[];
  42. tableCursor?: string;
  43. tableQuery?: string;
  44. tableSort?: string;
  45. } & DeprecatedAsyncComponent['props'];
  46. type State = {
  47. projectStats: UsageSeries | undefined;
  48. } & DeprecatedAsyncComponent['state'];
  49. export enum SortBy {
  50. PROJECT = 'project',
  51. TOTAL = 'total',
  52. ACCEPTED = 'accepted',
  53. FILTERED = 'filtered',
  54. DROPPED = 'dropped',
  55. INVALID = 'invalid',
  56. RATE_LIMITED = 'rate_limited',
  57. }
  58. class UsageStatsProjects extends DeprecatedAsyncComponent<Props, State> {
  59. static MAX_ROWS_USAGE_TABLE = 25;
  60. componentDidUpdate(prevProps: Props) {
  61. const {
  62. dataDatetime: prevDateTime,
  63. dataCategory: prevDataCategory,
  64. projectIds: prevProjectIds,
  65. } = prevProps;
  66. const {
  67. dataDatetime: currDateTime,
  68. dataCategory: currDataCategory,
  69. projectIds: currProjectIds,
  70. } = this.props;
  71. if (
  72. prevDateTime.start !== currDateTime.start ||
  73. prevDateTime.end !== currDateTime.end ||
  74. prevDateTime.period !== currDateTime.period ||
  75. prevDateTime.utc !== currDateTime.utc ||
  76. prevDataCategory !== currDataCategory ||
  77. !isEqual(prevProjectIds, currProjectIds)
  78. ) {
  79. this.reloadData();
  80. }
  81. }
  82. getEndpoints(): ReturnType<DeprecatedAsyncComponent['getEndpoints']> {
  83. return [['projectStats', this.endpointPath, {query: this.endpointQuery}]];
  84. }
  85. get endpointPath() {
  86. const {organization} = this.props;
  87. return `/organizations/${organization.slug}/stats_v2/`;
  88. }
  89. get endpointQuery() {
  90. const {dataDatetime, dataCategory, projectIds, isSingleProject} = this.props;
  91. const queryDatetime =
  92. dataDatetime.start && dataDatetime.end
  93. ? {
  94. start: dataDatetime.start,
  95. end: dataDatetime.end,
  96. utc: dataDatetime.utc,
  97. }
  98. : {
  99. statsPeriod: dataDatetime.period || DEFAULT_STATS_PERIOD,
  100. };
  101. // We do not need more granularity in the data so interval is '1d'
  102. return {
  103. ...queryDatetime,
  104. interval: getSeriesApiInterval(dataDatetime),
  105. groupBy: ['outcome', 'project'],
  106. field: ['sum(quantity)'],
  107. // If only one project is in selected, display the entire project list
  108. project: isSingleProject ? [ALL_ACCESS_PROJECTS] : projectIds,
  109. category: dataCategory.apiName,
  110. };
  111. }
  112. get tableData() {
  113. const {projectStats} = this.state;
  114. return {
  115. headers: this.tableHeader,
  116. ...this.mapSeriesToTable(projectStats),
  117. };
  118. }
  119. get tableSort(): {
  120. direction: number;
  121. key: SortBy;
  122. } {
  123. const {tableSort} = this.props;
  124. if (!tableSort) {
  125. return {
  126. key: SortBy.TOTAL,
  127. direction: 1,
  128. };
  129. }
  130. let key: string = tableSort;
  131. let direction: number = -1;
  132. if (tableSort.charAt(0) === '-') {
  133. key = key.slice(1);
  134. direction = 1;
  135. }
  136. switch (key) {
  137. case SortBy.PROJECT:
  138. case SortBy.TOTAL:
  139. case SortBy.ACCEPTED:
  140. case SortBy.FILTERED:
  141. case SortBy.DROPPED:
  142. return {key, direction};
  143. default:
  144. return {key: SortBy.ACCEPTED, direction: -1};
  145. }
  146. }
  147. get tableOffset() {
  148. const {tableCursor} = this.props;
  149. return getOffsetFromCursor(tableCursor);
  150. }
  151. /**
  152. * OrganizationStatsEndpointV2 does not have any performance issues. We use
  153. * client-side pagination to limit the number of rows on the table so the
  154. * page doesn't scroll too deeply for organizations with a lot of projects
  155. */
  156. get pageLink() {
  157. const offset = this.tableOffset;
  158. const numRows = this.filteredProjects.length;
  159. return getPaginationPageLink({
  160. numRows,
  161. pageSize: UsageStatsProjects.MAX_ROWS_USAGE_TABLE,
  162. offset,
  163. });
  164. }
  165. get projectSelectionFilter(): (p: Project) => boolean {
  166. const {projectIds, isSingleProject} = this.props;
  167. const selectedProjects = new Set(projectIds.map(id => `${id}`));
  168. // If 'My Projects' or 'All Projects' are selected
  169. return selectedProjects.size === 0 || selectedProjects.has('-1') || isSingleProject
  170. ? _p => true
  171. : p => selectedProjects.has(p.id);
  172. }
  173. /**
  174. * Filter projects if there's a query
  175. */
  176. get filteredProjects() {
  177. const {projects, tableQuery} = this.props;
  178. return tableQuery
  179. ? projects.filter(
  180. p =>
  181. p.slug.includes(tableQuery) && p.hasAccess && this.projectSelectionFilter(p)
  182. )
  183. : projects.filter(p => p.hasAccess && this.projectSelectionFilter(p));
  184. }
  185. get tableHeader() {
  186. const {key, direction} = this.tableSort;
  187. const getArrowDirection = (linkKey: SortBy): Directions => {
  188. if (linkKey !== key) {
  189. return undefined;
  190. }
  191. return direction > 0 ? 'desc' : 'asc';
  192. };
  193. return [
  194. {
  195. key: SortBy.PROJECT,
  196. title: t('Project'),
  197. align: 'left',
  198. direction: getArrowDirection(SortBy.PROJECT),
  199. onClick: () => this.handleChangeSort(SortBy.PROJECT),
  200. },
  201. {
  202. key: SortBy.TOTAL,
  203. title: t('Total'),
  204. align: 'right',
  205. direction: getArrowDirection(SortBy.TOTAL),
  206. onClick: () => this.handleChangeSort(SortBy.TOTAL),
  207. },
  208. {
  209. key: SortBy.ACCEPTED,
  210. title: t('Accepted'),
  211. align: 'right',
  212. direction: getArrowDirection(SortBy.ACCEPTED),
  213. onClick: () => this.handleChangeSort(SortBy.ACCEPTED),
  214. },
  215. {
  216. key: SortBy.FILTERED,
  217. title: t('Filtered'),
  218. align: 'right',
  219. direction: getArrowDirection(SortBy.FILTERED),
  220. onClick: () => this.handleChangeSort(SortBy.FILTERED),
  221. },
  222. {
  223. key: SortBy.DROPPED,
  224. title: t('Dropped'),
  225. align: 'right',
  226. direction: getArrowDirection(SortBy.DROPPED),
  227. onClick: () => this.handleChangeSort(SortBy.DROPPED),
  228. },
  229. ]
  230. .map(h => {
  231. const Cell = h.key === SortBy.PROJECT ? CellProject : CellStat;
  232. return (
  233. <Cell key={h.key}>
  234. <SortLink
  235. canSort
  236. title={h.title}
  237. align={h.align as Alignments}
  238. direction={h.direction}
  239. generateSortLink={h.onClick}
  240. />
  241. </Cell>
  242. );
  243. })
  244. .concat([<CellStat key="empty" />]); // Extra column for displaying buttons etc.
  245. }
  246. getProjectLink(project: Project) {
  247. const {dataCategory, getNextLocations, organization} = this.props;
  248. const {performance, projectDetail, settings} = getNextLocations(project);
  249. if (
  250. dataCategory === DATA_CATEGORY_INFO.transaction &&
  251. organization.features.includes('performance-view')
  252. ) {
  253. return {
  254. projectLink: performance,
  255. projectSettingsLink: settings,
  256. };
  257. }
  258. return {
  259. projectLink: projectDetail,
  260. projectSettingsLink: settings,
  261. };
  262. }
  263. handleChangeSort = (nextKey: SortBy) => {
  264. const {handleChangeState} = this.props;
  265. const {key, direction} = this.tableSort;
  266. let nextDirection = 1; // Default to descending
  267. if (key === nextKey) {
  268. nextDirection = direction * -1; // Toggle if clicking on the same column
  269. } else if (nextKey === SortBy.PROJECT) {
  270. nextDirection = -1; // Default PROJECT to ascending
  271. }
  272. // The header uses SortLink, which takes a LocationDescriptor and pushes
  273. // that to the router. As such, we do not need to update the router in
  274. // handleChangeState
  275. return handleChangeState(
  276. {sort: `${nextDirection > 0 ? '-' : ''}${nextKey}`},
  277. {willUpdateRouter: false}
  278. );
  279. };
  280. handleSearch = (query: string) => {
  281. const {handleChangeState, tableQuery} = this.props;
  282. if (query === tableQuery) {
  283. return;
  284. }
  285. if (!query) {
  286. handleChangeState({query: undefined, cursor: undefined});
  287. return;
  288. }
  289. handleChangeState({query, cursor: undefined});
  290. };
  291. mapSeriesToTable(projectStats?: UsageSeries): {
  292. tableStats: TableStat[];
  293. error?: Error;
  294. } {
  295. if (!projectStats) {
  296. return {tableStats: []};
  297. }
  298. const stats: Record<number, object> = {};
  299. try {
  300. const baseStat: Partial<TableStat> = {
  301. [SortBy.TOTAL]: 0,
  302. [SortBy.ACCEPTED]: 0,
  303. [SortBy.FILTERED]: 0,
  304. [SortBy.DROPPED]: 0,
  305. };
  306. const projectList = this.filteredProjects;
  307. const projectSet = new Set(projectList.map(p => p.id));
  308. projectStats.groups.forEach(group => {
  309. const {outcome, project: projectId} = group.by;
  310. // Backend enum is singlar. Frontend enum is plural.
  311. if (!projectSet.has(projectId.toString())) {
  312. return;
  313. }
  314. if (!stats[projectId]) {
  315. stats[projectId] = {...baseStat};
  316. }
  317. if (outcome !== Outcome.CLIENT_DISCARD) {
  318. stats[projectId].total += group.totals['sum(quantity)'];
  319. }
  320. if (outcome === Outcome.ACCEPTED || outcome === Outcome.FILTERED) {
  321. stats[projectId][outcome] += group.totals['sum(quantity)'];
  322. } else if (
  323. outcome === Outcome.RATE_LIMITED ||
  324. outcome === Outcome.INVALID ||
  325. outcome === Outcome.DROPPED
  326. ) {
  327. stats[projectId][SortBy.DROPPED] += group.totals['sum(quantity)'];
  328. }
  329. });
  330. // For projects without stats, fill in with zero
  331. const tableStats: TableStat[] = projectList.map(proj => {
  332. const stat = stats[proj.id] ?? {...baseStat};
  333. return {
  334. project: {...proj},
  335. ...this.getProjectLink(proj),
  336. ...stat,
  337. };
  338. });
  339. const {key, direction} = this.tableSort;
  340. tableStats.sort((a, b) => {
  341. if (key === SortBy.PROJECT) {
  342. return b.project.slug.localeCompare(a.project.slug) * direction;
  343. }
  344. return a[key] !== b[key]
  345. ? (b[key] - a[key]) * direction
  346. : a.project.slug.localeCompare(b.project.slug);
  347. });
  348. const offset = this.tableOffset;
  349. return {
  350. tableStats: tableStats.slice(
  351. offset,
  352. offset + UsageStatsProjects.MAX_ROWS_USAGE_TABLE
  353. ),
  354. };
  355. } catch (err) {
  356. Sentry.withScope(scope => {
  357. scope.setContext('query', this.endpointQuery);
  358. scope.setContext('body', {...projectStats});
  359. Sentry.captureException(err);
  360. });
  361. return {
  362. tableStats: [],
  363. error: err,
  364. };
  365. }
  366. }
  367. renderComponent() {
  368. const {error, errors, loading} = this.state;
  369. const {dataCategory, loadingProjects, tableQuery, isSingleProject} = this.props;
  370. const {headers, tableStats} = this.tableData;
  371. return (
  372. <Fragment>
  373. {isSingleProject && (
  374. <PanelHeading>
  375. <Title>{t('All Projects')}</Title>
  376. </PanelHeading>
  377. )}
  378. {!isSingleProject && (
  379. <Container>
  380. <SearchBar
  381. defaultQuery=""
  382. query={tableQuery}
  383. placeholder={t('Filter your projects')}
  384. onSearch={this.handleSearch}
  385. />
  386. </Container>
  387. )}
  388. <Container data-test-id="usage-stats-table">
  389. <UsageTable
  390. isLoading={loading || loadingProjects}
  391. isError={error}
  392. errors={errors as any} // TODO(ts)
  393. isEmpty={tableStats.length === 0}
  394. headers={headers}
  395. dataCategory={dataCategory}
  396. usageStats={tableStats}
  397. />
  398. <Pagination pageLinks={this.pageLink} />
  399. </Container>
  400. </Fragment>
  401. );
  402. }
  403. }
  404. export default withProjects(UsageStatsProjects);
  405. const Container = styled('div')`
  406. margin-bottom: ${space(2)};
  407. `;
  408. const Title = styled('div')`
  409. font-weight: bold;
  410. font-size: ${p => p.theme.fontSizeLarge};
  411. color: ${p => p.theme.gray400};
  412. display: flex;
  413. flex: 1;
  414. align-items: center;
  415. `;
  416. const PanelHeading = styled('div')`
  417. display: flex;
  418. margin-bottom: ${space(2)};
  419. align-items: center;
  420. `;