index.tsx 10 KB

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