createProject.tsx 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464
  1. import {useCallback, useContext, useMemo, useState} from 'react';
  2. import {browserHistory} from 'react-router';
  3. import styled from '@emotion/styled';
  4. import * as Sentry from '@sentry/react';
  5. import omit from 'lodash/omit';
  6. import startCase from 'lodash/startCase';
  7. import {PlatformIcon} from 'platformicons';
  8. import {addErrorMessage, addSuccessMessage} from 'sentry/actionCreators/indicator';
  9. import {openModal} from 'sentry/actionCreators/modal';
  10. import Access from 'sentry/components/acl/access';
  11. import {Alert} from 'sentry/components/alert';
  12. import {Button} from 'sentry/components/button';
  13. import Input from 'sentry/components/input';
  14. import * as Layout from 'sentry/components/layouts/thirds';
  15. import ExternalLink from 'sentry/components/links/externalLink';
  16. import List from 'sentry/components/list';
  17. import ListItem from 'sentry/components/list/listItem';
  18. import {SupportedLanguages} from 'sentry/components/onboarding/frameworkSuggestionModal';
  19. import PlatformPicker, {Platform} from 'sentry/components/platformPicker';
  20. import {useProjectCreationAccess} from 'sentry/components/projects/useProjectCreationAccess';
  21. import TeamSelector from 'sentry/components/teamSelector';
  22. import {Tooltip} from 'sentry/components/tooltip';
  23. import {t, tct} from 'sentry/locale';
  24. import ProjectsStore from 'sentry/stores/projectsStore';
  25. import {space} from 'sentry/styles/space';
  26. import {OnboardingSelectedSDK, Team} from 'sentry/types';
  27. import {trackAnalytics} from 'sentry/utils/analytics';
  28. import useRouteAnalyticsEventNames from 'sentry/utils/routeAnalytics/useRouteAnalyticsEventNames';
  29. import slugify from 'sentry/utils/slugify';
  30. import useApi from 'sentry/utils/useApi';
  31. import {useLocation} from 'sentry/utils/useLocation';
  32. import useOrganization from 'sentry/utils/useOrganization';
  33. import {useTeams} from 'sentry/utils/useTeams';
  34. import {normalizeUrl} from 'sentry/utils/withDomainRequired';
  35. import IssueAlertOptions, {
  36. MetricValues,
  37. RuleAction,
  38. } from 'sentry/views/projectInstall/issueAlertOptions';
  39. import {GettingStartedWithProjectContext} from 'sentry/views/projects/gettingStartedWithProjectContext';
  40. type IssueAlertFragment = Parameters<
  41. React.ComponentProps<typeof IssueAlertOptions>['onChange']
  42. >[0];
  43. function CreateProject() {
  44. const api = useApi();
  45. const organization = useOrganization();
  46. const location = useLocation();
  47. const gettingStartedWithProjectContext = useContext(GettingStartedWithProjectContext);
  48. const {teams} = useTeams();
  49. const autoFill =
  50. location.query.referrer === 'getting-started' &&
  51. location.query.project === gettingStartedWithProjectContext.project?.id;
  52. const accessTeams = teams.filter((team: Team) => team.access.includes('team:admin'));
  53. useRouteAnalyticsEventNames(
  54. 'project_creation_page.viewed',
  55. 'Project Create: Creation page viewed'
  56. );
  57. const [projectName, setProjectName] = useState(
  58. autoFill ? gettingStartedWithProjectContext.project?.name : ''
  59. );
  60. const [platform, setPlatform] = useState<OnboardingSelectedSDK | undefined>(
  61. autoFill ? gettingStartedWithProjectContext.project?.platform : undefined
  62. );
  63. const [team, setTeam] = useState(
  64. autoFill
  65. ? gettingStartedWithProjectContext.project?.teamSlug ?? accessTeams?.[0]?.slug
  66. : accessTeams?.[0]?.slug
  67. );
  68. const [errors, setErrors] = useState(false);
  69. const [inFlight, setInFlight] = useState(false);
  70. const [alertRuleConfig, setAlertRuleConfig] = useState<IssueAlertFragment | undefined>(
  71. undefined
  72. );
  73. const frameworkSelectionEnabled = !!organization?.features.includes(
  74. 'onboarding-sdk-selection'
  75. );
  76. const createProject = useCallback(
  77. async (selectedFramework?: OnboardingSelectedSDK) => {
  78. const {slug} = organization;
  79. const {
  80. shouldCreateCustomRule,
  81. name,
  82. conditions,
  83. actions,
  84. actionMatch,
  85. frequency,
  86. defaultRules,
  87. } = alertRuleConfig || {};
  88. const selectedPlatform = selectedFramework ?? platform;
  89. if (!selectedPlatform) {
  90. addErrorMessage(t('Please select a platform in Step 1'));
  91. return;
  92. }
  93. setInFlight(true);
  94. try {
  95. const url = team
  96. ? `/teams/${slug}/${team}/projects/`
  97. : `/organizations/${slug}/experimental/projects/`;
  98. const projectData = await api.requestPromise(url, {
  99. method: 'POST',
  100. data: {
  101. name: projectName,
  102. platform: selectedPlatform.key,
  103. default_rules: defaultRules ?? true,
  104. },
  105. });
  106. let ruleId: string | undefined;
  107. if (shouldCreateCustomRule) {
  108. const ruleData = await api.requestPromise(
  109. `/projects/${organization.slug}/${projectData.slug}/rules/`,
  110. {
  111. method: 'POST',
  112. data: {
  113. name,
  114. conditions,
  115. actions,
  116. actionMatch,
  117. frequency,
  118. },
  119. }
  120. );
  121. ruleId = ruleData.id;
  122. }
  123. trackAnalytics('project_creation_page.created', {
  124. organization,
  125. issue_alert: defaultRules
  126. ? 'Default'
  127. : shouldCreateCustomRule
  128. ? 'Custom'
  129. : 'No Rule',
  130. project_id: projectData.id,
  131. rule_id: ruleId || '',
  132. });
  133. ProjectsStore.onCreateSuccess(projectData, organization.slug);
  134. if (team) {
  135. addSuccessMessage(
  136. tct('Created project [project]', {
  137. project: `${projectData.slug}`,
  138. })
  139. );
  140. } else {
  141. addSuccessMessage(
  142. tct('Created [project] under new team [team]', {
  143. project: `${projectData.slug}`,
  144. team: `#${projectData.team_slug}`,
  145. })
  146. );
  147. }
  148. browserHistory.push(
  149. normalizeUrl(
  150. `/organizations/${organization.slug}/projects/${projectData.slug}/getting-started/`
  151. )
  152. );
  153. } catch (err) {
  154. setInFlight(false);
  155. setErrors(err.responseJSON);
  156. addErrorMessage(
  157. tct('Failed to create project [project]', {
  158. project: `${projectName}`,
  159. })
  160. );
  161. // Only log this if the error is something other than:
  162. // * The user not having access to create a project, or,
  163. // * A project with that slug already exists
  164. if (err.status !== 403 && err.status !== 409) {
  165. Sentry.withScope(scope => {
  166. scope.setExtra('err', err);
  167. Sentry.captureMessage('Project creation failed');
  168. });
  169. }
  170. }
  171. },
  172. [api, alertRuleConfig, organization, platform, projectName, team]
  173. );
  174. const handleProjectCreation = useCallback(async () => {
  175. const selectedPlatform = platform;
  176. if (!selectedPlatform) {
  177. addErrorMessage(t('Please select a platform in Step 1'));
  178. return;
  179. }
  180. if (
  181. selectedPlatform.type !== 'language' ||
  182. !Object.values(SupportedLanguages).includes(
  183. selectedPlatform.language as SupportedLanguages
  184. )
  185. ) {
  186. createProject();
  187. return;
  188. }
  189. const {FrameworkSuggestionModal, modalCss} = await import(
  190. 'sentry/components/onboarding/frameworkSuggestionModal'
  191. );
  192. openModal(
  193. deps => (
  194. <FrameworkSuggestionModal
  195. {...deps}
  196. organization={organization}
  197. selectedPlatform={selectedPlatform}
  198. onConfigure={selectedFramework => {
  199. createProject(selectedFramework);
  200. }}
  201. onSkip={createProject}
  202. />
  203. ),
  204. {
  205. modalCss,
  206. onClose: () => {
  207. trackAnalytics('project_creation.select_framework_modal_close_button_clicked', {
  208. platform: selectedPlatform.key,
  209. organization,
  210. });
  211. },
  212. }
  213. );
  214. }, [platform, createProject, organization]);
  215. function handlePlatformChange(selectedPlatform: Platform | null) {
  216. if (!selectedPlatform?.id) {
  217. setPlatform(undefined);
  218. setProjectName('');
  219. return;
  220. }
  221. const userModifiedName = !!projectName && projectName !== platform?.key;
  222. const newName = userModifiedName ? projectName : selectedPlatform.id;
  223. setPlatform({
  224. ...omit(selectedPlatform, 'id'),
  225. key: selectedPlatform.id,
  226. });
  227. setProjectName(newName);
  228. }
  229. const {shouldCreateCustomRule, conditions} = alertRuleConfig || {};
  230. const {canCreateProject} = useProjectCreationAccess({organization});
  231. const canCreateTeam = organization.access.includes('project:admin');
  232. const isOrgMemberWithNoAccess = accessTeams.length === 0 && !canCreateTeam;
  233. const isMissingTeam = !isOrgMemberWithNoAccess && !team;
  234. const isMissingProjectName = projectName === '';
  235. const isMissingAlertThreshold =
  236. shouldCreateCustomRule && !conditions?.every?.(condition => condition.value);
  237. const formErrorCount = [
  238. isMissingTeam,
  239. isMissingProjectName,
  240. isMissingAlertThreshold,
  241. ].filter(value => value).length;
  242. const canSubmitForm = !inFlight && canCreateProject && formErrorCount === 0;
  243. let submitTooltipText: string = t('Please select a team');
  244. if (formErrorCount > 1) {
  245. submitTooltipText = t('Please fill out all the required fields');
  246. } else if (isMissingProjectName) {
  247. submitTooltipText = t('Please provide a project name');
  248. } else if (isMissingAlertThreshold) {
  249. submitTooltipText = t('Please provide an alert threshold');
  250. }
  251. const alertFrequencyDefaultValues = useMemo(() => {
  252. if (!autoFill) {
  253. return {};
  254. }
  255. const alertRules = gettingStartedWithProjectContext.project?.alertRules;
  256. if (alertRules?.length === 0) {
  257. return {
  258. alertSetting: String(RuleAction.CREATE_ALERT_LATER),
  259. };
  260. }
  261. if (
  262. alertRules?.[0].conditions?.[0].id?.endsWith('EventFrequencyCondition') ||
  263. alertRules?.[0].conditions?.[0].id?.endsWith('EventUniqueUserFrequencyCondition')
  264. ) {
  265. return {
  266. alertSetting: String(RuleAction.CUSTOMIZED_ALERTS),
  267. interval: String(alertRules?.[0].conditions?.[0].interval),
  268. threshold: String(alertRules?.[0].conditions?.[0].value),
  269. metric: alertRules?.[0].conditions?.[0].id?.endsWith('EventFrequencyCondition')
  270. ? MetricValues.ERRORS
  271. : MetricValues.USERS,
  272. };
  273. }
  274. return {
  275. alertSetting: String(RuleAction.DEFAULT_ALERT),
  276. };
  277. }, [autoFill, gettingStartedWithProjectContext.project?.alertRules]);
  278. return (
  279. <Access access={canCreateProject ? ['project:read'] : ['project:admin']}>
  280. <div data-test-id="onboarding-info">
  281. <List symbol="colored-numeric">
  282. <Layout.Title withMargins>{t('Create a new project in 3 steps')}</Layout.Title>
  283. <HelpText>
  284. {tct(
  285. 'Set up a separate project for each part of your application (for example, your API server and frontend client), to quickly pinpoint which part of your application errors are coming from. [link: Read the docs].',
  286. {
  287. link: (
  288. <ExternalLink href="https://docs.sentry.io/product/sentry-basics/integrate-frontend/create-new-project/" />
  289. ),
  290. }
  291. )}
  292. </HelpText>
  293. <StyledListItem>{t('Choose your platform')}</StyledListItem>
  294. <PlatformPicker
  295. platform={platform?.key}
  296. defaultCategory={platform?.category}
  297. setPlatform={handlePlatformChange}
  298. organization={organization}
  299. showOther
  300. noAutoFilter
  301. />
  302. <StyledListItem>{t('Set your alert frequency')}</StyledListItem>
  303. <IssueAlertOptions
  304. {...alertFrequencyDefaultValues}
  305. platformLanguage={platform?.language as SupportedLanguages}
  306. onChange={updatedData => setAlertRuleConfig(updatedData)}
  307. />
  308. <StyledListItem>{t('Name your project and assign it a team')}</StyledListItem>
  309. <CreateProjectForm
  310. onSubmit={(event: React.FormEvent<HTMLFormElement>) => {
  311. // Prevent the page from reloading
  312. event.preventDefault();
  313. frameworkSelectionEnabled ? handleProjectCreation() : createProject();
  314. }}
  315. >
  316. <div>
  317. <FormLabel>{t('Project name')}</FormLabel>
  318. <ProjectNameInputWrap>
  319. <StyledPlatformIcon platform={platform?.key ?? 'other'} size={20} />
  320. <ProjectNameInput
  321. type="text"
  322. name="name"
  323. placeholder={t('project-name')}
  324. autoComplete="off"
  325. value={projectName}
  326. onChange={e => setProjectName(slugify(e.target.value))}
  327. />
  328. </ProjectNameInputWrap>
  329. </div>
  330. {!isOrgMemberWithNoAccess && (
  331. <div>
  332. <FormLabel>{t('Team')}</FormLabel>
  333. <TeamSelectInput>
  334. <TeamSelector
  335. allowCreate
  336. name="select-team"
  337. aria-label={t('Select a Team')}
  338. menuPlacement="auto"
  339. clearable={false}
  340. value={team}
  341. placeholder={t('Select a Team')}
  342. onChange={choice => setTeam(choice.value)}
  343. teamFilter={(tm: Team) => tm.access.includes('team:admin')}
  344. />
  345. </TeamSelectInput>
  346. </div>
  347. )}
  348. <div>
  349. <Tooltip title={submitTooltipText} disabled={formErrorCount === 0}>
  350. <Button
  351. type="submit"
  352. data-test-id="create-project"
  353. priority="primary"
  354. disabled={!canSubmitForm}
  355. >
  356. {t('Create Project')}
  357. </Button>
  358. </Tooltip>
  359. </div>
  360. </CreateProjectForm>
  361. {errors && (
  362. <Alert type="error">
  363. {Object.keys(errors).map(key => (
  364. <div key={key}>
  365. <strong>{startCase(key)}</strong>: {errors[key]}
  366. </div>
  367. ))}
  368. </Alert>
  369. )}
  370. </List>
  371. </div>
  372. </Access>
  373. );
  374. }
  375. export {CreateProject};
  376. const StyledListItem = styled(ListItem)`
  377. margin: ${space(2)} 0 ${space(1)} 0;
  378. font-size: ${p => p.theme.fontSizeExtraLarge};
  379. `;
  380. const CreateProjectForm = styled('form')`
  381. display: grid;
  382. grid-template-columns: 300px minmax(250px, max-content) max-content;
  383. gap: ${space(2)};
  384. align-items: end;
  385. padding: ${space(3)} 0;
  386. background: ${p => p.theme.background};
  387. `;
  388. const FormLabel = styled('div')`
  389. font-size: ${p => p.theme.fontSizeExtraLarge};
  390. margin-bottom: ${space(1)};
  391. `;
  392. const ProjectNameInputWrap = styled('div')`
  393. position: relative;
  394. `;
  395. const ProjectNameInput = styled(Input)`
  396. padding-left: calc(${p => p.theme.formPadding.md.paddingLeft}px * 1.5 + 20px);
  397. `;
  398. const StyledPlatformIcon = styled(PlatformIcon)`
  399. position: absolute;
  400. top: 50%;
  401. left: ${p => p.theme.formPadding.md.paddingLeft}px;
  402. transform: translateY(-50%);
  403. `;
  404. const TeamSelectInput = styled('div')`
  405. display: grid;
  406. gap: ${space(1)};
  407. grid-template-columns: 1fr min-content;
  408. align-items: center;
  409. `;
  410. const HelpText = styled('p')`
  411. color: ${p => p.theme.subText};
  412. max-width: 760px;
  413. `;