overview.tsx 40 KB

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