overview.tsx 38 KB

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