overview.tsx 41 KB

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