index.tsx 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398
  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. query: {
  89. include_feature_flags: 1,
  90. },
  91. }),
  92. api.requestPromise(`/organizations/${orgSlug}/sentry-app-installations/`),
  93. ]);
  94. const installed = installations
  95. .map(install => install.app.slug)
  96. .includes(params.sentryAppSlug);
  97. setOrganization(org);
  98. setSelectedOrgSlug(org.slug);
  99. setIsInstalled(installed);
  100. } catch (err) {
  101. addErrorMessage(t('Failed to retrieve organization or integration details'));
  102. }
  103. },
  104. [
  105. api,
  106. params.sentryAppSlug,
  107. props.location.search,
  108. setOrganization,
  109. setSelectedOrgSlug,
  110. setIsInstalled,
  111. ]
  112. );
  113. useEffect(function () {
  114. // Skip if we have a selected org, or if there aren't any orgs loaded yet.
  115. if (organization || organizations.length < 1) {
  116. return;
  117. }
  118. if (organizations.length === 1) {
  119. // auto select the org if there is only one
  120. onSelectOrg(organizations[0].slug);
  121. }
  122. // now check the subomdain and use that org slug if it exists
  123. const customerDomain = ConfigStore.get('customerDomain');
  124. if (customerDomain?.subdomain) {
  125. onSelectOrg(customerDomain.subdomain);
  126. }
  127. });
  128. const onClose = useCallback(() => {
  129. // if we came from somewhere, go back there. Otherwise, back to the integrations page
  130. const newUrl = document.referrer || `/settings/${selectedOrgSlug}/integrations/`;
  131. window.location.assign(newUrl);
  132. }, [selectedOrgSlug]);
  133. const disableInstall = useCallback(
  134. function () {
  135. if (!(sentryApp && selectedOrgSlug)) {
  136. return false;
  137. }
  138. return isInstalled || isSentryAppUnavailableForOrg(sentryApp, selectedOrgSlug);
  139. },
  140. [isInstalled, selectedOrgSlug, sentryApp]
  141. );
  142. const onInstall = useCallback(async (): Promise<any | undefined> => {
  143. if (!organization || !sentryApp) {
  144. return undefined;
  145. }
  146. trackIntegrationAnalytics('integrations.installation_start', {
  147. integration_type: 'sentry_app',
  148. integration: sentryApp.slug,
  149. view: 'external_install',
  150. integration_status: sentryApp.status,
  151. organization,
  152. });
  153. const install = await installSentryApp(api, organization.slug, sentryApp);
  154. // installation is complete if the status is installed
  155. if (install.status === 'installed') {
  156. trackIntegrationAnalytics('integrations.installation_complete', {
  157. integration_type: 'sentry_app',
  158. integration: sentryApp.slug,
  159. view: 'external_install',
  160. integration_status: sentryApp.status,
  161. organization,
  162. });
  163. }
  164. if (sentryApp.redirectUrl) {
  165. const queryParams: Record<string, string | undefined> = {
  166. installationId: install.uuid,
  167. code: install.code,
  168. orgSlug: organization.slug,
  169. };
  170. const state = props.location.query.state;
  171. if (state) {
  172. queryParams.state = state;
  173. }
  174. const redirectUrl = addQueryParamsToExistingUrl(sentryApp.redirectUrl, queryParams);
  175. return window.location.assign(redirectUrl);
  176. }
  177. return onClose();
  178. }, [api, organization, sentryApp, onClose, props.location.query.state]);
  179. if (sentryAppLoading || orgsLoading || !sentryApp) {
  180. return <LoadingIndicator />;
  181. }
  182. return (
  183. <div>
  184. <OrgViewHolder>
  185. {isSingleOrg(organizations) ? (
  186. <SingleOrgView organizations={organizations} sentryApp={sentryApp} />
  187. ) : (
  188. <MultiOrgView
  189. onSelectOrg={onSelectOrg}
  190. organizations={organizations}
  191. selectedOrgSlug={selectedOrgSlug}
  192. sentryApp={sentryApp}
  193. />
  194. )}
  195. </OrgViewHolder>
  196. <CheckAndRenderError
  197. organization={organization}
  198. selectedOrgSlug={selectedOrgSlug}
  199. isInstalled={isInstalled}
  200. sentryApp={sentryApp}
  201. />
  202. {organization && (
  203. <OrganizationContext.Provider value={organization}>
  204. <SentryAppDetailsModal
  205. sentryApp={sentryApp}
  206. organization={organization}
  207. onInstall={onInstall}
  208. closeModal={onClose}
  209. isInstalled={disableInstall()}
  210. />
  211. </OrganizationContext.Provider>
  212. )}
  213. </div>
  214. );
  215. }
  216. type CheckAndRenderProps = {
  217. isInstalled: boolean | undefined;
  218. organization: Organization | undefined;
  219. selectedOrgSlug: string | undefined;
  220. sentryApp: SentryApp;
  221. };
  222. function CheckAndRenderError({
  223. organization,
  224. selectedOrgSlug,
  225. isInstalled,
  226. sentryApp,
  227. }: CheckAndRenderProps) {
  228. if (selectedOrgSlug && organization && !hasAccess(organization)) {
  229. return (
  230. <Alert type="error" showIcon>
  231. <p>
  232. {tct(
  233. `You do not have permission to install integrations in
  234. [organization]. Ask an organization owner or manager to
  235. visit this page to finish installing this integration.`,
  236. {organization: <strong>{organization.slug}</strong>}
  237. )}
  238. </p>
  239. <InstallLink>{generateOrgSlugUrl(selectedOrgSlug)}</InstallLink>
  240. </Alert>
  241. );
  242. }
  243. if (isInstalled && organization && sentryApp) {
  244. return (
  245. <Alert type="error" showIcon>
  246. {tct('Integration [sentryAppName] already installed for [organization]', {
  247. organization: <strong>{organization.name}</strong>,
  248. sentryAppName: <strong>{sentryApp.name}</strong>,
  249. })}
  250. </Alert>
  251. );
  252. }
  253. if (isSentryAppUnavailableForOrg(sentryApp, selectedOrgSlug)) {
  254. // use the slug of the owner if we have it, otherwise use 'another organization'
  255. const ownerSlug = sentryApp?.owner?.slug ?? 'another organization';
  256. return (
  257. <Alert type="error" showIcon>
  258. {tct(
  259. 'Integration [sentryAppName] is an unpublished integration for [otherOrg]. An unpublished integration can only be installed on the organization which created it.',
  260. {
  261. sentryAppName: <strong>{sentryApp.name}</strong>,
  262. otherOrg: <strong>{ownerSlug}</strong>,
  263. }
  264. )}
  265. </Alert>
  266. );
  267. }
  268. return null;
  269. }
  270. type SingleOrgProps = {
  271. organizations: Array<OrganizationSummary>;
  272. sentryApp: SentryApp;
  273. };
  274. function SingleOrgView({organizations, sentryApp}: SingleOrgProps) {
  275. const organizationName = organizations[0].name;
  276. return (
  277. <div>
  278. <p>
  279. {tct('You are installing [sentryAppName] for organization [organization]', {
  280. organization: <strong>{organizationName}</strong>,
  281. sentryAppName: <strong>{sentryApp.name}</strong>,
  282. })}
  283. </p>
  284. </div>
  285. );
  286. }
  287. type SelectOrgCallback = (slug: string) => void;
  288. type MultiOrgProps = {
  289. onSelectOrg: SelectOrgCallback;
  290. organizations: Array<OrganizationSummary>;
  291. selectedOrgSlug: string | undefined;
  292. sentryApp: SentryApp;
  293. };
  294. function MultiOrgView({
  295. onSelectOrg,
  296. organizations,
  297. selectedOrgSlug,
  298. sentryApp,
  299. }: MultiOrgProps) {
  300. return (
  301. <div>
  302. <p>
  303. {tct(
  304. 'Please pick a specific [organization:organization] to install [sentryAppName]',
  305. {
  306. organization: <strong />,
  307. sentryAppName: <strong>{sentryApp.name}</strong>,
  308. }
  309. )}
  310. </p>
  311. <FieldGroup label={t('Organization')} inline={false} stacked required>
  312. {() => (
  313. <SelectControl
  314. onChange={({value}) => onSelectOrg(value)}
  315. value={selectedOrgSlug}
  316. placeholder={t('Select an organization')}
  317. options={getOrganizationOptions(organizations)}
  318. data-test-id="org-select"
  319. />
  320. )}
  321. </FieldGroup>
  322. </div>
  323. );
  324. }
  325. const hasAccess = (org: Organization) => org.access.includes('org:integrations');
  326. function isSingleOrg(organizations: Array<OrganizationSummary>): boolean {
  327. return organizations.length === 1;
  328. }
  329. function getOrganizationOptions(organizations: Array<OrganizationSummary>) {
  330. return organizations.map(org => ({
  331. value: org.slug,
  332. label: (
  333. <div key={org.slug}>
  334. <OrganizationAvatar organization={org} />
  335. <OrgNameHolder>{org.slug}</OrgNameHolder>
  336. </div>
  337. ),
  338. }));
  339. }
  340. function isSentryAppUnavailableForOrg(
  341. sentryApp: SentryApp,
  342. selectedOrgSlug: string | undefined
  343. ): boolean {
  344. if (!selectedOrgSlug) {
  345. return false;
  346. }
  347. // if the app is unpublished for a different org
  348. return sentryApp?.owner?.slug !== selectedOrgSlug && sentryApp.status === 'unpublished';
  349. }
  350. const InstallLink = styled('pre')`
  351. margin-bottom: 0;
  352. background: #fbe3e1;
  353. `;
  354. const OrgNameHolder = styled('span')`
  355. margin-left: 5px;
  356. `;
  357. const Content = styled('div')`
  358. margin-bottom: 40px;
  359. `;
  360. const OrgViewHolder = styled('div')`
  361. margin-bottom: 20px;
  362. `;