overview.tsx 40 KB

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