overview.tsx 40 KB

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