usageStatsProjects.tsx 12 KB

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