overview.tsx 37 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180
  1. import {useCallback, useEffect, useMemo, useRef, useState} from 'react';
  2. import styled from '@emotion/styled';
  3. import * as Sentry from '@sentry/react';
  4. import type {Location} from 'history';
  5. import Cookies from 'js-cookie';
  6. import isEqual from 'lodash/isEqual';
  7. import mapValues from 'lodash/mapValues';
  8. import omit from 'lodash/omit';
  9. import pickBy from 'lodash/pickBy';
  10. import moment from 'moment-timezone';
  11. import * as qs from 'query-string';
  12. import {addMessage} from 'sentry/actionCreators/indicator';
  13. import {fetchOrgMembers, indexMembersByProject} from 'sentry/actionCreators/members';
  14. import ErrorBoundary from 'sentry/components/errorBoundary';
  15. import * as Layout from 'sentry/components/layouts/thirds';
  16. import {extractSelectionParameters} from 'sentry/components/organizations/pageFilters/utils';
  17. import type {CursorHandler} from 'sentry/components/pagination';
  18. import QueryCount from 'sentry/components/queryCount';
  19. import {DEFAULT_QUERY, DEFAULT_STATS_PERIOD} from 'sentry/constants';
  20. import {t, tct} from 'sentry/locale';
  21. import GroupStore from 'sentry/stores/groupStore';
  22. import IssueListCacheStore from 'sentry/stores/IssueListCacheStore';
  23. import SelectedGroupStore from 'sentry/stores/selectedGroupStore';
  24. import {useLegacyStore} from 'sentry/stores/useLegacyStore';
  25. import {space} from 'sentry/styles/space';
  26. import type {PageFilters} from 'sentry/types/core';
  27. import type {BaseGroup, Group, PriorityLevel, SavedSearch} from 'sentry/types/group';
  28. import {GroupStatus, IssueCategory} from 'sentry/types/group';
  29. import type {RouteComponentProps} from 'sentry/types/legacyReactRouter';
  30. import {defined} from 'sentry/utils';
  31. import {trackAnalytics} from 'sentry/utils/analytics';
  32. import CursorPoller from 'sentry/utils/cursorPoller';
  33. import {getUtcDateString} from 'sentry/utils/dates';
  34. import getCurrentSentryReactRootSpan from 'sentry/utils/getCurrentSentryReactRootSpan';
  35. import parseApiError from 'sentry/utils/parseApiError';
  36. import parseLinkHeader from 'sentry/utils/parseLinkHeader';
  37. import {makeIssuesINPObserver} from 'sentry/utils/performanceForSentry';
  38. import {decodeScalar} from 'sentry/utils/queryString';
  39. import useDisableRouteAnalytics from 'sentry/utils/routeAnalytics/useDisableRouteAnalytics';
  40. import useRouteAnalyticsParams from 'sentry/utils/routeAnalytics/useRouteAnalyticsParams';
  41. import normalizeUrl from 'sentry/utils/url/normalizeUrl';
  42. import useApi from 'sentry/utils/useApi';
  43. import {useLocation} from 'sentry/utils/useLocation';
  44. import {useNavigate} from 'sentry/utils/useNavigate';
  45. import useOrganization from 'sentry/utils/useOrganization';
  46. import usePageFilters from 'sentry/utils/usePageFilters';
  47. import {useParams} from 'sentry/utils/useParams';
  48. import usePrevious from 'sentry/utils/usePrevious';
  49. import IssueListTable from 'sentry/views/issueList/issueListTable';
  50. import {IssuesDataConsentBanner} from 'sentry/views/issueList/issuesDataConsentBanner';
  51. import IssueViewsIssueListHeader from 'sentry/views/issueList/issueViewsHeader';
  52. import {useFetchSavedSearchesForOrg} from 'sentry/views/issueList/queries/useFetchSavedSearchesForOrg';
  53. import SavedIssueSearches from 'sentry/views/issueList/savedIssueSearches';
  54. import type {IssueUpdateData} from 'sentry/views/issueList/types';
  55. import {NewTabContextProvider} from 'sentry/views/issueList/utils/newTabContext';
  56. import {parseIssuePrioritySearch} from 'sentry/views/issueList/utils/parseIssuePrioritySearch';
  57. import {useSelectedSavedSearch} from 'sentry/views/issueList/utils/useSelectedSavedSearch';
  58. import IssueListFilters from './filters';
  59. import IssueListHeader from './header';
  60. import type {QueryCounts} from './utils';
  61. import {
  62. DEFAULT_ISSUE_STREAM_SORT,
  63. FOR_REVIEW_QUERIES,
  64. getTabs,
  65. getTabsWithCounts,
  66. isForReviewQuery,
  67. IssueSortOptions,
  68. Query,
  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 Props = RouteComponentProps<{}, {searchId?: string}>;
  78. interface EndpointParams extends Partial<PageFilters['datetime']> {
  79. environment: string[];
  80. project: number[];
  81. cursor?: string;
  82. groupStatsPeriod?: string | null;
  83. page?: number | string;
  84. query?: string;
  85. sort?: string;
  86. statsPeriod?: string | null;
  87. useGroupSnubaDataset?: boolean;
  88. }
  89. type CountsEndpointParams = Omit<EndpointParams, 'cursor' | 'page' | 'query'> & {
  90. query: string[];
  91. };
  92. type StatEndpointParams = Omit<EndpointParams, 'cursor' | 'page'> & {
  93. groups: string[];
  94. expand?: string | string[];
  95. };
  96. function useIssuesINPObserver() {
  97. const _performanceObserver = useRef<PerformanceObserver | undefined>(undefined);
  98. useEffect(() => {
  99. _performanceObserver.current = makeIssuesINPObserver();
  100. return () => {
  101. if (_performanceObserver.current) {
  102. _performanceObserver.current.disconnect();
  103. }
  104. };
  105. }, []);
  106. }
  107. function useSavedSearches() {
  108. const organization = useOrganization();
  109. const {data: savedSearches = [], isPending} = useFetchSavedSearchesForOrg(
  110. {
  111. orgSlug: organization.slug,
  112. },
  113. {enabled: !organization.features.includes('issue-stream-custom-views')}
  114. );
  115. const params = useParams();
  116. const selectedSavedSearch = useSelectedSavedSearch();
  117. return {
  118. savedSearches,
  119. savedSearchLoading:
  120. !organization.features.includes('issue-stream-custom-views') && isPending,
  121. savedSearch: selectedSavedSearch,
  122. selectedSearchId: params.searchId ?? null,
  123. };
  124. }
  125. const parsePageQueryParam = (location: Location, defaultPage: number = 0) => {
  126. const page = location.query.page;
  127. const pageInt = Array.isArray(page)
  128. ? parseInt(page[0] ?? '', 10)
  129. : parseInt(page ?? '', 10);
  130. if (isNaN(pageInt)) {
  131. return defaultPage;
  132. }
  133. return pageInt;
  134. };
  135. function IssueListOverview({router}: Props) {
  136. const location = useLocation();
  137. const organization = useOrganization();
  138. const navigate = useNavigate();
  139. const {selection} = usePageFilters();
  140. const api = useApi();
  141. const realtimeActiveCookie = Cookies.get('realtimeActive');
  142. const [realtimeActive, setRealtimeActive] = useState(
  143. typeof realtimeActiveCookie === 'undefined' ? false : realtimeActiveCookie === 'true'
  144. );
  145. const [groupIds, setGroupIds] = useState<string[]>([]);
  146. const [pageLinks, setPageLinks] = useState('');
  147. const [queryCount, setQueryCount] = useState(0);
  148. const [queryCounts, setQueryCounts] = useState<QueryCounts>({});
  149. const [queryMaxCount, setQueryMaxCount] = useState(0);
  150. const [error, setError] = useState<string | null>(null);
  151. const [issuesLoading, setIssuesLoading] = useState(true);
  152. const [memberList, setMemberList] = useState<ReturnType<typeof indexMembersByProject>>(
  153. {}
  154. );
  155. const undoRef = useRef(false);
  156. const pollerRef = useRef<CursorPoller | undefined>(undefined);
  157. const actionTakenRef = useRef(false);
  158. const {savedSearch, savedSearchLoading, savedSearches, selectedSearchId} =
  159. useSavedSearches();
  160. const groups = useLegacyStore(GroupStore);
  161. useEffect(() => {
  162. const storeGroupIds = groups.map(group => group.id).slice(0, MAX_ISSUES_COUNT);
  163. if (!isEqual(groupIds, storeGroupIds)) {
  164. setGroupIds(storeGroupIds);
  165. }
  166. // eslint-disable-next-line react-hooks/exhaustive-deps
  167. }, [groups]);
  168. useIssuesINPObserver();
  169. const onRealtimePoll = useCallback(
  170. (data: any, {queryCount: newQueryCount}: {queryCount: number}) => {
  171. // Note: We do not update state with cursors from polling,
  172. // `CursorPoller` updates itself with new cursors
  173. GroupStore.addToFront(data);
  174. setQueryCount(newQueryCount);
  175. },
  176. []
  177. );
  178. useEffect(() => {
  179. pollerRef.current = new CursorPoller({
  180. linkPreviousHref: parseLinkHeader(pageLinks)?.previous?.href!,
  181. success: onRealtimePoll,
  182. });
  183. }, [onRealtimePoll, pageLinks]);
  184. const getQueryFromSavedSearchOrLocation = useCallback(
  185. (props: {location: Location; savedSearch: SavedSearch | null}): string => {
  186. if (
  187. !organization.features.includes('issue-stream-custom-views') &&
  188. props.savedSearch
  189. ) {
  190. return props.savedSearch.query;
  191. }
  192. const {query} = props.location.query;
  193. if (query !== undefined) {
  194. return decodeScalar(query, '');
  195. }
  196. return DEFAULT_QUERY;
  197. },
  198. [organization.features]
  199. );
  200. const getSortFromSavedSearchOrLocation = useCallback(
  201. (props: {location: Location; savedSearch: SavedSearch | null}): string => {
  202. if (!props.location.query.sort && props.savedSearch?.id) {
  203. return props.savedSearch.sort;
  204. }
  205. if (props.location.query.sort) {
  206. return props.location.query.sort as string;
  207. }
  208. return DEFAULT_ISSUE_STREAM_SORT;
  209. },
  210. []
  211. );
  212. const query = useMemo((): string => {
  213. return getQueryFromSavedSearchOrLocation({
  214. savedSearch,
  215. location,
  216. });
  217. }, [getQueryFromSavedSearchOrLocation, savedSearch, location]);
  218. const sort = useMemo((): string => {
  219. return getSortFromSavedSearchOrLocation({
  220. savedSearch,
  221. location,
  222. });
  223. }, [getSortFromSavedSearchOrLocation, savedSearch, location]);
  224. const getGroupStatsPeriod = useCallback((): string => {
  225. let currentPeriod: string;
  226. if (typeof location.query?.groupStatsPeriod === 'string') {
  227. currentPeriod = location.query.groupStatsPeriod;
  228. } else {
  229. currentPeriod = DEFAULT_GRAPH_STATS_PERIOD;
  230. }
  231. return DYNAMIC_COUNTS_STATS_PERIODS.has(currentPeriod)
  232. ? currentPeriod
  233. : DEFAULT_GRAPH_STATS_PERIOD;
  234. }, [location]);
  235. const getEndpointParams = useCallback((): EndpointParams => {
  236. const params: EndpointParams = {
  237. project: selection.projects,
  238. environment: selection.environments,
  239. query,
  240. ...selection.datetime,
  241. };
  242. if (selection.datetime.period) {
  243. delete params.period;
  244. params.statsPeriod = selection.datetime.period;
  245. }
  246. if (params.end) {
  247. params.end = getUtcDateString(params.end);
  248. }
  249. if (params.start) {
  250. params.start = getUtcDateString(params.start);
  251. }
  252. if (sort !== DEFAULT_ISSUE_STREAM_SORT) {
  253. params.sort = sort;
  254. }
  255. const groupStatsPeriod = getGroupStatsPeriod();
  256. if (groupStatsPeriod !== DEFAULT_GRAPH_STATS_PERIOD) {
  257. params.groupStatsPeriod = groupStatsPeriod;
  258. }
  259. if (location.query.useGroupSnubaDataset) {
  260. params.useGroupSnubaDataset = true;
  261. }
  262. // only include defined values.
  263. return pickBy(params, v => defined(v)) as EndpointParams;
  264. }, [selection, location, query, sort, getGroupStatsPeriod]);
  265. const requestParams = useMemo(() => {
  266. // Used for Issue Stream Performance project, enabled means we are doing saved search look up in the backend
  267. const savedSearchLookupEnabled = 0;
  268. const savedSearchLookupDisabled = 1;
  269. const params: any = {
  270. ...getEndpointParams(),
  271. limit: MAX_ITEMS,
  272. shortIdLookup: 1,
  273. savedSearch: savedSearchLoading
  274. ? savedSearchLookupEnabled
  275. : savedSearchLookupDisabled,
  276. };
  277. if (selectedSearchId) {
  278. params.searchId = selectedSearchId;
  279. }
  280. if (savedSearchLoading && !defined(location.query.query)) {
  281. delete params.query;
  282. }
  283. const currentQuery = location.query || {};
  284. if ('cursor' in currentQuery) {
  285. params.cursor = currentQuery.cursor;
  286. }
  287. // If no stats period values are set, use default
  288. if (!params.statsPeriod && !params.start) {
  289. params.statsPeriod = DEFAULT_STATS_PERIOD;
  290. }
  291. params.expand = ['owners', 'inbox'];
  292. params.collapse = ['stats', 'unhandled'];
  293. return params;
  294. }, [getEndpointParams, location.query, savedSearchLoading, selectedSearchId]);
  295. const loadFromCache = useCallback((): boolean => {
  296. const cache = IssueListCacheStore.getFromCache(requestParams);
  297. if (!cache) {
  298. return false;
  299. }
  300. setIssuesLoading(false);
  301. setQueryCount(cache.queryCount);
  302. setQueryMaxCount(cache.queryMaxCount);
  303. setPageLinks(cache.pageLinks);
  304. GroupStore.add(cache.groups);
  305. return true;
  306. }, [requestParams]);
  307. const resumePolling = useCallback(() => {
  308. if (!pageLinks) {
  309. return;
  310. }
  311. // Only resume polling if we're on the first page of results
  312. const links = parseLinkHeader(pageLinks);
  313. if (links && !links.previous!.results && realtimeActive) {
  314. pollerRef.current?.setEndpoint(links?.previous!.href);
  315. pollerRef.current?.enable();
  316. }
  317. }, [pageLinks, realtimeActive]);
  318. const trackTabViewed = useCallback(
  319. (newGroupIds: string[], data: Group[], numHits: number | null) => {
  320. const endpointParams = getEndpointParams();
  321. const tabQueriesWithCounts = getTabsWithCounts();
  322. const currentTabQuery = tabQueriesWithCounts.includes(endpointParams.query as Query)
  323. ? endpointParams.query
  324. : null;
  325. const tab = getTabs().find(([tabQuery]) => currentTabQuery === tabQuery)?.[1];
  326. const numPerfIssues = newGroupIds.filter(
  327. groupId => GroupStore.get(groupId)?.issueCategory === IssueCategory.PERFORMANCE
  328. ).length;
  329. // First and last seen are only available after the group has fetched stats
  330. // Number of issues shown whose first seen is more than 30 days ago
  331. const numOldIssues = data.filter((group: BaseGroup) =>
  332. moment(new Date(group.firstSeen)).isBefore(moment().subtract(30, 'd'))
  333. ).length;
  334. // number of issues shown whose first seen is less than 7 days
  335. const numNewIssues = data.filter((group: BaseGroup) =>
  336. moment(new Date(group.firstSeen)).isAfter(moment().subtract(7, 'd'))
  337. ).length;
  338. trackAnalytics('issues_tab.viewed', {
  339. organization,
  340. tab: tab?.analyticsName,
  341. page: parsePageQueryParam(location, 0),
  342. query,
  343. num_perf_issues: numPerfIssues,
  344. num_old_issues: numOldIssues,
  345. num_new_issues: numNewIssues,
  346. num_issues: data.length,
  347. total_issues_count: numHits,
  348. issue_views_enabled: organization.features.includes('issue-stream-custom-views'),
  349. sort,
  350. });
  351. },
  352. [organization, location, getEndpointParams, query, sort]
  353. );
  354. const fetchCounts = useCallback(
  355. (currentQueryCount: number, fetchAllCounts: boolean) => {
  356. const newQueryCounts: QueryCounts = {...queryCounts};
  357. const endpointParams = getEndpointParams();
  358. const tabQueriesWithCounts = getTabsWithCounts();
  359. const currentTabQuery = tabQueriesWithCounts.includes(endpointParams.query as Query)
  360. ? endpointParams.query
  361. : null;
  362. // Update the count based on the exact number of issues, these shown as is
  363. if (currentTabQuery) {
  364. // @ts-expect-error TS(7053): Element implicitly has an 'any' type because expre... Remove this comment to see the full error message
  365. newQueryCounts[currentTabQuery] = {
  366. count: currentQueryCount,
  367. hasMore: false,
  368. };
  369. }
  370. setQueryCounts(newQueryCounts);
  371. // If all tabs' counts are fetched, skip and only set
  372. if (
  373. fetchAllCounts ||
  374. // @ts-expect-error TS(7053): Element implicitly has an 'any' type because expre... Remove this comment to see the full error message
  375. !tabQueriesWithCounts.every(tabQuery => newQueryCounts[tabQuery] !== undefined)
  376. ) {
  377. const countsRequestParams: CountsEndpointParams = {
  378. ...omit(endpointParams, 'query'),
  379. // fetch the counts for the tabs whose counts haven't been fetched yet
  380. query: tabQueriesWithCounts.filter(_query => _query !== currentTabQuery),
  381. };
  382. // If no stats period values are set, use default
  383. if (!countsRequestParams.statsPeriod && !countsRequestParams.start) {
  384. countsRequestParams.statsPeriod = DEFAULT_STATS_PERIOD;
  385. }
  386. api.request(`/organizations/${organization.slug}/issues-count/`, {
  387. method: 'GET',
  388. data: qs.stringify(countsRequestParams),
  389. success: data => {
  390. if (!data) {
  391. return;
  392. }
  393. setQueryCounts({
  394. ...newQueryCounts,
  395. ...mapValues(data, (count: number | null) => ({
  396. count: count ?? 0,
  397. // Counts coming from the counts endpoint is limited to 100, for >= 100 we display 99+
  398. hasMore: (count ?? 0) > TAB_MAX_COUNT,
  399. })),
  400. });
  401. },
  402. error: () => {
  403. setQueryCounts({});
  404. },
  405. });
  406. }
  407. },
  408. [api, getEndpointParams, organization.slug, queryCounts]
  409. );
  410. const fetchStats = useCallback(
  411. async (newGroupIds: string[]) => {
  412. // If we have no groups to fetch, just skip stats
  413. if (!newGroupIds.length) {
  414. return;
  415. }
  416. const statsRequestParams: StatEndpointParams = {
  417. ...getEndpointParams(),
  418. groups: newGroupIds,
  419. };
  420. // If no stats period values are set, use default
  421. if (!statsRequestParams.statsPeriod && !statsRequestParams.start) {
  422. statsRequestParams.statsPeriod = DEFAULT_STATS_PERIOD;
  423. }
  424. try {
  425. const data = await api.requestPromise(
  426. `/organizations/${organization.slug}/issues-stats/`,
  427. {
  428. method: 'GET',
  429. data: qs.stringify(statsRequestParams),
  430. }
  431. );
  432. if (data) {
  433. GroupStore.onPopulateStats(newGroupIds, data);
  434. trackTabViewed(newGroupIds, data, queryCount);
  435. }
  436. } catch (e) {
  437. setError(parseApiError(e));
  438. } finally {
  439. // End navigation transaction to prevent additional page requests from impacting page metrics.
  440. // Other transactions include stacktrace preview request
  441. const currentSpan = Sentry.getActiveSpan();
  442. const rootSpan = currentSpan ? Sentry.getRootSpan(currentSpan) : undefined;
  443. if (rootSpan && Sentry.spanToJSON(rootSpan).op === 'navigation') {
  444. rootSpan.end();
  445. }
  446. }
  447. },
  448. [getEndpointParams, api, organization.slug, trackTabViewed, queryCount]
  449. );
  450. const fetchData = useCallback(
  451. (fetchAllCounts = false) => {
  452. if (realtimeActive || (!actionTakenRef.current && !undoRef.current)) {
  453. GroupStore.loadInitialData([]);
  454. setIssuesLoading(true);
  455. setQueryCount(0);
  456. setError(null);
  457. }
  458. const span = getCurrentSentryReactRootSpan();
  459. span?.setAttribute('query.sort', sort);
  460. setError(null);
  461. api.clear();
  462. pollerRef.current?.disable();
  463. api.request(`/organizations/${organization.slug}/issues/`, {
  464. method: 'GET',
  465. data: qs.stringify(requestParams),
  466. success: async (data, _, resp) => {
  467. if (!resp) {
  468. return;
  469. }
  470. // If this is a direct hit, we redirect to the intended result directly.
  471. if (resp.getResponseHeader('X-Sentry-Direct-Hit') === '1') {
  472. let redirect: string;
  473. if (data[0]?.matchingEventId) {
  474. const {id, matchingEventId} = data[0];
  475. redirect = `/organizations/${organization.slug}/issues/${id}/events/${matchingEventId}/`;
  476. } else {
  477. const {id} = data[0];
  478. redirect = `/organizations/${organization.slug}/issues/${id}/`;
  479. }
  480. navigate(
  481. normalizeUrl({
  482. pathname: redirect,
  483. query: {
  484. referrer: 'issue-list',
  485. ...extractSelectionParameters(location.query),
  486. },
  487. }),
  488. {replace: true}
  489. );
  490. return;
  491. }
  492. if (undoRef.current) {
  493. GroupStore.loadInitialData(data);
  494. }
  495. GroupStore.add(data);
  496. if (data.length === 0) {
  497. trackAnalytics('issue_search.empty', {
  498. organization,
  499. search_type: 'issues',
  500. search_source: 'main_search',
  501. query,
  502. });
  503. }
  504. const hits = resp.getResponseHeader('X-Hits');
  505. const newQueryCount =
  506. typeof hits !== 'undefined' && hits ? parseInt(hits, 10) || 0 : 0;
  507. const maxHits = resp.getResponseHeader('X-Max-Hits');
  508. const newQueryMaxCount =
  509. typeof maxHits !== 'undefined' && maxHits ? parseInt(maxHits, 10) || 0 : 0;
  510. const newPageLinks = resp.getResponseHeader('Link');
  511. setError(null);
  512. setIssuesLoading(false);
  513. setQueryCount(newQueryCount);
  514. setQueryMaxCount(newQueryMaxCount);
  515. setPageLinks(newPageLinks !== null ? newPageLinks : '');
  516. fetchCounts(newQueryCount, fetchAllCounts);
  517. // Need to wait for stats request to finish before saving to cache
  518. await fetchStats(data.map((group: BaseGroup) => group.id));
  519. IssueListCacheStore.save(requestParams, {
  520. groups: GroupStore.getState() as Group[],
  521. queryCount: newQueryCount,
  522. queryMaxCount: newQueryMaxCount,
  523. pageLinks: newPageLinks ?? '',
  524. });
  525. },
  526. error: err => {
  527. trackAnalytics('issue_search.failed', {
  528. organization,
  529. search_type: 'issues',
  530. search_source: 'main_search',
  531. error: parseApiError(err),
  532. });
  533. setError(parseApiError(err));
  534. setIssuesLoading(false);
  535. },
  536. complete: () => {
  537. resumePolling();
  538. if (!realtimeActive) {
  539. actionTakenRef.current = false;
  540. undoRef.current = false;
  541. }
  542. },
  543. });
  544. },
  545. [
  546. realtimeActive,
  547. sort,
  548. api,
  549. organization,
  550. requestParams,
  551. fetchStats,
  552. fetchCounts,
  553. navigate,
  554. location.query,
  555. query,
  556. resumePolling,
  557. ]
  558. );
  559. useRouteAnalyticsParams({
  560. issue_views_enabled: organization.features.includes('issue-stream-custom-views'),
  561. });
  562. useDisableRouteAnalytics();
  563. // Update polling status
  564. useEffect(() => {
  565. if (realtimeActive) {
  566. resumePolling();
  567. } else {
  568. pollerRef.current?.disable();
  569. }
  570. }, [realtimeActive, resumePolling]);
  571. // Fetch data on mount if necessary
  572. useEffect(() => {
  573. const loadedFromCache = loadFromCache();
  574. if (!loadedFromCache) {
  575. // It's possible the projects query parameter is not yet ready and this
  576. // request will be repeated in componentDidUpdate
  577. fetchData();
  578. }
  579. // eslint-disable-next-line react-hooks/exhaustive-deps
  580. }, []);
  581. const previousSelection = usePrevious(selection);
  582. const previousSavedSearchLoading = usePrevious(savedSearchLoading);
  583. const previousIssuesLoading = usePrevious(issuesLoading);
  584. const previousRequestParams = usePrevious(requestParams);
  585. // Keep data up to date
  586. useEffect(() => {
  587. const selectionChanged = !isEqual(previousSelection, selection);
  588. // Wait for saved searches to load before we attempt to fetch stream data
  589. // Selection changing could indicate that the projects query parameter has populated
  590. // and we should refetch data.
  591. if (savedSearchLoading && !selectionChanged) {
  592. return;
  593. }
  594. if (previousSavedSearchLoading && !savedSearchLoading) {
  595. return;
  596. }
  597. // If any important url parameter changed or saved search changed
  598. // reload data.
  599. if (!isEqual(previousRequestParams, requestParams)) {
  600. fetchData(selectionChanged);
  601. }
  602. }, [
  603. fetchData,
  604. savedSearchLoading,
  605. selection,
  606. previousSelection,
  607. organization.features,
  608. issuesLoading,
  609. loadFromCache,
  610. previousSavedSearchLoading,
  611. previousIssuesLoading,
  612. previousRequestParams,
  613. requestParams,
  614. ]);
  615. // Fetch members on mount
  616. useEffect(() => {
  617. const projectIds = selection.projects.map(projectId => String(projectId));
  618. fetchOrgMembers(api, organization.slug, projectIds).then(members => {
  619. setMemberList(indexMembersByProject(members));
  620. });
  621. // eslint-disable-next-line react-hooks/exhaustive-deps
  622. }, []);
  623. // If the project selection has changed reload the member list and tag keys
  624. // allowing autocomplete and tag sidebar to be more accurate.
  625. useEffect(() => {
  626. if (isEqual(previousSelection?.projects, selection.projects)) {
  627. return;
  628. }
  629. const projectIds = selection.projects.map(projectId => String(projectId));
  630. fetchOrgMembers(api, organization.slug, projectIds).then(members => {
  631. setMemberList(indexMembersByProject(members));
  632. });
  633. }, [api, organization.slug, selection.projects, previousSelection?.projects]);
  634. // Cleanup
  635. useEffect(() => {
  636. return () => {
  637. pollerRef.current?.disable();
  638. SelectedGroupStore.reset();
  639. GroupStore.reset();
  640. };
  641. }, []);
  642. const allResultsVisible = useCallback(() => {
  643. if (!pageLinks) {
  644. return false;
  645. }
  646. const links = parseLinkHeader(pageLinks);
  647. return links && !links.previous!.results && !links.next!.results;
  648. }, [pageLinks]);
  649. const getPageCounts = useCallback(() => {
  650. const links = parseLinkHeader(pageLinks);
  651. const queryPageInt = parsePageQueryParam(location, 0);
  652. // Cursor must be present for the page number to be used
  653. const page = !location.query.cursor ? 0 : queryPageInt;
  654. let numPreviousIssues = Math.min(page * MAX_ITEMS, queryCount);
  655. // Because the query param `page` is not tied to the request, we need to
  656. // validate that it's correct at the first and last page
  657. if (!links?.next?.results || allResultsVisible()) {
  658. // On last available page
  659. numPreviousIssues = Math.max(queryCount - groupIds.length, 0);
  660. } else if (!links?.previous?.results) {
  661. // On first available page
  662. numPreviousIssues = 0;
  663. }
  664. return {
  665. numPreviousIssues,
  666. numIssuesOnPage: groupIds.length,
  667. };
  668. }, [pageLinks, location, queryCount, allResultsVisible, groupIds.length]);
  669. const onRealtimeChange = useCallback(
  670. (realtime: boolean) => {
  671. Cookies.set('realtimeActive', realtime.toString());
  672. setRealtimeActive(realtime);
  673. trackAnalytics('issues_stream.realtime_clicked', {
  674. organization,
  675. enabled: realtime,
  676. });
  677. },
  678. [organization]
  679. );
  680. const transitionTo = (
  681. newParams: Partial<EndpointParams> = {},
  682. newSavedSearch: (SavedSearch & {projectId?: number}) | null = savedSearch
  683. ) => {
  684. const queryData = {
  685. ...omit(location.query, ['page', 'cursor']),
  686. referrer: 'issue-list',
  687. ...getEndpointParams(),
  688. ...newParams,
  689. };
  690. let path: string;
  691. if (newSavedSearch?.id) {
  692. path = `/organizations/${organization.slug}/issues/searches/${newSavedSearch.id}/`;
  693. // Remove the query as saved searches bring their own query string.
  694. delete queryData.query;
  695. // If we aren't going to another page in the same search
  696. // drop the query and replace the current project, with the saved search search project
  697. // if available.
  698. if (!queryData.cursor && newSavedSearch.projectId) {
  699. queryData.project = [newSavedSearch.projectId];
  700. }
  701. if (!queryData.cursor && !newParams.sort && newSavedSearch.sort) {
  702. queryData.sort = newSavedSearch.sort;
  703. }
  704. } else {
  705. path = `/organizations/${organization.slug}/issues/`;
  706. }
  707. if (
  708. queryData.sort === IssueSortOptions.INBOX &&
  709. !FOR_REVIEW_QUERIES.includes(queryData.query || '')
  710. ) {
  711. delete queryData.sort;
  712. }
  713. if (path !== location.pathname || !isEqual(query, location.query)) {
  714. navigate({
  715. pathname: normalizeUrl(path),
  716. query: queryData,
  717. });
  718. setIssuesLoading(true);
  719. }
  720. };
  721. const onSearch = (newQuery: string) => {
  722. if (newQuery === query) {
  723. // if query is the same, just re-fetch data
  724. fetchData();
  725. } else {
  726. // Clear the saved search as the user wants something else.
  727. transitionTo({query: newQuery}, null);
  728. }
  729. };
  730. const onSortChange = (newSort: string) => {
  731. trackAnalytics('issues_stream.sort_changed', {
  732. organization,
  733. sort: newSort,
  734. });
  735. transitionTo({sort: newSort});
  736. };
  737. const onCursorChange: CursorHandler = (nextCursor, _path, _query, delta) => {
  738. const queryPageInt = Array.isArray(location.query.page)
  739. ? NaN
  740. : parseInt(location.query.page?.toString() ?? '', 10);
  741. let nextPage: number | undefined = isNaN(queryPageInt) ? delta : queryPageInt + delta;
  742. let cursor: undefined | string = nextCursor;
  743. // unset cursor and page when we navigate back to the first page
  744. // also reset cursor if somehow the previous button is enabled on
  745. // first page and user attempts to go backwards
  746. if (nextPage <= 0) {
  747. cursor = undefined;
  748. nextPage = undefined;
  749. }
  750. transitionTo({cursor, page: nextPage});
  751. };
  752. const onSelectStatsPeriod = (period: string) => {
  753. if (period !== getGroupStatsPeriod()) {
  754. const cursor = Array.isArray(location.query.cursor)
  755. ? location.query.cursor[0]
  756. : location.query.cursor ?? undefined;
  757. const queryPageInt = parsePageQueryParam(location, 0);
  758. const page = !location.query.cursor ? 0 : queryPageInt;
  759. transitionTo({cursor, page, groupStatsPeriod: period});
  760. }
  761. };
  762. const undoAction = ({
  763. data,
  764. groupItems,
  765. }: {
  766. data: IssueUpdateData;
  767. groupItems: BaseGroup[];
  768. }) => {
  769. const projectIds = selection?.projects?.map(p => p.toString());
  770. const endpoint = `/organizations/${organization.slug}/issues/`;
  771. api.clear();
  772. api.request(endpoint, {
  773. method: 'PUT',
  774. data,
  775. query: {
  776. project: projectIds,
  777. id: groupItems.map(group => group.id),
  778. },
  779. success: response => {
  780. if (!response) {
  781. return;
  782. }
  783. // If on the Ignore or For Review tab, adding back to the GroupStore will make the issue show up
  784. // on this page for a second and then be removed (will show up on All Unresolved). This is to
  785. // stop this from happening and avoid confusion.
  786. if (!query.includes('is:ignored') && !isForReviewQuery(query)) {
  787. GroupStore.add(groupItems);
  788. }
  789. actionTakenRef.current = true;
  790. },
  791. error: err => {
  792. setError(parseApiError(err));
  793. setIssuesLoading(false);
  794. },
  795. complete: () => {
  796. fetchData(true);
  797. },
  798. });
  799. };
  800. const onIssueAction = ({
  801. itemIds,
  802. actionType,
  803. shouldRemove,
  804. undo,
  805. }: {
  806. actionType: 'Reviewed' | 'Resolved' | 'Ignored' | 'Archived' | 'Reprioritized';
  807. itemIds: string[];
  808. shouldRemove: boolean;
  809. undo?: () => void;
  810. }) => {
  811. if (itemIds.length > 1) {
  812. addMessage(`${actionType} ${itemIds.length} ${t('Issues')}`, 'success', {
  813. duration: 4000,
  814. undo,
  815. });
  816. } else {
  817. const shortId = itemIds.map(item => GroupStore.get(item)?.shortId).toString();
  818. addMessage(`${actionType} ${shortId}`, 'success', {
  819. duration: 4000,
  820. undo,
  821. });
  822. }
  823. if (!shouldRemove) {
  824. return;
  825. }
  826. const links = parseLinkHeader(pageLinks);
  827. GroupStore.remove(itemIds);
  828. const newQueryCount = queryCount - itemIds.length;
  829. actionTakenRef.current = true;
  830. setQueryCount(newQueryCount);
  831. if (GroupStore.getAllItemIds().length === 0) {
  832. // If we run out of issues on the last page, navigate back a page to
  833. // avoid showing an empty state - if not on the last page, just show a spinner
  834. const shouldGoBackAPage = links?.previous?.results && !links?.next?.results;
  835. transitionTo({cursor: shouldGoBackAPage ? links.previous!.cursor : undefined});
  836. fetchCounts(newQueryCount, true);
  837. } else {
  838. fetchData(true);
  839. }
  840. };
  841. const onActionTaken = (itemIds: string[], data: IssueUpdateData) => {
  842. if (realtimeActive) {
  843. return;
  844. }
  845. const groupItems = itemIds.map(id => GroupStore.get(id)).filter(defined);
  846. if ('status' in data) {
  847. if (data.status === 'resolved') {
  848. onIssueAction({
  849. itemIds,
  850. actionType: 'Resolved',
  851. shouldRemove:
  852. query.includes('is:unresolved') ||
  853. query.includes('is:ignored') ||
  854. isForReviewQuery(query),
  855. undo: () =>
  856. undoAction({
  857. data: {status: GroupStatus.UNRESOLVED, statusDetails: {}},
  858. groupItems,
  859. }),
  860. });
  861. return;
  862. }
  863. if (data.status === 'ignored') {
  864. onIssueAction({
  865. itemIds,
  866. actionType: 'Archived',
  867. shouldRemove: query.includes('is:unresolved') || isForReviewQuery(query),
  868. undo: () =>
  869. undoAction({
  870. data: {status: GroupStatus.UNRESOLVED, statusDetails: {}},
  871. groupItems,
  872. }),
  873. });
  874. return;
  875. }
  876. }
  877. if ('inbox' in data && data.inbox === false) {
  878. onIssueAction({
  879. itemIds,
  880. actionType: 'Reviewed',
  881. shouldRemove: isForReviewQuery(query),
  882. });
  883. return;
  884. }
  885. if ('priority' in data && typeof data.priority === 'string') {
  886. const priorityValues = parseIssuePrioritySearch(query);
  887. const priority = data.priority.toLowerCase() as PriorityLevel;
  888. onIssueAction({
  889. itemIds,
  890. actionType: 'Reprioritized',
  891. shouldRemove: !priorityValues.has(priority),
  892. });
  893. return;
  894. }
  895. };
  896. const onDelete = () => {
  897. actionTakenRef.current = true;
  898. fetchData(true);
  899. };
  900. const paginationAnalyticsEvent = (direction: string) => {
  901. trackAnalytics('issues_stream.paginate', {
  902. organization,
  903. direction,
  904. });
  905. };
  906. const onSavedSearchSelect = (newSavedSearch: SavedSearch) => {
  907. trackAnalytics('organization_saved_search.selected', {
  908. organization,
  909. search_type: 'issues',
  910. id: newSavedSearch.id ? parseInt(newSavedSearch.id, 10) : -1,
  911. is_global: newSavedSearch.isGlobal,
  912. query: newSavedSearch.query,
  913. visibility: newSavedSearch.visibility,
  914. });
  915. setIssuesLoading(true);
  916. setTimeout(() => {
  917. transitionTo(undefined, newSavedSearch);
  918. }, 0);
  919. };
  920. const modifiedQueryCount = Math.max(queryCount, 0);
  921. // TODO: these two might still be in use for reprocessing2
  922. const showReprocessingTab = !!queryCounts?.[Query.REPROCESSING]?.count;
  923. const displayReprocessingActions = showReprocessingTab && query === Query.REPROCESSING;
  924. const {numPreviousIssues, numIssuesOnPage} = getPageCounts();
  925. return (
  926. <NewTabContextProvider>
  927. <Layout.Page>
  928. {organization.features.includes('issue-stream-custom-views') ? (
  929. <ErrorBoundary message={'Failed to load custom tabs'} mini>
  930. <IssueViewsIssueListHeader
  931. router={router}
  932. selectedProjectIds={selection.projects}
  933. realtimeActive={realtimeActive}
  934. onRealtimeChange={onRealtimeChange}
  935. />
  936. </ErrorBoundary>
  937. ) : (
  938. <IssueListHeader
  939. organization={organization}
  940. query={query}
  941. sort={sort}
  942. queryCount={queryCount}
  943. queryCounts={queryCounts}
  944. realtimeActive={realtimeActive}
  945. router={router}
  946. displayReprocessingTab={showReprocessingTab}
  947. selectedProjectIds={selection.projects}
  948. onRealtimeChange={onRealtimeChange}
  949. />
  950. )}
  951. <StyledBody>
  952. <StyledMain>
  953. <IssuesDataConsentBanner source="issues" />
  954. <IssueListFilters
  955. query={query}
  956. sort={sort}
  957. onSortChange={onSortChange}
  958. onSearch={onSearch}
  959. />
  960. <IssueListTable
  961. selection={selection}
  962. query={query}
  963. queryCount={modifiedQueryCount}
  964. onSelectStatsPeriod={onSelectStatsPeriod}
  965. onActionTaken={onActionTaken}
  966. onDelete={onDelete}
  967. statsPeriod={getGroupStatsPeriod()}
  968. groupIds={groupIds}
  969. allResultsVisible={allResultsVisible()}
  970. displayReprocessingActions={displayReprocessingActions}
  971. sort={sort}
  972. onSortChange={onSortChange}
  973. memberList={memberList}
  974. selectedProjectIds={selection.projects}
  975. issuesLoading={issuesLoading}
  976. error={error}
  977. refetchGroups={fetchData}
  978. paginationCaption={
  979. !issuesLoading && modifiedQueryCount > 0
  980. ? tct('[start]-[end] of [total]', {
  981. start: numPreviousIssues + 1,
  982. end: numPreviousIssues + numIssuesOnPage,
  983. total: (
  984. <QueryCount
  985. hideParens
  986. hideIfEmpty={false}
  987. count={modifiedQueryCount}
  988. max={queryMaxCount || 100}
  989. />
  990. ),
  991. })
  992. : null
  993. }
  994. pageLinks={pageLinks}
  995. onCursor={onCursorChange}
  996. paginationAnalyticsEvent={paginationAnalyticsEvent}
  997. personalSavedSearches={savedSearches?.filter(
  998. search => search.visibility === 'owner'
  999. )}
  1000. organizationSavedSearches={savedSearches?.filter(
  1001. search => search.visibility === 'organization'
  1002. )}
  1003. />
  1004. </StyledMain>
  1005. <SavedIssueSearches
  1006. {...{organization, query}}
  1007. onSavedSearchSelect={onSavedSearchSelect}
  1008. sort={sort}
  1009. />
  1010. </StyledBody>
  1011. </Layout.Page>
  1012. </NewTabContextProvider>
  1013. );
  1014. }
  1015. export default Sentry.withProfiler(IssueListOverview);
  1016. const StyledBody = styled('div')`
  1017. background-color: ${p => p.theme.background};
  1018. flex: 1;
  1019. display: grid;
  1020. gap: 0;
  1021. padding: 0;
  1022. grid-template-rows: 1fr;
  1023. grid-template-columns: minmax(0, 1fr) auto;
  1024. grid-template-areas: 'content saved-searches';
  1025. `;
  1026. const StyledMain = styled('section')`
  1027. grid-area: content;
  1028. padding: ${space(2)};
  1029. @media (min-width: ${p => p.theme.breakpoints.medium}) {
  1030. padding: ${space(3)} ${space(4)};
  1031. }
  1032. `;