integrationListDirectory.tsx 18 KB

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