overview.tsx 40 KB

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