usageStatsProjects.tsx 13 KB

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