overview.tsx 40 KB

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