monitorCreateForm.tsx 10 KB

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