overview.tsx 40 KB

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