refactor(frontend): 重构前端目录结构并优化认证流程

将前端文件从html目录迁移到views目录,按功能模块组织
重构认证中间件和路由处理,简化页面权限控制
更新静态资源引用路径,统一使用/public前缀
添加学生仪表板页面,优化移动端显示
移除旧版html和js文件,更新样式和脚本
This commit is contained in:
祀梦
2025-12-21 22:07:23 +08:00
parent 38b200f9b3
commit bcf2c71fad
20 changed files with 2009 additions and 2009 deletions
+215
View File
@@ -0,0 +1,215 @@
/* 首页通用交互样式 */
/* 滚动时导航栏样式 */
.navbar-scrolled {
background-color: rgba(255, 255, 255, 0.95) !important;
box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
backdrop-filter: blur(10px);
}
.navbar-scrolled .navbar-brand,
.navbar-scrolled .nav-link {
color: #333 !important;
}
.navbar-scrolled .navbar-toggler-icon {
background-image: url("data:image/svg+xml,%3csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 30 30'%3e%3cpath stroke='rgba(0, 0, 0, 0.7)' stroke-linecap='round' stroke-miterlimit='10' stroke-width='2' d='M4 7h22M4 15h22M4 23h22'/%3e%3c/svg%3e") !important;
}
/* 滚动动画效果 */
.feature-card, .hero-content {
opacity: 0;
transform: translateY(20px);
transition: opacity 0.6s ease, transform 0.6s ease;
}
.feature-card.animate-in,
.hero-content.animate-in {
opacity: 1;
transform: translateY(0);
}
/* 返回顶部按钮 */
#backToTop {
position: fixed;
bottom: 30px;
right: 30px;
width: 50px;
height: 50px;
background-color: #4e73df;
color: white;
border: none;
border-radius: 50%;
cursor: pointer;
opacity: 0;
visibility: hidden;
transition: all 0.3s ease;
z-index: 1000;
display: flex;
align-items: center;
justify-content: center;
font-size: 1.2rem;
box-shadow: 0 4px 15px rgba(78, 115, 223, 0.3);
}
#backToTop:hover {
background-color: #2e59d9;
transform: translateY(-3px);
box-shadow: 0 6px 20px rgba(78, 115, 223, 0.4);
}
#backToTop.show {
opacity: 1;
visibility: visible;
}
/* 通知样式 */
.notification {
position: fixed;
top: 20px;
right: 20px;
padding: 15px 20px;
border-radius: 8px;
background-color: white;
box-shadow: 0 4px 15px rgba(0, 0, 0, 0.1);
z-index: 9999;
opacity: 0;
transform: translateX(100%);
transition: opacity 0.3s ease, transform 0.3s ease;
max-width: 350px;
display: flex;
align-items: center;
}
.notification.show {
opacity: 1;
transform: translateX(0);
}
.notification-content {
display: flex;
align-items: center;
gap: 10px;
}
.notification i {
font-size: 1.2rem;
}
.notification-success {
border-left: 4px solid #1cc88a;
}
.notification-success i {
color: #1cc88a;
}
.notification-error {
border-left: 4px solid #e74a3b;
}
.notification-error i {
color: #e74a3b;
}
.notification-info {
border-left: 4px solid #36b9cc;
}
.notification-info i {
color: #36b9cc;
}
/* 移动端菜单优化 */
@media (max-width: 991.98px) {
.navbar-collapse {
background-color: white;
padding: 20px;
border-radius: 8px;
box-shadow: 0 4px 15px rgba(0, 0, 0, 0.1);
margin-top: 10px;
}
.navbar-nav .nav-link {
padding: 10px 15px;
border-radius: 4px;
margin-bottom: 5px;
}
.navbar-nav .nav-link:hover {
background-color: #f8f9fc;
}
}
/* 平滑滚动优化 */
html {
scroll-behavior: smooth;
}
/* 当前页面高亮 */
.nav-link.active {
color: #4e73df !important;
font-weight: 600;
}
.nav-link.active::after {
content: '';
position: absolute;
bottom: -2px;
left: 0;
width: 100%;
height: 2px;
background-color: #4e73df;
border-radius: 2px;
}
/* 按钮悬停效果增强 */
.btn {
transition: all 0.3s ease;
}
.btn:hover {
transform: translateY(-2px);
box-shadow: 0 4px 15px rgba(0, 0, 0, 0.1);
}
/* 卡片悬停效果 */
.feature-card {
transition: all 0.3s ease;
}
.feature-card:hover {
transform: translateY(-5px);
box-shadow: 0 8px 25px rgba(0, 0, 0, 0.1);
}
/* 加载动画 */
.loading-spinner {
display: inline-block;
width: 20px;
height: 20px;
border: 3px solid rgba(255, 255, 255, 0.3);
border-radius: 50%;
border-top-color: white;
animation: spin 1s ease-in-out infinite;
}
@keyframes spin {
to { transform: rotate(360deg); }
}
/* 响应式调整 */
@media (max-width: 768px) {
#backToTop {
bottom: 20px;
right: 20px;
width: 45px;
height: 45px;
}
.notification {
left: 20px;
right: 20px;
max-width: none;
}
}
+47
View File
@@ -0,0 +1,47 @@
/* 通知消息样式 */
.notification {
position: fixed;
top: 20px;
right: 20px;
padding: 15px 25px;
background: white;
border-radius: 8px;
box-shadow: 0 4px 12px rgba(0,0,0,0.15);
display: flex;
align-items: center;
z-index: 1000;
transform: translateX(120%);
transition: transform 0.3s ease;
border-left: 4px solid #4e73df;
max-width: 350px;
}
.notification.show {
transform: translateX(0);
}
.notification.success {
border-left-color: #2ecc71;
}
.notification.error {
border-left-color: #e74c3c;
}
.notification i {
margin-right: 10px;
font-size: 1.2em;
}
.notification.success i {
color: #2ecc71;
}
.notification.error i {
color: #e74c3c;
}
.notification-content {
font-size: 14px;
color: #333;
}
File diff suppressed because it is too large Load Diff
+583
View 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() {
// 检查登录状� if (!await this.checkAuth()) {
window.location.href = '/login';
return;
}
// 加载用户信æ¯
await this.loadUserInfo();
// 加载统计数æ®
await this.loadStats();
// 加载用户数æ®
await this.loadUsers();
// 绑定事件
this.bindEvents();
// 更新界é¢
this.updateUI();
// åˆå§‹åŒ–图è¡? 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('è®¤è¯æ£€æŸ¥å¤±è´?', 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);
}
});
// 退出登� document.getElementById('logoutBtn')?.addEventListener('click', () => {
this.handleLogout();
});
// 刷新按钮
document.getElementById('refreshBtn')?.addEventListener('click', () => {
this.refreshData();
});
}
async loadPage(page) {
// 这里å¯ä»¥å®žçް页é¢åˆ‡æ¢é€»è¾‘
// 暂时使用简å•è·³è½? switch (page) {
case 'users':
window.location.href = '/admin/user_management';
break;
case 'students':
window.location.href = '/admin/student_management';
break;
case 'teachers':
// å¯ä»¥è·³è½¬åˆ°æ•™å¸ˆç®¡ç†é¡µé? break;
case 'grades':
window.location.href = '/teacher/grade_management';
break;
case 'settings':
// å¯ä»¥è·³è½¬åˆ°ç³»ç»Ÿè®¾ç½®é¡µé? 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(œç´¢åŠŸèƒ½å¾…å®žçŽ?, '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('请è¾å¥å§å?'),
role: prompt('请è¾å¥è§è?(admin/teacher/student):'),
email: prompt('请è¾å¥é®ç®?'),
class_name: prompt('请è¾å¥ç­çº?(å­¦çŸ/æå¸ˆå¯é?:')
};
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(`确定è¦åˆ é™¤é€‰ä¸­çš?${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('请è¾å¥æ°çšå§å?', user.full_name);
if (newName === null) return;
const newRole = prompt('请è¾å¥æ°çšè§è?', 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('确定è¦åˆ é¤è¿ä¸ªç¨æˆ·åï¼?)) {
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('退出登录失�', error);
}
}
async refreshData() {
await this.loadStats();
await this.loadUsers();
this.showNotification('æ•°æ®å·²åˆ·æ–?, '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� await this.loadChartLibrary();
// åˆå§‹åŒ–用户分布饼å›? 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">&times;</button>
`;
// 添加到页é? 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: ['学生', '教师', '管ç†å‘?],
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
View 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
View File
@@ -0,0 +1,213 @@
// 首页通用JavaScript功能
// 主è¦å¤„ç†å¯¼èˆªæ äº¤äº’ã€é¡µé¢æ»šåŠ¨æ•ˆæžœç­‰é€šç”¨åŠŸèƒ½
class MainPage {
constructor() {
this.init();
}
init() {
// åˆå§‹åŒ–所有功èƒ? 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');
}
});
// åˆå§‹åŒ–当å‰é¡µé¢é«˜äº? 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');
}
});
}
// åˆå§‹åŒ–滚动效æž? initScrollEffects() {
// 滚动时显ç¤?éšè—元素
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);
});
}
// åˆå§‹åŒ–平滑滚åŠ? 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'
});
}
});
});
}
// åˆå§‹åŒ–返回顶部按é’? initBackToTop() {
const backToTopBtn = document.createElement('button');
backToTopBtn.id = 'backToTop';
backToTopBtn.innerHTML = '<i class="fas fa-chevron-up"></i>';
backToTopBtn.title = '返回顶部';
document.body.appendChild(backToTopBtn);
// 滚动时显ç¤?éšè—按钮
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');
}
});
});
}
// åˆå§‹åŒ–è®¤è¯æŒ‰é’®çжæ€? initAuthButtons() {
// 检查用户是å¦å·²ç™»å½•
this.checkLoginStatus().then(user => {
const loginBtn = document.getElementById('loginBtn');
const registerBtn = document.getElementById('registerBtn');
const heroLoginBtn = document.getElementById('heroLoginBtn');
if (user) {
// ç”¨æˆ·å·²ç™»å½•ï¼Œæ˜¾ç¤ºä»ªè¡¨æ¿æŒ‰é’? // æ ¹æ®ç”¨æˆ·è§’色设置正确的仪表æ¿è·¯å¾„
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 = '进入仪表æ?;
loginBtn.href = dashboardUrl;
}
if (heroLoginBtn) {
heroLoginBtn.textContent = 'è¿å¥ä»ªè¡¨æ?;
heroLoginBtn.href = dashboardUrl;
}
if (registerBtn) {
registerBtn.style.display = 'none';
}
}
});
}
// 检查登录状� 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('用户未登�);
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>
`;
// 添加到页é? 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
View File
@@ -0,0 +1,438 @@
class StudentManager {
constructor() {
// 挽蝵唧PIURL嚗峕𣈲ile:///讛悅𨧣ocalhost: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) {
// 芰蒈敶𤏪憿?
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">餃郎?/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">撟喳?/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) {
// 芰蒈敶𤏪憿?
this.showNotification('霂瑕', 'error');
setTimeout(() => {
window.location.href = '/login';
}, 1500);
return;
}
const data = await response.json();
if (data.success) {
const profile = data.profile;
// 湔鰵摮衣隞芾”輸▲其縑?
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 || '芾挽蝵?;
}
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 || '芾挽蝵?}</p>
</div>
</div>
<div class="detail-item">
<i class="fas fa-calendar-alt"></i>
<div>
<h4>亙郎撟港遢</h4>
<p>${profile.enrollment_year || '芾挽蝵?}</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 = '銝滚?;
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} ?
<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>摮血嚗?/span>
<strong>${grade.credit}</strong>
</div>
<div class="detail-row">
<span>摮行嚗?/span>
<strong>${grade.semester}</strong>
</div>
<div class="detail-row">
<span>嚗?/span>
<strong>${new Date(grade.exam_date).toLocaleDateString()}</strong>
</div>
<div class="detail-row">
<span>蝑厩漣嚗?/span>
<strong class="grade-level-${grade.grade_level}">${grade.grade_level || '-'}</strong>
</div>
<div class="detail-row">
<span>蝏拍嚗?/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>憪枏嚗?/span>
<strong>${grade.full_name}</strong>
</div>
<div class="detail-row">
<span>摮血噡嚗?/span>
<strong>${grade.student_number}</strong>
</div>
<div class="detail-row">
<span>剔漣嚗?/span>
<strong>${grade.class_name}</strong>
</div>
<div class="detail-row">
<span>銝㮖嚗?/span>
<strong>${grade.major || '芾挽蝵?}</strong>
</div>
</div>
<div class="detail-section">
<h3><i class="fas fa-chalkboard-teacher"></i> 靽⊥</h3>
<div class="detail-row">
<span>隞餉紋嚗?/span>
<strong>${grade.teacher_name}</strong>
</div>
<div class="detail-row">
<span>桃拳嚗?/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> 枏㫲鞟貍?
</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嚗辣餈笔頧?
this.loadChartLibrary().then(() => this.updateChart(grades));
return;
}
const courseNames = grades.map(g => g.course_name);
const scores = grades.map(g => g.score);
// 匧㦛銵典靘?
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𡁶䰻蝟餌𤥁䌊撌勗?
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
View 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() {
// 检查登录状� 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('è®¤è¯æ£€æŸ¥å¤±è´?', 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() {
// 填充课程选择� 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() : '未设�}</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);
}
});
// 退出登� 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(`确定è¦åˆ é™¤é€‰ä¸­çš?${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('请è¾å¥æ°çšåˆæ?', grade.score);
if (newScore === null) return;
const numericScore = parseFloat(newScore);
if (isNaN(numericScore) || numericScore < 0 || numericScore > 100) {
this.showNotification('请è¾å?-100ä¹é´çšæœæˆåˆæ?, '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('确定è¦åˆ é™¤è¿™æ¡æˆç»©è®°å½•å—ï¼?)) {
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('退出登录失�', 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();
}
});