overview.tsx 39 KB

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