overview.tsx 39 KB

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