-
-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathCourseForm.jsx
More file actions
223 lines (209 loc) · 9.09 KB
/
CourseForm.jsx
File metadata and controls
223 lines (209 loc) · 9.09 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
import { Alert, Box, Button, FormControlLabel, Switch, Tooltip, Typography } from '@mui/material';
import RequiredTextField from '../../../src/components/RequiredTextField.jsx';
import InfoOutlinedIcon from '@mui/icons-material/InfoOutlined';
import IconButton from '@mui/material/IconButton';
import AddImapConnectionForm from './AddImapConnectionForm.jsx';
import ImageUpload from '../../../src/components/ImageUpload.jsx';
import { useEffect, useState } from 'react';
import { getCookie } from '../../../src/utils.js';
function CourseForm({successCallback, failureCallback, cancelCallback, activeOrganizationId, createMode, courseId}) {
const [courseTitle, setCourseTitle] = useState("")
const [courseSlug, setCourseSlug] = useState("")
const [courseDescription, setCourseDescription] = useState("")
const [addImapConnection, setAddImapConnection] = useState(false)
const [imapConnectionId, setImapConnectionId] = useState(null)
const [titleHelperText, setTitleHelperText] = useState("")
const [slugHelperText, setSlugHelperText] = useState("")
const [descriptionHelperText, setDescriptionHelperText] = useState("")
const [errorMessage, setErrorMessage] = useState("")
const [imageUrl, setImageUrl] = useState(null)
const [imageServerPath, setImageServerPath] = useState(null)
const apiBaseUrl = localStorage.getItem('apiBaseUrl');
const switchImapConnection = () => {
if (addImapConnection) {
setAddImapConnection(false)
} else {
setAddImapConnection(true)
}
}
useEffect(() => {
if (!createMode && courseId) {
fetch(apiBaseUrl + '/organizations/' + activeOrganizationId + '/courses/' + courseId + '/', {
method: 'GET',
headers: {
'Content-Type': 'application/json',
'X-CSRFToken': getCookie('csrftoken')
},
credentials: 'include', // Include cookies in the request
})
.then(response => {
if (!response.ok) {
throw new Error('Network response was not ok');
}
return response.json();
})
.then(data => {
setCourseTitle(data.title);
setCourseSlug(data.slug);
setCourseDescription(data.description);
setImageUrl(data.image);
setImageServerPath(data.image_path);
if (data.imap_connection_id) {
setImapConnectionId(data.imap_connection_id);
setAddImapConnection(true);
}
})
.catch((error) => {
console.error('Error:', error);
if (error)
failureCallback(error);
});
}
}, [createMode, courseId]);
const validateForm = () => {
let isValid = true
if (!courseTitle) {
setTitleHelperText(localeMessages["title_required_helper_text"]);
isValid = false;
} else {
setTitleHelperText("");
}
if (!courseSlug) {
setSlugHelperText(localeMessages["slug_required_helper_text"]);
isValid = false;
} else {
setSlugHelperText("");
}
if (!courseDescription) {
setDescriptionHelperText(localeMessages["description_required_helper_text"]);
isValid = false;
} else {
setDescriptionHelperText("");
}
return isValid;
}
const handleUpdateCourse = () => {
const isValid = validateForm()
if (!isValid) {
return
}
fetch(apiBaseUrl + '/organizations/' + activeOrganizationId + '/courses/' + courseId + '/', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'X-CSRFToken': getCookie('csrftoken')
},
credentials: 'include', // Include cookies in the request
body: JSON.stringify({
title: courseTitle,
// slug is not updatable
description: courseDescription,
imap_connection_id: imapConnectionId && addImapConnection? parseInt(imapConnectionId) : null,
reset_imap_connection: !addImapConnection || imapConnectionId == null,
image: imageServerPath ? imageServerPath : null
}),
})
.then(response => {
if (!response.ok && response.status != 409) {
if (response.status >= 500) {
setErrorMessage("Server error occurred. Please try again later.");
}
throw new Error('Network response was not ok');
}
return response.json();
})
.then(data => {
if (data.error) {
setErrorMessage(data.error);
failureCallback(data);
} else {
console.log('Success:', data);
successCallback(data);
}
})
.catch((error) => {
console.error('Error:', error);
failureCallback(error);
});
};
const handleCreateCourse = () => {
const isValid = validateForm()
if (!isValid) {
return
}
fetch(apiBaseUrl + '/organizations/' + activeOrganizationId + '/courses/', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'X-CSRFToken': getCookie('csrftoken')
},
credentials: 'include', // Include cookies in the request
body: JSON.stringify({
title: courseTitle,
slug: courseSlug,
description: courseDescription,
imap_connection_id: imapConnectionId ? parseInt(imapConnectionId) : null,
image: imageServerPath ? imageServerPath : null
}),
})
.then(response => {
if (!response.ok && response.status != 409) {
if (response.status >= 500) {
setErrorMessage("Server error occurred. Please try again later.");
}
throw new Error('Network response was not ok');
}
return response.json();
})
.then(data => {
if (data.error) {
setErrorMessage(data.error);
failureCallback(data);
} else {
console.log('Success:', data);
// Optionally reset form fields here
setCourseTitle("");
setCourseSlug("");
setCourseDescription("");
successCallback(data);
}
})
.catch((error) => {
console.error('Error:', error);
failureCallback(error);
});
};
return (<Box p={2}>
{ errorMessage && <Alert severity="error" sx={{ marginBottom: "10px" }}>{errorMessage}</Alert> }
<RequiredTextField label={localeMessages["course_title"]} helperText={titleHelperText} fullWidth margin="normal" value={courseTitle} onChange={(e) => setCourseTitle(e.target.value)} />
<RequiredTextField label={localeMessages["course_slug"]} helperText={slugHelperText} fullWidth margin="normal" value={courseSlug} onChange={(e) => setCourseSlug(e.target.value)} {...(!createMode ? { disabled: true } : {})} />
<RequiredTextField label={localeMessages["course_description"]} helperText={descriptionHelperText} fullWidth margin="normal" multiline rows={4} value={courseDescription} onChange={(e) => setCourseDescription(e.target.value)} />
<FormControlLabel
control={<Switch onChange={() => switchImapConnection()} checked={addImapConnection} dir={direction} />}
label={localeMessages["add_imap_connection"]} sx={{ m: 0 }} />
<Tooltip title={localeMessages["imap_connection_tooltip"]}>
<IconButton size="small">
<InfoOutlinedIcon fontSize="small" />
</IconButton>
</Tooltip>
{ addImapConnection && <Box py={2}>
<AddImapConnectionForm
onChangeCallback={(id) => setImapConnectionId(id)}
activeOrganizationId={activeOrganizationId}
initialImapConnectionId={imapConnectionId}
/>
</Box>}
<Box>
<ImageUpload initialUrl={imageUrl} onUploadSuccess={(data) => {
setImageUrl(data.file_url);
setImageServerPath(data.file_path);
}} />
</Box>
<Box mt={2} textAlign="right">
<Button onClick={cancelCallback} sx={{ mr: 1 }}>Cancel</Button>
{ createMode && <Button variant="contained" onClick={() => handleCreateCourse()} sx={{ boxShadow: 'none' }}>{localeMessages["create"]}</Button> }
{ !createMode && <Button variant="contained" onClick={() => handleUpdateCourse()} sx={{ boxShadow: 'none' }}>{localeMessages["update"]}</Button> }
</Box>
</Box>);
}
export default CourseForm;