monitorCreateForm.tsx 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319
  1. import {Fragment, useRef} from 'react';
  2. import {css} from '@emotion/react';
  3. import styled from '@emotion/styled';
  4. import {Observer} from 'mobx-react';
  5. import NumberField from 'sentry/components/forms/fields/numberField';
  6. import SelectField from 'sentry/components/forms/fields/selectField';
  7. import SentryMemberTeamSelectorField from 'sentry/components/forms/fields/sentryMemberTeamSelectorField';
  8. import SentryProjectSelectorField from 'sentry/components/forms/fields/sentryProjectSelectorField';
  9. import TextField from 'sentry/components/forms/fields/textField';
  10. import Form from 'sentry/components/forms/form';
  11. import FormModel from 'sentry/components/forms/model';
  12. import Panel from 'sentry/components/panels/panel';
  13. import PanelBody from 'sentry/components/panels/panelBody';
  14. import {timezoneOptions} from 'sentry/data/timezones';
  15. import {t} from 'sentry/locale';
  16. import HookStore from 'sentry/stores/hookStore';
  17. import {space} from 'sentry/styles/space';
  18. import {browserHistory} from 'sentry/utils/browserHistory';
  19. import {isActiveSuperuser} from 'sentry/utils/isActiveSuperuser';
  20. import commonTheme from 'sentry/utils/theme';
  21. import normalizeUrl from 'sentry/utils/url/normalizeUrl';
  22. import useOrganization from 'sentry/utils/useOrganization';
  23. import usePageFilters from 'sentry/utils/usePageFilters';
  24. import useProjects from 'sentry/utils/useProjects';
  25. import type {Monitor} from 'sentry/views/monitors/types';
  26. import {ScheduleType} from 'sentry/views/monitors/types';
  27. import {getScheduleIntervals} from 'sentry/views/monitors/utils';
  28. import {crontabAsText} from 'sentry/views/monitors/utils/crontabAsText';
  29. import {MockTimelineVisualization} from './mockTimelineVisualization';
  30. import {
  31. DEFAULT_CRONTAB,
  32. DEFAULT_MONITOR_TYPE,
  33. mapMonitorFormErrors,
  34. transformMonitorFormData,
  35. } from './monitorForm';
  36. const DEFAULT_SCHEDULE_CONFIG = {
  37. scheduleType: 'crontab',
  38. cronSchedule: DEFAULT_CRONTAB,
  39. intervalFrequency: '1',
  40. intervalUnit: 'day',
  41. };
  42. export default function MonitorCreateForm() {
  43. const organization = useOrganization();
  44. const {projects} = useProjects();
  45. const {selection} = usePageFilters();
  46. const monitorCreationCallbacks = HookStore.get('callback:on-monitor-created');
  47. const form = useRef(
  48. new FormModel({
  49. transformData: transformMonitorFormData,
  50. mapFormErrors: mapMonitorFormErrors,
  51. })
  52. );
  53. const selectedProjectId = selection.projects[0];
  54. const selectedProject = selectedProjectId
  55. ? projects.find(p => p.id === selectedProjectId + '')
  56. : null;
  57. const isSuperuser = isActiveSuperuser();
  58. const filteredProjects = projects.filter(project => isSuperuser || project.isMember);
  59. function onCreateMonitor(data: Monitor) {
  60. const endpointOptions = {
  61. query: {
  62. project: selection.projects,
  63. environment: selection.environments,
  64. },
  65. };
  66. browserHistory.push(
  67. normalizeUrl({
  68. pathname: `/organizations/${organization.slug}/crons/${data.project.slug}/${data.slug}/`,
  69. query: endpointOptions.query,
  70. })
  71. );
  72. monitorCreationCallbacks.map(cb => cb(organization));
  73. }
  74. function changeScheduleType(type: ScheduleType) {
  75. form.current.setValue('config.scheduleType', type);
  76. }
  77. return (
  78. <Form
  79. allowUndo
  80. requireChanges
  81. apiEndpoint={`/organizations/${organization.slug}/monitors/`}
  82. apiMethod="POST"
  83. model={form.current}
  84. initialData={{
  85. project: selectedProject ? selectedProject.slug : null,
  86. type: DEFAULT_MONITOR_TYPE,
  87. 'config.scheduleType': DEFAULT_SCHEDULE_CONFIG.scheduleType,
  88. }}
  89. onSubmitSuccess={onCreateMonitor}
  90. submitLabel={t('Create')}
  91. >
  92. <FieldContainer>
  93. <ProjectOwnerNameInputs>
  94. <StyledSentryProjectSelectorField
  95. name="project"
  96. projects={filteredProjects}
  97. placeholder={t('Choose Project')}
  98. disabledReason={t('Existing monitors cannot be moved between projects')}
  99. valueIsSlug
  100. required
  101. stacked
  102. inline={false}
  103. />
  104. <StyledSentryMemberTeamSelectorField
  105. name="owner"
  106. placeholder={t('Assign Ownership')}
  107. stacked
  108. inline={false}
  109. menuPlacement="auto"
  110. />
  111. <StyledTextField
  112. name="name"
  113. placeholder={t('My Cron Job')}
  114. required
  115. stacked
  116. inline={false}
  117. />
  118. </ProjectOwnerNameInputs>
  119. <LabelText>{t('SCHEDULE')}</LabelText>
  120. <ScheduleOptions>
  121. <Observer>
  122. {() => {
  123. const currScheduleType = form.current.getValue('config.scheduleType');
  124. const selectedCrontab = currScheduleType === ScheduleType.CRONTAB;
  125. const parsedSchedule = form.current.getError('config.schedule')
  126. ? null
  127. : crontabAsText(
  128. form.current.getValue('config.schedule')?.toString() ?? ''
  129. );
  130. return (
  131. <Fragment>
  132. <SchedulePanel
  133. highlighted={selectedCrontab}
  134. onClick={() => changeScheduleType(ScheduleType.CRONTAB)}
  135. >
  136. <PanelBody withPadding>
  137. <ScheduleLabel>{t('Crontab Schedule')}</ScheduleLabel>
  138. <CrontabInputs>
  139. <StyledTextField
  140. name="config.schedule"
  141. placeholder="* * * * *"
  142. defaultValue={DEFAULT_SCHEDULE_CONFIG.cronSchedule}
  143. css={{input: {fontFamily: commonTheme.text.familyMono}}}
  144. required={selectedCrontab}
  145. stacked
  146. inline={false}
  147. hideControlState={!selectedCrontab}
  148. />
  149. <StyledSelectField
  150. name="config.timezone"
  151. defaultValue="UTC"
  152. options={timezoneOptions}
  153. required={selectedCrontab}
  154. stacked
  155. inline={false}
  156. />
  157. <CronstrueText>
  158. {parsedSchedule ?? t('(invalid schedule)')}
  159. </CronstrueText>
  160. </CrontabInputs>
  161. </PanelBody>
  162. </SchedulePanel>
  163. <SchedulePanel
  164. highlighted={!selectedCrontab}
  165. onClick={() => changeScheduleType(ScheduleType.INTERVAL)}
  166. >
  167. <PanelBody withPadding>
  168. <ScheduleLabel>{t('Interval Schedule')}</ScheduleLabel>
  169. <IntervalInputs>
  170. <Label>{t('Every')}</Label>
  171. <StyledNumberField
  172. name="config.schedule.frequency"
  173. placeholder="e.g. 1"
  174. defaultValue={DEFAULT_SCHEDULE_CONFIG.intervalFrequency}
  175. required={!selectedCrontab}
  176. stacked
  177. inline={false}
  178. hideControlState={selectedCrontab}
  179. />
  180. <StyledSelectField
  181. name="config.schedule.interval"
  182. options={getScheduleIntervals(
  183. Number(
  184. form.current.getValue('config.schedule.frequency') ?? 1
  185. )
  186. )}
  187. defaultValue={DEFAULT_SCHEDULE_CONFIG.intervalUnit}
  188. required={!selectedCrontab}
  189. stacked
  190. inline={false}
  191. />
  192. </IntervalInputs>
  193. </PanelBody>
  194. </SchedulePanel>
  195. </Fragment>
  196. );
  197. }}
  198. </Observer>
  199. </ScheduleOptions>
  200. <Observer>
  201. {() => {
  202. const scheduleType = form.current.getValue('config.scheduleType');
  203. const cronSchedule = form.current.getValue('config.schedule');
  204. const timezone = form.current.getValue('config.timezone');
  205. const intervalFrequency = form.current.getValue('config.schedule.frequency');
  206. const intervalUnit = form.current.getValue('config.schedule.interval');
  207. const schedule = {
  208. scheduleType,
  209. timezone,
  210. cronSchedule,
  211. intervalFrequency,
  212. intervalUnit,
  213. };
  214. return <MockTimelineVisualization schedule={schedule} />;
  215. }}
  216. </Observer>
  217. </FieldContainer>
  218. </Form>
  219. );
  220. }
  221. const FieldContainer = styled('div')`
  222. max-width: 800px;
  223. `;
  224. const SchedulePanel = styled(Panel)<{highlighted: boolean}>`
  225. border-radius: 0 ${space(0.75)} ${space(0.75)} 0;
  226. ${p =>
  227. p.highlighted
  228. ? css`
  229. border: 2px solid ${p.theme.purple300};
  230. `
  231. : css`
  232. padding: 1px;
  233. `};
  234. &:first-child {
  235. border-radius: ${space(0.75)} 0 0 ${space(0.75)};
  236. }
  237. `;
  238. const ScheduleLabel = styled('div')`
  239. font-weight: ${p => p.theme.fontWeightBold};
  240. margin-bottom: ${space(2)};
  241. `;
  242. const Label = styled('div')`
  243. font-weight: ${p => p.theme.fontWeightBold};
  244. color: ${p => p.theme.subText};
  245. `;
  246. const LabelText = styled(Label)`
  247. margin-top: ${space(2)};
  248. margin-bottom: ${space(1)};
  249. `;
  250. const ScheduleOptions = styled('div')`
  251. display: grid;
  252. grid-template-columns: 1fr 1fr;
  253. `;
  254. const MultiColumnInput = styled('div')`
  255. display: grid;
  256. align-items: center;
  257. gap: ${space(1)};
  258. `;
  259. const ProjectOwnerNameInputs = styled(MultiColumnInput)`
  260. grid-template-columns: 230px 230px 1fr;
  261. `;
  262. const CrontabInputs = styled(MultiColumnInput)`
  263. grid-template-columns: 1fr 1fr;
  264. `;
  265. const IntervalInputs = styled(MultiColumnInput)`
  266. grid-template-columns: auto 1fr 2fr;
  267. `;
  268. const CronstrueText = styled(LabelText)`
  269. font-weight: ${p => p.theme.fontWeightNormal};
  270. font-size: ${p => p.theme.fontSizeExtraSmall};
  271. font-family: ${p => p.theme.text.familyMono};
  272. grid-column: auto / span 2;
  273. `;
  274. const StyledNumberField = styled(NumberField)`
  275. padding: 0;
  276. `;
  277. const StyledSelectField = styled(SelectField)`
  278. padding: 0;
  279. `;
  280. const StyledSentryMemberTeamSelectorField = styled(SentryMemberTeamSelectorField)`
  281. padding: 0;
  282. `;
  283. const StyledTextField = styled(TextField)`
  284. padding: 0;
  285. `;
  286. const StyledSentryProjectSelectorField = styled(SentryProjectSelectorField)`
  287. padding: 0;
  288. `;