overview.tsx 40 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344
  1. import {Component} from 'react';
  2. import {browserHistory, RouteComponentProps} from 'react-router';
  3. import styled from '@emotion/styled';
  4. import {withProfiler} from '@sentry/react';
  5. import * as Sentry from '@sentry/react';
  6. import {Location} from 'history';
  7. import Cookies from 'js-cookie';
  8. import isEqual from 'lodash/isEqual';
  9. import mapValues from 'lodash/mapValues';
  10. import omit from 'lodash/omit';
  11. import pickBy from 'lodash/pickBy';
  12. import * as qs from 'query-string';
  13. import {addMessage} from 'sentry/actionCreators/indicator';
  14. import {fetchOrgMembers, indexMembersByProject} from 'sentry/actionCreators/members';
  15. import {
  16. deleteSavedSearch,
  17. fetchSavedSearches,
  18. resetSavedSearches,
  19. } from 'sentry/actionCreators/savedSearches';
  20. import {fetchTagValues, loadOrganizationTags} from 'sentry/actionCreators/tags';
  21. import {Client} from 'sentry/api';
  22. import * as Layout from 'sentry/components/layouts/thirds';
  23. import LoadingError from 'sentry/components/loadingError';
  24. import LoadingIndicator from 'sentry/components/loadingIndicator';
  25. import {extractSelectionParameters} from 'sentry/components/organizations/pageFilters/utils';
  26. import Pagination, {CursorHandler} from 'sentry/components/pagination';
  27. import {Panel, PanelBody} from 'sentry/components/panels';
  28. import QueryCount from 'sentry/components/queryCount';
  29. import {parseSearch} from 'sentry/components/searchSyntax/parser';
  30. import StreamGroup from 'sentry/components/stream/group';
  31. import ProcessingIssueList from 'sentry/components/stream/processingIssueList';
  32. import {DEFAULT_QUERY, DEFAULT_STATS_PERIOD} from 'sentry/constants';
  33. import {t, tct} from 'sentry/locale';
  34. import GroupStore from 'sentry/stores/groupStore';
  35. import {PageContent} from 'sentry/styles/organization';
  36. import {
  37. BaseGroup,
  38. Group,
  39. Member,
  40. Organization,
  41. PageFilters,
  42. SavedSearch,
  43. TagCollection,
  44. } from 'sentry/types';
  45. import {defined} from 'sentry/utils';
  46. import trackAdvancedAnalyticsEvent from 'sentry/utils/analytics/trackAdvancedAnalyticsEvent';
  47. import {callIfFunction} from 'sentry/utils/callIfFunction';
  48. import CursorPoller from 'sentry/utils/cursorPoller';
  49. import {getUtcDateString} from 'sentry/utils/dates';
  50. import getCurrentSentryReactTransaction from 'sentry/utils/getCurrentSentryReactTransaction';
  51. import parseApiError from 'sentry/utils/parseApiError';
  52. import parseLinkHeader from 'sentry/utils/parseLinkHeader';
  53. import {VisuallyCompleteWithData} from 'sentry/utils/performanceForSentry';
  54. import {decodeScalar} from 'sentry/utils/queryString';
  55. import withApi from 'sentry/utils/withApi';
  56. import withIssueTags from 'sentry/utils/withIssueTags';
  57. import withOrganization from 'sentry/utils/withOrganization';
  58. import withPageFilters from 'sentry/utils/withPageFilters';
  59. import withSavedSearches from 'sentry/utils/withSavedSearches';
  60. import IssueListActions from './actions';
  61. import IssueListFilters from './filters';
  62. import IssueListHeader from './header';
  63. import NoGroupsHandler from './noGroupsHandler';
  64. import IssueListSidebar from './sidebar';
  65. import {
  66. getTabs,
  67. getTabsWithCounts,
  68. isForReviewQuery,
  69. IssueSortOptions,
  70. Query,
  71. QueryCounts,
  72. TAB_MAX_COUNT,
  73. } from './utils';
  74. const MAX_ITEMS = 25;
  75. const DEFAULT_SORT = IssueSortOptions.DATE;
  76. // the default period for the graph in each issue row
  77. const DEFAULT_GRAPH_STATS_PERIOD = '24h';
  78. // the allowed period choices for graph in each issue row
  79. const DYNAMIC_COUNTS_STATS_PERIODS = new Set(['14d', '24h', 'auto']);
  80. const MAX_ISSUES_COUNT = 100;
  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. this._poller = new CursorPoller({
  174. linkPreviousHref: parseLinkHeader(this.state.pageLinks)?.previous?.href,
  175. success: this.onRealtimePoll,
  176. });
  177. // Start by getting searches first so if the user is on a saved search
  178. // or they have a pinned search we load the correct data the first time.
  179. this.fetchSavedSearches();
  180. this.fetchTags();
  181. this.fetchMemberList();
  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. callIfFunction(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. getGlobalSearchProjectIds = () => {
  323. return this.props.selection.projects;
  324. };
  325. fetchMemberList() {
  326. const projectIds = this.getGlobalSearchProjectIds()?.map(projectId =>
  327. String(projectId)
  328. );
  329. fetchOrgMembers(this.props.api, this.props.organization.slug, projectIds).then(
  330. members => {
  331. this.setState({memberList: indexMembersByProject(members)});
  332. }
  333. );
  334. }
  335. fetchTags() {
  336. const {organization, selection} = this.props;
  337. this.setState({tagsLoading: true});
  338. loadOrganizationTags(this.props.api, organization.slug, selection).then(() =>
  339. this.setState({tagsLoading: false})
  340. );
  341. }
  342. fetchSavedSearches() {
  343. const {organization, api} = this.props;
  344. fetchSavedSearches(api, organization.slug);
  345. }
  346. fetchStats = (groups: string[]) => {
  347. // If we have no groups to fetch, just skip stats
  348. if (!groups.length) {
  349. return;
  350. }
  351. const requestParams: StatEndpointParams = {
  352. ...this.getEndpointParams(),
  353. groups,
  354. };
  355. // If no stats period values are set, use default
  356. if (!requestParams.statsPeriod && !requestParams.start) {
  357. requestParams.statsPeriod = DEFAULT_STATS_PERIOD;
  358. }
  359. this._lastStatsRequest = this.props.api.request(this.groupStatsEndpoint, {
  360. method: 'GET',
  361. data: qs.stringify(requestParams),
  362. success: data => {
  363. if (!data) {
  364. return;
  365. }
  366. GroupStore.onPopulateStats(groups, data);
  367. },
  368. error: err => {
  369. this.setState({
  370. error: parseApiError(err),
  371. });
  372. },
  373. complete: () => {
  374. this._lastStatsRequest = null;
  375. // End navigation transaction to prevent additional page requests from impacting page metrics.
  376. // Other transactions include stacktrace preview request
  377. const currentTransaction = Sentry.getCurrentHub().getScope()?.getTransaction();
  378. if (currentTransaction?.op === 'navigation') {
  379. currentTransaction.finish();
  380. }
  381. },
  382. });
  383. };
  384. fetchCounts = (currentQueryCount: number, fetchAllCounts: boolean) => {
  385. const {organization} = this.props;
  386. const {queryCounts: _queryCounts} = this.state;
  387. let queryCounts: QueryCounts = {..._queryCounts};
  388. const endpointParams = this.getEndpointParams();
  389. const tabQueriesWithCounts = getTabsWithCounts(organization);
  390. const currentTabQuery = tabQueriesWithCounts.includes(endpointParams.query as Query)
  391. ? endpointParams.query
  392. : null;
  393. // Update the count based on the exact number of issues, these shown as is
  394. if (currentTabQuery) {
  395. queryCounts[currentTabQuery] = {
  396. count: currentQueryCount,
  397. hasMore: false,
  398. };
  399. const tab = getTabs(organization).find(
  400. ([tabQuery]) => currentTabQuery === tabQuery
  401. )?.[1];
  402. if (tab && !endpointParams.cursor) {
  403. trackAdvancedAnalyticsEvent('issues_tab.viewed', {
  404. organization,
  405. tab: tab.analyticsName,
  406. num_issues: queryCounts[currentTabQuery].count,
  407. });
  408. }
  409. }
  410. this.setState({queryCounts});
  411. // If all tabs' counts are fetched, skip and only set
  412. if (
  413. fetchAllCounts ||
  414. !tabQueriesWithCounts.every(tabQuery => queryCounts[tabQuery] !== undefined)
  415. ) {
  416. const requestParams: CountsEndpointParams = {
  417. ...omit(endpointParams, 'query'),
  418. // fetch the counts for the tabs whose counts haven't been fetched yet
  419. query: tabQueriesWithCounts.filter(_query => _query !== currentTabQuery),
  420. };
  421. // If no stats period values are set, use default
  422. if (!requestParams.statsPeriod && !requestParams.start) {
  423. requestParams.statsPeriod = DEFAULT_STATS_PERIOD;
  424. }
  425. this._lastFetchCountsRequest = this.props.api.request(this.groupCountsEndpoint, {
  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. fetchData = (fetchAllCounts = false) => {
  452. const {organization} = this.props;
  453. const query = this.getQuery();
  454. const hasIssueListRemovalAction = organization.features.includes(
  455. 'issue-list-removal-action'
  456. );
  457. // TODO(Kelly): update once issue-list-removal-action feature is stable
  458. if (hasIssueListRemovalAction && !this.state.realtimeActive) {
  459. if (!this.state.actionTaken && !this.state.undo) {
  460. GroupStore.loadInitialData([]);
  461. this.setState({
  462. issuesLoading: true,
  463. queryCount: 0,
  464. itemsRemoved: 0,
  465. error: null,
  466. });
  467. }
  468. } else {
  469. if (!this.state.reviewedIds.length || !isForReviewQuery(query)) {
  470. GroupStore.loadInitialData([]);
  471. this.setState({
  472. issuesLoading: true,
  473. queryCount: 0,
  474. itemsRemoved: 0,
  475. reviewedIds: [],
  476. error: null,
  477. });
  478. }
  479. }
  480. const transaction = getCurrentSentryReactTransaction();
  481. transaction?.setTag('query.sort', this.getSort());
  482. this.setState({
  483. queryCount: 0,
  484. itemsRemoved: 0,
  485. error: null,
  486. });
  487. const requestParams: any = {
  488. ...this.getEndpointParams(),
  489. limit: MAX_ITEMS,
  490. shortIdLookup: 1,
  491. };
  492. const currentQuery = this.props.location.query || {};
  493. if ('cursor' in currentQuery) {
  494. requestParams.cursor = currentQuery.cursor;
  495. }
  496. // If no stats period values are set, use default
  497. if (!requestParams.statsPeriod && !requestParams.start) {
  498. requestParams.statsPeriod = DEFAULT_STATS_PERIOD;
  499. }
  500. requestParams.expand = ['owners', 'inbox'];
  501. requestParams.collapse = 'stats';
  502. if (this._lastRequest) {
  503. this._lastRequest.cancel();
  504. }
  505. if (this._lastStatsRequest) {
  506. this._lastStatsRequest.cancel();
  507. }
  508. if (this._lastFetchCountsRequest) {
  509. this._lastFetchCountsRequest.cancel();
  510. }
  511. this._poller.disable();
  512. this._lastRequest = this.props.api.request(this.groupListEndpoint, {
  513. method: 'GET',
  514. data: qs.stringify(requestParams),
  515. success: (data, _, resp) => {
  516. if (!resp) {
  517. return;
  518. }
  519. const {orgId} = this.props.params;
  520. // If this is a direct hit, we redirect to the intended result directly.
  521. if (resp.getResponseHeader('X-Sentry-Direct-Hit') === '1') {
  522. let redirect: string;
  523. if (data[0] && data[0].matchingEventId) {
  524. const {id, matchingEventId} = data[0];
  525. redirect = `/organizations/${orgId}/issues/${id}/events/${matchingEventId}/`;
  526. } else {
  527. const {id} = data[0];
  528. redirect = `/organizations/${orgId}/issues/${id}/`;
  529. }
  530. browserHistory.replace({
  531. pathname: redirect,
  532. query: extractSelectionParameters(this.props.location.query),
  533. });
  534. return;
  535. }
  536. if (this.state.undo) {
  537. GroupStore.loadInitialData(data);
  538. }
  539. GroupStore.add(data);
  540. // TODO(Kelly): update once issue-list-removal-action feature is stable
  541. if (!hasIssueListRemovalAction) {
  542. if (isForReviewQuery(query)) {
  543. GroupStore.remove(this.state.reviewedIds);
  544. }
  545. }
  546. this.fetchStats(data.map((group: BaseGroup) => group.id));
  547. const hits = resp.getResponseHeader('X-Hits');
  548. const queryCount =
  549. typeof hits !== 'undefined' && hits ? parseInt(hits, 10) || 0 : 0;
  550. const maxHits = resp.getResponseHeader('X-Max-Hits');
  551. const queryMaxCount =
  552. typeof maxHits !== 'undefined' && maxHits ? parseInt(maxHits, 10) || 0 : 0;
  553. const pageLinks = resp.getResponseHeader('Link');
  554. // TODO(Kelly): update once issue-list-removal-action feature is stable
  555. if (hasIssueListRemovalAction && !this.state.realtimeActive) {
  556. this.fetchCounts(queryCount, fetchAllCounts);
  557. } else {
  558. if (!this.state.forReview) {
  559. this.fetchCounts(queryCount, fetchAllCounts);
  560. }
  561. }
  562. this.setState({
  563. error: null,
  564. issuesLoading: false,
  565. queryCount,
  566. queryMaxCount,
  567. pageLinks: pageLinks !== null ? pageLinks : '',
  568. });
  569. if (data.length === 0) {
  570. trackAdvancedAnalyticsEvent('issue_search.empty', {
  571. organization: this.props.organization,
  572. search_type: 'issues',
  573. search_source: 'main_search',
  574. query,
  575. });
  576. }
  577. },
  578. error: err => {
  579. trackAdvancedAnalyticsEvent('issue_search.failed', {
  580. organization: this.props.organization,
  581. search_type: 'issues',
  582. search_source: 'main_search',
  583. error: parseApiError(err),
  584. });
  585. this.setState({
  586. error: parseApiError(err),
  587. issuesLoading: false,
  588. });
  589. },
  590. complete: () => {
  591. this._lastRequest = null;
  592. this.resumePolling();
  593. // TODO(Kelly): update once issue-list-removal-action feature is stable
  594. if (hasIssueListRemovalAction && !this.state.realtimeActive) {
  595. this.setState({actionTaken: false, undo: false});
  596. } else {
  597. this.setState({forReview: false});
  598. }
  599. },
  600. });
  601. };
  602. resumePolling = () => {
  603. if (!this.state.pageLinks) {
  604. return;
  605. }
  606. // Only resume polling if we're on the first page of results
  607. const links = parseLinkHeader(this.state.pageLinks);
  608. if (links && !links.previous.results && this.state.realtimeActive) {
  609. this._poller.setEndpoint(links?.previous?.href);
  610. this._poller.enable();
  611. }
  612. };
  613. get groupListEndpoint(): string {
  614. return `/organizations/${this.props.params.orgId}/issues/`;
  615. }
  616. get groupCountsEndpoint(): string {
  617. return `/organizations/${this.props.params.orgId}/issues-count/`;
  618. }
  619. get groupStatsEndpoint(): string {
  620. return `/organizations/${this.props.params.orgId}/issues-stats/`;
  621. }
  622. onRealtimeChange = (realtime: boolean) => {
  623. Cookies.set('realtimeActive', realtime.toString());
  624. this.setState({realtimeActive: realtime});
  625. trackAdvancedAnalyticsEvent('issues_stream.realtime_clicked', {
  626. organization: this.props.organization,
  627. enabled: realtime,
  628. });
  629. };
  630. onSelectStatsPeriod = (period: string) => {
  631. const {location} = this.props;
  632. if (period !== this.getGroupStatsPeriod()) {
  633. const cursor = location.query.cursor;
  634. const queryPageInt = parseInt(location.query.page, 10);
  635. const page = isNaN(queryPageInt) || !location.query.cursor ? 0 : queryPageInt;
  636. this.transitionTo({cursor, page, groupStatsPeriod: period});
  637. }
  638. };
  639. onRealtimePoll = (data: any, _links: any) => {
  640. // Note: We do not update state with cursors from polling,
  641. // `CursorPoller` updates itself with new cursors
  642. GroupStore.addToFront(data);
  643. };
  644. listener = GroupStore.listen(() => this.onGroupChange(), undefined);
  645. onGroupChange() {
  646. const {organization} = this.props;
  647. const {actionTakenGroupData} = this.state;
  648. const query = this.getQuery();
  649. const hasIssueListRemovalAction = organization.features.includes(
  650. 'issue-list-removal-action'
  651. );
  652. // TODO(Kelly): update once issue-list-removal-action feature is stable
  653. if (
  654. hasIssueListRemovalAction &&
  655. !this.state.realtimeActive &&
  656. actionTakenGroupData.length > 0
  657. ) {
  658. const filteredItems = GroupStore.getAllItems().filter(item => {
  659. return actionTakenGroupData.findIndex(data => data.id === item.id) !== -1;
  660. });
  661. const resolvedIds = filteredItems
  662. .filter(item => item.status === 'resolved')
  663. .map(id => id.id);
  664. const ignoredIds = filteredItems
  665. .filter(item => item.status === 'ignored')
  666. .map(i => i.id);
  667. // need to include resolve and ignored statuses because marking as resolved/ignored also
  668. // counts as reviewed
  669. const reviewedIds = filteredItems
  670. .filter(
  671. item => !item.inbox && item.status !== 'resolved' && item.status !== 'ignored'
  672. )
  673. .map(i => i.id);
  674. // Remove Ignored and Resolved group ids from the issue stream if on the All Unresolved,
  675. // For Review, or Ignored tab. Still include on the saved/custom search tab.
  676. if (
  677. resolvedIds.length > 0 &&
  678. (query.includes('is:unresolved') ||
  679. query.includes('is:ignored') ||
  680. isForReviewQuery(query))
  681. ) {
  682. this.onIssueAction(resolvedIds, t('Resolved'));
  683. }
  684. if (
  685. ignoredIds.length > 0 &&
  686. (query.includes('is:unresolved') || isForReviewQuery(query))
  687. ) {
  688. this.onIssueAction(ignoredIds, t('Ignored'));
  689. }
  690. // Remove issues that are marked as Reviewed from the For Review tab, but still include the
  691. // issues if on the All Unresolved tab or saved/custom searches.
  692. if (
  693. reviewedIds.length > 0 &&
  694. (isForReviewQuery(query) || query.includes('is:ignored'))
  695. ) {
  696. this.onIssueAction(reviewedIds, t('Reviewed'));
  697. }
  698. }
  699. const groupIds = GroupStore.getAllItems()
  700. .map(item => item.id)
  701. .slice(0, MAX_ISSUES_COUNT);
  702. if (!isEqual(groupIds, this.state.groupIds)) {
  703. this.setState({groupIds});
  704. }
  705. }
  706. onIssueListSidebarSearch = (query: string) => {
  707. trackAdvancedAnalyticsEvent('search.searched', {
  708. organization: this.props.organization,
  709. query,
  710. search_type: 'issues',
  711. search_source: 'search_builder',
  712. });
  713. this.onSearch(query);
  714. };
  715. onSearch = (query: string) => {
  716. if (query === this.state.query) {
  717. // if query is the same, just re-fetch data
  718. this.fetchData();
  719. } else {
  720. // Clear the saved search as the user wants something else.
  721. this.transitionTo({query}, null);
  722. }
  723. };
  724. onSortChange = (sort: string) => {
  725. trackAdvancedAnalyticsEvent('issues_stream.sort_changed', {
  726. organization: this.props.organization,
  727. sort,
  728. });
  729. this.transitionTo({sort});
  730. };
  731. onCursorChange: CursorHandler = (nextCursor, _path, _query, delta) => {
  732. const queryPageInt = parseInt(this.props.location.query.page, 10);
  733. let nextPage: number | undefined = isNaN(queryPageInt) ? delta : queryPageInt + delta;
  734. let cursor: undefined | string = nextCursor;
  735. // unset cursor and page when we navigate back to the first page
  736. // also reset cursor if somehow the previous button is enabled on
  737. // first page and user attempts to go backwards
  738. if (nextPage <= 0) {
  739. cursor = undefined;
  740. nextPage = undefined;
  741. }
  742. this.transitionTo({cursor, page: nextPage});
  743. };
  744. onSidebarToggle = () => {
  745. const {organization} = this.props;
  746. this.setState({
  747. isSidebarVisible: !this.state.isSidebarVisible,
  748. });
  749. trackAdvancedAnalyticsEvent('issue.search_sidebar_clicked', {
  750. organization,
  751. });
  752. };
  753. paginationAnalyticsEvent = (direction: string) => {
  754. trackAdvancedAnalyticsEvent('issues_stream.paginate', {
  755. organization: this.props.organization,
  756. direction,
  757. });
  758. };
  759. /**
  760. * Returns true if all results in the current query are visible/on this page
  761. */
  762. allResultsVisible(): boolean {
  763. if (!this.state.pageLinks) {
  764. return false;
  765. }
  766. const links = parseLinkHeader(this.state.pageLinks);
  767. return links && !links.previous.results && !links.next.results;
  768. }
  769. transitionTo = (
  770. newParams: Partial<EndpointParams> = {},
  771. savedSearch: (SavedSearch & {projectId?: number}) | null = this.props.savedSearch
  772. ) => {
  773. const query = {
  774. ...this.getEndpointParams(),
  775. ...newParams,
  776. };
  777. const {organization} = this.props;
  778. let path: string;
  779. if (savedSearch && savedSearch.id) {
  780. path = `/organizations/${organization.slug}/issues/searches/${savedSearch.id}/`;
  781. // Remove the query as saved searches bring their own query string.
  782. delete query.query;
  783. // If we aren't going to another page in the same search
  784. // drop the query and replace the current project, with the saved search search project
  785. // if available.
  786. if (!query.cursor && savedSearch.projectId) {
  787. query.project = [savedSearch.projectId];
  788. }
  789. if (!query.cursor && !newParams.sort && savedSearch.sort) {
  790. query.sort = savedSearch.sort;
  791. }
  792. } else {
  793. path = `/organizations/${organization.slug}/issues/`;
  794. }
  795. // Remove inbox tab specific sort
  796. if (query.sort === IssueSortOptions.INBOX && query.query !== Query.FOR_REVIEW) {
  797. delete query.sort;
  798. }
  799. if (
  800. path !== this.props.location.pathname ||
  801. !isEqual(query, this.props.location.query)
  802. ) {
  803. browserHistory.push({
  804. pathname: path,
  805. query,
  806. });
  807. this.setState({issuesLoading: true});
  808. }
  809. };
  810. displayReprocessingTab() {
  811. const {organization} = this.props;
  812. const {queryCounts} = this.state;
  813. return (
  814. organization.features.includes('reprocessing-v2') &&
  815. !!queryCounts?.[Query.REPROCESSING]?.count
  816. );
  817. }
  818. displayReprocessingLayout(showReprocessingTab: boolean, query: string) {
  819. return showReprocessingTab && query === Query.REPROCESSING;
  820. }
  821. renderGroupNodes = (ids: string[], groupStatsPeriod: string) => {
  822. const topIssue = ids[0];
  823. const {memberList} = this.state;
  824. const query = this.getQuery();
  825. const showInboxTime = this.getSort() === IssueSortOptions.INBOX;
  826. return ids.map((id, index) => {
  827. const hasGuideAnchor = id === topIssue;
  828. const group = GroupStore.get(id) as Group | undefined;
  829. let members: Member['user'][] | undefined;
  830. if (group?.project) {
  831. members = memberList[group.project.slug];
  832. }
  833. const showReprocessingTab = this.displayReprocessingTab();
  834. const displayReprocessingLayout = this.displayReprocessingLayout(
  835. showReprocessingTab,
  836. query
  837. );
  838. return (
  839. <StreamGroup
  840. index={index}
  841. key={id}
  842. id={id}
  843. statsPeriod={groupStatsPeriod}
  844. query={query}
  845. hasGuideAnchor={hasGuideAnchor}
  846. memberList={members}
  847. displayReprocessingLayout={displayReprocessingLayout}
  848. useFilteredStats
  849. showInboxTime={showInboxTime}
  850. />
  851. );
  852. });
  853. };
  854. renderLoading(): React.ReactNode {
  855. return (
  856. <PageContent>
  857. <LoadingIndicator />
  858. </PageContent>
  859. );
  860. }
  861. renderStreamBody(): React.ReactNode {
  862. const {issuesLoading, error, groupIds} = this.state;
  863. if (issuesLoading) {
  864. return <LoadingIndicator hideMessage />;
  865. }
  866. if (error) {
  867. return <LoadingError message={error} onRetry={this.fetchData} />;
  868. }
  869. if (groupIds.length > 0) {
  870. return (
  871. <PanelBody>
  872. {this.renderGroupNodes(groupIds, this.getGroupStatsPeriod())}
  873. </PanelBody>
  874. );
  875. }
  876. const {api, organization, selection} = this.props;
  877. return (
  878. <NoGroupsHandler
  879. api={api}
  880. organization={organization}
  881. query={this.getQuery()}
  882. selectedProjectIds={selection.projects}
  883. groupIds={groupIds}
  884. />
  885. );
  886. }
  887. onSavedSearchSelect = (savedSearch: SavedSearch) => {
  888. trackAdvancedAnalyticsEvent('organization_saved_search.selected', {
  889. organization: this.props.organization,
  890. search_type: 'issues',
  891. id: savedSearch.id ? parseInt(savedSearch.id, 10) : -1,
  892. });
  893. this.setState({issuesLoading: true}, () => this.transitionTo(undefined, savedSearch));
  894. };
  895. onSavedSearchDelete = (search: SavedSearch) => {
  896. const {orgId} = this.props.params;
  897. deleteSavedSearch(this.props.api, orgId, search).then(() => {
  898. this.setState(
  899. {
  900. issuesLoading: true,
  901. },
  902. () => this.transitionTo({}, null)
  903. );
  904. });
  905. };
  906. onDelete = () => {
  907. this.setState({actionTaken: true});
  908. this.fetchData(true);
  909. };
  910. onUndo = () => {
  911. const {organization, selection} = this.props;
  912. const {actionTakenGroupData} = this.state;
  913. const query = this.getQuery();
  914. const groupIds = actionTakenGroupData.map(data => data.id);
  915. const projectIds = selection?.projects?.map(p => p.toString());
  916. const endpoint = `/organizations/${organization.slug}/issues/`;
  917. if (this._lastRequest) {
  918. this._lastRequest.cancel();
  919. }
  920. if (this._lastStatsRequest) {
  921. this._lastStatsRequest.cancel();
  922. }
  923. if (this._lastFetchCountsRequest) {
  924. this._lastFetchCountsRequest.cancel();
  925. }
  926. this.props.api.request(endpoint, {
  927. method: 'PUT',
  928. data: {
  929. status: 'unresolved',
  930. },
  931. query: {
  932. project: projectIds,
  933. id: groupIds,
  934. },
  935. success: response => {
  936. if (!response) {
  937. return;
  938. }
  939. // If on the Ignore or For Review tab, adding back to the GroupStore will make the issue show up
  940. // on this page for a second and then be removed (will show up on All Unresolved). This is to
  941. // stop this from happening and avoid confusion.
  942. if (!query.includes('is:ignored') && !isForReviewQuery(query)) {
  943. GroupStore.add(actionTakenGroupData);
  944. }
  945. this.setState({undo: true});
  946. },
  947. error: err => {
  948. this.setState({
  949. error: parseApiError(err),
  950. issuesLoading: false,
  951. });
  952. },
  953. complete: () => {
  954. this.setState({actionTakenGroupData: []});
  955. this.fetchData();
  956. },
  957. });
  958. };
  959. onMarkReviewed = (itemIds: string[]) => {
  960. const {organization} = this.props;
  961. const query = this.getQuery();
  962. const hasIssueListRemovalAction = organization.features.includes(
  963. 'issue-list-removal-action'
  964. );
  965. if (!isForReviewQuery(query)) {
  966. if (itemIds.length > 1) {
  967. addMessage(t(`Reviewed ${itemIds.length} Issues`), 'success', {duration: 4000});
  968. } else {
  969. const shortId = itemIds.map(item => GroupStore.get(item)?.shortId).toString();
  970. addMessage(t(`Reviewed ${shortId}`), 'success', {duration: 4000});
  971. }
  972. return;
  973. }
  974. const {queryCounts, itemsRemoved} = this.state;
  975. const currentQueryCount = queryCounts[query as Query];
  976. if (itemIds.length && currentQueryCount) {
  977. const inInboxCount = itemIds.filter(id => GroupStore.get(id)?.inbox).length;
  978. currentQueryCount.count -= inInboxCount;
  979. // TODO(Kelly): update once issue-list-removal-action feature is stable
  980. if (!hasIssueListRemovalAction) {
  981. this.setState({
  982. reviewedIds: itemIds,
  983. forReview: true,
  984. });
  985. }
  986. this.setState({
  987. queryCounts: {
  988. ...queryCounts,
  989. [query as Query]: currentQueryCount,
  990. },
  991. itemsRemoved: itemsRemoved + inInboxCount,
  992. });
  993. }
  994. };
  995. onActionTaken = (itemIds: string[]) => {
  996. const actionTakenGroupData = itemIds.map(id => GroupStore.get(id) as Group);
  997. this.setState({
  998. actionTakenGroupData,
  999. });
  1000. };
  1001. onIssueAction = (itemIds: string[], actionType: string) => {
  1002. if (itemIds.length > 1) {
  1003. addMessage(t(`${actionType} ${itemIds.length} Issues`), 'success', {
  1004. duration: 4000,
  1005. ...(actionType !== 'Reviewed' && {undo: this.onUndo}),
  1006. });
  1007. } else {
  1008. const shortId = itemIds.map(item => GroupStore.get(item)?.shortId).toString();
  1009. addMessage(t(`${actionType} ${shortId}`), 'success', {
  1010. duration: 4000,
  1011. ...(actionType !== 'Reviewed' && {undo: this.onUndo}),
  1012. });
  1013. }
  1014. GroupStore.remove(itemIds);
  1015. this.setState({actionTaken: true});
  1016. this.fetchData(true);
  1017. };
  1018. tagValueLoader = (key: string, search: string) => {
  1019. const {orgId} = this.props.params;
  1020. const projectIds = this.getGlobalSearchProjectIds().map(id => id.toString());
  1021. const endpointParams = this.getEndpointParams();
  1022. return fetchTagValues(
  1023. this.props.api,
  1024. orgId,
  1025. key,
  1026. search,
  1027. projectIds,
  1028. endpointParams as any
  1029. );
  1030. };
  1031. render() {
  1032. if (this.props.savedSearchLoading) {
  1033. return this.renderLoading();
  1034. }
  1035. const {
  1036. isSidebarVisible,
  1037. tagsLoading,
  1038. pageLinks,
  1039. queryCount,
  1040. queryCounts,
  1041. realtimeActive,
  1042. groupIds,
  1043. queryMaxCount,
  1044. itemsRemoved,
  1045. } = this.state;
  1046. const {organization, savedSearch, savedSearches, tags, selection, location, router} =
  1047. this.props;
  1048. const links = parseLinkHeader(pageLinks);
  1049. const query = this.getQuery();
  1050. const queryPageInt = parseInt(location.query.page, 10);
  1051. // Cursor must be present for the page number to be used
  1052. const page = isNaN(queryPageInt) || !location.query.cursor ? 0 : queryPageInt;
  1053. const pageBasedCount = page * MAX_ITEMS + groupIds.length;
  1054. let pageCount = pageBasedCount > queryCount ? queryCount : pageBasedCount;
  1055. if (!links?.next?.results || this.allResultsVisible()) {
  1056. // On last available page
  1057. pageCount = queryCount;
  1058. } else if (!links?.previous?.results) {
  1059. // On first available page
  1060. pageCount = groupIds.length;
  1061. }
  1062. // Subtract # items that have been marked reviewed
  1063. pageCount = Math.max(pageCount - itemsRemoved, 0);
  1064. const modifiedQueryCount = Math.max(queryCount - itemsRemoved, 0);
  1065. const displayCount = tct('[count] of [total]', {
  1066. count: pageCount,
  1067. total: (
  1068. <StyledQueryCount
  1069. hideParens
  1070. hideIfEmpty={false}
  1071. count={modifiedQueryCount}
  1072. max={queryMaxCount || 100}
  1073. />
  1074. ),
  1075. });
  1076. const projectIds = selection?.projects?.map(p => p.toString());
  1077. const showReprocessingTab = this.displayReprocessingTab();
  1078. const displayReprocessingActions = this.displayReprocessingLayout(
  1079. showReprocessingTab,
  1080. query
  1081. );
  1082. const layoutProps = {
  1083. fullWidth: !isSidebarVisible,
  1084. };
  1085. return (
  1086. <StyledPageContent>
  1087. <IssueListHeader
  1088. organization={organization}
  1089. query={query}
  1090. sort={this.getSort()}
  1091. queryCount={queryCount}
  1092. queryCounts={queryCounts}
  1093. realtimeActive={realtimeActive}
  1094. onRealtimeChange={this.onRealtimeChange}
  1095. router={router}
  1096. savedSearchList={savedSearches}
  1097. onSavedSearchSelect={this.onSavedSearchSelect}
  1098. onSavedSearchDelete={this.onSavedSearchDelete}
  1099. displayReprocessingTab={showReprocessingTab}
  1100. selectedProjectIds={selection.projects}
  1101. />
  1102. <Layout.Body {...layoutProps}>
  1103. <Layout.Main {...layoutProps}>
  1104. <IssueListFilters
  1105. organization={organization}
  1106. query={query}
  1107. savedSearch={savedSearch}
  1108. sort={this.getSort()}
  1109. onSearch={this.onSearch}
  1110. onSidebarToggle={this.onSidebarToggle}
  1111. isSearchDisabled={isSidebarVisible}
  1112. tagValueLoader={this.tagValueLoader}
  1113. tags={tags}
  1114. />
  1115. <Panel>
  1116. <IssueListActions
  1117. organization={organization}
  1118. selection={selection}
  1119. query={query}
  1120. queryCount={modifiedQueryCount}
  1121. displayCount={displayCount}
  1122. onSelectStatsPeriod={this.onSelectStatsPeriod}
  1123. onMarkReviewed={this.onMarkReviewed}
  1124. onActionTaken={this.onActionTaken}
  1125. onDelete={this.onDelete}
  1126. statsPeriod={this.getGroupStatsPeriod()}
  1127. groupIds={groupIds}
  1128. allResultsVisible={this.allResultsVisible()}
  1129. displayReprocessingActions={displayReprocessingActions}
  1130. sort={this.getSort()}
  1131. onSortChange={this.onSortChange}
  1132. />
  1133. <PanelBody>
  1134. <ProcessingIssueList
  1135. organization={organization}
  1136. projectIds={projectIds}
  1137. showProject
  1138. />
  1139. <VisuallyCompleteWithData
  1140. hasData={this.state.groupIds.length > 0}
  1141. id="IssueList-Body"
  1142. >
  1143. {this.renderStreamBody()}
  1144. </VisuallyCompleteWithData>
  1145. </PanelBody>
  1146. </Panel>
  1147. <StyledPagination
  1148. caption={tct('Showing [displayCount] issues', {
  1149. displayCount,
  1150. })}
  1151. pageLinks={pageLinks}
  1152. onCursor={this.onCursorChange}
  1153. paginationAnalyticsEvent={this.paginationAnalyticsEvent}
  1154. />
  1155. </Layout.Main>
  1156. {/* Avoid rendering sidebar until first accessed */}
  1157. {isSidebarVisible && (
  1158. <Layout.Side>
  1159. <IssueListSidebar
  1160. loading={tagsLoading}
  1161. tags={tags}
  1162. query={query}
  1163. parsedQuery={parseSearch(query) || []}
  1164. onQueryChange={this.onIssueListSidebarSearch}
  1165. tagValueLoader={this.tagValueLoader}
  1166. />
  1167. </Layout.Side>
  1168. )}
  1169. </Layout.Body>
  1170. </StyledPageContent>
  1171. );
  1172. }
  1173. }
  1174. export default withApi(
  1175. withPageFilters(
  1176. withSavedSearches(withOrganization(withIssueTags(withProfiler(IssueListOverview))))
  1177. )
  1178. );
  1179. export {IssueListOverview};
  1180. const StyledPagination = styled(Pagination)`
  1181. margin-top: 0;
  1182. `;
  1183. const StyledQueryCount = styled(QueryCount)`
  1184. margin-left: 0;
  1185. `;
  1186. const StyledPageContent = styled(PageContent)`
  1187. padding: 0;
  1188. `;