createProject.tsx 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350
  1. import {Component, Fragment} from 'react';
  2. // eslint-disable-next-line no-restricted-imports
  3. import {browserHistory, withRouter, WithRouterProps} from 'react-router';
  4. import styled from '@emotion/styled';
  5. import * as Sentry from '@sentry/react';
  6. import {PlatformIcon} from 'platformicons';
  7. import {openCreateTeamModal} from 'sentry/actionCreators/modal';
  8. import Alert from 'sentry/components/alert';
  9. import Button from 'sentry/components/button';
  10. import Input from 'sentry/components/input';
  11. import PageHeading from 'sentry/components/pageHeading';
  12. import PlatformPicker from 'sentry/components/platformPicker';
  13. import TeamSelector from 'sentry/components/teamSelector';
  14. import categoryList from 'sentry/data/platformCategories';
  15. import {IconAdd} from 'sentry/icons';
  16. import {t} from 'sentry/locale';
  17. import ProjectsStore from 'sentry/stores/projectsStore';
  18. import space from 'sentry/styles/space';
  19. import {Organization, Team} from 'sentry/types';
  20. import trackAdvancedAnalyticsEvent from 'sentry/utils/analytics/trackAdvancedAnalyticsEvent';
  21. import getPlatformName from 'sentry/utils/getPlatformName';
  22. import slugify from 'sentry/utils/slugify';
  23. import withApi from 'sentry/utils/withApi';
  24. import withOrganization from 'sentry/utils/withOrganization';
  25. import withTeams from 'sentry/utils/withTeams';
  26. import IssueAlertOptions from 'sentry/views/projectInstall/issueAlertOptions';
  27. const getCategoryName = (category?: string) =>
  28. categoryList.find(({id}) => id === category)?.id;
  29. type Props = WithRouterProps & {
  30. api: any;
  31. organization: Organization;
  32. teams: Team[];
  33. };
  34. type PlatformName = React.ComponentProps<typeof PlatformIcon>['platform'];
  35. type IssueAlertFragment = Parameters<
  36. React.ComponentProps<typeof IssueAlertOptions>['onChange']
  37. >[0];
  38. type State = {
  39. dataFragment: IssueAlertFragment | undefined;
  40. error: boolean;
  41. inFlight: boolean;
  42. platform: PlatformName | null;
  43. projectName: string;
  44. team: string;
  45. };
  46. class CreateProject extends Component<Props, State> {
  47. constructor(props: Props, context) {
  48. super(props, context);
  49. const {teams, location} = props;
  50. const {query} = location;
  51. const accessTeams = teams.filter((team: Team) => team.hasAccess);
  52. const team = query.team || (accessTeams.length && accessTeams[0].slug);
  53. const platform = getPlatformName(query.platform) ? query.platform : '';
  54. this.state = {
  55. error: false,
  56. projectName: getPlatformName(platform) || '',
  57. team,
  58. platform,
  59. inFlight: false,
  60. dataFragment: undefined,
  61. };
  62. }
  63. componentDidMount() {
  64. trackAdvancedAnalyticsEvent('project_creation_page.viewed', {
  65. organization: this.props.organization,
  66. });
  67. }
  68. get defaultCategory() {
  69. const {query} = this.props.location;
  70. return getCategoryName(query.category);
  71. }
  72. renderProjectForm() {
  73. const {organization} = this.props;
  74. const {projectName, platform, team} = this.state;
  75. const createProjectForm = (
  76. <CreateProjectForm onSubmit={this.createProject}>
  77. <div>
  78. <FormLabel>{t('Project name')}</FormLabel>
  79. <ProjectNameInputWrap>
  80. <StyledPlatformIcon platform={platform ?? ''} size={20} />
  81. <ProjectNameInput
  82. type="text"
  83. name="name"
  84. placeholder={t('project-name')}
  85. autoComplete="off"
  86. value={projectName}
  87. onChange={e => this.setState({projectName: slugify(e.target.value)})}
  88. />
  89. </ProjectNameInputWrap>
  90. </div>
  91. <div>
  92. <FormLabel>{t('Team')}</FormLabel>
  93. <TeamSelectInput>
  94. <TeamSelector
  95. name="select-team"
  96. menuPlacement="auto"
  97. clearable={false}
  98. value={team}
  99. placeholder={t('Select a Team')}
  100. onChange={choice => this.setState({team: choice.value})}
  101. teamFilter={(filterTeam: Team) => filterTeam.hasAccess}
  102. />
  103. <Button
  104. borderless
  105. data-test-id="create-team"
  106. type="button"
  107. icon={<IconAdd isCircled />}
  108. onClick={() =>
  109. openCreateTeamModal({
  110. organization,
  111. onClose: ({slug}) => this.setState({team: slug}),
  112. })
  113. }
  114. title={t('Create a team')}
  115. aria-label={t('Create a team')}
  116. />
  117. </TeamSelectInput>
  118. </div>
  119. <div>
  120. <Button
  121. data-test-id="create-project"
  122. priority="primary"
  123. disabled={!this.canSubmitForm}
  124. >
  125. {t('Create Project')}
  126. </Button>
  127. </div>
  128. </CreateProjectForm>
  129. );
  130. return (
  131. <Fragment>
  132. <PageHeading withMargins>{t('Give your project a name')}</PageHeading>
  133. {createProjectForm}
  134. </Fragment>
  135. );
  136. }
  137. get canSubmitForm() {
  138. const {projectName, team, inFlight} = this.state;
  139. const {shouldCreateCustomRule, conditions} = this.state.dataFragment || {};
  140. return (
  141. !inFlight &&
  142. team &&
  143. projectName !== '' &&
  144. (!shouldCreateCustomRule || conditions?.every?.(condition => condition.value))
  145. );
  146. }
  147. createProject = async e => {
  148. e.preventDefault();
  149. const {organization, api} = this.props;
  150. const {projectName, platform, team, dataFragment} = this.state;
  151. const {slug} = organization;
  152. const {
  153. shouldCreateCustomRule,
  154. name,
  155. conditions,
  156. actions,
  157. actionMatch,
  158. frequency,
  159. defaultRules,
  160. } = dataFragment || {};
  161. this.setState({inFlight: true});
  162. if (!projectName) {
  163. Sentry.withScope(scope => {
  164. scope.setExtra('props', this.props);
  165. scope.setExtra('state', this.state);
  166. Sentry.captureMessage('No project name');
  167. });
  168. }
  169. try {
  170. const projectData = await api.requestPromise(`/teams/${slug}/${team}/projects/`, {
  171. method: 'POST',
  172. data: {
  173. name: projectName,
  174. platform,
  175. default_rules: defaultRules ?? true,
  176. },
  177. });
  178. let ruleId: string | undefined;
  179. if (shouldCreateCustomRule) {
  180. const ruleData = await api.requestPromise(
  181. `/projects/${organization.slug}/${projectData.slug}/rules/`,
  182. {
  183. method: 'POST',
  184. data: {
  185. name,
  186. conditions,
  187. actions,
  188. actionMatch,
  189. frequency,
  190. },
  191. }
  192. );
  193. ruleId = ruleData.id;
  194. }
  195. trackAdvancedAnalyticsEvent('project_creation_page.created', {
  196. organization,
  197. issue_alert: defaultRules
  198. ? 'Default'
  199. : shouldCreateCustomRule
  200. ? 'Custom'
  201. : 'No Rule',
  202. project_id: projectData.id,
  203. rule_id: ruleId || '',
  204. });
  205. ProjectsStore.onCreateSuccess(projectData, organization.slug);
  206. const platformKey = platform || 'other';
  207. const nextUrl = `/${organization.slug}/${projectData.slug}/getting-started/${platformKey}/`;
  208. browserHistory.push(nextUrl);
  209. } catch (err) {
  210. this.setState({
  211. inFlight: false,
  212. error: err.responseJSON.detail,
  213. });
  214. // Only log this if the error is something other than:
  215. // * The user not having access to create a project, or,
  216. // * A project with that slug already exists
  217. if (err.status !== 403 && err.status !== 409) {
  218. Sentry.withScope(scope => {
  219. scope.setExtra('err', err);
  220. scope.setExtra('props', this.props);
  221. scope.setExtra('state', this.state);
  222. Sentry.captureMessage('Project creation failed');
  223. });
  224. }
  225. }
  226. };
  227. setPlatform = (platformKey: PlatformName | null) => {
  228. if (!platformKey) {
  229. this.setState({platform: null, projectName: ''});
  230. return;
  231. }
  232. this.setState(({projectName, platform}) => {
  233. // Avoid replacing project name when the user already modified it
  234. const userModifiedName = projectName && projectName !== platform;
  235. const newName = userModifiedName ? projectName : platformKey;
  236. return {
  237. platform: platformKey,
  238. projectName: slugify(newName),
  239. };
  240. });
  241. };
  242. render() {
  243. const {platform, error} = this.state;
  244. return (
  245. <Fragment>
  246. {error && <Alert type="error">{error}</Alert>}
  247. <div data-test-id="onboarding-info">
  248. <PageHeading withMargins>{t('Create a new Project')}</PageHeading>
  249. <HelpText>
  250. {t(
  251. `Projects allow you to scope error and transaction events to a specific
  252. application in your organization. For example, you might have separate
  253. projects for your API server and frontend client.`
  254. )}
  255. </HelpText>
  256. <PageHeading withMargins>{t('Choose a platform')}</PageHeading>
  257. <PlatformPicker
  258. platform={platform}
  259. defaultCategory={this.defaultCategory}
  260. setPlatform={this.setPlatform}
  261. organization={this.props.organization}
  262. showOther
  263. />
  264. <IssueAlertOptions
  265. onChange={updatedData => {
  266. this.setState({dataFragment: updatedData});
  267. }}
  268. />
  269. {this.renderProjectForm()}
  270. </div>
  271. </Fragment>
  272. );
  273. }
  274. }
  275. // TODO(davidenwang): change to functional component and replace withTeams with useTeams
  276. export default withApi(withRouter(withOrganization(withTeams(CreateProject))));
  277. export {CreateProject};
  278. const CreateProjectForm = styled('form')`
  279. display: grid;
  280. grid-template-columns: 300px minmax(250px, max-content) max-content;
  281. gap: ${space(2)};
  282. align-items: end;
  283. padding: ${space(3)} 0;
  284. box-shadow: 0 -1px 0 rgba(0, 0, 0, 0.1);
  285. background: ${p => p.theme.background};
  286. `;
  287. const FormLabel = styled('div')`
  288. font-size: ${p => p.theme.fontSizeExtraLarge};
  289. margin-bottom: ${space(1)};
  290. `;
  291. const ProjectNameInputWrap = styled('div')`
  292. position: relative;
  293. `;
  294. const ProjectNameInput = styled(Input)`
  295. padding-left: calc(${p => p.theme.formPadding.md.paddingLeft}px * 1.5 + 20px);
  296. `;
  297. const StyledPlatformIcon = styled(PlatformIcon)`
  298. position: absolute;
  299. top: 50%;
  300. left: ${p => p.theme.formPadding.md.paddingLeft}px;
  301. transform: translateY(-50%);
  302. `;
  303. const TeamSelectInput = styled('div')`
  304. display: grid;
  305. gap: ${space(1)};
  306. grid-template-columns: 1fr min-content;
  307. align-items: center;
  308. `;
  309. const HelpText = styled('p')`
  310. color: ${p => p.theme.subText};
  311. max-width: 760px;
  312. `;