usageStatsProjects.tsx 12 KB

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