createProject.tsx 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396
  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 ProjectActions from 'sentry/actions/projectActions';
  9. import Alert from 'sentry/components/alert';
  10. import Button from 'sentry/components/button';
  11. import TeamSelector from 'sentry/components/forms/teamSelector';
  12. import PageHeading from 'sentry/components/pageHeading';
  13. import PlatformPicker from 'sentry/components/platformPicker';
  14. import categoryList from 'sentry/data/platformCategories';
  15. import {IconAdd} from 'sentry/icons';
  16. import {t} from 'sentry/locale';
  17. import {inputStyles} from 'sentry/styles/input';
  18. import space from 'sentry/styles/space';
  19. import {Organization, Team} from 'sentry/types';
  20. import {logExperiment} from 'sentry/utils/analytics';
  21. import trackAdvancedAnalyticsEvent from 'sentry/utils/analytics/trackAdvancedAnalyticsEvent';
  22. import getPlatformName from 'sentry/utils/getPlatformName';
  23. import slugify from 'sentry/utils/slugify';
  24. import withApi from 'sentry/utils/withApi';
  25. import withOrganization from 'sentry/utils/withOrganization';
  26. import withTeams from 'sentry/utils/withTeams';
  27. import IssueAlertOptions from 'sentry/views/projectInstall/issueAlertOptions';
  28. import {PRESET_AGGREGATES} from '../alerts/rules/metric/presets';
  29. const getCategoryName = (category?: string) =>
  30. categoryList.find(({id}) => id === category)?.id;
  31. type Props = WithRouterProps & {
  32. api: any;
  33. organization: Organization;
  34. teams: Team[];
  35. };
  36. type PlatformName = React.ComponentProps<typeof PlatformIcon>['platform'];
  37. type IssueAlertFragment = Parameters<
  38. React.ComponentProps<typeof IssueAlertOptions>['onChange']
  39. >[0];
  40. type State = {
  41. dataFragment: IssueAlertFragment | undefined;
  42. error: boolean;
  43. inFlight: boolean;
  44. platform: PlatformName | null;
  45. projectName: string;
  46. team: string;
  47. };
  48. class CreateProject extends Component<Props, State> {
  49. constructor(props: Props, context) {
  50. super(props, context);
  51. const {teams, location} = props;
  52. const {query} = location;
  53. const accessTeams = teams.filter((team: Team) => team.hasAccess);
  54. const team = query.team || (accessTeams.length && accessTeams[0].slug);
  55. const platform = getPlatformName(query.platform) ? query.platform : '';
  56. this.state = {
  57. error: false,
  58. projectName: getPlatformName(platform) || '',
  59. team,
  60. platform,
  61. inFlight: false,
  62. dataFragment: undefined,
  63. };
  64. }
  65. componentDidMount() {
  66. trackAdvancedAnalyticsEvent('project_creation_page.viewed', {
  67. organization: this.props.organization,
  68. });
  69. logExperiment({
  70. key: 'MetricAlertOnProjectCreationExperiment',
  71. organization: this.props.organization,
  72. });
  73. }
  74. get defaultCategory() {
  75. const {query} = this.props.location;
  76. return getCategoryName(query.category);
  77. }
  78. renderProjectForm() {
  79. const {organization} = this.props;
  80. const {projectName, platform, team} = this.state;
  81. const createProjectForm = (
  82. <CreateProjectForm onSubmit={this.createProject}>
  83. <div>
  84. <FormLabel>{t('Project name')}</FormLabel>
  85. <ProjectNameInput>
  86. <StyledPlatformIcon platform={platform ?? ''} />
  87. <input
  88. type="text"
  89. name="name"
  90. placeholder={t('project-name')}
  91. autoComplete="off"
  92. value={projectName}
  93. onChange={e => this.setState({projectName: slugify(e.target.value)})}
  94. />
  95. </ProjectNameInput>
  96. </div>
  97. <div>
  98. <FormLabel>{t('Team')}</FormLabel>
  99. <TeamSelectInput>
  100. <TeamSelector
  101. name="select-team"
  102. menuPlacement="auto"
  103. clearable={false}
  104. value={team}
  105. placeholder={t('Select a Team')}
  106. onChange={choice => this.setState({team: choice.value})}
  107. teamFilter={(filterTeam: Team) => filterTeam.hasAccess}
  108. />
  109. <Button
  110. borderless
  111. data-test-id="create-team"
  112. type="button"
  113. icon={<IconAdd isCircled />}
  114. onClick={() =>
  115. openCreateTeamModal({
  116. organization,
  117. onClose: ({slug}) => this.setState({team: slug}),
  118. })
  119. }
  120. title={t('Create a team')}
  121. aria-label={t('Create a team')}
  122. />
  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. <Fragment>
  138. <PageHeading withMargins>{t('Give your project a name')}</PageHeading>
  139. {createProjectForm}
  140. </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. metricAlertPresets,
  167. } = dataFragment || {};
  168. this.setState({inFlight: true});
  169. if (!projectName) {
  170. Sentry.withScope(scope => {
  171. scope.setExtra('props', this.props);
  172. scope.setExtra('state', this.state);
  173. Sentry.captureMessage('No project name');
  174. });
  175. }
  176. try {
  177. const projectData = await api.requestPromise(`/teams/${slug}/${team}/projects/`, {
  178. method: 'POST',
  179. data: {
  180. name: projectName,
  181. platform,
  182. default_rules: defaultRules ?? true,
  183. },
  184. });
  185. let ruleId: string | undefined;
  186. if (shouldCreateCustomRule) {
  187. const ruleData = await api.requestPromise(
  188. `/projects/${organization.slug}/${projectData.slug}/rules/`,
  189. {
  190. method: 'POST',
  191. data: {
  192. name,
  193. conditions,
  194. actions,
  195. actionMatch,
  196. frequency,
  197. },
  198. }
  199. );
  200. ruleId = ruleData.id;
  201. }
  202. if (
  203. !!organization.experiments.MetricAlertOnProjectCreationExperiment &&
  204. metricAlertPresets &&
  205. metricAlertPresets.length > 0
  206. ) {
  207. const presets = PRESET_AGGREGATES.filter(aggregate =>
  208. metricAlertPresets.includes(aggregate.id)
  209. );
  210. const teamObj = this.props.teams.find(aTeam => aTeam.slug === team);
  211. await Promise.all([
  212. presets.map(preset => {
  213. const context = preset.makeUnqueriedContext(
  214. {
  215. ...projectData,
  216. teams: teamObj ? [teamObj] : [],
  217. },
  218. organization
  219. );
  220. return api.requestPromise(
  221. `/projects/${organization.slug}/${projectData.slug}/alert-rules/?referrer=create_project`,
  222. {
  223. method: 'POST',
  224. data: {
  225. aggregate: context.aggregate,
  226. comparisonDelta: context.comparisonDelta,
  227. dataset: context.dataset,
  228. eventTypes: context.eventTypes,
  229. name: context.name,
  230. owner: null,
  231. projectId: projectData.id,
  232. projects: [projectData.slug],
  233. query: '',
  234. resolveThreshold: null,
  235. thresholdPeriod: 1,
  236. thresholdType: context.thresholdType,
  237. timeWindow: context.timeWindow,
  238. triggers: context.triggers,
  239. },
  240. }
  241. );
  242. }),
  243. ]);
  244. }
  245. trackAdvancedAnalyticsEvent('project_creation_page.created', {
  246. organization,
  247. metric_alerts: (metricAlertPresets || []).join(','),
  248. issue_alert: defaultRules
  249. ? 'Default'
  250. : shouldCreateCustomRule
  251. ? 'Custom'
  252. : 'No Rule',
  253. project_id: projectData.id,
  254. rule_id: ruleId || '',
  255. });
  256. ProjectActions.createSuccess(projectData);
  257. const platformKey = platform || 'other';
  258. const nextUrl = `/${organization.slug}/${projectData.slug}/getting-started/${platformKey}/`;
  259. browserHistory.push(nextUrl);
  260. } catch (err) {
  261. this.setState({
  262. inFlight: false,
  263. error: err.responseJSON.detail,
  264. });
  265. // Only log this if the error is something other than:
  266. // * The user not having access to create a project, or,
  267. // * A project with that slug already exists
  268. if (err.status !== 403 && err.status !== 409) {
  269. Sentry.withScope(scope => {
  270. scope.setExtra('err', err);
  271. scope.setExtra('props', this.props);
  272. scope.setExtra('state', this.state);
  273. Sentry.captureMessage('Project creation failed');
  274. });
  275. }
  276. }
  277. };
  278. setPlatform = (platformId: PlatformName | null) =>
  279. this.setState(({projectName, platform}: State) => ({
  280. platform: platformId,
  281. projectName:
  282. !projectName || (platform && getPlatformName(platform) === projectName)
  283. ? getPlatformName(platformId) || ''
  284. : projectName,
  285. }));
  286. render() {
  287. const {platform, error} = this.state;
  288. return (
  289. <Fragment>
  290. {error && <Alert type="error">{error}</Alert>}
  291. <div data-test-id="onboarding-info">
  292. <PageHeading withMargins>{t('Create a new Project')}</PageHeading>
  293. <HelpText>
  294. {t(
  295. `Projects allow you to scope error and transaction events to a specific
  296. application in your organization. For example, you might have separate
  297. projects for your API server and frontend client.`
  298. )}
  299. </HelpText>
  300. <PageHeading withMargins>{t('Choose a platform')}</PageHeading>
  301. <PlatformPicker
  302. platform={platform}
  303. defaultCategory={this.defaultCategory}
  304. setPlatform={this.setPlatform}
  305. organization={this.props.organization}
  306. showOther
  307. />
  308. <IssueAlertOptions
  309. onChange={updatedData => {
  310. this.setState({dataFragment: updatedData});
  311. }}
  312. />
  313. {this.renderProjectForm()}
  314. </div>
  315. </Fragment>
  316. );
  317. }
  318. }
  319. // TODO(davidenwang): change to functional component and replace withTeams with useTeams
  320. export default withApi(withRouter(withOrganization(withTeams(CreateProject))));
  321. export {CreateProject};
  322. const CreateProjectForm = styled('form')`
  323. display: grid;
  324. grid-template-columns: 300px minmax(250px, max-content) max-content;
  325. gap: ${space(2)};
  326. align-items: end;
  327. padding: ${space(3)} 0;
  328. box-shadow: 0 -1px 0 rgba(0, 0, 0, 0.1);
  329. background: ${p => p.theme.background};
  330. `;
  331. const FormLabel = styled('div')`
  332. font-size: ${p => p.theme.fontSizeExtraLarge};
  333. margin-bottom: ${space(1)};
  334. `;
  335. const StyledPlatformIcon = styled(PlatformIcon)`
  336. margin-right: ${space(1)};
  337. `;
  338. const ProjectNameInput = styled('div')`
  339. ${p => inputStyles(p)};
  340. padding: 5px 10px;
  341. display: flex;
  342. align-items: center;
  343. input {
  344. background: ${p => p.theme.background};
  345. border: 0;
  346. outline: 0;
  347. flex: 1;
  348. }
  349. `;
  350. const TeamSelectInput = styled('div')`
  351. display: grid;
  352. gap: ${space(1)};
  353. grid-template-columns: 1fr min-content;
  354. align-items: center;
  355. `;
  356. const HelpText = styled('p')`
  357. color: ${p => p.theme.subText};
  358. max-width: 760px;
  359. `;