groupDetails.tsx 24 KB

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