overview.tsx 39 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306
  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, tn} 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 CursorPoller from 'sentry/utils/cursorPoller';
  46. import {getUtcDateString} from 'sentry/utils/dates';
  47. import getCurrentSentryReactTransaction from 'sentry/utils/getCurrentSentryReactTransaction';
  48. import parseApiError from 'sentry/utils/parseApiError';
  49. import parseLinkHeader from 'sentry/utils/parseLinkHeader';
  50. import {VisuallyCompleteWithData} from 'sentry/utils/performanceForSentry';
  51. import {decodeScalar} from 'sentry/utils/queryString';
  52. import withApi from 'sentry/utils/withApi';
  53. import withIssueTags from 'sentry/utils/withIssueTags';
  54. import withOrganization from 'sentry/utils/withOrganization';
  55. import withPageFilters from 'sentry/utils/withPageFilters';
  56. import withSavedSearches from 'sentry/utils/withSavedSearches';
  57. import IssueListActions from './actions';
  58. import IssueListFilters from './filters';
  59. import GroupListBody from './groupListBody';
  60. import IssueListHeader from './header';
  61. import IssueListSidebar from './sidebar';
  62. import {
  63. getTabs,
  64. getTabsWithCounts,
  65. isForReviewQuery,
  66. IssueSortOptions,
  67. Query,
  68. QueryCounts,
  69. TAB_MAX_COUNT,
  70. } from './utils';
  71. const MAX_ITEMS = 25;
  72. const DEFAULT_SORT = IssueSortOptions.DATE;
  73. // the default period for the graph in each issue row
  74. const DEFAULT_GRAPH_STATS_PERIOD = '24h';
  75. // the allowed period choices for graph in each issue row
  76. const DYNAMIC_COUNTS_STATS_PERIODS = new Set(['14d', '24h', 'auto']);
  77. const MAX_ISSUES_COUNT = 100;
  78. type Params = {
  79. orgId: string;
  80. };
  81. type Props = {
  82. api: Client;
  83. location: Location;
  84. organization: Organization;
  85. params: Params;
  86. savedSearch: SavedSearch;
  87. savedSearchLoading: boolean;
  88. savedSearches: SavedSearch[];
  89. selection: PageFilters;
  90. tags: TagCollection;
  91. } & RouteComponentProps<{searchId?: string}, {}>;
  92. type State = {
  93. actionTaken: boolean;
  94. actionTakenGroupData: Group[];
  95. error: string | null;
  96. // TODO(Kelly): remove forReview once issue-list-removal-action feature is stable
  97. forReview: boolean;
  98. groupIds: string[];
  99. isSidebarVisible: boolean;
  100. issuesLoading: boolean;
  101. itemsRemoved: number;
  102. memberList: ReturnType<typeof indexMembersByProject>;
  103. pageLinks: string;
  104. /**
  105. * Current query total
  106. */
  107. queryCount: number;
  108. /**
  109. * Counts for each inbox tab
  110. */
  111. queryCounts: QueryCounts;
  112. queryMaxCount: number;
  113. realtimeActive: boolean;
  114. // TODO(Kelly): remove reviewedIds once issue-list-removal-action feature is stable
  115. reviewedIds: string[];
  116. selectAllActive: boolean;
  117. tagsLoading: boolean;
  118. undo: boolean;
  119. // Will be set to true if there is valid session data from issue-stats api call
  120. query?: string;
  121. };
  122. type EndpointParams = Partial<PageFilters['datetime']> & {
  123. environment: string[];
  124. project: number[];
  125. cursor?: string;
  126. groupStatsPeriod?: string | null;
  127. page?: number | string;
  128. query?: string;
  129. sort?: string;
  130. statsPeriod?: string | null;
  131. };
  132. type CountsEndpointParams = Omit<EndpointParams, 'cursor' | 'page' | 'query'> & {
  133. query: string[];
  134. };
  135. type StatEndpointParams = Omit<EndpointParams, 'cursor' | 'page'> & {
  136. groups: string[];
  137. expand?: string | string[];
  138. };
  139. class IssueListOverview extends Component<Props, State> {
  140. state: State = this.getInitialState();
  141. getInitialState() {
  142. const realtimeActiveCookie = Cookies.get('realtimeActive');
  143. const realtimeActive =
  144. typeof realtimeActiveCookie === 'undefined'
  145. ? false
  146. : realtimeActiveCookie === 'true';
  147. return {
  148. groupIds: [],
  149. // TODO(Kelly): remove reviewedIds and forReview once issue-list-removal-action feature is stable
  150. reviewedIds: [],
  151. actionTaken: false,
  152. actionTakenGroupData: [],
  153. forReview: false,
  154. undo: false,
  155. selectAllActive: false,
  156. realtimeActive,
  157. pageLinks: '',
  158. itemsRemoved: 0,
  159. queryCount: 0,
  160. queryCounts: {},
  161. queryMaxCount: 0,
  162. error: null,
  163. isSidebarVisible: false,
  164. issuesLoading: true,
  165. tagsLoading: true,
  166. memberList: {},
  167. };
  168. }
  169. componentDidMount() {
  170. this._poller = new CursorPoller({
  171. linkPreviousHref: parseLinkHeader(this.state.pageLinks)?.previous?.href,
  172. success: this.onRealtimePoll,
  173. });
  174. // Start by getting searches first so if the user is on a saved search
  175. // or they have a pinned search we load the correct data the first time.
  176. this.fetchSavedSearches();
  177. this.fetchTags();
  178. this.fetchMemberList();
  179. }
  180. componentDidUpdate(prevProps: Props, prevState: State) {
  181. if (prevState.realtimeActive !== this.state.realtimeActive) {
  182. // User toggled realtime button
  183. if (this.state.realtimeActive) {
  184. this.resumePolling();
  185. } else {
  186. this._poller.disable();
  187. }
  188. }
  189. // If the project selection has changed reload the member list and tag keys
  190. // allowing autocomplete and tag sidebar to be more accurate.
  191. if (!isEqual(prevProps.selection.projects, this.props.selection.projects)) {
  192. this.fetchMemberList();
  193. this.fetchTags();
  194. }
  195. // TODO(Kelly): remove once issue-list-removal-action feature is stable
  196. if (!this.props.organization.features.includes('issue-list-removal-action')) {
  197. if (prevState.forReview !== this.state.forReview) {
  198. this.fetchData();
  199. }
  200. }
  201. // Wait for saved searches to load before we attempt to fetch stream data
  202. if (this.props.savedSearchLoading) {
  203. return;
  204. }
  205. if (prevProps.savedSearchLoading) {
  206. this.fetchData();
  207. return;
  208. }
  209. const prevQuery = prevProps.location.query;
  210. const newQuery = this.props.location.query;
  211. const selectionChanged = !isEqual(prevProps.selection, this.props.selection);
  212. // If any important url parameter changed or saved search changed
  213. // reload data.
  214. if (
  215. selectionChanged ||
  216. prevQuery.cursor !== newQuery.cursor ||
  217. prevQuery.sort !== newQuery.sort ||
  218. prevQuery.query !== newQuery.query ||
  219. prevQuery.statsPeriod !== newQuery.statsPeriod ||
  220. prevQuery.groupStatsPeriod !== newQuery.groupStatsPeriod ||
  221. prevProps.savedSearch !== this.props.savedSearch
  222. ) {
  223. this.fetchData(selectionChanged);
  224. } else if (
  225. !this._lastRequest &&
  226. prevState.issuesLoading === false &&
  227. this.state.issuesLoading
  228. ) {
  229. // Reload if we issues are loading or their loading state changed.
  230. // This can happen when transitionTo is called
  231. this.fetchData();
  232. }
  233. }
  234. componentWillUnmount() {
  235. this._poller.disable();
  236. GroupStore.reset();
  237. this.props.api.clear();
  238. this.listener?.();
  239. // Reset store when unmounting because we always fetch on mount
  240. // This means if you navigate away from stream and then back to stream,
  241. // this component will go from:
  242. // "ready" ->
  243. // "loading" (because fetching saved searches) ->
  244. // "ready"
  245. //
  246. // We don't render anything until saved searches is ready, so this can
  247. // cause weird side effects (e.g. ProcessingIssueList mounting and making
  248. // a request, but immediately unmounting when fetching saved searches)
  249. resetSavedSearches();
  250. }
  251. private _poller: any;
  252. private _lastRequest: any;
  253. private _lastStatsRequest: any;
  254. private _lastFetchCountsRequest: any;
  255. getQuery(): string {
  256. const {savedSearch, location} = this.props;
  257. if (savedSearch) {
  258. return savedSearch.query;
  259. }
  260. const {query} = location.query;
  261. if (query !== undefined) {
  262. return decodeScalar(query, '');
  263. }
  264. return DEFAULT_QUERY;
  265. }
  266. getSort(): string {
  267. const {location, savedSearch} = this.props;
  268. if (!location.query.sort && savedSearch?.id) {
  269. return savedSearch.sort;
  270. }
  271. if (location.query.sort) {
  272. return location.query.sort as string;
  273. }
  274. return DEFAULT_SORT;
  275. }
  276. getGroupStatsPeriod(): string {
  277. let currentPeriod: string;
  278. if (typeof this.props.location.query?.groupStatsPeriod === 'string') {
  279. currentPeriod = this.props.location.query.groupStatsPeriod;
  280. } else if (this.getSort() === IssueSortOptions.TREND) {
  281. // Default to the larger graph when sorting by relative change
  282. currentPeriod = 'auto';
  283. } else {
  284. currentPeriod = DEFAULT_GRAPH_STATS_PERIOD;
  285. }
  286. return DYNAMIC_COUNTS_STATS_PERIODS.has(currentPeriod)
  287. ? currentPeriod
  288. : DEFAULT_GRAPH_STATS_PERIOD;
  289. }
  290. getEndpointParams = (): EndpointParams => {
  291. const {selection} = this.props;
  292. const params: EndpointParams = {
  293. project: selection.projects,
  294. environment: selection.environments,
  295. query: this.getQuery(),
  296. ...selection.datetime,
  297. };
  298. if (selection.datetime.period) {
  299. delete params.period;
  300. params.statsPeriod = selection.datetime.period;
  301. }
  302. if (params.end) {
  303. params.end = getUtcDateString(params.end);
  304. }
  305. if (params.start) {
  306. params.start = getUtcDateString(params.start);
  307. }
  308. const sort = this.getSort();
  309. if (sort !== DEFAULT_SORT) {
  310. params.sort = sort;
  311. }
  312. const groupStatsPeriod = this.getGroupStatsPeriod();
  313. if (groupStatsPeriod !== DEFAULT_GRAPH_STATS_PERIOD) {
  314. params.groupStatsPeriod = groupStatsPeriod;
  315. }
  316. // only include defined values.
  317. return pickBy(params, v => defined(v)) as EndpointParams;
  318. };
  319. getSelectedProjectIds = (): string[] => {
  320. return this.props.selection.projects.map(projectId => String(projectId));
  321. };
  322. fetchMemberList() {
  323. const projectIds = this.getSelectedProjectIds();
  324. fetchOrgMembers(this.props.api, this.props.organization.slug, projectIds).then(
  325. members => {
  326. this.setState({memberList: indexMembersByProject(members)});
  327. }
  328. );
  329. }
  330. fetchTags() {
  331. const {api, organization, selection} = this.props;
  332. this.setState({tagsLoading: true});
  333. loadOrganizationTags(api, organization.slug, selection).then(() =>
  334. this.setState({tagsLoading: false})
  335. );
  336. }
  337. fetchSavedSearches() {
  338. const {organization, api} = this.props;
  339. fetchSavedSearches(api, organization.slug);
  340. }
  341. fetchStats = (groups: string[]) => {
  342. // If we have no groups to fetch, just skip stats
  343. if (!groups.length) {
  344. return;
  345. }
  346. const requestParams: StatEndpointParams = {
  347. ...this.getEndpointParams(),
  348. groups,
  349. };
  350. // If no stats period values are set, use default
  351. if (!requestParams.statsPeriod && !requestParams.start) {
  352. requestParams.statsPeriod = DEFAULT_STATS_PERIOD;
  353. }
  354. this._lastStatsRequest = this.props.api.request(this.groupStatsEndpoint, {
  355. method: 'GET',
  356. data: qs.stringify(requestParams),
  357. success: data => {
  358. if (!data) {
  359. return;
  360. }
  361. GroupStore.onPopulateStats(groups, data);
  362. },
  363. error: err => {
  364. this.setState({
  365. error: parseApiError(err),
  366. });
  367. },
  368. complete: () => {
  369. this._lastStatsRequest = null;
  370. // End navigation transaction to prevent additional page requests from impacting page metrics.
  371. // Other transactions include stacktrace preview request
  372. const currentTransaction = Sentry.getCurrentHub().getScope()?.getTransaction();
  373. if (currentTransaction?.op === 'navigation') {
  374. currentTransaction.finish();
  375. }
  376. },
  377. });
  378. };
  379. fetchCounts = (currentQueryCount: number, fetchAllCounts: boolean) => {
  380. const {organization} = this.props;
  381. const {queryCounts: _queryCounts} = this.state;
  382. let queryCounts: QueryCounts = {..._queryCounts};
  383. const endpointParams = this.getEndpointParams();
  384. const tabQueriesWithCounts = getTabsWithCounts(organization);
  385. const currentTabQuery = tabQueriesWithCounts.includes(endpointParams.query as Query)
  386. ? endpointParams.query
  387. : null;
  388. // Update the count based on the exact number of issues, these shown as is
  389. if (currentTabQuery) {
  390. queryCounts[currentTabQuery] = {
  391. count: currentQueryCount,
  392. hasMore: false,
  393. };
  394. }
  395. this.setState({queryCounts});
  396. // If all tabs' counts are fetched, skip and only set
  397. if (
  398. fetchAllCounts ||
  399. !tabQueriesWithCounts.every(tabQuery => queryCounts[tabQuery] !== undefined)
  400. ) {
  401. const requestParams: CountsEndpointParams = {
  402. ...omit(endpointParams, 'query'),
  403. // fetch the counts for the tabs whose counts haven't been fetched yet
  404. query: tabQueriesWithCounts.filter(_query => _query !== currentTabQuery),
  405. };
  406. // If no stats period values are set, use default
  407. if (!requestParams.statsPeriod && !requestParams.start) {
  408. requestParams.statsPeriod = DEFAULT_STATS_PERIOD;
  409. }
  410. this._lastFetchCountsRequest = this.props.api.request(this.groupCountsEndpoint, {
  411. method: 'GET',
  412. data: qs.stringify(requestParams),
  413. success: data => {
  414. if (!data) {
  415. return;
  416. }
  417. // Counts coming from the counts endpoint is limited to 100, for >= 100 we display 99+
  418. queryCounts = {
  419. ...queryCounts,
  420. ...mapValues(data, (count: number) => ({
  421. count,
  422. hasMore: count > TAB_MAX_COUNT,
  423. })),
  424. };
  425. },
  426. error: () => {
  427. this.setState({queryCounts: {}});
  428. },
  429. complete: () => {
  430. this._lastFetchCountsRequest = null;
  431. this.setState({queryCounts});
  432. },
  433. });
  434. }
  435. };
  436. fetchData = (fetchAllCounts = false) => {
  437. const {organization} = this.props;
  438. const query = this.getQuery();
  439. const hasIssueListRemovalAction = organization.features.includes(
  440. 'issue-list-removal-action'
  441. );
  442. // TODO(Kelly): update once issue-list-removal-action feature is stable
  443. if (hasIssueListRemovalAction && !this.state.realtimeActive) {
  444. if (!this.state.actionTaken && !this.state.undo) {
  445. GroupStore.loadInitialData([]);
  446. this.setState({
  447. issuesLoading: true,
  448. queryCount: 0,
  449. itemsRemoved: 0,
  450. error: null,
  451. });
  452. }
  453. } else {
  454. if (!this.state.reviewedIds.length || !isForReviewQuery(query)) {
  455. GroupStore.loadInitialData([]);
  456. this.setState({
  457. issuesLoading: true,
  458. queryCount: 0,
  459. itemsRemoved: 0,
  460. reviewedIds: [],
  461. error: null,
  462. });
  463. }
  464. }
  465. const transaction = getCurrentSentryReactTransaction();
  466. transaction?.setTag('query.sort', this.getSort());
  467. this.setState({
  468. queryCount: 0,
  469. itemsRemoved: 0,
  470. error: null,
  471. });
  472. const requestParams: any = {
  473. ...this.getEndpointParams(),
  474. limit: MAX_ITEMS,
  475. shortIdLookup: 1,
  476. };
  477. const currentQuery = this.props.location.query || {};
  478. if ('cursor' in currentQuery) {
  479. requestParams.cursor = currentQuery.cursor;
  480. }
  481. // If no stats period values are set, use default
  482. if (!requestParams.statsPeriod && !requestParams.start) {
  483. requestParams.statsPeriod = DEFAULT_STATS_PERIOD;
  484. }
  485. requestParams.expand = ['owners', 'inbox'];
  486. requestParams.collapse = 'stats';
  487. if (this._lastRequest) {
  488. this._lastRequest.cancel();
  489. }
  490. if (this._lastStatsRequest) {
  491. this._lastStatsRequest.cancel();
  492. }
  493. if (this._lastFetchCountsRequest) {
  494. this._lastFetchCountsRequest.cancel();
  495. }
  496. this._poller.disable();
  497. this._lastRequest = this.props.api.request(this.groupListEndpoint, {
  498. method: 'GET',
  499. data: qs.stringify(requestParams),
  500. success: (data, _, resp) => {
  501. if (!resp) {
  502. return;
  503. }
  504. const {orgId} = this.props.params;
  505. // If this is a direct hit, we redirect to the intended result directly.
  506. if (resp.getResponseHeader('X-Sentry-Direct-Hit') === '1') {
  507. let redirect: string;
  508. if (data[0] && data[0].matchingEventId) {
  509. const {id, matchingEventId} = data[0];
  510. redirect = `/organizations/${orgId}/issues/${id}/events/${matchingEventId}/`;
  511. } else {
  512. const {id} = data[0];
  513. redirect = `/organizations/${orgId}/issues/${id}/`;
  514. }
  515. browserHistory.replace({
  516. pathname: redirect,
  517. query: extractSelectionParameters(this.props.location.query),
  518. });
  519. return;
  520. }
  521. if (this.state.undo) {
  522. GroupStore.loadInitialData(data);
  523. }
  524. GroupStore.add(data);
  525. // TODO(Kelly): update once issue-list-removal-action feature is stable
  526. if (!hasIssueListRemovalAction) {
  527. if (isForReviewQuery(query)) {
  528. GroupStore.remove(this.state.reviewedIds);
  529. }
  530. }
  531. const numPerfIssues = data.filter(
  532. (group: BaseGroup) => group.issueCategory === IssueCategory.PERFORMANCE
  533. ).length;
  534. const page = this.props.location.query.page;
  535. const endpointParams = this.getEndpointParams();
  536. const tabQueriesWithCounts = getTabsWithCounts(organization);
  537. const currentTabQuery = tabQueriesWithCounts.includes(
  538. endpointParams.query as Query
  539. )
  540. ? endpointParams.query
  541. : null;
  542. const tab = getTabs(organization).find(
  543. ([tabQuery]) => currentTabQuery === tabQuery
  544. )?.[1];
  545. trackAdvancedAnalyticsEvent('issues_tab.viewed', {
  546. organization,
  547. tab: tab?.analyticsName,
  548. page: page ? parseInt(page, 10) : 0,
  549. query,
  550. num_perf_issues: numPerfIssues,
  551. num_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, 'Resolved');
  690. }
  691. if (
  692. ignoredIds.length > 0 &&
  693. (query.includes('is:unresolved') || isForReviewQuery(query))
  694. ) {
  695. this.onIssueAction(ignoredIds, '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, '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(
  916. tn('Reviewed %s Issue', 'Reviewed %s Issues', itemIds.length),
  917. 'success',
  918. {duration: 4000}
  919. );
  920. } else {
  921. const shortId = itemIds.map(item => GroupStore.get(item)?.shortId).toString();
  922. addMessage(t('Reviewed %s', shortId), 'success', {duration: 4000});
  923. }
  924. return;
  925. }
  926. const {queryCounts, itemsRemoved} = this.state;
  927. const currentQueryCount = queryCounts[query as Query];
  928. if (itemIds.length && currentQueryCount) {
  929. const inInboxCount = itemIds.filter(id => GroupStore.get(id)?.inbox).length;
  930. currentQueryCount.count -= inInboxCount;
  931. // TODO(Kelly): update once issue-list-removal-action feature is stable
  932. if (!hasIssueListRemovalAction) {
  933. this.setState({
  934. reviewedIds: itemIds,
  935. forReview: true,
  936. });
  937. }
  938. this.setState({
  939. queryCounts: {
  940. ...queryCounts,
  941. [query as Query]: currentQueryCount,
  942. },
  943. itemsRemoved: itemsRemoved + inInboxCount,
  944. });
  945. }
  946. };
  947. onActionTaken = (itemIds: string[]) => {
  948. const actionTakenGroupData = itemIds.map(id => GroupStore.get(id) as Group);
  949. this.setState({
  950. actionTakenGroupData,
  951. });
  952. };
  953. onIssueAction = (
  954. itemIds: string[],
  955. actionType: 'Reviewed' | 'Resolved' | 'Ignored'
  956. ) => {
  957. if (itemIds.length > 1) {
  958. addMessage(`${actionType} ${itemIds.length} ${t('Issues')}`, 'success', {
  959. duration: 4000,
  960. ...(actionType !== 'Reviewed' && {undo: this.onUndo}),
  961. });
  962. } else {
  963. const shortId = itemIds.map(item => GroupStore.get(item)?.shortId).toString();
  964. addMessage(`${actionType} ${shortId}`, 'success', {
  965. duration: 4000,
  966. ...(actionType !== 'Reviewed' && {undo: this.onUndo}),
  967. });
  968. }
  969. GroupStore.remove(itemIds);
  970. this.setState({actionTaken: true});
  971. this.fetchData(true);
  972. };
  973. tagValueLoader = (key: string, search: string) => {
  974. const {orgId} = this.props.params;
  975. const projectIds = this.getSelectedProjectIds();
  976. const endpointParams = this.getEndpointParams();
  977. return fetchTagValues(
  978. this.props.api,
  979. orgId,
  980. key,
  981. search,
  982. projectIds,
  983. endpointParams as any
  984. );
  985. };
  986. render() {
  987. if (this.props.savedSearchLoading) {
  988. return this.renderLoading();
  989. }
  990. const {
  991. isSidebarVisible,
  992. tagsLoading,
  993. pageLinks,
  994. queryCount,
  995. queryCounts,
  996. realtimeActive,
  997. groupIds,
  998. queryMaxCount,
  999. itemsRemoved,
  1000. issuesLoading,
  1001. error,
  1002. } = this.state;
  1003. const {organization, savedSearch, savedSearches, tags, selection, location, router} =
  1004. this.props;
  1005. const links = parseLinkHeader(pageLinks);
  1006. const query = this.getQuery();
  1007. const queryPageInt = parseInt(location.query.page, 10);
  1008. // Cursor must be present for the page number to be used
  1009. const page = isNaN(queryPageInt) || !location.query.cursor ? 0 : queryPageInt;
  1010. const pageBasedCount = page * MAX_ITEMS + groupIds.length;
  1011. let pageCount = pageBasedCount > queryCount ? queryCount : pageBasedCount;
  1012. if (!links?.next?.results || this.allResultsVisible()) {
  1013. // On last available page
  1014. pageCount = queryCount;
  1015. } else if (!links?.previous?.results) {
  1016. // On first available page
  1017. pageCount = groupIds.length;
  1018. }
  1019. // Subtract # items that have been marked reviewed
  1020. pageCount = Math.max(pageCount - itemsRemoved, 0);
  1021. const modifiedQueryCount = Math.max(queryCount - itemsRemoved, 0);
  1022. const displayCount = tct('[count] of [total]', {
  1023. count: pageCount,
  1024. total: (
  1025. <StyledQueryCount
  1026. hideParens
  1027. hideIfEmpty={false}
  1028. count={modifiedQueryCount}
  1029. max={queryMaxCount || 100}
  1030. />
  1031. ),
  1032. });
  1033. const projectIds = selection?.projects?.map(p => p.toString());
  1034. const showReprocessingTab = this.displayReprocessingTab();
  1035. const displayReprocessingActions = this.displayReprocessingLayout(
  1036. showReprocessingTab,
  1037. query
  1038. );
  1039. const layoutProps = {
  1040. fullWidth: !isSidebarVisible,
  1041. };
  1042. return (
  1043. <StyledPageContent>
  1044. <IssueListHeader
  1045. organization={organization}
  1046. query={query}
  1047. sort={this.getSort()}
  1048. queryCount={queryCount}
  1049. queryCounts={queryCounts}
  1050. realtimeActive={realtimeActive}
  1051. onRealtimeChange={this.onRealtimeChange}
  1052. router={router}
  1053. savedSearchList={savedSearches}
  1054. onSavedSearchSelect={this.onSavedSearchSelect}
  1055. onSavedSearchDelete={this.onSavedSearchDelete}
  1056. displayReprocessingTab={showReprocessingTab}
  1057. selectedProjectIds={selection.projects}
  1058. />
  1059. <Layout.Body {...layoutProps}>
  1060. <Layout.Main {...layoutProps}>
  1061. <IssueListFilters
  1062. organization={organization}
  1063. query={query}
  1064. savedSearch={savedSearch}
  1065. sort={this.getSort()}
  1066. onSearch={this.onSearch}
  1067. onSidebarToggle={this.onSidebarToggle}
  1068. isSearchDisabled={isSidebarVisible}
  1069. tagValueLoader={this.tagValueLoader}
  1070. tags={tags}
  1071. />
  1072. <Panel>
  1073. <IssueListActions
  1074. selection={selection}
  1075. query={query}
  1076. queryCount={modifiedQueryCount}
  1077. displayCount={displayCount}
  1078. onSelectStatsPeriod={this.onSelectStatsPeriod}
  1079. onMarkReviewed={this.onMarkReviewed}
  1080. onActionTaken={this.onActionTaken}
  1081. onDelete={this.onDelete}
  1082. statsPeriod={this.getGroupStatsPeriod()}
  1083. groupIds={groupIds}
  1084. allResultsVisible={this.allResultsVisible()}
  1085. displayReprocessingActions={displayReprocessingActions}
  1086. sort={this.getSort()}
  1087. onSortChange={this.onSortChange}
  1088. />
  1089. <PanelBody>
  1090. <ProcessingIssueList
  1091. organization={organization}
  1092. projectIds={projectIds}
  1093. showProject
  1094. />
  1095. <VisuallyCompleteWithData
  1096. hasData={this.state.groupIds.length > 0}
  1097. id="IssueList-Body"
  1098. >
  1099. <GroupListBody
  1100. memberList={this.state.memberList}
  1101. groupStatsPeriod={this.getGroupStatsPeriod()}
  1102. groupIds={groupIds}
  1103. displayReprocessingLayout={displayReprocessingActions}
  1104. query={query}
  1105. sort={this.getSort()}
  1106. selectedProjectIds={selection.projects}
  1107. loading={issuesLoading}
  1108. error={error}
  1109. refetchGroups={this.fetchData}
  1110. />
  1111. </VisuallyCompleteWithData>
  1112. </PanelBody>
  1113. </Panel>
  1114. <StyledPagination
  1115. caption={tct('Showing [displayCount] issues', {
  1116. displayCount,
  1117. })}
  1118. pageLinks={pageLinks}
  1119. onCursor={this.onCursorChange}
  1120. paginationAnalyticsEvent={this.paginationAnalyticsEvent}
  1121. />
  1122. </Layout.Main>
  1123. {/* Avoid rendering sidebar until first accessed */}
  1124. {isSidebarVisible && (
  1125. <Layout.Side>
  1126. <IssueListSidebar
  1127. loading={tagsLoading}
  1128. tags={tags}
  1129. query={query}
  1130. parsedQuery={parseSearch(query) || []}
  1131. onQueryChange={this.onIssueListSidebarSearch}
  1132. tagValueLoader={this.tagValueLoader}
  1133. />
  1134. </Layout.Side>
  1135. )}
  1136. </Layout.Body>
  1137. </StyledPageContent>
  1138. );
  1139. }
  1140. }
  1141. export default withApi(
  1142. withPageFilters(
  1143. withSavedSearches(withOrganization(withIssueTags(withProfiler(IssueListOverview))))
  1144. )
  1145. );
  1146. export {IssueListOverview};
  1147. const StyledPagination = styled(Pagination)`
  1148. margin-top: 0;
  1149. `;
  1150. const StyledQueryCount = styled(QueryCount)`
  1151. margin-left: 0;
  1152. `;
  1153. const StyledPageContent = styled(PageContent)`
  1154. padding: 0;
  1155. `;