configureIntegration.tsx 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491
  1. import {Fragment} from 'react';
  2. import {RouteComponentProps} from 'react-router';
  3. import styled from '@emotion/styled';
  4. import {addErrorMessage, addSuccessMessage} from 'sentry/actionCreators/indicator';
  5. import {Client} from 'sentry/api';
  6. import Access from 'sentry/components/acl/access';
  7. import {Alert} from 'sentry/components/alert';
  8. import {Button, LinkButton} from 'sentry/components/button';
  9. import Confirm from 'sentry/components/confirm';
  10. import Form from 'sentry/components/forms/form';
  11. import JsonForm from 'sentry/components/forms/jsonForm';
  12. import List from 'sentry/components/list';
  13. import ListItem from 'sentry/components/list/listItem';
  14. import NavTabs from 'sentry/components/navTabs';
  15. import {IconAdd, IconArrow} from 'sentry/icons';
  16. import {t} from 'sentry/locale';
  17. import {space} from 'sentry/styles/space';
  18. import {
  19. IntegrationProvider,
  20. IntegrationWithConfig,
  21. Organization,
  22. PluginWithProjectList,
  23. } from 'sentry/types';
  24. import {trackIntegrationAnalytics} from 'sentry/utils/integrationUtil';
  25. import {singleLineRenderer} from 'sentry/utils/marked';
  26. import withApi from 'sentry/utils/withApi';
  27. import {normalizeUrl} from 'sentry/utils/withDomainRequired';
  28. import withOrganization from 'sentry/utils/withOrganization';
  29. import DeprecatedAsyncView from 'sentry/views/deprecatedAsyncView';
  30. import BreadcrumbTitle from 'sentry/views/settings/components/settingsBreadcrumb/breadcrumbTitle';
  31. import SettingsPageHeader from 'sentry/views/settings/components/settingsPageHeader';
  32. import AddIntegration from './addIntegration';
  33. import IntegrationAlertRules from './integrationAlertRules';
  34. import IntegrationCodeMappings from './integrationCodeMappings';
  35. import IntegrationExternalTeamMappings from './integrationExternalTeamMappings';
  36. import IntegrationExternalUserMappings from './integrationExternalUserMappings';
  37. import IntegrationItem from './integrationItem';
  38. import IntegrationMainSettings from './integrationMainSettings';
  39. import IntegrationRepos from './integrationRepos';
  40. import IntegrationServerlessFunctions from './integrationServerlessFunctions';
  41. type RouteParams = {
  42. integrationId: string;
  43. providerKey: string;
  44. };
  45. type Props = RouteComponentProps<RouteParams, {}> & {
  46. api: Client;
  47. organization: Organization;
  48. };
  49. type Tab = 'repos' | 'codeMappings' | 'userMappings' | 'teamMappings' | 'settings';
  50. type State = DeprecatedAsyncView['state'] & {
  51. config: {providers: IntegrationProvider[]};
  52. integration: IntegrationWithConfig;
  53. plugins: PluginWithProjectList[] | null;
  54. tab?: Tab;
  55. };
  56. class ConfigureIntegration extends DeprecatedAsyncView<Props, State> {
  57. getEndpoints(): ReturnType<DeprecatedAsyncView['getEndpoints']> {
  58. const {organization} = this.props;
  59. const {integrationId} = this.props.params;
  60. return [
  61. ['config', `/organizations/${organization.slug}/config/integrations/`],
  62. [
  63. 'integration',
  64. `/organizations/${organization.slug}/integrations/${integrationId}/`,
  65. ],
  66. ['plugins', `/organizations/${organization.slug}/plugins/configs/`],
  67. ];
  68. }
  69. componentDidMount() {
  70. super.componentDidMount();
  71. const {
  72. location,
  73. router,
  74. organization,
  75. params: {providerKey},
  76. } = this.props;
  77. // This page should not be accessible by members (unless its github or gitlab)
  78. const allowMemberConfiguration = ['github', 'gitlab'].includes(providerKey);
  79. if (!allowMemberConfiguration && !organization.access.includes('org:integrations')) {
  80. router.push(
  81. normalizeUrl({
  82. pathname: `/settings/${organization.slug}/integrations/${providerKey}/`,
  83. })
  84. );
  85. }
  86. const value =
  87. (['codeMappings', 'userMappings', 'teamMappings'] as const).find(
  88. tab => tab === location.query.tab
  89. ) || 'repos';
  90. // eslint-disable-next-line react/no-did-mount-set-state
  91. this.setState({tab: value});
  92. }
  93. onRequestSuccess({stateKey, data}) {
  94. if (stateKey !== 'integration') {
  95. return;
  96. }
  97. trackIntegrationAnalytics('integrations.details_viewed', {
  98. integration: data.provider.key,
  99. integration_type: 'first_party',
  100. organization: this.props.organization,
  101. });
  102. }
  103. getTitle() {
  104. return this.state.integration
  105. ? this.state.integration.provider.name
  106. : 'Configure Integration';
  107. }
  108. hasStacktraceLinking(provider: IntegrationProvider) {
  109. // CodeOwners will only work if the provider has StackTrace Linking
  110. return (
  111. provider.features.includes('stacktrace-link') &&
  112. this.props.organization.features.includes('integrations-stacktrace-link')
  113. );
  114. }
  115. hasCodeOwners(provider: IntegrationProvider) {
  116. return (
  117. provider.features.includes('codeowners') &&
  118. this.props.organization.features.includes('integrations-codeowners')
  119. );
  120. }
  121. onTabChange = (value: Tab) => {
  122. this.setState({tab: value});
  123. };
  124. get tab() {
  125. return this.state.tab || 'repos';
  126. }
  127. onUpdateIntegration = () => {
  128. this.setState(this.getDefaultState(), this.fetchData);
  129. };
  130. handleJiraMigration = async () => {
  131. try {
  132. const {
  133. organization,
  134. params: {integrationId},
  135. } = this.props;
  136. await this.api.requestPromise(
  137. `/organizations/${organization.slug}/integrations/${integrationId}/issues/`,
  138. {
  139. method: 'PUT',
  140. data: {},
  141. }
  142. );
  143. this.setState(
  144. {
  145. plugins: (this.state.plugins || []).filter(({id}) => id === 'jira'),
  146. },
  147. () => addSuccessMessage(t('Migration in progress.'))
  148. );
  149. } catch (error) {
  150. addErrorMessage(t('Something went wrong! Please try again.'));
  151. }
  152. };
  153. handleOpsgenieMigration = async () => {
  154. const {
  155. organization,
  156. params: {integrationId},
  157. } = this.props;
  158. try {
  159. await this.api.requestPromise(
  160. `/organizations/${organization.slug}/integrations/${integrationId}/migrate-opsgenie/`,
  161. {
  162. method: 'PUT',
  163. }
  164. );
  165. this.setState(
  166. {
  167. plugins: (this.state.plugins || []).filter(({id}) => id === 'opsgenie'),
  168. },
  169. () => addSuccessMessage(t('Migration in progress.'))
  170. );
  171. } catch (error) {
  172. addErrorMessage(t('Something went wrong! Please try again.'));
  173. }
  174. };
  175. isInstalledOpsgeniePlugin = (plugin: PluginWithProjectList) => {
  176. return (
  177. plugin.id === 'opsgenie' &&
  178. plugin.projectList.length >= 1 &&
  179. plugin.projectList.find(({enabled}) => enabled === true)
  180. );
  181. };
  182. getAction = (provider: IntegrationProvider | undefined) => {
  183. const {integration, plugins} = this.state;
  184. const shouldMigrateJiraPlugin =
  185. provider &&
  186. ['jira', 'jira_server'].includes(provider.key) &&
  187. (plugins || []).find(({id}) => id === 'jira');
  188. const shouldMigrateOpsgeniePlugin =
  189. this.props.organization.features.includes('integrations-opsgenie-migration') &&
  190. provider &&
  191. provider.key === 'opsgenie' &&
  192. (plugins || []).find(this.isInstalledOpsgeniePlugin);
  193. const action =
  194. provider && provider.key === 'pagerduty' ? (
  195. <AddIntegration
  196. provider={provider}
  197. onInstall={this.onUpdateIntegration}
  198. account={integration.domainName}
  199. organization={this.props.organization}
  200. >
  201. {onClick => (
  202. <Button
  203. priority="primary"
  204. size="sm"
  205. icon={<IconAdd size="xs" isCircled />}
  206. onClick={() => onClick()}
  207. >
  208. {t('Add Services')}
  209. </Button>
  210. )}
  211. </AddIntegration>
  212. ) : shouldMigrateJiraPlugin ? (
  213. <Access access={['org:integrations']}>
  214. {({hasAccess}) => (
  215. <Confirm
  216. disabled={!hasAccess}
  217. header="Migrate Linked Issues from Jira Plugins"
  218. renderMessage={() => (
  219. <Fragment>
  220. <p>
  221. {t(
  222. 'This will automatically associate all the Linked Issues of your Jira Plugins to this integration.'
  223. )}
  224. </p>
  225. <p>
  226. {t(
  227. 'If the Jira Plugins had the option checked to automatically create a Jira ticket for every new Sentry issue checked, you will need to create alert rules to recreate this behavior. Jira Server does not have this feature.'
  228. )}
  229. </p>
  230. <p>
  231. {t(
  232. 'Once the migration is complete, your Jira Plugins will be disabled.'
  233. )}
  234. </p>
  235. </Fragment>
  236. )}
  237. onConfirm={() => {
  238. this.handleJiraMigration();
  239. }}
  240. >
  241. <Button priority="primary" size="md" disabled={!hasAccess}>
  242. {t('Migrate Plugin')}
  243. </Button>
  244. </Confirm>
  245. )}
  246. </Access>
  247. ) : provider && provider.key === 'discord' ? (
  248. <LinkButton
  249. aria-label="Open this server in the Discord app"
  250. size="sm"
  251. // @ts-ignore - the type of integration here is weird.
  252. href={`discord://discord.com/channels/${integration.externalId}`}
  253. >
  254. Open in Discord
  255. </LinkButton>
  256. ) : shouldMigrateOpsgeniePlugin ? (
  257. <Access access={['org:integrations']}>
  258. {({hasAccess}) => (
  259. <Confirm
  260. disabled={!hasAccess}
  261. header="Migrate API Keys and Alert Rules from Opsgenie"
  262. renderMessage={() => (
  263. <Fragment>
  264. <p>
  265. {t(
  266. 'This will automatically associate all the API keys and Alert Rules of your Opsgenie Plugins to this integration.'
  267. )}
  268. </p>
  269. <p>
  270. {t(
  271. 'API keys will be automatically named after one of the projects with which they were associated.'
  272. )}
  273. </p>
  274. <p>
  275. {t(
  276. 'Once the migration is complete, your Opsgenie Plugins will be disabled.'
  277. )}
  278. </p>
  279. </Fragment>
  280. )}
  281. onConfirm={() => {
  282. this.handleOpsgenieMigration();
  283. }}
  284. >
  285. <Button priority="primary" size="md" disabled={!hasAccess}>
  286. {t('Migrate Plugin')}
  287. </Button>
  288. </Confirm>
  289. )}
  290. </Access>
  291. ) : null;
  292. return action;
  293. };
  294. // TODO(Steve): Refactor components into separate tabs and use more generic tab logic
  295. renderMainTab(provider: IntegrationProvider) {
  296. const {organization} = this.props;
  297. const {integration} = this.state;
  298. const instructions =
  299. integration.dynamicDisplayInformation?.configure_integration?.instructions;
  300. return (
  301. <Fragment>
  302. {integration.configOrganization.length > 0 && (
  303. <Form
  304. hideFooter
  305. saveOnBlur
  306. allowUndo
  307. apiMethod="POST"
  308. initialData={integration.configData || {}}
  309. apiEndpoint={`/organizations/${organization.slug}/integrations/${integration.id}/`}
  310. >
  311. <JsonForm
  312. fields={integration.configOrganization}
  313. title={
  314. integration.provider.aspects.configure_integration?.title ||
  315. t('Organization Integration Settings')
  316. }
  317. />
  318. </Form>
  319. )}
  320. {instructions && instructions.length > 0 && (
  321. <Alert type="info">
  322. {instructions?.length === 1 ? (
  323. <span
  324. dangerouslySetInnerHTML={{__html: singleLineRenderer(instructions[0])}}
  325. />
  326. ) : (
  327. <List symbol={<IconArrow size="xs" direction="right" />}>
  328. {instructions?.map((instruction, i) => (
  329. <ListItem key={i}>
  330. <span
  331. dangerouslySetInnerHTML={{__html: singleLineRenderer(instruction)}}
  332. />
  333. </ListItem>
  334. )) ?? []}
  335. </List>
  336. )}
  337. </Alert>
  338. )}
  339. {provider.features.includes('alert-rule') && <IntegrationAlertRules />}
  340. {provider.features.includes('commits') && (
  341. <IntegrationRepos {...this.props} integration={integration} />
  342. )}
  343. {provider.features.includes('serverless') && (
  344. <IntegrationServerlessFunctions integration={integration} />
  345. )}
  346. </Fragment>
  347. );
  348. }
  349. renderBody() {
  350. const {integration} = this.state;
  351. const {organization, router} = this.props;
  352. const provider = this.state.config.providers.find(
  353. p => p.key === integration.provider.key
  354. );
  355. if (!provider) {
  356. return null;
  357. }
  358. const title = <IntegrationItem integration={integration} />;
  359. const header = (
  360. <SettingsPageHeader noTitleStyles title={title} action={this.getAction(provider)} />
  361. );
  362. const backButton = (
  363. <BackButtonWrapper>
  364. <Button
  365. icon={<IconArrow direction="left" size="sm" />}
  366. size="sm"
  367. onClick={() => {
  368. router.push(
  369. normalizeUrl({
  370. pathname: `/settings/${organization.slug}/integrations/${provider.key}/`,
  371. })
  372. );
  373. }}
  374. >
  375. Back
  376. </Button>
  377. </BackButtonWrapper>
  378. );
  379. return (
  380. <Fragment>
  381. {backButton}
  382. {header}
  383. {this.renderMainContent(provider)}
  384. <BreadcrumbTitle
  385. routes={this.props.routes}
  386. title={t('Configure %s', integration.provider.name)}
  387. />
  388. </Fragment>
  389. );
  390. }
  391. // renders everything below header
  392. renderMainContent(provider: IntegrationProvider) {
  393. // if no code mappings, render the single tab
  394. if (!this.hasStacktraceLinking(provider)) {
  395. return this.renderMainTab(provider);
  396. }
  397. // otherwise render the tab view
  398. const tabs = [
  399. ['repos', t('Repositories')],
  400. ['codeMappings', t('Code Mappings')],
  401. ...(this.hasCodeOwners(provider) ? [['userMappings', t('User Mappings')]] : []),
  402. ...(this.hasCodeOwners(provider) ? [['teamMappings', t('Team Mappings')]] : []),
  403. ] as [id: Tab, label: string][];
  404. return (
  405. <Fragment>
  406. <NavTabs underlined>
  407. {tabs.map(tabTuple => (
  408. <li
  409. key={tabTuple[0]}
  410. className={this.tab === tabTuple[0] ? 'active' : ''}
  411. onClick={() => this.onTabChange(tabTuple[0])}
  412. >
  413. <CapitalizedLink>{tabTuple[1]}</CapitalizedLink>
  414. </li>
  415. ))}
  416. </NavTabs>
  417. {this.renderTabContent(this.tab, provider)}
  418. </Fragment>
  419. );
  420. }
  421. renderTabContent(tab: Tab, provider: IntegrationProvider) {
  422. const {integration} = this.state;
  423. const {organization} = this.props;
  424. switch (tab) {
  425. case 'codeMappings':
  426. return <IntegrationCodeMappings integration={integration} />;
  427. case 'repos':
  428. return this.renderMainTab(provider);
  429. case 'userMappings':
  430. return <IntegrationExternalUserMappings integration={integration} />;
  431. case 'teamMappings':
  432. return <IntegrationExternalTeamMappings integration={integration} />;
  433. case 'settings':
  434. return (
  435. <IntegrationMainSettings
  436. onUpdate={this.onUpdateIntegration}
  437. organization={organization}
  438. integration={integration}
  439. />
  440. );
  441. default:
  442. return this.renderMainTab(provider);
  443. }
  444. }
  445. }
  446. export default withOrganization(withApi(ConfigureIntegration));
  447. const BackButtonWrapper = styled('div')`
  448. margin-bottom: ${space(2)};
  449. width: 100%;
  450. `;
  451. const CapitalizedLink = styled('a')`
  452. text-transform: capitalize;
  453. `;