overview.tsx 40 KB

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