groupDetails.tsx 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921
  1. import {
  2. cloneElement,
  3. Fragment,
  4. isValidElement,
  5. useCallback,
  6. useEffect,
  7. useRef,
  8. useState,
  9. } from 'react';
  10. import type {RouteComponentProps} from 'react-router';
  11. import {browserHistory} from 'react-router';
  12. import styled from '@emotion/styled';
  13. import * as Sentry from '@sentry/react';
  14. import omit from 'lodash/omit';
  15. import pick from 'lodash/pick';
  16. import * as qs from 'query-string';
  17. import LoadingError from 'sentry/components/loadingError';
  18. import LoadingIndicator from 'sentry/components/loadingIndicator';
  19. import PageFiltersContainer from 'sentry/components/organizations/pageFilters/container';
  20. import MissingProjectMembership from 'sentry/components/projects/missingProjectMembership';
  21. import SentryDocumentTitle from 'sentry/components/sentryDocumentTitle';
  22. import {TabPanels, Tabs} from 'sentry/components/tabs';
  23. import {t} from 'sentry/locale';
  24. import GroupStore from 'sentry/stores/groupStore';
  25. import {space} from 'sentry/styles/space';
  26. import type {Group, Organization, Project} from 'sentry/types';
  27. import {GroupStatus, IssueCategory, IssueType} from 'sentry/types';
  28. import type {Event} from 'sentry/types/event';
  29. import {defined} from 'sentry/utils';
  30. import {trackAnalytics} from 'sentry/utils/analytics';
  31. import {getUtcDateString} from 'sentry/utils/dates';
  32. import {
  33. getAnalyticsDataForEvent,
  34. getAnalyticsDataForGroup,
  35. getMessage,
  36. getTitle,
  37. } from 'sentry/utils/events';
  38. import {getAnalyicsDataForProject} from 'sentry/utils/projects';
  39. import type {ApiQueryKey} from 'sentry/utils/queryClient';
  40. import {setApiQueryData, useApiQuery, useQueryClient} from 'sentry/utils/queryClient';
  41. import recreateRoute from 'sentry/utils/recreateRoute';
  42. import type RequestError from 'sentry/utils/requestError/requestError';
  43. import useDisableRouteAnalytics from 'sentry/utils/routeAnalytics/useDisableRouteAnalytics';
  44. import useRouteAnalyticsEventNames from 'sentry/utils/routeAnalytics/useRouteAnalyticsEventNames';
  45. import useRouteAnalyticsParams from 'sentry/utils/routeAnalytics/useRouteAnalyticsParams';
  46. import useApi from 'sentry/utils/useApi';
  47. import {useLocation} from 'sentry/utils/useLocation';
  48. import useOrganization from 'sentry/utils/useOrganization';
  49. import {useParams} from 'sentry/utils/useParams';
  50. import useProjects from 'sentry/utils/useProjects';
  51. import useRouter from 'sentry/utils/useRouter';
  52. import {useUser} from 'sentry/utils/useUser';
  53. import {normalizeUrl} from 'sentry/utils/withDomainRequired';
  54. import {ERROR_TYPES} from './constants';
  55. import GroupHeader from './header';
  56. import SampleEventAlert from './sampleEventAlert';
  57. import {Tab, TabPaths} from './types';
  58. import {
  59. getGroupDetailsQueryData,
  60. getGroupEventDetailsQueryData,
  61. getGroupReprocessingStatus,
  62. markEventSeen,
  63. ReprocessingStatus,
  64. useDefaultIssueEvent,
  65. useEnvironmentsFromUrl,
  66. useFetchIssueTagsForDetailsPage,
  67. } from './utils';
  68. type Error = (typeof ERROR_TYPES)[keyof typeof ERROR_TYPES] | null;
  69. type RouterParams = {groupId: string; eventId?: string};
  70. type RouteProps = RouteComponentProps<RouterParams, {}>;
  71. interface GroupDetailsProps extends RouteComponentProps<{groupId: string}, {}> {
  72. children: React.ReactNode;
  73. }
  74. type FetchGroupDetailsState = {
  75. error: boolean;
  76. errorType: Error;
  77. event: Event | null;
  78. eventError: boolean;
  79. group: Group | null;
  80. loadingEvent: boolean;
  81. loadingGroup: boolean;
  82. refetchData: () => void;
  83. refetchGroup: () => void;
  84. };
  85. interface GroupDetailsContentProps extends GroupDetailsProps, FetchGroupDetailsState {
  86. group: Group;
  87. project: Project;
  88. }
  89. function getFetchDataRequestErrorType(status?: number | null): Error {
  90. if (!status) {
  91. return null;
  92. }
  93. if (status === 404) {
  94. return ERROR_TYPES.GROUP_NOT_FOUND;
  95. }
  96. if (status === 403) {
  97. return ERROR_TYPES.MISSING_MEMBERSHIP;
  98. }
  99. return null;
  100. }
  101. function getCurrentTab({router}: {router: RouteProps['router']}) {
  102. const currentRoute = router.routes[router.routes.length - 1];
  103. // If we're in the tag details page ("/tags/:tagKey/")
  104. if (router.params.tagKey) {
  105. return Tab.TAGS;
  106. }
  107. return (
  108. Object.values(Tab).find(tab => currentRoute.path === TabPaths[tab]) ?? Tab.DETAILS
  109. );
  110. }
  111. function getCurrentRouteInfo({
  112. group,
  113. event,
  114. organization,
  115. router,
  116. }: {
  117. event: Event | null;
  118. group: Group;
  119. organization: Organization;
  120. router: RouteProps['router'];
  121. }): {
  122. baseUrl: string;
  123. currentTab: Tab;
  124. } {
  125. const currentTab = getCurrentTab({router});
  126. const baseUrl = normalizeUrl(
  127. `/organizations/${organization.slug}/issues/${group.id}/${
  128. router.params.eventId && event ? `events/${event.id}/` : ''
  129. }`
  130. );
  131. return {baseUrl, currentTab};
  132. }
  133. function getReprocessingNewRoute({
  134. group,
  135. event,
  136. organization,
  137. router,
  138. }: {
  139. event: Event | null;
  140. group: Group;
  141. organization: Organization;
  142. router: RouteProps['router'];
  143. }) {
  144. const {routes, params, location} = router;
  145. const {groupId} = params;
  146. const {currentTab, baseUrl} = getCurrentRouteInfo({group, event, organization, router});
  147. const hasReprocessingV2Feature = organization.features?.includes('reprocessing-v2');
  148. const {id: nextGroupId} = group;
  149. const reprocessingStatus = getGroupReprocessingStatus(group);
  150. if (groupId !== nextGroupId) {
  151. if (hasReprocessingV2Feature) {
  152. // Redirects to the Activities tab
  153. if (
  154. reprocessingStatus === ReprocessingStatus.REPROCESSED_AND_HASNT_EVENT &&
  155. currentTab !== Tab.ACTIVITY
  156. ) {
  157. return {
  158. pathname: `${baseUrl}${Tab.ACTIVITY}/`,
  159. query: {...params, groupId: nextGroupId},
  160. };
  161. }
  162. }
  163. return recreateRoute('', {
  164. routes,
  165. location,
  166. params: {...params, groupId: nextGroupId},
  167. });
  168. }
  169. if (hasReprocessingV2Feature) {
  170. if (
  171. reprocessingStatus === ReprocessingStatus.REPROCESSING &&
  172. currentTab !== Tab.DETAILS
  173. ) {
  174. return {
  175. pathname: baseUrl,
  176. query: params,
  177. };
  178. }
  179. if (
  180. reprocessingStatus === ReprocessingStatus.REPROCESSED_AND_HASNT_EVENT &&
  181. currentTab !== Tab.ACTIVITY &&
  182. currentTab !== Tab.USER_FEEDBACK
  183. ) {
  184. return {
  185. pathname: `${baseUrl}${Tab.ACTIVITY}/`,
  186. query: params,
  187. };
  188. }
  189. }
  190. return undefined;
  191. }
  192. function useRefetchGroupForReprocessing({
  193. refetchGroup,
  194. }: Pick<FetchGroupDetailsState, 'refetchGroup'>) {
  195. const organization = useOrganization();
  196. const hasReprocessingV2Feature = organization.features?.includes('reprocessing-v2');
  197. useEffect(() => {
  198. let refetchInterval: number;
  199. if (hasReprocessingV2Feature) {
  200. refetchInterval = window.setInterval(refetchGroup, 30000);
  201. }
  202. return () => {
  203. window.clearInterval(refetchInterval);
  204. };
  205. }, [hasReprocessingV2Feature, refetchGroup]);
  206. }
  207. function useEventApiQuery({
  208. groupId,
  209. eventId,
  210. environments,
  211. }: {
  212. environments: string[];
  213. groupId: string;
  214. eventId?: string;
  215. }) {
  216. const organization = useOrganization();
  217. const location = useLocation<{query?: string}>();
  218. const router = useRouter();
  219. const defaultIssueEvent = useDefaultIssueEvent();
  220. const eventIdUrl = eventId ?? defaultIssueEvent;
  221. const recommendedEventQuery =
  222. typeof location.query.query === 'string' ? location.query.query : undefined;
  223. const queryKey: ApiQueryKey = [
  224. `/organizations/${organization.slug}/issues/${groupId}/events/${eventIdUrl}/`,
  225. {
  226. query: getGroupEventDetailsQueryData({
  227. environments,
  228. query: recommendedEventQuery,
  229. }),
  230. },
  231. ];
  232. const tab = getCurrentTab({router});
  233. const isOnDetailsTab = tab === Tab.DETAILS;
  234. const isLatestOrRecommendedEvent =
  235. eventIdUrl === 'latest' || eventIdUrl === 'recommended';
  236. const latestOrRecommendedEvent = useApiQuery<Event>(queryKey, {
  237. // Latest/recommended event will change over time, so only cache for 30 seconds
  238. staleTime: 30000,
  239. cacheTime: 30000,
  240. enabled: isOnDetailsTab && isLatestOrRecommendedEvent,
  241. retry: false,
  242. });
  243. const otherEventQuery = useApiQuery<Event>(queryKey, {
  244. // Oldest/specific events will never change
  245. staleTime: Infinity,
  246. enabled: isOnDetailsTab && !isLatestOrRecommendedEvent,
  247. retry: false,
  248. });
  249. useEffect(() => {
  250. if (latestOrRecommendedEvent.isError) {
  251. // If we get an error from the helpful event endpoint, it probably means
  252. // the query failed validation. We should remove the query to try again.
  253. browserHistory.replace({
  254. ...window.location,
  255. query: omit(qs.parse(window.location.search), 'query'),
  256. });
  257. // 404s are expected if all events have exceeded retention
  258. if (latestOrRecommendedEvent.error.status === 404) {
  259. return;
  260. }
  261. const scope = new Sentry.Scope();
  262. scope.setExtras({
  263. groupId,
  264. query: recommendedEventQuery,
  265. ...pick(latestOrRecommendedEvent.error, ['message', 'status', 'responseJSON']),
  266. });
  267. scope.setFingerprint(['issue-details-helpful-event-request-failed']);
  268. Sentry.captureException(
  269. new Error('Issue Details: Helpful event request failed'),
  270. scope
  271. );
  272. }
  273. }, [
  274. latestOrRecommendedEvent.isError,
  275. latestOrRecommendedEvent.error,
  276. groupId,
  277. recommendedEventQuery,
  278. ]);
  279. return isLatestOrRecommendedEvent ? latestOrRecommendedEvent : otherEventQuery;
  280. }
  281. type FetchGroupQueryParameters = {
  282. environments: string[];
  283. groupId: string;
  284. organizationSlug: string;
  285. };
  286. function makeFetchGroupQueryKey({
  287. groupId,
  288. organizationSlug,
  289. environments,
  290. }: FetchGroupQueryParameters): ApiQueryKey {
  291. return [
  292. `/organizations/${organizationSlug}/issues/${groupId}/`,
  293. {query: getGroupDetailsQueryData({environments})},
  294. ];
  295. }
  296. /**
  297. * This is a temporary measure to ensure that the GroupStore and query cache
  298. * are both up to date while we are still using both in the issue details page.
  299. * Once we remove all references to GroupStore in the issue details page we
  300. * should remove this.
  301. */
  302. function useSyncGroupStore(incomingEnvs: string[]) {
  303. const queryClient = useQueryClient();
  304. const organization = useOrganization();
  305. const environmentsRef = useRef<string[]>(incomingEnvs);
  306. environmentsRef.current = incomingEnvs;
  307. const unlisten = useRef<Function>();
  308. if (unlisten.current === undefined) {
  309. unlisten.current = GroupStore.listen(() => {
  310. const [storeGroup] = GroupStore.getState();
  311. const environments = environmentsRef.current;
  312. if (defined(storeGroup)) {
  313. setApiQueryData(
  314. queryClient,
  315. makeFetchGroupQueryKey({
  316. groupId: storeGroup.id,
  317. organizationSlug: organization.slug,
  318. environments,
  319. }),
  320. storeGroup
  321. );
  322. }
  323. }, undefined);
  324. }
  325. useEffect(() => {
  326. return () => unlisten.current?.();
  327. }, []);
  328. }
  329. function useFetchGroupDetails(): FetchGroupDetailsState {
  330. const api = useApi();
  331. const organization = useOrganization();
  332. const router = useRouter();
  333. const params = router.params;
  334. const [error, setError] = useState<boolean>(false);
  335. const [errorType, setErrorType] = useState<Error | null>(null);
  336. const [event, setEvent] = useState<Event | null>(null);
  337. const [allProjectChanged, setAllProjectChanged] = useState<boolean>(false);
  338. const environments = useEnvironmentsFromUrl();
  339. const groupId = params.groupId;
  340. const {
  341. data: eventData,
  342. isLoading: loadingEvent,
  343. isError,
  344. refetch: refetchEvent,
  345. } = useEventApiQuery({
  346. groupId,
  347. eventId: params.eventId,
  348. environments,
  349. });
  350. const {
  351. data: groupData,
  352. isLoading: loadingGroup,
  353. isError: isGroupError,
  354. error: groupError,
  355. refetch: refetchGroupCall,
  356. } = useApiQuery<Group>(
  357. makeFetchGroupQueryKey({organizationSlug: organization.slug, groupId, environments}),
  358. {
  359. staleTime: 30000,
  360. cacheTime: 30000,
  361. retry: false,
  362. }
  363. );
  364. const group = groupData ?? null;
  365. useEffect(() => {
  366. if (defined(group)) {
  367. GroupStore.loadInitialData([group]);
  368. }
  369. }, [groupId, group]);
  370. useSyncGroupStore(environments);
  371. useEffect(() => {
  372. if (eventData) {
  373. setEvent(eventData);
  374. }
  375. }, [eventData]);
  376. useEffect(() => {
  377. if (group && event) {
  378. const reprocessingNewRoute = getReprocessingNewRoute({
  379. group,
  380. event,
  381. router,
  382. organization,
  383. });
  384. if (reprocessingNewRoute) {
  385. browserHistory.push(reprocessingNewRoute);
  386. return;
  387. }
  388. }
  389. }, [group, event, router, organization]);
  390. useEffect(() => {
  391. const matchingProjectSlug = group?.project?.slug;
  392. if (!matchingProjectSlug) {
  393. return;
  394. }
  395. if (!group.hasSeen) {
  396. markEventSeen(api, organization.slug, matchingProjectSlug, params.groupId);
  397. }
  398. }, [
  399. api,
  400. group?.hasSeen,
  401. group?.project?.id,
  402. group?.project?.slug,
  403. organization.slug,
  404. params.groupId,
  405. ]);
  406. const allProjectsFlag = router.location.query._allp;
  407. useEffect(() => {
  408. const locationQuery = qs.parse(window.location.search) || {};
  409. // We use _allp as a temporary measure to know they came from the
  410. // issue list page with no project selected (all projects included in
  411. // filter).
  412. //
  413. // If it is not defined, we add the locked project id to the URL
  414. // (this is because if someone navigates directly to an issue on
  415. // single-project priveleges, then goes back - they were getting
  416. // assigned to the first project).
  417. //
  418. // If it is defined, we do not so that our back button will bring us
  419. // to the issue list page with no project selected instead of the
  420. // locked project.
  421. if (
  422. locationQuery.project === undefined &&
  423. !allProjectsFlag &&
  424. !allProjectChanged &&
  425. group?.project.id
  426. ) {
  427. locationQuery.project = group?.project.id;
  428. browserHistory.replace({...window.location, query: locationQuery});
  429. }
  430. if (allProjectsFlag && !allProjectChanged) {
  431. delete locationQuery.project;
  432. // We delete _allp from the URL to keep the hack a bit cleaner, but
  433. // this is not an ideal solution and will ultimately be replaced with
  434. // something smarter.
  435. delete locationQuery._allp;
  436. browserHistory.replace({...window.location, query: locationQuery});
  437. setAllProjectChanged(true);
  438. }
  439. }, [allProjectsFlag, group?.project.id, allProjectChanged]);
  440. const handleError = useCallback((e: RequestError) => {
  441. Sentry.captureException(e);
  442. setErrorType(getFetchDataRequestErrorType(e?.status));
  443. setError(true);
  444. }, []);
  445. useEffect(() => {
  446. if (isGroupError) {
  447. handleError(groupError);
  448. }
  449. }, [isGroupError, groupError, handleError]);
  450. const refetchGroup = useCallback(() => {
  451. if (group?.status !== GroupStatus.REPROCESSING || loadingGroup || loadingEvent) {
  452. return;
  453. }
  454. refetchGroupCall();
  455. }, [group, loadingGroup, loadingEvent, refetchGroupCall]);
  456. const refetchData = useCallback(() => {
  457. // Set initial state
  458. setError(false);
  459. setErrorType(null);
  460. refetchEvent();
  461. refetchGroup();
  462. }, [refetchGroup, refetchEvent]);
  463. // Refetch when group is stale
  464. useEffect(() => {
  465. if (group) {
  466. if ((group as Group & {stale?: boolean}).stale) {
  467. refetchGroup();
  468. return;
  469. }
  470. }
  471. }, [refetchGroup, group]);
  472. useRefetchGroupForReprocessing({refetchGroup});
  473. useEffect(() => {
  474. return () => {
  475. GroupStore.reset();
  476. };
  477. }, []);
  478. return {
  479. loadingGroup,
  480. loadingEvent,
  481. group,
  482. event,
  483. errorType,
  484. error,
  485. eventError: isError,
  486. refetchData,
  487. refetchGroup,
  488. };
  489. }
  490. function useLoadedEventType() {
  491. const params = useParams<{eventId?: string}>();
  492. const defaultIssueEvent = useDefaultIssueEvent();
  493. switch (params.eventId) {
  494. case undefined:
  495. return defaultIssueEvent;
  496. case 'latest':
  497. case 'oldest':
  498. return params.eventId;
  499. default:
  500. return 'event_id';
  501. }
  502. }
  503. function useTrackView({
  504. group,
  505. event,
  506. project,
  507. tab,
  508. }: {
  509. event: Event | null;
  510. group: Group | null;
  511. tab: Tab;
  512. project?: Project;
  513. }) {
  514. const organization = useOrganization();
  515. const location = useLocation();
  516. const {alert_date, alert_rule_id, alert_type, ref_fallback, stream_index, query} =
  517. location.query;
  518. const groupEventType = useLoadedEventType();
  519. const user = useUser();
  520. useRouteAnalyticsEventNames('issue_details.viewed', 'Issue Details: Viewed');
  521. useRouteAnalyticsParams({
  522. ...getAnalyticsDataForGroup(group),
  523. ...getAnalyticsDataForEvent(event),
  524. ...getAnalyicsDataForProject(project),
  525. tab,
  526. stream_index: typeof stream_index === 'string' ? Number(stream_index) : undefined,
  527. query: typeof query === 'string' ? query : undefined,
  528. // Alert properties track if the user came from email/slack alerts
  529. alert_date:
  530. typeof alert_date === 'string' ? getUtcDateString(Number(alert_date)) : undefined,
  531. alert_rule_id: typeof alert_rule_id === 'string' ? alert_rule_id : undefined,
  532. alert_type: typeof alert_type === 'string' ? alert_type : undefined,
  533. ref_fallback,
  534. group_event_type: groupEventType,
  535. has_hierarchical_grouping:
  536. !!organization.features?.includes('grouping-stacktrace-ui') &&
  537. !!(event?.metadata?.current_tree_label || event?.metadata?.finest_tree_label),
  538. new_issue_experience: user?.options?.issueDetailsNewExperienceQ42023 ?? false,
  539. });
  540. // Set default values for properties that may be updated in subcomponents.
  541. // Must be separate from the above values, otherwise the actual values filled in
  542. // by subcomponents may be overwritten when the above values change.
  543. useRouteAnalyticsParams({
  544. // Will be updated by StacktraceLink if there is a stacktrace link
  545. stacktrace_link_viewed: false,
  546. // Will be updated by IssueQuickTrace if there is a trace
  547. trace_status: 'none',
  548. // Will be updated in GroupDetailsHeader if there are replays
  549. group_has_replay: false,
  550. // Will be updated in ReplayPreview if there is a replay
  551. event_replay_status: 'none',
  552. // Will be updated in SuspectCommits if there are suspect commits
  553. num_suspect_commits: 0,
  554. suspect_commit_calculation: 'no suspect commit',
  555. });
  556. useDisableRouteAnalytics(!group || !event || !project);
  557. }
  558. const trackTabChanged = ({
  559. organization,
  560. project,
  561. group,
  562. event,
  563. tab,
  564. }: {
  565. event: Event | null;
  566. group: Group;
  567. organization: Organization;
  568. project: Project;
  569. tab: Tab;
  570. }) => {
  571. if (!project || !group) {
  572. return;
  573. }
  574. trackAnalytics('issue_details.tab_changed', {
  575. organization,
  576. project_id: parseInt(project.id, 10),
  577. tab,
  578. ...getAnalyticsDataForGroup(group),
  579. });
  580. if (group.issueCategory !== IssueCategory.ERROR) {
  581. return;
  582. }
  583. const analyticsData = event
  584. ? event.tags
  585. .filter(({key}) => ['device', 'os', 'browser'].includes(key))
  586. .reduce((acc, {key, value}) => {
  587. acc[key] = value;
  588. return acc;
  589. }, {})
  590. : {};
  591. trackAnalytics('issue_group_details.tab.clicked', {
  592. organization,
  593. tab,
  594. platform: project.platform,
  595. ...analyticsData,
  596. });
  597. };
  598. function GroupDetailsContentError({
  599. errorType,
  600. onRetry,
  601. }: {
  602. errorType: Error;
  603. onRetry: () => void;
  604. }) {
  605. const organization = useOrganization();
  606. const location = useLocation();
  607. const projectId = location.query.project;
  608. const {projects} = useProjects();
  609. const project = projects.find(proj => proj.id === projectId);
  610. switch (errorType) {
  611. case ERROR_TYPES.GROUP_NOT_FOUND:
  612. return (
  613. <StyledLoadingError
  614. message={t('The issue you were looking for was not found.')}
  615. />
  616. );
  617. case ERROR_TYPES.MISSING_MEMBERSHIP:
  618. return <MissingProjectMembership organization={organization} project={project} />;
  619. default:
  620. return <StyledLoadingError onRetry={onRetry} />;
  621. }
  622. }
  623. function GroupDetailsContent({
  624. children,
  625. group,
  626. project,
  627. loadingEvent,
  628. eventError,
  629. event,
  630. refetchData,
  631. }: GroupDetailsContentProps) {
  632. const organization = useOrganization();
  633. const router = useRouter();
  634. const {currentTab, baseUrl} = getCurrentRouteInfo({group, event, router, organization});
  635. const groupReprocessingStatus = getGroupReprocessingStatus(group);
  636. const environments = useEnvironmentsFromUrl();
  637. useTrackView({group, event, project, tab: currentTab});
  638. const childProps = {
  639. environments,
  640. group,
  641. project,
  642. event,
  643. loadingEvent,
  644. eventError,
  645. groupReprocessingStatus,
  646. onRetry: refetchData,
  647. baseUrl,
  648. };
  649. return (
  650. <Tabs
  651. value={currentTab}
  652. onChange={tab => trackTabChanged({tab, group, project, event, organization})}
  653. >
  654. <GroupHeader
  655. organization={organization}
  656. groupReprocessingStatus={groupReprocessingStatus}
  657. event={event ?? undefined}
  658. group={group}
  659. baseUrl={baseUrl}
  660. project={project as Project}
  661. />
  662. <GroupTabPanels>
  663. <TabPanels.Item key={currentTab}>
  664. {isValidElement(children) ? cloneElement(children, childProps) : children}
  665. </TabPanels.Item>
  666. </GroupTabPanels>
  667. </Tabs>
  668. );
  669. }
  670. function GroupDetailsPageContent(props: GroupDetailsProps & FetchGroupDetailsState) {
  671. const projectSlug = props.group?.project?.slug;
  672. const api = useApi();
  673. const organization = useOrganization();
  674. const [injectedEvent, setInjectedEvent] = useState(null);
  675. const {
  676. projects,
  677. initiallyLoaded: projectsLoaded,
  678. fetchError: errorFetchingProjects,
  679. } = useProjects({slugs: projectSlug ? [projectSlug] : []});
  680. const project = projects.find(({slug}) => slug === projectSlug);
  681. const projectWithFallback = project ?? projects[0];
  682. const isRegressionIssue =
  683. props.group?.issueType === IssueType.PERFORMANCE_DURATION_REGRESSION ||
  684. props.group?.issueType === IssueType.PERFORMANCE_ENDPOINT_REGRESSION;
  685. useEffect(() => {
  686. if (props.group && projectsLoaded && !project) {
  687. Sentry.withScope(scope => {
  688. const projectIds = projects.map(item => item.id);
  689. scope.setContext('missingProject', {
  690. projectId: props.group?.project.id,
  691. availableProjects: projectIds,
  692. });
  693. scope.setFingerprint(['group-details-project-not-found']);
  694. Sentry.captureException(new Error('Project not found'));
  695. });
  696. }
  697. }, [props.group, project, projects, projectsLoaded]);
  698. useEffect(() => {
  699. const fetchLatestEvent = async () => {
  700. const event = await api.requestPromise(
  701. `/organizations/${organization.slug}/issues/${props.group?.id}/events/latest/`
  702. );
  703. setInjectedEvent(event);
  704. };
  705. if (isRegressionIssue && !defined(props.event)) {
  706. fetchLatestEvent();
  707. }
  708. }, [
  709. api,
  710. organization.slug,
  711. props.event,
  712. props.group,
  713. props.group?.id,
  714. isRegressionIssue,
  715. ]);
  716. if (props.error) {
  717. return (
  718. <GroupDetailsContentError errorType={props.errorType} onRetry={props.refetchData} />
  719. );
  720. }
  721. if (errorFetchingProjects) {
  722. return <StyledLoadingError message={t('Error loading the specified project')} />;
  723. }
  724. if (projectSlug && !errorFetchingProjects && projectsLoaded && !projectWithFallback) {
  725. return (
  726. <StyledLoadingError message={t('The project %s does not exist', projectSlug)} />
  727. );
  728. }
  729. const regressionIssueLoaded = defined(injectedEvent ?? props.event);
  730. if (
  731. !projectsLoaded ||
  732. !projectWithFallback ||
  733. !props.group ||
  734. (isRegressionIssue && !regressionIssueLoaded)
  735. ) {
  736. return <LoadingIndicator />;
  737. }
  738. return (
  739. <GroupDetailsContent
  740. {...props}
  741. project={projectWithFallback}
  742. group={props.group}
  743. event={props.event ?? injectedEvent}
  744. />
  745. );
  746. }
  747. function GroupDetails(props: GroupDetailsProps) {
  748. const organization = useOrganization();
  749. const router = useRouter();
  750. const {group, ...fetchGroupDetailsProps} = useFetchGroupDetails();
  751. const environments = useEnvironmentsFromUrl();
  752. const {data} = useFetchIssueTagsForDetailsPage(
  753. {
  754. groupId: router.params.groupId,
  755. orgSlug: organization.slug,
  756. environment: environments,
  757. },
  758. // Don't want this query to take precedence over the main requests
  759. {enabled: defined(group)}
  760. );
  761. const isSampleError = data?.some(tag => tag.key === 'sample_event') ?? false;
  762. const getGroupDetailsTitle = () => {
  763. const defaultTitle = 'Sentry';
  764. if (!group) {
  765. return defaultTitle;
  766. }
  767. const {title} = getTitle(group, organization?.features);
  768. const message = getMessage(group);
  769. const eventDetails = `${organization.slug} — ${group.project.slug}`;
  770. if (title && message) {
  771. return `${title}: ${message} — ${eventDetails}`;
  772. }
  773. return `${title || message || defaultTitle} — ${eventDetails}`;
  774. };
  775. return (
  776. <Fragment>
  777. {isSampleError && group && (
  778. <SampleEventAlert project={group.project} organization={organization} />
  779. )}
  780. <SentryDocumentTitle noSuffix title={getGroupDetailsTitle()}>
  781. <PageFiltersContainer
  782. skipLoadLastUsed
  783. forceProject={group?.project}
  784. shouldForceProject
  785. >
  786. <GroupDetailsPageContent
  787. {...props}
  788. {...{
  789. group,
  790. ...fetchGroupDetailsProps,
  791. }}
  792. />
  793. </PageFiltersContainer>
  794. </SentryDocumentTitle>
  795. </Fragment>
  796. );
  797. }
  798. export default Sentry.withProfiler(GroupDetails);
  799. const StyledLoadingError = styled(LoadingError)`
  800. margin: ${space(2)};
  801. `;
  802. const GroupTabPanels = styled(TabPanels)`
  803. flex-grow: 1;
  804. display: flex;
  805. flex-direction: column;
  806. justify-content: stretch;
  807. `;