overview.tsx 36 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223
  1. import * as React from 'react';
  2. import {browserHistory, RouteComponentProps} from 'react-router';
  3. import styled from '@emotion/styled';
  4. import {withProfiler} from '@sentry/react';
  5. import {Location} from 'history';
  6. import Cookies from 'js-cookie';
  7. import isEqual from 'lodash/isEqual';
  8. import mapValues from 'lodash/mapValues';
  9. import omit from 'lodash/omit';
  10. import pickBy from 'lodash/pickBy';
  11. import * as qs from 'query-string';
  12. import {fetchOrgMembers, indexMembersByProject} from 'app/actionCreators/members';
  13. import {
  14. deleteSavedSearch,
  15. fetchSavedSearches,
  16. resetSavedSearches,
  17. } from 'app/actionCreators/savedSearches';
  18. import {fetchTagValues, loadOrganizationTags} from 'app/actionCreators/tags';
  19. import GroupActions from 'app/actions/groupActions';
  20. import {Client} from 'app/api';
  21. import GuideAnchor from 'app/components/assistant/guideAnchor';
  22. import LoadingError from 'app/components/loadingError';
  23. import LoadingIndicator from 'app/components/loadingIndicator';
  24. import {extractSelectionParameters} from 'app/components/organizations/globalSelectionHeader/utils';
  25. import Pagination from 'app/components/pagination';
  26. import {Panel, PanelBody} from 'app/components/panels';
  27. import QueryCount from 'app/components/queryCount';
  28. import StreamGroup from 'app/components/stream/group';
  29. import ProcessingIssueList from 'app/components/stream/processingIssueList';
  30. import {DEFAULT_QUERY, DEFAULT_STATS_PERIOD} from 'app/constants';
  31. import {tct} from 'app/locale';
  32. import GroupStore from 'app/stores/groupStore';
  33. import {PageContent} from 'app/styles/organization';
  34. import space from 'app/styles/space';
  35. import {
  36. BaseGroup,
  37. GlobalSelection,
  38. Group,
  39. Member,
  40. Organization,
  41. SavedSearch,
  42. TagCollection,
  43. } from 'app/types';
  44. import {defined} from 'app/utils';
  45. import {analytics, metric, trackAnalyticsEvent} from 'app/utils/analytics';
  46. import {callIfFunction} from 'app/utils/callIfFunction';
  47. import CursorPoller from 'app/utils/cursorPoller';
  48. import {getUtcDateString} from 'app/utils/dates';
  49. import getCurrentSentryReactTransaction from 'app/utils/getCurrentSentryReactTransaction';
  50. import parseApiError from 'app/utils/parseApiError';
  51. import parseLinkHeader from 'app/utils/parseLinkHeader';
  52. import StreamManager from 'app/utils/streamManager';
  53. import withApi from 'app/utils/withApi';
  54. import withGlobalSelection from 'app/utils/withGlobalSelection';
  55. import withIssueTags from 'app/utils/withIssueTags';
  56. import withOrganization from 'app/utils/withOrganization';
  57. import withSavedSearches from 'app/utils/withSavedSearches';
  58. import IssueListActions from './actions';
  59. import IssueListFilters from './filters';
  60. import IssueListHeader from './header';
  61. import NoGroupsHandler from './noGroupsHandler';
  62. import IssueListSidebar from './sidebar';
  63. import {
  64. getTabs,
  65. getTabsWithCounts,
  66. isForReviewQuery,
  67. IssueDisplayOptions,
  68. IssueSortOptions,
  69. Query,
  70. QueryCounts,
  71. TAB_MAX_COUNT,
  72. } from './utils';
  73. const MAX_ITEMS = 25;
  74. const DEFAULT_SORT = IssueSortOptions.DATE;
  75. const DEFAULT_DISPLAY = IssueDisplayOptions.EVENTS;
  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. type Params = {
  81. orgId: string;
  82. };
  83. type Props = {
  84. api: Client;
  85. location: Location;
  86. organization: Organization;
  87. params: Params;
  88. selection: GlobalSelection;
  89. savedSearch: SavedSearch;
  90. savedSearches: SavedSearch[];
  91. savedSearchLoading: boolean;
  92. tags: TagCollection;
  93. } & RouteComponentProps<{searchId?: string}, {}>;
  94. type State = {
  95. groupIds: string[];
  96. selectAllActive: boolean;
  97. realtimeActive: boolean;
  98. pageLinks: string;
  99. /**
  100. * Current query total
  101. */
  102. queryCount: number;
  103. /**
  104. * Counts for each inbox tab
  105. */
  106. queryCounts: QueryCounts;
  107. queryMaxCount: number;
  108. itemsRemoved: number;
  109. error: string | null;
  110. isSidebarVisible: boolean;
  111. renderSidebar: boolean;
  112. issuesLoading: boolean;
  113. tagsLoading: boolean;
  114. memberList: ReturnType<typeof indexMembersByProject>;
  115. // Will be set to true if there is valid session data from issue-stats api call
  116. hasSessions: boolean;
  117. query?: string;
  118. };
  119. type EndpointParams = Partial<GlobalSelection['datetime']> & {
  120. project: number[];
  121. environment: string[];
  122. query?: string;
  123. sort?: string;
  124. statsPeriod?: string;
  125. groupStatsPeriod?: string;
  126. cursor?: string;
  127. page?: number | string;
  128. display?: string;
  129. };
  130. type CountsEndpointParams = Omit<EndpointParams, 'cursor' | 'page' | 'query'> & {
  131. query: string[];
  132. };
  133. type StatEndpointParams = Omit<EndpointParams, 'cursor' | 'page'> & {
  134. groups: string[];
  135. expand?: string | string[];
  136. };
  137. class IssueListOverview extends React.Component<Props, State> {
  138. state: State = this.getInitialState();
  139. getInitialState() {
  140. const realtimeActiveCookie = Cookies.get('realtimeActive');
  141. const realtimeActive =
  142. typeof realtimeActiveCookie === 'undefined'
  143. ? false
  144. : realtimeActiveCookie === 'true';
  145. return {
  146. groupIds: [],
  147. selectAllActive: false,
  148. realtimeActive,
  149. pageLinks: '',
  150. itemsRemoved: 0,
  151. queryCount: 0,
  152. queryCounts: {},
  153. queryMaxCount: 0,
  154. error: null,
  155. isSidebarVisible: false,
  156. renderSidebar: false,
  157. issuesLoading: true,
  158. tagsLoading: true,
  159. memberList: {},
  160. hasSessions: false,
  161. };
  162. }
  163. componentDidMount() {
  164. const links = parseLinkHeader(this.state.pageLinks);
  165. this._poller = new CursorPoller({
  166. endpoint: links.previous?.href || '',
  167. success: this.onRealtimePoll,
  168. });
  169. // Start by getting searches first so if the user is on a saved search
  170. // or they have a pinned search we load the correct data the first time.
  171. this.fetchSavedSearches();
  172. this.fetchTags();
  173. this.fetchMemberList();
  174. }
  175. componentDidUpdate(prevProps: Props, prevState: State) {
  176. // Fire off profiling/metrics first
  177. if (prevState.issuesLoading && !this.state.issuesLoading) {
  178. // First Meaningful Paint for /organizations/:orgId/issues/
  179. if (prevState.queryCount === null) {
  180. metric.measure({
  181. name: 'app.page.perf.issue-list',
  182. start: 'page-issue-list-start',
  183. data: {
  184. // start_type is set on 'page-issue-list-start'
  185. org_id: parseInt(this.props.organization.id, 10),
  186. group: this.props.organization.features.includes('enterprise-perf')
  187. ? 'enterprise-perf'
  188. : 'control',
  189. milestone: 'first-meaningful-paint',
  190. is_enterprise: this.props.organization.features
  191. .includes('enterprise-orgs')
  192. .toString(),
  193. is_outlier: this.props.organization.features
  194. .includes('enterprise-orgs-outliers')
  195. .toString(),
  196. },
  197. });
  198. }
  199. }
  200. if (prevState.realtimeActive !== this.state.realtimeActive) {
  201. // User toggled realtime button
  202. if (this.state.realtimeActive) {
  203. this.resumePolling();
  204. } else {
  205. this._poller.disable();
  206. }
  207. }
  208. // If the project selection has changed reload the member list and tag keys
  209. // allowing autocomplete and tag sidebar to be more accurate.
  210. if (!isEqual(prevProps.selection.projects, this.props.selection.projects)) {
  211. this.fetchMemberList();
  212. this.fetchTags();
  213. // Reset display when selecting multiple projects
  214. const projects = this.props.selection.projects ?? [];
  215. const hasMultipleProjects = projects.length !== 1 || projects[0] === -1;
  216. if (hasMultipleProjects && this.getDisplay() !== DEFAULT_DISPLAY) {
  217. this.transitionTo({display: undefined});
  218. }
  219. }
  220. // Wait for saved searches to load before we attempt to fetch stream data
  221. if (this.props.savedSearchLoading) {
  222. return;
  223. } else if (prevProps.savedSearchLoading) {
  224. this.fetchData();
  225. return;
  226. }
  227. const prevQuery = prevProps.location.query;
  228. const newQuery = this.props.location.query;
  229. const selectionChanged = !isEqual(prevProps.selection, this.props.selection);
  230. // If any important url parameter changed or saved search changed
  231. // reload data.
  232. if (
  233. selectionChanged ||
  234. prevQuery.cursor !== newQuery.cursor ||
  235. prevQuery.sort !== newQuery.sort ||
  236. prevQuery.query !== newQuery.query ||
  237. prevQuery.statsPeriod !== newQuery.statsPeriod ||
  238. prevQuery.groupStatsPeriod !== newQuery.groupStatsPeriod ||
  239. prevProps.savedSearch !== this.props.savedSearch
  240. ) {
  241. this.fetchData(selectionChanged);
  242. } else if (
  243. !this._lastRequest &&
  244. prevState.issuesLoading === false &&
  245. this.state.issuesLoading
  246. ) {
  247. // Reload if we issues are loading or their loading state changed.
  248. // This can happen when transitionTo is called
  249. this.fetchData();
  250. }
  251. }
  252. componentWillUnmount() {
  253. this._poller.disable();
  254. GroupStore.reset();
  255. this.props.api.clear();
  256. callIfFunction(this.listener);
  257. // Reset store when unmounting because we always fetch on mount
  258. // This means if you navigate away from stream and then back to stream,
  259. // this component will go from:
  260. // "ready" ->
  261. // "loading" (because fetching saved searches) ->
  262. // "ready"
  263. //
  264. // We don't render anything until saved searches is ready, so this can
  265. // cause weird side effects (e.g. ProcessingIssueList mounting and making
  266. // a request, but immediately unmounting when fetching saved searches)
  267. resetSavedSearches();
  268. }
  269. private _poller: any;
  270. private _lastRequest: any;
  271. private _lastStatsRequest: any;
  272. private _streamManager = new StreamManager(GroupStore);
  273. getQuery(): string {
  274. const {savedSearch, location} = this.props;
  275. if (savedSearch) {
  276. return savedSearch.query;
  277. }
  278. const {query} = location.query;
  279. if (query !== undefined) {
  280. return query as string;
  281. }
  282. return DEFAULT_QUERY;
  283. }
  284. getSort(): string {
  285. const {location, savedSearch} = this.props;
  286. if (!location.query.sort && savedSearch?.id) {
  287. return savedSearch.sort;
  288. }
  289. if (location.query.sort) {
  290. return location.query.sort as string;
  291. }
  292. return DEFAULT_SORT;
  293. }
  294. getDisplay(): IssueDisplayOptions {
  295. const {organization, location} = this.props;
  296. if (organization.features.includes('issue-percent-display')) {
  297. if (
  298. location.query.display &&
  299. Object.values(IssueDisplayOptions).includes(location.query.display)
  300. ) {
  301. return location.query.display as IssueDisplayOptions;
  302. }
  303. }
  304. return DEFAULT_DISPLAY;
  305. }
  306. getGroupStatsPeriod(): string {
  307. let currentPeriod: string;
  308. if (typeof this.props.location.query?.groupStatsPeriod === 'string') {
  309. currentPeriod = this.props.location.query.groupStatsPeriod;
  310. } else if (this.getSort() === IssueSortOptions.TREND) {
  311. // Default to the larger graph when sorting by relative change
  312. currentPeriod = 'auto';
  313. } else {
  314. currentPeriod = DEFAULT_GRAPH_STATS_PERIOD;
  315. }
  316. return DYNAMIC_COUNTS_STATS_PERIODS.has(currentPeriod)
  317. ? currentPeriod
  318. : DEFAULT_GRAPH_STATS_PERIOD;
  319. }
  320. getEndpointParams = (): EndpointParams => {
  321. const {selection} = this.props;
  322. const params: EndpointParams = {
  323. project: selection.projects,
  324. environment: selection.environments,
  325. query: this.getQuery(),
  326. ...selection.datetime,
  327. };
  328. if (selection.datetime.period) {
  329. delete params.period;
  330. params.statsPeriod = selection.datetime.period;
  331. }
  332. if (params.end) {
  333. params.end = getUtcDateString(params.end);
  334. }
  335. if (params.start) {
  336. params.start = getUtcDateString(params.start);
  337. }
  338. const sort = this.getSort();
  339. if (sort !== DEFAULT_SORT) {
  340. params.sort = sort;
  341. }
  342. const display = this.getDisplay();
  343. if (display !== DEFAULT_DISPLAY) {
  344. params.display = display;
  345. }
  346. const groupStatsPeriod = this.getGroupStatsPeriod();
  347. if (groupStatsPeriod !== DEFAULT_GRAPH_STATS_PERIOD) {
  348. params.groupStatsPeriod = groupStatsPeriod;
  349. }
  350. // only include defined values.
  351. return pickBy(params, v => defined(v)) as EndpointParams;
  352. };
  353. getGlobalSearchProjectIds = () => {
  354. return this.props.selection.projects;
  355. };
  356. fetchMemberList() {
  357. const projectIds = this.getGlobalSearchProjectIds()?.map(projectId =>
  358. String(projectId)
  359. );
  360. fetchOrgMembers(this.props.api, this.props.organization.slug, projectIds).then(
  361. members => {
  362. this.setState({memberList: indexMembersByProject(members)});
  363. }
  364. );
  365. }
  366. fetchTags() {
  367. const {organization, selection} = this.props;
  368. this.setState({tagsLoading: true});
  369. loadOrganizationTags(this.props.api, organization.slug, selection).then(() =>
  370. this.setState({tagsLoading: false})
  371. );
  372. }
  373. fetchStats = (groups: string[]) => {
  374. // If we have no groups to fetch, just skip stats
  375. if (!groups.length) {
  376. this.setState({hasSessions: false});
  377. return;
  378. }
  379. const requestParams: StatEndpointParams = {
  380. ...this.getEndpointParams(),
  381. groups,
  382. };
  383. // If no stats period values are set, use default
  384. if (!requestParams.statsPeriod && !requestParams.start) {
  385. requestParams.statsPeriod = DEFAULT_STATS_PERIOD;
  386. }
  387. if (this.props.organization.features.includes('issue-percent-display')) {
  388. requestParams.expand = 'sessions';
  389. }
  390. this._lastStatsRequest = this.props.api.request(this.getGroupStatsEndpoint(), {
  391. method: 'GET',
  392. data: qs.stringify(requestParams),
  393. success: data => {
  394. if (!data) {
  395. return;
  396. }
  397. GroupActions.populateStats(groups, data);
  398. const hasSessions =
  399. data.filter(groupStats => !groupStats.sessionCount).length === 0;
  400. if (hasSessions !== this.state.hasSessions) {
  401. this.setState({
  402. hasSessions,
  403. });
  404. }
  405. },
  406. error: err => {
  407. this.setState({
  408. error: parseApiError(err),
  409. });
  410. },
  411. complete: () => {
  412. this._lastStatsRequest = null;
  413. },
  414. });
  415. };
  416. fetchCounts = async (currentQueryCount: number, fetchAllCounts: boolean) => {
  417. const {organization} = this.props;
  418. const {queryCounts: _queryCounts} = this.state;
  419. let queryCounts: QueryCounts = {..._queryCounts};
  420. const endpointParams = this.getEndpointParams();
  421. const tabQueriesWithCounts = getTabsWithCounts(organization);
  422. const currentTabQuery = tabQueriesWithCounts.includes(endpointParams.query as Query)
  423. ? endpointParams.query
  424. : null;
  425. // If all tabs' counts are fetched, skip and only set
  426. if (
  427. fetchAllCounts ||
  428. !tabQueriesWithCounts.every(tabQuery => queryCounts[tabQuery] !== undefined)
  429. ) {
  430. const requestParams: CountsEndpointParams = {
  431. ...omit(endpointParams, 'query'),
  432. // fetch the counts for the tabs whose counts haven't been fetched yet
  433. query: tabQueriesWithCounts.filter(_query => _query !== currentTabQuery),
  434. };
  435. // If no stats period values are set, use default
  436. if (!requestParams.statsPeriod && !requestParams.start) {
  437. requestParams.statsPeriod = DEFAULT_STATS_PERIOD;
  438. }
  439. try {
  440. const response = await this.props.api.requestPromise(
  441. this.getGroupCountsEndpoint(),
  442. {
  443. method: 'GET',
  444. data: qs.stringify(requestParams),
  445. }
  446. );
  447. // Counts coming from the counts endpoint is limited to 100, for >= 100 we display 99+
  448. queryCounts = {
  449. ...queryCounts,
  450. ...mapValues(response, (count: number) => ({
  451. count,
  452. hasMore: count > TAB_MAX_COUNT,
  453. })),
  454. };
  455. } catch (e) {
  456. this.setState({
  457. error: parseApiError(e),
  458. });
  459. return;
  460. }
  461. }
  462. // Update the count based on the exact number of issues, these shown as is
  463. if (currentTabQuery) {
  464. queryCounts[currentTabQuery] = {
  465. count: currentQueryCount,
  466. hasMore: false,
  467. };
  468. const tab = getTabs(organization).find(
  469. ([tabQuery]) => currentTabQuery === tabQuery
  470. )?.[1];
  471. if (tab && !endpointParams.cursor) {
  472. trackAnalyticsEvent({
  473. eventKey: 'issues_tab.viewed',
  474. eventName: 'Viewed Issues Tab',
  475. organization_id: organization.id,
  476. tab: tab.analyticsName,
  477. num_issues: queryCounts[currentTabQuery].count,
  478. });
  479. }
  480. }
  481. this.setState({queryCounts});
  482. };
  483. fetchData = (fetchAllCounts = false) => {
  484. GroupStore.loadInitialData([]);
  485. this._streamManager.reset();
  486. const transaction = getCurrentSentryReactTransaction();
  487. transaction?.setTag('query.sort', this.getSort());
  488. this.setState({
  489. issuesLoading: true,
  490. queryCount: 0,
  491. itemsRemoved: 0,
  492. error: null,
  493. });
  494. const requestParams: any = {
  495. ...this.getEndpointParams(),
  496. limit: MAX_ITEMS,
  497. shortIdLookup: 1,
  498. };
  499. const currentQuery = this.props.location.query || {};
  500. if ('cursor' in currentQuery) {
  501. requestParams.cursor = currentQuery.cursor;
  502. }
  503. // If no stats period values are set, use default
  504. if (!requestParams.statsPeriod && !requestParams.start) {
  505. requestParams.statsPeriod = DEFAULT_STATS_PERIOD;
  506. }
  507. requestParams.expand = ['owners', 'inbox'];
  508. requestParams.collapse = 'stats';
  509. if (this._lastRequest) {
  510. this._lastRequest.cancel();
  511. }
  512. if (this._lastStatsRequest) {
  513. this._lastStatsRequest.cancel();
  514. }
  515. this._poller.disable();
  516. this._lastRequest = this.props.api.request(this.getGroupListEndpoint(), {
  517. method: 'GET',
  518. data: qs.stringify(requestParams),
  519. success: (data, _, jqXHR) => {
  520. if (!jqXHR) {
  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 (jqXHR.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. this._streamManager.push(data);
  541. this.fetchStats(data.map((group: BaseGroup) => group.id));
  542. const hits = jqXHR.getResponseHeader('X-Hits');
  543. const queryCount =
  544. typeof hits !== 'undefined' && hits ? parseInt(hits, 10) || 0 : 0;
  545. const maxHits = jqXHR.getResponseHeader('X-Max-Hits');
  546. const queryMaxCount =
  547. typeof maxHits !== 'undefined' && maxHits ? parseInt(maxHits, 10) || 0 : 0;
  548. const pageLinks = jqXHR.getResponseHeader('Link');
  549. this.fetchCounts(queryCount, fetchAllCounts);
  550. this.setState({
  551. error: null,
  552. issuesLoading: false,
  553. queryCount,
  554. queryMaxCount,
  555. pageLinks: pageLinks !== null ? pageLinks : '',
  556. });
  557. },
  558. error: err => {
  559. trackAnalyticsEvent({
  560. eventKey: 'issue_search.failed',
  561. eventName: 'Issue Search: Failed',
  562. organization_id: this.props.organization.id,
  563. query: this.getQuery(),
  564. search_type: 'issues',
  565. search_source: 'main_search',
  566. error: parseApiError(err),
  567. });
  568. this.setState({
  569. error: parseApiError(err),
  570. issuesLoading: false,
  571. });
  572. },
  573. complete: () => {
  574. this._lastRequest = null;
  575. this.resumePolling();
  576. },
  577. });
  578. };
  579. resumePolling = () => {
  580. if (!this.state.pageLinks) {
  581. return;
  582. }
  583. // Only resume polling if we're on the first page of results
  584. const links = parseLinkHeader(this.state.pageLinks);
  585. if (links && !links.previous.results && this.state.realtimeActive) {
  586. // Remove collapse stats from endpoint before supplying to poller
  587. const issueEndpoint = new URL(links.previous.href, window.location.origin);
  588. issueEndpoint.searchParams.delete('collapse');
  589. this._poller.setEndpoint(decodeURIComponent(issueEndpoint.href));
  590. this._poller.enable();
  591. }
  592. };
  593. getGroupListEndpoint(): string {
  594. const {orgId} = this.props.params;
  595. return `/organizations/${orgId}/issues/`;
  596. }
  597. getGroupCountsEndpoint(): string {
  598. const {orgId} = this.props.params;
  599. return `/organizations/${orgId}/issues-count/`;
  600. }
  601. getGroupStatsEndpoint(): string {
  602. const {orgId} = this.props.params;
  603. return `/organizations/${orgId}/issues-stats/`;
  604. }
  605. onRealtimeChange = (realtime: boolean) => {
  606. Cookies.set('realtimeActive', realtime.toString());
  607. this.setState({realtimeActive: realtime});
  608. };
  609. onSelectStatsPeriod = (period: string) => {
  610. if (period !== this.getGroupStatsPeriod()) {
  611. this.transitionTo({groupStatsPeriod: period});
  612. }
  613. };
  614. onRealtimePoll = (data: any, _links: any) => {
  615. // Note: We do not update state with cursors from polling,
  616. // `CursorPoller` updates itself with new cursors
  617. this._streamManager.unshift(data);
  618. };
  619. listener = GroupStore.listen(() => this.onGroupChange(), undefined);
  620. onGroupChange() {
  621. const groupIds = this._streamManager.getAllItems().map(item => item.id) ?? [];
  622. if (!isEqual(groupIds, this.state.groupIds)) {
  623. this.setState({groupIds});
  624. }
  625. }
  626. onIssueListSidebarSearch = (query: string) => {
  627. analytics('search.searched', {
  628. org_id: this.props.organization.id,
  629. query,
  630. search_type: 'issues',
  631. search_source: 'search_builder',
  632. });
  633. this.onSearch(query);
  634. };
  635. onSearch = (query: string) => {
  636. if (query === this.state.query) {
  637. // if query is the same, just re-fetch data
  638. this.fetchData();
  639. } else {
  640. // Clear the saved search as the user wants something else.
  641. this.transitionTo({query}, null);
  642. }
  643. };
  644. onSortChange = (sort: string) => {
  645. this.transitionTo({sort});
  646. };
  647. onDisplayChange = (display: string) => {
  648. this.transitionTo({display});
  649. };
  650. onCursorChange = (cursor: string | undefined, _path, query, pageDiff: number) => {
  651. const queryPageInt = parseInt(query.page, 10);
  652. let nextPage: number | undefined = isNaN(queryPageInt)
  653. ? pageDiff
  654. : queryPageInt + pageDiff;
  655. // unset cursor and page when we navigate back to the first page
  656. // also reset cursor if somehow the previous button is enabled on
  657. // first page and user attempts to go backwards
  658. if (nextPage <= 0) {
  659. cursor = undefined;
  660. nextPage = undefined;
  661. }
  662. this.transitionTo({cursor, page: nextPage});
  663. };
  664. onSidebarToggle = () => {
  665. const {organization} = this.props;
  666. this.setState({
  667. isSidebarVisible: !this.state.isSidebarVisible,
  668. renderSidebar: true,
  669. });
  670. analytics('issue.search_sidebar_clicked', {
  671. org_id: parseInt(organization.id, 10),
  672. });
  673. };
  674. /**
  675. * Returns true if all results in the current query are visible/on this page
  676. */
  677. allResultsVisible(): boolean {
  678. if (!this.state.pageLinks) {
  679. return false;
  680. }
  681. const links = parseLinkHeader(this.state.pageLinks);
  682. return links && !links.previous.results && !links.next.results;
  683. }
  684. transitionTo = (
  685. newParams: Partial<EndpointParams> = {},
  686. savedSearch: (SavedSearch & {projectId?: number}) | null = this.props.savedSearch
  687. ) => {
  688. const query = {
  689. ...this.getEndpointParams(),
  690. ...newParams,
  691. };
  692. const {organization} = this.props;
  693. let path: string;
  694. if (savedSearch && savedSearch.id) {
  695. path = `/organizations/${organization.slug}/issues/searches/${savedSearch.id}/`;
  696. // Remove the query as saved searches bring their own query string.
  697. delete query.query;
  698. // If we aren't going to another page in the same search
  699. // drop the query and replace the current project, with the saved search search project
  700. // if available.
  701. if (!query.cursor && savedSearch.projectId) {
  702. query.project = [savedSearch.projectId];
  703. }
  704. if (!query.cursor && !newParams.sort && savedSearch.sort) {
  705. query.sort = savedSearch.sort;
  706. }
  707. } else {
  708. path = `/organizations/${organization.slug}/issues/`;
  709. }
  710. // Remove inbox tab specific sort
  711. if (query.sort === IssueSortOptions.INBOX && query.query !== Query.FOR_REVIEW) {
  712. delete query.sort;
  713. }
  714. if (
  715. path !== this.props.location.pathname ||
  716. !isEqual(query, this.props.location.query)
  717. ) {
  718. browserHistory.push({
  719. pathname: path,
  720. query,
  721. });
  722. this.setState({issuesLoading: true});
  723. }
  724. };
  725. displayReprocessingTab() {
  726. const {organization} = this.props;
  727. const {queryCounts} = this.state;
  728. return (
  729. organization.features.includes('reprocessing-v2') &&
  730. !!queryCounts?.[Query.REPROCESSING]?.count
  731. );
  732. }
  733. displayReprocessingLayout(showReprocessingTab: boolean, query: string) {
  734. return showReprocessingTab && query === Query.REPROCESSING;
  735. }
  736. renderGroupNodes = (ids: string[], groupStatsPeriod: string) => {
  737. const topIssue = ids[0];
  738. const {memberList} = this.state;
  739. const query = this.getQuery();
  740. const showInboxTime = this.getSort() === IssueSortOptions.INBOX;
  741. return ids.map((id, index) => {
  742. const hasGuideAnchor = id === topIssue;
  743. const group = GroupStore.get(id) as Group | undefined;
  744. let members: Member['user'][] | undefined;
  745. if (group?.project) {
  746. members = memberList[group.project.slug];
  747. }
  748. const showReprocessingTab = this.displayReprocessingTab();
  749. const displayReprocessingLayout = this.displayReprocessingLayout(
  750. showReprocessingTab,
  751. query
  752. );
  753. return (
  754. <StreamGroup
  755. index={index}
  756. key={id}
  757. id={id}
  758. statsPeriod={groupStatsPeriod}
  759. query={query}
  760. hasGuideAnchor={hasGuideAnchor}
  761. memberList={members}
  762. displayReprocessingLayout={displayReprocessingLayout}
  763. useFilteredStats
  764. showInboxTime={showInboxTime}
  765. display={this.getDisplay()}
  766. />
  767. );
  768. });
  769. };
  770. renderLoading(): React.ReactNode {
  771. return (
  772. <StyledPageContent>
  773. <LoadingIndicator />
  774. </StyledPageContent>
  775. );
  776. }
  777. renderStreamBody(): React.ReactNode {
  778. const {issuesLoading, error, groupIds} = this.state;
  779. if (issuesLoading) {
  780. return <LoadingIndicator hideMessage />;
  781. }
  782. if (error) {
  783. return <LoadingError message={error} onRetry={this.fetchData} />;
  784. }
  785. if (groupIds.length > 0) {
  786. return (
  787. <PanelBody>
  788. {this.renderGroupNodes(groupIds, this.getGroupStatsPeriod())}
  789. </PanelBody>
  790. );
  791. }
  792. const {api, organization, selection} = this.props;
  793. return (
  794. <NoGroupsHandler
  795. api={api}
  796. organization={organization}
  797. query={this.getQuery()}
  798. selectedProjectIds={selection.projects}
  799. groupIds={groupIds}
  800. />
  801. );
  802. }
  803. fetchSavedSearches = () => {
  804. const {organization, api} = this.props;
  805. fetchSavedSearches(api, organization.slug);
  806. };
  807. onSavedSearchSelect = (savedSearch: SavedSearch) => {
  808. trackAnalyticsEvent({
  809. eventKey: 'organization_saved_search.selected',
  810. eventName: 'Organization Saved Search: Selected saved search',
  811. organization_id: this.props.organization.id,
  812. query: savedSearch.query,
  813. search_type: 'issues',
  814. id: savedSearch.id ? parseInt(savedSearch.id, 10) : -1,
  815. });
  816. this.setState({issuesLoading: true}, () => this.transitionTo(undefined, savedSearch));
  817. };
  818. onSavedSearchDelete = (search: SavedSearch) => {
  819. const {orgId} = this.props.params;
  820. deleteSavedSearch(this.props.api, orgId, search).then(() => {
  821. this.setState(
  822. {
  823. issuesLoading: true,
  824. },
  825. () => this.transitionTo({}, null)
  826. );
  827. });
  828. };
  829. onDelete = () => {
  830. this.fetchData(true);
  831. };
  832. onMarkReviewed = (itemIds: string[]) => {
  833. const query = this.getQuery();
  834. if (!isForReviewQuery(query)) {
  835. return;
  836. }
  837. const {queryCounts, itemsRemoved} = this.state;
  838. const currentQueryCount = queryCounts[query as Query];
  839. if (itemIds.length && currentQueryCount) {
  840. const inInboxCount = itemIds.filter(id => GroupStore.get(id)?.inbox).length;
  841. currentQueryCount.count -= inInboxCount;
  842. this.setState({
  843. queryCounts: {
  844. ...queryCounts,
  845. [query as Query]: currentQueryCount,
  846. },
  847. itemsRemoved: itemsRemoved + inInboxCount,
  848. });
  849. }
  850. };
  851. tagValueLoader = (key: string, search: string) => {
  852. const {orgId} = this.props.params;
  853. const projectIds = this.getGlobalSearchProjectIds().map(id => id.toString());
  854. const endpointParams = this.getEndpointParams();
  855. return fetchTagValues(
  856. this.props.api,
  857. orgId,
  858. key,
  859. search,
  860. projectIds,
  861. endpointParams as any
  862. );
  863. };
  864. render() {
  865. if (this.props.savedSearchLoading) {
  866. return this.renderLoading();
  867. }
  868. const {
  869. renderSidebar,
  870. isSidebarVisible,
  871. tagsLoading,
  872. pageLinks,
  873. queryCount,
  874. queryCounts,
  875. realtimeActive,
  876. groupIds,
  877. queryMaxCount,
  878. itemsRemoved,
  879. hasSessions,
  880. } = this.state;
  881. const {organization, savedSearch, savedSearches, tags, selection, location, router} =
  882. this.props;
  883. const links = parseLinkHeader(pageLinks);
  884. const query = this.getQuery();
  885. const queryPageInt = parseInt(location.query.page, 10);
  886. // Cursor must be present for the page number to be used
  887. const page = isNaN(queryPageInt) || !location.query.cursor ? 0 : queryPageInt;
  888. const pageBasedCount = page * MAX_ITEMS + groupIds.length;
  889. let pageCount = pageBasedCount > queryCount ? queryCount : pageBasedCount;
  890. if (!links?.next?.results || this.allResultsVisible()) {
  891. // On last available page
  892. pageCount = queryCount;
  893. } else if (!links?.previous?.results) {
  894. // On first available page
  895. pageCount = groupIds.length;
  896. }
  897. // Subtract # items that have been marked reviewed
  898. pageCount = Math.max(pageCount - itemsRemoved, 0);
  899. const modifiedQueryCount = Math.max(queryCount - itemsRemoved, 0);
  900. const displayCount = tct('[count] of [total]', {
  901. count: pageCount,
  902. total: (
  903. <StyledQueryCount
  904. hideParens
  905. hideIfEmpty={false}
  906. count={modifiedQueryCount}
  907. max={queryMaxCount || 100}
  908. />
  909. ),
  910. });
  911. // TODO(workflow): When organization:semver flag is removed add semver tags to tagStore
  912. if (organization.features.includes('semver') && !tags['release.version']) {
  913. tags['release.version'] = {
  914. key: 'release.version',
  915. name: 'release.version',
  916. };
  917. tags['release.build'] = {
  918. key: 'release.build',
  919. name: 'release.build',
  920. };
  921. tags['release.package'] = {
  922. key: 'release.package',
  923. name: 'release.package',
  924. };
  925. }
  926. const projectIds = selection?.projects?.map(p => p.toString());
  927. const orgSlug = organization.slug;
  928. const showReprocessingTab = this.displayReprocessingTab();
  929. const displayReprocessingActions = this.displayReprocessingLayout(
  930. showReprocessingTab,
  931. query
  932. );
  933. return (
  934. <React.Fragment>
  935. <IssueListHeader
  936. organization={organization}
  937. query={query}
  938. sort={this.getSort()}
  939. queryCount={queryCount}
  940. queryCounts={queryCounts}
  941. realtimeActive={realtimeActive}
  942. onRealtimeChange={this.onRealtimeChange}
  943. projectIds={projectIds}
  944. orgSlug={orgSlug}
  945. router={router}
  946. savedSearchList={savedSearches}
  947. onSavedSearchSelect={this.onSavedSearchSelect}
  948. onSavedSearchDelete={this.onSavedSearchDelete}
  949. displayReprocessingTab={showReprocessingTab}
  950. />
  951. <StyledPageContent>
  952. <StreamContent showSidebar={isSidebarVisible}>
  953. <IssueListFilters
  954. organization={organization}
  955. query={query}
  956. savedSearch={savedSearch}
  957. sort={this.getSort()}
  958. display={this.getDisplay()}
  959. onDisplayChange={this.onDisplayChange}
  960. onSortChange={this.onSortChange}
  961. onSearch={this.onSearch}
  962. onSidebarToggle={this.onSidebarToggle}
  963. isSearchDisabled={isSidebarVisible}
  964. tagValueLoader={this.tagValueLoader}
  965. tags={tags}
  966. hasSessions={hasSessions}
  967. selectedProjects={selection.projects}
  968. />
  969. <Panel>
  970. <IssueListActions
  971. organization={organization}
  972. selection={selection}
  973. query={query}
  974. queryCount={modifiedQueryCount}
  975. displayCount={displayCount}
  976. onSelectStatsPeriod={this.onSelectStatsPeriod}
  977. onMarkReviewed={this.onMarkReviewed}
  978. onDelete={this.onDelete}
  979. statsPeriod={this.getGroupStatsPeriod()}
  980. groupIds={groupIds}
  981. allResultsVisible={this.allResultsVisible()}
  982. displayReprocessingActions={displayReprocessingActions}
  983. />
  984. <PanelBody>
  985. <ProcessingIssueList
  986. organization={organization}
  987. projectIds={projectIds}
  988. showProject
  989. />
  990. {this.renderStreamBody()}
  991. </PanelBody>
  992. </Panel>
  993. <PaginationWrapper>
  994. {groupIds?.length > 0 && (
  995. <div>
  996. {/* total includes its own space */}
  997. {tct('Showing [displayCount] issues', {
  998. displayCount,
  999. })}
  1000. </div>
  1001. )}
  1002. <StyledPagination pageLinks={pageLinks} onCursor={this.onCursorChange} />
  1003. </PaginationWrapper>
  1004. </StreamContent>
  1005. <SidebarContainer showSidebar={isSidebarVisible}>
  1006. {/* Avoid rendering sidebar until first accessed */}
  1007. {renderSidebar && (
  1008. <IssueListSidebar
  1009. loading={tagsLoading}
  1010. tags={tags}
  1011. query={query}
  1012. onQueryChange={this.onIssueListSidebarSearch}
  1013. tagValueLoader={this.tagValueLoader}
  1014. />
  1015. )}
  1016. </SidebarContainer>
  1017. </StyledPageContent>
  1018. {query === Query.FOR_REVIEW && <GuideAnchor target="is_inbox_tab" />}
  1019. </React.Fragment>
  1020. );
  1021. }
  1022. }
  1023. export default withApi(
  1024. withGlobalSelection(
  1025. withSavedSearches(withOrganization(withIssueTags(withProfiler(IssueListOverview))))
  1026. )
  1027. );
  1028. export {IssueListOverview};
  1029. // TODO(workflow): Replace PageContent with thirds body
  1030. const StyledPageContent = styled(PageContent)`
  1031. display: flex;
  1032. flex-direction: row;
  1033. background-color: ${p => p.theme.background};
  1034. @media (max-width: ${p => p.theme.breakpoints[0]}) {
  1035. /* Matches thirds layout */
  1036. padding: ${space(2)} ${space(2)} 0 ${space(2)};
  1037. }
  1038. `;
  1039. const StreamContent = styled('div')<{showSidebar: boolean}>`
  1040. width: ${p => (p.showSidebar ? '75%' : '100%')};
  1041. transition: width 0.2s ease-in-out;
  1042. @media (max-width: ${p => p.theme.breakpoints[0]}) {
  1043. width: 100%;
  1044. }
  1045. `;
  1046. const SidebarContainer = styled('div')<{showSidebar: boolean}>`
  1047. display: ${p => (p.showSidebar ? 'block' : 'none')};
  1048. overflow: ${p => (p.showSidebar ? 'visible' : 'hidden')};
  1049. height: ${p => (p.showSidebar ? 'auto' : 0)};
  1050. width: ${p => (p.showSidebar ? '25%' : 0)};
  1051. transition: width 0.2s ease-in-out;
  1052. margin-left: 20px;
  1053. @media (max-width: ${p => p.theme.breakpoints[0]}) {
  1054. display: none;
  1055. }
  1056. `;
  1057. const PaginationWrapper = styled('div')`
  1058. display: flex;
  1059. justify-content: flex-end;
  1060. align-items: center;
  1061. font-size: ${p => p.theme.fontSizeMedium};
  1062. `;
  1063. const StyledPagination = styled(Pagination)`
  1064. margin-top: 0;
  1065. margin-left: ${space(2)};
  1066. `;
  1067. const StyledQueryCount = styled(QueryCount)`
  1068. margin-left: 0;
  1069. `;