createProject.tsx 10 KB

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