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

[Prod] Update R10 goals & objectives, add admin for course management, update requested TRs + sessions #2226

Merged
merged 25 commits into from
Jun 25, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
25 commits
Select commit Hold shift + click to select a range
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
30 changes: 29 additions & 1 deletion frontend/src/fetchers/courses.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,11 @@
/* eslint-disable import/prefer-default-export */
import join from 'url-join';
import { get } from './index';
import {
destroy,
get,
post,
put,
} from './index';

export async function getCourses() {
const courses = await get(join('/', 'api', 'courses'));
Expand All @@ -16,6 +21,29 @@ export async function getCourses() {
// ];
}

export async function getCourseById(id) {
const course = await get(join('/', 'api', 'courses', id));
return course.json();
// response like { id: 1, name: 'Guiding Children\'s Behavior (BTS-P)' }
}

export async function updateCourseById(id, data) {
const course = await put(join('/', 'api', 'courses', id), data);
return course.json();
// response like { id: 1, name: 'Guiding Children\'s Behavior (BTS-P)' }
}

export async function deleteCourseById(id) {
return destroy(join('/', 'api', 'courses', id));
// response like { id: 1, name: 'Guiding Children\'s Behavior (BTS-P)' }
}

export async function createCourseByName(name) {
const course = await post(join('/', 'api', 'courses'), { name });
return course.json();
// response like { id: 1, name: 'Guiding Children\'s Behavior (BTS-P)' }
}

export const fetchCourseDashboardData = async (query) => {
const request = join('/', 'api', 'courses', 'dashboard', `?${query}`);
const res = await get(request);
Expand Down
60 changes: 60 additions & 0 deletions frontend/src/pages/Admin/CourseAdd.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
import React, { useState } from 'react';
import PropTypes from 'prop-types';
import {
Button,
Fieldset,
Form,
FormGroup,
Label,
TextInput,
} from '@trussworks/react-uswds';
import { createCourseByName } from '../../fetchers/courses';

function CourseAdd({ refresh }) {
const [courseName, setCourseName] = useState('');

const create = async () => {
await createCourseByName(courseName);
refresh();
setCourseName('');
};

const onSubmit = (e) => {
e.preventDefault();
create();
};

return (
<div>
<h2>Add a new course</h2>
<Form key="add-new-course-form" onSubmit={onSubmit}>
<FormGroup>
<Fieldset>
<Label htmlFor="coursename">Course name</Label>
<TextInput
type="text"
id="coursename"
key="coursename"
name="coursename"
onChange={(e) => setCourseName(e.target.value)}
value={courseName}
/>
</Fieldset>
</FormGroup>
<Button
type="submit"
data-testid="add-course"
className="margin-top-2"
>
Add course
</Button>
</Form>
</div>
);
}

CourseAdd.propTypes = {
refresh: PropTypes.func.isRequired,
};

export default CourseAdd;
106 changes: 106 additions & 0 deletions frontend/src/pages/Admin/CourseEdit.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,106 @@
import React, {
useCallback,
useEffect,
useRef,
useState,
} from 'react';
import ReactRouterPropTypes from 'react-router-prop-types';
import {
Button,
ButtonGroup,
Label,
TextInput,
} from '@trussworks/react-uswds';
import { useHistory } from 'react-router-dom';
import { deleteCourseById, getCourseById, updateCourseById } from '../../fetchers/courses';
import Modal from '../../components/Modal';

function CourseEdit({ match }) {
const { params: { courseId } } = match;
const [course, setCourse] = useState();
const [newCourse, setNewCourse] = useState();
const modalRef = useRef();
const history = useHistory();

useEffect(() => {
async function fetchCourse() {
const c = await getCourseById(courseId);
setCourse({ ...c });
setNewCourse({ ...c });
}

if (!course) {
fetchCourse();
}
}, [course, courseId]);

const askConfirmDelete = useCallback(() => {
if (modalRef.current) {
modalRef.current.toggleModal(true);
}
}, []);

if (!course || !newCourse) {
return <div>Loading course...</div>;
}

const onChange = (e) => {
setNewCourse((prevCourse) => ({ ...prevCourse, name: e.target.value }));
};

const saveChanges = async () => {
const updated = await updateCourseById(courseId, { name: newCourse.name });
setCourse({ ...updated });
history.replace(`/admin/course/${updated.id}`);
};

const confirmDelete = async () => {
if (modalRef.current) {
modalRef.current.toggleModal(false);
}

await deleteCourseById(courseId);

history.push('/admin/courses');
};

return (
<div>
<h2>{course.name}</h2>
<Label htmlFor={`coursename-${course.id}`}>Course Name</Label>
<TextInput
type="text"
id={`coursename-${course.id}`}
key={`coursename-${course.id}`}
name="coursename"
value={newCourse.name}
placeholder={course.name}
onChange={onChange}
/>

<ButtonGroup type="default" style={{ marginTop: '8px' }}>
<Button onClick={saveChanges}>Save changes</Button>
<Button id="delete-course-button" onClick={askConfirmDelete} secondary>Delete course</Button>
</ButtonGroup>

<Modal
modalRef={modalRef}
onOk={confirmDelete}
modalId="DeleteCourseModal"
title="Are you sure you want to delete this course?"
okButtonText="Yes, delete it"
okButtonAriaLabel="Delete course"
okButtonCss="usa-button--secondary"
cancelButtonCss="usa-button--unstyled"
>
This action cannot be undone.
</Modal>
</div>
);
}

CourseEdit.propTypes = {
match: ReactRouterPropTypes.match.isRequired,
};

export default CourseEdit;
51 changes: 51 additions & 0 deletions frontend/src/pages/Admin/CourseList.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
import React, { useState } from 'react';
import PropTypes from 'prop-types';
import { Label, TextInput } from '@trussworks/react-uswds';
import { Link } from 'react-router-dom';

function CourseList({ courses }) {
const [filter, setFilter] = useState('');

if (!courses) {
return null;
}

const onFilterChange = (e) => {
setFilter(e.target.value);
};

const filteredCourses = courses.filter(
(course) => course.name.toLowerCase().includes(filter.toLowerCase()),
);

return (
<div>
<Label htmlFor="courses-filter">
Filter courses by name
</Label>
<TextInput
type="text"
id="courses-filter"
name="courses-filter"
key="courses-filter"
value={filter}
onChange={onFilterChange}
className="margin-bottom-2"
/>
{filteredCourses.map((course) => (
<div key={course.id} className="margin-bottom-1">
<Link to={`/admin/course/${course.id}`}>{course.name}</Link>
</div>
))}
</div>
);
}

CourseList.propTypes = {
courses: PropTypes.arrayOf(PropTypes.shape({
name: PropTypes.string,
id: PropTypes.number,
})).isRequired,
};

export default CourseList;
71 changes: 42 additions & 29 deletions frontend/src/pages/Admin/Courses.js
Original file line number Diff line number Diff line change
@@ -1,24 +1,25 @@
import React, { useEffect, useState } from 'react';
import { Button } from '@trussworks/react-uswds';
import React, { useCallback, useEffect, useState } from 'react';
import { Button, Grid, GridContainer } from '@trussworks/react-uswds';
import CsvImport from './components/CsvImport';
import { getCourses } from '../../fetchers/courses';
import Container from '../../components/Container';
import CourseList from './CourseList';
import CourseAdd from './CourseAdd';

function Courses() {
const [courses, setCourses] = useState();
const primaryIdColumn = 'course name';
const typeName = 'courses';
const apiPathName = 'courses';

useEffect(() => {
async function get() {
const response = await getCourses();
setCourses(response);
}
const refresh = useCallback(async () => {
const response = await getCourses();
setCourses(response);
}, []);

if (!courses) {
get();
}
}, [courses]);
useEffect(() => {
refresh();
}, [refresh]);

const exportCourses = () => {
// export courses as CSV
Expand Down Expand Up @@ -47,24 +48,36 @@ function Courses() {

return (
<>
<CsvImport
validCsvHeaders={validCsvHeaders}
requiredCsvHeaders={requiredCsvHeaders}
typeName={typeName}
apiPathName={apiPathName}
primaryIdColumn={primaryIdColumn}
/>

{courses && (
<Button
outline
type="button"
onClick={exportCourses}
>
Export courses as CSV
</Button>
)}

<GridContainer className="margin-0 padding-0">
<Grid row gap="lg">
<Grid tablet={{ col: 6 }}>
<Container>
<CourseList courses={courses} />
</Container>
</Grid>
<Grid tablet={{ col: 6 }}>
<Container>
<CourseAdd refresh={refresh} />
</Container>
<Container>
<CsvImport
validCsvHeaders={validCsvHeaders}
requiredCsvHeaders={requiredCsvHeaders}
typeName={typeName}
apiPathName={apiPathName}
primaryIdColumn={primaryIdColumn}
/>
</Container>
{courses && (
<Container>
<Button outline type="button" onClick={exportCourses}>
Export courses as CSV
</Button>
</Container>
)}
</Grid>
</Grid>
</GridContainer>
</>
);
}
Expand Down
37 changes: 37 additions & 0 deletions frontend/src/pages/Admin/__tests__/CourseAdd.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
import React from 'react';
import {
render,
screen,
fireEvent,
waitFor,
} from '@testing-library/react';
import fetchMock from 'fetch-mock';
import CourseAdd from '../CourseAdd';

describe('CourseAdd', () => {
const mockRefresh = jest.fn();
const renderCourseAdd = () => {
render(<CourseAdd refresh={mockRefresh} />);
};

beforeEach(() => {
fetchMock.reset();
});

it('renders the CourseAdd component', () => {
renderCourseAdd();
expect(screen.getByLabelText('Course name')).toBeInTheDocument();
expect(screen.getByTestId('add-course')).toBeInTheDocument();
});

it('calls createCourseByName and refresh on form submit', async () => {
fetchMock.post('/api/courses', {});
renderCourseAdd();

fireEvent.change(screen.getByLabelText('Course name'), { target: { value: 'New Course' } });
fireEvent.click(screen.getByTestId('add-course'));

await waitFor(() => expect(fetchMock.called('/api/courses')).toBe(true));
await waitFor(() => expect(mockRefresh).toHaveBeenCalled());
});
});
Loading