overview.tsx 37 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183
  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. let 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 => queryCounts[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. // Counts coming from the counts endpoint is limited to 100, for >= 100 we display 99+
  394. newQueryCounts = {
  395. ...queryCounts,
  396. ...mapValues(data, (count: number) => ({
  397. count,
  398. hasMore: count > TAB_MAX_COUNT,
  399. })),
  400. };
  401. },
  402. error: () => {
  403. setQueryCounts({});
  404. },
  405. complete: () => {
  406. setQueryCounts(newQueryCounts);
  407. },
  408. });
  409. }
  410. },
  411. [api, getEndpointParams, organization.slug, queryCounts]
  412. );
  413. const fetchStats = useCallback(
  414. async (newGroupIds: string[]) => {
  415. // If we have no groups to fetch, just skip stats
  416. if (!newGroupIds.length) {
  417. return;
  418. }
  419. const statsRequestParams: StatEndpointParams = {
  420. ...getEndpointParams(),
  421. groups: newGroupIds,
  422. };
  423. // If no stats period values are set, use default
  424. if (!statsRequestParams.statsPeriod && !statsRequestParams.start) {
  425. statsRequestParams.statsPeriod = DEFAULT_STATS_PERIOD;
  426. }
  427. try {
  428. const data = await api.requestPromise(
  429. `/organizations/${organization.slug}/issues-stats/`,
  430. {
  431. method: 'GET',
  432. data: qs.stringify(statsRequestParams),
  433. }
  434. );
  435. if (data) {
  436. GroupStore.onPopulateStats(newGroupIds, data);
  437. trackTabViewed(newGroupIds, data, queryCount);
  438. }
  439. } catch (e) {
  440. setError(parseApiError(e));
  441. } finally {
  442. // End navigation transaction to prevent additional page requests from impacting page metrics.
  443. // Other transactions include stacktrace preview request
  444. const currentSpan = Sentry.getActiveSpan();
  445. const rootSpan = currentSpan ? Sentry.getRootSpan(currentSpan) : undefined;
  446. if (rootSpan && Sentry.spanToJSON(rootSpan).op === 'navigation') {
  447. rootSpan.end();
  448. }
  449. }
  450. },
  451. [getEndpointParams, api, organization.slug, trackTabViewed, queryCount]
  452. );
  453. const fetchData = useCallback(
  454. (fetchAllCounts = false) => {
  455. if (realtimeActive || (!actionTakenRef.current && !undoRef.current)) {
  456. GroupStore.loadInitialData([]);
  457. setIssuesLoading(true);
  458. setQueryCount(0);
  459. setError(null);
  460. }
  461. const span = getCurrentSentryReactRootSpan();
  462. span?.setAttribute('query.sort', sort);
  463. setError(null);
  464. api.clear();
  465. pollerRef.current?.disable();
  466. api.request(`/organizations/${organization.slug}/issues/`, {
  467. method: 'GET',
  468. data: qs.stringify(requestParams),
  469. success: async (data, _, resp) => {
  470. if (!resp) {
  471. return;
  472. }
  473. // If this is a direct hit, we redirect to the intended result directly.
  474. if (resp.getResponseHeader('X-Sentry-Direct-Hit') === '1') {
  475. let redirect: string;
  476. if (data[0]?.matchingEventId) {
  477. const {id, matchingEventId} = data[0];
  478. redirect = `/organizations/${organization.slug}/issues/${id}/events/${matchingEventId}/`;
  479. } else {
  480. const {id} = data[0];
  481. redirect = `/organizations/${organization.slug}/issues/${id}/`;
  482. }
  483. navigate(
  484. normalizeUrl({
  485. pathname: redirect,
  486. query: {
  487. referrer: 'issue-list',
  488. ...extractSelectionParameters(location.query),
  489. },
  490. }),
  491. {replace: true}
  492. );
  493. return;
  494. }
  495. if (undoRef.current) {
  496. GroupStore.loadInitialData(data);
  497. }
  498. GroupStore.add(data);
  499. if (data.length === 0) {
  500. trackAnalytics('issue_search.empty', {
  501. organization,
  502. search_type: 'issues',
  503. search_source: 'main_search',
  504. query,
  505. });
  506. }
  507. const hits = resp.getResponseHeader('X-Hits');
  508. const newQueryCount =
  509. typeof hits !== 'undefined' && hits ? parseInt(hits, 10) || 0 : 0;
  510. const maxHits = resp.getResponseHeader('X-Max-Hits');
  511. const newQueryMaxCount =
  512. typeof maxHits !== 'undefined' && maxHits ? parseInt(maxHits, 10) || 0 : 0;
  513. const newPageLinks = resp.getResponseHeader('Link');
  514. setError(null);
  515. setIssuesLoading(false);
  516. setQueryCount(newQueryCount);
  517. setQueryMaxCount(newQueryMaxCount);
  518. setPageLinks(newPageLinks !== null ? newPageLinks : '');
  519. fetchCounts(newQueryCount, fetchAllCounts);
  520. // Need to wait for stats request to finish before saving to cache
  521. await fetchStats(data.map((group: BaseGroup) => group.id));
  522. IssueListCacheStore.save(requestParams, {
  523. groups: GroupStore.getState() as Group[],
  524. queryCount: newQueryCount,
  525. queryMaxCount: newQueryMaxCount,
  526. pageLinks: newPageLinks ?? '',
  527. });
  528. },
  529. error: err => {
  530. trackAnalytics('issue_search.failed', {
  531. organization,
  532. search_type: 'issues',
  533. search_source: 'main_search',
  534. error: parseApiError(err),
  535. });
  536. setError(parseApiError(err));
  537. setIssuesLoading(false);
  538. },
  539. complete: () => {
  540. resumePolling();
  541. if (!realtimeActive) {
  542. actionTakenRef.current = false;
  543. undoRef.current = false;
  544. }
  545. },
  546. });
  547. },
  548. [
  549. realtimeActive,
  550. sort,
  551. api,
  552. organization,
  553. requestParams,
  554. fetchStats,
  555. fetchCounts,
  556. navigate,
  557. location.query,
  558. query,
  559. resumePolling,
  560. ]
  561. );
  562. useRouteAnalyticsParams({
  563. issue_views_enabled: organization.features.includes('issue-stream-custom-views'),
  564. });
  565. useDisableRouteAnalytics();
  566. // Update polling status
  567. useEffect(() => {
  568. if (realtimeActive) {
  569. resumePolling();
  570. } else {
  571. pollerRef.current?.disable();
  572. }
  573. }, [realtimeActive, resumePolling]);
  574. // Fetch data on mount if necessary
  575. useEffect(() => {
  576. const loadedFromCache = loadFromCache();
  577. if (!loadedFromCache) {
  578. // It's possible the projects query parameter is not yet ready and this
  579. // request will be repeated in componentDidUpdate
  580. fetchData();
  581. }
  582. // eslint-disable-next-line react-hooks/exhaustive-deps
  583. }, []);
  584. const previousSelection = usePrevious(selection);
  585. const previousSavedSearchLoading = usePrevious(savedSearchLoading);
  586. const previousIssuesLoading = usePrevious(issuesLoading);
  587. const previousRequestParams = usePrevious(requestParams);
  588. // Keep data up to date
  589. useEffect(() => {
  590. const selectionChanged = !isEqual(previousSelection, selection);
  591. // Wait for saved searches to load before we attempt to fetch stream data
  592. // Selection changing could indicate that the projects query parameter has populated
  593. // and we should refetch data.
  594. if (savedSearchLoading && !selectionChanged) {
  595. return;
  596. }
  597. if (previousSavedSearchLoading && !savedSearchLoading) {
  598. return;
  599. }
  600. // If any important url parameter changed or saved search changed
  601. // reload data.
  602. if (!isEqual(previousRequestParams, requestParams)) {
  603. fetchData(selectionChanged);
  604. }
  605. }, [
  606. fetchData,
  607. savedSearchLoading,
  608. selection,
  609. previousSelection,
  610. organization.features,
  611. issuesLoading,
  612. loadFromCache,
  613. previousSavedSearchLoading,
  614. previousIssuesLoading,
  615. previousRequestParams,
  616. requestParams,
  617. ]);
  618. // Fetch members on mount
  619. useEffect(() => {
  620. const projectIds = selection.projects.map(projectId => String(projectId));
  621. fetchOrgMembers(api, organization.slug, projectIds).then(members => {
  622. setMemberList(indexMembersByProject(members));
  623. });
  624. // eslint-disable-next-line react-hooks/exhaustive-deps
  625. }, []);
  626. // If the project selection has changed reload the member list and tag keys
  627. // allowing autocomplete and tag sidebar to be more accurate.
  628. useEffect(() => {
  629. if (isEqual(previousSelection?.projects, selection.projects)) {
  630. return;
  631. }
  632. const projectIds = selection.projects.map(projectId => String(projectId));
  633. fetchOrgMembers(api, organization.slug, projectIds).then(members => {
  634. setMemberList(indexMembersByProject(members));
  635. });
  636. }, [api, organization.slug, selection.projects, previousSelection?.projects]);
  637. // Cleanup
  638. useEffect(() => {
  639. return () => {
  640. pollerRef.current?.disable();
  641. SelectedGroupStore.reset();
  642. GroupStore.reset();
  643. };
  644. }, []);
  645. const allResultsVisible = useCallback(() => {
  646. if (!pageLinks) {
  647. return false;
  648. }
  649. const links = parseLinkHeader(pageLinks);
  650. return links && !links.previous!.results && !links.next!.results;
  651. }, [pageLinks]);
  652. const getPageCounts = useCallback(() => {
  653. const links = parseLinkHeader(pageLinks);
  654. const queryPageInt = parsePageQueryParam(location, 0);
  655. // Cursor must be present for the page number to be used
  656. const page = !location.query.cursor ? 0 : queryPageInt;
  657. let numPreviousIssues = Math.min(page * MAX_ITEMS, queryCount);
  658. // Because the query param `page` is not tied to the request, we need to
  659. // validate that it's correct at the first and last page
  660. if (!links?.next?.results || allResultsVisible()) {
  661. // On last available page
  662. numPreviousIssues = Math.max(queryCount - groupIds.length, 0);
  663. } else if (!links?.previous?.results) {
  664. // On first available page
  665. numPreviousIssues = 0;
  666. }
  667. return {
  668. numPreviousIssues,
  669. numIssuesOnPage: groupIds.length,
  670. };
  671. }, [pageLinks, location, queryCount, allResultsVisible, groupIds.length]);
  672. const onRealtimeChange = useCallback(
  673. (realtime: boolean) => {
  674. Cookies.set('realtimeActive', realtime.toString());
  675. setRealtimeActive(realtime);
  676. trackAnalytics('issues_stream.realtime_clicked', {
  677. organization,
  678. enabled: realtime,
  679. });
  680. },
  681. [organization]
  682. );
  683. const transitionTo = (
  684. newParams: Partial<EndpointParams> = {},
  685. newSavedSearch: (SavedSearch & {projectId?: number}) | null = savedSearch
  686. ) => {
  687. const queryData = {
  688. ...omit(location.query, ['page', 'cursor']),
  689. referrer: 'issue-list',
  690. ...getEndpointParams(),
  691. ...newParams,
  692. };
  693. let path: string;
  694. if (newSavedSearch?.id) {
  695. path = `/organizations/${organization.slug}/issues/searches/${newSavedSearch.id}/`;
  696. // Remove the query as saved searches bring their own query string.
  697. delete queryData.query;
  698. // If we aren't going to another page in the same search
  699. // drop the query and replace the current project, with the saved search search project
  700. // if available.
  701. if (!queryData.cursor && newSavedSearch.projectId) {
  702. queryData.project = [newSavedSearch.projectId];
  703. }
  704. if (!queryData.cursor && !newParams.sort && newSavedSearch.sort) {
  705. queryData.sort = newSavedSearch.sort;
  706. }
  707. } else {
  708. path = `/organizations/${organization.slug}/issues/`;
  709. }
  710. if (
  711. queryData.sort === IssueSortOptions.INBOX &&
  712. !FOR_REVIEW_QUERIES.includes(queryData.query || '')
  713. ) {
  714. delete queryData.sort;
  715. }
  716. if (path !== location.pathname || !isEqual(query, location.query)) {
  717. navigate({
  718. pathname: normalizeUrl(path),
  719. query: queryData,
  720. });
  721. setIssuesLoading(true);
  722. }
  723. };
  724. const onSearch = (newQuery: string) => {
  725. if (newQuery === query) {
  726. // if query is the same, just re-fetch data
  727. fetchData();
  728. } else {
  729. // Clear the saved search as the user wants something else.
  730. transitionTo({query: newQuery}, null);
  731. }
  732. };
  733. const onSortChange = (newSort: string) => {
  734. trackAnalytics('issues_stream.sort_changed', {
  735. organization,
  736. sort: newSort,
  737. });
  738. transitionTo({sort: newSort});
  739. };
  740. const onCursorChange: CursorHandler = (nextCursor, _path, _query, delta) => {
  741. const queryPageInt = Array.isArray(location.query.page)
  742. ? NaN
  743. : parseInt(location.query.page?.toString() ?? '', 10);
  744. let nextPage: number | undefined = isNaN(queryPageInt) ? delta : queryPageInt + delta;
  745. let cursor: undefined | string = nextCursor;
  746. // unset cursor and page when we navigate back to the first page
  747. // also reset cursor if somehow the previous button is enabled on
  748. // first page and user attempts to go backwards
  749. if (nextPage <= 0) {
  750. cursor = undefined;
  751. nextPage = undefined;
  752. }
  753. transitionTo({cursor, page: nextPage});
  754. };
  755. const onSelectStatsPeriod = (period: string) => {
  756. if (period !== getGroupStatsPeriod()) {
  757. const cursor = Array.isArray(location.query.cursor)
  758. ? location.query.cursor[0]
  759. : location.query.cursor ?? undefined;
  760. const queryPageInt = parsePageQueryParam(location, 0);
  761. const page = !location.query.cursor ? 0 : queryPageInt;
  762. transitionTo({cursor, page, groupStatsPeriod: period});
  763. }
  764. };
  765. const undoAction = ({
  766. data,
  767. groupItems,
  768. }: {
  769. data: IssueUpdateData;
  770. groupItems: BaseGroup[];
  771. }) => {
  772. const projectIds = selection?.projects?.map(p => p.toString());
  773. const endpoint = `/organizations/${organization.slug}/issues/`;
  774. api.clear();
  775. api.request(endpoint, {
  776. method: 'PUT',
  777. data,
  778. query: {
  779. project: projectIds,
  780. id: groupItems.map(group => group.id),
  781. },
  782. success: response => {
  783. if (!response) {
  784. return;
  785. }
  786. // If on the Ignore or For Review tab, adding back to the GroupStore will make the issue show up
  787. // on this page for a second and then be removed (will show up on All Unresolved). This is to
  788. // stop this from happening and avoid confusion.
  789. if (!query.includes('is:ignored') && !isForReviewQuery(query)) {
  790. GroupStore.add(groupItems);
  791. }
  792. actionTakenRef.current = true;
  793. },
  794. error: err => {
  795. setError(parseApiError(err));
  796. setIssuesLoading(false);
  797. },
  798. complete: () => {
  799. fetchData(true);
  800. },
  801. });
  802. };
  803. const onIssueAction = ({
  804. itemIds,
  805. actionType,
  806. shouldRemove,
  807. undo,
  808. }: {
  809. actionType: 'Reviewed' | 'Resolved' | 'Ignored' | 'Archived' | 'Reprioritized';
  810. itemIds: string[];
  811. shouldRemove: boolean;
  812. undo?: () => void;
  813. }) => {
  814. if (itemIds.length > 1) {
  815. addMessage(`${actionType} ${itemIds.length} ${t('Issues')}`, 'success', {
  816. duration: 4000,
  817. undo,
  818. });
  819. } else {
  820. const shortId = itemIds.map(item => GroupStore.get(item)?.shortId).toString();
  821. addMessage(`${actionType} ${shortId}`, 'success', {
  822. duration: 4000,
  823. undo,
  824. });
  825. }
  826. if (!shouldRemove) {
  827. return;
  828. }
  829. const links = parseLinkHeader(pageLinks);
  830. GroupStore.remove(itemIds);
  831. const newQueryCount = queryCount - itemIds.length;
  832. actionTakenRef.current = true;
  833. setQueryCount(newQueryCount);
  834. if (GroupStore.getAllItemIds().length === 0) {
  835. // If we run out of issues on the last page, navigate back a page to
  836. // avoid showing an empty state - if not on the last page, just show a spinner
  837. const shouldGoBackAPage = links?.previous?.results && !links?.next?.results;
  838. transitionTo({cursor: shouldGoBackAPage ? links.previous!.cursor : undefined});
  839. fetchCounts(newQueryCount, true);
  840. } else {
  841. fetchData(true);
  842. }
  843. };
  844. const onActionTaken = (itemIds: string[], data: IssueUpdateData) => {
  845. if (realtimeActive) {
  846. return;
  847. }
  848. const groupItems = itemIds.map(id => GroupStore.get(id)).filter(defined);
  849. if ('status' in data) {
  850. if (data.status === 'resolved') {
  851. onIssueAction({
  852. itemIds,
  853. actionType: 'Resolved',
  854. shouldRemove:
  855. query.includes('is:unresolved') ||
  856. query.includes('is:ignored') ||
  857. isForReviewQuery(query),
  858. undo: () =>
  859. undoAction({
  860. data: {status: GroupStatus.UNRESOLVED, statusDetails: {}},
  861. groupItems,
  862. }),
  863. });
  864. return;
  865. }
  866. if (data.status === 'ignored') {
  867. onIssueAction({
  868. itemIds,
  869. actionType: 'Archived',
  870. shouldRemove: query.includes('is:unresolved') || isForReviewQuery(query),
  871. undo: () =>
  872. undoAction({
  873. data: {status: GroupStatus.UNRESOLVED, statusDetails: {}},
  874. groupItems,
  875. }),
  876. });
  877. return;
  878. }
  879. }
  880. if ('inbox' in data && data.inbox === false) {
  881. onIssueAction({
  882. itemIds,
  883. actionType: 'Reviewed',
  884. shouldRemove: isForReviewQuery(query),
  885. });
  886. return;
  887. }
  888. if ('priority' in data && typeof data.priority === 'string') {
  889. const priorityValues = parseIssuePrioritySearch(query);
  890. const priority = data.priority.toLowerCase() as PriorityLevel;
  891. onIssueAction({
  892. itemIds,
  893. actionType: 'Reprioritized',
  894. shouldRemove: !priorityValues.has(priority),
  895. });
  896. return;
  897. }
  898. };
  899. const onDelete = () => {
  900. actionTakenRef.current = true;
  901. fetchData(true);
  902. };
  903. const paginationAnalyticsEvent = (direction: string) => {
  904. trackAnalytics('issues_stream.paginate', {
  905. organization,
  906. direction,
  907. });
  908. };
  909. const onSavedSearchSelect = (newSavedSearch: SavedSearch) => {
  910. trackAnalytics('organization_saved_search.selected', {
  911. organization,
  912. search_type: 'issues',
  913. id: newSavedSearch.id ? parseInt(newSavedSearch.id, 10) : -1,
  914. is_global: newSavedSearch.isGlobal,
  915. query: newSavedSearch.query,
  916. visibility: newSavedSearch.visibility,
  917. });
  918. setIssuesLoading(true);
  919. setTimeout(() => {
  920. transitionTo(undefined, newSavedSearch);
  921. }, 0);
  922. };
  923. const modifiedQueryCount = Math.max(queryCount, 0);
  924. // TODO: these two might still be in use for reprocessing2
  925. const showReprocessingTab = !!queryCounts?.[Query.REPROCESSING]?.count;
  926. const displayReprocessingActions = showReprocessingTab && query === Query.REPROCESSING;
  927. const {numPreviousIssues, numIssuesOnPage} = getPageCounts();
  928. return (
  929. <NewTabContextProvider>
  930. <Layout.Page>
  931. {organization.features.includes('issue-stream-custom-views') ? (
  932. <ErrorBoundary message={'Failed to load custom tabs'} mini>
  933. <IssueViewsIssueListHeader
  934. router={router}
  935. selectedProjectIds={selection.projects}
  936. realtimeActive={realtimeActive}
  937. onRealtimeChange={onRealtimeChange}
  938. />
  939. </ErrorBoundary>
  940. ) : (
  941. <IssueListHeader
  942. organization={organization}
  943. query={query}
  944. sort={sort}
  945. queryCount={queryCount}
  946. queryCounts={queryCounts}
  947. realtimeActive={realtimeActive}
  948. router={router}
  949. displayReprocessingTab={showReprocessingTab}
  950. selectedProjectIds={selection.projects}
  951. onRealtimeChange={onRealtimeChange}
  952. />
  953. )}
  954. <StyledBody>
  955. <StyledMain>
  956. <IssuesDataConsentBanner source="issues" />
  957. <IssueListFilters
  958. query={query}
  959. sort={sort}
  960. onSortChange={onSortChange}
  961. onSearch={onSearch}
  962. />
  963. <IssueListTable
  964. selection={selection}
  965. query={query}
  966. queryCount={modifiedQueryCount}
  967. onSelectStatsPeriod={onSelectStatsPeriod}
  968. onActionTaken={onActionTaken}
  969. onDelete={onDelete}
  970. statsPeriod={getGroupStatsPeriod()}
  971. groupIds={groupIds}
  972. allResultsVisible={allResultsVisible()}
  973. displayReprocessingActions={displayReprocessingActions}
  974. sort={sort}
  975. onSortChange={onSortChange}
  976. memberList={memberList}
  977. selectedProjectIds={selection.projects}
  978. issuesLoading={issuesLoading}
  979. error={error}
  980. refetchGroups={fetchData}
  981. paginationCaption={
  982. !issuesLoading && modifiedQueryCount > 0
  983. ? tct('[start]-[end] of [total]', {
  984. start: numPreviousIssues + 1,
  985. end: numPreviousIssues + numIssuesOnPage,
  986. total: (
  987. <QueryCount
  988. hideParens
  989. hideIfEmpty={false}
  990. count={modifiedQueryCount}
  991. max={queryMaxCount || 100}
  992. />
  993. ),
  994. })
  995. : null
  996. }
  997. pageLinks={pageLinks}
  998. onCursor={onCursorChange}
  999. paginationAnalyticsEvent={paginationAnalyticsEvent}
  1000. personalSavedSearches={savedSearches?.filter(
  1001. search => search.visibility === 'owner'
  1002. )}
  1003. organizationSavedSearches={savedSearches?.filter(
  1004. search => search.visibility === 'organization'
  1005. )}
  1006. />
  1007. </StyledMain>
  1008. <SavedIssueSearches
  1009. {...{organization, query}}
  1010. onSavedSearchSelect={onSavedSearchSelect}
  1011. sort={sort}
  1012. />
  1013. </StyledBody>
  1014. </Layout.Page>
  1015. </NewTabContextProvider>
  1016. );
  1017. }
  1018. export default Sentry.withProfiler(IssueListOverview);
  1019. const StyledBody = styled('div')`
  1020. background-color: ${p => p.theme.background};
  1021. flex: 1;
  1022. display: grid;
  1023. gap: 0;
  1024. padding: 0;
  1025. grid-template-rows: 1fr;
  1026. grid-template-columns: minmax(0, 1fr) auto;
  1027. grid-template-areas: 'content saved-searches';
  1028. `;
  1029. const StyledMain = styled('section')`
  1030. grid-area: content;
  1031. padding: ${space(2)};
  1032. @media (min-width: ${p => p.theme.breakpoints.medium}) {
  1033. padding: ${space(3)} ${space(4)};
  1034. }
  1035. `;