index.tsx 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310
  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()});
  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. this.props.router.push(
  120. normalizeUrl(`/settings/${orgId}/integrations/${data.provider.key}/${data.id}/`)
  121. );
  122. };
  123. // non-Github redirects to the extension view where the backend will finish the installation
  124. finishInstallation = () => {
  125. // add the selected org to the query parameters and then redirect back to configure
  126. const {selectedOrgSlug} = this.state;
  127. const query = {orgSlug: selectedOrgSlug, ...this.queryParams};
  128. this.trackInstallationStart();
  129. window.location.assign(
  130. `/extensions/${this.integrationSlug}/configure/?${urlEncode(query)}`
  131. );
  132. };
  133. renderAddButton() {
  134. const {installationId} = this.props.params;
  135. const {organization, provider} = this.state;
  136. // should never happen but we need this check for TS
  137. if (!provider || !organization) {
  138. return null;
  139. }
  140. const {features} = provider.metadata;
  141. // Prepare the features list
  142. const featuresComponents = features.map(f => ({
  143. featureGate: f.featureGate,
  144. description: (
  145. <FeatureListItem
  146. dangerouslySetInnerHTML={{__html: singleLineRenderer(f.description)}}
  147. />
  148. ),
  149. }));
  150. const {IntegrationFeatures} = getIntegrationFeatureGate();
  151. // Github uses a different installation flow with the installationId as a parameter
  152. // We have to wrap our installation button with AddIntegration so we can get the
  153. // addIntegrationWithInstallationId callback.
  154. // if we don't hve an installationId, we need to use the finishInstallation callback.
  155. return (
  156. <IntegrationFeatures organization={organization} features={featuresComponents}>
  157. {({disabled}) => (
  158. <AddIntegration
  159. provider={provider}
  160. onInstall={this.onInstallWithInstallationId}
  161. organization={organization}
  162. >
  163. {addIntegrationWithInstallationId => (
  164. <ButtonWrapper>
  165. <Button
  166. priority="primary"
  167. disabled={!this.hasAccess() || disabled}
  168. onClick={() =>
  169. installationId
  170. ? addIntegrationWithInstallationId({
  171. installation_id: installationId,
  172. })
  173. : this.finishInstallation()
  174. }
  175. >
  176. {t('Install %s', provider.name)}
  177. </Button>
  178. </ButtonWrapper>
  179. )}
  180. </AddIntegration>
  181. )}
  182. </IntegrationFeatures>
  183. );
  184. }
  185. renderBottom() {
  186. const {organization, selectedOrgSlug, provider, reloading} = this.state;
  187. const {FeatureList} = getIntegrationFeatureGate();
  188. if (reloading) {
  189. return <LoadingIndicator />;
  190. }
  191. return (
  192. <Fragment>
  193. {selectedOrgSlug && organization && !this.hasAccess() && (
  194. <Alert type="error" showIcon>
  195. <p>
  196. {tct(
  197. `You do not have permission to install integrations in
  198. [organization]. Ask an organization owner or manager to
  199. visit this page to finish installing this integration.`,
  200. {organization: <strong>{organization.slug}</strong>}
  201. )}
  202. </p>
  203. <InstallLink>{window.location.href}</InstallLink>
  204. </Alert>
  205. )}
  206. {provider && organization && this.hasAccess() && FeatureList && (
  207. <Fragment>
  208. <p>
  209. {tct(
  210. 'The following features will be available for [organization] when installed.',
  211. {organization: <strong>{organization.slug}</strong>}
  212. )}
  213. </p>
  214. <FeatureList
  215. organization={organization}
  216. features={provider.metadata.features}
  217. provider={provider}
  218. />
  219. </Fragment>
  220. )}
  221. <div className="form-actions">{this.renderAddButton()}</div>
  222. </Fragment>
  223. );
  224. }
  225. renderBody() {
  226. const {selectedOrgSlug} = this.state;
  227. const options = this.state.organizations.map((org: Organization) => ({
  228. value: org.slug,
  229. label: (
  230. <IdBadge
  231. organization={org}
  232. avatarSize={20}
  233. displayName={org.name}
  234. avatarProps={{consistentWidth: true}}
  235. />
  236. ),
  237. }));
  238. return (
  239. <NarrowLayout>
  240. <h3>{t('Finish integration installation')}</h3>
  241. <p>
  242. {tct(
  243. `Please pick a specific [organization:organization] to link with
  244. your integration installation of [integation].`,
  245. {
  246. organization: <strong />,
  247. integation: <strong>{this.integrationSlug}</strong>,
  248. }
  249. )}
  250. </p>
  251. <FieldGroup label={t('Organization')} inline={false} stacked required>
  252. <SelectControl
  253. onChange={this.onSelectOrg}
  254. value={selectedOrgSlug}
  255. placeholder={t('Select an organization')}
  256. options={options}
  257. />
  258. </FieldGroup>
  259. {this.renderBottom()}
  260. </NarrowLayout>
  261. );
  262. }
  263. }
  264. const InstallLink = styled('pre')`
  265. margin-bottom: 0;
  266. background: #fbe3e1;
  267. `;
  268. const FeatureListItem = styled('span')`
  269. line-height: 24px;
  270. `;
  271. const ButtonWrapper = styled('div')`
  272. margin-left: auto;
  273. align-self: center;
  274. display: flex;
  275. flex-direction: column;
  276. align-items: center;
  277. `;