overview.tsx 40 KB

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