usageStatsProjects.tsx 13 KB

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