overview.tsx 38 KB

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