createProject.tsx 12 KB

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