createProject.tsx 15 KB

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