createProject.tsx 10 KB

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