index.tsx 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394
  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: Record<string, string | undefined> = {
  162. installationId: install.uuid,
  163. code: install.code,
  164. orgSlug: organization.slug,
  165. };
  166. const state = props.location.query.state;
  167. if (state) {
  168. queryParams.state = state;
  169. }
  170. const redirectUrl = addQueryParamsToExistingUrl(sentryApp.redirectUrl, queryParams);
  171. return window.location.assign(redirectUrl);
  172. }
  173. return onClose();
  174. }, [api, organization, sentryApp, onClose, props.location.query.state]);
  175. if (sentryAppLoading || orgsLoading || !sentryApp) {
  176. return <LoadingIndicator />;
  177. }
  178. return (
  179. <div>
  180. <OrgViewHolder>
  181. {isSingleOrg(organizations) ? (
  182. <SingleOrgView organizations={organizations} sentryApp={sentryApp} />
  183. ) : (
  184. <MultiOrgView
  185. onSelectOrg={onSelectOrg}
  186. organizations={organizations}
  187. selectedOrgSlug={selectedOrgSlug}
  188. sentryApp={sentryApp}
  189. />
  190. )}
  191. </OrgViewHolder>
  192. <CheckAndRenderError
  193. organization={organization}
  194. selectedOrgSlug={selectedOrgSlug}
  195. isInstalled={isInstalled}
  196. sentryApp={sentryApp}
  197. />
  198. {organization && (
  199. <OrganizationContext.Provider value={organization}>
  200. <SentryAppDetailsModal
  201. sentryApp={sentryApp}
  202. organization={organization}
  203. onInstall={onInstall}
  204. closeModal={onClose}
  205. isInstalled={disableInstall()}
  206. />
  207. </OrganizationContext.Provider>
  208. )}
  209. </div>
  210. );
  211. }
  212. type CheckAndRenderProps = {
  213. isInstalled: boolean | undefined;
  214. organization: Organization | undefined;
  215. selectedOrgSlug: string | undefined;
  216. sentryApp: SentryApp;
  217. };
  218. function CheckAndRenderError({
  219. organization,
  220. selectedOrgSlug,
  221. isInstalled,
  222. sentryApp,
  223. }: CheckAndRenderProps) {
  224. if (selectedOrgSlug && organization && !hasAccess(organization)) {
  225. return (
  226. <Alert type="error" showIcon>
  227. <p>
  228. {tct(
  229. `You do not have permission to install integrations in
  230. [organization]. Ask an organization owner or manager to
  231. visit this page to finish installing this integration.`,
  232. {organization: <strong>{organization.slug}</strong>}
  233. )}
  234. </p>
  235. <InstallLink>{generateOrgSlugUrl(selectedOrgSlug)}</InstallLink>
  236. </Alert>
  237. );
  238. }
  239. if (isInstalled && organization && sentryApp) {
  240. return (
  241. <Alert type="error" showIcon>
  242. {tct('Integration [sentryAppName] already installed for [organization]', {
  243. organization: <strong>{organization.name}</strong>,
  244. sentryAppName: <strong>{sentryApp.name}</strong>,
  245. })}
  246. </Alert>
  247. );
  248. }
  249. if (isSentryAppUnavailableForOrg(sentryApp, selectedOrgSlug)) {
  250. // use the slug of the owner if we have it, otherwise use 'another organization'
  251. const ownerSlug = sentryApp?.owner?.slug ?? 'another organization';
  252. return (
  253. <Alert type="error" showIcon>
  254. {tct(
  255. 'Integration [sentryAppName] is an unpublished integration for [otherOrg]. An unpublished integration can only be installed on the organization which created it.',
  256. {
  257. sentryAppName: <strong>{sentryApp.name}</strong>,
  258. otherOrg: <strong>{ownerSlug}</strong>,
  259. }
  260. )}
  261. </Alert>
  262. );
  263. }
  264. return null;
  265. }
  266. type SingleOrgProps = {
  267. organizations: Array<OrganizationSummary>;
  268. sentryApp: SentryApp;
  269. };
  270. function SingleOrgView({organizations, sentryApp}: SingleOrgProps) {
  271. const organizationName = organizations[0].name;
  272. return (
  273. <div>
  274. <p>
  275. {tct('You are installing [sentryAppName] for organization [organization]', {
  276. organization: <strong>{organizationName}</strong>,
  277. sentryAppName: <strong>{sentryApp.name}</strong>,
  278. })}
  279. </p>
  280. </div>
  281. );
  282. }
  283. type SelectOrgCallback = (slug: string) => void;
  284. type MultiOrgProps = {
  285. onSelectOrg: SelectOrgCallback;
  286. organizations: Array<OrganizationSummary>;
  287. selectedOrgSlug: string | undefined;
  288. sentryApp: SentryApp;
  289. };
  290. function MultiOrgView({
  291. onSelectOrg,
  292. organizations,
  293. selectedOrgSlug,
  294. sentryApp,
  295. }: MultiOrgProps) {
  296. return (
  297. <div>
  298. <p>
  299. {tct(
  300. 'Please pick a specific [organization:organization] to install [sentryAppName]',
  301. {
  302. organization: <strong />,
  303. sentryAppName: <strong>{sentryApp.name}</strong>,
  304. }
  305. )}
  306. </p>
  307. <FieldGroup label={t('Organization')} inline={false} stacked required>
  308. {() => (
  309. <SelectControl
  310. onChange={({value}) => onSelectOrg(value)}
  311. value={selectedOrgSlug}
  312. placeholder={t('Select an organization')}
  313. options={getOrganizationOptions(organizations)}
  314. data-test-id="org-select"
  315. />
  316. )}
  317. </FieldGroup>
  318. </div>
  319. );
  320. }
  321. const hasAccess = (org: Organization) => org.access.includes('org:integrations');
  322. function isSingleOrg(organizations: Array<OrganizationSummary>): boolean {
  323. return organizations.length === 1;
  324. }
  325. function getOrganizationOptions(organizations: Array<OrganizationSummary>) {
  326. return organizations.map(org => ({
  327. value: org.slug,
  328. label: (
  329. <div key={org.slug}>
  330. <OrganizationAvatar organization={org} />
  331. <OrgNameHolder>{org.slug}</OrgNameHolder>
  332. </div>
  333. ),
  334. }));
  335. }
  336. function isSentryAppUnavailableForOrg(
  337. sentryApp: SentryApp,
  338. selectedOrgSlug: string | undefined
  339. ): boolean {
  340. if (!selectedOrgSlug) {
  341. return false;
  342. }
  343. // if the app is unpublished for a different org
  344. return sentryApp?.owner?.slug !== selectedOrgSlug && sentryApp.status === 'unpublished';
  345. }
  346. const InstallLink = styled('pre')`
  347. margin-bottom: 0;
  348. background: #fbe3e1;
  349. `;
  350. const OrgNameHolder = styled('span')`
  351. margin-left: 5px;
  352. `;
  353. const Content = styled('div')`
  354. margin-bottom: 40px;
  355. `;
  356. const OrgViewHolder = styled('div')`
  357. margin-bottom: 20px;
  358. `;