groupDetails.tsx 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923
  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 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. return (
  778. <Fragment>
  779. {isSampleError && group && (
  780. <SampleEventAlert project={group.project} organization={organization} />
  781. )}
  782. <SentryDocumentTitle noSuffix title={getGroupDetailsTitle()}>
  783. <PageFiltersContainer
  784. skipLoadLastUsed
  785. forceProject={group?.project}
  786. shouldForceProject
  787. >
  788. <GroupDetailsPageContent
  789. {...props}
  790. {...{
  791. group,
  792. ...fetchGroupDetailsProps,
  793. }}
  794. />
  795. </PageFiltersContainer>
  796. </SentryDocumentTitle>
  797. </Fragment>
  798. );
  799. }
  800. export default Sentry.withProfiler(GroupDetails);
  801. const StyledLoadingError = styled(LoadingError)`
  802. margin: ${space(2)};
  803. `;
  804. const GroupTabPanels = styled(TabPanels)`
  805. flex-grow: 1;
  806. display: flex;
  807. flex-direction: column;
  808. justify-content: stretch;
  809. `;