groupDetails.tsx 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926
  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 type RequestError from 'sentry/utils/requestError/requestError';
  45. import useDisableRouteAnalytics from 'sentry/utils/routeAnalytics/useDisableRouteAnalytics';
  46. import useRouteAnalyticsEventNames from 'sentry/utils/routeAnalytics/useRouteAnalyticsEventNames';
  47. import useRouteAnalyticsParams from 'sentry/utils/routeAnalytics/useRouteAnalyticsParams';
  48. import useApi from 'sentry/utils/useApi';
  49. import {useLocation} from 'sentry/utils/useLocation';
  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 [error, setError] = useState<boolean>(false);
  337. const [errorType, setErrorType] = useState<Error | null>(null);
  338. const [event, setEvent] = useState<Event | null>(null);
  339. const [allProjectChanged, setAllProjectChanged] = useState<boolean>(false);
  340. const environments = useEnvironmentsFromUrl();
  341. const groupId = params.groupId;
  342. const {
  343. data: eventData,
  344. isLoading: loadingEvent,
  345. isError,
  346. refetch: refetchEvent,
  347. } = useEventApiQuery({
  348. groupId,
  349. eventId: params.eventId,
  350. environments,
  351. });
  352. const {
  353. data: groupData,
  354. isLoading: loadingGroup,
  355. isError: isGroupError,
  356. error: groupError,
  357. refetch: refetchGroupCall,
  358. } = useApiQuery<Group>(
  359. makeFetchGroupQueryKey({organizationSlug: organization.slug, groupId, environments}),
  360. {
  361. staleTime: 30000,
  362. cacheTime: 30000,
  363. retry: false,
  364. }
  365. );
  366. const group = groupData ?? null;
  367. useEffect(() => {
  368. if (defined(group)) {
  369. GroupStore.loadInitialData([group]);
  370. }
  371. }, [groupId, group]);
  372. useSyncGroupStore(environments);
  373. useEffect(() => {
  374. if (eventData) {
  375. setEvent(eventData);
  376. }
  377. }, [eventData]);
  378. useEffect(() => {
  379. if (group && event) {
  380. const reprocessingNewRoute = getReprocessingNewRoute({
  381. group,
  382. event,
  383. router,
  384. organization,
  385. });
  386. if (reprocessingNewRoute) {
  387. browserHistory.push(reprocessingNewRoute);
  388. return;
  389. }
  390. }
  391. }, [group, event, router, organization]);
  392. useEffect(() => {
  393. const matchingProjectSlug = group?.project?.slug;
  394. if (!matchingProjectSlug) {
  395. return;
  396. }
  397. if (!group.hasSeen) {
  398. markEventSeen(api, organization.slug, matchingProjectSlug, params.groupId);
  399. }
  400. }, [
  401. api,
  402. group?.hasSeen,
  403. group?.project?.id,
  404. group?.project?.slug,
  405. organization.slug,
  406. params.groupId,
  407. ]);
  408. const allProjectsFlag = router.location.query._allp;
  409. useEffect(() => {
  410. const locationQuery = qs.parse(window.location.search) || {};
  411. // We use _allp as a temporary measure to know they came from the
  412. // issue list page with no project selected (all projects included in
  413. // filter).
  414. //
  415. // If it is not defined, we add the locked project id to the URL
  416. // (this is because if someone navigates directly to an issue on
  417. // single-project priveleges, then goes back - they were getting
  418. // assigned to the first project).
  419. //
  420. // If it is defined, we do not so that our back button will bring us
  421. // to the issue list page with no project selected instead of the
  422. // locked project.
  423. if (
  424. locationQuery.project === undefined &&
  425. !allProjectsFlag &&
  426. !allProjectChanged &&
  427. group?.project.id
  428. ) {
  429. locationQuery.project = group?.project.id;
  430. browserHistory.replace({...window.location, query: locationQuery});
  431. }
  432. if (allProjectsFlag && !allProjectChanged) {
  433. delete locationQuery.project;
  434. // We delete _allp from the URL to keep the hack a bit cleaner, but
  435. // this is not an ideal solution and will ultimately be replaced with
  436. // something smarter.
  437. delete locationQuery._allp;
  438. browserHistory.replace({...window.location, query: locationQuery});
  439. setAllProjectChanged(true);
  440. }
  441. }, [allProjectsFlag, group?.project.id, allProjectChanged]);
  442. const handleError = useCallback((e: RequestError) => {
  443. Sentry.captureException(e);
  444. setErrorType(getFetchDataRequestErrorType(e?.status));
  445. setError(true);
  446. }, []);
  447. useEffect(() => {
  448. if (isGroupError) {
  449. handleError(groupError);
  450. }
  451. }, [isGroupError, groupError, handleError]);
  452. const refetchGroup = useCallback(() => {
  453. if (group?.status !== GroupStatus.REPROCESSING || loadingGroup || loadingEvent) {
  454. return;
  455. }
  456. refetchGroupCall();
  457. }, [group, loadingGroup, loadingEvent, refetchGroupCall]);
  458. const refetchData = useCallback(() => {
  459. // Set initial state
  460. setError(false);
  461. setErrorType(null);
  462. refetchEvent();
  463. refetchGroup();
  464. }, [refetchGroup, refetchEvent]);
  465. // Refetch when group is stale
  466. useEffect(() => {
  467. if (group) {
  468. if ((group as Group & {stale?: boolean}).stale) {
  469. refetchGroup();
  470. return;
  471. }
  472. }
  473. }, [refetchGroup, group]);
  474. useRefetchGroupForReprocessing({refetchGroup});
  475. useEffect(() => {
  476. return () => {
  477. GroupStore.reset();
  478. };
  479. }, []);
  480. return {
  481. loadingGroup,
  482. loadingEvent,
  483. group,
  484. event,
  485. errorType,
  486. error,
  487. eventError: isError,
  488. refetchData,
  489. refetchGroup,
  490. };
  491. }
  492. function useLoadedEventType() {
  493. const params = useParams<{eventId?: string}>();
  494. const defaultIssueEvent = useDefaultIssueEvent();
  495. switch (params.eventId) {
  496. case undefined:
  497. return defaultIssueEvent;
  498. case 'latest':
  499. case 'oldest':
  500. return params.eventId;
  501. default:
  502. return 'event_id';
  503. }
  504. }
  505. function useTrackView({
  506. group,
  507. event,
  508. project,
  509. tab,
  510. }: {
  511. event: Event | null;
  512. group: Group | null;
  513. tab: Tab;
  514. project?: Project;
  515. }) {
  516. const organization = useOrganization();
  517. const location = useLocation();
  518. const {alert_date, alert_rule_id, alert_type, ref_fallback, stream_index, query} =
  519. location.query;
  520. const groupEventType = useLoadedEventType();
  521. const user = useUser();
  522. useRouteAnalyticsEventNames('issue_details.viewed', 'Issue Details: Viewed');
  523. useRouteAnalyticsParams({
  524. ...getAnalyticsDataForGroup(group),
  525. ...getAnalyticsDataForEvent(event),
  526. ...getAnalyicsDataForProject(project),
  527. tab,
  528. stream_index: typeof stream_index === 'string' ? Number(stream_index) : undefined,
  529. query: typeof query === 'string' ? query : undefined,
  530. // Alert properties track if the user came from email/slack alerts
  531. alert_date:
  532. typeof alert_date === 'string' ? getUtcDateString(Number(alert_date)) : undefined,
  533. alert_rule_id: typeof alert_rule_id === 'string' ? alert_rule_id : undefined,
  534. alert_type: typeof alert_type === 'string' ? alert_type : undefined,
  535. ref_fallback,
  536. group_event_type: groupEventType,
  537. has_hierarchical_grouping:
  538. !!organization.features?.includes('grouping-stacktrace-ui') &&
  539. !!(event?.metadata?.current_tree_label || event?.metadata?.finest_tree_label),
  540. new_issue_experience: user?.options?.issueDetailsNewExperienceQ42023 ?? false,
  541. });
  542. // Set default values for properties that may be updated in subcomponents.
  543. // Must be separate from the above values, otherwise the actual values filled in
  544. // by subcomponents may be overwritten when the above values change.
  545. useRouteAnalyticsParams({
  546. // Will be updated by StacktraceLink if there is a stacktrace link
  547. stacktrace_link_viewed: false,
  548. // Will be updated by IssueQuickTrace if there is a trace
  549. trace_status: 'none',
  550. // Will be updated in GroupDetailsHeader if there are replays
  551. group_has_replay: false,
  552. // Will be updated in ReplayPreview if there is a replay
  553. event_replay_status: 'none',
  554. // Will be updated in SuspectCommits if there are suspect commits
  555. num_suspect_commits: 0,
  556. suspect_commit_calculation: 'no suspect commit',
  557. });
  558. useDisableRouteAnalytics(!group || !event || !project);
  559. }
  560. const trackTabChanged = ({
  561. organization,
  562. project,
  563. group,
  564. event,
  565. tab,
  566. }: {
  567. event: Event | null;
  568. group: Group;
  569. organization: Organization;
  570. project: Project;
  571. tab: Tab;
  572. }) => {
  573. if (!project || !group) {
  574. return;
  575. }
  576. trackAnalytics('issue_details.tab_changed', {
  577. organization,
  578. project_id: parseInt(project.id, 10),
  579. tab,
  580. ...getAnalyticsDataForGroup(group),
  581. });
  582. if (group.issueCategory !== IssueCategory.ERROR) {
  583. return;
  584. }
  585. const analyticsData = event
  586. ? event.tags
  587. .filter(({key}) => ['device', 'os', 'browser'].includes(key))
  588. .reduce((acc, {key, value}) => {
  589. acc[key] = value;
  590. return acc;
  591. }, {})
  592. : {};
  593. trackAnalytics('issue_group_details.tab.clicked', {
  594. organization,
  595. tab,
  596. platform: project.platform,
  597. ...analyticsData,
  598. });
  599. };
  600. function GroupDetailsContentError({
  601. errorType,
  602. onRetry,
  603. }: {
  604. errorType: Error;
  605. onRetry: () => void;
  606. }) {
  607. const organization = useOrganization();
  608. const location = useLocation();
  609. const projectId = location.query.project;
  610. const {projects} = useProjects();
  611. const project = projects.find(proj => proj.id === projectId);
  612. switch (errorType) {
  613. case ERROR_TYPES.GROUP_NOT_FOUND:
  614. return (
  615. <StyledLoadingError
  616. message={t('The issue you were looking for was not found.')}
  617. />
  618. );
  619. case ERROR_TYPES.MISSING_MEMBERSHIP:
  620. return <MissingProjectMembership organization={organization} project={project} />;
  621. default:
  622. return <StyledLoadingError onRetry={onRetry} />;
  623. }
  624. }
  625. function GroupDetailsContent({
  626. children,
  627. group,
  628. project,
  629. loadingEvent,
  630. eventError,
  631. event,
  632. refetchData,
  633. }: GroupDetailsContentProps) {
  634. const organization = useOrganization();
  635. const router = useRouter();
  636. const {currentTab, baseUrl} = getCurrentRouteInfo({group, event, router, organization});
  637. const groupReprocessingStatus = getGroupReprocessingStatus(group);
  638. const environments = useEnvironmentsFromUrl();
  639. useTrackView({group, event, project, tab: currentTab});
  640. const childProps = {
  641. environments,
  642. group,
  643. project,
  644. event,
  645. loadingEvent,
  646. eventError,
  647. groupReprocessingStatus,
  648. onRetry: refetchData,
  649. baseUrl,
  650. };
  651. return (
  652. <Tabs
  653. value={currentTab}
  654. onChange={tab => trackTabChanged({tab, group, project, event, organization})}
  655. >
  656. <GroupHeader
  657. organization={organization}
  658. groupReprocessingStatus={groupReprocessingStatus}
  659. event={event ?? undefined}
  660. group={group}
  661. baseUrl={baseUrl}
  662. project={project as Project}
  663. />
  664. <GroupTabPanels>
  665. <TabPanels.Item key={currentTab}>
  666. {isValidElement(children) ? cloneElement(children, childProps) : children}
  667. </TabPanels.Item>
  668. </GroupTabPanels>
  669. </Tabs>
  670. );
  671. }
  672. function GroupDetailsPageContent(props: GroupDetailsProps & FetchGroupDetailsState) {
  673. const projectSlug = props.group?.project?.slug;
  674. const api = useApi();
  675. const organization = useOrganization();
  676. const [injectedEvent, setInjectedEvent] = useState(null);
  677. const {
  678. projects,
  679. initiallyLoaded: projectsLoaded,
  680. fetchError: errorFetchingProjects,
  681. } = useProjects({slugs: projectSlug ? [projectSlug] : []});
  682. const project = projects.find(({slug}) => slug === projectSlug);
  683. const projectWithFallback = project ?? projects[0];
  684. const isRegressionIssue =
  685. props.group?.issueType === IssueType.PERFORMANCE_DURATION_REGRESSION ||
  686. props.group?.issueType === IssueType.PERFORMANCE_ENDPOINT_REGRESSION;
  687. useEffect(() => {
  688. if (props.group && projectsLoaded && !project) {
  689. Sentry.withScope(scope => {
  690. const projectIds = projects.map(item => item.id);
  691. scope.setContext('missingProject', {
  692. projectId: props.group?.project.id,
  693. availableProjects: projectIds,
  694. });
  695. scope.setFingerprint(['group-details-project-not-found']);
  696. Sentry.captureException(new Error('Project not found'));
  697. });
  698. }
  699. }, [props.group, project, projects, projectsLoaded]);
  700. useEffect(() => {
  701. const fetchLatestEvent = async () => {
  702. const event = await api.requestPromise(
  703. `/organizations/${organization.slug}/issues/${props.group?.id}/events/latest/`
  704. );
  705. setInjectedEvent(event);
  706. };
  707. if (isRegressionIssue && !defined(props.event)) {
  708. fetchLatestEvent();
  709. }
  710. }, [
  711. api,
  712. organization.slug,
  713. props.event,
  714. props.group,
  715. props.group?.id,
  716. isRegressionIssue,
  717. ]);
  718. if (props.error) {
  719. return (
  720. <GroupDetailsContentError errorType={props.errorType} onRetry={props.refetchData} />
  721. );
  722. }
  723. if (errorFetchingProjects) {
  724. return <StyledLoadingError message={t('Error loading the specified project')} />;
  725. }
  726. if (projectSlug && !errorFetchingProjects && projectsLoaded && !projectWithFallback) {
  727. return (
  728. <StyledLoadingError message={t('The project %s does not exist', projectSlug)} />
  729. );
  730. }
  731. const regressionIssueLoaded = defined(injectedEvent ?? props.event);
  732. if (
  733. !projectsLoaded ||
  734. !projectWithFallback ||
  735. !props.group ||
  736. (isRegressionIssue && !regressionIssueLoaded)
  737. ) {
  738. return <LoadingIndicator />;
  739. }
  740. return (
  741. <GroupDetailsContent
  742. {...props}
  743. project={projectWithFallback}
  744. group={props.group}
  745. event={props.event ?? injectedEvent}
  746. />
  747. );
  748. }
  749. function GroupDetails(props: GroupDetailsProps) {
  750. const organization = useOrganization();
  751. const router = useRouter();
  752. const {group, ...fetchGroupDetailsProps} = useFetchGroupDetails();
  753. const environments = useEnvironmentsFromUrl();
  754. const {data} = useFetchIssueTagsForDetailsPage(
  755. {
  756. groupId: router.params.groupId,
  757. orgSlug: organization.slug,
  758. environment: environments,
  759. },
  760. // Don't want this query to take precedence over the main requests
  761. {enabled: defined(group)}
  762. );
  763. const isSampleError = data?.some(tag => tag.key === 'sample_event') ?? false;
  764. const getGroupDetailsTitle = () => {
  765. const defaultTitle = 'Sentry';
  766. if (!group) {
  767. return defaultTitle;
  768. }
  769. const {title} = getTitle(group, organization?.features);
  770. const message = getMessage(group);
  771. const eventDetails = `${organization.slug} — ${group.project.slug}`;
  772. if (title && message) {
  773. return `${title}: ${message} — ${eventDetails}`;
  774. }
  775. return `${title || message || defaultTitle} — ${eventDetails}`;
  776. };
  777. const config = group && getConfigForIssueType(group, group.project);
  778. return (
  779. <Fragment>
  780. {isSampleError && group && (
  781. <SampleEventAlert project={group.project} organization={organization} />
  782. )}
  783. <SentryDocumentTitle noSuffix title={getGroupDetailsTitle()}>
  784. <PageFiltersContainer
  785. skipLoadLastUsed
  786. forceProject={group?.project}
  787. shouldForceProject
  788. >
  789. {config?.showFeedbackWidget && <FloatingFeedbackWidget />}
  790. <GroupDetailsPageContent
  791. {...props}
  792. {...{
  793. group,
  794. ...fetchGroupDetailsProps,
  795. }}
  796. />
  797. </PageFiltersContainer>
  798. </SentryDocumentTitle>
  799. </Fragment>
  800. );
  801. }
  802. export default Sentry.withProfiler(GroupDetails);
  803. const StyledLoadingError = styled(LoadingError)`
  804. margin: ${space(2)};
  805. `;
  806. const GroupTabPanels = styled(TabPanels)`
  807. flex-grow: 1;
  808. display: flex;
  809. flex-direction: column;
  810. justify-content: stretch;
  811. `;