configureIntegration.tsx 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488
  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() {
  116. return this.props.organization.features.includes('integrations-codeowners');
  117. }
  118. onTabChange = (value: Tab) => {
  119. this.setState({tab: value});
  120. };
  121. get tab() {
  122. return this.state.tab || 'repos';
  123. }
  124. onUpdateIntegration = () => {
  125. this.setState(this.getDefaultState(), this.fetchData);
  126. };
  127. handleJiraMigration = async () => {
  128. try {
  129. const {
  130. organization,
  131. params: {integrationId},
  132. } = this.props;
  133. await this.api.requestPromise(
  134. `/organizations/${organization.slug}/integrations/${integrationId}/issues/`,
  135. {
  136. method: 'PUT',
  137. data: {},
  138. }
  139. );
  140. this.setState(
  141. {
  142. plugins: (this.state.plugins || []).filter(({id}) => id === 'jira'),
  143. },
  144. () => addSuccessMessage(t('Migration in progress.'))
  145. );
  146. } catch (error) {
  147. addErrorMessage(t('Something went wrong! Please try again.'));
  148. }
  149. };
  150. handleOpsgenieMigration = async () => {
  151. const {
  152. organization,
  153. params: {integrationId},
  154. } = this.props;
  155. try {
  156. await this.api.requestPromise(
  157. `/organizations/${organization.slug}/integrations/${integrationId}/migrate-opsgenie/`,
  158. {
  159. method: 'PUT',
  160. }
  161. );
  162. this.setState(
  163. {
  164. plugins: (this.state.plugins || []).filter(({id}) => id === 'opsgenie'),
  165. },
  166. () => addSuccessMessage(t('Migration in progress.'))
  167. );
  168. } catch (error) {
  169. addErrorMessage(t('Something went wrong! Please try again.'));
  170. }
  171. };
  172. isInstalledOpsgeniePlugin = (plugin: PluginWithProjectList) => {
  173. return (
  174. plugin.id === 'opsgenie' &&
  175. plugin.projectList.length >= 1 &&
  176. plugin.projectList.find(({enabled}) => enabled === true)
  177. );
  178. };
  179. getAction = (provider: IntegrationProvider | undefined) => {
  180. const {integration, plugins} = this.state;
  181. const shouldMigrateJiraPlugin =
  182. provider &&
  183. ['jira', 'jira_server'].includes(provider.key) &&
  184. (plugins || []).find(({id}) => id === 'jira');
  185. const shouldMigrateOpsgeniePlugin =
  186. this.props.organization.features.includes('integrations-opsgenie-migration') &&
  187. provider &&
  188. provider.key === 'opsgenie' &&
  189. (plugins || []).find(this.isInstalledOpsgeniePlugin);
  190. const action =
  191. provider && provider.key === 'pagerduty' ? (
  192. <AddIntegration
  193. provider={provider}
  194. onInstall={this.onUpdateIntegration}
  195. account={integration.domainName}
  196. organization={this.props.organization}
  197. >
  198. {onClick => (
  199. <Button
  200. priority="primary"
  201. size="sm"
  202. icon={<IconAdd size="xs" isCircled />}
  203. onClick={() => onClick()}
  204. >
  205. {t('Add Services')}
  206. </Button>
  207. )}
  208. </AddIntegration>
  209. ) : shouldMigrateJiraPlugin ? (
  210. <Access access={['org:integrations']}>
  211. {({hasAccess}) => (
  212. <Confirm
  213. disabled={!hasAccess}
  214. header="Migrate Linked Issues from Jira Plugins"
  215. renderMessage={() => (
  216. <Fragment>
  217. <p>
  218. {t(
  219. 'This will automatically associate all the Linked Issues of your Jira Plugins to this integration.'
  220. )}
  221. </p>
  222. <p>
  223. {t(
  224. '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.'
  225. )}
  226. </p>
  227. <p>
  228. {t(
  229. 'Once the migration is complete, your Jira Plugins will be disabled.'
  230. )}
  231. </p>
  232. </Fragment>
  233. )}
  234. onConfirm={() => {
  235. this.handleJiraMigration();
  236. }}
  237. >
  238. <Button priority="primary" size="md" disabled={!hasAccess}>
  239. {t('Migrate Plugin')}
  240. </Button>
  241. </Confirm>
  242. )}
  243. </Access>
  244. ) : provider && provider.key === 'discord' ? (
  245. <LinkButton
  246. aria-label="Open this server in the Discord app"
  247. size="sm"
  248. // @ts-ignore - the type of integration here is weird.
  249. href={`discord://discord.com/channels/${integration.externalId}`}
  250. >
  251. Open in Discord
  252. </LinkButton>
  253. ) : shouldMigrateOpsgeniePlugin ? (
  254. <Access access={['org:integrations']}>
  255. {({hasAccess}) => (
  256. <Confirm
  257. disabled={!hasAccess}
  258. header="Migrate API Keys and Alert Rules from Opsgenie"
  259. renderMessage={() => (
  260. <Fragment>
  261. <p>
  262. {t(
  263. 'This will automatically associate all the API keys and Alert Rules of your Opsgenie Plugins to this integration.'
  264. )}
  265. </p>
  266. <p>
  267. {t(
  268. 'API keys will be automatically named after one of the projects with which they were associated.'
  269. )}
  270. </p>
  271. <p>
  272. {t(
  273. 'Once the migration is complete, your Opsgenie Plugins will be disabled.'
  274. )}
  275. </p>
  276. </Fragment>
  277. )}
  278. onConfirm={() => {
  279. this.handleOpsgenieMigration();
  280. }}
  281. >
  282. <Button priority="primary" size="md" disabled={!hasAccess}>
  283. {t('Migrate Plugin')}
  284. </Button>
  285. </Confirm>
  286. )}
  287. </Access>
  288. ) : null;
  289. return action;
  290. };
  291. // TODO(Steve): Refactor components into separate tabs and use more generic tab logic
  292. renderMainTab(provider: IntegrationProvider) {
  293. const {organization} = this.props;
  294. const {integration} = this.state;
  295. const instructions =
  296. integration.dynamicDisplayInformation?.configure_integration?.instructions;
  297. return (
  298. <Fragment>
  299. {integration.configOrganization.length > 0 && (
  300. <Form
  301. hideFooter
  302. saveOnBlur
  303. allowUndo
  304. apiMethod="POST"
  305. initialData={integration.configData || {}}
  306. apiEndpoint={`/organizations/${organization.slug}/integrations/${integration.id}/`}
  307. >
  308. <JsonForm
  309. fields={integration.configOrganization}
  310. title={
  311. integration.provider.aspects.configure_integration?.title ||
  312. t('Organization Integration Settings')
  313. }
  314. />
  315. </Form>
  316. )}
  317. {instructions && instructions.length > 0 && (
  318. <Alert type="info">
  319. {instructions?.length === 1 ? (
  320. <span
  321. dangerouslySetInnerHTML={{__html: singleLineRenderer(instructions[0])}}
  322. />
  323. ) : (
  324. <List symbol={<IconArrow size="xs" direction="right" />}>
  325. {instructions?.map((instruction, i) => (
  326. <ListItem key={i}>
  327. <span
  328. dangerouslySetInnerHTML={{__html: singleLineRenderer(instruction)}}
  329. />
  330. </ListItem>
  331. )) ?? []}
  332. </List>
  333. )}
  334. </Alert>
  335. )}
  336. {provider.features.includes('alert-rule') && <IntegrationAlertRules />}
  337. {provider.features.includes('commits') && (
  338. <IntegrationRepos {...this.props} integration={integration} />
  339. )}
  340. {provider.features.includes('serverless') && (
  341. <IntegrationServerlessFunctions integration={integration} />
  342. )}
  343. </Fragment>
  344. );
  345. }
  346. renderBody() {
  347. const {integration} = this.state;
  348. const {organization, router} = this.props;
  349. const provider = this.state.config.providers.find(
  350. p => p.key === integration.provider.key
  351. );
  352. if (!provider) {
  353. return null;
  354. }
  355. const title = <IntegrationItem integration={integration} />;
  356. const header = (
  357. <SettingsPageHeader noTitleStyles title={title} action={this.getAction(provider)} />
  358. );
  359. const backButton = (
  360. <BackButtonWrapper>
  361. <Button
  362. icon={<IconArrow direction="left" size="sm" />}
  363. size="sm"
  364. onClick={() => {
  365. router.push(
  366. normalizeUrl({
  367. pathname: `/settings/${organization.slug}/integrations/${provider.key}/`,
  368. })
  369. );
  370. }}
  371. >
  372. Back
  373. </Button>
  374. </BackButtonWrapper>
  375. );
  376. return (
  377. <Fragment>
  378. {backButton}
  379. {header}
  380. {this.renderMainContent(provider)}
  381. <BreadcrumbTitle
  382. routes={this.props.routes}
  383. title={t('Configure %s', integration.provider.name)}
  384. />
  385. </Fragment>
  386. );
  387. }
  388. // renders everything below header
  389. renderMainContent(provider: IntegrationProvider) {
  390. // if no code mappings, render the single tab
  391. if (!this.hasStacktraceLinking(provider)) {
  392. return this.renderMainTab(provider);
  393. }
  394. // otherwise render the tab view
  395. const tabs = [
  396. ['repos', t('Repositories')],
  397. ['codeMappings', t('Code Mappings')],
  398. ...(this.hasCodeOwners() ? [['userMappings', t('User Mappings')]] : []),
  399. ...(this.hasCodeOwners() ? [['teamMappings', t('Team Mappings')]] : []),
  400. ] as [id: Tab, label: string][];
  401. return (
  402. <Fragment>
  403. <NavTabs underlined>
  404. {tabs.map(tabTuple => (
  405. <li
  406. key={tabTuple[0]}
  407. className={this.tab === tabTuple[0] ? 'active' : ''}
  408. onClick={() => this.onTabChange(tabTuple[0])}
  409. >
  410. <CapitalizedLink>{tabTuple[1]}</CapitalizedLink>
  411. </li>
  412. ))}
  413. </NavTabs>
  414. {this.renderTabContent(this.tab, provider)}
  415. </Fragment>
  416. );
  417. }
  418. renderTabContent(tab: Tab, provider: IntegrationProvider) {
  419. const {integration} = this.state;
  420. const {organization} = this.props;
  421. switch (tab) {
  422. case 'codeMappings':
  423. return <IntegrationCodeMappings integration={integration} />;
  424. case 'repos':
  425. return this.renderMainTab(provider);
  426. case 'userMappings':
  427. return <IntegrationExternalUserMappings integration={integration} />;
  428. case 'teamMappings':
  429. return <IntegrationExternalTeamMappings integration={integration} />;
  430. case 'settings':
  431. return (
  432. <IntegrationMainSettings
  433. onUpdate={this.onUpdateIntegration}
  434. organization={organization}
  435. integration={integration}
  436. />
  437. );
  438. default:
  439. return this.renderMainTab(provider);
  440. }
  441. }
  442. }
  443. export default withOrganization(withApi(ConfigureIntegration));
  444. const BackButtonWrapper = styled('div')`
  445. margin-bottom: ${space(2)};
  446. width: 100%;
  447. `;
  448. const CapitalizedLink = styled('a')`
  449. text-transform: capitalize;
  450. `;