overview.tsx 40 KB

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