index.tsx 11 KB

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