overview.tsx 41 KB

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