feat: 添加学生个人中心页面和数据库备份功能
refactor(auth): 重构认证模块适配Bootstrap 5样式 feat(controller): 在登录响应中返回用户对象 feat(server): 添加学生个人中心路由 refactor(models): 重构学生和成绩模型结构 style: 更新登录和注册页面UI设计 chore: 添加数据库备份脚本和空备份文件
This commit is contained in:
@@ -1,6 +1,7 @@
|
||||
/**
|
||||
* 认证模块管理器
|
||||
* 处理登录、注册、注销及权限检查
|
||||
* 适配 Bootstrap 5 样式
|
||||
*/
|
||||
class AuthManager {
|
||||
constructor() {
|
||||
@@ -15,21 +16,14 @@ class AuthManager {
|
||||
}
|
||||
|
||||
/**
|
||||
* 创建通知容器
|
||||
* 创建通知容器 (适配 Bootstrap Toast)
|
||||
*/
|
||||
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;
|
||||
`;
|
||||
container.className = 'toast-container position-fixed top-0 end-0 p-3';
|
||||
container.style.zIndex = '9999';
|
||||
document.body.appendChild(container);
|
||||
}
|
||||
}
|
||||
@@ -38,7 +32,6 @@ class AuthManager {
|
||||
* 检查用户认证状态
|
||||
*/
|
||||
async checkAuthStatus() {
|
||||
// 如果当前是公共页面,可以选择不检查,或者检查后更新UI
|
||||
const currentPath = window.location.pathname;
|
||||
const isAuthPage = currentPath.includes('/login') || currentPath.includes('/register');
|
||||
|
||||
@@ -46,20 +39,11 @@ class AuthManager {
|
||||
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 (data.success && data.data && data.data.user) {
|
||||
const redirectUrl = this.getDashboardUrl(data.data.user.role);
|
||||
if (isAuthPage || currentPath === '/') {
|
||||
window.location.href = redirectUrl;
|
||||
}
|
||||
} else {
|
||||
// 用户未登录,如果在受保护页面,跳转到登录页
|
||||
// 注意:后端通常已经处理了重定向,这里是前端的额外保障
|
||||
if (!isAuthPage && currentPath !== '/') {
|
||||
// 可以在这里添加逻辑,但通常交给后端控制
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Auth check failed:', error);
|
||||
@@ -94,7 +78,7 @@ class AuthManager {
|
||||
}
|
||||
}
|
||||
|
||||
// 注销按钮 (可能有多个,例如在导航栏)
|
||||
// 注销按钮
|
||||
document.querySelectorAll('.btn-logout, #logoutBtn').forEach(btn => {
|
||||
btn.addEventListener('click', (e) => this.handleLogout(e));
|
||||
});
|
||||
@@ -107,12 +91,12 @@ class AuthManager {
|
||||
|
||||
if (classField && classInput) {
|
||||
if (role === 'student' || role === 'teacher') {
|
||||
classField.style.display = 'block';
|
||||
classField.style.display = 'flex'; // 配合 Bootstrap input-group
|
||||
classInput.required = true;
|
||||
} else {
|
||||
classField.style.display = 'none';
|
||||
classInput.required = false;
|
||||
classInput.value = ''; // 清空值
|
||||
classInput.value = '';
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -120,9 +104,9 @@ class AuthManager {
|
||||
async handleLogin(e) {
|
||||
e.preventDefault();
|
||||
const form = e.target;
|
||||
const submitBtn = form.querySelector('button[type="submit"]');
|
||||
const submitBtn = document.getElementById('loginBtn') || form.querySelector('button[type="submit"]');
|
||||
|
||||
if (this.setLoading(submitBtn, true, '登录中...')) {
|
||||
if (this.setLoading(submitBtn, true)) {
|
||||
try {
|
||||
const formData = new FormData(form);
|
||||
const data = Object.fromEntries(formData.entries());
|
||||
@@ -137,16 +121,27 @@ class AuthManager {
|
||||
|
||||
if (result.success) {
|
||||
this.showNotification('登录成功,正在跳转...', 'success');
|
||||
setTimeout(() => {
|
||||
window.location.href = this.getDashboardUrl(result.user.role);
|
||||
}, 1000);
|
||||
|
||||
// 获取用户信息,优先从 result.data.user 获取,兼容旧格式 result.data 或 result.user
|
||||
const user = (result.data && result.data.user) || result.data || result.user;
|
||||
const role = user ? user.role : null;
|
||||
|
||||
if (role) {
|
||||
setTimeout(() => {
|
||||
window.location.href = this.getDashboardUrl(role);
|
||||
}, 1000);
|
||||
} else {
|
||||
console.error('Login success but role not found:', result);
|
||||
this.showNotification('登录状态异常,请重试', 'error');
|
||||
this.setLoading(submitBtn, false);
|
||||
}
|
||||
} else {
|
||||
this.showNotification(result.message || '登录失败', 'error');
|
||||
this.setLoading(submitBtn, false);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Login error:', error);
|
||||
this.showNotification('网络错误,请稍后重试', 'error');
|
||||
this.showNotification('服务器连接失败,请稍后重试', 'error');
|
||||
this.setLoading(submitBtn, false);
|
||||
}
|
||||
}
|
||||
@@ -155,19 +150,17 @@ class AuthManager {
|
||||
async handleRegister(e) {
|
||||
e.preventDefault();
|
||||
const form = e.target;
|
||||
const submitBtn = form.querySelector('button[type="submit"]');
|
||||
const submitBtn = document.getElementById('registerBtn') || 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, '注册中...')) {
|
||||
if (this.setLoading(submitBtn, true)) {
|
||||
try {
|
||||
const response = await fetch(`${this.apiBase}/auth/register`, {
|
||||
method: 'POST',
|
||||
@@ -188,7 +181,7 @@ class AuthManager {
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Register error:', error);
|
||||
this.showNotification('网络错误,请稍后重试', 'error');
|
||||
this.showNotification('服务器连接失败,请稍后重试', 'error');
|
||||
this.setLoading(submitBtn, false);
|
||||
}
|
||||
}
|
||||
@@ -196,24 +189,17 @@ class AuthManager {
|
||||
|
||||
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);
|
||||
window.location.href = '/login';
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Logout error:', error);
|
||||
// 即使出错也强制跳转到登录页
|
||||
window.location.href = '/login';
|
||||
}
|
||||
}
|
||||
@@ -221,67 +207,68 @@ class AuthManager {
|
||||
|
||||
/**
|
||||
* 设置按钮加载状态
|
||||
* @param {HTMLElement} btn 按钮元素
|
||||
* @param {boolean} isLoading 是否正在加载
|
||||
* @param {string} text 加载时的文本
|
||||
* @returns {boolean} true表示状态设置成功
|
||||
*/
|
||||
setLoading(btn, isLoading, text = '') {
|
||||
setLoading(btn, isLoading) {
|
||||
if (!btn) return false;
|
||||
|
||||
const spinner = btn.querySelector('.spinner-border');
|
||||
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}`;
|
||||
if (btn.disabled) return false;
|
||||
btn.disabled = true;
|
||||
if (spinner) spinner.classList.remove('d-none');
|
||||
} else {
|
||||
btn.innerHTML = btn.dataset.originalText || btn.innerHTML;
|
||||
delete btn.dataset.loading;
|
||||
btn.disabled = false;
|
||||
if (spinner) spinner.classList.add('d-none');
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* 显示通知
|
||||
* @param {string} message 消息内容
|
||||
* @param {string} type 消息类型 'success' | 'error' | 'info'
|
||||
* 显示通知 (Bootstrap 5 Toast)
|
||||
*/
|
||||
showNotification(message, type = 'info') {
|
||||
const container = document.getElementById('notification-container');
|
||||
if (!container) return;
|
||||
|
||||
const notification = document.createElement('div');
|
||||
notification.className = `notification ${type}`;
|
||||
const iconMap = {
|
||||
success: 'fa-check-circle',
|
||||
error: 'fa-exclamation-circle',
|
||||
warning: 'fa-exclamation-triangle',
|
||||
info: 'fa-info-circle'
|
||||
};
|
||||
|
||||
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>
|
||||
const bgMap = {
|
||||
success: 'bg-success',
|
||||
error: 'bg-danger',
|
||||
warning: 'bg-warning',
|
||||
info: 'bg-info'
|
||||
};
|
||||
|
||||
const toastId = 'toast-' + Date.now();
|
||||
const toastHtml = `
|
||||
<div id="${toastId}" class="toast align-items-center text-white ${bgMap[type]} border-0" role="alert" aria-live="assertive" aria-atomic="true">
|
||||
<div class="d-flex">
|
||||
<div class="toast-body">
|
||||
<i class="fas ${iconMap[type]} me-2"></i>
|
||||
${message}
|
||||
</div>
|
||||
<button type="button" class="btn-close btn-close-white me-2 m-auto" data-bs-dismiss="toast" aria-label="Close"></button>
|
||||
</div>
|
||||
</div>
|
||||
`;
|
||||
|
||||
container.insertAdjacentHTML('beforeend', toastHtml);
|
||||
const toastElement = document.getElementById(toastId);
|
||||
const toast = new bootstrap.Toast(toastElement, { delay: 3000 });
|
||||
toast.show();
|
||||
|
||||
container.appendChild(notification);
|
||||
|
||||
// 动画显示
|
||||
requestAnimationFrame(() => {
|
||||
notification.classList.add('show');
|
||||
toastElement.addEventListener('hidden.bs.toast', () => {
|
||||
toastElement.remove();
|
||||
});
|
||||
|
||||
// 自动消失
|
||||
setTimeout(() => {
|
||||
notification.classList.remove('show');
|
||||
notification.addEventListener('transitionend', () => {
|
||||
notification.remove();
|
||||
});
|
||||
}, 3000);
|
||||
}
|
||||
}
|
||||
|
||||
// 初始化
|
||||
// 初始化认证管理器
|
||||
document.addEventListener('DOMContentLoaded', () => {
|
||||
window.authManager = new AuthManager();
|
||||
});
|
||||
@@ -1,438 +1,135 @@
|
||||
/**
|
||||
* 学生端功能管理
|
||||
*/
|
||||
class StudentManager {
|
||||
constructor() {
|
||||
// 动态设置API基础URL,支持file:///协议和localhost:3000访问
|
||||
this.apiBase = window.location.protocol === 'file:' ? 'http://localhost:3000/api' : '/api';
|
||||
this.apiBase = '/api/student';
|
||||
this.init();
|
||||
}
|
||||
|
||||
init() {
|
||||
this.initDashboard();
|
||||
this.initGradeDetails();
|
||||
this.loadProfile();
|
||||
this.updateCurrentTime();
|
||||
setInterval(() => this.updateCurrentTime(), 1000);
|
||||
}
|
||||
|
||||
updateCurrentTime() {
|
||||
const timeElement = document.getElementById('currentTime');
|
||||
if (timeElement) {
|
||||
const now = new Date();
|
||||
const options = {
|
||||
year: 'numeric', month: 'long', day: 'numeric',
|
||||
hour: '2-digit', minute: '2-digit', second: '2-digit'
|
||||
};
|
||||
timeElement.textContent = now.toLocaleString('zh-CN', options);
|
||||
}
|
||||
}
|
||||
|
||||
async initDashboard() {
|
||||
const gradeList = document.getElementById('gradeList');
|
||||
const statisticsElement = document.getElementById('statistics');
|
||||
|
||||
if (!gradeList) return;
|
||||
// 检查是否在仪表板页面
|
||||
if (!document.getElementById('gradesTableBody')) return;
|
||||
|
||||
try {
|
||||
const response = await fetch(`${this.apiBase}/student/grades`, {
|
||||
credentials: 'include'
|
||||
});
|
||||
const response = await fetch(`${this.apiBase}/grades`);
|
||||
const result = await response.json();
|
||||
|
||||
if (response.status === 401) {
|
||||
// 未登录,重定向到登录<E799BB><E5BD95>?
|
||||
this.showNotification('请先登录', 'error');
|
||||
setTimeout(() => {
|
||||
window.location.href = '/login';
|
||||
}, 1500);
|
||||
if (result.success) {
|
||||
this.renderDashboard(result.data);
|
||||
} else {
|
||||
if (window.authManager) {
|
||||
window.authManager.showNotification(result.message || '获取数据失败', 'error');
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Fetch dashboard data failed:', error);
|
||||
}
|
||||
}
|
||||
|
||||
renderDashboard(data) {
|
||||
const { grades, statistics } = data;
|
||||
|
||||
// 渲染统计数据
|
||||
if (statistics) {
|
||||
this.updateElement('gpaValue', statistics.gpa);
|
||||
this.updateElement('courseCount', statistics.totalCourses);
|
||||
this.updateElement('creditTotal', statistics.totalCredits);
|
||||
// 班级排名如果后端没提供,可以显示为 '-' 或固定值
|
||||
this.updateElement('classRank', statistics.classRank || '-');
|
||||
}
|
||||
|
||||
// 渲染成绩表格
|
||||
const tbody = document.getElementById('gradesTableBody');
|
||||
if (tbody) {
|
||||
if (!grades || grades.length === 0) {
|
||||
tbody.innerHTML = '<tr><td colspan="8" class="text-center py-4 text-muted">暂无成绩记录</td></tr>';
|
||||
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');
|
||||
tbody.innerHTML = grades.map(grade => `
|
||||
<tr>
|
||||
<td>${grade.course_name}</td>
|
||||
<td>${grade.course_code || '-'}</td>
|
||||
<td>${grade.credit}</td>
|
||||
<td>${grade.score}</td>
|
||||
<td>${grade.grade_level || '-'}</td>
|
||||
<td>${grade.grade_point || '-'}</td>
|
||||
<td>
|
||||
<span class="badge ${this.getScoreBadgeClass(grade.score)}">
|
||||
${this.getScoreText(grade.score)}
|
||||
</span>
|
||||
</td>
|
||||
<td>
|
||||
<button class="btn btn-sm btn-outline-primary" onclick="studentManager.viewDetails(${grade.id})">
|
||||
<i class="fas fa-eye"></i> 详情
|
||||
</button>
|
||||
</td>
|
||||
</tr>
|
||||
`).join('');
|
||||
}
|
||||
}
|
||||
|
||||
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);
|
||||
});
|
||||
updateElement(id, value) {
|
||||
const el = document.getElementById(id);
|
||||
if (el) el.textContent = value;
|
||||
}
|
||||
|
||||
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>
|
||||
`;
|
||||
getScoreBadgeClass(score) {
|
||||
const s = parseFloat(score);
|
||||
if (s >= 90) return 'bg-success';
|
||||
if (s >= 80) return 'bg-info';
|
||||
if (s >= 60) return 'bg-warning';
|
||||
return 'bg-danger';
|
||||
}
|
||||
|
||||
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');
|
||||
}
|
||||
getScoreText(score) {
|
||||
const s = parseFloat(score);
|
||||
if (s >= 60) return '及格';
|
||||
return '不及格';
|
||||
}
|
||||
|
||||
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);
|
||||
}
|
||||
viewDetails(id) {
|
||||
// 实现查看详情逻辑,或者跳转到详情页
|
||||
console.log('View details for score:', id);
|
||||
}
|
||||
}
|
||||
|
||||
// 初始化学生管理器
|
||||
// 初始化
|
||||
document.addEventListener('DOMContentLoaded', () => {
|
||||
if (window.location.pathname.includes('/student/')) {
|
||||
window.studentManager = new StudentManager();
|
||||
}
|
||||
});
|
||||
window.studentManager = new StudentManager();
|
||||
|
||||
// 从 Session 获取用户信息并更新 UI
|
||||
fetch('/api/auth/me')
|
||||
.then(res => res.json())
|
||||
.then(result => {
|
||||
if (result.success && result.data.user) {
|
||||
const user = result.data.user;
|
||||
const nameEl = document.getElementById('userName');
|
||||
const studentNameEl = document.getElementById('studentName');
|
||||
const studentClassEl = document.getElementById('studentClass');
|
||||
|
||||
if (nameEl) nameEl.textContent = user.name;
|
||||
if (studentNameEl) studentNameEl.textContent = user.name;
|
||||
if (studentClassEl) studentClassEl.textContent = user.class || '未分配';
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -1,406 +1,108 @@
|
||||
class TeacherDashboard {
|
||||
/**
|
||||
* 教师端功能管理
|
||||
*/
|
||||
class TeacherManager {
|
||||
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.apiBase = '/api/teacher';
|
||||
this.init();
|
||||
}
|
||||
|
||||
async init() {
|
||||
// 检查登录状<E5BD95><E78AB6>? if (!await this.checkAuth()) {
|
||||
window.location.href = '/login';
|
||||
|
||||
init() {
|
||||
this.initDashboard();
|
||||
this.updateCurrentTime();
|
||||
setInterval(() => this.updateCurrentTime(), 1000);
|
||||
}
|
||||
|
||||
updateCurrentTime() {
|
||||
const timeElement = document.getElementById('currentTime');
|
||||
if (timeElement) {
|
||||
const now = new Date();
|
||||
const options = {
|
||||
year: 'numeric', month: 'long', day: 'numeric',
|
||||
hour: '2-digit', minute: '2-digit', second: '2-digit'
|
||||
};
|
||||
timeElement.textContent = now.toLocaleString('zh-CN', options);
|
||||
}
|
||||
}
|
||||
|
||||
async initDashboard() {
|
||||
// 检查是否在仪表板页面
|
||||
if (!document.getElementById('courseList')) return;
|
||||
|
||||
try {
|
||||
const response = await fetch(`${this.apiBase}/courses`);
|
||||
const result = await response.json();
|
||||
|
||||
if (result.success) {
|
||||
this.renderDashboard(result.data.courses);
|
||||
} else {
|
||||
if (window.authManager) {
|
||||
window.authManager.showNotification(result.message || '获取课程失败', 'error');
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Fetch teacher data failed:', error);
|
||||
}
|
||||
}
|
||||
|
||||
renderDashboard(courses) {
|
||||
const courseList = document.getElementById('courseList');
|
||||
if (!courseList) return;
|
||||
|
||||
if (!courses || courses.length === 0) {
|
||||
courseList.innerHTML = '<div class="col-12 text-center py-5 text-muted">暂无负责课程</div>';
|
||||
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>
|
||||
courseList.innerHTML = courses.map(course => `
|
||||
<div class="col-md-6 col-xl-4 mb-4">
|
||||
<div class="card h-100 border-0 shadow-sm course-card">
|
||||
<div class="card-body">
|
||||
<div class="d-flex justify-content-between align-items-center mb-3">
|
||||
<span class="badge bg-primary bg-opacity-10 text-primary px-3 py-2">
|
||||
<i class="fas fa-book me-1"></i> ${course.course_code || 'CODE'}
|
||||
</span>
|
||||
<span class="text-muted small">${course.credit} 学分</span>
|
||||
</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>
|
||||
<h5 class="card-title fw-bold mb-2">${course.course_name}</h5>
|
||||
<p class="card-text text-secondary small mb-4">
|
||||
<i class="fas fa-users me-1"></i> 学生人数: ${course.student_count || 0}
|
||||
</p>
|
||||
<div class="d-grid gap-2">
|
||||
<a href="/teacher/grade_entry?courseId=${course.id}" class="btn btn-outline-primary btn-sm">
|
||||
<i class="fas fa-edit me-1"></i> 成绩录入
|
||||
</a>
|
||||
<a href="/teacher/grade_management?courseId=${course.id}" class="btn btn-primary btn-sm">
|
||||
<i class="fas fa-tasks me-1"></i> 成绩管理
|
||||
</a>
|
||||
</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);
|
||||
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
`).join('');
|
||||
|
||||
// 更新统计数据
|
||||
document.getElementById('courseCount').textContent = courses.length;
|
||||
const totalStudents = courses.reduce((sum, c) => sum + (c.student_count || 0), 0);
|
||||
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();
|
||||
}
|
||||
});
|
||||
window.teacherManager = new TeacherManager();
|
||||
|
||||
// 从 Session 获取用户信息并更新 UI
|
||||
fetch('/api/auth/me')
|
||||
.then(res => res.json())
|
||||
.then(result => {
|
||||
if (result.success && result.data.user) {
|
||||
const user = result.data.user;
|
||||
const nameEl = document.getElementById('userName');
|
||||
const teacherNameEl = document.getElementById('teacherName');
|
||||
|
||||
if (nameEl) nameEl.textContent = user.name;
|
||||
if (teacherNameEl) teacherNameEl.textContent = user.name;
|
||||
}
|
||||
});
|
||||
});
|
||||
Reference in New Issue
Block a user