index.tsx 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315
  1. import {Fragment} from 'react';
  2. import {RouteComponentProps} from 'react-router';
  3. import styled from '@emotion/styled';
  4. import {urlEncode} from '@sentry/utils';
  5. import {addErrorMessage} from 'sentry/actionCreators/indicator';
  6. import {Client} from 'sentry/api';
  7. import {Alert} from 'sentry/components/alert';
  8. import {Button} from 'sentry/components/button';
  9. import SelectControl from 'sentry/components/forms/controls/selectControl';
  10. import FieldGroup from 'sentry/components/forms/fieldGroup';
  11. import IdBadge from 'sentry/components/idBadge';
  12. import LoadingIndicator from 'sentry/components/loadingIndicator';
  13. import NarrowLayout from 'sentry/components/narrowLayout';
  14. import {t, tct} from 'sentry/locale';
  15. import {Integration, IntegrationProvider, Organization} from 'sentry/types';
  16. import {generateBaseControlSiloUrl} from 'sentry/utils';
  17. import {IntegrationAnalyticsKey} from 'sentry/utils/analytics/integrations';
  18. import {
  19. getIntegrationFeatureGate,
  20. trackIntegrationAnalytics,
  21. } from 'sentry/utils/integrationUtil';
  22. import {singleLineRenderer} from 'sentry/utils/marked';
  23. import {normalizeUrl} from 'sentry/utils/withDomainRequired';
  24. import AsyncView from 'sentry/views/asyncView';
  25. import AddIntegration from 'sentry/views/settings/organizationIntegrations/addIntegration';
  26. // installationId present for Github flow
  27. type Props = RouteComponentProps<{integrationSlug: string; installationId?: string}, {}>;
  28. type State = AsyncView['state'] & {
  29. organization?: Organization;
  30. provider?: IntegrationProvider;
  31. selectedOrgSlug?: string;
  32. };
  33. const controlSiloUrl = generateBaseControlSiloUrl();
  34. export default class IntegrationOrganizationLink extends AsyncView<Props, State> {
  35. disableErrorReport = false;
  36. controlSiloApi = new Client({baseUrl: controlSiloUrl + '/api/0'});
  37. getEndpoints(): ReturnType<AsyncView['getEndpoints']> {
  38. return [['organizations', '/organizations/']];
  39. }
  40. getTitle() {
  41. return t('Choose Installation Organization');
  42. }
  43. trackIntegrationAnalytics = (
  44. eventName: IntegrationAnalyticsKey,
  45. startSession?: boolean
  46. ) => {
  47. const {organization, provider} = this.state;
  48. // should have these set but need to make TS happy
  49. if (!organization || !provider) {
  50. return;
  51. }
  52. trackIntegrationAnalytics(
  53. eventName,
  54. {
  55. integration_type: 'first_party',
  56. integration: provider.key,
  57. // We actually don't know if it's installed but neither does the user in the view and multiple installs is possible
  58. already_installed: false,
  59. view: 'external_install',
  60. organization,
  61. },
  62. {startSession: !!startSession}
  63. );
  64. };
  65. trackOpened() {
  66. this.trackIntegrationAnalytics('integrations.integration_viewed', true);
  67. }
  68. trackInstallationStart() {
  69. this.trackIntegrationAnalytics('integrations.installation_start');
  70. }
  71. get integrationSlug() {
  72. return this.props.params.integrationSlug;
  73. }
  74. get queryParams() {
  75. return this.props.location.query;
  76. }
  77. getOrgBySlug = (orgSlug: string): Organization | undefined => {
  78. return this.state.organizations.find((org: Organization) => org.slug === orgSlug);
  79. };
  80. onLoadAllEndpointsSuccess() {
  81. // auto select the org if there is only one
  82. const {organizations} = this.state;
  83. if (organizations.length === 1) {
  84. this.onSelectOrg({value: organizations[0].slug});
  85. }
  86. }
  87. onSelectOrg = async ({value: orgSlug}: {value: string}) => {
  88. this.setState({selectedOrgSlug: orgSlug, reloading: true, organization: undefined});
  89. try {
  90. const [organization, {providers}]: [
  91. Organization,
  92. {providers: IntegrationProvider[]}
  93. ] = await Promise.all([
  94. this.controlSiloApi.requestPromise(`/organizations/${orgSlug}/`),
  95. this.controlSiloApi.requestPromise(
  96. `/organizations/${orgSlug}/config/integrations/?provider_key=${this.integrationSlug}`
  97. ),
  98. ]);
  99. // should never happen with a valid provider
  100. if (providers.length === 0) {
  101. throw new Error('Invalid provider');
  102. }
  103. this.setState(
  104. {organization, reloading: false, provider: providers[0]},
  105. this.trackOpened
  106. );
  107. } catch (_err) {
  108. addErrorMessage(t('Failed to retrieve organization or integration details'));
  109. this.setState({reloading: false});
  110. }
  111. };
  112. hasAccess = () => {
  113. const {organization} = this.state;
  114. return organization?.access.includes('org:integrations');
  115. };
  116. // used with Github to redirect to the the integration detail
  117. onInstallWithInstallationId = (data: Integration) => {
  118. const {organization} = this.state;
  119. const orgId = organization && organization.slug;
  120. this.props.router.push(
  121. normalizeUrl(`/settings/${orgId}/integrations/${data.provider.key}/${data.id}/`)
  122. );
  123. };
  124. // non-Github redirects to the extension view where the backend will finish the installation
  125. finishInstallation = () => {
  126. // add the selected org to the query parameters and then redirect back to configure
  127. const {selectedOrgSlug} = this.state;
  128. const query = {orgSlug: selectedOrgSlug, ...this.queryParams};
  129. this.trackInstallationStart();
  130. // need to send to control silo to finish the installation
  131. window.location.assign(
  132. `${controlSiloUrl}/extensions/${this.integrationSlug}/configure/?${urlEncode(
  133. query
  134. )}`
  135. );
  136. };
  137. renderAddButton() {
  138. const {installationId} = this.props.params;
  139. const {organization, provider} = this.state;
  140. // should never happen but we need this check for TS
  141. if (!provider || !organization) {
  142. return null;
  143. }
  144. const {features} = provider.metadata;
  145. // Prepare the features list
  146. const featuresComponents = features.map(f => ({
  147. featureGate: f.featureGate,
  148. description: (
  149. <FeatureListItem
  150. dangerouslySetInnerHTML={{__html: singleLineRenderer(f.description)}}
  151. />
  152. ),
  153. }));
  154. const {IntegrationFeatures} = getIntegrationFeatureGate();
  155. // Github uses a different installation flow with the installationId as a parameter
  156. // We have to wrap our installation button with AddIntegration so we can get the
  157. // addIntegrationWithInstallationId callback.
  158. // if we don't hve an installationId, we need to use the finishInstallation callback.
  159. return (
  160. <IntegrationFeatures organization={organization} features={featuresComponents}>
  161. {({disabled}) => (
  162. <AddIntegration
  163. provider={provider}
  164. onInstall={this.onInstallWithInstallationId}
  165. organization={organization}
  166. >
  167. {addIntegrationWithInstallationId => (
  168. <ButtonWrapper>
  169. <Button
  170. priority="primary"
  171. disabled={!this.hasAccess() || disabled}
  172. onClick={() =>
  173. installationId
  174. ? addIntegrationWithInstallationId({
  175. installation_id: installationId,
  176. })
  177. : this.finishInstallation()
  178. }
  179. >
  180. {t('Install %s', provider.name)}
  181. </Button>
  182. </ButtonWrapper>
  183. )}
  184. </AddIntegration>
  185. )}
  186. </IntegrationFeatures>
  187. );
  188. }
  189. renderBottom() {
  190. const {organization, selectedOrgSlug, provider, reloading} = this.state;
  191. const {FeatureList} = getIntegrationFeatureGate();
  192. if (reloading) {
  193. return <LoadingIndicator />;
  194. }
  195. return (
  196. <Fragment>
  197. {selectedOrgSlug && organization && !this.hasAccess() && (
  198. <Alert type="error" showIcon>
  199. <p>
  200. {tct(
  201. `You do not have permission to install integrations in
  202. [organization]. Ask an organization owner or manager to
  203. visit this page to finish installing this integration.`,
  204. {organization: <strong>{organization.slug}</strong>}
  205. )}
  206. </p>
  207. <InstallLink>{window.location.href}</InstallLink>
  208. </Alert>
  209. )}
  210. {provider && organization && this.hasAccess() && FeatureList && (
  211. <Fragment>
  212. <p>
  213. {tct(
  214. 'The following features will be available for [organization] when installed.',
  215. {organization: <strong>{organization.slug}</strong>}
  216. )}
  217. </p>
  218. <FeatureList
  219. organization={organization}
  220. features={provider.metadata.features}
  221. provider={provider}
  222. />
  223. </Fragment>
  224. )}
  225. <div className="form-actions">{this.renderAddButton()}</div>
  226. </Fragment>
  227. );
  228. }
  229. renderBody() {
  230. const {selectedOrgSlug} = this.state;
  231. const options = this.state.organizations.map((org: Organization) => ({
  232. value: org.slug,
  233. label: (
  234. <IdBadge
  235. organization={org}
  236. avatarSize={20}
  237. displayName={org.name}
  238. avatarProps={{consistentWidth: true}}
  239. />
  240. ),
  241. }));
  242. return (
  243. <NarrowLayout>
  244. <h3>{t('Finish integration installation')}</h3>
  245. <p>
  246. {tct(
  247. `Please pick a specific [organization:organization] to link with
  248. your integration installation of [integation].`,
  249. {
  250. organization: <strong />,
  251. integation: <strong>{this.integrationSlug}</strong>,
  252. }
  253. )}
  254. </p>
  255. <FieldGroup label={t('Organization')} inline={false} stacked required>
  256. <SelectControl
  257. onChange={this.onSelectOrg}
  258. value={selectedOrgSlug}
  259. placeholder={t('Select an organization')}
  260. options={options}
  261. />
  262. </FieldGroup>
  263. {this.renderBottom()}
  264. </NarrowLayout>
  265. );
  266. }
  267. }
  268. const InstallLink = styled('pre')`
  269. margin-bottom: 0;
  270. background: #fbe3e1;
  271. `;
  272. const FeatureListItem = styled('span')`
  273. line-height: 24px;
  274. `;
  275. const ButtonWrapper = styled('div')`
  276. margin-left: auto;
  277. align-self: center;
  278. display: flex;
  279. flex-direction: column;
  280. align-items: center;
  281. `;