overview.tsx 41 KB

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