overview.tsx 40 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326
  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. this.fetchSavedSearches();
  178. this.fetchTags();
  179. this.fetchMemberList();
  180. // let custom analytics take control
  181. this.props.setDisableRouteAnalytics?.();
  182. }
  183. componentDidUpdate(prevProps: Props, prevState: State) {
  184. if (prevState.realtimeActive !== this.state.realtimeActive) {
  185. // User toggled realtime button
  186. if (this.state.realtimeActive) {
  187. this.resumePolling();
  188. } else {
  189. this._poller.disable();
  190. }
  191. }
  192. // If the project selection has changed reload the member list and tag keys
  193. // allowing autocomplete and tag sidebar to be more accurate.
  194. if (!isEqual(prevProps.selection.projects, this.props.selection.projects)) {
  195. this.fetchMemberList();
  196. this.fetchTags();
  197. }
  198. // TODO(Kelly): remove once issue-list-removal-action feature is stable
  199. if (!this.props.organization.features.includes('issue-list-removal-action')) {
  200. if (prevState.forReview !== this.state.forReview) {
  201. this.fetchData();
  202. }
  203. }
  204. // Wait for saved searches to load before we attempt to fetch stream data
  205. if (this.props.savedSearchLoading) {
  206. return;
  207. }
  208. if (prevProps.savedSearchLoading) {
  209. this.fetchData();
  210. return;
  211. }
  212. const prevQuery = prevProps.location.query;
  213. const newQuery = this.props.location.query;
  214. const selectionChanged = !isEqual(prevProps.selection, this.props.selection);
  215. // If any important url parameter changed or saved search changed
  216. // reload data.
  217. if (
  218. selectionChanged ||
  219. prevQuery.cursor !== newQuery.cursor ||
  220. prevQuery.sort !== newQuery.sort ||
  221. prevQuery.query !== newQuery.query ||
  222. prevQuery.statsPeriod !== newQuery.statsPeriod ||
  223. prevQuery.groupStatsPeriod !== newQuery.groupStatsPeriod ||
  224. prevProps.savedSearch !== this.props.savedSearch
  225. ) {
  226. this.fetchData(selectionChanged);
  227. } else if (
  228. !this._lastRequest &&
  229. prevState.issuesLoading === false &&
  230. this.state.issuesLoading
  231. ) {
  232. // Reload if we issues are loading or their loading state changed.
  233. // This can happen when transitionTo is called
  234. this.fetchData();
  235. }
  236. }
  237. componentWillUnmount() {
  238. this._poller.disable();
  239. GroupStore.reset();
  240. this.props.api.clear();
  241. this.listener?.();
  242. // Reset store when unmounting because we always fetch on mount
  243. // This means if you navigate away from stream and then back to stream,
  244. // this component will go from:
  245. // "ready" ->
  246. // "loading" (because fetching saved searches) ->
  247. // "ready"
  248. //
  249. // We don't render anything until saved searches is ready, so this can
  250. // cause weird side effects (e.g. ProcessingIssueList mounting and making
  251. // a request, but immediately unmounting when fetching saved searches)
  252. resetSavedSearches();
  253. }
  254. private _poller: any;
  255. private _lastRequest: any;
  256. private _lastStatsRequest: any;
  257. private _lastFetchCountsRequest: any;
  258. getQuery(): string {
  259. const {savedSearch, location} = this.props;
  260. if (savedSearch) {
  261. return savedSearch.query;
  262. }
  263. const {query} = location.query;
  264. if (query !== undefined) {
  265. return decodeScalar(query, '');
  266. }
  267. return DEFAULT_QUERY;
  268. }
  269. getSort(): string {
  270. const {location, savedSearch} = this.props;
  271. if (!location.query.sort && savedSearch?.id) {
  272. return savedSearch.sort;
  273. }
  274. if (location.query.sort) {
  275. return location.query.sort as string;
  276. }
  277. return DEFAULT_SORT;
  278. }
  279. getGroupStatsPeriod(): string {
  280. let currentPeriod: string;
  281. if (typeof this.props.location.query?.groupStatsPeriod === 'string') {
  282. currentPeriod = this.props.location.query.groupStatsPeriod;
  283. } else if (this.getSort() === IssueSortOptions.TREND) {
  284. // Default to the larger graph when sorting by relative change
  285. currentPeriod = 'auto';
  286. } else {
  287. currentPeriod = DEFAULT_GRAPH_STATS_PERIOD;
  288. }
  289. return DYNAMIC_COUNTS_STATS_PERIODS.has(currentPeriod)
  290. ? currentPeriod
  291. : DEFAULT_GRAPH_STATS_PERIOD;
  292. }
  293. getEndpointParams = (): EndpointParams => {
  294. const {selection} = this.props;
  295. const params: EndpointParams = {
  296. project: selection.projects,
  297. environment: selection.environments,
  298. query: this.getQuery(),
  299. ...selection.datetime,
  300. };
  301. if (selection.datetime.period) {
  302. delete params.period;
  303. params.statsPeriod = selection.datetime.period;
  304. }
  305. if (params.end) {
  306. params.end = getUtcDateString(params.end);
  307. }
  308. if (params.start) {
  309. params.start = getUtcDateString(params.start);
  310. }
  311. const sort = this.getSort();
  312. if (sort !== DEFAULT_SORT) {
  313. params.sort = sort;
  314. }
  315. const groupStatsPeriod = this.getGroupStatsPeriod();
  316. if (groupStatsPeriod !== DEFAULT_GRAPH_STATS_PERIOD) {
  317. params.groupStatsPeriod = groupStatsPeriod;
  318. }
  319. // only include defined values.
  320. return pickBy(params, v => defined(v)) as EndpointParams;
  321. };
  322. getSelectedProjectIds = (): string[] => {
  323. return this.props.selection.projects.map(projectId => String(projectId));
  324. };
  325. fetchMemberList() {
  326. const projectIds = this.getSelectedProjectIds();
  327. fetchOrgMembers(this.props.api, this.props.organization.slug, projectIds).then(
  328. members => {
  329. this.setState({memberList: indexMembersByProject(members)});
  330. }
  331. );
  332. }
  333. fetchTags() {
  334. const {api, organization, selection} = this.props;
  335. loadOrganizationTags(api, organization.slug, selection);
  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. }
  395. this.setState({queryCounts});
  396. // If all tabs' counts are fetched, skip and only set
  397. if (
  398. fetchAllCounts ||
  399. !tabQueriesWithCounts.every(tabQuery => queryCounts[tabQuery] !== undefined)
  400. ) {
  401. const requestParams: CountsEndpointParams = {
  402. ...omit(endpointParams, 'query'),
  403. // fetch the counts for the tabs whose counts haven't been fetched yet
  404. query: tabQueriesWithCounts.filter(_query => _query !== currentTabQuery),
  405. };
  406. // If no stats period values are set, use default
  407. if (!requestParams.statsPeriod && !requestParams.start) {
  408. requestParams.statsPeriod = DEFAULT_STATS_PERIOD;
  409. }
  410. this._lastFetchCountsRequest = this.props.api.request(this.groupCountsEndpoint, {
  411. method: 'GET',
  412. data: qs.stringify(requestParams),
  413. success: data => {
  414. if (!data) {
  415. return;
  416. }
  417. // Counts coming from the counts endpoint is limited to 100, for >= 100 we display 99+
  418. queryCounts = {
  419. ...queryCounts,
  420. ...mapValues(data, (count: number) => ({
  421. count,
  422. hasMore: count > TAB_MAX_COUNT,
  423. })),
  424. };
  425. },
  426. error: () => {
  427. this.setState({queryCounts: {}});
  428. },
  429. complete: () => {
  430. this._lastFetchCountsRequest = null;
  431. this.setState({queryCounts});
  432. },
  433. });
  434. }
  435. };
  436. fetchData = (fetchAllCounts = false) => {
  437. const {organization} = this.props;
  438. const query = this.getQuery();
  439. const hasIssueListRemovalAction = organization.features.includes(
  440. 'issue-list-removal-action'
  441. );
  442. // TODO(Kelly): update once issue-list-removal-action feature is stable
  443. if (hasIssueListRemovalAction && !this.state.realtimeActive) {
  444. if (!this.state.actionTaken && !this.state.undo) {
  445. GroupStore.loadInitialData([]);
  446. this.setState({
  447. issuesLoading: true,
  448. queryCount: 0,
  449. itemsRemoved: 0,
  450. error: null,
  451. });
  452. }
  453. } else {
  454. if (!this.state.reviewedIds.length || !isForReviewQuery(query)) {
  455. GroupStore.loadInitialData([]);
  456. this.setState({
  457. issuesLoading: true,
  458. queryCount: 0,
  459. itemsRemoved: 0,
  460. reviewedIds: [],
  461. error: null,
  462. });
  463. }
  464. }
  465. const transaction = getCurrentSentryReactTransaction();
  466. transaction?.setTag('query.sort', this.getSort());
  467. this.setState({
  468. queryCount: 0,
  469. itemsRemoved: 0,
  470. error: null,
  471. });
  472. const requestParams: any = {
  473. ...this.getEndpointParams(),
  474. limit: MAX_ITEMS,
  475. shortIdLookup: 1,
  476. };
  477. const currentQuery = this.props.location.query || {};
  478. if ('cursor' in currentQuery) {
  479. requestParams.cursor = currentQuery.cursor;
  480. }
  481. // If no stats period values are set, use default
  482. if (!requestParams.statsPeriod && !requestParams.start) {
  483. requestParams.statsPeriod = DEFAULT_STATS_PERIOD;
  484. }
  485. requestParams.expand = ['owners', 'inbox'];
  486. requestParams.collapse = 'stats';
  487. if (this._lastRequest) {
  488. this._lastRequest.cancel();
  489. }
  490. if (this._lastStatsRequest) {
  491. this._lastStatsRequest.cancel();
  492. }
  493. if (this._lastFetchCountsRequest) {
  494. this._lastFetchCountsRequest.cancel();
  495. }
  496. this._poller.disable();
  497. this._lastRequest = this.props.api.request(this.groupListEndpoint, {
  498. method: 'GET',
  499. data: qs.stringify(requestParams),
  500. success: (data, _, resp) => {
  501. if (!resp) {
  502. return;
  503. }
  504. const {orgId} = this.props.params;
  505. // If this is a direct hit, we redirect to the intended result directly.
  506. if (resp.getResponseHeader('X-Sentry-Direct-Hit') === '1') {
  507. let redirect: string;
  508. if (data[0] && data[0].matchingEventId) {
  509. const {id, matchingEventId} = data[0];
  510. redirect = `/organizations/${orgId}/issues/${id}/events/${matchingEventId}/`;
  511. } else {
  512. const {id} = data[0];
  513. redirect = `/organizations/${orgId}/issues/${id}/`;
  514. }
  515. browserHistory.replace({
  516. pathname: redirect,
  517. query: {
  518. referrer: 'issue-list',
  519. ...extractSelectionParameters(this.props.location.query),
  520. },
  521. });
  522. return;
  523. }
  524. if (this.state.undo) {
  525. GroupStore.loadInitialData(data);
  526. }
  527. GroupStore.add(data);
  528. // TODO(Kelly): update once issue-list-removal-action feature is stable
  529. if (!hasIssueListRemovalAction) {
  530. if (isForReviewQuery(query)) {
  531. GroupStore.remove(this.state.reviewedIds);
  532. }
  533. }
  534. const numPerfIssues = data.filter(
  535. (group: BaseGroup) => group.issueCategory === IssueCategory.PERFORMANCE
  536. ).length;
  537. const page = this.props.location.query.page;
  538. const endpointParams = this.getEndpointParams();
  539. const tabQueriesWithCounts = getTabsWithCounts(organization);
  540. const currentTabQuery = tabQueriesWithCounts.includes(
  541. endpointParams.query as Query
  542. )
  543. ? endpointParams.query
  544. : null;
  545. const tab = getTabs(organization).find(
  546. ([tabQuery]) => currentTabQuery === tabQuery
  547. )?.[1];
  548. trackAdvancedAnalyticsEvent('issues_tab.viewed', {
  549. organization,
  550. tab: tab?.analyticsName,
  551. page: page ? parseInt(page, 10) : 0,
  552. query,
  553. num_perf_issues: numPerfIssues,
  554. num_issues: data.length,
  555. });
  556. this.fetchStats(data.map((group: BaseGroup) => group.id));
  557. const hits = resp.getResponseHeader('X-Hits');
  558. const queryCount =
  559. typeof hits !== 'undefined' && hits ? parseInt(hits, 10) || 0 : 0;
  560. const maxHits = resp.getResponseHeader('X-Max-Hits');
  561. const queryMaxCount =
  562. typeof maxHits !== 'undefined' && maxHits ? parseInt(maxHits, 10) || 0 : 0;
  563. const pageLinks = resp.getResponseHeader('Link');
  564. // TODO(Kelly): update once issue-list-removal-action feature is stable
  565. if (hasIssueListRemovalAction && !this.state.realtimeActive) {
  566. this.fetchCounts(queryCount, fetchAllCounts);
  567. } else {
  568. if (!this.state.forReview) {
  569. this.fetchCounts(queryCount, fetchAllCounts);
  570. }
  571. }
  572. this.setState({
  573. error: null,
  574. issuesLoading: false,
  575. queryCount,
  576. queryMaxCount,
  577. pageLinks: pageLinks !== null ? pageLinks : '',
  578. });
  579. if (data.length === 0) {
  580. trackAdvancedAnalyticsEvent('issue_search.empty', {
  581. organization: this.props.organization,
  582. search_type: 'issues',
  583. search_source: 'main_search',
  584. query,
  585. });
  586. }
  587. },
  588. error: err => {
  589. trackAdvancedAnalyticsEvent('issue_search.failed', {
  590. organization: this.props.organization,
  591. search_type: 'issues',
  592. search_source: 'main_search',
  593. error: parseApiError(err),
  594. });
  595. this.setState({
  596. error: parseApiError(err),
  597. issuesLoading: false,
  598. });
  599. },
  600. complete: () => {
  601. this._lastRequest = null;
  602. this.resumePolling();
  603. // TODO(Kelly): update once issue-list-removal-action feature is stable
  604. if (hasIssueListRemovalAction && !this.state.realtimeActive) {
  605. this.setState({actionTaken: false, undo: false});
  606. } else {
  607. this.setState({forReview: false});
  608. }
  609. },
  610. });
  611. };
  612. resumePolling = () => {
  613. if (!this.state.pageLinks) {
  614. return;
  615. }
  616. // Only resume polling if we're on the first page of results
  617. const links = parseLinkHeader(this.state.pageLinks);
  618. if (links && !links.previous.results && this.state.realtimeActive) {
  619. this._poller.setEndpoint(links?.previous?.href);
  620. this._poller.enable();
  621. }
  622. };
  623. get groupListEndpoint(): string {
  624. return `/organizations/${this.props.params.orgId}/issues/`;
  625. }
  626. get groupCountsEndpoint(): string {
  627. return `/organizations/${this.props.params.orgId}/issues-count/`;
  628. }
  629. get groupStatsEndpoint(): string {
  630. return `/organizations/${this.props.params.orgId}/issues-stats/`;
  631. }
  632. onRealtimeChange = (realtime: boolean) => {
  633. Cookies.set('realtimeActive', realtime.toString());
  634. this.setState({realtimeActive: realtime});
  635. trackAdvancedAnalyticsEvent('issues_stream.realtime_clicked', {
  636. organization: this.props.organization,
  637. enabled: realtime,
  638. });
  639. };
  640. onSelectStatsPeriod = (period: string) => {
  641. const {location} = this.props;
  642. if (period !== this.getGroupStatsPeriod()) {
  643. const cursor = location.query.cursor;
  644. const queryPageInt = parseInt(location.query.page, 10);
  645. const page = isNaN(queryPageInt) || !location.query.cursor ? 0 : queryPageInt;
  646. this.transitionTo({cursor, page, groupStatsPeriod: period});
  647. }
  648. };
  649. onRealtimePoll = (data: any, _links: any) => {
  650. // Note: We do not update state with cursors from polling,
  651. // `CursorPoller` updates itself with new cursors
  652. GroupStore.addToFront(data);
  653. };
  654. listener = GroupStore.listen(() => this.onGroupChange(), undefined);
  655. onGroupChange() {
  656. const {organization} = this.props;
  657. const {actionTakenGroupData} = this.state;
  658. const query = this.getQuery();
  659. const hasIssueListRemovalAction = organization.features.includes(
  660. 'issue-list-removal-action'
  661. );
  662. // TODO(Kelly): update once issue-list-removal-action feature is stable
  663. if (
  664. hasIssueListRemovalAction &&
  665. !this.state.realtimeActive &&
  666. actionTakenGroupData.length > 0
  667. ) {
  668. const filteredItems = GroupStore.getAllItems().filter(item => {
  669. return actionTakenGroupData.findIndex(data => data.id === item.id) !== -1;
  670. });
  671. const resolvedIds = filteredItems
  672. .filter(item => item.status === 'resolved')
  673. .map(id => id.id);
  674. const ignoredIds = filteredItems
  675. .filter(item => item.status === 'ignored')
  676. .map(i => i.id);
  677. // need to include resolve and ignored statuses because marking as resolved/ignored also
  678. // counts as reviewed
  679. const reviewedIds = filteredItems
  680. .filter(
  681. item => !item.inbox && item.status !== 'resolved' && item.status !== 'ignored'
  682. )
  683. .map(i => i.id);
  684. // Remove Ignored and Resolved group ids from the issue stream if on the All Unresolved,
  685. // For Review, or Ignored tab. Still include on the saved/custom search tab.
  686. if (
  687. resolvedIds.length > 0 &&
  688. (query.includes('is:unresolved') ||
  689. query.includes('is:ignored') ||
  690. isForReviewQuery(query))
  691. ) {
  692. this.onIssueAction(resolvedIds, 'Resolved');
  693. }
  694. if (
  695. ignoredIds.length > 0 &&
  696. (query.includes('is:unresolved') || isForReviewQuery(query))
  697. ) {
  698. this.onIssueAction(ignoredIds, 'Ignored');
  699. }
  700. // Remove issues that are marked as Reviewed from the For Review tab, but still include the
  701. // issues if on the All Unresolved tab or saved/custom searches.
  702. if (
  703. reviewedIds.length > 0 &&
  704. (isForReviewQuery(query) || query.includes('is:ignored'))
  705. ) {
  706. this.onIssueAction(reviewedIds, 'Reviewed');
  707. }
  708. }
  709. const groupIds = GroupStore.getAllItems()
  710. .map(item => item.id)
  711. .slice(0, MAX_ISSUES_COUNT);
  712. if (!isEqual(groupIds, this.state.groupIds)) {
  713. this.setState({groupIds});
  714. }
  715. }
  716. onIssueListSidebarSearch = (query: string) => {
  717. trackAdvancedAnalyticsEvent('search.searched', {
  718. organization: this.props.organization,
  719. query,
  720. search_type: 'issues',
  721. search_source: 'search_builder',
  722. });
  723. this.onSearch(query);
  724. };
  725. onSearch = (query: string) => {
  726. if (query === this.state.query) {
  727. // if query is the same, just re-fetch data
  728. this.fetchData();
  729. } else {
  730. // Clear the saved search as the user wants something else.
  731. this.transitionTo({query}, null);
  732. }
  733. };
  734. onSortChange = (sort: string) => {
  735. trackAdvancedAnalyticsEvent('issues_stream.sort_changed', {
  736. organization: this.props.organization,
  737. sort,
  738. });
  739. this.transitionTo({sort});
  740. };
  741. onCursorChange: CursorHandler = (nextCursor, _path, _query, delta) => {
  742. const queryPageInt = parseInt(this.props.location.query.page, 10);
  743. let nextPage: number | undefined = isNaN(queryPageInt) ? delta : queryPageInt + delta;
  744. let cursor: undefined | string = nextCursor;
  745. // unset cursor and page when we navigate back to the first page
  746. // also reset cursor if somehow the previous button is enabled on
  747. // first page and user attempts to go backwards
  748. if (nextPage <= 0) {
  749. cursor = undefined;
  750. nextPage = undefined;
  751. }
  752. this.transitionTo({cursor, page: nextPage});
  753. };
  754. paginationAnalyticsEvent = (direction: string) => {
  755. trackAdvancedAnalyticsEvent('issues_stream.paginate', {
  756. organization: this.props.organization,
  757. direction,
  758. });
  759. };
  760. /**
  761. * Returns true if all results in the current query are visible/on this page
  762. */
  763. allResultsVisible(): boolean {
  764. if (!this.state.pageLinks) {
  765. return false;
  766. }
  767. const links = parseLinkHeader(this.state.pageLinks);
  768. return links && !links.previous.results && !links.next.results;
  769. }
  770. transitionTo = (
  771. newParams: Partial<EndpointParams> = {},
  772. savedSearch: (SavedSearch & {projectId?: number}) | null = this.props.savedSearch
  773. ) => {
  774. const query = {
  775. referrer: 'issue-list',
  776. ...this.getEndpointParams(),
  777. ...newParams,
  778. };
  779. const {organization} = this.props;
  780. let path: string;
  781. if (savedSearch && savedSearch.id) {
  782. path = `/organizations/${organization.slug}/issues/searches/${savedSearch.id}/`;
  783. // Remove the query as saved searches bring their own query string.
  784. delete query.query;
  785. // If we aren't going to another page in the same search
  786. // drop the query and replace the current project, with the saved search search project
  787. // if available.
  788. if (!query.cursor && savedSearch.projectId) {
  789. query.project = [savedSearch.projectId];
  790. }
  791. if (!query.cursor && !newParams.sort && savedSearch.sort) {
  792. query.sort = savedSearch.sort;
  793. }
  794. } else {
  795. path = `/organizations/${organization.slug}/issues/`;
  796. }
  797. // Remove inbox tab specific sort
  798. if (query.sort === IssueSortOptions.INBOX && query.query !== Query.FOR_REVIEW) {
  799. delete query.sort;
  800. }
  801. if (
  802. path !== this.props.location.pathname ||
  803. !isEqual(query, this.props.location.query)
  804. ) {
  805. browserHistory.push({
  806. pathname: path,
  807. query,
  808. });
  809. this.setState({issuesLoading: true});
  810. }
  811. };
  812. displayReprocessingTab() {
  813. const {organization} = this.props;
  814. const {queryCounts} = this.state;
  815. return (
  816. organization.features.includes('reprocessing-v2') &&
  817. !!queryCounts?.[Query.REPROCESSING]?.count
  818. );
  819. }
  820. displayReprocessingLayout(showReprocessingTab: boolean, query: string) {
  821. return showReprocessingTab && query === Query.REPROCESSING;
  822. }
  823. renderLoading(): React.ReactNode {
  824. return (
  825. <PageContent>
  826. <LoadingIndicator />
  827. </PageContent>
  828. );
  829. }
  830. onSavedSearchSelect = (savedSearch: SavedSearch) => {
  831. trackAdvancedAnalyticsEvent('organization_saved_search.selected', {
  832. organization: this.props.organization,
  833. search_type: 'issues',
  834. id: savedSearch.id ? parseInt(savedSearch.id, 10) : -1,
  835. });
  836. this.setState({issuesLoading: true}, () => this.transitionTo(undefined, savedSearch));
  837. };
  838. onSavedSearchDelete = (search: SavedSearch) => {
  839. const {orgId} = this.props.params;
  840. deleteSavedSearch(this.props.api, orgId, search).then(() => {
  841. this.setState(
  842. {
  843. issuesLoading: true,
  844. },
  845. () => this.transitionTo({}, null)
  846. );
  847. });
  848. };
  849. onDelete = () => {
  850. this.setState({actionTaken: true});
  851. this.fetchData(true);
  852. };
  853. onUndo = () => {
  854. const {organization, selection} = this.props;
  855. const {actionTakenGroupData} = this.state;
  856. const query = this.getQuery();
  857. const groupIds = actionTakenGroupData.map(data => data.id);
  858. const projectIds = selection?.projects?.map(p => p.toString());
  859. const endpoint = `/organizations/${organization.slug}/issues/`;
  860. if (this._lastRequest) {
  861. this._lastRequest.cancel();
  862. }
  863. if (this._lastStatsRequest) {
  864. this._lastStatsRequest.cancel();
  865. }
  866. if (this._lastFetchCountsRequest) {
  867. this._lastFetchCountsRequest.cancel();
  868. }
  869. this.props.api.request(endpoint, {
  870. method: 'PUT',
  871. data: {
  872. status: 'unresolved',
  873. },
  874. query: {
  875. project: projectIds,
  876. id: groupIds,
  877. },
  878. success: response => {
  879. if (!response) {
  880. return;
  881. }
  882. // If on the Ignore or For Review tab, adding back to the GroupStore will make the issue show up
  883. // on this page for a second and then be removed (will show up on All Unresolved). This is to
  884. // stop this from happening and avoid confusion.
  885. if (!query.includes('is:ignored') && !isForReviewQuery(query)) {
  886. GroupStore.add(actionTakenGroupData);
  887. }
  888. this.setState({undo: true});
  889. },
  890. error: err => {
  891. this.setState({
  892. error: parseApiError(err),
  893. issuesLoading: false,
  894. });
  895. },
  896. complete: () => {
  897. this.setState({actionTakenGroupData: []});
  898. this.fetchData();
  899. },
  900. });
  901. };
  902. onMarkReviewed = (itemIds: string[]) => {
  903. const {organization} = this.props;
  904. const query = this.getQuery();
  905. const hasIssueListRemovalAction = organization.features.includes(
  906. 'issue-list-removal-action'
  907. );
  908. if (!isForReviewQuery(query)) {
  909. if (itemIds.length > 1) {
  910. addMessage(
  911. tn('Reviewed %s Issue', 'Reviewed %s Issues', itemIds.length),
  912. 'success',
  913. {duration: 4000}
  914. );
  915. } else {
  916. const shortId = itemIds.map(item => GroupStore.get(item)?.shortId).toString();
  917. addMessage(t('Reviewed %s', 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(`${actionType} ${itemIds.length} ${t('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(`${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. onToggleSavedSearches = (isOpen: boolean) => {
  969. this.setState({
  970. isSavedSearchesOpen: isOpen,
  971. });
  972. };
  973. tagValueLoader = (key: string, search: string) => {
  974. const {orgId} = this.props.params;
  975. const projectIds = this.getSelectedProjectIds();
  976. const endpointParams = this.getEndpointParams();
  977. return fetchTagValues({
  978. api: this.props.api,
  979. orgSlug: orgId,
  980. tagKey: key,
  981. search,
  982. projectIds,
  983. endpointParams: endpointParams as any,
  984. });
  985. };
  986. render() {
  987. if (this.props.savedSearchLoading) {
  988. return this.renderLoading();
  989. }
  990. const {
  991. isSavedSearchesOpen,
  992. pageLinks,
  993. queryCount,
  994. queryCounts,
  995. realtimeActive,
  996. groupIds,
  997. queryMaxCount,
  998. itemsRemoved,
  999. issuesLoading,
  1000. error,
  1001. } = this.state;
  1002. const {
  1003. organization,
  1004. savedSearch,
  1005. savedSearches,
  1006. savedSearchLoading,
  1007. selection,
  1008. location,
  1009. router,
  1010. } = this.props;
  1011. const links = parseLinkHeader(pageLinks);
  1012. const query = this.getQuery();
  1013. const queryPageInt = parseInt(location.query.page, 10);
  1014. // Cursor must be present for the page number to be used
  1015. const page = isNaN(queryPageInt) || !location.query.cursor ? 0 : queryPageInt;
  1016. const pageBasedCount = page * MAX_ITEMS + groupIds.length;
  1017. let pageCount = pageBasedCount > queryCount ? queryCount : pageBasedCount;
  1018. if (!links?.next?.results || this.allResultsVisible()) {
  1019. // On last available page
  1020. pageCount = queryCount;
  1021. } else if (!links?.previous?.results) {
  1022. // On first available page
  1023. pageCount = groupIds.length;
  1024. }
  1025. // Subtract # items that have been marked reviewed
  1026. pageCount = Math.max(pageCount - itemsRemoved, 0);
  1027. const modifiedQueryCount = Math.max(queryCount - itemsRemoved, 0);
  1028. const displayCount = tct('[count] of [total]', {
  1029. count: pageCount,
  1030. total: (
  1031. <StyledQueryCount
  1032. hideParens
  1033. hideIfEmpty={false}
  1034. count={modifiedQueryCount}
  1035. max={queryMaxCount || 100}
  1036. />
  1037. ),
  1038. });
  1039. const projectIds = selection?.projects?.map(p => p.toString());
  1040. const showReprocessingTab = this.displayReprocessingTab();
  1041. const displayReprocessingActions = this.displayReprocessingLayout(
  1042. showReprocessingTab,
  1043. query
  1044. );
  1045. return (
  1046. <StyledPageContent>
  1047. <IssueListHeader
  1048. isSavedSearchesOpen={isSavedSearchesOpen}
  1049. onToggleSavedSearches={this.onToggleSavedSearches}
  1050. organization={organization}
  1051. query={query}
  1052. sort={this.getSort()}
  1053. queryCount={queryCount}
  1054. queryCounts={queryCounts}
  1055. realtimeActive={realtimeActive}
  1056. onRealtimeChange={this.onRealtimeChange}
  1057. router={router}
  1058. savedSearchList={savedSearches}
  1059. onSavedSearchSelect={this.onSavedSearchSelect}
  1060. onSavedSearchDelete={this.onSavedSearchDelete}
  1061. displayReprocessingTab={showReprocessingTab}
  1062. savedSearch={savedSearch}
  1063. selectedProjectIds={selection.projects}
  1064. />
  1065. <StyledBody>
  1066. <StyledMain>
  1067. <IssueListFilters
  1068. organization={organization}
  1069. query={query}
  1070. savedSearch={savedSearch}
  1071. sort={this.getSort()}
  1072. onSearch={this.onSearch}
  1073. />
  1074. <Panel>
  1075. <IssueListActions
  1076. selection={selection}
  1077. query={query}
  1078. queryCount={modifiedQueryCount}
  1079. displayCount={displayCount}
  1080. onSelectStatsPeriod={this.onSelectStatsPeriod}
  1081. onMarkReviewed={this.onMarkReviewed}
  1082. onActionTaken={this.onActionTaken}
  1083. onDelete={this.onDelete}
  1084. statsPeriod={this.getGroupStatsPeriod()}
  1085. groupIds={groupIds}
  1086. allResultsVisible={this.allResultsVisible()}
  1087. displayReprocessingActions={displayReprocessingActions}
  1088. sort={this.getSort()}
  1089. onSortChange={this.onSortChange}
  1090. />
  1091. <PanelBody>
  1092. <ProcessingIssueList
  1093. organization={organization}
  1094. projectIds={projectIds}
  1095. showProject
  1096. />
  1097. <VisuallyCompleteWithData
  1098. hasData={this.state.groupIds.length > 0}
  1099. id="IssueList-Body"
  1100. >
  1101. <GroupListBody
  1102. memberList={this.state.memberList}
  1103. groupStatsPeriod={this.getGroupStatsPeriod()}
  1104. groupIds={groupIds}
  1105. displayReprocessingLayout={displayReprocessingActions}
  1106. query={query}
  1107. sort={this.getSort()}
  1108. selectedProjectIds={selection.projects}
  1109. loading={issuesLoading}
  1110. error={error}
  1111. refetchGroups={this.fetchData}
  1112. />
  1113. </VisuallyCompleteWithData>
  1114. </PanelBody>
  1115. </Panel>
  1116. <StyledPagination
  1117. caption={tct('Showing [displayCount] issues', {
  1118. displayCount,
  1119. })}
  1120. pageLinks={pageLinks}
  1121. onCursor={this.onCursorChange}
  1122. paginationAnalyticsEvent={this.paginationAnalyticsEvent}
  1123. />
  1124. </StyledMain>
  1125. <SavedIssueSearches
  1126. {...{savedSearches, savedSearch, savedSearchLoading, organization}}
  1127. isOpen={isSavedSearchesOpen}
  1128. onSavedSearchSelect={this.onSavedSearchSelect}
  1129. />
  1130. </StyledBody>
  1131. </StyledPageContent>
  1132. );
  1133. }
  1134. }
  1135. export default withRouteAnalytics(
  1136. withApi(
  1137. withPageFilters(
  1138. withSavedSearches(withOrganization(withIssueTags(withProfiler(IssueListOverview))))
  1139. )
  1140. )
  1141. );
  1142. export {IssueListOverview};
  1143. const StyledBody = styled('div')`
  1144. background-color: ${p => p.theme.background};
  1145. display: flex;
  1146. flex-direction: column-reverse;
  1147. @media (min-width: ${p => p.theme.breakpoints.small}) {
  1148. flex: 1;
  1149. display: grid;
  1150. grid-template-rows: 1fr;
  1151. grid-template-columns: 1fr auto;
  1152. gap: 0;
  1153. padding: 0;
  1154. }
  1155. `;
  1156. const StyledMain = styled('section')`
  1157. padding: ${space(2)};
  1158. overflow: hidden;
  1159. @media (min-width: ${p => p.theme.breakpoints.medium}) {
  1160. padding: ${space(3)} ${space(4)};
  1161. }
  1162. `;
  1163. const StyledPagination = styled(Pagination)`
  1164. margin-top: 0;
  1165. `;
  1166. const StyledQueryCount = styled(QueryCount)`
  1167. margin-left: 0;
  1168. `;
  1169. const StyledPageContent = styled(PageContent)`
  1170. padding: 0;
  1171. `;