overview.tsx 40 KB

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