overview.tsx 39 KB

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