overview.tsx 41 KB

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