overview.tsx 40 KB

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