usageStatsProjects.tsx 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481
  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. ]
  229. .map(h => {
  230. const Cell = h.key === SortBy.PROJECT ? CellProject : CellStat;
  231. return (
  232. <Cell key={h.key}>
  233. <SortLink
  234. canSort
  235. title={h.title}
  236. align={h.align as Alignments}
  237. direction={h.direction}
  238. generateSortLink={h.onClick}
  239. />
  240. </Cell>
  241. );
  242. })
  243. .concat([<CellStat key="empty" />]); // Extra column for displaying buttons etc.
  244. }
  245. getProjectLink(project: Project) {
  246. const {dataCategory, getNextLocations, organization} = this.props;
  247. const {performance, projectDetail, settings} = getNextLocations(project);
  248. if (
  249. dataCategory === DATA_CATEGORY_INFO.transaction.plural &&
  250. organization.features.includes('performance-view')
  251. ) {
  252. return {
  253. projectLink: performance,
  254. projectSettingsLink: settings,
  255. };
  256. }
  257. return {
  258. projectLink: projectDetail,
  259. projectSettingsLink: settings,
  260. };
  261. }
  262. handleChangeSort = (nextKey: SortBy) => {
  263. const {handleChangeState} = this.props;
  264. const {key, direction} = this.tableSort;
  265. let nextDirection = 1; // Default to descending
  266. if (key === nextKey) {
  267. nextDirection = direction * -1; // Toggle if clicking on the same column
  268. } else if (nextKey === SortBy.PROJECT) {
  269. nextDirection = -1; // Default PROJECT to ascending
  270. }
  271. // The header uses SortLink, which takes a LocationDescriptor and pushes
  272. // that to the router. As such, we do not need to update the router in
  273. // handleChangeState
  274. return handleChangeState(
  275. {sort: `${nextDirection > 0 ? '-' : ''}${nextKey}`},
  276. {willUpdateRouter: false}
  277. );
  278. };
  279. handleSearch = (query: string) => {
  280. const {handleChangeState, tableQuery} = this.props;
  281. if (query === tableQuery) {
  282. return;
  283. }
  284. if (!query) {
  285. handleChangeState({query: undefined, cursor: undefined});
  286. return;
  287. }
  288. handleChangeState({query, cursor: undefined});
  289. };
  290. mapSeriesToTable(projectStats?: UsageSeries): {
  291. tableStats: TableStat[];
  292. error?: Error;
  293. } {
  294. if (!projectStats) {
  295. return {tableStats: []};
  296. }
  297. const stats: Record<number, object> = {};
  298. try {
  299. const baseStat: Partial<TableStat> = {
  300. [SortBy.TOTAL]: 0,
  301. [SortBy.ACCEPTED]: 0,
  302. [SortBy.FILTERED]: 0,
  303. [SortBy.DROPPED]: 0,
  304. };
  305. const projectList = this.filteredProjects;
  306. const projectSet = new Set(projectList.map(p => p.id));
  307. projectStats.groups.forEach(group => {
  308. const {outcome, project: projectId} = group.by;
  309. // Backend enum is singlar. Frontend enum is plural.
  310. if (!projectSet.has(projectId.toString())) {
  311. return;
  312. }
  313. if (!stats[projectId]) {
  314. stats[projectId] = {...baseStat};
  315. }
  316. if (outcome !== Outcome.CLIENT_DISCARD) {
  317. stats[projectId].total += group.totals['sum(quantity)'];
  318. }
  319. if (outcome === Outcome.ACCEPTED || outcome === Outcome.FILTERED) {
  320. stats[projectId][outcome] += group.totals['sum(quantity)'];
  321. } else if (
  322. outcome === Outcome.RATE_LIMITED ||
  323. outcome === Outcome.INVALID ||
  324. outcome === Outcome.DROPPED
  325. ) {
  326. stats[projectId][SortBy.DROPPED] += group.totals['sum(quantity)'];
  327. }
  328. });
  329. // For projects without stats, fill in with zero
  330. const tableStats: TableStat[] = projectList.map(proj => {
  331. const stat = stats[proj.id] ?? {...baseStat};
  332. return {
  333. project: {...proj},
  334. ...this.getProjectLink(proj),
  335. ...stat,
  336. };
  337. });
  338. const {key, direction} = this.tableSort;
  339. tableStats.sort((a, b) => {
  340. if (key === SortBy.PROJECT) {
  341. return b.project.slug.localeCompare(a.project.slug) * direction;
  342. }
  343. return a[key] !== b[key]
  344. ? (b[key] - a[key]) * direction
  345. : a.project.slug.localeCompare(b.project.slug);
  346. });
  347. const offset = this.tableCursor;
  348. return {
  349. tableStats: tableStats.slice(
  350. offset,
  351. offset + UsageStatsProjects.MAX_ROWS_USAGE_TABLE
  352. ),
  353. };
  354. } catch (err) {
  355. Sentry.withScope(scope => {
  356. scope.setContext('query', this.endpointQuery);
  357. scope.setContext('body', {...projectStats});
  358. Sentry.captureException(err);
  359. });
  360. return {
  361. tableStats: [],
  362. error: err,
  363. };
  364. }
  365. }
  366. renderComponent() {
  367. const {error, errors, loading} = this.state;
  368. const {dataCategory, loadingProjects, tableQuery, isSingleProject} = this.props;
  369. const {headers, tableStats} = this.tableData;
  370. return (
  371. <Fragment>
  372. {isSingleProject && (
  373. <PanelHeading>
  374. <Title>{t('All Projects')}</Title>
  375. </PanelHeading>
  376. )}
  377. {!isSingleProject && (
  378. <Container>
  379. <SearchBar
  380. defaultQuery=""
  381. query={tableQuery}
  382. placeholder={t('Filter your projects')}
  383. onSearch={this.handleSearch}
  384. />
  385. </Container>
  386. )}
  387. <Container data-test-id="usage-stats-table">
  388. <UsageTable
  389. isLoading={loading || loadingProjects}
  390. isError={error}
  391. errors={errors as any} // TODO(ts)
  392. isEmpty={tableStats.length === 0}
  393. headers={headers}
  394. dataCategory={dataCategory}
  395. usageStats={tableStats}
  396. />
  397. <Pagination pageLinks={this.pageLink} />
  398. </Container>
  399. </Fragment>
  400. );
  401. }
  402. }
  403. export default withProjects(UsageStatsProjects);
  404. const Container = styled('div')`
  405. margin-bottom: ${space(2)};
  406. `;
  407. const Title = styled('div')`
  408. font-weight: bold;
  409. font-size: ${p => p.theme.fontSizeLarge};
  410. color: ${p => p.theme.gray400};
  411. display: flex;
  412. flex: 1;
  413. align-items: center;
  414. `;
  415. const PanelHeading = styled('div')`
  416. display: flex;
  417. margin-bottom: ${space(2)};
  418. align-items: center;
  419. `;