table.tsx 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483
  1. import * as React from 'react';
  2. import {browserHistory} from 'react-router';
  3. import {Location, LocationDescriptorObject} from 'history';
  4. import {addSuccessMessage} from 'app/actionCreators/indicator';
  5. import {openModal} from 'app/actionCreators/modal';
  6. import {fetchLegacyKeyTransactionsCount} from 'app/actionCreators/performance';
  7. import GuideAnchor from 'app/components/assistant/guideAnchor';
  8. import GridEditable, {COL_WIDTH_UNDEFINED, GridColumn} from 'app/components/gridEditable';
  9. import SortLink from 'app/components/gridEditable/sortLink';
  10. import Link from 'app/components/links/link';
  11. import Pagination from 'app/components/pagination';
  12. import Tooltip from 'app/components/tooltip';
  13. import {IconStar} from 'app/icons';
  14. import {tct} from 'app/locale';
  15. import {Organization, Project} from 'app/types';
  16. import {defined} from 'app/utils';
  17. import trackAdvancedAnalyticsEvent from 'app/utils/analytics/trackAdvancedAnalyticsEvent';
  18. import DiscoverQuery, {TableData, TableDataRow} from 'app/utils/discover/discoverQuery';
  19. import EventView, {EventData, isFieldSortable} from 'app/utils/discover/eventView';
  20. import {getFieldRenderer} from 'app/utils/discover/fieldRenderers';
  21. import {fieldAlignment, getAggregateAlias} from 'app/utils/discover/fields';
  22. import {MutableSearch} from 'app/utils/tokenizeSearch';
  23. import CellAction, {Actions, updateQuery} from 'app/views/eventsV2/table/cellAction';
  24. import {TableColumn} from 'app/views/eventsV2/table/types';
  25. import TransactionThresholdModal, {
  26. modalCss,
  27. TransactionThresholdMetric,
  28. } from './transactionSummary/transactionThresholdModal';
  29. import {transactionSummaryRouteWithQuery} from './transactionSummary/utils';
  30. import {COLUMN_TITLES} from './data';
  31. export function getProjectID(
  32. eventData: EventData,
  33. projects: Project[]
  34. ): string | undefined {
  35. const projectSlug = (eventData?.project as string) || undefined;
  36. if (typeof projectSlug === undefined) {
  37. return undefined;
  38. }
  39. const project = projects.find(currentProject => currentProject.slug === projectSlug);
  40. if (!project) {
  41. return undefined;
  42. }
  43. return project.id;
  44. }
  45. type Props = {
  46. eventView: EventView;
  47. organization: Organization;
  48. location: Location;
  49. setError: (msg: string | undefined) => void;
  50. summaryConditions: string;
  51. projects: Project[];
  52. columnTitles?: string[];
  53. };
  54. type State = {
  55. widths: number[];
  56. keyedTransactions: number | null;
  57. transaction: string | undefined;
  58. transactionThreshold: number | undefined;
  59. transactionThresholdMetric: TransactionThresholdMetric | undefined;
  60. };
  61. class Table extends React.Component<Props, State> {
  62. state: State = {
  63. widths: [],
  64. keyedTransactions: null,
  65. transaction: undefined,
  66. transactionThreshold: undefined,
  67. transactionThresholdMetric: undefined,
  68. };
  69. componentDidMount() {
  70. this.fetchKeyTransactionCount();
  71. }
  72. async fetchKeyTransactionCount() {
  73. const {organization} = this.props;
  74. try {
  75. const count = await fetchLegacyKeyTransactionsCount(organization.slug);
  76. this.setState({keyedTransactions: count});
  77. } catch (error) {
  78. this.setState({keyedTransactions: null});
  79. }
  80. }
  81. handleCellAction = (column: TableColumn<keyof TableDataRow>, dataRow: TableDataRow) => {
  82. return (action: Actions, value: React.ReactText) => {
  83. const {eventView, location, organization, projects} = this.props;
  84. trackAdvancedAnalyticsEvent('performance_views.overview.cellaction', {
  85. organization,
  86. action,
  87. });
  88. if (action === Actions.EDIT_THRESHOLD) {
  89. const project_threshold = dataRow.project_threshold_config;
  90. const transactionName = dataRow.transaction as string;
  91. const projectID = getProjectID(dataRow, projects);
  92. openModal(
  93. modalProps => (
  94. <TransactionThresholdModal
  95. {...modalProps}
  96. organization={organization}
  97. transactionName={transactionName}
  98. eventView={eventView}
  99. project={projectID}
  100. transactionThreshold={project_threshold[1]}
  101. transactionThresholdMetric={project_threshold[0]}
  102. onApply={(threshold, metric) => {
  103. if (
  104. threshold !== project_threshold[1] ||
  105. metric !== project_threshold[0]
  106. ) {
  107. this.setState({
  108. transaction: transactionName,
  109. transactionThreshold: threshold,
  110. transactionThresholdMetric: metric,
  111. });
  112. }
  113. addSuccessMessage(
  114. tct('[transactionName] updated successfully', {
  115. transactionName,
  116. })
  117. );
  118. }}
  119. />
  120. ),
  121. {modalCss, backdrop: 'static'}
  122. );
  123. return;
  124. }
  125. const searchConditions = new MutableSearch(eventView.query);
  126. // remove any event.type queries since it is implied to apply to only transactions
  127. searchConditions.removeFilter('event.type');
  128. updateQuery(searchConditions, action, column, value);
  129. browserHistory.push({
  130. pathname: location.pathname,
  131. query: {
  132. ...location.query,
  133. cursor: undefined,
  134. query: searchConditions.formatString(),
  135. },
  136. });
  137. };
  138. };
  139. renderBodyCell(
  140. tableData: TableData | null,
  141. column: TableColumn<keyof TableDataRow>,
  142. dataRow: TableDataRow
  143. ): React.ReactNode {
  144. const {eventView, organization, projects, location} = this.props;
  145. if (!tableData || !tableData.meta) {
  146. return dataRow[column.key];
  147. }
  148. const tableMeta = tableData.meta;
  149. const field = String(column.key);
  150. const fieldRenderer = getFieldRenderer(field, tableMeta);
  151. const rendered = fieldRenderer(dataRow, {organization, location});
  152. const allowActions = [
  153. Actions.ADD,
  154. Actions.EXCLUDE,
  155. Actions.SHOW_GREATER_THAN,
  156. Actions.SHOW_LESS_THAN,
  157. ];
  158. if (organization.features.includes('project-transaction-threshold-override')) {
  159. allowActions.push(Actions.EDIT_THRESHOLD);
  160. }
  161. if (field === 'transaction') {
  162. const projectID = getProjectID(dataRow, projects);
  163. const summaryView = eventView.clone();
  164. if (dataRow['http.method']) {
  165. summaryView.additionalConditions.setFilterValues('http.method', [
  166. dataRow['http.method'] as string,
  167. ]);
  168. }
  169. summaryView.query = summaryView.getQueryWithAdditionalConditions();
  170. const target = transactionSummaryRouteWithQuery({
  171. orgSlug: organization.slug,
  172. transaction: String(dataRow.transaction) || '',
  173. query: summaryView.generateQueryStringObject(),
  174. projectID,
  175. });
  176. return (
  177. <CellAction
  178. column={column}
  179. dataRow={dataRow}
  180. handleCellAction={this.handleCellAction(column, dataRow)}
  181. allowActions={allowActions}
  182. >
  183. <Link to={target} onClick={this.handleSummaryClick}>
  184. {rendered}
  185. </Link>
  186. </CellAction>
  187. );
  188. }
  189. if (field.startsWith('key_transaction')) {
  190. // don't display per cell actions for key_transaction
  191. return rendered;
  192. }
  193. if (field.startsWith('team_key_transaction')) {
  194. // don't display per cell actions for team_key_transaction
  195. return rendered;
  196. }
  197. const fieldName = getAggregateAlias(field);
  198. const value = dataRow[fieldName];
  199. if (tableMeta[fieldName] === 'integer' && defined(value) && value > 999) {
  200. return (
  201. <Tooltip
  202. title={value.toLocaleString()}
  203. containerDisplayMode="block"
  204. position="right"
  205. >
  206. <CellAction
  207. column={column}
  208. dataRow={dataRow}
  209. handleCellAction={this.handleCellAction(column, dataRow)}
  210. allowActions={allowActions}
  211. >
  212. {rendered}
  213. </CellAction>
  214. </Tooltip>
  215. );
  216. }
  217. return (
  218. <CellAction
  219. column={column}
  220. dataRow={dataRow}
  221. handleCellAction={this.handleCellAction(column, dataRow)}
  222. allowActions={allowActions}
  223. >
  224. {rendered}
  225. </CellAction>
  226. );
  227. }
  228. renderBodyCellWithData = (tableData: TableData | null) => {
  229. return (
  230. column: TableColumn<keyof TableDataRow>,
  231. dataRow: TableDataRow
  232. ): React.ReactNode => this.renderBodyCell(tableData, column, dataRow);
  233. };
  234. onSortClick(currentSortKind?: string, currentSortField?: string) {
  235. const {organization} = this.props;
  236. trackAdvancedAnalyticsEvent('performance_views.landingv2.transactions.sort', {
  237. organization,
  238. field: currentSortField,
  239. direction: currentSortKind,
  240. });
  241. }
  242. renderHeadCell(
  243. tableMeta: TableData['meta'],
  244. column: TableColumn<keyof TableDataRow>,
  245. title: React.ReactNode
  246. ): React.ReactNode {
  247. const {eventView, location, organization} = this.props;
  248. const align = fieldAlignment(column.name, column.type, tableMeta);
  249. const field = {field: column.name, width: column.width};
  250. function generateSortLink(): LocationDescriptorObject | undefined {
  251. if (!tableMeta) {
  252. return undefined;
  253. }
  254. const nextEventView = eventView.sortOnField(field, tableMeta);
  255. const queryStringObject = nextEventView.generateQueryStringObject();
  256. return {
  257. ...location,
  258. query: {...location.query, sort: queryStringObject.sort},
  259. };
  260. }
  261. const currentSort = eventView.sortForField(field, tableMeta);
  262. const canSort = isFieldSortable(field, tableMeta);
  263. const currentSortKind = currentSort ? currentSort.kind : undefined;
  264. const currentSortField = currentSort ? currentSort.field : undefined;
  265. const sortLink = (
  266. <SortLink
  267. align={align}
  268. title={title || field.field}
  269. direction={currentSortKind}
  270. canSort={canSort}
  271. generateSortLink={generateSortLink}
  272. onClick={() => this.onSortClick(currentSortKind, currentSortField)}
  273. />
  274. );
  275. if (field.field.startsWith('user_misery')) {
  276. return (
  277. <GuideAnchor
  278. target="project_transaction_threshold"
  279. position="top"
  280. disabled={!organization.features.includes('project-transaction-threshold')}
  281. >
  282. {sortLink}
  283. </GuideAnchor>
  284. );
  285. }
  286. return sortLink;
  287. }
  288. renderHeadCellWithMeta = (tableMeta: TableData['meta']) => {
  289. const columnTitles = this.props.columnTitles ?? COLUMN_TITLES;
  290. return (column: TableColumn<keyof TableDataRow>, index: number): React.ReactNode =>
  291. this.renderHeadCell(tableMeta, column, columnTitles[index]);
  292. };
  293. renderPrependCellWithData = (tableData: TableData | null) => {
  294. const {eventView} = this.props;
  295. const {keyedTransactions} = this.state;
  296. const keyTransactionColumn = eventView
  297. .getColumns()
  298. .find((col: TableColumn<React.ReactText>) => col.name === 'key_transaction');
  299. const teamKeyTransactionColumn = eventView
  300. .getColumns()
  301. .find((col: TableColumn<React.ReactText>) => col.name === 'team_key_transaction');
  302. return (isHeader: boolean, dataRow?: any) => {
  303. if (keyTransactionColumn) {
  304. if (isHeader) {
  305. const star = (
  306. <IconStar
  307. key="keyTransaction"
  308. color="yellow300"
  309. isSolid
  310. data-test-id="key-transaction-header"
  311. />
  312. );
  313. return [this.renderHeadCell(tableData?.meta, keyTransactionColumn, star)];
  314. } else {
  315. return [this.renderBodyCell(tableData, keyTransactionColumn, dataRow)];
  316. }
  317. } else if (teamKeyTransactionColumn) {
  318. if (isHeader) {
  319. const star = (
  320. <GuideAnchor
  321. target="team_key_transaction_header"
  322. position="top"
  323. disabled={keyedTransactions === null} // wait for the legacy counts to load
  324. >
  325. <GuideAnchor
  326. target="team_key_transaction_existing"
  327. position="top"
  328. disabled={!keyedTransactions}
  329. >
  330. <IconStar
  331. key="keyTransaction"
  332. color="yellow300"
  333. isSolid
  334. data-test-id="team-key-transaction-header"
  335. />
  336. </GuideAnchor>
  337. </GuideAnchor>
  338. );
  339. return [this.renderHeadCell(tableData?.meta, teamKeyTransactionColumn, star)];
  340. } else {
  341. return [this.renderBodyCell(tableData, teamKeyTransactionColumn, dataRow)];
  342. }
  343. }
  344. return [];
  345. };
  346. };
  347. handleSummaryClick = () => {
  348. const {organization} = this.props;
  349. trackAdvancedAnalyticsEvent('performance_views.overview.navigate.summary', {
  350. organization,
  351. });
  352. };
  353. handleResizeColumn = (columnIndex: number, nextColumn: GridColumn) => {
  354. const widths: number[] = [...this.state.widths];
  355. widths[columnIndex] = nextColumn.width
  356. ? Number(nextColumn.width)
  357. : COL_WIDTH_UNDEFINED;
  358. this.setState({widths});
  359. };
  360. getSortedEventView() {
  361. const {eventView} = this.props;
  362. return eventView.withSorts([
  363. {
  364. field: 'team_key_transaction',
  365. kind: 'desc',
  366. },
  367. ...eventView.sorts,
  368. ]);
  369. }
  370. render() {
  371. const {eventView, organization, location, setError} = this.props;
  372. const {widths, transaction, transactionThreshold, transactionThresholdMetric} =
  373. this.state;
  374. const columnOrder = eventView
  375. .getColumns()
  376. // remove key_transactions from the column order as we'll be rendering it
  377. // via a prepended column
  378. .filter(
  379. (col: TableColumn<React.ReactText>) =>
  380. col.name !== 'key_transaction' &&
  381. col.name !== 'team_key_transaction' &&
  382. !col.name.startsWith('count_miserable') &&
  383. col.name !== 'project_threshold_config'
  384. )
  385. .map((col: TableColumn<React.ReactText>, i: number) => {
  386. if (typeof widths[i] === 'number') {
  387. return {...col, width: widths[i]};
  388. }
  389. return col;
  390. });
  391. const sortedEventView = this.getSortedEventView();
  392. const columnSortBy = sortedEventView.getSorts();
  393. const prependColumnWidths = ['max-content'];
  394. return (
  395. <div>
  396. <DiscoverQuery
  397. eventView={sortedEventView}
  398. orgSlug={organization.slug}
  399. location={location}
  400. setError={setError}
  401. referrer="api.performance.landing-table"
  402. transactionName={transaction}
  403. transactionThreshold={transactionThreshold}
  404. transactionThresholdMetric={transactionThresholdMetric}
  405. >
  406. {({pageLinks, isLoading, tableData}) => (
  407. <React.Fragment>
  408. <GridEditable
  409. isLoading={isLoading}
  410. data={tableData ? tableData.data : []}
  411. columnOrder={columnOrder}
  412. columnSortBy={columnSortBy}
  413. grid={{
  414. onResizeColumn: this.handleResizeColumn,
  415. renderHeadCell: this.renderHeadCellWithMeta(tableData?.meta) as any,
  416. renderBodyCell: this.renderBodyCellWithData(tableData) as any,
  417. renderPrependColumns: this.renderPrependCellWithData(tableData) as any,
  418. prependColumnWidths,
  419. }}
  420. location={location}
  421. />
  422. <Pagination pageLinks={pageLinks} />
  423. </React.Fragment>
  424. )}
  425. </DiscoverQuery>
  426. </div>
  427. );
  428. }
  429. }
  430. export default Table;