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