groupDetails.tsx 25 KB

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