refactor(frontend): 重构前端目录结构并优化认证流程
将前端文件从html目录迁移到views目录,按功能模块组织 重构认证中间件和路由处理,简化页面权限控制 更新静态资源引用路径,统一使用/public前缀 添加学生仪表板页面,优化移动端显示 移除旧版html和js文件,更新样式和脚本
This commit is contained in:
583
frontend/public/js/admin.js
Normal file
583
frontend/public/js/admin.js
Normal file
@@ -0,0 +1,583 @@
|
||||
class AdminDashboard {
|
||||
constructor() {
|
||||
// 动态设置API基础URL,支持file:///协议和localhost:3000访问
|
||||
this.apiBase = window.location.protocol === 'file:' ? 'http://localhost:3000/api' : '/api';
|
||||
this.currentUser = null;
|
||||
this.stats = {};
|
||||
this.users = [];
|
||||
this.students = [];
|
||||
this.teachers = [];
|
||||
this.init();
|
||||
}
|
||||
|
||||
async init() {
|
||||
// 检查登录状<E5BD95><E78AB6>? if (!await this.checkAuth()) {
|
||||
window.location.href = '/login';
|
||||
return;
|
||||
}
|
||||
|
||||
// 加载用户信息
|
||||
await this.loadUserInfo();
|
||||
|
||||
// 加载统计数据
|
||||
await this.loadStats();
|
||||
|
||||
// 加载用户数据
|
||||
await this.loadUsers();
|
||||
|
||||
// 绑定事件
|
||||
this.bindEvents();
|
||||
|
||||
// 更新界面
|
||||
this.updateUI();
|
||||
|
||||
// 初始化图<E58C96><E59BBE>? this.initCharts();
|
||||
}
|
||||
|
||||
async checkAuth() {
|
||||
try {
|
||||
const response = await fetch(`${this.apiBase}/auth/me`, {
|
||||
credentials: 'include'
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const data = await response.json();
|
||||
return data.success && data.user.role === 'admin';
|
||||
} catch (error) {
|
||||
console.error('认证检查失<E69FA5><E5A4B1>?', error);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
async loadUserInfo() {
|
||||
try {
|
||||
const response = await fetch(`${this.apiBase}/auth/me`, {
|
||||
credentials: 'include'
|
||||
});
|
||||
|
||||
if (response.ok) {
|
||||
const data = await response.json();
|
||||
if (data.success) {
|
||||
this.currentUser = data.user;
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('加载用户信息失败:', error);
|
||||
}
|
||||
}
|
||||
|
||||
async loadStats() {
|
||||
try {
|
||||
const response = await fetch(`${this.apiBase}/admin/stats`, {
|
||||
credentials: 'include'
|
||||
});
|
||||
|
||||
if (response.ok) {
|
||||
const data = await response.json();
|
||||
if (data.success) {
|
||||
this.stats = data.stats;
|
||||
this.updateStatsUI();
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('加载统计数据失败:', error);
|
||||
this.showNotification('加载统计数据失败', 'error');
|
||||
}
|
||||
}
|
||||
|
||||
async loadUsers() {
|
||||
try {
|
||||
const response = await fetch(`${this.apiBase}/admin/users`, {
|
||||
credentials: 'include'
|
||||
});
|
||||
|
||||
if (response.ok) {
|
||||
const data = await response.json();
|
||||
if (data.success) {
|
||||
this.users = data.users;
|
||||
this.renderUsersTable();
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('加载用户数据失败:', error);
|
||||
this.showNotification('加载用户数据失败', 'error');
|
||||
}
|
||||
}
|
||||
|
||||
updateStatsUI() {
|
||||
// 更新统计卡片
|
||||
const statElements = {
|
||||
'totalUsers': 'totalUsers',
|
||||
'totalStudents': 'totalStudents',
|
||||
'totalTeachers': 'totalTeachers',
|
||||
'totalCourses': 'totalCourses',
|
||||
'totalGrades': 'totalGrades',
|
||||
'avgScore': 'avgScore'
|
||||
};
|
||||
|
||||
Object.entries(statElements).forEach(([key, elementId]) => {
|
||||
const element = document.getElementById(elementId);
|
||||
if (element && this.stats[key] !== undefined) {
|
||||
element.textContent = this.stats[key];
|
||||
}
|
||||
});
|
||||
|
||||
// 更新时间
|
||||
const timeElement = document.getElementById('currentTime');
|
||||
if (timeElement) {
|
||||
timeElement.textContent = new Date().toLocaleString();
|
||||
}
|
||||
}
|
||||
|
||||
renderUsersTable() {
|
||||
const tableBody = document.getElementById('usersTableBody');
|
||||
if (!tableBody) return;
|
||||
|
||||
if (this.users.length === 0) {
|
||||
tableBody.innerHTML = `
|
||||
<tr>
|
||||
<td colspan="7" class="text-center">
|
||||
<div class="no-data">
|
||||
<i class="fas fa-info-circle"></i>
|
||||
<p>暂无用户数据</p>
|
||||
</div>
|
||||
</td>
|
||||
</tr>
|
||||
`;
|
||||
return;
|
||||
}
|
||||
|
||||
tableBody.innerHTML = this.users.map(user => {
|
||||
const roleClass = this.getRoleClass(user.role);
|
||||
return `
|
||||
<tr>
|
||||
<td><input type="checkbox" class="user-checkbox" data-id="${user.id}"></td>
|
||||
<td>${user.user_id}</td>
|
||||
<td>${user.full_name}</td>
|
||||
<td><span class="role-badge ${roleClass}">${user.role}</span></td>
|
||||
<td>${user.class_name || 'N/A'}</td>
|
||||
<td>${user.email || 'N/A'}</td>
|
||||
<td>
|
||||
<div class="action-buttons">
|
||||
<button class="btn-edit" data-id="${user.id}">
|
||||
<i class="fas fa-edit"></i> 编辑
|
||||
</button>
|
||||
<button class="btn-delete" data-id="${user.id}">
|
||||
<i class="fas fa-trash"></i> 删除
|
||||
</button>
|
||||
</div>
|
||||
</td>
|
||||
</tr>
|
||||
`;
|
||||
}).join('');
|
||||
}
|
||||
|
||||
getRoleClass(role) {
|
||||
switch (role) {
|
||||
case 'admin': return 'role-admin';
|
||||
case 'teacher': return 'role-teacher';
|
||||
case 'student': return 'role-student';
|
||||
default: return 'role-default';
|
||||
}
|
||||
}
|
||||
|
||||
bindEvents() {
|
||||
// 导航菜单点击
|
||||
document.querySelectorAll('.nav-link').forEach(link => {
|
||||
link.addEventListener('click', (e) => {
|
||||
e.preventDefault();
|
||||
const page = link.dataset.page;
|
||||
this.loadPage(page);
|
||||
});
|
||||
});
|
||||
|
||||
// 搜索按钮
|
||||
document.getElementById('searchBtn')?.addEventListener('click', () => {
|
||||
this.handleSearch();
|
||||
});
|
||||
|
||||
// 重置按钮
|
||||
document.getElementById('resetBtn')?.addEventListener('click', () => {
|
||||
this.resetFilters();
|
||||
});
|
||||
|
||||
// 添加用户按钮
|
||||
document.getElementById('addUserBtn')?.addEventListener('click', () => {
|
||||
this.addUser();
|
||||
});
|
||||
|
||||
// 导出按钮
|
||||
document.getElementById('exportBtn')?.addEventListener('click', () => {
|
||||
this.exportUsers();
|
||||
});
|
||||
|
||||
// 批量删除按钮
|
||||
document.getElementById('batchDeleteBtn')?.addEventListener('click', () => {
|
||||
this.batchDeleteUsers();
|
||||
});
|
||||
|
||||
// 表格操作按钮事件委托
|
||||
document.addEventListener('click', (e) => {
|
||||
if (e.target.closest('.btn-edit')) {
|
||||
const userId = e.target.closest('.btn-edit').dataset.id;
|
||||
this.editUser(userId);
|
||||
}
|
||||
|
||||
if (e.target.closest('.btn-delete')) {
|
||||
const userId = e.target.closest('.btn-delete').dataset.id;
|
||||
this.deleteUser(userId);
|
||||
}
|
||||
});
|
||||
|
||||
// 退出登<E587BA><E799BB>? document.getElementById('logoutBtn')?.addEventListener('click', () => {
|
||||
this.handleLogout();
|
||||
});
|
||||
|
||||
// 刷新按钮
|
||||
document.getElementById('refreshBtn')?.addEventListener('click', () => {
|
||||
this.refreshData();
|
||||
});
|
||||
}
|
||||
|
||||
async loadPage(page) {
|
||||
// 这里可以实现页面切换逻辑
|
||||
// 暂时使用简单跳<E58D95><E8B7B3>? switch (page) {
|
||||
case 'users':
|
||||
window.location.href = '/admin/user_management';
|
||||
break;
|
||||
case 'students':
|
||||
window.location.href = '/admin/student_management';
|
||||
break;
|
||||
case 'teachers':
|
||||
// 可以跳转到教师管理页<E79086><E9A1B5>? break;
|
||||
case 'grades':
|
||||
window.location.href = '/teacher/grade_management';
|
||||
break;
|
||||
case 'settings':
|
||||
// 可以跳转到系统设置页<E7BDAE><E9A1B5>? break;
|
||||
}
|
||||
}
|
||||
|
||||
handleSearch() {
|
||||
const userId = document.getElementById('userIdFilter')?.value || '';
|
||||
const name = document.getElementById('nameFilter')?.value || '';
|
||||
const role = document.getElementById('roleFilter')?.value || '';
|
||||
const className = document.getElementById('classFilter')?.value || '';
|
||||
|
||||
// 这里可以实现搜索逻辑
|
||||
this.showNotification('搜索功能待实<E5BE85><E5AE9E>?, 'info');
|
||||
}
|
||||
|
||||
resetFilters() {
|
||||
document.getElementById('userIdFilter').value = '';
|
||||
document.getElementById('nameFilter').value = '';
|
||||
document.getElementById('roleFilter').value = '';
|
||||
document.getElementById('classFilter').value = '';
|
||||
|
||||
// 重新加载数据
|
||||
this.loadUsers();
|
||||
}
|
||||
|
||||
async addUser() {
|
||||
// 这里可以打开添加用户模态框
|
||||
const userData = {
|
||||
user_id: prompt('请输入用户ID:'),
|
||||
full_name: prompt('请输入姓<EFBFBD><EFBFBD>?'),
|
||||
role: prompt('请输入角<EFBFBD><EFBFBD>?(admin/teacher/student):'),
|
||||
email: prompt('请输入邮<EFBFBD><EFBFBD>?'),
|
||||
class_name: prompt('请输入班<EFBFBD><EFBFBD>?(学生/教师可<EFBFBD><EFBFBD>?:')
|
||||
};
|
||||
|
||||
if (!userData.user_id || !userData.full_name || !userData.role) {
|
||||
this.showNotification('用户ID、姓名和角色为必填项', 'error');
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const response = await fetch(`${this.apiBase}/admin/users`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
credentials: 'include',
|
||||
body: JSON.stringify(userData)
|
||||
});
|
||||
|
||||
const data = await response.json();
|
||||
if (data.success) {
|
||||
this.showNotification('用户添加成功', 'success');
|
||||
await this.loadUsers();
|
||||
} else {
|
||||
this.showNotification(data.message || '添加失败', 'error');
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('添加用户失败:', error);
|
||||
this.showNotification('添加用户失败', 'error');
|
||||
}
|
||||
}
|
||||
|
||||
async exportUsers() {
|
||||
try {
|
||||
const response = await fetch(`${this.apiBase}/admin/users/export`, {
|
||||
credentials: 'include'
|
||||
});
|
||||
|
||||
if (response.ok) {
|
||||
const blob = await response.blob();
|
||||
const url = window.URL.createObjectURL(blob);
|
||||
const a = document.createElement('a');
|
||||
a.href = url;
|
||||
a.download = `用户列表_${new Date().toISOString().split('T')[0]}.xlsx`;
|
||||
document.body.appendChild(a);
|
||||
a.click();
|
||||
document.body.removeChild(a);
|
||||
window.URL.revokeObjectURL(url);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('导出失败:', error);
|
||||
this.showNotification('导出失败', 'error');
|
||||
}
|
||||
}
|
||||
|
||||
async batchDeleteUsers() {
|
||||
const checkboxes = document.querySelectorAll('.user-checkbox:checked');
|
||||
if (checkboxes.length === 0) {
|
||||
this.showNotification('请选择要删除的用户', 'warning');
|
||||
return;
|
||||
}
|
||||
|
||||
if (!confirm(`确定要删除选中<E98089><E4B8AD>?${checkboxes.length} 个用户吗?`)) {
|
||||
return;
|
||||
}
|
||||
|
||||
const userIds = Array.from(checkboxes).map(cb => cb.dataset.id);
|
||||
|
||||
try {
|
||||
const response = await fetch(`${this.apiBase}/admin/users/batch`, {
|
||||
method: 'DELETE',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
credentials: 'include',
|
||||
body: JSON.stringify({ userIds })
|
||||
});
|
||||
|
||||
const data = await response.json();
|
||||
if (data.success) {
|
||||
this.showNotification(`成功删除 ${userIds.length} 个用户`, 'success');
|
||||
await this.loadUsers();
|
||||
} else {
|
||||
this.showNotification(data.message || '删除失败', 'error');
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('批量删除失败:', error);
|
||||
this.showNotification('批量删除失败', 'error');
|
||||
}
|
||||
}
|
||||
|
||||
async editUser(userId) {
|
||||
const user = this.users.find(u => u.id == userId);
|
||||
if (!user) return;
|
||||
|
||||
// 这里可以打开编辑模态框
|
||||
const newName = prompt('请输入新的姓<EFBFBD><EFBFBD>?', user.full_name);
|
||||
if (newName === null) return;
|
||||
|
||||
const newRole = prompt('请输入新的角<EFBFBD><EFBFBD>?', user.role);
|
||||
if (newRole === null) return;
|
||||
|
||||
try {
|
||||
const response = await fetch(`${this.apiBase}/admin/users/${userId}`, {
|
||||
method: 'PUT',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
credentials: 'include',
|
||||
body: JSON.stringify({
|
||||
full_name: newName,
|
||||
role: newRole,
|
||||
email: user.email,
|
||||
class_name: user.class_name
|
||||
})
|
||||
});
|
||||
|
||||
const data = await response.json();
|
||||
if (data.success) {
|
||||
this.showNotification('用户更新成功', 'success');
|
||||
await this.loadUsers();
|
||||
} else {
|
||||
this.showNotification(data.message || '更新失败', 'error');
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('更新用户失败:', error);
|
||||
this.showNotification('更新用户失败', 'error');
|
||||
}
|
||||
}
|
||||
|
||||
async deleteUser(userId) {
|
||||
if (!confirm('确定要删除这个用户吗<EFBFBD><EFBFBD>?)) {
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const response = await fetch(`${this.apiBase}/admin/users/${userId}`, {
|
||||
method: 'DELETE',
|
||||
credentials: 'include'
|
||||
});
|
||||
|
||||
const data = await response.json();
|
||||
if (data.success) {
|
||||
this.showNotification('用户删除成功', 'success');
|
||||
await this.loadUsers();
|
||||
} else {
|
||||
this.showNotification(data.message || '删除失败', 'error');
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('删除用户失败:', error);
|
||||
this.showNotification('删除用户失败', 'error');
|
||||
}
|
||||
}
|
||||
|
||||
async handleLogout() {
|
||||
try {
|
||||
const response = await fetch(`${this.apiBase}/auth/logout`, {
|
||||
method: 'POST',
|
||||
credentials: 'include'
|
||||
});
|
||||
|
||||
if (response.ok) {
|
||||
window.location.href = '/login';
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('退出登录失<E5BD95><E5A4B1>?', error);
|
||||
}
|
||||
}
|
||||
|
||||
async refreshData() {
|
||||
await this.loadStats();
|
||||
await this.loadUsers();
|
||||
this.showNotification('数据已刷<E5B7B2><E588B7>?, 'success');
|
||||
}
|
||||
|
||||
updateUI() {
|
||||
// 更新用户信息
|
||||
if (this.currentUser) {
|
||||
const userInfoElements = document.querySelectorAll('.user-info');
|
||||
userInfoElements.forEach(el => {
|
||||
el.textContent = `${this.currentUser.full_name} (${this.currentUser.role})`;
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
async initCharts() {
|
||||
// 加载Chart.js<6A><73>? await this.loadChartLibrary();
|
||||
|
||||
// 初始化用户分布饼<E5B883><E9A5BC>? this.initUserDistributionChart();
|
||||
|
||||
// 初始化成绩分布柱状图
|
||||
this.initGradeDistributionChart();
|
||||
}
|
||||
|
||||
showNotification(message, type = 'info') {
|
||||
// 创建通知元素
|
||||
const notification = document.createElement('div');
|
||||
notification.className = `notification notification-${type}`;
|
||||
notification.innerHTML = `
|
||||
<i class="fas fa-${type === 'success' ? 'check-circle' : type === 'error' ? 'exclamation-circle' : type === 'warning' ? 'exclamation-triangle' : 'info-circle'}"></i>
|
||||
<span>${message}</span>
|
||||
<button class="notification-close">×</button>
|
||||
`;
|
||||
|
||||
// 添加到页<E588B0><E9A1B5>? document.body.appendChild(notification);
|
||||
|
||||
// 添加关闭事件
|
||||
notification.querySelector('.notification-close').addEventListener('click', () => {
|
||||
notification.remove();
|
||||
});
|
||||
|
||||
// 自动移除
|
||||
setTimeout(() => {
|
||||
if (notification.parentNode) {
|
||||
notification.remove();
|
||||
}
|
||||
}, 5000);
|
||||
}
|
||||
|
||||
async loadChartLibrary() {
|
||||
if (typeof Chart !== 'undefined') return;
|
||||
|
||||
return new Promise((resolve, reject) => {
|
||||
const script = document.createElement('script');
|
||||
script.src = 'https://cdn.jsdelivr.net/npm/chart.js@3.9.1/dist/chart.min.js';
|
||||
script.onload = resolve;
|
||||
script.onerror = reject;
|
||||
document.head.appendChild(script);
|
||||
});
|
||||
}
|
||||
|
||||
initUserDistributionChart() {
|
||||
const ctx = document.getElementById('userDistributionChart');
|
||||
if (!ctx) return;
|
||||
|
||||
// 模拟数据
|
||||
const data = {
|
||||
labels: ['学生', '教师', '管理<E7AEA1><E79086>?],
|
||||
datasets: [{
|
||||
data: [this.stats.totalStudents || 100, this.stats.totalTeachers || 20, 1],
|
||||
backgroundColor: [
|
||||
'rgba(54, 162, 235, 0.8)',
|
||||
'rgba(255, 206, 86, 0.8)',
|
||||
'rgba(255, 99, 132, 0.8)'
|
||||
]
|
||||
}]
|
||||
};
|
||||
|
||||
new Chart(ctx, {
|
||||
type: 'pie',
|
||||
data: data,
|
||||
options: {
|
||||
responsive: true,
|
||||
plugins: {
|
||||
legend: {
|
||||
position: 'bottom'
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
initGradeDistributionChart() {
|
||||
const ctx = document.getElementById('gradeDistributionChart');
|
||||
if (!ctx) return;
|
||||
|
||||
// 模拟数据
|
||||
const data = {
|
||||
labels: ['A', 'B', 'C', 'D', 'F'],
|
||||
datasets: [{
|
||||
label: '成绩分布',
|
||||
data: [25, 35, 20, 15, 5],
|
||||
backgroundColor: [
|
||||
'rgba(75, 192, 192, 0.8)',
|
||||
'rgba(54, 162, 235, 0.8)',
|
||||
'rgba(255, 206, 86, 0.8)',
|
||||
'rgba(255, 159, 64, 0.8)',
|
||||
'rgba(255, 99, 132, 0.8)'
|
||||
]
|
||||
}]
|
||||
};
|
||||
|
||||
new Chart(ctx, {
|
||||
type: 'bar',
|
||||
data: data,
|
||||
options: {
|
||||
responsive: true,
|
||||
scales: {
|
||||
y: {
|
||||
beginAtZero: true,
|
||||
ticks: {
|
||||
stepSize: 10
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
287
frontend/public/js/auth.js
Normal file
287
frontend/public/js/auth.js
Normal file
@@ -0,0 +1,287 @@
|
||||
/**
|
||||
* 认证模块管理器
|
||||
* 处理登录、注册、注销及权限检查
|
||||
*/
|
||||
class AuthManager {
|
||||
constructor() {
|
||||
this.apiBase = '/api';
|
||||
this.init();
|
||||
}
|
||||
|
||||
init() {
|
||||
this.createNotificationContainer();
|
||||
this.initEventListeners();
|
||||
this.checkAuthStatus();
|
||||
}
|
||||
|
||||
/**
|
||||
* 创建通知容器
|
||||
*/
|
||||
createNotificationContainer() {
|
||||
if (!document.getElementById('notification-container')) {
|
||||
const container = document.createElement('div');
|
||||
container.id = 'notification-container';
|
||||
container.style.cssText = `
|
||||
position: fixed;
|
||||
top: 20px;
|
||||
right: 20px;
|
||||
z-index: 9999;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 10px;
|
||||
`;
|
||||
document.body.appendChild(container);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 检查用户认证状态
|
||||
*/
|
||||
async checkAuthStatus() {
|
||||
// 如果当前是公共页面,可以选择不检查,或者检查后更新UI
|
||||
const currentPath = window.location.pathname;
|
||||
const isAuthPage = currentPath.includes('/login') || currentPath.includes('/register');
|
||||
|
||||
try {
|
||||
const response = await fetch(`${this.apiBase}/auth/me`);
|
||||
const data = await response.json();
|
||||
|
||||
if (data.success && data.user) {
|
||||
// 用户已登录
|
||||
const redirectUrl = this.getDashboardUrl(data.user.role);
|
||||
|
||||
// 如果在登录/注册页,跳转到仪表板
|
||||
if (isAuthPage || currentPath === '/') {
|
||||
window.location.href = redirectUrl;
|
||||
}
|
||||
} else {
|
||||
// 用户未登录,如果在受保护页面,跳转到登录页
|
||||
// 注意:后端通常已经处理了重定向,这里是前端的额外保障
|
||||
if (!isAuthPage && currentPath !== '/') {
|
||||
// 可以在这里添加逻辑,但通常交给后端控制
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Auth check failed:', error);
|
||||
}
|
||||
}
|
||||
|
||||
getDashboardUrl(role) {
|
||||
switch(role) {
|
||||
case 'student': return '/student/dashboard';
|
||||
case 'teacher': return '/teacher/dashboard';
|
||||
case 'admin': return '/admin/dashboard';
|
||||
default: return '/dashboard';
|
||||
}
|
||||
}
|
||||
|
||||
initEventListeners() {
|
||||
// 登录表单
|
||||
const loginForm = document.getElementById('loginForm');
|
||||
if (loginForm) {
|
||||
loginForm.addEventListener('submit', (e) => this.handleLogin(e));
|
||||
}
|
||||
|
||||
// 注册表单
|
||||
const registerForm = document.getElementById('registerForm');
|
||||
if (registerForm) {
|
||||
registerForm.addEventListener('submit', (e) => this.handleRegister(e));
|
||||
|
||||
// 角色选择联动
|
||||
const roleSelect = document.getElementById('role');
|
||||
if (roleSelect) {
|
||||
roleSelect.addEventListener('change', (e) => this.handleRoleChange(e));
|
||||
}
|
||||
}
|
||||
|
||||
// 注销按钮 (可能有多个,例如在导航栏)
|
||||
document.querySelectorAll('.btn-logout, #logoutBtn').forEach(btn => {
|
||||
btn.addEventListener('click', (e) => this.handleLogout(e));
|
||||
});
|
||||
}
|
||||
|
||||
handleRoleChange(e) {
|
||||
const role = e.target.value;
|
||||
const classField = document.getElementById('classField');
|
||||
const classInput = document.getElementById('class');
|
||||
|
||||
if (classField && classInput) {
|
||||
if (role === 'student' || role === 'teacher') {
|
||||
classField.style.display = 'block';
|
||||
classInput.required = true;
|
||||
} else {
|
||||
classField.style.display = 'none';
|
||||
classInput.required = false;
|
||||
classInput.value = ''; // 清空值
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async handleLogin(e) {
|
||||
e.preventDefault();
|
||||
const form = e.target;
|
||||
const submitBtn = form.querySelector('button[type="submit"]');
|
||||
|
||||
if (this.setLoading(submitBtn, true, '登录中...')) {
|
||||
try {
|
||||
const formData = new FormData(form);
|
||||
const data = Object.fromEntries(formData.entries());
|
||||
|
||||
const response = await fetch(`${this.apiBase}/auth/login`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(data)
|
||||
});
|
||||
|
||||
const result = await response.json();
|
||||
|
||||
if (result.success) {
|
||||
this.showNotification('登录成功,正在跳转...', 'success');
|
||||
setTimeout(() => {
|
||||
window.location.href = this.getDashboardUrl(result.user.role);
|
||||
}, 1000);
|
||||
} else {
|
||||
this.showNotification(result.message || '登录失败', 'error');
|
||||
this.setLoading(submitBtn, false);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Login error:', error);
|
||||
this.showNotification('网络错误,请稍后重试', 'error');
|
||||
this.setLoading(submitBtn, false);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async handleRegister(e) {
|
||||
e.preventDefault();
|
||||
const form = e.target;
|
||||
const submitBtn = form.querySelector('button[type="submit"]');
|
||||
|
||||
// 获取数据
|
||||
const formData = new FormData(form);
|
||||
const data = Object.fromEntries(formData.entries());
|
||||
|
||||
// 简单验证
|
||||
if (data.password !== data.confirmPassword) {
|
||||
this.showNotification('两次输入的密码不一致', 'error');
|
||||
return;
|
||||
}
|
||||
|
||||
if (this.setLoading(submitBtn, true, '注册中...')) {
|
||||
try {
|
||||
const response = await fetch(`${this.apiBase}/auth/register`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(data)
|
||||
});
|
||||
|
||||
const result = await response.json();
|
||||
|
||||
if (result.success) {
|
||||
this.showNotification('注册成功,请登录', 'success');
|
||||
setTimeout(() => {
|
||||
window.location.href = '/login';
|
||||
}, 1500);
|
||||
} else {
|
||||
this.showNotification(result.message || '注册失败', 'error');
|
||||
this.setLoading(submitBtn, false);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Register error:', error);
|
||||
this.showNotification('网络错误,请稍后重试', 'error');
|
||||
this.setLoading(submitBtn, false);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async handleLogout(e) {
|
||||
e.preventDefault();
|
||||
|
||||
if (confirm('确定要退出登录吗?')) {
|
||||
try {
|
||||
const response = await fetch(`${this.apiBase}/auth/logout`, {
|
||||
method: 'POST'
|
||||
});
|
||||
|
||||
const result = await response.json();
|
||||
|
||||
if (result.success) {
|
||||
this.showNotification('已退出登录', 'success');
|
||||
setTimeout(() => {
|
||||
window.location.href = '/login';
|
||||
}, 1000);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Logout error:', error);
|
||||
// 即使出错也强制跳转到登录页
|
||||
window.location.href = '/login';
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 设置按钮加载状态
|
||||
* @param {HTMLElement} btn 按钮元素
|
||||
* @param {boolean} isLoading 是否正在加载
|
||||
* @param {string} text 加载时的文本
|
||||
* @returns {boolean} true表示状态设置成功
|
||||
*/
|
||||
setLoading(btn, isLoading, text = '') {
|
||||
if (!btn) return false;
|
||||
|
||||
if (isLoading) {
|
||||
if (btn.dataset.loading) return false; // 防止重复提交
|
||||
btn.dataset.loading = 'true';
|
||||
btn.dataset.originalText = btn.innerHTML;
|
||||
btn.innerHTML = `<i class="fas fa-spinner fa-spin"></i> ${text}`;
|
||||
btn.disabled = true;
|
||||
} else {
|
||||
btn.innerHTML = btn.dataset.originalText || btn.innerHTML;
|
||||
delete btn.dataset.loading;
|
||||
btn.disabled = false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* 显示通知
|
||||
* @param {string} message 消息内容
|
||||
* @param {string} type 消息类型 'success' | 'error' | 'info'
|
||||
*/
|
||||
showNotification(message, type = 'info') {
|
||||
const container = document.getElementById('notification-container');
|
||||
if (!container) return;
|
||||
|
||||
const notification = document.createElement('div');
|
||||
notification.className = `notification ${type}`;
|
||||
|
||||
let icon = 'info-circle';
|
||||
if (type === 'success') icon = 'check-circle';
|
||||
if (type === 'error') icon = 'exclamation-circle';
|
||||
|
||||
notification.innerHTML = `
|
||||
<i class="fas fa-${icon}"></i>
|
||||
<span class="notification-content">${message}</span>
|
||||
`;
|
||||
|
||||
container.appendChild(notification);
|
||||
|
||||
// 动画显示
|
||||
requestAnimationFrame(() => {
|
||||
notification.classList.add('show');
|
||||
});
|
||||
|
||||
// 自动消失
|
||||
setTimeout(() => {
|
||||
notification.classList.remove('show');
|
||||
notification.addEventListener('transitionend', () => {
|
||||
notification.remove();
|
||||
});
|
||||
}, 3000);
|
||||
}
|
||||
}
|
||||
|
||||
// 初始化
|
||||
document.addEventListener('DOMContentLoaded', () => {
|
||||
window.authManager = new AuthManager();
|
||||
});
|
||||
213
frontend/public/js/main.js
Normal file
213
frontend/public/js/main.js
Normal file
@@ -0,0 +1,213 @@
|
||||
// 首页通用JavaScript功能
|
||||
// 主要处理导航栏交互、页面滚动效果等通用功能
|
||||
|
||||
class MainPage {
|
||||
constructor() {
|
||||
this.init();
|
||||
}
|
||||
|
||||
init() {
|
||||
// 初始化所有功<E69C89><E58A9F>? this.initNavbar();
|
||||
this.initScrollEffects();
|
||||
this.initSmoothScroll();
|
||||
this.initBackToTop();
|
||||
this.initMobileMenu();
|
||||
this.initAuthButtons();
|
||||
}
|
||||
|
||||
// 初始化导航栏交互
|
||||
initNavbar() {
|
||||
const navbar = document.querySelector('.navbar');
|
||||
if (!navbar) return;
|
||||
|
||||
// 滚动时改变导航栏样式
|
||||
window.addEventListener('scroll', () => {
|
||||
if (window.scrollY > 50) {
|
||||
navbar.classList.add('navbar-scrolled');
|
||||
} else {
|
||||
navbar.classList.remove('navbar-scrolled');
|
||||
}
|
||||
});
|
||||
|
||||
// 初始化当前页面高<E99DA2><E9AB98>? this.highlightCurrentPage();
|
||||
}
|
||||
|
||||
// 高亮当前页面导航链接
|
||||
highlightCurrentPage() {
|
||||
const currentPath = window.location.pathname;
|
||||
const navLinks = document.querySelectorAll('.nav-link');
|
||||
|
||||
navLinks.forEach(link => {
|
||||
const href = link.getAttribute('href');
|
||||
if (href && currentPath.includes(href.replace('.html', ''))) {
|
||||
link.classList.add('active');
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
// 初始化滚动效<E58AA8><E69588>? initScrollEffects() {
|
||||
// 滚动时显<E697B6><E698BE>?隐藏元素
|
||||
const observerOptions = {
|
||||
root: null,
|
||||
rootMargin: '0px',
|
||||
threshold: 0.1
|
||||
};
|
||||
|
||||
const observer = new IntersectionObserver((entries) => {
|
||||
entries.forEach(entry => {
|
||||
if (entry.isIntersecting) {
|
||||
entry.target.classList.add('animate-in');
|
||||
}
|
||||
});
|
||||
}, observerOptions);
|
||||
|
||||
// 观察需要动画的元素
|
||||
document.querySelectorAll('.feature-card, .hero-content').forEach(el => {
|
||||
observer.observe(el);
|
||||
});
|
||||
}
|
||||
|
||||
// 初始化平滑滚<E6BB91><E6BB9A>? initSmoothScroll() {
|
||||
document.querySelectorAll('a[href^="#"]').forEach(anchor => {
|
||||
anchor.addEventListener('click', (e) => {
|
||||
e.preventDefault();
|
||||
const targetId = anchor.getAttribute('href');
|
||||
if (targetId === '#') return;
|
||||
|
||||
const targetElement = document.querySelector(targetId);
|
||||
if (targetElement) {
|
||||
targetElement.scrollIntoView({
|
||||
behavior: 'smooth',
|
||||
block: 'start'
|
||||
});
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
// 初始化返回顶部按<E983A8><E68C89>? initBackToTop() {
|
||||
const backToTopBtn = document.createElement('button');
|
||||
backToTopBtn.id = 'backToTop';
|
||||
backToTopBtn.innerHTML = '<i class="fas fa-chevron-up"></i>';
|
||||
backToTopBtn.title = '返回顶部';
|
||||
document.body.appendChild(backToTopBtn);
|
||||
|
||||
// 滚动时显<E697B6><E698BE>?隐藏按钮
|
||||
window.addEventListener('scroll', () => {
|
||||
if (window.scrollY > 300) {
|
||||
backToTopBtn.classList.add('show');
|
||||
} else {
|
||||
backToTopBtn.classList.remove('show');
|
||||
}
|
||||
});
|
||||
|
||||
// 点击返回顶部
|
||||
backToTopBtn.addEventListener('click', () => {
|
||||
window.scrollTo({
|
||||
top: 0,
|
||||
behavior: 'smooth'
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
// 初始化移动端菜单
|
||||
initMobileMenu() {
|
||||
const navbarToggler = document.querySelector('.navbar-toggler');
|
||||
const navbarCollapse = document.querySelector('.navbar-collapse');
|
||||
|
||||
if (!navbarToggler || !navbarCollapse) return;
|
||||
|
||||
navbarToggler.addEventListener('click', () => {
|
||||
navbarCollapse.classList.toggle('show');
|
||||
});
|
||||
|
||||
// 点击菜单项后自动关闭移动菜单
|
||||
document.querySelectorAll('.navbar-nav .nav-link').forEach(link => {
|
||||
link.addEventListener('click', () => {
|
||||
if (navbarCollapse.classList.contains('show')) {
|
||||
navbarCollapse.classList.remove('show');
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
// 初始化认证按钮状<E992AE><E78AB6>? initAuthButtons() {
|
||||
// 检查用户是否已登录
|
||||
this.checkLoginStatus().then(user => {
|
||||
const loginBtn = document.getElementById('loginBtn');
|
||||
const registerBtn = document.getElementById('registerBtn');
|
||||
const heroLoginBtn = document.getElementById('heroLoginBtn');
|
||||
|
||||
if (user) {
|
||||
// 用户已登录,显示仪表板按<E69DBF><E68C89>? // 根据用户角色设置正确的仪表板路径
|
||||
let dashboardUrl = '/dashboard';
|
||||
if (user.role === 'student') {
|
||||
dashboardUrl = '/student/dashboard';
|
||||
} else if (user.role === 'teacher') {
|
||||
dashboardUrl = '/teacher/dashboard';
|
||||
} else if (user.role === 'admin') {
|
||||
dashboardUrl = '/admin/dashboard';
|
||||
}
|
||||
|
||||
if (loginBtn) {
|
||||
loginBtn.textContent = '进入仪表<E4BBAA><E8A1A8>?;
|
||||
loginBtn.href = dashboardUrl;
|
||||
}
|
||||
if (heroLoginBtn) {
|
||||
heroLoginBtn.textContent = '进入仪表<EFBFBD><EFBFBD>?;
|
||||
heroLoginBtn.href = dashboardUrl;
|
||||
}
|
||||
if (registerBtn) {
|
||||
registerBtn.style.display = 'none';
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
// 检查登录状<E5BD95><E78AB6>? async checkLoginStatus() {
|
||||
try {
|
||||
const apiBase = window.location.protocol === 'file:' ? 'http://localhost:3000/api' : '/api';
|
||||
const response = await fetch(`${apiBase}/auth/me`);
|
||||
const data = await response.json();
|
||||
return data.success && data.user;
|
||||
} catch (error) {
|
||||
console.log('用户未登<E69CAA><E799BB>?);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
// 显示通知
|
||||
showNotification(message, type = 'info') {
|
||||
// 创建通知元素
|
||||
const notification = document.createElement('div');
|
||||
notification.className = `notification notification-${type}`;
|
||||
notification.innerHTML = `
|
||||
<div class="notification-content">
|
||||
<i class="fas ${type === 'success' ? 'fa-check-circle' : type === 'error' ? 'fa-exclamation-circle' : 'fa-info-circle'}"></i>
|
||||
<span>${message}</span>
|
||||
</div>
|
||||
`;
|
||||
|
||||
// 添加到页<E588B0><E9A1B5>? document.body.appendChild(notification);
|
||||
|
||||
// 显示通知
|
||||
setTimeout(() => {
|
||||
notification.classList.add('show');
|
||||
}, 10);
|
||||
|
||||
// 自动隐藏
|
||||
setTimeout(() => {
|
||||
notification.classList.remove('show');
|
||||
setTimeout(() => {
|
||||
if (notification.parentNode) {
|
||||
notification.parentNode.removeChild(notification);
|
||||
}
|
||||
}, 300);
|
||||
}, 3000);
|
||||
}
|
||||
}
|
||||
|
||||
// 页面加载完成后初始化
|
||||
document.addEventListener('DOMContentLoaded', () => {
|
||||
new MainPage();
|
||||
});
|
||||
438
frontend/public/js/student.js
Normal file
438
frontend/public/js/student.js
Normal file
@@ -0,0 +1,438 @@
|
||||
class StudentManager {
|
||||
constructor() {
|
||||
// 动态设置API基础URL,支持file:///协议和localhost:3000访问
|
||||
this.apiBase = window.location.protocol === 'file:' ? 'http://localhost:3000/api' : '/api';
|
||||
this.initDashboard();
|
||||
this.initGradeDetails();
|
||||
this.loadProfile();
|
||||
}
|
||||
|
||||
async initDashboard() {
|
||||
const gradeList = document.getElementById('gradeList');
|
||||
const statisticsElement = document.getElementById('statistics');
|
||||
|
||||
if (!gradeList) return;
|
||||
|
||||
try {
|
||||
const response = await fetch(`${this.apiBase}/student/grades`, {
|
||||
credentials: 'include'
|
||||
});
|
||||
|
||||
if (response.status === 401) {
|
||||
// 未登录,重定向到登录<E799BB><E5BD95>?
|
||||
this.showNotification('请先登录', 'error');
|
||||
setTimeout(() => {
|
||||
window.location.href = '/login';
|
||||
}, 1500);
|
||||
return;
|
||||
}
|
||||
|
||||
const data = await response.json();
|
||||
|
||||
if (data.success) {
|
||||
this.renderGrades(data.grades);
|
||||
this.renderStatistics(data.statistics);
|
||||
this.updateChart(data.grades);
|
||||
} else {
|
||||
this.showNotification(data.message || '获取成绩失败', 'error');
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('获取成绩错误:', error);
|
||||
this.showNotification('网络错误,请重试', 'error');
|
||||
}
|
||||
}
|
||||
|
||||
renderGrades(grades) {
|
||||
const gradeList = document.getElementById('gradeList');
|
||||
const gradeTable = document.getElementById('gradeTable');
|
||||
|
||||
if (!gradeTable) return;
|
||||
|
||||
if (grades.length === 0) {
|
||||
gradeList.innerHTML = `
|
||||
<div class="empty-state">
|
||||
<i class="fas fa-clipboard-list fa-3x"></i>
|
||||
<h3>暂无成绩记录</h3>
|
||||
<p>你还没有任何成绩记录</p>
|
||||
</div>
|
||||
`;
|
||||
return;
|
||||
}
|
||||
|
||||
const tbody = gradeTable.querySelector('tbody');
|
||||
tbody.innerHTML = '';
|
||||
|
||||
grades.forEach(grade => {
|
||||
const row = document.createElement('tr');
|
||||
|
||||
// 根据分数设置颜色
|
||||
let scoreClass = '';
|
||||
if (grade.score >= 90) scoreClass = 'grade-excellent';
|
||||
else if (grade.score >= 80) scoreClass = 'grade-good';
|
||||
else if (grade.score >= 60) scoreClass = 'grade-pass';
|
||||
else scoreClass = 'grade-fail';
|
||||
|
||||
row.innerHTML = `
|
||||
<td>${grade.course_code}</td>
|
||||
<td>${grade.course_name}</td>
|
||||
<td>${grade.credit}</td>
|
||||
<td class="${scoreClass}">
|
||||
<span class="grade-badge">${grade.score}</span>
|
||||
</td>
|
||||
<td>${grade.grade_level || '-'}</td>
|
||||
<td>${grade.grade_point || '-'}</td>
|
||||
<td>${grade.teacher_name}</td>
|
||||
<td>${new Date(grade.exam_date).toLocaleDateString()}</td>
|
||||
<td>
|
||||
<a href="/html/student/details.html?id=${grade.id}"
|
||||
class="btn btn-sm btn-secondary">
|
||||
<i class="fas fa-eye"></i> 查看
|
||||
</a>
|
||||
</td>
|
||||
`;
|
||||
|
||||
tbody.appendChild(row);
|
||||
});
|
||||
}
|
||||
|
||||
renderStatistics(statistics) {
|
||||
const element = document.getElementById('statistics');
|
||||
if (!element) return;
|
||||
|
||||
element.innerHTML = `
|
||||
<div class="stats-grid">
|
||||
<div class="stat-card">
|
||||
<div class="stat-icon student">
|
||||
<i class="fas fa-book"></i>
|
||||
</div>
|
||||
<div class="stat-value">${statistics.totalCourses}</div>
|
||||
<div class="stat-label">总课程数</div>
|
||||
</div>
|
||||
<div class="stat-card">
|
||||
<div class="stat-icon course">
|
||||
<i class="fas fa-star"></i>
|
||||
</div>
|
||||
<div class="stat-value">${statistics.totalCredits}</div>
|
||||
<div class="stat-label">总学<E680BB><E5ADA6>?/div>
|
||||
</div>
|
||||
<div class="stat-card">
|
||||
<div class="stat-icon grade">
|
||||
<i class="fas fa-chart-line"></i>
|
||||
</div>
|
||||
<div class="stat-value">${statistics.averageScore}</div>
|
||||
<div class="stat-label">平均<E5B9B3><E59D87>?/div>
|
||||
</div>
|
||||
<div class="stat-card">
|
||||
<div class="stat-icon teacher">
|
||||
<i class="fas fa-graduation-cap"></i>
|
||||
</div>
|
||||
<div class="stat-value">${statistics.gpa}</div>
|
||||
<div class="stat-label">平均绩点</div>
|
||||
</div>
|
||||
</div>
|
||||
`;
|
||||
}
|
||||
|
||||
async loadProfile() {
|
||||
const profileElement = document.getElementById('profileInfo');
|
||||
if (!profileElement) return;
|
||||
|
||||
try {
|
||||
const response = await fetch(`${this.apiBase}/student/profile`, {
|
||||
credentials: 'include'
|
||||
});
|
||||
|
||||
if (response.status === 401) {
|
||||
// 未登录,重定向到登录<E799BB><E5BD95>?
|
||||
this.showNotification('请先登录', 'error');
|
||||
setTimeout(() => {
|
||||
window.location.href = '/login';
|
||||
}, 1500);
|
||||
return;
|
||||
}
|
||||
|
||||
const data = await response.json();
|
||||
|
||||
if (data.success) {
|
||||
const profile = data.profile;
|
||||
|
||||
// 更新学生仪表板顶部信<E983A8><E4BFA1>?
|
||||
const userNameElement = document.getElementById('userName');
|
||||
const studentNameElement = document.getElementById('studentName');
|
||||
const studentClassElement = document.getElementById('studentClass');
|
||||
|
||||
if (userNameElement) {
|
||||
userNameElement.textContent = profile.full_name || profile.username;
|
||||
}
|
||||
if (studentNameElement) {
|
||||
studentNameElement.textContent = profile.full_name || profile.username;
|
||||
}
|
||||
if (studentClassElement) {
|
||||
studentClassElement.textContent = profile.class_name || '未设<E69CAA><E8AEBE>?;
|
||||
}
|
||||
|
||||
profileElement.innerHTML = `
|
||||
<div class="profile-header">
|
||||
<div class="profile-avatar">
|
||||
<i class="fas fa-user-graduate"></i>
|
||||
</div>
|
||||
<div class="profile-info">
|
||||
<h2>${profile.full_name}</h2>
|
||||
<p class="profile-role">
|
||||
<i class="fas fa-user-tag"></i> 学生
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
<div class="profile-details">
|
||||
<div class="detail-item">
|
||||
<i class="fas fa-id-card"></i>
|
||||
<div>
|
||||
<h4>学号</h4>
|
||||
<p>${profile.student_id}</p>
|
||||
</div>
|
||||
</div>
|
||||
<div class="detail-item">
|
||||
<i class="fas fa-users"></i>
|
||||
<div>
|
||||
<h4>班级</h4>
|
||||
<p>${profile.class_name}</p>
|
||||
</div>
|
||||
</div>
|
||||
<div class="detail-item">
|
||||
<i class="fas fa-book"></i>
|
||||
<div>
|
||||
<h4>专业</h4>
|
||||
<p>${profile.major || '未设<EFBFBD><EFBFBD>?}</p>
|
||||
</div>
|
||||
</div>
|
||||
<div class="detail-item">
|
||||
<i class="fas fa-calendar-alt"></i>
|
||||
<div>
|
||||
<h4>入学年份</h4>
|
||||
<p>${profile.enrollment_year || '未设<E69CAA><E8AEBE>?}</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
`;
|
||||
} else {
|
||||
// API返回失败
|
||||
this.showNotification(data.message || '获取个人信息失败', 'error');
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('加载个人信息错误:', error);
|
||||
this.showNotification('网络错误,请重试', 'error');
|
||||
}
|
||||
}
|
||||
|
||||
async initGradeDetails() {
|
||||
const urlParams = new URLSearchParams(window.location.search);
|
||||
const gradeId = urlParams.get('id');
|
||||
|
||||
if (!gradeId) return;
|
||||
|
||||
try {
|
||||
const response = await fetch(`${this.apiBase}/student/grades/${gradeId}`, {
|
||||
credentials: 'include'
|
||||
});
|
||||
const data = await response.json();
|
||||
|
||||
if (data.success) {
|
||||
this.renderGradeDetails(data.grade);
|
||||
} else {
|
||||
this.showNotification('获取成绩详情失败', 'error');
|
||||
setTimeout(() => window.history.back(), 1500);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('获取成绩详情错误:', error);
|
||||
this.showNotification('网络错误,请重试', 'error');
|
||||
}
|
||||
}
|
||||
|
||||
renderGradeDetails(grade) {
|
||||
const container = document.getElementById('gradeDetails');
|
||||
if (!container) return;
|
||||
|
||||
// 计算绩点描述
|
||||
let gradeDescription = '';
|
||||
if (grade.score >= 90) gradeDescription = '优秀';
|
||||
else if (grade.score >= 80) gradeDescription = '良好';
|
||||
else if (grade.score >= 70) gradeDescription = '中等';
|
||||
else if (grade.score >= 60) gradeDescription = '及格';
|
||||
else gradeDescription = '不及<EFBFBD><EFBFBD>?;
|
||||
|
||||
container.innerHTML = `
|
||||
<div class="grade-detail-card">
|
||||
<div class="grade-header">
|
||||
<h2>${grade.course_name} (${grade.course_code})</h2>
|
||||
<div class="grade-score ${grade.score >= 60 ? 'score-pass' : 'score-fail'}">
|
||||
${grade.score} <20><>?
|
||||
<span class="grade-description">${gradeDescription}</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="grade-details-grid">
|
||||
<div class="detail-section">
|
||||
<h3><i class="fas fa-info-circle"></i> 基本信息</h3>
|
||||
<div class="detail-row">
|
||||
<span>学分<E5ADA6><E58886>?/span>
|
||||
<strong>${grade.credit}</strong>
|
||||
</div>
|
||||
<div class="detail-row">
|
||||
<span>学期<E5ADA6><E69C9F>?/span>
|
||||
<strong>${grade.semester}</strong>
|
||||
</div>
|
||||
<div class="detail-row">
|
||||
<span>考试日期<E697A5><E69C9F>?/span>
|
||||
<strong>${new Date(grade.exam_date).toLocaleDateString()}</strong>
|
||||
</div>
|
||||
<div class="detail-row">
|
||||
<span>等级<E7AD89><E7BAA7>?/span>
|
||||
<strong class="grade-level-${grade.grade_level}">${grade.grade_level || '-'}</strong>
|
||||
</div>
|
||||
<div class="detail-row">
|
||||
<span>绩点<E7BBA9><E782B9>?/span>
|
||||
<strong>${grade.grade_point || '-'}</strong>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="detail-section">
|
||||
<h3><i class="fas fa-user-graduate"></i> 学生信息</h3>
|
||||
<div class="detail-row">
|
||||
<span>姓名<E5A793><E5908D>?/span>
|
||||
<strong>${grade.full_name}</strong>
|
||||
</div>
|
||||
<div class="detail-row">
|
||||
<span>学号<E5ADA6><E58FB7>?/span>
|
||||
<strong>${grade.student_number}</strong>
|
||||
</div>
|
||||
<div class="detail-row">
|
||||
<span>班级<E78FAD><E7BAA7>?/span>
|
||||
<strong>${grade.class_name}</strong>
|
||||
</div>
|
||||
<div class="detail-row">
|
||||
<span>专业<E4B893><E4B89A>?/span>
|
||||
<strong>${grade.major || '未设<E69CAA><E8AEBE>?}</strong>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="detail-section">
|
||||
<h3><i class="fas fa-chalkboard-teacher"></i> 教师信息</h3>
|
||||
<div class="detail-row">
|
||||
<span>任课教师<E69599><E5B888>?/span>
|
||||
<strong>${grade.teacher_name}</strong>
|
||||
</div>
|
||||
<div class="detail-row">
|
||||
<span>教师邮箱<E982AE><E7AEB1>?/span>
|
||||
<strong>${grade.teacher_email}</strong>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
${grade.remark ? `
|
||||
<div class="remark-section">
|
||||
<h3><i class="fas fa-comment"></i> 备注</h3>
|
||||
<p>${grade.remark}</p>
|
||||
</div>
|
||||
` : ''}
|
||||
|
||||
<div class="grade-actions">
|
||||
<button onclick="window.print()" class="btn btn-secondary">
|
||||
<i class="fas fa-print"></i> 打印成绩<E68890><E7BBA9>?
|
||||
</button>
|
||||
<button onclick="window.history.back()" class="btn btn-primary">
|
||||
<i class="fas fa-arrow-left"></i> 返回
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
`;
|
||||
}
|
||||
|
||||
updateChart(grades) {
|
||||
const ctx = document.getElementById('gradeChart');
|
||||
if (!ctx) return;
|
||||
|
||||
if (typeof Chart === 'undefined') {
|
||||
// 如果没有Chart.js,延迟加<E8BF9F><E58AA0>?
|
||||
this.loadChartLibrary().then(() => this.updateChart(grades));
|
||||
return;
|
||||
}
|
||||
|
||||
const courseNames = grades.map(g => g.course_name);
|
||||
const scores = grades.map(g => g.score);
|
||||
|
||||
// 销毁现有图表实<E8A1A8><E5AE9E>?
|
||||
if (window.gradeChart instanceof Chart) {
|
||||
window.gradeChart.destroy();
|
||||
}
|
||||
|
||||
window.gradeChart = new Chart(ctx, {
|
||||
type: 'bar',
|
||||
data: {
|
||||
labels: courseNames,
|
||||
datasets: [{
|
||||
label: '分数',
|
||||
data: scores,
|
||||
backgroundColor: scores.map(score => {
|
||||
if (score >= 90) return 'rgba(75, 192, 192, 0.7)';
|
||||
if (score >= 80) return 'rgba(54, 162, 235, 0.7)';
|
||||
if (score >= 60) return 'rgba(255, 206, 86, 0.7)';
|
||||
return 'rgba(255, 99, 132, 0.7)';
|
||||
}),
|
||||
borderColor: scores.map(score => {
|
||||
if (score >= 90) return 'rgb(75, 192, 192)';
|
||||
if (score >= 80) return 'rgb(54, 162, 235)';
|
||||
if (score >= 60) return 'rgb(255, 206, 86)';
|
||||
return 'rgb(255, 99, 132)';
|
||||
}),
|
||||
borderWidth: 1
|
||||
}]
|
||||
},
|
||||
options: {
|
||||
responsive: true,
|
||||
plugins: {
|
||||
title: {
|
||||
display: true,
|
||||
text: '各科成绩分布'
|
||||
}
|
||||
},
|
||||
scales: {
|
||||
y: {
|
||||
beginAtZero: true,
|
||||
max: 100
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
async loadChartLibrary() {
|
||||
return new Promise((resolve, reject) => {
|
||||
if (typeof Chart !== 'undefined') {
|
||||
resolve();
|
||||
return;
|
||||
}
|
||||
|
||||
const script = document.createElement('script');
|
||||
script.src = 'https://cdn.jsdelivr.net/npm/chart.js';
|
||||
script.onload = resolve;
|
||||
script.onerror = reject;
|
||||
document.head.appendChild(script);
|
||||
});
|
||||
}
|
||||
|
||||
showNotification(message, type = 'info') {
|
||||
// 使用AuthManager的通知系统或自己实<E5B7B1><E5AE9E>?
|
||||
if (window.authManager && window.authManager.showNotification) {
|
||||
window.authManager.showNotification(message, type);
|
||||
} else {
|
||||
alert(message);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 初始化学生管理器
|
||||
document.addEventListener('DOMContentLoaded', () => {
|
||||
if (window.location.pathname.includes('/student/')) {
|
||||
window.studentManager = new StudentManager();
|
||||
}
|
||||
});
|
||||
406
frontend/public/js/teacher.js
Normal file
406
frontend/public/js/teacher.js
Normal file
@@ -0,0 +1,406 @@
|
||||
class TeacherDashboard {
|
||||
constructor() {
|
||||
// 动态设置API基础URL,支持file:///协议和localhost:3000访问
|
||||
this.apiBase = window.location.protocol === 'file:' ? 'http://localhost:3000/api' : '/api';
|
||||
this.currentUser = null;
|
||||
this.courses = [];
|
||||
this.grades = [];
|
||||
this.init();
|
||||
}
|
||||
|
||||
async init() {
|
||||
// 检查登录状<E5BD95><E78AB6>? if (!await this.checkAuth()) {
|
||||
window.location.href = '/login';
|
||||
return;
|
||||
}
|
||||
|
||||
// 加载用户信息
|
||||
await this.loadUserInfo();
|
||||
|
||||
// 加载课程数据
|
||||
await this.loadCourses();
|
||||
|
||||
// 加载成绩数据
|
||||
await this.loadGrades();
|
||||
|
||||
// 绑定事件
|
||||
this.bindEvents();
|
||||
|
||||
// 更新界面
|
||||
this.updateUI();
|
||||
}
|
||||
|
||||
async checkAuth() {
|
||||
try {
|
||||
const response = await fetch(`${this.apiBase}/auth/check`, {
|
||||
credentials: 'include'
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const data = await response.json();
|
||||
return data.success && data.user.role === 'teacher';
|
||||
} catch (error) {
|
||||
console.error('认证检查失<E69FA5><E5A4B1>?', error);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
async loadUserInfo() {
|
||||
try {
|
||||
const response = await fetch(`${this.apiBase}/auth/me`, {
|
||||
credentials: 'include'
|
||||
});
|
||||
|
||||
if (response.ok) {
|
||||
const data = await response.json();
|
||||
if (data.success) {
|
||||
this.currentUser = data.user;
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('加载用户信息失败:', error);
|
||||
}
|
||||
}
|
||||
|
||||
async loadCourses() {
|
||||
try {
|
||||
const response = await fetch(`${this.apiBase}/teacher/courses`, {
|
||||
credentials: 'include'
|
||||
});
|
||||
|
||||
if (response.ok) {
|
||||
const data = await response.json();
|
||||
if (data.success) {
|
||||
this.courses = data.courses;
|
||||
this.populateCourseSelectors();
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('加载课程失败:', error);
|
||||
this.showNotification('加载课程失败', 'error');
|
||||
}
|
||||
}
|
||||
|
||||
async loadGrades(filters = {}) {
|
||||
try {
|
||||
const queryParams = new URLSearchParams(filters).toString();
|
||||
const url = `${this.apiBase}/teacher/grades${queryParams ? '?' + queryParams : ''}`;
|
||||
|
||||
const response = await fetch(url, {
|
||||
credentials: 'include'
|
||||
});
|
||||
|
||||
if (response.ok) {
|
||||
const data = await response.json();
|
||||
if (data.success) {
|
||||
this.grades = data.grades;
|
||||
this.renderGradesTable();
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('加载成绩失败:', error);
|
||||
this.showNotification('加载成绩失败', 'error');
|
||||
}
|
||||
}
|
||||
|
||||
populateCourseSelectors() {
|
||||
// 填充课程选择<E98089><E68BA9>? const courseSelectors = document.querySelectorAll('.course-selector');
|
||||
courseSelectors.forEach(select => {
|
||||
select.innerHTML = '<option value="">请选择课程</option>';
|
||||
this.courses.forEach(course => {
|
||||
const option = document.createElement('option');
|
||||
option.value = course.id;
|
||||
option.textContent = `${course.course_code} - ${course.course_name}`;
|
||||
select.appendChild(option);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
renderGradesTable() {
|
||||
const tableBody = document.getElementById('gradesTableBody');
|
||||
if (!tableBody) return;
|
||||
|
||||
if (this.grades.length === 0) {
|
||||
tableBody.innerHTML = `
|
||||
<tr>
|
||||
<td colspan="9" class="text-center">
|
||||
<div class="no-data">
|
||||
<i class="fas fa-info-circle"></i>
|
||||
<p>暂无成绩数据</p>
|
||||
</div>
|
||||
</td>
|
||||
</tr>
|
||||
`;
|
||||
return;
|
||||
}
|
||||
|
||||
tableBody.innerHTML = this.grades.map(grade => {
|
||||
const gradeClass = this.getGradeClass(grade.score);
|
||||
return `
|
||||
<tr>
|
||||
<td><input type="checkbox" class="grade-checkbox" data-id="${grade.id}"></td>
|
||||
<td>${grade.student_id}</td>
|
||||
<td>${grade.full_name}</td>
|
||||
<td>${grade.class_name}</td>
|
||||
<td>${grade.course_code}</td>
|
||||
<td>${grade.course_name}</td>
|
||||
<td class="grade-cell ${gradeClass}">
|
||||
<span class="grade-score">${grade.score}</span>
|
||||
<span class="grade-level">${grade.grade_level}</span>
|
||||
</td>
|
||||
<td>${grade.exam_date ? new Date(grade.exam_date).toLocaleDateString() : '未设<E69CAA><E8AEBE>?}</td>
|
||||
<td>
|
||||
<div class="action-buttons">
|
||||
<button class="btn-edit" data-id="${grade.id}">
|
||||
<i class="fas fa-edit"></i> 编辑
|
||||
</button>
|
||||
<button class="btn-delete" data-id="${grade.id}">
|
||||
<i class="fas fa-trash"></i> 删除
|
||||
</button>
|
||||
</div>
|
||||
</td>
|
||||
</tr>
|
||||
`;
|
||||
}).join('');
|
||||
|
||||
// 更新统计信息
|
||||
this.updateStats();
|
||||
}
|
||||
|
||||
getGradeClass(score) {
|
||||
if (score >= 90) return 'grade-excellent';
|
||||
if (score >= 80) return 'grade-good';
|
||||
if (score >= 70) return 'grade-medium';
|
||||
if (score >= 60) return 'grade-pass';
|
||||
return 'grade-fail';
|
||||
}
|
||||
|
||||
updateStats() {
|
||||
if (this.grades.length === 0) return;
|
||||
|
||||
const totalStudents = new Set(this.grades.map(g => g.student_id)).size;
|
||||
const avgScore = this.grades.reduce((sum, g) => sum + g.score, 0) / this.grades.length;
|
||||
const passRate = (this.grades.filter(g => g.score >= 60).length / this.grades.length * 100).toFixed(1);
|
||||
|
||||
document.getElementById('totalStudents').textContent = totalStudents;
|
||||
document.getElementById('avgScore').textContent = avgScore.toFixed(1);
|
||||
document.getElementById('passRate').textContent = `${passRate}%`;
|
||||
}
|
||||
|
||||
bindEvents() {
|
||||
// 搜索按钮
|
||||
document.getElementById('searchBtn')?.addEventListener('click', () => {
|
||||
this.handleSearch();
|
||||
});
|
||||
|
||||
// 重置按钮
|
||||
document.getElementById('resetBtn')?.addEventListener('click', () => {
|
||||
this.resetFilters();
|
||||
});
|
||||
|
||||
// 导出按钮
|
||||
document.getElementById('exportBtn')?.addEventListener('click', () => {
|
||||
this.exportGrades();
|
||||
});
|
||||
|
||||
// 批量删除按钮
|
||||
document.getElementById('batchDeleteBtn')?.addEventListener('click', () => {
|
||||
this.batchDeleteGrades();
|
||||
});
|
||||
|
||||
// 表格操作按钮事件委托
|
||||
document.addEventListener('click', (e) => {
|
||||
if (e.target.closest('.btn-edit')) {
|
||||
const gradeId = e.target.closest('.btn-edit').dataset.id;
|
||||
this.editGrade(gradeId);
|
||||
}
|
||||
|
||||
if (e.target.closest('.btn-delete')) {
|
||||
const gradeId = e.target.closest('.btn-delete').dataset.id;
|
||||
this.deleteGrade(gradeId);
|
||||
}
|
||||
});
|
||||
|
||||
// 退出登<E587BA><E799BB>? document.getElementById('logoutBtn')?.addEventListener('click', () => {
|
||||
this.handleLogout();
|
||||
});
|
||||
}
|
||||
|
||||
handleSearch() {
|
||||
const className = document.getElementById('classFilter')?.value || '';
|
||||
const courseId = document.getElementById('courseFilter')?.value || '';
|
||||
|
||||
this.loadGrades({ class_name: className, course_id: courseId });
|
||||
}
|
||||
|
||||
resetFilters() {
|
||||
document.getElementById('classFilter').value = '';
|
||||
document.getElementById('courseFilter').value = '';
|
||||
this.loadGrades();
|
||||
}
|
||||
|
||||
async exportGrades() {
|
||||
try {
|
||||
const response = await fetch(`${this.apiBase}/teacher/grades/export`, {
|
||||
credentials: 'include'
|
||||
});
|
||||
|
||||
if (response.ok) {
|
||||
const blob = await response.blob();
|
||||
const url = window.URL.createObjectURL(blob);
|
||||
const a = document.createElement('a');
|
||||
a.href = url;
|
||||
a.download = `成绩报表_${new Date().toISOString().split('T')[0]}.xlsx`;
|
||||
document.body.appendChild(a);
|
||||
a.click();
|
||||
document.body.removeChild(a);
|
||||
window.URL.revokeObjectURL(url);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('导出失败:', error);
|
||||
this.showNotification('导出失败', 'error');
|
||||
}
|
||||
}
|
||||
|
||||
async batchDeleteGrades() {
|
||||
const checkboxes = document.querySelectorAll('.grade-checkbox:checked');
|
||||
if (checkboxes.length === 0) {
|
||||
this.showNotification('请选择要删除的成绩', 'warning');
|
||||
return;
|
||||
}
|
||||
|
||||
if (!confirm(`确定要删除选中<E98089><E4B8AD>?${checkboxes.length} 条成绩记录吗?`)) {
|
||||
return;
|
||||
}
|
||||
|
||||
const gradeIds = Array.from(checkboxes).map(cb => cb.dataset.id);
|
||||
|
||||
try {
|
||||
const response = await fetch(`${this.apiBase}/teacher/grades/batch`, {
|
||||
method: 'DELETE',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
credentials: 'include',
|
||||
body: JSON.stringify({ gradeIds })
|
||||
});
|
||||
|
||||
const data = await response.json();
|
||||
if (data.success) {
|
||||
this.showNotification(`成功删除 ${gradeIds.length} 条成绩记录`, 'success');
|
||||
await this.loadGrades();
|
||||
} else {
|
||||
this.showNotification(data.message || '删除失败', 'error');
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('批量删除失败:', error);
|
||||
this.showNotification('批量删除失败', 'error');
|
||||
}
|
||||
}
|
||||
|
||||
async editGrade(gradeId) {
|
||||
const grade = this.grades.find(g => g.id == gradeId);
|
||||
if (!grade) return;
|
||||
|
||||
// 这里可以打开编辑模态框
|
||||
// 暂时使用简单提示框
|
||||
const newScore = prompt('请输入新的分<EFBFBD><EFBFBD>?', grade.score);
|
||||
if (newScore === null) return;
|
||||
|
||||
const numericScore = parseFloat(newScore);
|
||||
if (isNaN(numericScore) || numericScore < 0 || numericScore > 100) {
|
||||
this.showNotification('请输<EFBFBD><EFBFBD>?-100之间的有效分<EFBFBD><EFBFBD>?, 'error');
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const response = await fetch(`${this.apiBase}/teacher/grades/${gradeId}`, {
|
||||
method: 'PUT',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
credentials: 'include',
|
||||
body: JSON.stringify({
|
||||
score: numericScore,
|
||||
examDate: grade.exam_date,
|
||||
remark: grade.remark
|
||||
})
|
||||
});
|
||||
|
||||
const data = await response.json();
|
||||
if (data.success) {
|
||||
this.showNotification('成绩更新成功', 'success');
|
||||
await this.loadGrades();
|
||||
} else {
|
||||
this.showNotification(data.message || '更新失败', 'error');
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('更新成绩失败:', error);
|
||||
this.showNotification('更新成绩失败', 'error');
|
||||
}
|
||||
}
|
||||
|
||||
async deleteGrade(gradeId) {
|
||||
if (!confirm('确定要删除这条成绩记录吗<E5BD95><E59097>?)) {
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
const response = await fetch(`${this.apiBase}/teacher/grades/${gradeId}`, {
|
||||
method: 'DELETE',
|
||||
credentials: 'include'
|
||||
});
|
||||
|
||||
const data = await response.json();
|
||||
if (data.success) {
|
||||
this.showNotification('成绩删除成功', 'success');
|
||||
await this.loadGrades();
|
||||
} else {
|
||||
this.showNotification(data.message || '删除失败', 'error');
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('删除成绩失败:', error);
|
||||
this.showNotification('删除成绩失败', 'error');
|
||||
}
|
||||
}
|
||||
|
||||
async handleLogout() {
|
||||
try {
|
||||
const response = await fetch(`${this.apiBase}/auth/logout`, {
|
||||
method: 'POST',
|
||||
credentials: 'include'
|
||||
});
|
||||
|
||||
if (response.ok) {
|
||||
window.location.href = '/login';
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('退出登录失<E5BD95><E5A4B1>?', error);
|
||||
}
|
||||
}
|
||||
|
||||
updateUI() {
|
||||
// 更新用户信息
|
||||
if (this.currentUser) {
|
||||
const userInfoElements = document.querySelectorAll('.user-info');
|
||||
userInfoElements.forEach(el => {
|
||||
el.textContent = `${this.currentUser.full_name} (${this.currentUser.role})`;
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
showNotification(message, type = 'info') {
|
||||
// 使用AuthManager的通知系统或简单alert
|
||||
if (typeof AuthManager !== 'undefined' && AuthManager.showNotification) {
|
||||
AuthManager.showNotification(message, type);
|
||||
} else {
|
||||
alert(`${type}: ${message}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 页面加载完成后初始化
|
||||
document.addEventListener('DOMContentLoaded', () => {
|
||||
if (window.location.pathname.includes('/teacher/')) {
|
||||
new TeacherDashboard();
|
||||
}
|
||||
});
|
||||
Reference in New Issue
Block a user