overview.tsx 40 KB

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