Skip to content

Commit

Permalink
add teacher management page showing list of all teacher and allowing …
Browse files Browse the repository at this point in the history
…role edit and user delete
  • Loading branch information
135ze committed Jul 27, 2024
1 parent 6187ec6 commit 143de9d
Show file tree
Hide file tree
Showing 2 changed files with 208 additions and 1 deletion.
76 changes: 75 additions & 1 deletion app/api/users/[id]/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ export async function GET(req: NextRequest, params) {
return new NextResponse('Invalid id provided', { status: 400 });
}

const id = params.params.id;
const id = Number(params.params.id);

if (Number.isNaN(id)) {
return new NextResponse('ID not a number', { status: 400 });
Expand All @@ -40,3 +40,77 @@ export async function GET(req: NextRequest, params) {
return new NextResponse('Internal server error', { status: 500 });
}
}

export async function PATCH(req: NextRequest, params) {
// DATA UPDATED
const data = await req.json();
const email = data['email'];
const firstName = data['firstName'];
const lastName = data['lastName'];
const role = data['role'];
const status = data['status'];

const updatedData = {
email: email,
firstName: firstName,
lastName: lastName,
role: role,
status: status,
};

console.log(updatedData);

// ID
if (!params || !params.params || !params.params.id) {
return new NextResponse('Invalid id provided', { status: 400 });
}

const id = Number(params.params.id);

if (Number.isNaN(id)) {
return new NextResponse('ID not a number', { status: 400 });
}

try {
const user = await prisma.user.update({
where: { id },
data: updatedData,
});

if (!user) {
return new NextResponse('User not found', { status: 400 });
} else {
return new NextResponse(JSON.stringify(user), { status: 200 });
}
} catch (error) {
console.log(error);
return new NextResponse('Internal server error', { status: 500 });
}
}

export async function DELETE(req: NextRequest, params) {
// ID
if (!params || !params.params || !params.params.id) {
return new NextResponse('Invalid id provided', { status: 400 });
}

const id = Number(params.params.id);

if (Number.isNaN(id)) {
return new NextResponse('ID not a number', { status: 400 });
}

try {
const user = await prisma.user.delete({
where: { id },
});

if (!user) {
return new NextResponse('User not found', { status: 400 });
} else {
return new NextResponse('User with id' + id + 'deleted', { status: 200 });
}
} catch (error) {
return new NextResponse('Internal server error', { status: 500 });
}
}
133 changes: 133 additions & 0 deletions src/pages/manage.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,133 @@
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[]>([]);

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) {
console.error('Error fetching users:', error);
}
};

fetchUsers();
}, []);

const deleteUser = async (userId: number) => {
const confirmed = window.confirm('Confirm delete user');

if (!confirmed) {
return;
}

const apiUrl = `/api/users/${userId}`;

try {
// delete server side
const response = await fetch(apiUrl, { method: 'DELETE' });

if (!response.ok) {
throw new Error(response.statusText);
}

// delete in frontend
setUsers((prevUsers) => prevUsers.filter((user) => user.id !== userId));
} catch (error) {
console.error('Error deleting user:', error);
}
};

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

if (!confirmed) {
return;
}

const apiUrl = `/api/users/${userId}`;

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

if (!response.ok) {
throw new Error(response.statusText);
}

// update in frontend
setUsers(
users.map((user) =>
user.id === userId ? { ...user, role: newRole } : user
)
);
} catch (error) {
console.error('Error updating user:', error);
}
};

return (
<div>
<h1>Admin Management</h1>
{users ? (
<table>
<thead>
<tr>
<th>Name</th>
<th>Email</th>
<th>Role</th>
<th>Actions</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>
<td>
<button onClick={() => deleteUser(user.id)}>Delete</button>
</td>
</tr>
))}
</tbody>
</table>
) : (
<p>Loading...</p>
)}
</div>
);
}

0 comments on commit 143de9d

Please sign in to comment.