overview.tsx 40 KB

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