overview.tsx 40 KB

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