overview.tsx 39 KB

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