overview.tsx 40 KB

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