overview.tsx 40 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337
  1. import {Component} from 'react';
  2. import {browserHistory, RouteComponentProps} from 'react-router';
  3. import styled from '@emotion/styled';
  4. import {withProfiler} from '@sentry/react';
  5. import * as Sentry from '@sentry/react';
  6. import {Location} from 'history';
  7. import Cookies from 'js-cookie';
  8. import isEqual from 'lodash/isEqual';
  9. import mapValues from 'lodash/mapValues';
  10. import omit from 'lodash/omit';
  11. import pickBy from 'lodash/pickBy';
  12. import * as qs from 'query-string';
  13. import {addMessage} from 'sentry/actionCreators/indicator';
  14. import {fetchOrgMembers, indexMembersByProject} from 'sentry/actionCreators/members';
  15. import {
  16. deleteSavedSearch,
  17. fetchSavedSearches,
  18. resetSavedSearches,
  19. } from 'sentry/actionCreators/savedSearches';
  20. import {fetchTagValues, loadOrganizationTags} from 'sentry/actionCreators/tags';
  21. import {Client} from 'sentry/api';
  22. import LoadingIndicator from 'sentry/components/loadingIndicator';
  23. import {extractSelectionParameters} from 'sentry/components/organizations/pageFilters/utils';
  24. import Pagination, {CursorHandler} from 'sentry/components/pagination';
  25. import {Panel, PanelBody} from 'sentry/components/panels';
  26. import QueryCount from 'sentry/components/queryCount';
  27. import ProcessingIssueList from 'sentry/components/stream/processingIssueList';
  28. import {DEFAULT_QUERY, DEFAULT_STATS_PERIOD} from 'sentry/constants';
  29. import {t, tct, tn} from 'sentry/locale';
  30. import GroupStore from 'sentry/stores/groupStore';
  31. import {PageContent} from 'sentry/styles/organization';
  32. import space from 'sentry/styles/space';
  33. import {
  34. BaseGroup,
  35. Group,
  36. IssueCategory,
  37. Organization,
  38. PageFilters,
  39. SavedSearch,
  40. TagCollection,
  41. } from 'sentry/types';
  42. import {defined} from 'sentry/utils';
  43. import trackAdvancedAnalyticsEvent from 'sentry/utils/analytics/trackAdvancedAnalyticsEvent';
  44. import CursorPoller from 'sentry/utils/cursorPoller';
  45. import {getUtcDateString} from 'sentry/utils/dates';
  46. import getCurrentSentryReactTransaction from 'sentry/utils/getCurrentSentryReactTransaction';
  47. import parseApiError from 'sentry/utils/parseApiError';
  48. import parseLinkHeader from 'sentry/utils/parseLinkHeader';
  49. import {VisuallyCompleteWithData} from 'sentry/utils/performanceForSentry';
  50. import {decodeScalar} from 'sentry/utils/queryString';
  51. import withRouteAnalytics, {
  52. WithRouteAnalyticsProps,
  53. } from 'sentry/utils/routeAnalytics/withRouteAnalytics';
  54. import withApi from 'sentry/utils/withApi';
  55. import withIssueTags from 'sentry/utils/withIssueTags';
  56. import withOrganization from 'sentry/utils/withOrganization';
  57. import withPageFilters from 'sentry/utils/withPageFilters';
  58. import withSavedSearches from 'sentry/utils/withSavedSearches';
  59. import SavedIssueSearches from 'sentry/views/issueList/savedIssueSearches';
  60. import IssueListActions from './actions';
  61. import IssueListFilters from './filters';
  62. import GroupListBody from './groupListBody';
  63. import IssueListHeader from './header';
  64. import {
  65. getTabs,
  66. getTabsWithCounts,
  67. isForReviewQuery,
  68. IssueSortOptions,
  69. Query,
  70. QueryCounts,
  71. TAB_MAX_COUNT,
  72. } from './utils';
  73. const MAX_ITEMS = 25;
  74. const DEFAULT_SORT = IssueSortOptions.DATE;
  75. // the default period for the graph in each issue row
  76. const DEFAULT_GRAPH_STATS_PERIOD = '24h';
  77. // the allowed period choices for graph in each issue row
  78. const DYNAMIC_COUNTS_STATS_PERIODS = new Set(['14d', '24h', 'auto']);
  79. const MAX_ISSUES_COUNT = 100;
  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. WithRouteAnalyticsProps;
  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. isSavedSearchesOpen: 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. 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. isSavedSearchesOpen: false,
  166. issuesLoading: true,
  167. memberList: {},
  168. };
  169. }
  170. componentDidMount() {
  171. this._poller = new CursorPoller({
  172. linkPreviousHref: parseLinkHeader(this.state.pageLinks)?.previous?.href,
  173. success: this.onRealtimePoll,
  174. });
  175. // Start by getting searches first so if the user is on a saved search
  176. // or they have a pinned search we load the correct data the first time.
  177. this.fetchSavedSearches();
  178. this.fetchTags();
  179. this.fetchMemberList();
  180. // let custom analytics take control
  181. this.props.setDisableRouteAnalytics?.();
  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. 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. loadOrganizationTags(api, organization.slug, selection);
  336. }
  337. fetchSavedSearches() {
  338. const {organization, api} = this.props;
  339. fetchSavedSearches(api, organization.slug);
  340. }
  341. fetchStats = (groups: string[]) => {
  342. // If we have no groups to fetch, just skip stats
  343. if (!groups.length) {
  344. return;
  345. }
  346. const requestParams: StatEndpointParams = {
  347. ...this.getEndpointParams(),
  348. groups,
  349. };
  350. // If no stats period values are set, use default
  351. if (!requestParams.statsPeriod && !requestParams.start) {
  352. requestParams.statsPeriod = DEFAULT_STATS_PERIOD;
  353. }
  354. this._lastStatsRequest = this.props.api.request(this.groupStatsEndpoint, {
  355. method: 'GET',
  356. data: qs.stringify(requestParams),
  357. success: data => {
  358. if (!data) {
  359. return;
  360. }
  361. GroupStore.onPopulateStats(groups, data);
  362. },
  363. error: err => {
  364. this.setState({
  365. error: parseApiError(err),
  366. });
  367. },
  368. complete: () => {
  369. this._lastStatsRequest = null;
  370. // End navigation transaction to prevent additional page requests from impacting page metrics.
  371. // Other transactions include stacktrace preview request
  372. const currentTransaction = Sentry.getCurrentHub().getScope()?.getTransaction();
  373. if (currentTransaction?.op === 'navigation') {
  374. currentTransaction.finish();
  375. }
  376. },
  377. });
  378. };
  379. fetchCounts = (currentQueryCount: number, fetchAllCounts: boolean) => {
  380. const {organization} = this.props;
  381. const {queryCounts: _queryCounts} = this.state;
  382. let queryCounts: QueryCounts = {..._queryCounts};
  383. const endpointParams = this.getEndpointParams();
  384. const tabQueriesWithCounts = getTabsWithCounts(organization);
  385. const currentTabQuery = tabQueriesWithCounts.includes(endpointParams.query as Query)
  386. ? endpointParams.query
  387. : null;
  388. // Update the count based on the exact number of issues, these shown as is
  389. if (currentTabQuery) {
  390. queryCounts[currentTabQuery] = {
  391. count: currentQueryCount,
  392. hasMore: false,
  393. };
  394. }
  395. this.setState({queryCounts});
  396. // If all tabs' counts are fetched, skip and only set
  397. if (
  398. fetchAllCounts ||
  399. !tabQueriesWithCounts.every(tabQuery => queryCounts[tabQuery] !== undefined)
  400. ) {
  401. const requestParams: CountsEndpointParams = {
  402. ...omit(endpointParams, 'query'),
  403. // fetch the counts for the tabs whose counts haven't been fetched yet
  404. query: tabQueriesWithCounts.filter(_query => _query !== currentTabQuery),
  405. };
  406. // If no stats period values are set, use default
  407. if (!requestParams.statsPeriod && !requestParams.start) {
  408. requestParams.statsPeriod = DEFAULT_STATS_PERIOD;
  409. }
  410. this._lastFetchCountsRequest = this.props.api.request(this.groupCountsEndpoint, {
  411. method: 'GET',
  412. data: qs.stringify(requestParams),
  413. success: data => {
  414. if (!data) {
  415. return;
  416. }
  417. // Counts coming from the counts endpoint is limited to 100, for >= 100 we display 99+
  418. queryCounts = {
  419. ...queryCounts,
  420. ...mapValues(data, (count: number) => ({
  421. count,
  422. hasMore: count > TAB_MAX_COUNT,
  423. })),
  424. };
  425. },
  426. error: () => {
  427. this.setState({queryCounts: {}});
  428. },
  429. complete: () => {
  430. this._lastFetchCountsRequest = null;
  431. this.setState({queryCounts});
  432. },
  433. });
  434. }
  435. };
  436. fetchData = (fetchAllCounts = false) => {
  437. const {organization} = this.props;
  438. const query = this.getQuery();
  439. const hasIssueListRemovalAction = organization.features.includes(
  440. 'issue-list-removal-action'
  441. );
  442. // TODO(Kelly): update once issue-list-removal-action feature is stable
  443. if (hasIssueListRemovalAction && !this.state.realtimeActive) {
  444. if (!this.state.actionTaken && !this.state.undo) {
  445. GroupStore.loadInitialData([]);
  446. this.setState({
  447. issuesLoading: true,
  448. queryCount: 0,
  449. itemsRemoved: 0,
  450. error: null,
  451. });
  452. }
  453. } else {
  454. if (!this.state.reviewedIds.length || !isForReviewQuery(query)) {
  455. GroupStore.loadInitialData([]);
  456. this.setState({
  457. issuesLoading: true,
  458. queryCount: 0,
  459. itemsRemoved: 0,
  460. reviewedIds: [],
  461. error: null,
  462. });
  463. }
  464. }
  465. const transaction = getCurrentSentryReactTransaction();
  466. transaction?.setTag('query.sort', this.getSort());
  467. this.setState({
  468. queryCount: 0,
  469. itemsRemoved: 0,
  470. error: null,
  471. });
  472. const requestParams: any = {
  473. ...this.getEndpointParams(),
  474. limit: MAX_ITEMS,
  475. shortIdLookup: 1,
  476. };
  477. const currentQuery = this.props.location.query || {};
  478. if ('cursor' in currentQuery) {
  479. requestParams.cursor = currentQuery.cursor;
  480. }
  481. // If no stats period values are set, use default
  482. if (!requestParams.statsPeriod && !requestParams.start) {
  483. requestParams.statsPeriod = DEFAULT_STATS_PERIOD;
  484. }
  485. requestParams.expand = ['owners', 'inbox'];
  486. requestParams.collapse = 'stats';
  487. if (this._lastRequest) {
  488. this._lastRequest.cancel();
  489. }
  490. if (this._lastStatsRequest) {
  491. this._lastStatsRequest.cancel();
  492. }
  493. if (this._lastFetchCountsRequest) {
  494. this._lastFetchCountsRequest.cancel();
  495. }
  496. this._poller.disable();
  497. this._lastRequest = this.props.api.request(this.groupListEndpoint, {
  498. method: 'GET',
  499. data: qs.stringify(requestParams),
  500. success: (data, _, resp) => {
  501. if (!resp) {
  502. return;
  503. }
  504. const {orgId} = this.props.params;
  505. // If this is a direct hit, we redirect to the intended result directly.
  506. if (resp.getResponseHeader('X-Sentry-Direct-Hit') === '1') {
  507. let redirect: string;
  508. if (data[0] && data[0].matchingEventId) {
  509. const {id, matchingEventId} = data[0];
  510. redirect = `/organizations/${orgId}/issues/${id}/events/${matchingEventId}/`;
  511. } else {
  512. const {id} = data[0];
  513. redirect = `/organizations/${orgId}/issues/${id}/`;
  514. }
  515. browserHistory.replace({
  516. pathname: redirect,
  517. query: {
  518. referrer: 'issue-list',
  519. ...extractSelectionParameters(this.props.location.query),
  520. },
  521. });
  522. return;
  523. }
  524. if (this.state.undo) {
  525. GroupStore.loadInitialData(data);
  526. }
  527. GroupStore.add(data);
  528. // TODO(Kelly): update once issue-list-removal-action feature is stable
  529. if (!hasIssueListRemovalAction) {
  530. if (isForReviewQuery(query)) {
  531. GroupStore.remove(this.state.reviewedIds);
  532. }
  533. }
  534. const numPerfIssues = data.filter(
  535. (group: BaseGroup) => group.issueCategory === IssueCategory.PERFORMANCE
  536. ).length;
  537. const page = this.props.location.query.page;
  538. const endpointParams = this.getEndpointParams();
  539. const tabQueriesWithCounts = getTabsWithCounts(organization);
  540. const currentTabQuery = tabQueriesWithCounts.includes(
  541. endpointParams.query as Query
  542. )
  543. ? endpointParams.query
  544. : null;
  545. const tab = getTabs(organization).find(
  546. ([tabQuery]) => currentTabQuery === tabQuery
  547. )?.[1];
  548. trackAdvancedAnalyticsEvent('issues_tab.viewed', {
  549. organization,
  550. tab: tab?.analyticsName,
  551. page: page ? parseInt(page, 10) : 0,
  552. query,
  553. num_perf_issues: numPerfIssues,
  554. num_issues: data.length,
  555. });
  556. this.fetchStats(data.map((group: BaseGroup) => group.id));
  557. const hits = resp.getResponseHeader('X-Hits');
  558. const queryCount =
  559. typeof hits !== 'undefined' && hits ? parseInt(hits, 10) || 0 : 0;
  560. const maxHits = resp.getResponseHeader('X-Max-Hits');
  561. const queryMaxCount =
  562. typeof maxHits !== 'undefined' && maxHits ? parseInt(maxHits, 10) || 0 : 0;
  563. const pageLinks = resp.getResponseHeader('Link');
  564. // TODO(Kelly): update once issue-list-removal-action feature is stable
  565. if (hasIssueListRemovalAction && !this.state.realtimeActive) {
  566. this.fetchCounts(queryCount, fetchAllCounts);
  567. } else {
  568. if (!this.state.forReview) {
  569. this.fetchCounts(queryCount, fetchAllCounts);
  570. }
  571. }
  572. this.setState({
  573. error: null,
  574. issuesLoading: false,
  575. queryCount,
  576. queryMaxCount,
  577. pageLinks: pageLinks !== null ? pageLinks : '',
  578. });
  579. if (data.length === 0) {
  580. trackAdvancedAnalyticsEvent('issue_search.empty', {
  581. organization: this.props.organization,
  582. search_type: 'issues',
  583. search_source: 'main_search',
  584. query,
  585. });
  586. }
  587. },
  588. error: err => {
  589. trackAdvancedAnalyticsEvent('issue_search.failed', {
  590. organization: this.props.organization,
  591. search_type: 'issues',
  592. search_source: 'main_search',
  593. error: parseApiError(err),
  594. });
  595. this.setState({
  596. error: parseApiError(err),
  597. issuesLoading: false,
  598. });
  599. },
  600. complete: () => {
  601. this._lastRequest = null;
  602. this.resumePolling();
  603. // TODO(Kelly): update once issue-list-removal-action feature is stable
  604. if (hasIssueListRemovalAction && !this.state.realtimeActive) {
  605. this.setState({actionTaken: false, undo: false});
  606. } else {
  607. this.setState({forReview: false});
  608. }
  609. },
  610. });
  611. };
  612. resumePolling = () => {
  613. if (!this.state.pageLinks) {
  614. return;
  615. }
  616. // Only resume polling if we're on the first page of results
  617. const links = parseLinkHeader(this.state.pageLinks);
  618. if (links && !links.previous.results && this.state.realtimeActive) {
  619. this._poller.setEndpoint(links?.previous?.href);
  620. this._poller.enable();
  621. }
  622. };
  623. get groupListEndpoint(): string {
  624. return `/organizations/${this.props.params.orgId}/issues/`;
  625. }
  626. get groupCountsEndpoint(): string {
  627. return `/organizations/${this.props.params.orgId}/issues-count/`;
  628. }
  629. get groupStatsEndpoint(): string {
  630. return `/organizations/${this.props.params.orgId}/issues-stats/`;
  631. }
  632. onRealtimeChange = (realtime: boolean) => {
  633. Cookies.set('realtimeActive', realtime.toString());
  634. this.setState({realtimeActive: realtime});
  635. trackAdvancedAnalyticsEvent('issues_stream.realtime_clicked', {
  636. organization: this.props.organization,
  637. enabled: realtime,
  638. });
  639. };
  640. onSelectStatsPeriod = (period: string) => {
  641. const {location} = this.props;
  642. if (period !== this.getGroupStatsPeriod()) {
  643. const cursor = location.query.cursor;
  644. const queryPageInt = parseInt(location.query.page, 10);
  645. const page = isNaN(queryPageInt) || !location.query.cursor ? 0 : queryPageInt;
  646. this.transitionTo({cursor, page, groupStatsPeriod: period});
  647. }
  648. };
  649. onRealtimePoll = (data: any, _links: any) => {
  650. // Note: We do not update state with cursors from polling,
  651. // `CursorPoller` updates itself with new cursors
  652. GroupStore.addToFront(data);
  653. };
  654. listener = GroupStore.listen(() => this.onGroupChange(), undefined);
  655. onGroupChange() {
  656. const {organization} = this.props;
  657. const {actionTakenGroupData} = this.state;
  658. const query = this.getQuery();
  659. const hasIssueListRemovalAction = organization.features.includes(
  660. 'issue-list-removal-action'
  661. );
  662. // TODO(Kelly): update once issue-list-removal-action feature is stable
  663. if (
  664. hasIssueListRemovalAction &&
  665. !this.state.realtimeActive &&
  666. actionTakenGroupData.length > 0
  667. ) {
  668. const filteredItems = GroupStore.getAllItems().filter(item => {
  669. return actionTakenGroupData.findIndex(data => data.id === item.id) !== -1;
  670. });
  671. const resolvedIds = filteredItems
  672. .filter(item => item.status === 'resolved')
  673. .map(id => id.id);
  674. const ignoredIds = filteredItems
  675. .filter(item => item.status === 'ignored')
  676. .map(i => i.id);
  677. // need to include resolve and ignored statuses because marking as resolved/ignored also
  678. // counts as reviewed
  679. const reviewedIds = filteredItems
  680. .filter(
  681. item => !item.inbox && item.status !== 'resolved' && item.status !== 'ignored'
  682. )
  683. .map(i => i.id);
  684. // Remove Ignored and Resolved group ids from the issue stream if on the All Unresolved,
  685. // For Review, or Ignored tab. Still include on the saved/custom search tab.
  686. if (
  687. resolvedIds.length > 0 &&
  688. (query.includes('is:unresolved') ||
  689. query.includes('is:ignored') ||
  690. isForReviewQuery(query))
  691. ) {
  692. this.onIssueAction(resolvedIds, 'Resolved');
  693. }
  694. if (
  695. ignoredIds.length > 0 &&
  696. (query.includes('is:unresolved') || isForReviewQuery(query))
  697. ) {
  698. this.onIssueAction(ignoredIds, 'Ignored');
  699. }
  700. // Remove issues that are marked as Reviewed from the For Review tab, but still include the
  701. // issues if on the All Unresolved tab or saved/custom searches.
  702. if (
  703. reviewedIds.length > 0 &&
  704. (isForReviewQuery(query) || query.includes('is:ignored'))
  705. ) {
  706. this.onIssueAction(reviewedIds, 'Reviewed');
  707. }
  708. }
  709. const groupIds = GroupStore.getAllItems()
  710. .map(item => item.id)
  711. .slice(0, MAX_ISSUES_COUNT);
  712. if (!isEqual(groupIds, this.state.groupIds)) {
  713. this.setState({groupIds});
  714. }
  715. }
  716. onIssueListSidebarSearch = (query: string) => {
  717. trackAdvancedAnalyticsEvent('search.searched', {
  718. organization: this.props.organization,
  719. query,
  720. search_type: 'issues',
  721. search_source: 'search_builder',
  722. });
  723. this.onSearch(query);
  724. };
  725. onSearch = (query: string) => {
  726. if (query === this.state.query) {
  727. // if query is the same, just re-fetch data
  728. this.fetchData();
  729. } else {
  730. // Clear the saved search as the user wants something else.
  731. this.transitionTo({query}, null);
  732. }
  733. };
  734. onSortChange = (sort: string) => {
  735. trackAdvancedAnalyticsEvent('issues_stream.sort_changed', {
  736. organization: this.props.organization,
  737. sort,
  738. });
  739. this.transitionTo({sort});
  740. };
  741. onCursorChange: CursorHandler = (nextCursor, _path, _query, delta) => {
  742. const queryPageInt = parseInt(this.props.location.query.page, 10);
  743. let nextPage: number | undefined = isNaN(queryPageInt) ? delta : queryPageInt + delta;
  744. let cursor: undefined | string = nextCursor;
  745. // unset cursor and page when we navigate back to the first page
  746. // also reset cursor if somehow the previous button is enabled on
  747. // first page and user attempts to go backwards
  748. if (nextPage <= 0) {
  749. cursor = undefined;
  750. nextPage = undefined;
  751. }
  752. this.transitionTo({cursor, page: nextPage});
  753. };
  754. paginationAnalyticsEvent = (direction: string) => {
  755. trackAdvancedAnalyticsEvent('issues_stream.paginate', {
  756. organization: this.props.organization,
  757. direction,
  758. });
  759. };
  760. /**
  761. * Returns true if all results in the current query are visible/on this page
  762. */
  763. allResultsVisible(): boolean {
  764. if (!this.state.pageLinks) {
  765. return false;
  766. }
  767. const links = parseLinkHeader(this.state.pageLinks);
  768. return links && !links.previous.results && !links.next.results;
  769. }
  770. transitionTo = (
  771. newParams: Partial<EndpointParams> = {},
  772. savedSearch: (SavedSearch & {projectId?: number}) | null = this.props.savedSearch
  773. ) => {
  774. const query = {
  775. referrer: 'issue-list',
  776. ...this.getEndpointParams(),
  777. ...newParams,
  778. };
  779. const {organization} = this.props;
  780. let path: string;
  781. if (savedSearch && savedSearch.id) {
  782. path = `/organizations/${organization.slug}/issues/searches/${savedSearch.id}/`;
  783. // Remove the query as saved searches bring their own query string.
  784. delete query.query;
  785. // If we aren't going to another page in the same search
  786. // drop the query and replace the current project, with the saved search search project
  787. // if available.
  788. if (!query.cursor && savedSearch.projectId) {
  789. query.project = [savedSearch.projectId];
  790. }
  791. if (!query.cursor && !newParams.sort && savedSearch.sort) {
  792. query.sort = savedSearch.sort;
  793. }
  794. } else {
  795. path = `/organizations/${organization.slug}/issues/`;
  796. }
  797. // Remove inbox tab specific sort
  798. if (query.sort === IssueSortOptions.INBOX && query.query !== Query.FOR_REVIEW) {
  799. delete query.sort;
  800. }
  801. if (
  802. path !== this.props.location.pathname ||
  803. !isEqual(query, this.props.location.query)
  804. ) {
  805. browserHistory.push({
  806. pathname: path,
  807. query,
  808. });
  809. this.setState({issuesLoading: true});
  810. }
  811. };
  812. displayReprocessingTab() {
  813. const {organization} = this.props;
  814. const {queryCounts} = this.state;
  815. return (
  816. organization.features.includes('reprocessing-v2') &&
  817. !!queryCounts?.[Query.REPROCESSING]?.count
  818. );
  819. }
  820. displayReprocessingLayout(showReprocessingTab: boolean, query: string) {
  821. return showReprocessingTab && query === Query.REPROCESSING;
  822. }
  823. renderLoading(): React.ReactNode {
  824. return (
  825. <PageContent>
  826. <LoadingIndicator />
  827. </PageContent>
  828. );
  829. }
  830. onSavedSearchSelect = (savedSearch: SavedSearch) => {
  831. trackAdvancedAnalyticsEvent('organization_saved_search.selected', {
  832. organization: this.props.organization,
  833. search_type: 'issues',
  834. id: savedSearch.id ? parseInt(savedSearch.id, 10) : -1,
  835. is_global: savedSearch.isGlobal,
  836. query: savedSearch.query,
  837. visibility: savedSearch.visibility,
  838. });
  839. this.setState({issuesLoading: true}, () => this.transitionTo(undefined, savedSearch));
  840. };
  841. onSavedSearchDelete = (search: SavedSearch) => {
  842. const {orgId} = this.props.params;
  843. deleteSavedSearch(this.props.api, orgId, search).then(() => {
  844. this.setState(
  845. {
  846. issuesLoading: true,
  847. },
  848. () => this.transitionTo({}, null)
  849. );
  850. });
  851. };
  852. onDelete = () => {
  853. this.setState({actionTaken: true});
  854. this.fetchData(true);
  855. };
  856. onUndo = () => {
  857. const {organization, selection} = this.props;
  858. const {actionTakenGroupData} = this.state;
  859. const query = this.getQuery();
  860. const groupIds = actionTakenGroupData.map(data => data.id);
  861. const projectIds = selection?.projects?.map(p => p.toString());
  862. const endpoint = `/organizations/${organization.slug}/issues/`;
  863. if (this._lastRequest) {
  864. this._lastRequest.cancel();
  865. }
  866. if (this._lastStatsRequest) {
  867. this._lastStatsRequest.cancel();
  868. }
  869. if (this._lastFetchCountsRequest) {
  870. this._lastFetchCountsRequest.cancel();
  871. }
  872. this.props.api.request(endpoint, {
  873. method: 'PUT',
  874. data: {
  875. status: 'unresolved',
  876. },
  877. query: {
  878. project: projectIds,
  879. id: groupIds,
  880. },
  881. success: response => {
  882. if (!response) {
  883. return;
  884. }
  885. // If on the Ignore or For Review tab, adding back to the GroupStore will make the issue show up
  886. // on this page for a second and then be removed (will show up on All Unresolved). This is to
  887. // stop this from happening and avoid confusion.
  888. if (!query.includes('is:ignored') && !isForReviewQuery(query)) {
  889. GroupStore.add(actionTakenGroupData);
  890. }
  891. this.setState({undo: true});
  892. },
  893. error: err => {
  894. this.setState({
  895. error: parseApiError(err),
  896. issuesLoading: false,
  897. });
  898. },
  899. complete: () => {
  900. this.setState({actionTakenGroupData: []});
  901. this.fetchData();
  902. },
  903. });
  904. };
  905. onMarkReviewed = (itemIds: string[]) => {
  906. const {organization} = this.props;
  907. const query = this.getQuery();
  908. const hasIssueListRemovalAction = organization.features.includes(
  909. 'issue-list-removal-action'
  910. );
  911. if (!isForReviewQuery(query)) {
  912. if (itemIds.length > 1) {
  913. addMessage(
  914. tn('Reviewed %s Issue', 'Reviewed %s Issues', itemIds.length),
  915. 'success',
  916. {duration: 4000}
  917. );
  918. } else {
  919. const shortId = itemIds.map(item => GroupStore.get(item)?.shortId).toString();
  920. addMessage(t('Reviewed %s', shortId), 'success', {duration: 4000});
  921. }
  922. return;
  923. }
  924. const {queryCounts, itemsRemoved} = this.state;
  925. const currentQueryCount = queryCounts[query as Query];
  926. if (itemIds.length && currentQueryCount) {
  927. const inInboxCount = itemIds.filter(id => GroupStore.get(id)?.inbox).length;
  928. currentQueryCount.count -= inInboxCount;
  929. // TODO(Kelly): update once issue-list-removal-action feature is stable
  930. if (!hasIssueListRemovalAction) {
  931. this.setState({
  932. reviewedIds: itemIds,
  933. forReview: true,
  934. });
  935. }
  936. this.setState({
  937. queryCounts: {
  938. ...queryCounts,
  939. [query as Query]: currentQueryCount,
  940. },
  941. itemsRemoved: itemsRemoved + inInboxCount,
  942. });
  943. }
  944. };
  945. onActionTaken = (itemIds: string[]) => {
  946. const actionTakenGroupData = itemIds.map(id => GroupStore.get(id) as Group);
  947. this.setState({
  948. actionTakenGroupData,
  949. });
  950. };
  951. onIssueAction = (
  952. itemIds: string[],
  953. actionType: 'Reviewed' | 'Resolved' | 'Ignored'
  954. ) => {
  955. if (itemIds.length > 1) {
  956. addMessage(`${actionType} ${itemIds.length} ${t('Issues')}`, 'success', {
  957. duration: 4000,
  958. ...(actionType !== 'Reviewed' && {undo: this.onUndo}),
  959. });
  960. } else {
  961. const shortId = itemIds.map(item => GroupStore.get(item)?.shortId).toString();
  962. addMessage(`${actionType} ${shortId}`, 'success', {
  963. duration: 4000,
  964. ...(actionType !== 'Reviewed' && {undo: this.onUndo}),
  965. });
  966. }
  967. GroupStore.remove(itemIds);
  968. this.setState({actionTaken: true});
  969. this.fetchData(true);
  970. };
  971. onToggleSavedSearches = (isOpen: boolean) => {
  972. this.setState({
  973. isSavedSearchesOpen: isOpen,
  974. });
  975. };
  976. tagValueLoader = (key: string, search: string) => {
  977. const {orgId} = this.props.params;
  978. const projectIds = this.getSelectedProjectIds();
  979. const endpointParams = this.getEndpointParams();
  980. return fetchTagValues({
  981. api: this.props.api,
  982. orgSlug: orgId,
  983. tagKey: key,
  984. search,
  985. projectIds,
  986. endpointParams: endpointParams as any,
  987. });
  988. };
  989. render() {
  990. if (this.props.savedSearchLoading) {
  991. return this.renderLoading();
  992. }
  993. const {
  994. isSavedSearchesOpen,
  995. pageLinks,
  996. queryCount,
  997. queryCounts,
  998. realtimeActive,
  999. groupIds,
  1000. queryMaxCount,
  1001. itemsRemoved,
  1002. issuesLoading,
  1003. error,
  1004. } = this.state;
  1005. const {
  1006. organization,
  1007. savedSearch,
  1008. savedSearches,
  1009. savedSearchLoading,
  1010. selection,
  1011. location,
  1012. router,
  1013. } = this.props;
  1014. const links = parseLinkHeader(pageLinks);
  1015. const query = this.getQuery();
  1016. const queryPageInt = parseInt(location.query.page, 10);
  1017. // Cursor must be present for the page number to be used
  1018. const page = isNaN(queryPageInt) || !location.query.cursor ? 0 : queryPageInt;
  1019. const pageBasedCount = page * MAX_ITEMS + groupIds.length;
  1020. let pageCount = pageBasedCount > queryCount ? queryCount : pageBasedCount;
  1021. if (!links?.next?.results || this.allResultsVisible()) {
  1022. // On last available page
  1023. pageCount = queryCount;
  1024. } else if (!links?.previous?.results) {
  1025. // On first available page
  1026. pageCount = groupIds.length;
  1027. }
  1028. // Subtract # items that have been marked reviewed
  1029. pageCount = Math.max(pageCount - itemsRemoved, 0);
  1030. const modifiedQueryCount = Math.max(queryCount - itemsRemoved, 0);
  1031. const displayCount = tct('[count] of [total]', {
  1032. count: pageCount,
  1033. total: (
  1034. <StyledQueryCount
  1035. hideParens
  1036. hideIfEmpty={false}
  1037. count={modifiedQueryCount}
  1038. max={queryMaxCount || 100}
  1039. />
  1040. ),
  1041. });
  1042. const projectIds = selection?.projects?.map(p => p.toString());
  1043. const showReprocessingTab = this.displayReprocessingTab();
  1044. const displayReprocessingActions = this.displayReprocessingLayout(
  1045. showReprocessingTab,
  1046. query
  1047. );
  1048. return (
  1049. <StyledPageContent>
  1050. <IssueListHeader
  1051. isSavedSearchesOpen={isSavedSearchesOpen}
  1052. onToggleSavedSearches={this.onToggleSavedSearches}
  1053. organization={organization}
  1054. query={query}
  1055. sort={this.getSort()}
  1056. queryCount={queryCount}
  1057. queryCounts={queryCounts}
  1058. realtimeActive={realtimeActive}
  1059. onRealtimeChange={this.onRealtimeChange}
  1060. router={router}
  1061. savedSearchList={savedSearches}
  1062. onSavedSearchSelect={this.onSavedSearchSelect}
  1063. onSavedSearchDelete={this.onSavedSearchDelete}
  1064. displayReprocessingTab={showReprocessingTab}
  1065. savedSearch={savedSearch}
  1066. selectedProjectIds={selection.projects}
  1067. />
  1068. <StyledBody>
  1069. <StyledMain>
  1070. <IssueListFilters
  1071. organization={organization}
  1072. query={query}
  1073. savedSearch={savedSearch}
  1074. sort={this.getSort()}
  1075. onSearch={this.onSearch}
  1076. />
  1077. <Panel>
  1078. <IssueListActions
  1079. selection={selection}
  1080. query={query}
  1081. queryCount={modifiedQueryCount}
  1082. displayCount={displayCount}
  1083. onSelectStatsPeriod={this.onSelectStatsPeriod}
  1084. onMarkReviewed={this.onMarkReviewed}
  1085. onActionTaken={this.onActionTaken}
  1086. onDelete={this.onDelete}
  1087. statsPeriod={this.getGroupStatsPeriod()}
  1088. groupIds={groupIds}
  1089. allResultsVisible={this.allResultsVisible()}
  1090. displayReprocessingActions={displayReprocessingActions}
  1091. sort={this.getSort()}
  1092. onSortChange={this.onSortChange}
  1093. />
  1094. <PanelBody>
  1095. <ProcessingIssueList
  1096. organization={organization}
  1097. projectIds={projectIds}
  1098. showProject
  1099. />
  1100. <VisuallyCompleteWithData
  1101. hasData={this.state.groupIds.length > 0}
  1102. id="IssueList-Body"
  1103. >
  1104. <GroupListBody
  1105. memberList={this.state.memberList}
  1106. groupStatsPeriod={this.getGroupStatsPeriod()}
  1107. groupIds={groupIds}
  1108. displayReprocessingLayout={displayReprocessingActions}
  1109. query={query}
  1110. sort={this.getSort()}
  1111. selectedProjectIds={selection.projects}
  1112. loading={issuesLoading}
  1113. error={error}
  1114. refetchGroups={this.fetchData}
  1115. />
  1116. </VisuallyCompleteWithData>
  1117. </PanelBody>
  1118. </Panel>
  1119. <StyledPagination
  1120. caption={tct('Showing [displayCount] issues', {
  1121. displayCount,
  1122. })}
  1123. pageLinks={pageLinks}
  1124. onCursor={this.onCursorChange}
  1125. paginationAnalyticsEvent={this.paginationAnalyticsEvent}
  1126. />
  1127. </StyledMain>
  1128. <SavedIssueSearches
  1129. {...{
  1130. savedSearches,
  1131. savedSearch,
  1132. savedSearchLoading,
  1133. organization,
  1134. query,
  1135. }}
  1136. isOpen={isSavedSearchesOpen}
  1137. onSavedSearchDelete={this.onSavedSearchDelete}
  1138. onSavedSearchSelect={this.onSavedSearchSelect}
  1139. sort={this.getSort()}
  1140. />
  1141. </StyledBody>
  1142. </StyledPageContent>
  1143. );
  1144. }
  1145. }
  1146. export default withRouteAnalytics(
  1147. withApi(
  1148. withPageFilters(
  1149. withSavedSearches(withOrganization(withIssueTags(withProfiler(IssueListOverview))))
  1150. )
  1151. )
  1152. );
  1153. export {IssueListOverview};
  1154. const StyledBody = styled('div')`
  1155. background-color: ${p => p.theme.background};
  1156. display: flex;
  1157. flex-direction: column-reverse;
  1158. @media (min-width: ${p => p.theme.breakpoints.small}) {
  1159. flex: 1;
  1160. display: grid;
  1161. grid-template-rows: 1fr;
  1162. grid-template-columns: 1fr auto;
  1163. gap: 0;
  1164. padding: 0;
  1165. }
  1166. `;
  1167. const StyledMain = styled('section')`
  1168. padding: ${space(2)};
  1169. overflow: hidden;
  1170. @media (min-width: ${p => p.theme.breakpoints.medium}) {
  1171. padding: ${space(3)} ${space(4)};
  1172. }
  1173. `;
  1174. const StyledPagination = styled(Pagination)`
  1175. margin-top: 0;
  1176. `;
  1177. const StyledQueryCount = styled(QueryCount)`
  1178. margin-left: 0;
  1179. `;
  1180. const StyledPageContent = styled(PageContent)`
  1181. padding: 0;
  1182. `;