integrationOrganizationLink.tsx 11 KB

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