createProject.tsx 12 KB

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