overview.tsx 40 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328
  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 if (this.getSort() === IssueSortOptions.TREND) {
  296. // Default to the larger graph when sorting by relative change
  297. currentPeriod = 'auto';
  298. } else {
  299. currentPeriod = DEFAULT_GRAPH_STATS_PERIOD;
  300. }
  301. return DYNAMIC_COUNTS_STATS_PERIODS.has(currentPeriod)
  302. ? currentPeriod
  303. : DEFAULT_GRAPH_STATS_PERIOD;
  304. }
  305. getEndpointParams = (): EndpointParams => {
  306. const {selection} = this.props;
  307. const params: EndpointParams = {
  308. project: selection.projects,
  309. environment: selection.environments,
  310. query: this.getQuery(),
  311. ...selection.datetime,
  312. };
  313. if (selection.datetime.period) {
  314. delete params.period;
  315. params.statsPeriod = selection.datetime.period;
  316. }
  317. if (params.end) {
  318. params.end = getUtcDateString(params.end);
  319. }
  320. if (params.start) {
  321. params.start = getUtcDateString(params.start);
  322. }
  323. const sort = this.getSort();
  324. if (sort !== DEFAULT_ISSUE_STREAM_SORT) {
  325. params.sort = sort;
  326. }
  327. const groupStatsPeriod = this.getGroupStatsPeriod();
  328. if (groupStatsPeriod !== DEFAULT_GRAPH_STATS_PERIOD) {
  329. params.groupStatsPeriod = groupStatsPeriod;
  330. }
  331. // only include defined values.
  332. return pickBy(params, v => defined(v)) as EndpointParams;
  333. };
  334. getSelectedProjectIds = (): string[] => {
  335. return this.props.selection.projects.map(projectId => String(projectId));
  336. };
  337. fetchMemberList() {
  338. const projectIds = this.getSelectedProjectIds();
  339. fetchOrgMembers(this.props.api, this.props.organization.slug, projectIds).then(
  340. members => {
  341. this.setState({memberList: indexMembersByProject(members)});
  342. }
  343. );
  344. }
  345. fetchTags() {
  346. const {api, organization, selection} = this.props;
  347. loadOrganizationTags(api, organization.slug, selection);
  348. }
  349. fetchStats = (groups: string[]) => {
  350. // If we have no groups to fetch, just skip stats
  351. if (!groups.length) {
  352. return;
  353. }
  354. const requestParams: StatEndpointParams = {
  355. ...this.getEndpointParams(),
  356. groups,
  357. };
  358. // If no stats period values are set, use default
  359. if (!requestParams.statsPeriod && !requestParams.start) {
  360. requestParams.statsPeriod = DEFAULT_STATS_PERIOD;
  361. }
  362. this._lastStatsRequest = this.props.api.request(this.groupStatsEndpoint, {
  363. method: 'GET',
  364. data: qs.stringify(requestParams),
  365. success: data => {
  366. if (!data) {
  367. return;
  368. }
  369. GroupStore.onPopulateStats(groups, data);
  370. this.trackTabViewed(groups, data);
  371. },
  372. error: err => {
  373. this.setState({
  374. error: parseApiError(err),
  375. });
  376. },
  377. complete: () => {
  378. this._lastStatsRequest = null;
  379. // End navigation transaction to prevent additional page requests from impacting page metrics.
  380. // Other transactions include stacktrace preview request
  381. const currentTransaction = Sentry.getCurrentHub().getScope()?.getTransaction();
  382. if (currentTransaction?.op === 'navigation') {
  383. currentTransaction.finish();
  384. }
  385. },
  386. });
  387. };
  388. fetchCounts = (currentQueryCount: number, fetchAllCounts: boolean) => {
  389. const {organization} = this.props;
  390. const {queryCounts: _queryCounts} = this.state;
  391. let queryCounts: QueryCounts = {..._queryCounts};
  392. const endpointParams = this.getEndpointParams();
  393. const tabQueriesWithCounts = getTabsWithCounts(organization);
  394. const currentTabQuery = tabQueriesWithCounts.includes(endpointParams.query as Query)
  395. ? endpointParams.query
  396. : null;
  397. // Update the count based on the exact number of issues, these shown as is
  398. if (currentTabQuery) {
  399. queryCounts[currentTabQuery] = {
  400. count: currentQueryCount,
  401. hasMore: false,
  402. };
  403. }
  404. this.setState({queryCounts});
  405. // If all tabs' counts are fetched, skip and only set
  406. if (
  407. fetchAllCounts ||
  408. !tabQueriesWithCounts.every(tabQuery => queryCounts[tabQuery] !== undefined)
  409. ) {
  410. const requestParams: CountsEndpointParams = {
  411. ...omit(endpointParams, 'query'),
  412. // fetch the counts for the tabs whose counts haven't been fetched yet
  413. query: tabQueriesWithCounts.filter(_query => _query !== currentTabQuery),
  414. };
  415. // If no stats period values are set, use default
  416. if (!requestParams.statsPeriod && !requestParams.start) {
  417. requestParams.statsPeriod = DEFAULT_STATS_PERIOD;
  418. }
  419. this._lastFetchCountsRequest = this.props.api.request(this.groupCountsEndpoint, {
  420. method: 'GET',
  421. data: qs.stringify(requestParams),
  422. success: data => {
  423. if (!data) {
  424. return;
  425. }
  426. // Counts coming from the counts endpoint is limited to 100, for >= 100 we display 99+
  427. queryCounts = {
  428. ...queryCounts,
  429. ...mapValues(data, (count: number) => ({
  430. count,
  431. hasMore: count > TAB_MAX_COUNT,
  432. })),
  433. };
  434. },
  435. error: () => {
  436. this.setState({queryCounts: {}});
  437. },
  438. complete: () => {
  439. this._lastFetchCountsRequest = null;
  440. this.setState({queryCounts});
  441. },
  442. });
  443. }
  444. };
  445. fetchData = (fetchAllCounts = false) => {
  446. const {organization} = this.props;
  447. const query = this.getQuery();
  448. const hasIssueListRemovalAction = organization.features.includes(
  449. 'issue-list-removal-action'
  450. );
  451. // TODO(Kelly): update once issue-list-removal-action feature is stable
  452. if (hasIssueListRemovalAction && !this.state.realtimeActive) {
  453. if (!this.state.actionTaken && !this.state.undo) {
  454. GroupStore.loadInitialData([]);
  455. this.setState({
  456. issuesLoading: true,
  457. queryCount: 0,
  458. itemsRemoved: 0,
  459. error: null,
  460. });
  461. }
  462. } else {
  463. if (!this.state.reviewedIds.length || !isForReviewQuery(query)) {
  464. GroupStore.loadInitialData([]);
  465. this.setState({
  466. issuesLoading: true,
  467. queryCount: 0,
  468. itemsRemoved: 0,
  469. reviewedIds: [],
  470. error: null,
  471. });
  472. }
  473. }
  474. const transaction = getCurrentSentryReactTransaction();
  475. transaction?.setTag('query.sort', this.getSort());
  476. this.setState({
  477. itemsRemoved: 0,
  478. error: null,
  479. });
  480. const requestParams: any = {
  481. ...this.getEndpointParams(),
  482. limit: MAX_ITEMS,
  483. shortIdLookup: 1,
  484. };
  485. const currentQuery = this.props.location.query || {};
  486. if ('cursor' in currentQuery) {
  487. requestParams.cursor = currentQuery.cursor;
  488. }
  489. // If no stats period values are set, use default
  490. if (!requestParams.statsPeriod && !requestParams.start) {
  491. requestParams.statsPeriod = DEFAULT_STATS_PERIOD;
  492. }
  493. requestParams.expand = ['owners', 'inbox'];
  494. requestParams.collapse = 'stats';
  495. if (this._lastRequest) {
  496. this._lastRequest.cancel();
  497. }
  498. if (this._lastStatsRequest) {
  499. this._lastStatsRequest.cancel();
  500. }
  501. if (this._lastFetchCountsRequest) {
  502. this._lastFetchCountsRequest.cancel();
  503. }
  504. this._poller.disable();
  505. this._lastRequest = this.props.api.request(this.groupListEndpoint, {
  506. method: 'GET',
  507. data: qs.stringify(requestParams),
  508. success: (data, _, resp) => {
  509. if (!resp) {
  510. return;
  511. }
  512. // If this is a direct hit, we redirect to the intended result directly.
  513. if (resp.getResponseHeader('X-Sentry-Direct-Hit') === '1') {
  514. let redirect: string;
  515. if (data[0] && data[0].matchingEventId) {
  516. const {id, matchingEventId} = data[0];
  517. redirect = `/organizations/${organization.slug}/issues/${id}/events/${matchingEventId}/`;
  518. } else {
  519. const {id} = data[0];
  520. redirect = `/organizations/${organization.slug}/issues/${id}/`;
  521. }
  522. browserHistory.replace(
  523. normalizeUrl({
  524. pathname: redirect,
  525. query: {
  526. referrer: 'issue-list',
  527. ...extractSelectionParameters(this.props.location.query),
  528. },
  529. })
  530. );
  531. return;
  532. }
  533. if (this.state.undo) {
  534. GroupStore.loadInitialData(data);
  535. }
  536. GroupStore.add(data);
  537. // TODO(Kelly): update once issue-list-removal-action feature is stable
  538. if (!hasIssueListRemovalAction) {
  539. if (isForReviewQuery(query)) {
  540. GroupStore.remove(this.state.reviewedIds);
  541. }
  542. }
  543. this.fetchStats(data.map((group: BaseGroup) => group.id));
  544. const hits = resp.getResponseHeader('X-Hits');
  545. const queryCount =
  546. typeof hits !== 'undefined' && hits ? parseInt(hits, 10) || 0 : 0;
  547. const maxHits = resp.getResponseHeader('X-Max-Hits');
  548. const queryMaxCount =
  549. typeof maxHits !== 'undefined' && maxHits ? parseInt(maxHits, 10) || 0 : 0;
  550. const pageLinks = resp.getResponseHeader('Link');
  551. // TODO(Kelly): update once issue-list-removal-action feature is stable
  552. if (hasIssueListRemovalAction && !this.state.realtimeActive) {
  553. this.fetchCounts(queryCount, fetchAllCounts);
  554. } else {
  555. if (!this.state.forReview) {
  556. this.fetchCounts(queryCount, fetchAllCounts);
  557. }
  558. }
  559. this.setState({
  560. error: null,
  561. issuesLoading: false,
  562. queryCount,
  563. queryMaxCount,
  564. pageLinks: pageLinks !== null ? pageLinks : '',
  565. });
  566. if (data.length === 0) {
  567. trackAnalytics('issue_search.empty', {
  568. organization: this.props.organization,
  569. search_type: 'issues',
  570. search_source: 'main_search',
  571. query,
  572. });
  573. }
  574. },
  575. error: err => {
  576. trackAnalytics('issue_search.failed', {
  577. organization: this.props.organization,
  578. search_type: 'issues',
  579. search_source: 'main_search',
  580. error: parseApiError(err),
  581. });
  582. this.setState({
  583. error: parseApiError(err),
  584. issuesLoading: false,
  585. });
  586. },
  587. complete: () => {
  588. this._lastRequest = null;
  589. this.resumePolling();
  590. // TODO(Kelly): update once issue-list-removal-action feature is stable
  591. if (hasIssueListRemovalAction && !this.state.realtimeActive) {
  592. this.setState({actionTaken: false, undo: false});
  593. } else {
  594. this.setState({forReview: false});
  595. }
  596. },
  597. });
  598. };
  599. resumePolling = () => {
  600. if (!this.state.pageLinks) {
  601. return;
  602. }
  603. // Only resume polling if we're on the first page of results
  604. const links = parseLinkHeader(this.state.pageLinks);
  605. if (links && !links.previous.results && this.state.realtimeActive) {
  606. this._poller.setEndpoint(links?.previous?.href);
  607. this._poller.enable();
  608. }
  609. };
  610. get groupListEndpoint(): string {
  611. const {organization} = this.props;
  612. return `/organizations/${organization.slug}/issues/`;
  613. }
  614. get groupCountsEndpoint(): string {
  615. const {organization} = this.props;
  616. return `/organizations/${organization.slug}/issues-count/`;
  617. }
  618. get groupStatsEndpoint(): string {
  619. const {organization} = this.props;
  620. return `/organizations/${organization.slug}/issues-stats/`;
  621. }
  622. onRealtimeChange = (realtime: boolean) => {
  623. Cookies.set('realtimeActive', realtime.toString());
  624. this.setState({realtimeActive: realtime});
  625. trackAnalytics('issues_stream.realtime_clicked', {
  626. organization: this.props.organization,
  627. enabled: realtime,
  628. });
  629. };
  630. onSelectStatsPeriod = (period: string) => {
  631. const {location} = this.props;
  632. if (period !== this.getGroupStatsPeriod()) {
  633. const cursor = location.query.cursor;
  634. const queryPageInt = parseInt(location.query.page, 10);
  635. const page = isNaN(queryPageInt) || !location.query.cursor ? 0 : queryPageInt;
  636. this.transitionTo({cursor, page, groupStatsPeriod: period});
  637. }
  638. };
  639. onRealtimePoll = (data: any, {queryCount}: {queryCount: number}) => {
  640. // Note: We do not update state with cursors from polling,
  641. // `CursorPoller` updates itself with new cursors
  642. GroupStore.addToFront(data);
  643. this.setState({queryCount});
  644. };
  645. listener = GroupStore.listen(() => this.onGroupChange(), undefined);
  646. onGroupChange() {
  647. const {organization} = this.props;
  648. const {actionTakenGroupData} = this.state;
  649. const query = this.getQuery();
  650. const hasIssueListRemovalAction = organization.features.includes(
  651. 'issue-list-removal-action'
  652. );
  653. // TODO(Kelly): update once issue-list-removal-action feature is stable
  654. if (
  655. hasIssueListRemovalAction &&
  656. !this.state.realtimeActive &&
  657. actionTakenGroupData.length > 0
  658. ) {
  659. const filteredItems = GroupStore.getAllItems().filter(item => {
  660. return actionTakenGroupData.findIndex(data => data.id === item.id) !== -1;
  661. });
  662. const resolvedIds = filteredItems
  663. .filter(item => item.status === 'resolved')
  664. .map(id => id.id);
  665. const ignoredIds = filteredItems
  666. .filter(item => item.status === 'ignored')
  667. .map(i => i.id);
  668. // need to include resolve and ignored statuses because marking as resolved/ignored also
  669. // counts as reviewed
  670. const reviewedIds = filteredItems
  671. .filter(
  672. item => !item.inbox && item.status !== 'resolved' && item.status !== 'ignored'
  673. )
  674. .map(i => i.id);
  675. // Remove Ignored and Resolved group ids from the issue stream if on the All Unresolved,
  676. // For Review, or Ignored tab. Still include on the saved/custom search tab.
  677. if (
  678. resolvedIds.length > 0 &&
  679. (query.includes('is:unresolved') ||
  680. query.includes('is:ignored') ||
  681. isForReviewQuery(query))
  682. ) {
  683. this.onIssueAction(resolvedIds, 'Resolved');
  684. }
  685. if (
  686. ignoredIds.length > 0 &&
  687. (query.includes('is:unresolved') || isForReviewQuery(query))
  688. ) {
  689. const hasEscalatingIssues =
  690. organization.features.includes('escalating-issues-ui');
  691. this.onIssueAction(ignoredIds, hasEscalatingIssues ? 'Archived' : 'Ignored');
  692. }
  693. // Remove issues that are marked as Reviewed from the For Review tab, but still include the
  694. // issues if on the All Unresolved tab or saved/custom searches.
  695. if (
  696. reviewedIds.length > 0 &&
  697. (isForReviewQuery(query) || query.includes('is:ignored'))
  698. ) {
  699. this.onIssueAction(reviewedIds, 'Reviewed');
  700. }
  701. }
  702. const groupIds = GroupStore.getAllItems()
  703. .map(item => item.id)
  704. .slice(0, MAX_ISSUES_COUNT);
  705. if (!isEqual(groupIds, this.state.groupIds)) {
  706. this.setState({groupIds});
  707. }
  708. }
  709. trackTabViewed(groups: string[], data: Group[]) {
  710. const {organization, location} = this.props;
  711. const page = location.query.page;
  712. const endpointParams = this.getEndpointParams();
  713. const tabQueriesWithCounts = getTabsWithCounts(organization);
  714. const currentTabQuery = tabQueriesWithCounts.includes(endpointParams.query as Query)
  715. ? endpointParams.query
  716. : null;
  717. const tab = getTabs(organization).find(
  718. ([tabQuery]) => currentTabQuery === tabQuery
  719. )?.[1];
  720. const numPerfIssues = groups.filter(
  721. group => GroupStore.get(group)?.issueCategory === IssueCategory.PERFORMANCE
  722. ).length;
  723. // First and last seen are only available after the group has fetched stats
  724. // Number of issues shown whose first seen is more than 30 days ago
  725. const numOldIssues = data.filter((group: BaseGroup) =>
  726. moment(new Date(group.firstSeen)).isBefore(moment().subtract(30, 'd'))
  727. ).length;
  728. // number of issues shown whose first seen is less than 7 days
  729. const numNewIssues = data.filter((group: BaseGroup) =>
  730. moment(new Date(group.firstSeen)).isAfter(moment().subtract(7, 'd'))
  731. ).length;
  732. trackAnalytics('issues_tab.viewed', {
  733. organization,
  734. tab: tab?.analyticsName,
  735. page: page ? parseInt(page, 10) : 0,
  736. query: this.getQuery(),
  737. num_perf_issues: numPerfIssues,
  738. num_old_issues: numOldIssues,
  739. num_new_issues: numNewIssues,
  740. num_issues: data.length,
  741. sort: this.getSort(),
  742. });
  743. }
  744. onSearch = (query: string) => {
  745. if (query === this.state.query) {
  746. // if query is the same, just re-fetch data
  747. this.fetchData();
  748. } else {
  749. // Clear the saved search as the user wants something else.
  750. this.transitionTo({query}, null);
  751. }
  752. };
  753. onSortChange = (sort: string) => {
  754. trackAnalytics('issues_stream.sort_changed', {
  755. organization: this.props.organization,
  756. sort,
  757. });
  758. this.transitionTo({sort});
  759. };
  760. onCursorChange: CursorHandler = (nextCursor, _path, _query, delta) => {
  761. const queryPageInt = parseInt(this.props.location.query.page, 10);
  762. let nextPage: number | undefined = isNaN(queryPageInt) ? delta : queryPageInt + delta;
  763. let cursor: undefined | string = nextCursor;
  764. // unset cursor and page when we navigate back to the first page
  765. // also reset cursor if somehow the previous button is enabled on
  766. // first page and user attempts to go backwards
  767. if (nextPage <= 0) {
  768. cursor = undefined;
  769. nextPage = undefined;
  770. }
  771. this.transitionTo({cursor, page: nextPage});
  772. };
  773. paginationAnalyticsEvent = (direction: string) => {
  774. trackAnalytics('issues_stream.paginate', {
  775. organization: this.props.organization,
  776. direction,
  777. });
  778. };
  779. /**
  780. * Returns true if all results in the current query are visible/on this page
  781. */
  782. allResultsVisible(): boolean {
  783. if (!this.state.pageLinks) {
  784. return false;
  785. }
  786. const links = parseLinkHeader(this.state.pageLinks);
  787. return links && !links.previous.results && !links.next.results;
  788. }
  789. transitionTo = (
  790. newParams: Partial<EndpointParams> = {},
  791. savedSearch: (SavedSearch & {projectId?: number}) | null = this.props.savedSearch
  792. ) => {
  793. const query = {
  794. referrer: 'issue-list',
  795. ...this.getEndpointParams(),
  796. ...newParams,
  797. };
  798. const {organization} = this.props;
  799. let path: string;
  800. if (savedSearch && savedSearch.id) {
  801. path = `/organizations/${organization.slug}/issues/searches/${savedSearch.id}/`;
  802. // Remove the query as saved searches bring their own query string.
  803. delete query.query;
  804. // If we aren't going to another page in the same search
  805. // drop the query and replace the current project, with the saved search search project
  806. // if available.
  807. if (!query.cursor && savedSearch.projectId) {
  808. query.project = [savedSearch.projectId];
  809. }
  810. if (!query.cursor && !newParams.sort && savedSearch.sort) {
  811. query.sort = savedSearch.sort;
  812. }
  813. } else {
  814. path = `/organizations/${organization.slug}/issues/`;
  815. }
  816. // Remove inbox tab specific sort
  817. if (query.sort === IssueSortOptions.INBOX && query.query !== Query.FOR_REVIEW) {
  818. delete query.sort;
  819. }
  820. if (
  821. path !== this.props.location.pathname ||
  822. !isEqual(query, this.props.location.query)
  823. ) {
  824. browserHistory.push({
  825. pathname: normalizeUrl(path),
  826. query,
  827. });
  828. this.setState({issuesLoading: true});
  829. }
  830. };
  831. displayReprocessingTab() {
  832. const {organization} = this.props;
  833. const {queryCounts} = this.state;
  834. return (
  835. organization.features.includes('reprocessing-v2') &&
  836. !!queryCounts?.[Query.REPROCESSING]?.count
  837. );
  838. }
  839. displayReprocessingLayout(showReprocessingTab: boolean, query: string) {
  840. return showReprocessingTab && query === Query.REPROCESSING;
  841. }
  842. renderLoading(): React.ReactNode {
  843. return (
  844. <Layout.Page withPadding>
  845. <LoadingIndicator />
  846. </Layout.Page>
  847. );
  848. }
  849. onSavedSearchSelect = (savedSearch: SavedSearch) => {
  850. trackAnalytics('organization_saved_search.selected', {
  851. organization: this.props.organization,
  852. search_type: 'issues',
  853. id: savedSearch.id ? parseInt(savedSearch.id, 10) : -1,
  854. is_global: savedSearch.isGlobal,
  855. query: savedSearch.query,
  856. visibility: savedSearch.visibility,
  857. });
  858. this.setState({issuesLoading: true}, () => this.transitionTo(undefined, savedSearch));
  859. };
  860. onDelete = () => {
  861. this.setState({actionTaken: true});
  862. this.fetchData(true);
  863. };
  864. onUndo = () => {
  865. const {organization, selection} = this.props;
  866. const {actionTakenGroupData} = this.state;
  867. const query = this.getQuery();
  868. const groupIds = actionTakenGroupData.map(data => data.id);
  869. const projectIds = selection?.projects?.map(p => p.toString());
  870. const endpoint = `/organizations/${organization.slug}/issues/`;
  871. if (this._lastRequest) {
  872. this._lastRequest.cancel();
  873. }
  874. if (this._lastStatsRequest) {
  875. this._lastStatsRequest.cancel();
  876. }
  877. if (this._lastFetchCountsRequest) {
  878. this._lastFetchCountsRequest.cancel();
  879. }
  880. this.props.api.request(endpoint, {
  881. method: 'PUT',
  882. data: {
  883. status: 'unresolved',
  884. },
  885. query: {
  886. project: projectIds,
  887. id: groupIds,
  888. },
  889. success: response => {
  890. if (!response) {
  891. return;
  892. }
  893. // If on the Ignore or For Review tab, adding back to the GroupStore will make the issue show up
  894. // on this page for a second and then be removed (will show up on All Unresolved). This is to
  895. // stop this from happening and avoid confusion.
  896. if (!query.includes('is:ignored') && !isForReviewQuery(query)) {
  897. GroupStore.add(actionTakenGroupData);
  898. }
  899. this.setState({undo: true});
  900. },
  901. error: err => {
  902. this.setState({
  903. error: parseApiError(err),
  904. issuesLoading: false,
  905. });
  906. },
  907. complete: () => {
  908. this.setState({actionTakenGroupData: []});
  909. this.fetchData();
  910. },
  911. });
  912. };
  913. onMarkReviewed = (itemIds: string[]) => {
  914. const {organization} = this.props;
  915. const query = this.getQuery();
  916. const hasIssueListRemovalAction = organization.features.includes(
  917. 'issue-list-removal-action'
  918. );
  919. if (!isForReviewQuery(query)) {
  920. if (itemIds.length > 1) {
  921. addMessage(
  922. tn('Reviewed %s Issue', 'Reviewed %s Issues', itemIds.length),
  923. 'success',
  924. {duration: 4000}
  925. );
  926. } else {
  927. const shortId = itemIds.map(item => GroupStore.get(item)?.shortId).toString();
  928. addMessage(t('Reviewed %s', shortId), 'success', {duration: 4000});
  929. }
  930. return;
  931. }
  932. const {queryCounts, itemsRemoved} = this.state;
  933. const currentQueryCount = queryCounts[query as Query];
  934. if (itemIds.length && currentQueryCount) {
  935. const inInboxCount = itemIds.filter(id => GroupStore.get(id)?.inbox).length;
  936. currentQueryCount.count -= inInboxCount;
  937. // TODO(Kelly): update once issue-list-removal-action feature is stable
  938. if (!hasIssueListRemovalAction) {
  939. this.setState({
  940. reviewedIds: itemIds,
  941. forReview: true,
  942. });
  943. }
  944. this.setState({
  945. queryCounts: {
  946. ...queryCounts,
  947. [query as Query]: currentQueryCount,
  948. },
  949. itemsRemoved: itemsRemoved + inInboxCount,
  950. });
  951. }
  952. };
  953. onActionTaken = (itemIds: string[]) => {
  954. const actionTakenGroupData = itemIds.map(id => GroupStore.get(id) as Group);
  955. this.setState({
  956. actionTakenGroupData,
  957. });
  958. };
  959. onIssueAction = (
  960. itemIds: string[],
  961. actionType: 'Reviewed' | 'Resolved' | 'Ignored' | 'Archived'
  962. ) => {
  963. if (itemIds.length > 1) {
  964. addMessage(`${actionType} ${itemIds.length} ${t('Issues')}`, 'success', {
  965. duration: 4000,
  966. ...(actionType !== 'Reviewed' && {undo: this.onUndo}),
  967. });
  968. } else {
  969. const shortId = itemIds.map(item => GroupStore.get(item)?.shortId).toString();
  970. addMessage(`${actionType} ${shortId}`, 'success', {
  971. duration: 4000,
  972. ...(actionType !== 'Reviewed' && {undo: this.onUndo}),
  973. });
  974. }
  975. const links = parseLinkHeader(this.state.pageLinks);
  976. GroupStore.remove(itemIds);
  977. const queryCount = this.state.queryCount - itemIds.length;
  978. this.setState({
  979. actionTaken: true,
  980. queryCount,
  981. });
  982. if (GroupStore.getAllItemIds().length === 0) {
  983. // If we run out of issues on the last page, navigate back a page to
  984. // avoid showing an empty state - if not on the last page, just show a spinner
  985. const shouldGoBackAPage = links?.previous?.results && !links?.next?.results;
  986. this.transitionTo({cursor: shouldGoBackAPage ? links.previous.cursor : undefined});
  987. this.fetchCounts(queryCount, true);
  988. } else {
  989. this.fetchData(true);
  990. }
  991. };
  992. tagValueLoader = (key: string, search: string) => {
  993. const {organization} = this.props;
  994. const projectIds = this.getSelectedProjectIds();
  995. const endpointParams = this.getEndpointParams();
  996. return fetchTagValues({
  997. api: this.props.api,
  998. orgSlug: organization.slug,
  999. tagKey: key,
  1000. search,
  1001. projectIds,
  1002. endpointParams: endpointParams as any,
  1003. });
  1004. };
  1005. getPageCounts = () => {
  1006. const {location} = this.props;
  1007. const {pageLinks, queryCount, groupIds} = this.state;
  1008. const links = parseLinkHeader(pageLinks);
  1009. const queryPageInt = parseInt(location.query.page, 10);
  1010. // Cursor must be present for the page number to be used
  1011. const page = isNaN(queryPageInt) || !location.query.cursor ? 0 : queryPageInt;
  1012. let numPreviousIssues = Math.min(page * MAX_ITEMS, queryCount);
  1013. // Because the query param `page` is not tied to the request, we need to
  1014. // validate that it's correct at the first and last page
  1015. if (!links?.next?.results || this.allResultsVisible()) {
  1016. // On last available page
  1017. numPreviousIssues = Math.max(queryCount - groupIds.length, 0);
  1018. } else if (!links?.previous?.results) {
  1019. // On first available page
  1020. numPreviousIssues = 0;
  1021. }
  1022. return {
  1023. numPreviousIssues,
  1024. numIssuesOnPage: groupIds.length,
  1025. };
  1026. };
  1027. render() {
  1028. if (this.props.savedSearchLoading) {
  1029. return this.renderLoading();
  1030. }
  1031. const {
  1032. pageLinks,
  1033. queryCount,
  1034. queryCounts,
  1035. realtimeActive,
  1036. groupIds,
  1037. queryMaxCount,
  1038. itemsRemoved,
  1039. issuesLoading,
  1040. error,
  1041. } = this.state;
  1042. const {organization, selection, router} = this.props;
  1043. const query = this.getQuery();
  1044. const modifiedQueryCount = Math.max(queryCount - itemsRemoved, 0);
  1045. const projectIds = selection?.projects?.map(p => p.toString());
  1046. const showReprocessingTab = this.displayReprocessingTab();
  1047. const displayReprocessingActions = this.displayReprocessingLayout(
  1048. showReprocessingTab,
  1049. query
  1050. );
  1051. const {numPreviousIssues, numIssuesOnPage} = this.getPageCounts();
  1052. return (
  1053. <Layout.Page>
  1054. <IssueListHeader
  1055. organization={organization}
  1056. query={query}
  1057. sort={this.getSort()}
  1058. queryCount={queryCount}
  1059. queryCounts={queryCounts}
  1060. realtimeActive={realtimeActive}
  1061. onRealtimeChange={this.onRealtimeChange}
  1062. router={router}
  1063. displayReprocessingTab={showReprocessingTab}
  1064. selectedProjectIds={selection.projects}
  1065. />
  1066. <StyledBody>
  1067. <StyledMain>
  1068. <IssueListFilters query={query} onSearch={this.onSearch} />
  1069. <Panel>
  1070. <IssueListActions
  1071. selection={selection}
  1072. query={query}
  1073. queryCount={modifiedQueryCount}
  1074. onSelectStatsPeriod={this.onSelectStatsPeriod}
  1075. onMarkReviewed={this.onMarkReviewed}
  1076. onActionTaken={this.onActionTaken}
  1077. onDelete={this.onDelete}
  1078. statsPeriod={this.getGroupStatsPeriod()}
  1079. groupIds={groupIds}
  1080. allResultsVisible={this.allResultsVisible()}
  1081. displayReprocessingActions={displayReprocessingActions}
  1082. sort={this.getSort()}
  1083. onSortChange={this.onSortChange}
  1084. />
  1085. <PanelBody>
  1086. <ProcessingIssueList
  1087. organization={organization}
  1088. projectIds={projectIds}
  1089. showProject
  1090. />
  1091. <VisuallyCompleteWithData
  1092. hasData={this.state.groupIds.length > 0}
  1093. id="IssueList-Body"
  1094. isLoading={this.state.issuesLoading}
  1095. >
  1096. <GroupListBody
  1097. memberList={this.state.memberList}
  1098. groupStatsPeriod={this.getGroupStatsPeriod()}
  1099. groupIds={groupIds}
  1100. displayReprocessingLayout={displayReprocessingActions}
  1101. query={query}
  1102. sort={this.getSort()}
  1103. selectedProjectIds={selection.projects}
  1104. loading={issuesLoading}
  1105. error={error}
  1106. refetchGroups={this.fetchData}
  1107. />
  1108. </VisuallyCompleteWithData>
  1109. </PanelBody>
  1110. </Panel>
  1111. <StyledPagination
  1112. caption={
  1113. !issuesLoading && modifiedQueryCount > 0
  1114. ? tct('[start]-[end] of [total]', {
  1115. start: numPreviousIssues + 1,
  1116. end: numPreviousIssues + numIssuesOnPage,
  1117. total: (
  1118. <StyledQueryCount
  1119. hideParens
  1120. hideIfEmpty={false}
  1121. count={modifiedQueryCount}
  1122. max={queryMaxCount || 100}
  1123. />
  1124. ),
  1125. })
  1126. : null
  1127. }
  1128. pageLinks={pageLinks}
  1129. onCursor={this.onCursorChange}
  1130. paginationAnalyticsEvent={this.paginationAnalyticsEvent}
  1131. />
  1132. </StyledMain>
  1133. <SavedIssueSearches
  1134. {...{organization, query}}
  1135. onSavedSearchSelect={this.onSavedSearchSelect}
  1136. sort={this.getSort()}
  1137. />
  1138. </StyledBody>
  1139. </Layout.Page>
  1140. );
  1141. }
  1142. }
  1143. export default withRouteAnalytics(
  1144. withApi(
  1145. withPageFilters(
  1146. withSavedSearches(withOrganization(withIssueTags(withProfiler(IssueListOverview))))
  1147. )
  1148. )
  1149. );
  1150. export {IssueListOverview};
  1151. const StyledBody = styled('div')`
  1152. background-color: ${p => p.theme.background};
  1153. flex: 1;
  1154. display: grid;
  1155. gap: 0;
  1156. padding: 0;
  1157. grid-template-rows: 1fr;
  1158. grid-template-columns: minmax(0, 1fr) auto;
  1159. grid-template-areas: 'content saved-searches';
  1160. `;
  1161. const StyledMain = styled('section')`
  1162. grid-area: content;
  1163. padding: ${space(2)};
  1164. @media (min-width: ${p => p.theme.breakpoints.medium}) {
  1165. padding: ${space(3)} ${space(4)};
  1166. }
  1167. `;
  1168. const StyledPagination = styled(Pagination)`
  1169. margin-top: 0;
  1170. `;
  1171. const StyledQueryCount = styled(QueryCount)`
  1172. margin-left: 0;
  1173. `;