Skip to content

Commit

Permalink
add teacher management page (#24)
Browse files Browse the repository at this point in the history
* add teacher management page with list of teachers and actions to edit role and delete user

* move /users and /users/[id] path to pages

* remove delete teacher route

* remove unused error in catch

* update prisma instance

* fix styling, add catch errors, add loading
  • Loading branch information
135ze authored Nov 20, 2024
1 parent 94383dd commit 650fe98
Show file tree
Hide file tree
Showing 3 changed files with 182 additions and 0 deletions.
15 changes: 15 additions & 0 deletions src/pages/api/users.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
import type { NextApiRequest, NextApiResponse } from 'next';
import { prisma } from '../../../utils/prisma';

export default async function handler(
req: NextApiRequest,
res: NextApiResponse
) {
try {
const users = await prisma.user.findMany();
res.status(200).json(users);
} catch (error) {
console.error('Error fetching users:', error);
res.status(500).json({ error: 'Internal server error' });
}
}
58 changes: 58 additions & 0 deletions src/pages/api/users/[id].ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
import type { NextApiRequest, NextApiResponse } from 'next';
import { prisma } from '../../../../utils/prisma';

export default async function handler(
req: NextApiRequest,
res: NextApiResponse
) {
const id = Number(req.query.id);

if (Number.isNaN(id)) {
return res.status(400).json({ error: 'Invalid ID provided' });
}

if (req.method === 'GET') {
const getAbsences = req.query.getAbsences === 'true';

try {
const user = await prisma.user.findUnique({
where: { id },
include: { absences: getAbsences },
});

if (!user) {
return res.status(404).json({ error: 'User not found' });
}

return res.status(200).json(user);
} catch (error) {
console.error('Error fetching user:', error);
return res.status(500).json({ error: 'Internal server error' });
}
} else if (req.method === 'PATCH') {
const { email, firstName, lastName, role, status } = req.body;
const id = Number(req.query.id as string);

if (Number.isNaN(id)) {
return res.status(400).json({ error: 'Invalid ID provided' });
}

try {
const updatedUser = await prisma.user.update({
where: { id },
data: { email, firstName, lastName, role, status },
});

if (!updatedUser) {
return res.status(400).json({ error: 'User not found' });
}

return res.status(200).json(updatedUser);
} catch (error) {
console.error('Error updating user:', error);
return res.status(500).json({ error: 'Internal server error' });
}
} else {
return res.status(405).json({ error: 'Method not allowed' });
}
}
109 changes: 109 additions & 0 deletions src/pages/manage.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,109 @@
import { useEffect, useState } from 'react';
interface User {
id: number;
firstName: string;
lastName: string;
email: string;
role: string;
status: string;
numOfAbsences: string;
}

export default function AnotherPage() {
const [users, setUsers] = useState<User[]>([]);
const [loading, setLoading] = useState<boolean>(true);

useEffect(() => {
const fetchUsers = async () => {
const apiUrl = `/api/users/`;

try {
const response = await fetch(apiUrl);
if (!response.ok) {
throw new Error(response.statusText);
}
const data: User[] = await response.json();
setUsers(data);
} catch (error: unknown) {
if (error instanceof Error) {
console.error('Error fetching users:', error.message);
}
} finally {
setLoading(false);
}
};

fetchUsers();
}, []);

const updateUserRole = async (userId: number, newRole: string) => {
const confirmed = window.confirm('Confirm change role to ' + newRole);
if (!confirmed) return;

const apiUrl = `/api/users/${userId}`;
const originalUsers = [...users];

setUsers((prevUsers) =>
prevUsers.map((user) =>
user.id === userId ? { ...user, role: newRole } : user
)
);

try {
const response = await fetch(apiUrl, {
method: 'PATCH',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify({ role: newRole }),
});

if (!response.ok) {
setUsers(originalUsers);
throw new Error(response.statusText);
}
} catch (error: unknown) {
if (error instanceof Error) {
console.error('Error updating user:', error.message);
}
}
};

return (
<div>
<h1>Admin Management</h1>
{loading ? (
<p>Loading...</p>
) : (
<table>
<thead>
<tr>
<th>Name</th>
<th>Email</th>
<th>Role</th>
</tr>
</thead>
<tbody>
{users.map((user) => (
<tr key={user.id}>
<td>
{user.firstName} {user.lastName}
</td>
<td>{user.email}</td>
<td>
<select
value={user.role}
onChange={(e) => updateUserRole(user.id, e.target.value)}
>
<option value="TEACHER">Teacher</option>
<option value="ADMIN">Admin</option>
</select>
</td>
</tr>
))}
</tbody>
</table>
)}
</div>
);
}

0 comments on commit 650fe98

Please sign in to comment.