createProject.tsx 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467
  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. platform: selectedPlatform.key,
  134. rule_id: ruleId || '',
  135. });
  136. ProjectsStore.onCreateSuccess(projectData, organization.slug);
  137. if (team) {
  138. addSuccessMessage(
  139. tct('Created project [project]', {
  140. project: `${projectData.slug}`,
  141. })
  142. );
  143. } else {
  144. addSuccessMessage(
  145. tct('Created [project] under new team [team]', {
  146. project: `${projectData.slug}`,
  147. team: `#${projectData.team_slug}`,
  148. })
  149. );
  150. }
  151. browserHistory.push(
  152. normalizeUrl(
  153. `/organizations/${organization.slug}/projects/${projectData.slug}/getting-started/`
  154. )
  155. );
  156. } catch (err) {
  157. setInFlight(false);
  158. setErrors(err.responseJSON);
  159. addErrorMessage(
  160. tct('Failed to create project [project]', {
  161. project: `${projectName}`,
  162. })
  163. );
  164. // Only log this if the error is something other than:
  165. // * The user not having access to create a project, or,
  166. // * A project with that slug already exists
  167. if (err.status !== 403 && err.status !== 409) {
  168. Sentry.withScope(scope => {
  169. scope.setExtra('err', err);
  170. Sentry.captureMessage('Project creation failed');
  171. });
  172. }
  173. }
  174. },
  175. [api, alertRuleConfig, organization, platform, projectName, team]
  176. );
  177. const handleProjectCreation = useCallback(async () => {
  178. const selectedPlatform = platform;
  179. if (!selectedPlatform) {
  180. addErrorMessage(t('Please select a platform in Step 1'));
  181. return;
  182. }
  183. if (
  184. selectedPlatform.type !== 'language' ||
  185. !Object.values(SupportedLanguages).includes(
  186. selectedPlatform.language as SupportedLanguages
  187. )
  188. ) {
  189. createProject();
  190. return;
  191. }
  192. const {FrameworkSuggestionModal, modalCss} = await import(
  193. 'sentry/components/onboarding/frameworkSuggestionModal'
  194. );
  195. openModal(
  196. deps => (
  197. <FrameworkSuggestionModal
  198. {...deps}
  199. organization={organization}
  200. selectedPlatform={selectedPlatform}
  201. onConfigure={selectedFramework => {
  202. createProject(selectedFramework);
  203. }}
  204. onSkip={createProject}
  205. />
  206. ),
  207. {
  208. modalCss,
  209. onClose: () => {
  210. trackAnalytics('project_creation.select_framework_modal_close_button_clicked', {
  211. platform: selectedPlatform.key,
  212. organization,
  213. });
  214. },
  215. }
  216. );
  217. }, [platform, createProject, organization]);
  218. function handlePlatformChange(selectedPlatform: Platform | null) {
  219. if (!selectedPlatform?.id) {
  220. setPlatform(undefined);
  221. setProjectName('');
  222. return;
  223. }
  224. const userModifiedName = !!projectName && projectName !== platform?.key;
  225. const newName = userModifiedName ? projectName : selectedPlatform.id;
  226. setPlatform({
  227. ...omit(selectedPlatform, 'id'),
  228. key: selectedPlatform.id,
  229. });
  230. setProjectName(newName);
  231. }
  232. const {shouldCreateCustomRule, conditions} = alertRuleConfig || {};
  233. const canUserCreateProject = canCreateProject(organization);
  234. const canCreateTeam = organization.access.includes('project:admin');
  235. const isOrgMemberWithNoAccess = accessTeams.length === 0 && !canCreateTeam;
  236. const isMissingTeam = !isOrgMemberWithNoAccess && !team;
  237. const isMissingProjectName = projectName === '';
  238. const isMissingAlertThreshold =
  239. shouldCreateCustomRule && !conditions?.every?.(condition => condition.value);
  240. const formErrorCount = [
  241. isMissingTeam,
  242. isMissingProjectName,
  243. isMissingAlertThreshold,
  244. ].filter(value => value).length;
  245. const canSubmitForm = !inFlight && canUserCreateProject && formErrorCount === 0;
  246. let submitTooltipText: string = t('Please select a team');
  247. if (formErrorCount > 1) {
  248. submitTooltipText = t('Please fill out all the required fields');
  249. } else if (isMissingProjectName) {
  250. submitTooltipText = t('Please provide a project name');
  251. } else if (isMissingAlertThreshold) {
  252. submitTooltipText = t('Please provide an alert threshold');
  253. }
  254. const alertFrequencyDefaultValues = useMemo(() => {
  255. if (!autoFill) {
  256. return {};
  257. }
  258. const alertRules = gettingStartedWithProjectContext.project?.alertRules;
  259. if (alertRules?.length === 0) {
  260. return {
  261. alertSetting: String(RuleAction.CREATE_ALERT_LATER),
  262. };
  263. }
  264. if (
  265. alertRules?.[0].conditions?.[0].id?.endsWith('EventFrequencyCondition') ||
  266. alertRules?.[0].conditions?.[0].id?.endsWith('EventUniqueUserFrequencyCondition')
  267. ) {
  268. return {
  269. alertSetting: String(RuleAction.CUSTOMIZED_ALERTS),
  270. interval: String(alertRules?.[0].conditions?.[0].interval),
  271. threshold: String(alertRules?.[0].conditions?.[0].value),
  272. metric: alertRules?.[0].conditions?.[0].id?.endsWith('EventFrequencyCondition')
  273. ? MetricValues.ERRORS
  274. : MetricValues.USERS,
  275. };
  276. }
  277. return {
  278. alertSetting: String(RuleAction.DEFAULT_ALERT),
  279. };
  280. }, [autoFill, gettingStartedWithProjectContext.project?.alertRules]);
  281. return (
  282. <Access access={canUserCreateProject ? ['project:read'] : ['project:admin']}>
  283. <div data-test-id="onboarding-info">
  284. <List symbol="colored-numeric">
  285. <Layout.Title withMargins>{t('Create a new project in 3 steps')}</Layout.Title>
  286. <HelpText>
  287. {tct(
  288. '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].',
  289. {
  290. link: (
  291. <ExternalLink href="https://docs.sentry.io/product/sentry-basics/integrate-frontend/create-new-project/" />
  292. ),
  293. }
  294. )}
  295. </HelpText>
  296. <StyledListItem>{t('Choose your platform')}</StyledListItem>
  297. <PlatformPicker
  298. platform={platform?.key}
  299. defaultCategory={platform?.category}
  300. setPlatform={handlePlatformChange}
  301. organization={organization}
  302. showOther
  303. noAutoFilter
  304. />
  305. <StyledListItem>{t('Set your alert frequency')}</StyledListItem>
  306. <IssueAlertOptions
  307. {...alertFrequencyDefaultValues}
  308. platformLanguage={platform?.language as SupportedLanguages}
  309. onChange={updatedData => setAlertRuleConfig(updatedData)}
  310. />
  311. <StyledListItem>{t('Name your project and assign it a team')}</StyledListItem>
  312. <CreateProjectForm
  313. onSubmit={(event: React.FormEvent<HTMLFormElement>) => {
  314. // Prevent the page from reloading
  315. event.preventDefault();
  316. frameworkSelectionEnabled ? handleProjectCreation() : createProject();
  317. }}
  318. >
  319. <div>
  320. <FormLabel>{t('Project name')}</FormLabel>
  321. <ProjectNameInputWrap>
  322. <StyledPlatformIcon platform={platform?.key ?? 'other'} size={20} />
  323. <ProjectNameInput
  324. type="text"
  325. name="name"
  326. placeholder={t('project-name')}
  327. autoComplete="off"
  328. value={projectName}
  329. onChange={e => setProjectName(slugify(e.target.value))}
  330. />
  331. </ProjectNameInputWrap>
  332. </div>
  333. {!isOrgMemberWithNoAccess && (
  334. <div>
  335. <FormLabel>{t('Team')}</FormLabel>
  336. <TeamSelectInput>
  337. <TeamSelector
  338. allowCreate
  339. name="select-team"
  340. aria-label={t('Select a Team')}
  341. menuPlacement="auto"
  342. clearable={false}
  343. value={team}
  344. placeholder={t('Select a Team')}
  345. onChange={choice => setTeam(choice.value)}
  346. teamFilter={(tm: Team) => tm.access.includes('team:admin')}
  347. />
  348. </TeamSelectInput>
  349. </div>
  350. )}
  351. <div>
  352. <Tooltip title={submitTooltipText} disabled={formErrorCount === 0}>
  353. <Button
  354. type="submit"
  355. data-test-id="create-project"
  356. priority="primary"
  357. disabled={!canSubmitForm}
  358. >
  359. {t('Create Project')}
  360. </Button>
  361. </Tooltip>
  362. </div>
  363. </CreateProjectForm>
  364. {errors && (
  365. <Alert type="error">
  366. {Object.keys(errors).map(key => (
  367. <div key={key}>
  368. <strong>{startCase(key)}</strong>: {errors[key]}
  369. </div>
  370. ))}
  371. </Alert>
  372. )}
  373. </List>
  374. </div>
  375. </Access>
  376. );
  377. }
  378. export {CreateProject};
  379. const StyledListItem = styled(ListItem)`
  380. margin: ${space(2)} 0 ${space(1)} 0;
  381. font-size: ${p => p.theme.fontSizeExtraLarge};
  382. `;
  383. const CreateProjectForm = styled('form')`
  384. display: grid;
  385. grid-template-columns: 300px minmax(250px, max-content) max-content;
  386. gap: ${space(2)};
  387. align-items: end;
  388. padding: ${space(3)} 0;
  389. background: ${p => p.theme.background};
  390. `;
  391. const FormLabel = styled('div')`
  392. font-size: ${p => p.theme.fontSizeExtraLarge};
  393. margin-bottom: ${space(1)};
  394. `;
  395. const ProjectNameInputWrap = styled('div')`
  396. position: relative;
  397. `;
  398. const ProjectNameInput = styled(Input)`
  399. padding-left: calc(${p => p.theme.formPadding.md.paddingLeft}px * 1.5 + 20px);
  400. `;
  401. const StyledPlatformIcon = styled(PlatformIcon)`
  402. position: absolute;
  403. top: 50%;
  404. left: ${p => p.theme.formPadding.md.paddingLeft}px;
  405. transform: translateY(-50%);
  406. `;
  407. const TeamSelectInput = styled('div')`
  408. display: grid;
  409. gap: ${space(1)};
  410. grid-template-columns: 1fr min-content;
  411. align-items: center;
  412. `;
  413. const HelpText = styled('p')`
  414. color: ${p => p.theme.subText};
  415. max-width: 760px;
  416. `;