overview.tsx 40 KB

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