overview.tsx 39 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312
  1. import {Component} from 'react';
  2. import {browserHistory, RouteComponentProps} from 'react-router';
  3. import styled from '@emotion/styled';
  4. import {withProfiler} from '@sentry/react';
  5. import * as Sentry from '@sentry/react';
  6. import {Location} from 'history';
  7. import Cookies from 'js-cookie';
  8. import isEqual from 'lodash/isEqual';
  9. import mapValues from 'lodash/mapValues';
  10. import omit from 'lodash/omit';
  11. import pickBy from 'lodash/pickBy';
  12. import * as qs from 'query-string';
  13. import {addMessage} from 'sentry/actionCreators/indicator';
  14. import {fetchOrgMembers, indexMembersByProject} from 'sentry/actionCreators/members';
  15. import {fetchTagValues, loadOrganizationTags} from 'sentry/actionCreators/tags';
  16. import {Client} from 'sentry/api';
  17. import LoadingIndicator from 'sentry/components/loadingIndicator';
  18. import {extractSelectionParameters} from 'sentry/components/organizations/pageFilters/utils';
  19. import Pagination, {CursorHandler} from 'sentry/components/pagination';
  20. import {Panel, PanelBody} from 'sentry/components/panels';
  21. import QueryCount from 'sentry/components/queryCount';
  22. import ProcessingIssueList from 'sentry/components/stream/processingIssueList';
  23. import {DEFAULT_QUERY, DEFAULT_STATS_PERIOD} from 'sentry/constants';
  24. import {t, tct, tn} from 'sentry/locale';
  25. import GroupStore from 'sentry/stores/groupStore';
  26. import {PageContent} from 'sentry/styles/organization';
  27. import space from 'sentry/styles/space';
  28. import {
  29. BaseGroup,
  30. Group,
  31. IssueCategory,
  32. Organization,
  33. PageFilters,
  34. SavedSearch,
  35. TagCollection,
  36. } from 'sentry/types';
  37. import {defined} from 'sentry/utils';
  38. import trackAdvancedAnalyticsEvent from 'sentry/utils/analytics/trackAdvancedAnalyticsEvent';
  39. import CursorPoller from 'sentry/utils/cursorPoller';
  40. import {getUtcDateString} from 'sentry/utils/dates';
  41. import getCurrentSentryReactTransaction from 'sentry/utils/getCurrentSentryReactTransaction';
  42. import parseApiError from 'sentry/utils/parseApiError';
  43. import parseLinkHeader from 'sentry/utils/parseLinkHeader';
  44. import {VisuallyCompleteWithData} from 'sentry/utils/performanceForSentry';
  45. import {decodeScalar} from 'sentry/utils/queryString';
  46. import withRouteAnalytics, {
  47. WithRouteAnalyticsProps,
  48. } from 'sentry/utils/routeAnalytics/withRouteAnalytics';
  49. import withApi from 'sentry/utils/withApi';
  50. import {normalizeUrl} from 'sentry/utils/withDomainRequired';
  51. import withIssueTags from 'sentry/utils/withIssueTags';
  52. import withOrganization from 'sentry/utils/withOrganization';
  53. import withPageFilters from 'sentry/utils/withPageFilters';
  54. import withSavedSearches from 'sentry/utils/withSavedSearches';
  55. import SavedIssueSearches from 'sentry/views/issueList/savedIssueSearches';
  56. import IssueListActions from './actions';
  57. import IssueListFilters from './filters';
  58. import GroupListBody from './groupListBody';
  59. import IssueListHeader from './header';
  60. import {
  61. DEFAULT_ISSUE_STREAM_SORT,
  62. getTabs,
  63. getTabsWithCounts,
  64. isForReviewQuery,
  65. IssueSortOptions,
  66. Query,
  67. QueryCounts,
  68. TAB_MAX_COUNT,
  69. } from './utils';
  70. const MAX_ITEMS = 25;
  71. // the default period for the graph in each issue row
  72. const DEFAULT_GRAPH_STATS_PERIOD = '24h';
  73. // the allowed period choices for graph in each issue row
  74. const DYNAMIC_COUNTS_STATS_PERIODS = new Set(['14d', '24h', 'auto']);
  75. const MAX_ISSUES_COUNT = 100;
  76. type Params = {
  77. orgId: string;
  78. };
  79. type Props = {
  80. api: Client;
  81. location: Location;
  82. organization: Organization;
  83. params: Params;
  84. savedSearch: SavedSearch;
  85. savedSearchLoading: boolean;
  86. savedSearches: SavedSearch[];
  87. selection: PageFilters;
  88. tags: TagCollection;
  89. } & RouteComponentProps<{searchId?: string}, {}> &
  90. WithRouteAnalyticsProps;
  91. type State = {
  92. actionTaken: boolean;
  93. actionTakenGroupData: Group[];
  94. error: string | null;
  95. // TODO(Kelly): remove forReview once issue-list-removal-action feature is stable
  96. forReview: boolean;
  97. groupIds: string[];
  98. issuesLoading: boolean;
  99. itemsRemoved: number;
  100. memberList: ReturnType<typeof indexMembersByProject>;
  101. pageLinks: string;
  102. /**
  103. * Current query total
  104. */
  105. queryCount: number;
  106. /**
  107. * Counts for each inbox tab
  108. */
  109. queryCounts: QueryCounts;
  110. queryMaxCount: number;
  111. realtimeActive: boolean;
  112. // TODO(Kelly): remove reviewedIds once issue-list-removal-action feature is stable
  113. reviewedIds: string[];
  114. selectAllActive: boolean;
  115. undo: boolean;
  116. // Will be set to true if there is valid session data from issue-stats api call
  117. query?: string;
  118. };
  119. type EndpointParams = Partial<PageFilters['datetime']> & {
  120. environment: string[];
  121. project: number[];
  122. cursor?: string;
  123. groupStatsPeriod?: string | null;
  124. page?: number | string;
  125. query?: string;
  126. sort?: string;
  127. statsPeriod?: string | null;
  128. };
  129. type CountsEndpointParams = Omit<EndpointParams, 'cursor' | 'page' | 'query'> & {
  130. query: string[];
  131. };
  132. type StatEndpointParams = Omit<EndpointParams, 'cursor' | 'page'> & {
  133. groups: string[];
  134. expand?: string | string[];
  135. };
  136. class IssueListOverview extends Component<Props, State> {
  137. state: State = this.getInitialState();
  138. getInitialState() {
  139. const realtimeActiveCookie = Cookies.get('realtimeActive');
  140. const realtimeActive =
  141. typeof realtimeActiveCookie === 'undefined'
  142. ? false
  143. : realtimeActiveCookie === 'true';
  144. return {
  145. groupIds: [],
  146. // TODO(Kelly): remove reviewedIds and forReview once issue-list-removal-action feature is stable
  147. reviewedIds: [],
  148. actionTaken: false,
  149. actionTakenGroupData: [],
  150. forReview: false,
  151. undo: false,
  152. selectAllActive: false,
  153. realtimeActive,
  154. pageLinks: '',
  155. itemsRemoved: 0,
  156. queryCount: 0,
  157. queryCounts: {},
  158. queryMaxCount: 0,
  159. error: null,
  160. issuesLoading: true,
  161. memberList: {},
  162. };
  163. }
  164. componentDidMount() {
  165. this._poller = new CursorPoller({
  166. linkPreviousHref: parseLinkHeader(this.state.pageLinks)?.previous?.href,
  167. success: this.onRealtimePoll,
  168. });
  169. // Wait for saved searches to load so if the user is on a saved search
  170. // or they have a pinned search we load the correct data the first time.
  171. // But if searches are already there, we can go right to fetching issues
  172. if (!this.props.savedSearchLoading) {
  173. this.fetchData();
  174. }
  175. this.fetchTags();
  176. this.fetchMemberList();
  177. // let custom analytics take control
  178. this.props.setDisableRouteAnalytics?.();
  179. }
  180. componentDidUpdate(prevProps: Props, prevState: State) {
  181. if (prevState.realtimeActive !== this.state.realtimeActive) {
  182. // User toggled realtime button
  183. if (this.state.realtimeActive) {
  184. this.resumePolling();
  185. } else {
  186. this._poller.disable();
  187. }
  188. }
  189. // If the project selection has changed reload the member list and tag keys
  190. // allowing autocomplete and tag sidebar to be more accurate.
  191. if (!isEqual(prevProps.selection.projects, this.props.selection.projects)) {
  192. this.fetchMemberList();
  193. this.fetchTags();
  194. }
  195. // TODO(Kelly): remove once issue-list-removal-action feature is stable
  196. if (!this.props.organization.features.includes('issue-list-removal-action')) {
  197. if (prevState.forReview !== this.state.forReview) {
  198. this.fetchData();
  199. }
  200. }
  201. // Wait for saved searches to load before we attempt to fetch stream data
  202. if (this.props.savedSearchLoading) {
  203. return;
  204. }
  205. if (prevProps.savedSearchLoading) {
  206. this.fetchData();
  207. return;
  208. }
  209. const prevUrlQuery = prevProps.location.query;
  210. const newUrlQuery = this.props.location.query;
  211. const prevQuery = this.getQueryFromSavedSearchOrLocation({
  212. savedSearch: prevProps.savedSearch,
  213. location: prevProps.location,
  214. });
  215. const newQuery = this.getQuery();
  216. const prevSort = this.getSortFromSavedSearchOrLocation({
  217. savedSearch: prevProps.savedSearch,
  218. location: prevProps.location,
  219. });
  220. const newSort = this.getSort();
  221. const selectionChanged = !isEqual(prevProps.selection, this.props.selection);
  222. // If any important url parameter changed or saved search changed
  223. // reload data.
  224. if (
  225. selectionChanged ||
  226. prevUrlQuery.cursor !== newUrlQuery.cursor ||
  227. prevUrlQuery.statsPeriod !== newUrlQuery.statsPeriod ||
  228. prevUrlQuery.groupStatsPeriod !== newUrlQuery.groupStatsPeriod ||
  229. prevQuery !== newQuery ||
  230. prevSort !== newSort
  231. ) {
  232. this.fetchData(selectionChanged);
  233. } else if (
  234. !this._lastRequest &&
  235. prevState.issuesLoading === false &&
  236. this.state.issuesLoading
  237. ) {
  238. // Reload if we issues are loading or their loading state changed.
  239. // This can happen when transitionTo is called
  240. this.fetchData();
  241. }
  242. }
  243. componentWillUnmount() {
  244. this._poller.disable();
  245. GroupStore.reset();
  246. this.props.api.clear();
  247. this.listener?.();
  248. }
  249. private _poller: any;
  250. private _lastRequest: any;
  251. private _lastStatsRequest: any;
  252. private _lastFetchCountsRequest: any;
  253. getQueryFromSavedSearchOrLocation({
  254. savedSearch,
  255. location,
  256. }: Pick<Props, 'savedSearch' | 'location'>): string {
  257. if (savedSearch) {
  258. return savedSearch.query;
  259. }
  260. const {query} = location.query;
  261. if (query !== undefined) {
  262. return decodeScalar(query, '');
  263. }
  264. return DEFAULT_QUERY;
  265. }
  266. getSortFromSavedSearchOrLocation({
  267. savedSearch,
  268. location,
  269. }: Pick<Props, 'savedSearch' | 'location'>): string {
  270. if (!location.query.sort && savedSearch?.id) {
  271. return savedSearch.sort;
  272. }
  273. if (location.query.sort) {
  274. return location.query.sort as string;
  275. }
  276. return DEFAULT_ISSUE_STREAM_SORT;
  277. }
  278. getQuery(): string {
  279. return this.getQueryFromSavedSearchOrLocation({
  280. savedSearch: this.props.savedSearch,
  281. location: this.props.location,
  282. });
  283. }
  284. getSort(): string {
  285. return this.getSortFromSavedSearchOrLocation({
  286. savedSearch: this.props.savedSearch,
  287. location: this.props.location,
  288. });
  289. }
  290. getGroupStatsPeriod(): string {
  291. let currentPeriod: string;
  292. if (typeof this.props.location.query?.groupStatsPeriod === 'string') {
  293. currentPeriod = this.props.location.query.groupStatsPeriod;
  294. } else if (this.getSort() === IssueSortOptions.TREND) {
  295. // Default to the larger graph when sorting by relative change
  296. currentPeriod = 'auto';
  297. } else {
  298. currentPeriod = DEFAULT_GRAPH_STATS_PERIOD;
  299. }
  300. return DYNAMIC_COUNTS_STATS_PERIODS.has(currentPeriod)
  301. ? currentPeriod
  302. : DEFAULT_GRAPH_STATS_PERIOD;
  303. }
  304. getEndpointParams = (): EndpointParams => {
  305. const {selection} = this.props;
  306. const params: EndpointParams = {
  307. project: selection.projects,
  308. environment: selection.environments,
  309. query: this.getQuery(),
  310. ...selection.datetime,
  311. };
  312. if (selection.datetime.period) {
  313. delete params.period;
  314. params.statsPeriod = selection.datetime.period;
  315. }
  316. if (params.end) {
  317. params.end = getUtcDateString(params.end);
  318. }
  319. if (params.start) {
  320. params.start = getUtcDateString(params.start);
  321. }
  322. const sort = this.getSort();
  323. if (sort !== DEFAULT_ISSUE_STREAM_SORT) {
  324. params.sort = sort;
  325. }
  326. const groupStatsPeriod = this.getGroupStatsPeriod();
  327. if (groupStatsPeriod !== DEFAULT_GRAPH_STATS_PERIOD) {
  328. params.groupStatsPeriod = groupStatsPeriod;
  329. }
  330. // only include defined values.
  331. return pickBy(params, v => defined(v)) as EndpointParams;
  332. };
  333. getSelectedProjectIds = (): string[] => {
  334. return this.props.selection.projects.map(projectId => String(projectId));
  335. };
  336. fetchMemberList() {
  337. const projectIds = this.getSelectedProjectIds();
  338. fetchOrgMembers(this.props.api, this.props.organization.slug, projectIds).then(
  339. members => {
  340. this.setState({memberList: indexMembersByProject(members)});
  341. }
  342. );
  343. }
  344. fetchTags() {
  345. const {api, organization, selection} = this.props;
  346. loadOrganizationTags(api, organization.slug, selection);
  347. }
  348. fetchStats = (groups: string[]) => {
  349. // If we have no groups to fetch, just skip stats
  350. if (!groups.length) {
  351. return;
  352. }
  353. const requestParams: StatEndpointParams = {
  354. ...this.getEndpointParams(),
  355. groups,
  356. };
  357. // If no stats period values are set, use default
  358. if (!requestParams.statsPeriod && !requestParams.start) {
  359. requestParams.statsPeriod = DEFAULT_STATS_PERIOD;
  360. }
  361. this._lastStatsRequest = this.props.api.request(this.groupStatsEndpoint, {
  362. method: 'GET',
  363. data: qs.stringify(requestParams),
  364. success: data => {
  365. if (!data) {
  366. return;
  367. }
  368. GroupStore.onPopulateStats(groups, data);
  369. },
  370. error: err => {
  371. this.setState({
  372. error: parseApiError(err),
  373. });
  374. },
  375. complete: () => {
  376. this._lastStatsRequest = null;
  377. // End navigation transaction to prevent additional page requests from impacting page metrics.
  378. // Other transactions include stacktrace preview request
  379. const currentTransaction = Sentry.getCurrentHub().getScope()?.getTransaction();
  380. if (currentTransaction?.op === 'navigation') {
  381. currentTransaction.finish();
  382. }
  383. },
  384. });
  385. };
  386. fetchCounts = (currentQueryCount: number, fetchAllCounts: boolean) => {
  387. const {organization} = this.props;
  388. const {queryCounts: _queryCounts} = this.state;
  389. let queryCounts: QueryCounts = {..._queryCounts};
  390. const endpointParams = this.getEndpointParams();
  391. const tabQueriesWithCounts = getTabsWithCounts(organization);
  392. const currentTabQuery = tabQueriesWithCounts.includes(endpointParams.query as Query)
  393. ? endpointParams.query
  394. : null;
  395. // Update the count based on the exact number of issues, these shown as is
  396. if (currentTabQuery) {
  397. queryCounts[currentTabQuery] = {
  398. count: currentQueryCount,
  399. hasMore: false,
  400. };
  401. }
  402. this.setState({queryCounts});
  403. // If all tabs' counts are fetched, skip and only set
  404. if (
  405. fetchAllCounts ||
  406. !tabQueriesWithCounts.every(tabQuery => queryCounts[tabQuery] !== undefined)
  407. ) {
  408. const requestParams: CountsEndpointParams = {
  409. ...omit(endpointParams, 'query'),
  410. // fetch the counts for the tabs whose counts haven't been fetched yet
  411. query: tabQueriesWithCounts.filter(_query => _query !== currentTabQuery),
  412. };
  413. // If no stats period values are set, use default
  414. if (!requestParams.statsPeriod && !requestParams.start) {
  415. requestParams.statsPeriod = DEFAULT_STATS_PERIOD;
  416. }
  417. this._lastFetchCountsRequest = this.props.api.request(this.groupCountsEndpoint, {
  418. method: 'GET',
  419. data: qs.stringify(requestParams),
  420. success: data => {
  421. if (!data) {
  422. return;
  423. }
  424. // Counts coming from the counts endpoint is limited to 100, for >= 100 we display 99+
  425. queryCounts = {
  426. ...queryCounts,
  427. ...mapValues(data, (count: number) => ({
  428. count,
  429. hasMore: count > TAB_MAX_COUNT,
  430. })),
  431. };
  432. },
  433. error: () => {
  434. this.setState({queryCounts: {}});
  435. },
  436. complete: () => {
  437. this._lastFetchCountsRequest = null;
  438. this.setState({queryCounts});
  439. },
  440. });
  441. }
  442. };
  443. fetchData = (fetchAllCounts = false) => {
  444. const {organization} = this.props;
  445. const query = this.getQuery();
  446. const hasIssueListRemovalAction = organization.features.includes(
  447. 'issue-list-removal-action'
  448. );
  449. // TODO(Kelly): update once issue-list-removal-action feature is stable
  450. if (hasIssueListRemovalAction && !this.state.realtimeActive) {
  451. if (!this.state.actionTaken && !this.state.undo) {
  452. GroupStore.loadInitialData([]);
  453. this.setState({
  454. issuesLoading: true,
  455. queryCount: 0,
  456. itemsRemoved: 0,
  457. error: null,
  458. });
  459. }
  460. } else {
  461. if (!this.state.reviewedIds.length || !isForReviewQuery(query)) {
  462. GroupStore.loadInitialData([]);
  463. this.setState({
  464. issuesLoading: true,
  465. queryCount: 0,
  466. itemsRemoved: 0,
  467. reviewedIds: [],
  468. error: null,
  469. });
  470. }
  471. }
  472. const transaction = getCurrentSentryReactTransaction();
  473. transaction?.setTag('query.sort', this.getSort());
  474. this.setState({
  475. queryCount: 0,
  476. itemsRemoved: 0,
  477. error: null,
  478. });
  479. const requestParams: any = {
  480. ...this.getEndpointParams(),
  481. limit: MAX_ITEMS,
  482. shortIdLookup: 1,
  483. };
  484. const currentQuery = this.props.location.query || {};
  485. if ('cursor' in currentQuery) {
  486. requestParams.cursor = currentQuery.cursor;
  487. }
  488. // If no stats period values are set, use default
  489. if (!requestParams.statsPeriod && !requestParams.start) {
  490. requestParams.statsPeriod = DEFAULT_STATS_PERIOD;
  491. }
  492. requestParams.expand = ['owners', 'inbox'];
  493. requestParams.collapse = 'stats';
  494. if (this._lastRequest) {
  495. this._lastRequest.cancel();
  496. }
  497. if (this._lastStatsRequest) {
  498. this._lastStatsRequest.cancel();
  499. }
  500. if (this._lastFetchCountsRequest) {
  501. this._lastFetchCountsRequest.cancel();
  502. }
  503. this._poller.disable();
  504. this._lastRequest = this.props.api.request(this.groupListEndpoint, {
  505. method: 'GET',
  506. data: qs.stringify(requestParams),
  507. success: (data, _, resp) => {
  508. if (!resp) {
  509. return;
  510. }
  511. // If this is a direct hit, we redirect to the intended result directly.
  512. if (resp.getResponseHeader('X-Sentry-Direct-Hit') === '1') {
  513. let redirect: string;
  514. if (data[0] && data[0].matchingEventId) {
  515. const {id, matchingEventId} = data[0];
  516. redirect = `/organizations/${organization.slug}/issues/${id}/events/${matchingEventId}/`;
  517. } else {
  518. const {id} = data[0];
  519. redirect = `/organizations/${organization.slug}/issues/${id}/`;
  520. }
  521. browserHistory.replace(
  522. normalizeUrl({
  523. pathname: redirect,
  524. query: {
  525. referrer: 'issue-list',
  526. ...extractSelectionParameters(this.props.location.query),
  527. },
  528. })
  529. );
  530. return;
  531. }
  532. if (this.state.undo) {
  533. GroupStore.loadInitialData(data);
  534. }
  535. GroupStore.add(data);
  536. // TODO(Kelly): update once issue-list-removal-action feature is stable
  537. if (!hasIssueListRemovalAction) {
  538. if (isForReviewQuery(query)) {
  539. GroupStore.remove(this.state.reviewedIds);
  540. }
  541. }
  542. const numPerfIssues = data.filter(
  543. (group: BaseGroup) => group.issueCategory === IssueCategory.PERFORMANCE
  544. ).length;
  545. const page = this.props.location.query.page;
  546. const endpointParams = this.getEndpointParams();
  547. const tabQueriesWithCounts = getTabsWithCounts(organization);
  548. const currentTabQuery = tabQueriesWithCounts.includes(
  549. endpointParams.query as Query
  550. )
  551. ? endpointParams.query
  552. : null;
  553. const tab = getTabs(organization).find(
  554. ([tabQuery]) => currentTabQuery === tabQuery
  555. )?.[1];
  556. trackAdvancedAnalyticsEvent('issues_tab.viewed', {
  557. organization,
  558. tab: tab?.analyticsName,
  559. page: page ? parseInt(page, 10) : 0,
  560. query,
  561. num_perf_issues: numPerfIssues,
  562. num_issues: data.length,
  563. });
  564. this.fetchStats(data.map((group: BaseGroup) => group.id));
  565. const hits = resp.getResponseHeader('X-Hits');
  566. const queryCount =
  567. typeof hits !== 'undefined' && hits ? parseInt(hits, 10) || 0 : 0;
  568. const maxHits = resp.getResponseHeader('X-Max-Hits');
  569. const queryMaxCount =
  570. typeof maxHits !== 'undefined' && maxHits ? parseInt(maxHits, 10) || 0 : 0;
  571. const pageLinks = resp.getResponseHeader('Link');
  572. // TODO(Kelly): update once issue-list-removal-action feature is stable
  573. if (hasIssueListRemovalAction && !this.state.realtimeActive) {
  574. this.fetchCounts(queryCount, fetchAllCounts);
  575. } else {
  576. if (!this.state.forReview) {
  577. this.fetchCounts(queryCount, fetchAllCounts);
  578. }
  579. }
  580. this.setState({
  581. error: null,
  582. issuesLoading: false,
  583. queryCount,
  584. queryMaxCount,
  585. pageLinks: pageLinks !== null ? pageLinks : '',
  586. });
  587. if (data.length === 0) {
  588. trackAdvancedAnalyticsEvent('issue_search.empty', {
  589. organization: this.props.organization,
  590. search_type: 'issues',
  591. search_source: 'main_search',
  592. query,
  593. });
  594. }
  595. },
  596. error: err => {
  597. trackAdvancedAnalyticsEvent('issue_search.failed', {
  598. organization: this.props.organization,
  599. search_type: 'issues',
  600. search_source: 'main_search',
  601. error: parseApiError(err),
  602. });
  603. this.setState({
  604. error: parseApiError(err),
  605. issuesLoading: false,
  606. });
  607. },
  608. complete: () => {
  609. this._lastRequest = null;
  610. this.resumePolling();
  611. // TODO(Kelly): update once issue-list-removal-action feature is stable
  612. if (hasIssueListRemovalAction && !this.state.realtimeActive) {
  613. this.setState({actionTaken: false, undo: false});
  614. } else {
  615. this.setState({forReview: false});
  616. }
  617. },
  618. });
  619. };
  620. resumePolling = () => {
  621. if (!this.state.pageLinks) {
  622. return;
  623. }
  624. // Only resume polling if we're on the first page of results
  625. const links = parseLinkHeader(this.state.pageLinks);
  626. if (links && !links.previous.results && this.state.realtimeActive) {
  627. this._poller.setEndpoint(links?.previous?.href);
  628. this._poller.enable();
  629. }
  630. };
  631. get groupListEndpoint(): string {
  632. const {organization} = this.props;
  633. return `/organizations/${organization.slug}/issues/`;
  634. }
  635. get groupCountsEndpoint(): string {
  636. const {organization} = this.props;
  637. return `/organizations/${organization.slug}/issues-count/`;
  638. }
  639. get groupStatsEndpoint(): string {
  640. const {organization} = this.props;
  641. return `/organizations/${organization.slug}/issues-stats/`;
  642. }
  643. onRealtimeChange = (realtime: boolean) => {
  644. Cookies.set('realtimeActive', realtime.toString());
  645. this.setState({realtimeActive: realtime});
  646. trackAdvancedAnalyticsEvent('issues_stream.realtime_clicked', {
  647. organization: this.props.organization,
  648. enabled: realtime,
  649. });
  650. };
  651. onSelectStatsPeriod = (period: string) => {
  652. const {location} = this.props;
  653. if (period !== this.getGroupStatsPeriod()) {
  654. const cursor = location.query.cursor;
  655. const queryPageInt = parseInt(location.query.page, 10);
  656. const page = isNaN(queryPageInt) || !location.query.cursor ? 0 : queryPageInt;
  657. this.transitionTo({cursor, page, groupStatsPeriod: period});
  658. }
  659. };
  660. onRealtimePoll = (data: any, _links: any) => {
  661. // Note: We do not update state with cursors from polling,
  662. // `CursorPoller` updates itself with new cursors
  663. GroupStore.addToFront(data);
  664. };
  665. listener = GroupStore.listen(() => this.onGroupChange(), undefined);
  666. onGroupChange() {
  667. const {organization} = this.props;
  668. const {actionTakenGroupData} = this.state;
  669. const query = this.getQuery();
  670. const hasIssueListRemovalAction = organization.features.includes(
  671. 'issue-list-removal-action'
  672. );
  673. // TODO(Kelly): update once issue-list-removal-action feature is stable
  674. if (
  675. hasIssueListRemovalAction &&
  676. !this.state.realtimeActive &&
  677. actionTakenGroupData.length > 0
  678. ) {
  679. const filteredItems = GroupStore.getAllItems().filter(item => {
  680. return actionTakenGroupData.findIndex(data => data.id === item.id) !== -1;
  681. });
  682. const resolvedIds = filteredItems
  683. .filter(item => item.status === 'resolved')
  684. .map(id => id.id);
  685. const ignoredIds = filteredItems
  686. .filter(item => item.status === 'ignored')
  687. .map(i => i.id);
  688. // need to include resolve and ignored statuses because marking as resolved/ignored also
  689. // counts as reviewed
  690. const reviewedIds = filteredItems
  691. .filter(
  692. item => !item.inbox && item.status !== 'resolved' && item.status !== 'ignored'
  693. )
  694. .map(i => i.id);
  695. // Remove Ignored and Resolved group ids from the issue stream if on the All Unresolved,
  696. // For Review, or Ignored tab. Still include on the saved/custom search tab.
  697. if (
  698. resolvedIds.length > 0 &&
  699. (query.includes('is:unresolved') ||
  700. query.includes('is:ignored') ||
  701. isForReviewQuery(query))
  702. ) {
  703. this.onIssueAction(resolvedIds, 'Resolved');
  704. }
  705. if (
  706. ignoredIds.length > 0 &&
  707. (query.includes('is:unresolved') || isForReviewQuery(query))
  708. ) {
  709. this.onIssueAction(ignoredIds, 'Ignored');
  710. }
  711. // Remove issues that are marked as Reviewed from the For Review tab, but still include the
  712. // issues if on the All Unresolved tab or saved/custom searches.
  713. if (
  714. reviewedIds.length > 0 &&
  715. (isForReviewQuery(query) || query.includes('is:ignored'))
  716. ) {
  717. this.onIssueAction(reviewedIds, 'Reviewed');
  718. }
  719. }
  720. const groupIds = GroupStore.getAllItems()
  721. .map(item => item.id)
  722. .slice(0, MAX_ISSUES_COUNT);
  723. if (!isEqual(groupIds, this.state.groupIds)) {
  724. this.setState({groupIds});
  725. }
  726. }
  727. onIssueListSidebarSearch = (query: string) => {
  728. trackAdvancedAnalyticsEvent('search.searched', {
  729. organization: this.props.organization,
  730. query,
  731. search_type: 'issues',
  732. search_source: 'search_builder',
  733. });
  734. this.onSearch(query);
  735. };
  736. onSearch = (query: string) => {
  737. if (query === this.state.query) {
  738. // if query is the same, just re-fetch data
  739. this.fetchData();
  740. } else {
  741. // Clear the saved search as the user wants something else.
  742. this.transitionTo({query}, null);
  743. }
  744. };
  745. onSortChange = (sort: string) => {
  746. trackAdvancedAnalyticsEvent('issues_stream.sort_changed', {
  747. organization: this.props.organization,
  748. sort,
  749. });
  750. this.transitionTo({sort});
  751. };
  752. onCursorChange: CursorHandler = (nextCursor, _path, _query, delta) => {
  753. const queryPageInt = parseInt(this.props.location.query.page, 10);
  754. let nextPage: number | undefined = isNaN(queryPageInt) ? delta : queryPageInt + delta;
  755. let cursor: undefined | string = nextCursor;
  756. // unset cursor and page when we navigate back to the first page
  757. // also reset cursor if somehow the previous button is enabled on
  758. // first page and user attempts to go backwards
  759. if (nextPage <= 0) {
  760. cursor = undefined;
  761. nextPage = undefined;
  762. }
  763. this.transitionTo({cursor, page: nextPage});
  764. };
  765. paginationAnalyticsEvent = (direction: string) => {
  766. trackAdvancedAnalyticsEvent('issues_stream.paginate', {
  767. organization: this.props.organization,
  768. direction,
  769. });
  770. };
  771. /**
  772. * Returns true if all results in the current query are visible/on this page
  773. */
  774. allResultsVisible(): boolean {
  775. if (!this.state.pageLinks) {
  776. return false;
  777. }
  778. const links = parseLinkHeader(this.state.pageLinks);
  779. return links && !links.previous.results && !links.next.results;
  780. }
  781. transitionTo = (
  782. newParams: Partial<EndpointParams> = {},
  783. savedSearch: (SavedSearch & {projectId?: number}) | null = this.props.savedSearch
  784. ) => {
  785. const query = {
  786. referrer: 'issue-list',
  787. ...this.getEndpointParams(),
  788. ...newParams,
  789. };
  790. const {organization} = this.props;
  791. let path: string;
  792. if (savedSearch && savedSearch.id) {
  793. path = `/organizations/${organization.slug}/issues/searches/${savedSearch.id}/`;
  794. // Remove the query as saved searches bring their own query string.
  795. delete query.query;
  796. // If we aren't going to another page in the same search
  797. // drop the query and replace the current project, with the saved search search project
  798. // if available.
  799. if (!query.cursor && savedSearch.projectId) {
  800. query.project = [savedSearch.projectId];
  801. }
  802. if (!query.cursor && !newParams.sort && savedSearch.sort) {
  803. query.sort = savedSearch.sort;
  804. }
  805. } else {
  806. path = `/organizations/${organization.slug}/issues/`;
  807. }
  808. // Remove inbox tab specific sort
  809. if (query.sort === IssueSortOptions.INBOX && query.query !== Query.FOR_REVIEW) {
  810. delete query.sort;
  811. }
  812. if (
  813. path !== this.props.location.pathname ||
  814. !isEqual(query, this.props.location.query)
  815. ) {
  816. browserHistory.push({
  817. pathname: normalizeUrl(path),
  818. query,
  819. });
  820. this.setState({issuesLoading: true});
  821. }
  822. };
  823. displayReprocessingTab() {
  824. const {organization} = this.props;
  825. const {queryCounts} = this.state;
  826. return (
  827. organization.features.includes('reprocessing-v2') &&
  828. !!queryCounts?.[Query.REPROCESSING]?.count
  829. );
  830. }
  831. displayReprocessingLayout(showReprocessingTab: boolean, query: string) {
  832. return showReprocessingTab && query === Query.REPROCESSING;
  833. }
  834. renderLoading(): React.ReactNode {
  835. return (
  836. <PageContent>
  837. <LoadingIndicator />
  838. </PageContent>
  839. );
  840. }
  841. onSavedSearchSelect = (savedSearch: SavedSearch) => {
  842. trackAdvancedAnalyticsEvent('organization_saved_search.selected', {
  843. organization: this.props.organization,
  844. search_type: 'issues',
  845. id: savedSearch.id ? parseInt(savedSearch.id, 10) : -1,
  846. is_global: savedSearch.isGlobal,
  847. query: savedSearch.query,
  848. visibility: savedSearch.visibility,
  849. });
  850. this.setState({issuesLoading: true}, () => this.transitionTo(undefined, savedSearch));
  851. };
  852. onDelete = () => {
  853. this.setState({actionTaken: true});
  854. this.fetchData(true);
  855. };
  856. onUndo = () => {
  857. const {organization, selection} = this.props;
  858. const {actionTakenGroupData} = this.state;
  859. const query = this.getQuery();
  860. const groupIds = actionTakenGroupData.map(data => data.id);
  861. const projectIds = selection?.projects?.map(p => p.toString());
  862. const endpoint = `/organizations/${organization.slug}/issues/`;
  863. if (this._lastRequest) {
  864. this._lastRequest.cancel();
  865. }
  866. if (this._lastStatsRequest) {
  867. this._lastStatsRequest.cancel();
  868. }
  869. if (this._lastFetchCountsRequest) {
  870. this._lastFetchCountsRequest.cancel();
  871. }
  872. this.props.api.request(endpoint, {
  873. method: 'PUT',
  874. data: {
  875. status: 'unresolved',
  876. },
  877. query: {
  878. project: projectIds,
  879. id: groupIds,
  880. },
  881. success: response => {
  882. if (!response) {
  883. return;
  884. }
  885. // If on the Ignore or For Review tab, adding back to the GroupStore will make the issue show up
  886. // on this page for a second and then be removed (will show up on All Unresolved). This is to
  887. // stop this from happening and avoid confusion.
  888. if (!query.includes('is:ignored') && !isForReviewQuery(query)) {
  889. GroupStore.add(actionTakenGroupData);
  890. }
  891. this.setState({undo: true});
  892. },
  893. error: err => {
  894. this.setState({
  895. error: parseApiError(err),
  896. issuesLoading: false,
  897. });
  898. },
  899. complete: () => {
  900. this.setState({actionTakenGroupData: []});
  901. this.fetchData();
  902. },
  903. });
  904. };
  905. onMarkReviewed = (itemIds: string[]) => {
  906. const {organization} = this.props;
  907. const query = this.getQuery();
  908. const hasIssueListRemovalAction = organization.features.includes(
  909. 'issue-list-removal-action'
  910. );
  911. if (!isForReviewQuery(query)) {
  912. if (itemIds.length > 1) {
  913. addMessage(
  914. tn('Reviewed %s Issue', 'Reviewed %s Issues', itemIds.length),
  915. 'success',
  916. {duration: 4000}
  917. );
  918. } else {
  919. const shortId = itemIds.map(item => GroupStore.get(item)?.shortId).toString();
  920. addMessage(t('Reviewed %s', shortId), 'success', {duration: 4000});
  921. }
  922. return;
  923. }
  924. const {queryCounts, itemsRemoved} = this.state;
  925. const currentQueryCount = queryCounts[query as Query];
  926. if (itemIds.length && currentQueryCount) {
  927. const inInboxCount = itemIds.filter(id => GroupStore.get(id)?.inbox).length;
  928. currentQueryCount.count -= inInboxCount;
  929. // TODO(Kelly): update once issue-list-removal-action feature is stable
  930. if (!hasIssueListRemovalAction) {
  931. this.setState({
  932. reviewedIds: itemIds,
  933. forReview: true,
  934. });
  935. }
  936. this.setState({
  937. queryCounts: {
  938. ...queryCounts,
  939. [query as Query]: currentQueryCount,
  940. },
  941. itemsRemoved: itemsRemoved + inInboxCount,
  942. });
  943. }
  944. };
  945. onActionTaken = (itemIds: string[]) => {
  946. const actionTakenGroupData = itemIds.map(id => GroupStore.get(id) as Group);
  947. this.setState({
  948. actionTakenGroupData,
  949. });
  950. };
  951. onIssueAction = (
  952. itemIds: string[],
  953. actionType: 'Reviewed' | 'Resolved' | 'Ignored'
  954. ) => {
  955. if (itemIds.length > 1) {
  956. addMessage(`${actionType} ${itemIds.length} ${t('Issues')}`, 'success', {
  957. duration: 4000,
  958. ...(actionType !== 'Reviewed' && {undo: this.onUndo}),
  959. });
  960. } else {
  961. const shortId = itemIds.map(item => GroupStore.get(item)?.shortId).toString();
  962. addMessage(`${actionType} ${shortId}`, 'success', {
  963. duration: 4000,
  964. ...(actionType !== 'Reviewed' && {undo: this.onUndo}),
  965. });
  966. }
  967. GroupStore.remove(itemIds);
  968. this.setState({actionTaken: true});
  969. this.fetchData(true);
  970. };
  971. tagValueLoader = (key: string, search: string) => {
  972. const {organization} = this.props;
  973. const projectIds = this.getSelectedProjectIds();
  974. const endpointParams = this.getEndpointParams();
  975. return fetchTagValues({
  976. api: this.props.api,
  977. orgSlug: organization.slug,
  978. tagKey: key,
  979. search,
  980. projectIds,
  981. endpointParams: endpointParams as any,
  982. });
  983. };
  984. render() {
  985. if (this.props.savedSearchLoading) {
  986. return this.renderLoading();
  987. }
  988. const {
  989. pageLinks,
  990. queryCount,
  991. queryCounts,
  992. realtimeActive,
  993. groupIds,
  994. queryMaxCount,
  995. itemsRemoved,
  996. issuesLoading,
  997. error,
  998. } = this.state;
  999. const {organization, savedSearch, selection, location, router} = this.props;
  1000. const links = parseLinkHeader(pageLinks);
  1001. const query = this.getQuery();
  1002. const queryPageInt = parseInt(location.query.page, 10);
  1003. // Cursor must be present for the page number to be used
  1004. const page = isNaN(queryPageInt) || !location.query.cursor ? 0 : queryPageInt;
  1005. const pageBasedCount = page * MAX_ITEMS + groupIds.length;
  1006. let pageCount = pageBasedCount > queryCount ? queryCount : pageBasedCount;
  1007. if (!links?.next?.results || this.allResultsVisible()) {
  1008. // On last available page
  1009. pageCount = queryCount;
  1010. } else if (!links?.previous?.results) {
  1011. // On first available page
  1012. pageCount = groupIds.length;
  1013. }
  1014. // Subtract # items that have been marked reviewed
  1015. pageCount = Math.max(pageCount - itemsRemoved, 0);
  1016. const modifiedQueryCount = Math.max(queryCount - itemsRemoved, 0);
  1017. const displayCount = tct('[count] of [total]', {
  1018. count: pageCount,
  1019. total: (
  1020. <StyledQueryCount
  1021. hideParens
  1022. hideIfEmpty={false}
  1023. count={modifiedQueryCount}
  1024. max={queryMaxCount || 100}
  1025. />
  1026. ),
  1027. });
  1028. const projectIds = selection?.projects?.map(p => p.toString());
  1029. const showReprocessingTab = this.displayReprocessingTab();
  1030. const displayReprocessingActions = this.displayReprocessingLayout(
  1031. showReprocessingTab,
  1032. query
  1033. );
  1034. return (
  1035. <StyledPageContent>
  1036. <IssueListHeader
  1037. organization={organization}
  1038. query={query}
  1039. sort={this.getSort()}
  1040. queryCount={queryCount}
  1041. queryCounts={queryCounts}
  1042. realtimeActive={realtimeActive}
  1043. onRealtimeChange={this.onRealtimeChange}
  1044. router={router}
  1045. displayReprocessingTab={showReprocessingTab}
  1046. savedSearch={savedSearch}
  1047. selectedProjectIds={selection.projects}
  1048. />
  1049. <StyledBody>
  1050. <StyledMain>
  1051. <IssueListFilters
  1052. organization={organization}
  1053. query={query}
  1054. onSearch={this.onSearch}
  1055. />
  1056. <Panel>
  1057. <IssueListActions
  1058. selection={selection}
  1059. query={query}
  1060. queryCount={modifiedQueryCount}
  1061. displayCount={displayCount}
  1062. onSelectStatsPeriod={this.onSelectStatsPeriod}
  1063. onMarkReviewed={this.onMarkReviewed}
  1064. onActionTaken={this.onActionTaken}
  1065. onDelete={this.onDelete}
  1066. statsPeriod={this.getGroupStatsPeriod()}
  1067. groupIds={groupIds}
  1068. allResultsVisible={this.allResultsVisible()}
  1069. displayReprocessingActions={displayReprocessingActions}
  1070. sort={this.getSort()}
  1071. onSortChange={this.onSortChange}
  1072. />
  1073. <PanelBody>
  1074. <ProcessingIssueList
  1075. organization={organization}
  1076. projectIds={projectIds}
  1077. showProject
  1078. />
  1079. <VisuallyCompleteWithData
  1080. hasData={this.state.groupIds.length > 0}
  1081. id="IssueList-Body"
  1082. >
  1083. <GroupListBody
  1084. memberList={this.state.memberList}
  1085. groupStatsPeriod={this.getGroupStatsPeriod()}
  1086. groupIds={groupIds}
  1087. displayReprocessingLayout={displayReprocessingActions}
  1088. query={query}
  1089. sort={this.getSort()}
  1090. selectedProjectIds={selection.projects}
  1091. loading={issuesLoading}
  1092. error={error}
  1093. refetchGroups={this.fetchData}
  1094. />
  1095. </VisuallyCompleteWithData>
  1096. </PanelBody>
  1097. </Panel>
  1098. <StyledPagination
  1099. caption={tct('Showing [displayCount] issues', {
  1100. displayCount,
  1101. })}
  1102. pageLinks={pageLinks}
  1103. onCursor={this.onCursorChange}
  1104. paginationAnalyticsEvent={this.paginationAnalyticsEvent}
  1105. />
  1106. </StyledMain>
  1107. <SavedIssueSearches
  1108. {...{organization, query}}
  1109. onSavedSearchSelect={this.onSavedSearchSelect}
  1110. sort={this.getSort()}
  1111. />
  1112. </StyledBody>
  1113. </StyledPageContent>
  1114. );
  1115. }
  1116. }
  1117. export default withRouteAnalytics(
  1118. withApi(
  1119. withPageFilters(
  1120. withSavedSearches(withOrganization(withIssueTags(withProfiler(IssueListOverview))))
  1121. )
  1122. )
  1123. );
  1124. export {IssueListOverview};
  1125. const StyledBody = styled('div')`
  1126. background-color: ${p => p.theme.background};
  1127. flex: 1;
  1128. display: grid;
  1129. gap: 0;
  1130. padding: 0;
  1131. grid-template-columns: minmax(0, 1fr);
  1132. grid-template-rows: auto minmax(max-content, 1fr);
  1133. grid-template-areas:
  1134. 'saved-searches'
  1135. 'content';
  1136. @media (min-width: ${p => p.theme.breakpoints.small}) {
  1137. grid-template-rows: 1fr;
  1138. grid-template-columns: minmax(0, 1fr) auto;
  1139. grid-template-areas: 'content saved-searches';
  1140. }
  1141. `;
  1142. const StyledMain = styled('section')`
  1143. grid-area: content;
  1144. padding: ${space(2)};
  1145. @media (min-width: ${p => p.theme.breakpoints.medium}) {
  1146. padding: ${space(3)} ${space(4)};
  1147. }
  1148. `;
  1149. const StyledPagination = styled(Pagination)`
  1150. margin-top: 0;
  1151. `;
  1152. const StyledQueryCount = styled(QueryCount)`
  1153. margin-left: 0;
  1154. `;
  1155. const StyledPageContent = styled(PageContent)`
  1156. padding: 0;
  1157. `;