overview.tsx 40 KB

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