index.tsx 10 KB

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