overview.tsx 39 KB

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