overview.tsx 40 KB

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