overview.tsx 39 KB

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