overview.tsx 35 KB

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