Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions django_email_learning/public/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@
from django.db.models import Prefetch
from django_email_learning.models import Organization, Course
from django.http import Http404
from django.urls import reverse
from django.conf import settings
from django_email_learning.public.serializers import (
OrganizationSerializer,
PublicCourseSerializer,
Expand Down Expand Up @@ -47,6 +49,10 @@ def get_context_data(self, **kwargs) -> dict: # type: ignore[no-untyped-def]
description=organization.description,
courses=courses,
)
enroll_api_path = reverse("django_email_learning:api_public:enroll")
context[
"enroll_api_url"
] = f"{settings.DJANGO_EMAIL_LEARNING['SITE_BASE_URL']}{enroll_api_path}"
context["organization_json"] = organization_data.model_dump_json()
context["organization"] = organization_data.model_dump()
context["page_title"] = organization.name
Expand Down
1 change: 1 addition & 0 deletions django_email_learning/templates/public/organization.html
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
{% block head_script %}
<script>
const organization = {{ organization_json | safe }};
const enrollApiUrl = "{{ enroll_api_url }}";
</script>
{% vite_asset 'public/organization/Organization.jsx' %}
{% endblock %}
43 changes: 37 additions & 6 deletions frontend/public/components/EnrollmentForm.jsx
Original file line number Diff line number Diff line change
@@ -1,11 +1,14 @@
import React from 'react';
import { Alert, Box, Button, Typography } from '@mui/material';
import { Alert, Box, Button, CircularProgress, Typography } from '@mui/material';
import RequiredTextField from '../../src/components/RequiredTextField.jsx';
import { getCookie } from '../../src/utils.js';

const EnrollmentForm = ({course_title, course_slug, onCancel}) => {

const EnrollmentForm = ({course_title, course_slug, organization_id, endpoint, onCancle, onComplete}) => {

const emailRef = React.useRef('');
const [errorMessage, setErrorMessage] = React.useState('');
const [isProcessing, setIsProcessing] = React.useState(false);

const validateForm = () => {
const email = emailRef.current.value;
Expand All @@ -25,13 +28,40 @@ const EnrollmentForm = ({course_title, course_slug, onCancel}) => {

const enroll = () => {
if (validateForm()) {
// TODO: call the public API to enroll the user when the endpoint is ready
console.log('Enrolling with email:', emailRef.current.value, 'for course:', course_slug);
setIsProcessing(true);
fetch(endpoint, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'X-CSRFToken': getCookie('csrftoken'),
},
body: JSON.stringify({
email: emailRef.current.value,
course_slug: course_slug,
organization_id: organization_id,
}),
})
.then(response => {
if (!response.ok) {
throw new Error('Network response was not ok');
}
return response.json();
})
.then(data => {
// Handle success
setIsProcessing(false);
onComplete();
})
.catch(error => {
setIsProcessing(false);
setErrorMessage('Enrollment failed. Please try again.');
});
}
}

return (<Box sx={{padding: 4}}>
return (<Box sx={{padding: 4, minWidth: '400px'}}>
<Typography variant='h3'> Enroll for {course_title}</Typography>
{ isProcessing ? <Typography variant='body1' sx={{ mt: 2 }}><CircularProgress enableTrackSlot size="30px" /></Typography> : <>
{errorMessage && <Alert severity="error" sx={{ mt: 2 }}>{errorMessage}</Alert>}
<RequiredTextField label="email" name="email" type="email" fullWidth margin="normal" inputRef={emailRef} onKeyDown={(e) => {
if (e.key === 'Enter') {
Expand All @@ -40,13 +70,14 @@ const EnrollmentForm = ({course_title, course_slug, onCancel}) => {
}} />
<input type="hidden" name="course_slug" value={course_slug} />
<Box sx={{ mt: 2, textAlign: 'right' }}>
<Button variant="outlined" sx={{ mr: 1 }} onClick={onCancel}>
<Button variant="outlined" sx={{ mr: 1 }} onClick={onCancle}>
Cancel
</Button>
<Button variant="contained" color="primary" type="submit" onClick={enroll}>
Submit
</Button>
</Box>
</>}
</Box>);

};
Expand Down
32 changes: 27 additions & 5 deletions frontend/public/organization/Organization.jsx
Original file line number Diff line number Diff line change
@@ -1,21 +1,42 @@
import { useState } from 'react'
import { useState, useEffect } from 'react'
import render from '../../src/render.jsx';
import Layout from '../components/Layout.jsx';
import EnrollmentForm from '../components/EnrollmentForm.jsx';
import { Box, Button, Dialog, Grid, Typography } from '@mui/material';
import { Alert, Box, Button, Dialog, Grid, Typography } from '@mui/material';


function Organization() {

const [displayModal, setDisplayModal] = useState(false);
const [modalContent, setModalContent] = useState(null);
const [courses, setCourses] = useState([]);

useEffect(() => {
for (let course of organization.courses) {
course.enrolled = false;
}
setCourses(organization.courses);
}, []);

const showModalForCourse = (course) => {
// Logic to show modal for specific course
setModalContent(<EnrollmentForm course_title={course.title} course_slug={course.slug} onCancel={() => {setDisplayModal(false); setModalContent(null);}} />);
setModalContent(<EnrollmentForm course_title={course.title} course_slug={course.slug} organization_id={organization.id} endpoint={enrollApiUrl} onCancle={() => {setDisplayModal(false); setModalContent(null);}} onComplete={() => completeEnrollment(course)} />);
setDisplayModal(true);
}

const completeEnrollment = (course) => {
setDisplayModal(false);
setModalContent(null);
// Disable the enrolled course button
let updatedCourses = courses.map(c => {
if (c.id === course.id) {
return { ...c, enrolled: true };
}
return c;
});
setCourses(updatedCourses);
}


return <Layout>
{ organization.logo_url &&
Expand All @@ -27,14 +48,15 @@ function Organization() {
<Typography variant="h2">Courses:</Typography>
{ organization.courses.length > 0 ? (
<Grid container spacing={2}>
{ organization.courses.map((course) => (
{ courses.map((course) => (
<Grid size={{ xs: 12, md: 6 }} key={course.id}>
<Box key={course.id} mb={2} p={2} border={1} borderRadius={2} sx={{ minHeight: '100%' }}>
<Typography variant="h3">{course.title}</Typography>
<Button variant="contained" color="primary" rel="noopener noreferrer" sx={{ mt: 1, mb: 2 }} onClick={() => showModalForCourse(course)}>
<Button variant="contained" color="primary" rel="noopener noreferrer" sx={{ mt: 1, mb: 2 }} onClick={() => showModalForCourse(course)} disabled={course.enrolled}>
Enroll Now
</Button>
<Typography variant="body2" dangerouslySetInnerHTML={{ __html: course.description }} />
{ course.enrolled && <Alert severity="success" sx={{ mt: 2 }}>You are enrolled in this course.</Alert> }
</Box>
</Grid>
))}
Expand Down
1 change: 1 addition & 0 deletions tests/public/test_views/test_public_organization_view.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ def test_organization_view_anonymous_client(db, anonymous_client):
assert response.status_code == 200
assert response.context["organization"]["id"] == 1
assert response.context["page_title"] == response.context["organization"]["name"]
assert response.context["enroll_api_url"].startswith("http")
assert "organization_json" in response.context

# No course added yet, so courses list should be empty
Expand Down