groupDetails.tsx 25 KB

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