overview.tsx 39 KB

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