groupDetails.tsx 25 KB

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