configureIntegration.tsx 16 KB

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