createProject.tsx 15 KB

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