Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

PADV-1395 feat: bulk students enroll #106

Merged
merged 2 commits into from
Jul 16, 2024
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
54 changes: 45 additions & 9 deletions src/features/Classes/EnrollStudent/__test__/index.test.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -13,17 +13,22 @@ jest.mock('react-router-dom', () => ({
}));

jest.mock('features/Students/data/api', () => ({
handleEnrollments: jest.fn(() => Promise.resolve()),
handleEnrollments: jest.fn().mockReturnValue({}),
getMessages: jest.fn().mockReturnValue({}),
}));

jest.mock('@edx/frontend-platform/logging', () => ({
logError: jest.fn(),
}));

describe('EnrollStudent', () => {
afterEach(() => {
jest.clearAllMocks();
});

test('Should render with correct elements', () => {
const { getByText, getByPlaceholderText } = renderWithProviders(
<EnrollStudent isOpen onClose={() => {}} />,
<EnrollStudent isOpen onClose={() => {}} queryClassId="ccx1" />,
{ preloadedState: {} },
);

Expand All @@ -36,15 +41,15 @@ describe('EnrollStudent', () => {
test('Should handle form submission and shows success toast', async () => {
const onCloseMock = jest.fn();

const { getByPlaceholderText, getByText } = renderWithProviders(
<EnrollStudent isOpen onClose={onCloseMock} />,
const { getByPlaceholderText, getByText, getByTestId } = renderWithProviders(
<EnrollStudent isOpen onClose={onCloseMock} queryClassId="ccx1" />,
{ preloadedState: {} },
);

const handleEnrollmentsMock = jest.spyOn(api, 'handleEnrollments').mockResolvedValue({
data: {
results: [{
tags: 'success',
identifier: '[email protected]',
}],
},
});
Expand All @@ -56,7 +61,7 @@ describe('EnrollStudent', () => {
fireEvent.click(submitButton);

await waitFor(() => {
expect(getByText('Email invite has been sent successfully')).toBeInTheDocument();
expect(getByTestId('toast-message').textContent).toBe('Successfully enrolled and sent email to the following user:\[email protected]');
});

expect(handleEnrollmentsMock).toHaveBeenCalledTimes(1);
Expand All @@ -66,14 +71,14 @@ describe('EnrollStudent', () => {
test('Should handle form submission and show error toast', async () => {
const onCloseMock = jest.fn();

const handleEnrollmentsMock = jest.spyOn(api, 'handleEnrollments').mockResolvedValue({
const messagesApiMock = jest.spyOn(api, 'getMessages').mockResolvedValue({
data: {
results: [{ tags: 'error', message: 'Enrollment limit reached' }],
},
});

const { getByPlaceholderText, getByText } = renderWithProviders(
<EnrollStudent isOpen onClose={onCloseMock} />,
<EnrollStudent isOpen onClose={onCloseMock} queryClassId="ccx1" />,
{ preloadedState: {} },
);

Expand All @@ -87,8 +92,39 @@ describe('EnrollStudent', () => {
expect(getByText('Enrollment limit reached')).toBeInTheDocument();
});

expect(handleEnrollmentsMock).toHaveBeenCalledTimes(1);
expect(messagesApiMock).toHaveBeenCalledTimes(1);

messagesApiMock.mockRestore();
});

test('Should handle form submission and show error toast for invalid email', async () => {
const onCloseMock = jest.fn();

const { getByPlaceholderText, getByText, getByTestId } = renderWithProviders(
<EnrollStudent isOpen onClose={onCloseMock} queryClassId="ccx1" />,
{ preloadedState: {} },
);

const handleEnrollmentsMock = jest.spyOn(api, 'handleEnrollments').mockResolvedValue({
data: {
results: [{
identifier: '[email protected]',
invalidIdentifier: true,
}],
},
});

const emailInput = getByPlaceholderText('Enter email of the student to enroll');
fireEvent.change(emailInput, { target: { value: '[email protected]' } });

const submitButton = getByText('Send invite');
fireEvent.click(submitButton);

await waitFor(() => {
expect(getByTestId('toast-message').textContent).toBe('The following email adress is invalid:\[email protected]\n');
});

expect(handleEnrollmentsMock).toHaveBeenCalledTimes(1);
handleEnrollmentsMock.mockRestore();
});
});
40 changes: 33 additions & 7 deletions src/features/Classes/EnrollStudent/index.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ import { Button } from 'react-paragon-topaz';
import { logError } from '@edx/frontend-platform/logging';

import { fetchStudentsData } from 'features/Students/data';
import { handleEnrollments } from 'features/Students/data/api';
import { handleEnrollments, getMessages } from 'features/Students/data/api';
import { fetchAllClassesData } from 'features/Classes/data/thunks';
import { initialPage } from 'features/constants';

Expand Down Expand Up @@ -47,20 +47,40 @@ const EnrollStudent = ({ isOpen, onClose, queryClassId }) => {
try {
setLoading(true);
const response = await handleEnrollments(formData, queryClassId);
const validationEmailList = response?.data?.results;
const messages = await getMessages();
const validEmails = [];
const invalidEmails = [];
let textToast = '';

/**
* This is because the service that checks the enrollment status is a different
* endpoint, and that endpoint always returns a status 200, so the error cannot be
* caught with a .catch.
*/
if (response?.data?.results[0]?.tags === 'error') {
setToastMessage(decodeURIComponent(response?.data?.results[0]?.message));
if (messages?.data?.results[0]?.tags === 'error') {
setToastMessage(decodeURIComponent(messages?.data?.results[0]?.message));
setShowToast(true);

return onClose();
}

setToastMessage('Email invite has been sent successfully');
validationEmailList.forEach(({ invalidIdentifier, identifier }) => {
(invalidIdentifier ? invalidEmails : validEmails).push(identifier);
});

if (invalidEmails.length > 0) {
textToast = `The following email ${invalidEmails.length === 1
? 'adress is invalid'
: 'adresses are invalid'}:\n${invalidEmails.join('\n')}\n`;
}
if (validEmails.length > 0) {
textToast += `Successfully enrolled and sent email to the following ${validEmails.length === 1
? 'user'
: 'users'}:\n${validEmails.join('\n')}`;
}

setToastMessage(textToast);
AuraAlba marked this conversation as resolved.
Show resolved Hide resolved

const params = {
course_name: courseNameDecoded,
Expand All @@ -84,7 +104,12 @@ const EnrollStudent = ({ isOpen, onClose, queryClassId }) => {

return (
<>
<Toast onClose={() => setShowToast(false)} show={showToast}>
<Toast
onClose={() => setShowToast(false)}
show={showToast}
className="toast-message"
data-testid="toast-message"
>
{toastMessage}
</Toast>
<ModalDialog
Expand Down Expand Up @@ -113,12 +138,13 @@ const EnrollStudent = ({ isOpen, onClose, queryClassId }) => {
<Form onSubmit={handleEnrollStudent}>
<FormGroup controlId="studentInfo">
<Form.Control
type="email"
as="textarea"
AuraAlba marked this conversation as resolved.
Show resolved Hide resolved
placeholder="Enter email of the student to enroll"
floatingLabel="Email"
className="my-4 mr-0"
className="my-4 mr-0 student-email"
name="studentEmail"
required
autoResize
/>
</FormGroup>
<div className="d-flex justify-content-end">
Expand Down
12 changes: 12 additions & 0 deletions src/features/Classes/EnrollStudent/index.scss
Original file line number Diff line number Diff line change
Expand Up @@ -7,4 +7,16 @@

.body-container {
min-height: 193px;

.student-email .pgn__form-control-floating-label {
display: block;
}

.student-email .form-control {
height: 44px;
}
}

.toast-message {
white-space: pre-wrap;
}
9 changes: 7 additions & 2 deletions src/features/Students/data/api.js
Original file line number Diff line number Diff line change
Expand Up @@ -21,9 +21,13 @@ function handleEnrollments(data, courseId) {
return getAuthenticatedHttpClient().post(
`${INSTRUCTOR_API_URL.replace(courseIdSearchPattern, courseId)}/students_update_enrollment`,
data,
).then(() => getAuthenticatedHttpClient().get(
);
}

function getMessages() {
return getAuthenticatedHttpClient().get(
`${getConfig().LMS_BASE_URL}/pearson_course_operation/api/messages/get-messages/`,
));
);
}

function getStudentsMetrics(institutionId, days) {
Expand Down Expand Up @@ -55,4 +59,5 @@ export {
handleEnrollments,
getStudentsMetrics,
getClassesMetrics,
getMessages,
};
Loading