index.tsx 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390
  1. import {useCallback, useEffect, useState} from 'react';
  2. import type {RouteComponentProps} from 'react-router';
  3. import styled from '@emotion/styled';
  4. import {addErrorMessage} from 'sentry/actionCreators/indicator';
  5. import {fetchOrganizations} from 'sentry/actionCreators/organizations';
  6. import {installSentryApp} from 'sentry/actionCreators/sentryAppInstallations';
  7. import {Alert} from 'sentry/components/alert';
  8. import OrganizationAvatar from 'sentry/components/avatar/organizationAvatar';
  9. import SelectControl from 'sentry/components/forms/controls/selectControl';
  10. import FieldGroup from 'sentry/components/forms/fieldGroup';
  11. import LoadingIndicator from 'sentry/components/loadingIndicator';
  12. import SentryAppDetailsModal from 'sentry/components/modals/sentryAppDetailsModal';
  13. import NarrowLayout from 'sentry/components/narrowLayout';
  14. import {t, tct} from 'sentry/locale';
  15. import ConfigStore from 'sentry/stores/configStore';
  16. import type {
  17. Organization,
  18. OrganizationSummary,
  19. SentryApp,
  20. SentryAppInstallation,
  21. } from 'sentry/types';
  22. import {generateOrgSlugUrl} from 'sentry/utils';
  23. import {trackIntegrationAnalytics} from 'sentry/utils/integrationUtil';
  24. import {useApiQuery} from 'sentry/utils/queryClient';
  25. import {addQueryParamsToExistingUrl} from 'sentry/utils/queryString';
  26. import useApi from 'sentry/utils/useApi';
  27. import {OrganizationContext} from '../organizationContext';
  28. type Props = RouteComponentProps<{sentryAppSlug: string}, {}>;
  29. // Page Layout
  30. export default function SentryAppExternalInstallation(props: Props) {
  31. return (
  32. <NarrowLayout>
  33. <Content>
  34. <h3>{t('Finish integration installation')}</h3>
  35. <SentryAppExternalInstallationContent {...props} />
  36. </Content>
  37. </NarrowLayout>
  38. );
  39. }
  40. // View Contents
  41. function SentryAppExternalInstallationContent({params, ...props}: Props) {
  42. const api = useApi();
  43. // The selected organization fetched from org details
  44. const [organization, setOrganization] = useState<Organization>();
  45. // The selected organization's slug. Should be removed as we have the selected organization as well.
  46. const [selectedOrgSlug, setSelectedOrgSlug] = useState<string>();
  47. const [organizations, setOrganizations] = useState<Array<OrganizationSummary>>([]);
  48. const [orgsLoading, setOrgsLoading] = useState<boolean>(true);
  49. const [isInstalled, setIsInstalled] = useState<boolean>();
  50. // Load data on mount.
  51. const {data: sentryApp, isLoading: sentryAppLoading} = useApiQuery<SentryApp>(
  52. [`/sentry-apps/${params.sentryAppSlug}/`],
  53. {
  54. staleTime: 0,
  55. }
  56. );
  57. useEffect(
  58. function () {
  59. async function loadOrgs() {
  60. try {
  61. const orgs = await fetchOrganizations(api);
  62. setOrganizations(orgs);
  63. setOrgsLoading(false);
  64. } catch (e) {
  65. setOrgsLoading(false);
  66. // Do nothing.
  67. }
  68. }
  69. loadOrgs();
  70. },
  71. [api]
  72. );
  73. const onSelectOrg = useCallback(
  74. async function (orgSlug: string) {
  75. const customerDomain = ConfigStore.get('customerDomain');
  76. // redirect to the org if it's different than the org being selected
  77. if (customerDomain?.subdomain && orgSlug !== customerDomain?.subdomain) {
  78. const urlWithQuery = generateOrgSlugUrl(orgSlug) + props.location.search;
  79. window.location.assign(urlWithQuery);
  80. return;
  81. }
  82. // otherwise proceed as normal
  83. setSelectedOrgSlug(orgSlug);
  84. try {
  85. const [org, installations]: [Organization, SentryAppInstallation[]] =
  86. await Promise.all([
  87. api.requestPromise(`/organizations/${orgSlug}/`),
  88. api.requestPromise(`/organizations/${orgSlug}/sentry-app-installations/`),
  89. ]);
  90. const installed = installations
  91. .map(install => install.app.slug)
  92. .includes(params.sentryAppSlug);
  93. setOrganization(org);
  94. setSelectedOrgSlug(org.slug);
  95. setIsInstalled(installed);
  96. } catch (err) {
  97. addErrorMessage(t('Failed to retrieve organization or integration details'));
  98. }
  99. },
  100. [
  101. api,
  102. params.sentryAppSlug,
  103. props.location.search,
  104. setOrganization,
  105. setSelectedOrgSlug,
  106. setIsInstalled,
  107. ]
  108. );
  109. useEffect(function () {
  110. // Skip if we have a selected org, or if there aren't any orgs loaded yet.
  111. if (organization || organizations.length < 1) {
  112. return;
  113. }
  114. if (organizations.length === 1) {
  115. // auto select the org if there is only one
  116. onSelectOrg(organizations[0].slug);
  117. }
  118. // now check the subomdain and use that org slug if it exists
  119. const customerDomain = ConfigStore.get('customerDomain');
  120. if (customerDomain?.subdomain) {
  121. onSelectOrg(customerDomain.subdomain);
  122. }
  123. });
  124. const onClose = useCallback(() => {
  125. // if we came from somewhere, go back there. Otherwise, back to the integrations page
  126. const newUrl = document.referrer || `/settings/${selectedOrgSlug}/integrations/`;
  127. window.location.assign(newUrl);
  128. }, [selectedOrgSlug]);
  129. const disableInstall = useCallback(
  130. function () {
  131. if (!(sentryApp && selectedOrgSlug)) {
  132. return false;
  133. }
  134. return isInstalled || isSentryAppUnavailableForOrg(sentryApp, selectedOrgSlug);
  135. },
  136. [isInstalled, selectedOrgSlug, sentryApp]
  137. );
  138. const onInstall = useCallback(async (): Promise<any | undefined> => {
  139. if (!organization || !sentryApp) {
  140. return undefined;
  141. }
  142. trackIntegrationAnalytics('integrations.installation_start', {
  143. integration_type: 'sentry_app',
  144. integration: sentryApp.slug,
  145. view: 'external_install',
  146. integration_status: sentryApp.status,
  147. organization,
  148. });
  149. const install = await installSentryApp(api, organization.slug, sentryApp);
  150. // installation is complete if the status is installed
  151. if (install.status === 'installed') {
  152. trackIntegrationAnalytics('integrations.installation_complete', {
  153. integration_type: 'sentry_app',
  154. integration: sentryApp.slug,
  155. view: 'external_install',
  156. integration_status: sentryApp.status,
  157. organization,
  158. });
  159. }
  160. if (sentryApp.redirectUrl) {
  161. const queryParams = {
  162. installationId: install.uuid,
  163. code: install.code,
  164. orgSlug: organization.slug,
  165. };
  166. const redirectUrl = addQueryParamsToExistingUrl(sentryApp.redirectUrl, queryParams);
  167. return window.location.assign(redirectUrl);
  168. }
  169. return onClose();
  170. }, [api, organization, sentryApp, onClose]);
  171. if (sentryAppLoading || orgsLoading || !sentryApp) {
  172. return <LoadingIndicator />;
  173. }
  174. return (
  175. <div>
  176. <OrgViewHolder>
  177. {isSingleOrg(organizations) ? (
  178. <SingleOrgView organizations={organizations} sentryApp={sentryApp} />
  179. ) : (
  180. <MultiOrgView
  181. onSelectOrg={onSelectOrg}
  182. organizations={organizations}
  183. selectedOrgSlug={selectedOrgSlug}
  184. sentryApp={sentryApp}
  185. />
  186. )}
  187. </OrgViewHolder>
  188. <CheckAndRenderError
  189. organization={organization}
  190. selectedOrgSlug={selectedOrgSlug}
  191. isInstalled={isInstalled}
  192. sentryApp={sentryApp}
  193. />
  194. {organization && (
  195. <OrganizationContext.Provider value={organization}>
  196. <SentryAppDetailsModal
  197. sentryApp={sentryApp}
  198. organization={organization}
  199. onInstall={onInstall}
  200. closeModal={onClose}
  201. isInstalled={disableInstall()}
  202. />
  203. </OrganizationContext.Provider>
  204. )}
  205. </div>
  206. );
  207. }
  208. type CheckAndRenderProps = {
  209. isInstalled: boolean | undefined;
  210. organization: Organization | undefined;
  211. selectedOrgSlug: string | undefined;
  212. sentryApp: SentryApp;
  213. };
  214. function CheckAndRenderError({
  215. organization,
  216. selectedOrgSlug,
  217. isInstalled,
  218. sentryApp,
  219. }: CheckAndRenderProps) {
  220. if (selectedOrgSlug && organization && !hasAccess(organization)) {
  221. return (
  222. <Alert type="error" showIcon>
  223. <p>
  224. {tct(
  225. `You do not have permission to install integrations in
  226. [organization]. Ask an organization owner or manager to
  227. visit this page to finish installing this integration.`,
  228. {organization: <strong>{organization.slug}</strong>}
  229. )}
  230. </p>
  231. <InstallLink>{generateOrgSlugUrl(selectedOrgSlug)}</InstallLink>
  232. </Alert>
  233. );
  234. }
  235. if (isInstalled && organization && sentryApp) {
  236. return (
  237. <Alert type="error" showIcon>
  238. {tct('Integration [sentryAppName] already installed for [organization]', {
  239. organization: <strong>{organization.name}</strong>,
  240. sentryAppName: <strong>{sentryApp.name}</strong>,
  241. })}
  242. </Alert>
  243. );
  244. }
  245. if (isSentryAppUnavailableForOrg(sentryApp, selectedOrgSlug)) {
  246. // use the slug of the owner if we have it, otherwise use 'another organization'
  247. const ownerSlug = sentryApp?.owner?.slug ?? 'another organization';
  248. return (
  249. <Alert type="error" showIcon>
  250. {tct(
  251. 'Integration [sentryAppName] is an unpublished integration for [otherOrg]. An unpublished integration can only be installed on the organization which created it.',
  252. {
  253. sentryAppName: <strong>{sentryApp.name}</strong>,
  254. otherOrg: <strong>{ownerSlug}</strong>,
  255. }
  256. )}
  257. </Alert>
  258. );
  259. }
  260. return null;
  261. }
  262. type SingleOrgProps = {
  263. organizations: Array<OrganizationSummary>;
  264. sentryApp: SentryApp;
  265. };
  266. function SingleOrgView({organizations, sentryApp}: SingleOrgProps) {
  267. const organizationName = organizations[0].name;
  268. return (
  269. <div>
  270. <p>
  271. {tct('You are installing [sentryAppName] for organization [organization]', {
  272. organization: <strong>{organizationName}</strong>,
  273. sentryAppName: <strong>{sentryApp.name}</strong>,
  274. })}
  275. </p>
  276. </div>
  277. );
  278. }
  279. type SelectOrgCallback = (slug: string) => void;
  280. type MultiOrgProps = {
  281. onSelectOrg: SelectOrgCallback;
  282. organizations: Array<OrganizationSummary>;
  283. selectedOrgSlug: string | undefined;
  284. sentryApp: SentryApp;
  285. };
  286. function MultiOrgView({
  287. onSelectOrg,
  288. organizations,
  289. selectedOrgSlug,
  290. sentryApp,
  291. }: MultiOrgProps) {
  292. return (
  293. <div>
  294. <p>
  295. {tct(
  296. 'Please pick a specific [organization:organization] to install [sentryAppName]',
  297. {
  298. organization: <strong />,
  299. sentryAppName: <strong>{sentryApp.name}</strong>,
  300. }
  301. )}
  302. </p>
  303. <FieldGroup label={t('Organization')} inline={false} stacked required>
  304. {() => (
  305. <SelectControl
  306. onChange={({value}) => onSelectOrg(value)}
  307. value={selectedOrgSlug}
  308. placeholder={t('Select an organization')}
  309. options={getOrganizationOptions(organizations)}
  310. data-test-id="org-select"
  311. />
  312. )}
  313. </FieldGroup>
  314. </div>
  315. );
  316. }
  317. const hasAccess = (org: Organization) => org.access.includes('org:integrations');
  318. function isSingleOrg(organizations: Array<OrganizationSummary>): boolean {
  319. return organizations.length === 1;
  320. }
  321. function getOrganizationOptions(organizations: Array<OrganizationSummary>) {
  322. return organizations.map(org => ({
  323. value: org.slug,
  324. label: (
  325. <div key={org.slug}>
  326. <OrganizationAvatar organization={org} />
  327. <OrgNameHolder>{org.slug}</OrgNameHolder>
  328. </div>
  329. ),
  330. }));
  331. }
  332. function isSentryAppUnavailableForOrg(
  333. sentryApp: SentryApp,
  334. selectedOrgSlug: string | undefined
  335. ): boolean {
  336. if (!selectedOrgSlug) {
  337. return false;
  338. }
  339. // if the app is unpublished for a different org
  340. return sentryApp?.owner?.slug !== selectedOrgSlug && sentryApp.status === 'unpublished';
  341. }
  342. const InstallLink = styled('pre')`
  343. margin-bottom: 0;
  344. background: #fbe3e1;
  345. `;
  346. const OrgNameHolder = styled('span')`
  347. margin-left: 5px;
  348. `;
  349. const Content = styled('div')`
  350. margin-bottom: 40px;
  351. `;
  352. const OrgViewHolder = styled('div')`
  353. margin-bottom: 20px;
  354. `;