overview.tsx 40 KB

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