integrationListDirectory.tsx 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604
  1. import {Fragment} from 'react';
  2. import type {RouteComponentProps} from 'react-router';
  3. import styled from '@emotion/styled';
  4. import debounce from 'lodash/debounce';
  5. import groupBy from 'lodash/groupBy';
  6. import startCase from 'lodash/startCase';
  7. import * as qs from 'query-string';
  8. import DocIntegrationAvatar from 'sentry/components/avatar/docIntegrationAvatar';
  9. import DeprecatedAsyncComponent from 'sentry/components/deprecatedAsyncComponent';
  10. import SelectControl from 'sentry/components/forms/controls/selectControl';
  11. import HookOrDefault from 'sentry/components/hookOrDefault';
  12. import ExternalLink from 'sentry/components/links/externalLink';
  13. import Panel from 'sentry/components/panels/panel';
  14. import PanelBody from 'sentry/components/panels/panelBody';
  15. import SearchBar from 'sentry/components/searchBar';
  16. import SentryAppIcon from 'sentry/components/sentryAppIcon';
  17. import SentryDocumentTitle from 'sentry/components/sentryDocumentTitle';
  18. import {t, tct} from 'sentry/locale';
  19. import {space} from 'sentry/styles/space';
  20. import type {
  21. AppOrProviderOrPlugin,
  22. DocIntegration,
  23. Integration,
  24. IntegrationProvider,
  25. Organization,
  26. PluginWithProjectList,
  27. SentryApp,
  28. SentryAppInstallation,
  29. } from 'sentry/types';
  30. import {uniq} from 'sentry/utils/array/uniq';
  31. import {browserHistory} from 'sentry/utils/browserHistory';
  32. import type {Fuse} from 'sentry/utils/fuzzySearch';
  33. import {createFuzzySearch} from 'sentry/utils/fuzzySearch';
  34. import {
  35. getAlertText,
  36. getCategoriesForIntegration,
  37. getIntegrationStatus,
  38. getSentryAppInstallStatus,
  39. isDocIntegration,
  40. isPlugin,
  41. isSentryApp,
  42. trackIntegrationAnalytics,
  43. } from 'sentry/utils/integrationUtil';
  44. import withOrganization from 'sentry/utils/withOrganization';
  45. import SettingsPageHeader from 'sentry/views/settings/components/settingsPageHeader';
  46. import PermissionAlert from 'sentry/views/settings/organization/permissionAlert';
  47. import CreateIntegrationButton from 'sentry/views/settings/organizationIntegrations/createIntegrationButton';
  48. import ReinstallAlert from 'sentry/views/settings/organizationIntegrations/reinstallAlert';
  49. import {POPULARITY_WEIGHT} from './constants';
  50. import IntegrationRow from './integrationRow';
  51. const FirstPartyIntegrationAlert = HookOrDefault({
  52. hookName: 'component:first-party-integration-alert',
  53. defaultComponent: () => null,
  54. });
  55. const fuseOptions = {
  56. threshold: 0.3,
  57. location: 0,
  58. distance: 100,
  59. includeScore: true as const,
  60. keys: ['slug', 'key', 'name', 'id'],
  61. };
  62. type Props = RouteComponentProps<{}, {}> & {
  63. hideHeader: boolean;
  64. organization: Organization;
  65. };
  66. type State = {
  67. appInstalls: SentryAppInstallation[] | null;
  68. config: {providers: IntegrationProvider[]} | null;
  69. displayedList: AppOrProviderOrPlugin[];
  70. docIntegrations: DocIntegration[] | null;
  71. integrations: Integration[] | null;
  72. list: AppOrProviderOrPlugin[];
  73. orgOwnedApps: SentryApp[] | null;
  74. plugins: PluginWithProjectList[] | null;
  75. publishedApps: SentryApp[] | null;
  76. searchInput: string;
  77. selectedCategory: string;
  78. extraApp?: SentryApp;
  79. fuzzy?: Fuse<AppOrProviderOrPlugin>;
  80. };
  81. const TEXT_SEARCH_ANALYTICS_DEBOUNCE_IN_MS = 1000;
  82. export class IntegrationListDirectory extends DeprecatedAsyncComponent<
  83. Props & DeprecatedAsyncComponent['props'],
  84. State & DeprecatedAsyncComponent['state']
  85. > {
  86. // Some integrations require visiting a different website to add them. When
  87. // we come back to the tab we want to show our integrations as soon as we can.
  88. shouldReload = true;
  89. reloadOnVisible = true;
  90. shouldReloadOnVisible = true;
  91. getDefaultState() {
  92. return {
  93. ...super.getDefaultState(),
  94. list: [],
  95. displayedList: [],
  96. selectedCategory: '',
  97. };
  98. }
  99. onLoadAllEndpointsSuccess() {
  100. const {publishedApps, orgOwnedApps, extraApp, plugins, docIntegrations} = this.state;
  101. const published = publishedApps || [];
  102. // If we have an extra app in state from query parameter, add it as org owned app
  103. if (orgOwnedApps !== null && extraApp) {
  104. orgOwnedApps.push(extraApp);
  105. }
  106. // we don't want the app to render twice if its the org that created
  107. // the published app.
  108. const orgOwned = orgOwnedApps?.filter(
  109. app => !published.find(p => p.slug === app.slug)
  110. );
  111. /**
  112. * We should have three sections:
  113. * 1. Public apps and integrations available to everyone
  114. * 2. Unpublished apps available to that org
  115. * 3. Internal apps available to that org
  116. */
  117. const combined = ([] as AppOrProviderOrPlugin[])
  118. .concat(published)
  119. .concat(orgOwned ?? [])
  120. .concat(this.providers)
  121. .concat(plugins ?? [])
  122. .concat(docIntegrations ?? []);
  123. const list = this.sortIntegrations(combined);
  124. const {searchInput, selectedCategory} = this.getFilterParameters();
  125. this.setState({list, searchInput, selectedCategory}, () => {
  126. this.updateDisplayedList();
  127. this.trackPageViewed();
  128. });
  129. }
  130. trackPageViewed() {
  131. // count the number of installed apps
  132. const {integrations, publishedApps, plugins} = this.state;
  133. const integrationsInstalled = new Set();
  134. // add installed integrations
  135. integrations?.forEach((integration: Integration) => {
  136. integrationsInstalled.add(integration.provider.key);
  137. });
  138. // add sentry apps
  139. publishedApps?.filter(this.getAppInstall).forEach((sentryApp: SentryApp) => {
  140. integrationsInstalled.add(sentryApp.slug);
  141. });
  142. // add plugins
  143. plugins?.forEach((plugin: PluginWithProjectList) => {
  144. if (plugin.projectList.length) {
  145. integrationsInstalled.add(plugin.slug);
  146. }
  147. });
  148. trackIntegrationAnalytics(
  149. 'integrations.index_viewed',
  150. {
  151. integrations_installed: integrationsInstalled.size,
  152. view: 'integrations_directory',
  153. organization: this.props.organization,
  154. },
  155. {startSession: true}
  156. );
  157. }
  158. getEndpoints(): ReturnType<DeprecatedAsyncComponent['getEndpoints']> {
  159. const {organization} = this.props;
  160. const baseEndpoints: ([string, string, any] | [string, string])[] = [
  161. ['config', `/organizations/${organization.slug}/config/integrations/`],
  162. [
  163. 'integrations',
  164. `/organizations/${organization.slug}/integrations/`,
  165. {query: {includeConfig: 0}},
  166. ],
  167. ['orgOwnedApps', `/organizations/${organization.slug}/sentry-apps/`],
  168. ['publishedApps', '/sentry-apps/', {query: {status: 'published'}}],
  169. ['appInstalls', `/organizations/${organization.slug}/sentry-app-installations/`],
  170. ['plugins', `/organizations/${organization.slug}/plugins/configs/`],
  171. ['docIntegrations', '/doc-integrations/'],
  172. ];
  173. /**
  174. * optional app to load for super users
  175. * should only be done for unpublished integrations from another org
  176. * but no checks are in place to ensure the above condition
  177. */
  178. const extraAppSlug = new URLSearchParams(this.props.location.search).get('extra_app');
  179. if (extraAppSlug) {
  180. baseEndpoints.push(['extraApp', `/sentry-apps/${extraAppSlug}/`]);
  181. }
  182. return baseEndpoints;
  183. }
  184. // State
  185. get unmigratableReposByOrg() {
  186. // Group by [GitHub|BitBucket|VSTS] Org name
  187. return groupBy(this.state.unmigratableRepos, repo => repo.name.split('/')[0]);
  188. }
  189. get providers(): IntegrationProvider[] {
  190. return this.state.config?.providers ?? [];
  191. }
  192. getAppInstall = (app: SentryApp) =>
  193. this.state.appInstalls?.find(i => i.app.slug === app.slug);
  194. // Returns 0 if uninstalled, 1 if pending, and 2 if installed
  195. getInstallValue(integration: AppOrProviderOrPlugin) {
  196. const {integrations} = this.state;
  197. if (isPlugin(integration)) {
  198. return integration.projectList.length > 0 ? 2 : 0;
  199. }
  200. if (isSentryApp(integration)) {
  201. const install = this.getAppInstall(integration);
  202. if (install) {
  203. return install.status === 'pending' ? 1 : 2;
  204. }
  205. return 0;
  206. }
  207. if (isDocIntegration(integration)) {
  208. return 0;
  209. }
  210. return integrations?.find(i => i.provider.key === integration.key) ? 2 : 0;
  211. }
  212. getInstallStatuses(integrations: Integration[]) {
  213. const statusList = integrations?.map(getIntegrationStatus);
  214. // if we have conflicting statuses, we have a priority order
  215. if (statusList.includes('active')) {
  216. return 'Installed';
  217. }
  218. if (statusList.includes('disabled')) {
  219. return 'Disabled';
  220. }
  221. if (statusList.includes('pending_deletion')) {
  222. return 'Pending Deletion';
  223. }
  224. return 'Not Installed';
  225. }
  226. getPopularityWeight = (integration: AppOrProviderOrPlugin) => {
  227. if (isSentryApp(integration) || isDocIntegration(integration)) {
  228. return integration?.popularity ?? 1;
  229. }
  230. return POPULARITY_WEIGHT[integration.slug] ?? 1;
  231. };
  232. sortByName = (a: AppOrProviderOrPlugin, b: AppOrProviderOrPlugin) =>
  233. a.slug.localeCompare(b.slug);
  234. sortByPopularity = (a: AppOrProviderOrPlugin, b: AppOrProviderOrPlugin) => {
  235. const weightA = this.getPopularityWeight(a);
  236. const weightB = this.getPopularityWeight(b);
  237. return weightB - weightA;
  238. };
  239. sortByInstalled = (a: AppOrProviderOrPlugin, b: AppOrProviderOrPlugin) =>
  240. this.getInstallValue(b) - this.getInstallValue(a);
  241. sortIntegrations(integrations: AppOrProviderOrPlugin[]) {
  242. return integrations.sort((a: AppOrProviderOrPlugin, b: AppOrProviderOrPlugin) => {
  243. // sort by whether installed first
  244. const diffWeight = this.sortByInstalled(a, b);
  245. if (diffWeight !== 0) {
  246. return diffWeight;
  247. }
  248. // then sort by popularity
  249. const diffPop = this.sortByPopularity(a, b);
  250. if (diffPop !== 0) {
  251. return diffPop;
  252. }
  253. // then sort by name
  254. return this.sortByName(a, b);
  255. });
  256. }
  257. async componentDidUpdate(_: Props, prevState: State) {
  258. if (this.state.list.length !== prevState.list.length) {
  259. await this.createSearch();
  260. }
  261. }
  262. async createSearch() {
  263. const {list} = this.state;
  264. this.setState({
  265. fuzzy: await createFuzzySearch(list || [], fuseOptions),
  266. });
  267. }
  268. debouncedTrackIntegrationSearch = debounce((search: string, numResults: number) => {
  269. trackIntegrationAnalytics('integrations.directory_item_searched', {
  270. view: 'integrations_directory',
  271. search_term: search,
  272. num_results: numResults,
  273. organization: this.props.organization,
  274. });
  275. }, TEXT_SEARCH_ANALYTICS_DEBOUNCE_IN_MS);
  276. /**
  277. * Get filter parameters and guard against `qs.parse` returning arrays.
  278. */
  279. getFilterParameters = (): {searchInput: string; selectedCategory: string} => {
  280. const {category, search} = qs.parse(this.props.location.search);
  281. const selectedCategory = Array.isArray(category) ? category[0] : category || '';
  282. const searchInput = Array.isArray(search) ? search[0] : search || '';
  283. return {searchInput, selectedCategory};
  284. };
  285. /**
  286. * Update the query string with the current filter parameter values.
  287. */
  288. updateQueryString = () => {
  289. const {searchInput, selectedCategory} = this.state;
  290. const searchString = qs.stringify({
  291. ...qs.parse(this.props.location.search),
  292. search: searchInput ? searchInput : undefined,
  293. category: selectedCategory ? selectedCategory : undefined,
  294. });
  295. browserHistory.replace({
  296. pathname: this.props.location.pathname,
  297. search: searchString ? `?${searchString}` : undefined,
  298. });
  299. };
  300. /**
  301. * Filter the integrations list by ANDing together the search query and the category select.
  302. */
  303. updateDisplayedList = (): AppOrProviderOrPlugin[] => {
  304. const {fuzzy, list, searchInput, selectedCategory} = this.state;
  305. let displayedList = list;
  306. if (searchInput && fuzzy) {
  307. const searchResults = fuzzy.search(searchInput);
  308. displayedList = this.sortIntegrations(searchResults.map(i => i.item));
  309. }
  310. if (selectedCategory) {
  311. displayedList = displayedList.filter(integration =>
  312. getCategoriesForIntegration(integration).includes(selectedCategory)
  313. );
  314. }
  315. this.setState({displayedList});
  316. return displayedList;
  317. };
  318. handleSearchChange = (value: string) => {
  319. this.setState({searchInput: value}, () => {
  320. this.updateQueryString();
  321. const result = this.updateDisplayedList();
  322. if (value) {
  323. this.debouncedTrackIntegrationSearch(value, result.length);
  324. }
  325. });
  326. };
  327. onCategorySelect = ({value: category}: {value: string}) => {
  328. this.setState({selectedCategory: category}, () => {
  329. this.updateQueryString();
  330. this.updateDisplayedList();
  331. if (category) {
  332. trackIntegrationAnalytics('integrations.directory_category_selected', {
  333. view: 'integrations_directory',
  334. category,
  335. organization: this.props.organization,
  336. });
  337. }
  338. });
  339. };
  340. getCategoryLabel = (value: string) => {
  341. if (value === 'api') {
  342. return 'API';
  343. }
  344. return startCase(value);
  345. };
  346. // Rendering
  347. renderProvider = (provider: IntegrationProvider) => {
  348. const {organization} = this.props;
  349. // find the integration installations for that provider
  350. const integrations =
  351. this.state.integrations?.filter(i => i.provider.key === provider.key) ?? [];
  352. return (
  353. <IntegrationRow
  354. key={`row-${provider.key}`}
  355. data-test-id="integration-row"
  356. organization={organization}
  357. type="firstParty"
  358. slug={provider.slug}
  359. displayName={provider.name}
  360. status={this.getInstallStatuses(integrations)}
  361. publishStatus="published"
  362. configurations={integrations.length}
  363. categories={getCategoriesForIntegration(provider)}
  364. alertText={getAlertText(integrations)}
  365. resolveText={t('Update Now')}
  366. customAlert={
  367. <FirstPartyIntegrationAlert integrations={integrations} wrapWithContainer />
  368. }
  369. />
  370. );
  371. };
  372. renderPlugin = (plugin: PluginWithProjectList) => {
  373. const {organization} = this.props;
  374. const isLegacy = plugin.isHidden;
  375. const displayName = `${plugin.name} ${isLegacy ? '(Legacy)' : ''}`;
  376. // hide legacy integrations if we don't have any projects with them
  377. if (isLegacy && !plugin.projectList.length) {
  378. return null;
  379. }
  380. return (
  381. <IntegrationRow
  382. key={`row-plugin-${plugin.id}`}
  383. data-test-id="integration-row"
  384. organization={organization}
  385. type="plugin"
  386. slug={plugin.slug}
  387. displayName={displayName}
  388. status={plugin.projectList.length ? 'Installed' : 'Not Installed'}
  389. publishStatus="published"
  390. configurations={plugin.projectList.length}
  391. categories={getCategoriesForIntegration(plugin)}
  392. plugin={plugin}
  393. />
  394. );
  395. };
  396. // render either an internal or non-internal app
  397. renderSentryApp = (app: SentryApp) => {
  398. const {organization} = this.props;
  399. const status = getSentryAppInstallStatus(this.getAppInstall(app));
  400. const categories = getCategoriesForIntegration(app);
  401. return (
  402. <IntegrationRow
  403. key={`sentry-app-row-${app.slug}`}
  404. data-test-id="integration-row"
  405. organization={organization}
  406. type="sentryApp"
  407. slug={app.slug}
  408. displayName={app.name}
  409. status={status}
  410. publishStatus={app.status}
  411. configurations={0}
  412. categories={categories}
  413. customIcon={<SentryAppIcon sentryApp={app} size={36} />}
  414. />
  415. );
  416. };
  417. renderDocIntegration = (doc: DocIntegration) => {
  418. const {organization} = this.props;
  419. return (
  420. <IntegrationRow
  421. key={`doc-int-${doc.slug}`}
  422. data-test-id="integration-row"
  423. organization={organization}
  424. type="docIntegration"
  425. slug={doc.slug}
  426. displayName={doc.name}
  427. publishStatus="published"
  428. configurations={0}
  429. categories={getCategoriesForIntegration(doc)}
  430. customIcon={<DocIntegrationAvatar docIntegration={doc} size={36} />}
  431. />
  432. );
  433. };
  434. renderIntegration = (integration: AppOrProviderOrPlugin) => {
  435. if (isSentryApp(integration)) {
  436. return this.renderSentryApp(integration);
  437. }
  438. if (isPlugin(integration)) {
  439. return this.renderPlugin(integration);
  440. }
  441. if (isDocIntegration(integration)) {
  442. return this.renderDocIntegration(integration);
  443. }
  444. return this.renderProvider(integration);
  445. };
  446. renderBody() {
  447. const {organization} = this.props;
  448. const {displayedList, list, searchInput, selectedCategory, integrations} = this.state;
  449. const title = t('Integrations');
  450. const categoryList = uniq(list.flatMap(getCategoriesForIntegration)).sort();
  451. return (
  452. <Fragment>
  453. <SentryDocumentTitle title={title} orgSlug={organization.slug} />
  454. {!this.props.hideHeader && (
  455. <SettingsPageHeader
  456. title={title}
  457. body={
  458. <ActionContainer>
  459. <SelectControl
  460. name="select-categories"
  461. onChange={this.onCategorySelect}
  462. value={selectedCategory}
  463. options={[
  464. {value: '', label: t('All Categories')},
  465. ...categoryList.map(category => ({
  466. value: category,
  467. label: this.getCategoryLabel(category),
  468. })),
  469. ]}
  470. />
  471. <SearchBar
  472. query={searchInput || ''}
  473. onChange={this.handleSearchChange}
  474. placeholder={t('Filter Integrations...')}
  475. aria-label={t('Filter')}
  476. width="100%"
  477. data-test-id="search-bar"
  478. />
  479. </ActionContainer>
  480. }
  481. action={<CreateIntegrationButton analyticsView="integrations_directory" />}
  482. />
  483. )}
  484. <PermissionAlert access={['org:integrations']} />
  485. <ReinstallAlert integrations={integrations} />
  486. <Panel>
  487. <PanelBody data-test-id="integration-panel">
  488. {displayedList.length ? (
  489. displayedList.map(this.renderIntegration)
  490. ) : (
  491. <EmptyResultsContainer>
  492. <EmptyResultsBody>
  493. {tct('No Integrations found for "[searchTerm]".', {
  494. searchTerm: searchInput,
  495. })}
  496. </EmptyResultsBody>
  497. <EmptyResultsBodyBold>
  498. {t("Not seeing what you're looking for?")}
  499. </EmptyResultsBodyBold>
  500. <EmptyResultsBody>
  501. {tct('[link:Build it on the Sentry Integration Platform.]', {
  502. link: (
  503. <ExternalLink href="https://docs.sentry.io/product/integrations/integration-platform/" />
  504. ),
  505. })}
  506. </EmptyResultsBody>
  507. </EmptyResultsContainer>
  508. )}
  509. </PanelBody>
  510. </Panel>
  511. </Fragment>
  512. );
  513. }
  514. }
  515. const ActionContainer = styled('div')`
  516. display: grid;
  517. grid-template-columns: 240px auto;
  518. gap: ${space(2)};
  519. `;
  520. const EmptyResultsContainer = styled('div')`
  521. height: 200px;
  522. display: flex;
  523. flex-direction: column;
  524. align-items: center;
  525. justify-content: center;
  526. `;
  527. const EmptyResultsBody = styled('div')`
  528. font-size: 16px;
  529. line-height: 28px;
  530. color: ${p => p.theme.gray300};
  531. padding-bottom: ${space(2)};
  532. `;
  533. const EmptyResultsBodyBold = styled(EmptyResultsBody)`
  534. font-weight: ${p => p.theme.fontWeightBold};
  535. `;
  536. export default withOrganization(IntegrationListDirectory);