feat: 添加学生个人中心页面和数据库备份功能

refactor(auth): 重构认证模块适配Bootstrap 5样式
feat(controller): 在登录响应中返回用户对象
feat(server): 添加学生个人中心路由
refactor(models): 重构学生和成绩模型结构
style: 更新登录和注册页面UI设计
chore: 添加数据库备份脚本和空备份文件
This commit is contained in:
祀梦
2025-12-21 22:34:29 +08:00
parent b9a975004b
commit e5a2a9d042
16 changed files with 1834 additions and 1651 deletions

View File

@@ -14,7 +14,7 @@ class AuthController {
// 设置 Session // 设置 Session
req.session.user = user; req.session.user = user;
success(res, user, '登录成功'); success(res, { user }, '登录成功');
} catch (err) { } catch (err) {
if (err.message === '用户名或密码错误') { if (err.message === '用户名或密码错误') {
return error(res, err.message, 401); return error(res, err.message, 401);

View File

@@ -3,9 +3,11 @@ const db = require('../config/database');
class Score { class Score {
static async findByStudentId(studentId) { static async findByStudentId(studentId) {
const sql = ` const sql = `
SELECT s.*, c.course_code, c.course_name, c.credit, SELECT s.id, s.student_id, s.course_id, s.teacher_id,
s.total_score as score, s.grade_point, s.grade_level, s.created_at,
c.course_code, c.course_name, c.credit,
u.name as teacher_name u.name as teacher_name
FROM scores s FROM grades s
JOIN courses c ON s.course_id = c.id JOIN courses c ON s.course_id = c.id
JOIN users u ON s.teacher_id = u.id JOIN users u ON s.teacher_id = u.id
WHERE s.student_id = ? WHERE s.student_id = ?
@@ -16,10 +18,13 @@ class Score {
static async findDetailsById(scoreId, studentId) { static async findDetailsById(scoreId, studentId) {
const sql = ` const sql = `
SELECT s.*, c.course_code, c.course_name, c.credit, c.semester, SELECT s.id, s.student_id, s.course_id, s.teacher_id,
s.usual_score, s.midterm_score, s.final_score, s.total_score as score,
s.grade_point, s.grade_level, s.created_at, s.remark,
c.course_code, c.course_name, c.credit, c.semester,
u.name as teacher_name, u.email as teacher_email, u.name as teacher_name, u.email as teacher_email,
st.id as student_number, st.class as class_name st.id as student_number, st.class as class_name
FROM scores s FROM grades s
JOIN courses c ON s.course_id = c.id JOIN courses c ON s.course_id = c.id
JOIN users u ON s.teacher_id = u.id JOIN users u ON s.teacher_id = u.id
JOIN students st ON s.student_id = st.id JOIN students st ON s.student_id = st.id
@@ -30,22 +35,23 @@ class Score {
} }
static async create(scoreData) { static async create(scoreData) {
const { studentId, courseId, teacherId, score, gradePoint, gradeLevel, examDate, remark } = scoreData; const { studentId, courseId, teacherId, score, gradePoint, gradeLevel, remark } = scoreData;
// 既然TeacherService只传了score我们默认把它作为 final_score 和 total_score
// 如果需要支持平时分/期中分需要修改前端和Controller
const sql = ` const sql = `
INSERT INTO scores (student_id, course_id, teacher_id, score, INSERT INTO grades (student_id, course_id, teacher_id, final_score, total_score,
grade_point, grade_level, created_at, remark) grade_point, grade_level, created_at, remark)
VALUES (?, ?, ?, ?, ?, ?, NOW(), ?) VALUES (?, ?, ?, ?, ?, ?, ?, NOW(), ?)
`; `;
// 注意:这里用 created_at 替代了 examDate如果数据库有 examDate 列可以改回去
const result = await db.pool.execute(sql, [ const result = await db.pool.execute(sql, [
studentId, courseId, teacherId, score, gradePoint, gradeLevel, remark studentId, courseId, teacherId, score, score, gradePoint, gradeLevel, remark
]); ]);
return result[0].insertId; return result[0].insertId;
} }
static async findByStudentAndCourse(studentId, courseId) { static async findByStudentAndCourse(studentId, courseId) {
const rows = await db.query( const rows = await db.query(
'SELECT * FROM scores WHERE student_id = ? AND course_id = ?', 'SELECT * FROM grades WHERE student_id = ? AND course_id = ?',
[studentId, courseId] [studentId, courseId]
); );
return rows[0]; return rows[0];

View File

@@ -1,21 +1,16 @@
const db = require('../config/database'); const db = require('../config/database');
class Student { class Student {
static async findByUserId(userId) { static async findById(id) {
const students = await db.query('SELECT * FROM students WHERE user_id = ?', [userId]); const students = await db.query('SELECT * FROM students WHERE id = ?', [id]);
return students[0];
}
static async findById(studentId) {
const students = await db.query('SELECT * FROM students WHERE student_id = ?', [studentId]);
return students[0]; return students[0];
} }
static async create(studentData) { static async create(studentData) {
const { id, name, className, userId } = studentData; const { id, name, className } = studentData;
await db.query( await db.query(
'INSERT INTO students (id, name, class, user_id) VALUES (?, ?, ?, ?)', 'INSERT INTO students (id, name, class) VALUES (?, ?, ?)',
[id, name, className, userId] [id, name, className]
); );
} }
} }

62
backend/scripts/backup.js Normal file
View File

@@ -0,0 +1,62 @@
const fs = require('fs');
const path = require('path');
const db = require('../config/database');
async function backup() {
console.log('开始备份数据库...');
const backupDir = path.join(__dirname, '../../database');
const filename = `backup_${new Date().toISOString().replace(/[:.]/g, '-')}.sql`;
const filepath = path.join(backupDir, filename);
if (!fs.existsSync(backupDir)) {
fs.mkdirSync(backupDir, { recursive: true });
}
try {
const fileStream = fs.createWriteStream(filepath, { flags: 'a' });
// 获取所有表
const tables = await db.query('SHOW TABLES');
const tableNames = tables.map(t => Object.values(t)[0]);
for (const tableName of tableNames) {
console.log(`正在备份表: ${tableName}`);
// 1. 获取 CREATE TABLE 语句
const createRows = await db.query(`SHOW CREATE TABLE ${tableName}`);
const createTableSql = createRows[0]['Create Table'];
fileStream.write(`\n\n-- Table structure for table \`${tableName}\`\n`);
fileStream.write(`DROP TABLE IF EXISTS \`${tableName}\`;\n`);
fileStream.write(`${createTableSql};\n`);
// 2. 获取数据
const rows = await db.query(`SELECT * FROM ${tableName}`);
if (rows.length > 0) {
fileStream.write(`\n-- Dumping data for table \`${tableName}\`\n`);
fileStream.write(`INSERT INTO \`${tableName}\` VALUES\n`);
const values = rows.map(row => {
const rowValues = Object.values(row).map(val => {
if (val === null) return 'NULL';
if (typeof val === 'number') return val;
// 转义单引号和反斜杠
return `'${String(val).replace(/\\/g, '\\\\').replace(/'/g, "\\'")}'`;
});
return `(${rowValues.join(', ')})`;
});
fileStream.write(values.join(',\n') + ';\n');
}
}
fileStream.end();
console.log(`备份完成! 文件保存在: ${filepath}`);
process.exit(0);
} catch (error) {
console.error('备份失败:', error);
process.exit(1);
}
}
backup();

View File

@@ -96,6 +96,9 @@ app.get('/dashboard', requirePageAuth, (req, res) => {
app.get('/student/dashboard', requirePageAuth, requirePageRole(['student']), (req, res) => { app.get('/student/dashboard', requirePageAuth, requirePageRole(['student']), (req, res) => {
res.sendFile(path.join(__dirname, '../frontend/views/student/dashboard.html')); res.sendFile(path.join(__dirname, '../frontend/views/student/dashboard.html'));
}); });
app.get('/student/profile', requirePageAuth, requirePageRole(['student']), (req, res) => {
res.sendFile(path.join(__dirname, '../frontend/views/student/profile.html'));
});
// Teacher Pages // Teacher Pages
const teacherPageRouter = express.Router(); const teacherPageRouter = express.Router();

View File

@@ -0,0 +1,177 @@
-- Table structure for table `classes`
DROP TABLE IF EXISTS `classes`;
CREATE TABLE `classes` (
`id` int NOT NULL AUTO_INCREMENT COMMENT '班级ID',
`class_name` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL COMMENT '班级名称',
`grade` varchar(20) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci DEFAULT NULL COMMENT '年级',
`major` varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci DEFAULT NULL COMMENT '专业',
`teacher_id` int DEFAULT NULL COMMENT '班主任ID',
`created_at` timestamp NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
`updated_at` timestamp NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
PRIMARY KEY (`id`) USING BTREE,
KEY `idx_class_name` (`class_name`) USING BTREE,
KEY `idx_teacher_id` (`teacher_id`) USING BTREE
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci ROW_FORMAT=DYNAMIC COMMENT='班级表';
-- Dumping data for table `classes`
INSERT INTO `classes` VALUES
(1, '计算机2301', '2023', '计算机科学与技术', 2001, 'Sun Dec 21 2025 14:23:14 GMT+0800 (中国标准时间)', 'Sun Dec 21 2025 14:23:14 GMT+0800 (中国标准时间)'),
(2, '软件工程2302', '2023', '软件工程', 2002, 'Sun Dec 21 2025 14:23:14 GMT+0800 (中国标准时间)', 'Sun Dec 21 2025 14:23:14 GMT+0800 (中国标准时间)');
-- Table structure for table `courses`
DROP TABLE IF EXISTS `courses`;
CREATE TABLE `courses` (
`id` int NOT NULL AUTO_INCREMENT COMMENT '课程ID',
`course_code` varchar(20) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL COMMENT '课程代码',
`course_name` varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL COMMENT '课程名称',
`credit` decimal(3,1) NOT NULL DEFAULT '2.0' COMMENT '学分',
`teacher_id` int NOT NULL COMMENT '授课教师ID',
`class_id` int NOT NULL COMMENT '授课班级ID',
`semester` varchar(20) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci DEFAULT NULL COMMENT '学期',
`academic_year` varchar(20) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci DEFAULT NULL COMMENT '学年',
`created_at` timestamp NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
`updated_at` timestamp NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
PRIMARY KEY (`id`) USING BTREE,
UNIQUE KEY `course_code` (`course_code`) USING BTREE,
KEY `idx_course_code` (`course_code`) USING BTREE,
KEY `idx_teacher_id` (`teacher_id`) USING BTREE,
KEY `idx_class_id` (`class_id`) USING BTREE
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci ROW_FORMAT=DYNAMIC COMMENT='课程表';
-- Dumping data for table `courses`
INSERT INTO `courses` VALUES
(1, 'CS101', '高级程序设计', '4.0', 2001, 1, NULL, NULL, 'Sun Dec 21 2025 14:23:14 GMT+0800 (中国标准时间)', 'Sun Dec 21 2025 14:23:14 GMT+0800 (中国标准时间)'),
(2, 'SE201', '软件工程导论', '3.0', 2002, 2, NULL, NULL, 'Sun Dec 21 2025 14:23:14 GMT+0800 (中国标准时间)', 'Sun Dec 21 2025 14:23:14 GMT+0800 (中国标准时间)'),
(3, 'MAT101', '高等数学', '5.0', 2003, 1, NULL, NULL, 'Sun Dec 21 2025 14:23:14 GMT+0800 (中国标准时间)', 'Sun Dec 21 2025 14:23:14 GMT+0800 (中国标准时间)');
-- Table structure for table `grades`
DROP TABLE IF EXISTS `grades`;
CREATE TABLE `grades` (
`id` int NOT NULL AUTO_INCREMENT COMMENT '成绩ID',
`student_id` int NOT NULL COMMENT '学生ID',
`course_id` int NOT NULL COMMENT '课程ID',
`usual_score` decimal(5,2) DEFAULT NULL COMMENT '平时成绩',
`midterm_score` decimal(5,2) DEFAULT NULL COMMENT '期中成绩',
`final_score` decimal(5,2) DEFAULT NULL COMMENT '期末成绩',
`total_score` decimal(5,2) DEFAULT NULL COMMENT '总评成绩',
`grade_point` decimal(3,2) DEFAULT NULL COMMENT '绩点',
`grade_level` varchar(10) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci DEFAULT NULL COMMENT '成绩等级A/B/C/D/F',
`teacher_id` int NOT NULL COMMENT '录入教师ID',
`remark` text CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci COMMENT '备注',
`created_at` timestamp NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
`updated_at` timestamp NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
PRIMARY KEY (`id`) USING BTREE,
UNIQUE KEY `uk_student_course` (`student_id`,`course_id`) USING BTREE,
KEY `idx_student_id` (`student_id`) USING BTREE,
KEY `idx_course_id` (`course_id`) USING BTREE,
KEY `idx_teacher_id` (`teacher_id`) USING BTREE,
KEY `idx_total_score` (`total_score`) USING BTREE
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci ROW_FORMAT=DYNAMIC COMMENT='成绩表';
-- Dumping data for table `grades`
INSERT INTO `grades` VALUES
(1, 3001, 1, '90.00', '85.00', '88.00', '87.70', '3.00', NULL, 2001, NULL, 'Sun Dec 21 2025 14:23:14 GMT+0800 (中国标准时间)', 'Sun Dec 21 2025 14:23:14 GMT+0800 (中国标准时间)'),
(2, 3001, 3, '80.00', '75.00', '82.00', '79.30', '2.00', NULL, 2003, NULL, 'Sun Dec 21 2025 14:23:14 GMT+0800 (中国标准时间)', 'Sun Dec 21 2025 14:23:14 GMT+0800 (中国标准时间)'),
(3, 3002, 1, '95.00', '92.00', '94.00', '93.70', '4.00', NULL, 2001, NULL, 'Sun Dec 21 2025 14:23:14 GMT+0800 (中国标准时间)', 'Sun Dec 21 2025 14:23:14 GMT+0800 (中国标准时间)'),
(4, 3003, 2, '88.00', '80.00', '85.00', '84.40', '3.00', NULL, 2002, NULL, 'Sun Dec 21 2025 14:23:14 GMT+0800 (中国标准时间)', 'Sun Dec 21 2025 14:23:14 GMT+0800 (中国标准时间)');
-- Table structure for table `operation_logs`
DROP TABLE IF EXISTS `operation_logs`;
CREATE TABLE `operation_logs` (
`id` int NOT NULL AUTO_INCREMENT COMMENT '日志ID',
`user_id` int NOT NULL COMMENT '操作用户ID',
`operation_type` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL COMMENT '操作类型',
`operation_target` varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci DEFAULT NULL COMMENT '操作目标',
`operation_details` text CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci COMMENT '操作详情',
`ip_address` varchar(45) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci DEFAULT NULL COMMENT 'IP地址',
`user_agent` text CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci COMMENT '用户代理',
`created_at` timestamp NULL DEFAULT CURRENT_TIMESTAMP COMMENT '操作时间',
PRIMARY KEY (`id`) USING BTREE,
KEY `idx_user_id` (`user_id`) USING BTREE,
KEY `idx_operation_type` (`operation_type`) USING BTREE,
KEY `idx_created_at` (`created_at`) USING BTREE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci ROW_FORMAT=DYNAMIC COMMENT='操作日志表';
-- Table structure for table `scores`
DROP TABLE IF EXISTS `scores`;
CREATE TABLE `scores` (
`id` int NOT NULL AUTO_INCREMENT COMMENT '成绩记录ID',
`student_id` varchar(20) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL COMMENT '学生ID',
`course` varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL COMMENT '课程名称',
`score` decimal(5,2) NOT NULL COMMENT '成绩',
`teacher_id` varchar(20) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL COMMENT '教师ID',
`class` varchar(20) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL COMMENT '班级',
`created_at` timestamp NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
PRIMARY KEY (`id`) USING BTREE,
KEY `idx_student_id` (`student_id`) USING BTREE,
KEY `idx_teacher_id` (`teacher_id`) USING BTREE,
KEY `idx_class` (`class`) USING BTREE,
CONSTRAINT `scores_ibfk_1` FOREIGN KEY (`student_id`) REFERENCES `users` (`id`) ON DELETE CASCADE ON UPDATE RESTRICT,
CONSTRAINT `scores_ibfk_2` FOREIGN KEY (`teacher_id`) REFERENCES `users` (`id`) ON DELETE CASCADE ON UPDATE RESTRICT,
CONSTRAINT `scores_chk_1` CHECK (((`score` >= 0) and (`score` <= 100)))
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci ROW_FORMAT=DYNAMIC COMMENT='成绩记录表';
-- Table structure for table `sessions`
DROP TABLE IF EXISTS `sessions`;
CREATE TABLE `sessions` (
`session_id` varchar(128) CHARACTER SET utf8mb4 COLLATE utf8mb4_bin NOT NULL,
`expires` int unsigned NOT NULL,
`data` mediumtext CHARACTER SET utf8mb4 COLLATE utf8mb4_bin,
PRIMARY KEY (`session_id`) USING BTREE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci ROW_FORMAT=DYNAMIC;
-- Dumping data for table `sessions`
INSERT INTO `sessions` VALUES
('KY6QaavAiws7rkdEBFIFDoHefl2bxzlI', 1766334525, '{"cookie":{"originalMaxAge":86400000,"expires":"2025-12-21T16:28:44.650Z","secure":false,"httpOnly":true,"path":"/"},"user":{"id":"teststudent","name":"????","role":"student","class":"2023?1?"}}'),
('KaDFs4HogLmkjS0HAs6qki6g2FmE3sTL', 1766334465, '{"cookie":{"originalMaxAge":86400000,"expires":"2025-12-21T16:27:45.314Z","secure":false,"httpOnly":true,"path":"/"},"user":{"id":"teststudent","name":"????","role":"student","class":"2023?1?"}}'),
('P-_AKfysnsUwA6PypoYdyXCxa-_8TiCE', 1766413502, '{"cookie":{"originalMaxAge":86400000,"expires":"2025-12-22T14:25:01.323Z","secure":false,"httpOnly":true,"path":"/"},"user":{"id":"3001","name":"陈同学","role":"student","class":"计算机2301","studentInfo":{"id":"3001","name":"陈同学","class":"计算机2301"}}}'),
('QAhXDQ1FOlhU6RhaFOm3ghRtLOW4hBTd', 1766334812, '{"cookie":{"originalMaxAge":86400000,"expires":"2025-12-21T16:33:31.987Z","secure":false,"httpOnly":true,"path":"/"},"user":{"id":"teststudent","name":"????","role":"student","class":"2023?1?"}}'),
('SAuQyktAI9gAHpXbjARpe-9BL42pDRiV', 1766334764, '{"cookie":{"originalMaxAge":86400000,"expires":"2025-12-21T16:32:43.695Z","secure":false,"httpOnly":true,"path":"/"},"user":{"id":"teststudent","name":"????","role":"student","class":"2023?1?"}}'),
('XduN1lYhGPeIaLTHbLTNVnTCBtKUCkJR', 1766334689, '{"cookie":{"originalMaxAge":86400000,"expires":"2025-12-21T16:31:28.994Z","secure":false,"httpOnly":true,"path":"/"},"user":{"id":"teststudent","name":"????","role":"student","class":"2023?1?"}}'),
('Y59PFvvqK7M0DKZshc6ONTmFQjzGyMmV', 1766334426, '{"cookie":{"originalMaxAge":86400000,"expires":"2025-12-21T16:27:05.673Z","secure":false,"httpOnly":true,"path":"/"},"user":{"id":"teststudent","name":"????","role":"student","class":"2023?1?"}}'),
('rlscT2Pi2EAyLXHs1CNXyQmNSiW8vEo4', 1766334271, '{"cookie":{"originalMaxAge":86400000,"expires":"2025-12-21T16:24:30.682Z","secure":false,"httpOnly":true,"path":"/"},"user":{"id":"teststudent","name":"????","role":"student","class":"2023?1?"}}'),
('rsaOCJRjYQLPtUWlDmUFJgWcCYZbOCgJ', 1766410574, '{"cookie":{"originalMaxAge":86400000,"expires":"2025-12-21T15:54:39.935Z","secure":false,"httpOnly":true,"path":"/"},"user":{"id":"123","name":"经济局","role":"student","class":"123"}}'),
('wXxRpNTGY0wqLaHsebSAsw1I6Pb7Ed6w', 1766410584, '{"cookie":{"originalMaxAge":86400000,"expires":"2025-12-22T13:35:43.191Z","secure":false,"httpOnly":true,"path":"/"},"user":{"id":"567","name":"急急急","role":"teacher","class":"567"}}');
-- Table structure for table `students`
DROP TABLE IF EXISTS `students`;
CREATE TABLE `students` (
`id` varchar(20) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL COMMENT '学生ID与users表id一致',
`name` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL COMMENT '姓名',
`class` varchar(20) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci DEFAULT NULL COMMENT '班级',
PRIMARY KEY (`id`) USING BTREE,
CONSTRAINT `students_ibfk_1` FOREIGN KEY (`id`) REFERENCES `users` (`id`) ON DELETE CASCADE ON UPDATE RESTRICT
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci ROW_FORMAT=DYNAMIC COMMENT='学生详细信息表';
-- Dumping data for table `students`
INSERT INTO `students` VALUES
('3001', '陈同学', '计算机2301'),
('3002', '林同学', '计算机2301'),
('3003', '黄同学', '软件工程2302'),
('3004', '吴同学', '软件工程2302');
-- Table structure for table `users`
DROP TABLE IF EXISTS `users`;
CREATE TABLE `users` (
`id` varchar(20) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL COMMENT '用户ID学号/工号)',
`name` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL COMMENT '姓名',
`password` varchar(100) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL COMMENT '密码bcrypt加密',
`role` enum('student','teacher','admin') CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci NOT NULL COMMENT '角色',
`class` varchar(20) CHARACTER SET utf8mb4 COLLATE utf8mb4_0900_ai_ci DEFAULT NULL COMMENT '班级学生和教师需要管理员为NULL',
`created_at` timestamp NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
`updated_at` timestamp NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
PRIMARY KEY (`id`) USING BTREE,
KEY `idx_role` (`role`) USING BTREE,
KEY `idx_class` (`class`) USING BTREE
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci ROW_FORMAT=DYNAMIC COMMENT='用户表';
-- Dumping data for table `users`

View File

@@ -1,6 +1,7 @@
/** /**
* 认证模块管理器 * 认证模块管理器
* 处理登录、注册、注销及权限检查 * 处理登录、注册、注销及权限检查
* 适配 Bootstrap 5 样式
*/ */
class AuthManager { class AuthManager {
constructor() { constructor() {
@@ -15,21 +16,14 @@ class AuthManager {
} }
/** /**
* 创建通知容器 * 创建通知容器 (适配 Bootstrap Toast)
*/ */
createNotificationContainer() { createNotificationContainer() {
if (!document.getElementById('notification-container')) { if (!document.getElementById('notification-container')) {
const container = document.createElement('div'); const container = document.createElement('div');
container.id = 'notification-container'; container.id = 'notification-container';
container.style.cssText = ` container.className = 'toast-container position-fixed top-0 end-0 p-3';
position: fixed; container.style.zIndex = '9999';
top: 20px;
right: 20px;
z-index: 9999;
display: flex;
flex-direction: column;
gap: 10px;
`;
document.body.appendChild(container); document.body.appendChild(container);
} }
} }
@@ -38,7 +32,6 @@ class AuthManager {
* 检查用户认证状态 * 检查用户认证状态
*/ */
async checkAuthStatus() { async checkAuthStatus() {
// 如果当前是公共页面可以选择不检查或者检查后更新UI
const currentPath = window.location.pathname; const currentPath = window.location.pathname;
const isAuthPage = currentPath.includes('/login') || currentPath.includes('/register'); const isAuthPage = currentPath.includes('/login') || currentPath.includes('/register');
@@ -46,20 +39,11 @@ class AuthManager {
const response = await fetch(`${this.apiBase}/auth/me`); const response = await fetch(`${this.apiBase}/auth/me`);
const data = await response.json(); const data = await response.json();
if (data.success && data.user) { if (data.success && data.data && data.data.user) {
// 用户已登录 const redirectUrl = this.getDashboardUrl(data.data.user.role);
const redirectUrl = this.getDashboardUrl(data.user.role);
// 如果在登录/注册页,跳转到仪表板
if (isAuthPage || currentPath === '/') { if (isAuthPage || currentPath === '/') {
window.location.href = redirectUrl; window.location.href = redirectUrl;
} }
} else {
// 用户未登录,如果在受保护页面,跳转到登录页
// 注意:后端通常已经处理了重定向,这里是前端的额外保障
if (!isAuthPage && currentPath !== '/') {
// 可以在这里添加逻辑,但通常交给后端控制
}
} }
} catch (error) { } catch (error) {
console.error('Auth check failed:', error); console.error('Auth check failed:', error);
@@ -94,7 +78,7 @@ class AuthManager {
} }
} }
// 注销按钮 (可能有多个,例如在导航栏) // 注销按钮
document.querySelectorAll('.btn-logout, #logoutBtn').forEach(btn => { document.querySelectorAll('.btn-logout, #logoutBtn').forEach(btn => {
btn.addEventListener('click', (e) => this.handleLogout(e)); btn.addEventListener('click', (e) => this.handleLogout(e));
}); });
@@ -107,12 +91,12 @@ class AuthManager {
if (classField && classInput) { if (classField && classInput) {
if (role === 'student' || role === 'teacher') { if (role === 'student' || role === 'teacher') {
classField.style.display = 'block'; classField.style.display = 'flex'; // 配合 Bootstrap input-group
classInput.required = true; classInput.required = true;
} else { } else {
classField.style.display = 'none'; classField.style.display = 'none';
classInput.required = false; classInput.required = false;
classInput.value = ''; // 清空值 classInput.value = '';
} }
} }
} }
@@ -120,9 +104,9 @@ class AuthManager {
async handleLogin(e) { async handleLogin(e) {
e.preventDefault(); e.preventDefault();
const form = e.target; 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 { try {
const formData = new FormData(form); const formData = new FormData(form);
const data = Object.fromEntries(formData.entries()); const data = Object.fromEntries(formData.entries());
@@ -137,16 +121,27 @@ class AuthManager {
if (result.success) { if (result.success) {
this.showNotification('登录成功,正在跳转...', 'success'); this.showNotification('登录成功,正在跳转...', 'success');
// 获取用户信息,优先从 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(() => { setTimeout(() => {
window.location.href = this.getDashboardUrl(result.user.role); window.location.href = this.getDashboardUrl(role);
}, 1000); }, 1000);
} else {
console.error('Login success but role not found:', result);
this.showNotification('登录状态异常,请重试', 'error');
this.setLoading(submitBtn, false);
}
} else { } else {
this.showNotification(result.message || '登录失败', 'error'); this.showNotification(result.message || '登录失败', 'error');
this.setLoading(submitBtn, false); this.setLoading(submitBtn, false);
} }
} catch (error) { } catch (error) {
console.error('Login error:', error); console.error('Login error:', error);
this.showNotification('网络错误,请稍后重试', 'error'); this.showNotification('服务器连接失败,请稍后重试', 'error');
this.setLoading(submitBtn, false); this.setLoading(submitBtn, false);
} }
} }
@@ -155,19 +150,17 @@ class AuthManager {
async handleRegister(e) { async handleRegister(e) {
e.preventDefault(); e.preventDefault();
const form = e.target; 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 formData = new FormData(form);
const data = Object.fromEntries(formData.entries()); const data = Object.fromEntries(formData.entries());
// 简单验证
if (data.password !== data.confirmPassword) { if (data.password !== data.confirmPassword) {
this.showNotification('两次输入的密码不一致', 'error'); this.showNotification('两次输入的密码不一致', 'error');
return; return;
} }
if (this.setLoading(submitBtn, true, '注册中...')) { if (this.setLoading(submitBtn, true)) {
try { try {
const response = await fetch(`${this.apiBase}/auth/register`, { const response = await fetch(`${this.apiBase}/auth/register`, {
method: 'POST', method: 'POST',
@@ -188,7 +181,7 @@ class AuthManager {
} }
} catch (error) { } catch (error) {
console.error('Register error:', error); console.error('Register error:', error);
this.showNotification('网络错误,请稍后重试', 'error'); this.showNotification('服务器连接失败,请稍后重试', 'error');
this.setLoading(submitBtn, false); this.setLoading(submitBtn, false);
} }
} }
@@ -196,24 +189,17 @@ class AuthManager {
async handleLogout(e) { async handleLogout(e) {
e.preventDefault(); e.preventDefault();
if (confirm('确定要退出登录吗?')) { if (confirm('确定要退出登录吗?')) {
try { try {
const response = await fetch(`${this.apiBase}/auth/logout`, { const response = await fetch(`${this.apiBase}/auth/logout`, {
method: 'POST' method: 'POST'
}); });
const result = await response.json(); const result = await response.json();
if (result.success) { if (result.success) {
this.showNotification('已退出登录', 'success');
setTimeout(() => {
window.location.href = '/login'; window.location.href = '/login';
}, 1000);
} }
} catch (error) { } catch (error) {
console.error('Logout error:', error); console.error('Logout error:', error);
// 即使出错也强制跳转到登录页
window.location.href = '/login'; 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; if (!btn) return false;
const spinner = btn.querySelector('.spinner-border');
if (isLoading) { if (isLoading) {
if (btn.dataset.loading) return false; // 防止重复提交 if (btn.disabled) 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; btn.disabled = true;
if (spinner) spinner.classList.remove('d-none');
} else { } else {
btn.innerHTML = btn.dataset.originalText || btn.innerHTML;
delete btn.dataset.loading;
btn.disabled = false; btn.disabled = false;
if (spinner) spinner.classList.add('d-none');
} }
return true; return true;
} }
/** /**
* 显示通知 * 显示通知 (Bootstrap 5 Toast)
* @param {string} message 消息内容
* @param {string} type 消息类型 'success' | 'error' | 'info'
*/ */
showNotification(message, type = 'info') { showNotification(message, type = 'info') {
const container = document.getElementById('notification-container'); const container = document.getElementById('notification-container');
if (!container) return; if (!container) return;
const notification = document.createElement('div'); const iconMap = {
notification.className = `notification ${type}`; success: 'fa-check-circle',
error: 'fa-exclamation-circle',
warning: 'fa-exclamation-triangle',
info: 'fa-info-circle'
};
let icon = 'info-circle'; const bgMap = {
if (type === 'success') icon = 'check-circle'; success: 'bg-success',
if (type === 'error') icon = 'exclamation-circle'; error: 'bg-danger',
warning: 'bg-warning',
info: 'bg-info'
};
notification.innerHTML = ` const toastId = 'toast-' + Date.now();
<i class="fas fa-${icon}"></i> const toastHtml = `
<span class="notification-content">${message}</span> <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.appendChild(notification); container.insertAdjacentHTML('beforeend', toastHtml);
const toastElement = document.getElementById(toastId);
const toast = new bootstrap.Toast(toastElement, { delay: 3000 });
toast.show();
// 动画显示 toastElement.addEventListener('hidden.bs.toast', () => {
requestAnimationFrame(() => { toastElement.remove();
notification.classList.add('show');
}); });
// 自动消失
setTimeout(() => {
notification.classList.remove('show');
notification.addEventListener('transitionend', () => {
notification.remove();
});
}, 3000);
} }
} }
// 初始化 // 初始化认证管理器
document.addEventListener('DOMContentLoaded', () => { document.addEventListener('DOMContentLoaded', () => {
window.authManager = new AuthManager(); window.authManager = new AuthManager();
}); });

View File

@@ -1,438 +1,135 @@
/**
* 学生端功能管理
*/
class StudentManager { class StudentManager {
constructor() { constructor() {
// 动态设置API基础URL支持file:///协议和localhost:3000访问 this.apiBase = '/api/student';
this.apiBase = window.location.protocol === 'file:' ? 'http://localhost:3000/api' : '/api'; this.init();
}
init() {
this.initDashboard(); this.initDashboard();
this.initGradeDetails(); this.updateCurrentTime();
this.loadProfile(); 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() { async initDashboard() {
const gradeList = document.getElementById('gradeList'); // 检查是否在仪表板页面
const statisticsElement = document.getElementById('statistics'); if (!document.getElementById('gradesTableBody')) return;
if (!gradeList) return;
try { try {
const response = await fetch(`${this.apiBase}/student/grades`, { const response = await fetch(`${this.apiBase}/grades`);
credentials: 'include' const result = await response.json();
});
if (response.status === 401) { if (result.success) {
// 未登录重定向到登录<E799BB><E5BD95>? this.renderDashboard(result.data);
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 { } else {
this.showNotification(data.message || '获取成绩失败', 'error'); if (window.authManager) {
window.authManager.showNotification(result.message || '获取数据失败', 'error');
}
} }
} catch (error) { } catch (error) {
console.error('获取成绩错误:', error); console.error('Fetch dashboard data failed:', error);
this.showNotification('网络错误,请重试', 'error');
} }
} }
renderGrades(grades) { renderDashboard(data) {
const gradeList = document.getElementById('gradeList'); const { grades, statistics } = data;
const gradeTable = document.getElementById('gradeTable');
if (!gradeTable) return; // 渲染统计数据
if (statistics) {
this.updateElement('gpaValue', statistics.gpa);
this.updateElement('courseCount', statistics.totalCourses);
this.updateElement('creditTotal', statistics.totalCredits);
// 班级排名如果后端没提供,可以显示为 '-' 或固定值
this.updateElement('classRank', statistics.classRank || '-');
}
if (grades.length === 0) { // 渲染成绩表格
gradeList.innerHTML = ` const tbody = document.getElementById('gradesTableBody');
<div class="empty-state"> if (tbody) {
<i class="fas fa-clipboard-list fa-3x"></i> if (!grades || grades.length === 0) {
<h3>暂无成绩记录</h3> tbody.innerHTML = '<tr><td colspan="8" class="text-center py-4 text-muted">暂无成绩记录</td></tr>';
<p>你还没有任何成绩记录</p>
</div>
`;
return; return;
} }
const tbody = gradeTable.querySelector('tbody'); tbody.innerHTML = grades.map(grade => `
tbody.innerHTML = ''; <tr>
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.course_name}</td>
<td>${grade.course_code || '-'}</td>
<td>${grade.credit}</td> <td>${grade.credit}</td>
<td class="${scoreClass}"> <td>${grade.score}</td>
<span class="grade-badge">${grade.score}</span>
</td>
<td>${grade.grade_level || '-'}</td> <td>${grade.grade_level || '-'}</td>
<td>${grade.grade_point || '-'}</td> <td>${grade.grade_point || '-'}</td>
<td>${grade.teacher_name}</td>
<td>${new Date(grade.exam_date).toLocaleDateString()}</td>
<td> <td>
<a href="/html/student/details.html?id=${grade.id}" <span class="badge ${this.getScoreBadgeClass(grade.score)}">
class="btn btn-sm btn-secondary"> ${this.getScoreText(grade.score)}
<i class="fas fa-eye"></i> 查看 </span>
</a>
</td> </td>
`; <td>
<button class="btn btn-sm btn-outline-primary" onclick="studentManager.viewDetails(${grade.id})">
tbody.appendChild(row); <i class="fas fa-eye"></i> 详情
});
}
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>
<button onclick="window.history.back()" class="btn btn-primary"> </td>
<i class="fas fa-arrow-left"></i> 返回 </tr>
</button> `).join('');
</div> }
</div>
`;
} }
updateChart(grades) { updateElement(id, value) {
const ctx = document.getElementById('gradeChart'); const el = document.getElementById(id);
if (!ctx) return; if (el) el.textContent = value;
if (typeof Chart === 'undefined') {
// 如果没有Chart.js延迟加<E8BF9F><E58AA0>?
this.loadChartLibrary().then(() => this.updateChart(grades));
return;
} }
const courseNames = grades.map(g => g.course_name); getScoreBadgeClass(score) {
const scores = grades.map(g => g.score); const s = parseFloat(score);
if (s >= 90) return 'bg-success';
// 销毁现有图表实<E8A1A8><E5AE9E>? if (s >= 80) return 'bg-info';
if (window.gradeChart instanceof Chart) { if (s >= 60) return 'bg-warning';
window.gradeChart.destroy(); return 'bg-danger';
} }
window.gradeChart = new Chart(ctx, { getScoreText(score) {
type: 'bar', const s = parseFloat(score);
data: { if (s >= 60) return '及格';
labels: courseNames, return '不及格';
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() { viewDetails(id) {
return new Promise((resolve, reject) => { // 实现查看详情逻辑,或者跳转到详情页
if (typeof Chart !== 'undefined') { console.log('View details for score:', id);
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', () => { 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 || '未分配';
} }
});
}); });

View File

@@ -1,406 +1,108 @@
class TeacherDashboard { /**
* 教师端功能管理
*/
class TeacherManager {
constructor() { constructor() {
// 动态设置API基础URL支持file:///协议和localhost:3000访问 this.apiBase = '/api/teacher';
this.apiBase = window.location.protocol === 'file:' ? 'http://localhost:3000/api' : '/api';
this.currentUser = null;
this.courses = [];
this.grades = [];
this.init(); this.init();
} }
async init() { init() {
// 检查登录状<E5BD95><E78AB6>? if (!await this.checkAuth()) { this.initDashboard();
window.location.href = '/login'; 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; return;
} }
// 加载用户信息 courseList.innerHTML = courses.map(course => `
await this.loadUserInfo(); <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">
await this.loadCourses(); <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'}
await this.loadGrades(); </span>
<span class="text-muted small">${course.credit} 学分</span>
// 绑定事件
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> </div>
</td> <h5 class="card-title fw-bold mb-2">${course.course_name}</h5>
</tr> <p class="card-text text-secondary small mb-4">
`; <i class="fas fa-users me-1"></i> 学生人数: ${course.student_count || 0}
return; </p>
} <div class="d-grid gap-2">
<a href="/teacher/grade_entry?courseId=${course.id}" class="btn btn-outline-primary btn-sm">
tableBody.innerHTML = this.grades.map(grade => { <i class="fas fa-edit me-1"></i> 成绩录入
const gradeClass = this.getGradeClass(grade.score); </a>
return ` <a href="/teacher/grade_management?courseId=${course.id}" class="btn btn-primary btn-sm">
<tr> <i class="fas fa-tasks me-1"></i> 成绩管理
<td><input type="checkbox" class="grade-checkbox" data-id="${grade.id}"></td> </a>
<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> </div>
</td> </div>
</tr> </div>
`; </div>
}).join(''); `).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('courseCount').textContent = courses.length;
const totalStudents = courses.reduce((sum, c) => sum + (c.student_count || 0), 0);
document.getElementById('totalStudents').textContent = totalStudents; 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', () => { document.addEventListener('DOMContentLoaded', () => {
if (window.location.pathname.includes('/teacher/')) { window.teacherManager = new TeacherManager();
new TeacherDashboard();
// 从 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;
} }
});
}); });

View File

@@ -3,60 +3,177 @@
<head> <head>
<meta charset="UTF-8"> <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>学生成绩管理系统 - 登录</title> <title>登录 - 学生成绩管理系统</title>
<link rel="stylesheet" href="/public/css/style.css"> <!-- Bootstrap 5 CSS -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css"> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
<!-- Font Awesome -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
<!-- Google Fonts -->
<link href="https://fonts.googleapis.com/css2?family=Noto+Sans+SC:wght@400;500;700&display=swap" rel="stylesheet">
<style>
:root {
--primary-gradient: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
--secondary-gradient: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
}
body {
font-family: 'Noto Sans SC', sans-serif;
background: #f4f7f9;
min-height: 100vh;
display: flex;
align-items: center;
justify-content: center;
}
.login-container {
width: 100%;
max-width: 450px;
padding: 20px;
}
.card {
border: none;
border-radius: 1.5rem;
box-shadow: 0 15px 35px rgba(0,0,0,0.1);
overflow: hidden;
}
.card-header {
background: var(--primary-gradient);
padding: 2.5rem 2rem;
text-align: center;
border: none;
}
.card-header h3 {
color: white;
font-weight: 700;
margin-bottom: 0.5rem;
letter-spacing: 1px;
}
.card-header p {
color: rgba(255,255,255,0.8);
margin-bottom: 0;
font-size: 0.9rem;
}
.card-body {
padding: 2.5rem;
}
.form-floating {
margin-bottom: 1.25rem;
}
.form-control:focus {
box-shadow: none;
border-color: #764ba2;
}
.btn-login {
background: var(--primary-gradient);
border: none;
padding: 0.8rem;
font-weight: 600;
letter-spacing: 1px;
border-radius: 0.75rem;
transition: all 0.3s ease;
}
.btn-login:hover {
transform: translateY(-2px);
box-shadow: 0 5px 15px rgba(118, 75, 162, 0.4);
opacity: 0.9;
}
.auth-footer {
text-align: center;
margin-top: 1.5rem;
color: #6c757d;
font-size: 0.9rem;
}
.auth-footer a {
color: #764ba2;
text-decoration: none;
font-weight: 600;
}
.auth-footer a:hover {
text-decoration: underline;
}
.input-group-text {
background-color: transparent;
border-right: none;
color: #adb5bd;
}
.form-control {
border-left: none;
}
.form-control:focus + .input-group-text,
.input-group-text:focus-within {
border-color: #764ba2;
}
/* 角色图标 */
.role-icon {
position: absolute;
right: 15px;
top: 50%;
transform: translateY(-50%);
z-index: 10;
color: #adb5bd;
}
</style>
</head> </head>
<body> <body>
<div class="auth-container"> <div class="login-container">
<div class="auth-header"> <div class="card">
<h1><i class="fas fa-graduation-cap"></i> 学生成绩管理系统</h1> <div class="card-header">
<p>请登录您的账户</p> <h3><i class="fas fa-graduation-cap me-2"></i>管理系统</h3>
<p>欢迎回来,请登录您的账户</p>
</div> </div>
<div class="card-body">
<div class="auth-card">
<form id="loginForm"> <form id="loginForm">
<div class="form-group"> <div class="input-group mb-3">
<label for="id"> <span class="input-group-text"><i class="fas fa-user"></i></span>
<i class="fas fa-user"></i> 学号/工号 <input type="text" class="form-control" id="id" name="id" placeholder="学号/工号" required autocomplete="username">
</label>
<input type="text" id="id" name="id" required
placeholder="请输入学号/工号" autocomplete="username">
</div> </div>
<div class="form-group"> <div class="input-group mb-3">
<label for="password"> <span class="input-group-text"><i class="fas fa-lock"></i></span>
<i class="fas fa-lock"></i> 密码 <input type="password" class="form-control" id="password" name="password" placeholder="请输入密码" required autocomplete="current-password">
</label>
<input type="password" id="password" name="password" required
placeholder="请输入密码" autocomplete="current-password">
</div> </div>
<div class="form-group"> <div class="input-group mb-4">
<label for="role"> <span class="input-group-text"><i class="fas fa-user-tag"></i></span>
<i class="fas fa-user-tag"></i> 角色 <select class="form-select" id="role" name="role" required>
</label> <option value="" selected disabled>请选择登录角色</option>
<select id="role" name="role" required>
<option value="">请选择角色</option>
<option value="student">学生</option> <option value="student">学生</option>
<option value="teacher">教师</option> <option value="teacher">教师</option>
<option value="admin">管理员</option> <option value="admin">管理员</option>
</select> </select>
</div> </div>
<div class="form-group"> <button type="submit" class="btn btn-primary w-100 btn-login mb-3" id="loginBtn">
<button type="submit" class="btn btn-primary btn-block"> <span class="spinner-border spinner-border-sm d-none me-2" role="status" aria-hidden="true"></span>
<i class="fas fa-sign-in-alt"></i> 登录
</button> </button>
</div>
<div class="auth-footer"> <div class="auth-footer">
<p>没有账户? <a href="/register">立即注册</a></p> 没有账户? <a href="/register">立即注册</a>
</div> </div>
</form> </form>
</div> </div>
</div> </div>
</div>
<!-- Bootstrap 5 JS -->
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
<script src="/public/js/auth.js"></script> <script src="/public/js/auth.js"></script>
</body> </body>
</html> </html>

View File

@@ -3,84 +3,185 @@
<head> <head>
<meta charset="UTF-8"> <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>学生成绩管理系统 - 注册</title> <title>注册 - 学生成绩管理系统</title>
<link rel="stylesheet" href="/public/css/style.css"> <!-- Bootstrap 5 CSS -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css"> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
<!-- Font Awesome -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
<!-- Google Fonts -->
<link href="https://fonts.googleapis.com/css2?family=Noto+Sans+SC:wght@400;500;700&display=swap" rel="stylesheet">
<style>
:root {
--primary-gradient: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
--secondary-gradient: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
}
body {
font-family: 'Noto Sans SC', sans-serif;
background: #f4f7f9;
min-height: 100vh;
display: flex;
align-items: center;
justify-content: center;
padding: 40px 0;
}
.register-container {
width: 100%;
max-width: 500px;
padding: 20px;
}
.card {
border: none;
border-radius: 1.5rem;
box-shadow: 0 15px 35px rgba(0,0,0,0.1);
overflow: hidden;
}
.card-header {
background: var(--primary-gradient);
padding: 2rem;
text-align: center;
border: none;
}
.card-header h3 {
color: white;
font-weight: 700;
margin-bottom: 0.5rem;
letter-spacing: 1px;
}
.card-header p {
color: rgba(255,255,255,0.8);
margin-bottom: 0;
font-size: 0.9rem;
}
.card-body {
padding: 2rem 2.5rem;
}
.btn-register {
background: var(--primary-gradient);
border: none;
padding: 0.8rem;
font-weight: 600;
letter-spacing: 1px;
border-radius: 0.75rem;
transition: all 0.3s ease;
}
.btn-register:hover {
transform: translateY(-2px);
box-shadow: 0 5px 15px rgba(118, 75, 162, 0.4);
opacity: 0.9;
}
.auth-footer {
text-align: center;
margin-top: 1.5rem;
color: #6c757d;
font-size: 0.9rem;
}
.auth-footer a {
color: #764ba2;
text-decoration: none;
font-weight: 600;
}
.auth-footer a:hover {
text-decoration: underline;
}
.input-group-text {
background-color: transparent;
border-right: none;
color: #adb5bd;
width: 45px;
justify-content: center;
}
.form-control, .form-select {
border-left: none;
}
.form-control:focus, .form-select:focus {
box-shadow: none;
border-color: #764ba2;
}
.form-control:focus + .input-group-text,
.input-group-text:focus-within {
border-color: #764ba2;
}
#classField {
transition: all 0.3s ease;
}
</style>
</head> </head>
<body> <body>
<div class="auth-container"> <div class="register-container">
<div class="auth-header"> <div class="card">
<h1><i class="fas fa-graduation-cap"></i> 学生成绩管理系统</h1> <div class="card-header">
<p>创建新账户</p> <h3><i class="fas fa-user-plus me-2"></i>账号注册</h3>
<p>请填写以下信息完成注册</p>
</div> </div>
<div class="card-body">
<div class="auth-card">
<form id="registerForm"> <form id="registerForm">
<div class="form-group"> <div class="input-group mb-3">
<label for="id"> <span class="input-group-text"><i class="fas fa-id-card"></i></span>
<i class="fas fa-id-card"></i> 学号/工号 <input type="text" class="form-control" id="id" name="id" placeholder="学号/工号" required autocomplete="username">
</label>
<input type="text" id="id" name="id" required
placeholder="请输入学号或工号" autocomplete="username">
</div> </div>
<div class="form-group"> <div class="input-group mb-3">
<label for="name"> <span class="input-group-text"><i class="fas fa-user"></i></span>
<i class="fas fa-user"></i> 姓名 <input type="text" class="form-control" id="name" name="name" placeholder="真实姓名" required>
</label>
<input type="text" id="name" name="name" required
placeholder="请输入姓名">
</div> </div>
<div class="form-group"> <div class="input-group mb-3">
<label for="password"> <span class="input-group-text"><i class="fas fa-lock"></i></span>
<i class="fas fa-lock"></i> 密码 <input type="password" class="form-control" id="password" name="password" placeholder="设置密码" required autocomplete="new-password">
</label>
<input type="password" id="password" name="password" required
placeholder="请输入密码" autocomplete="new-password">
</div> </div>
<div class="form-group"> <div class="input-group mb-3">
<label for="confirmPassword"> <span class="input-group-text"><i class="fas fa-shield-alt"></i></span>
<i class="fas fa-lock"></i> 确认密码 <input type="password" class="form-control" id="confirmPassword" name="confirmPassword" placeholder="确认密码" required autocomplete="new-password">
</label>
<input type="password" id="confirmPassword" name="confirmPassword" required
placeholder="请再次输入密码" autocomplete="new-password">
</div> </div>
<div class="form-group"> <div class="input-group mb-3">
<label for="role"> <span class="input-group-text"><i class="fas fa-user-tag"></i></span>
<i class="fas fa-user-tag"></i> 角色 <select class="form-select" id="role" name="role" required>
</label> <option value="" selected disabled>选择您的角色</option>
<select id="role" name="role" required>
<option value="">请选择角色</option>
<option value="student">学生</option> <option value="student">学生</option>
<option value="teacher">教师</option> <option value="teacher">教师</option>
<option value="admin">管理员</option> <option value="admin">管理员</option>
</select> </select>
</div> </div>
<div class="form-group" id="classField" style="display: none;"> <div class="input-group mb-4" id="classField" style="display: none;">
<label for="class"> <span class="input-group-text"><i class="fas fa-users"></i></span>
<i class="fas fa-users"></i> 班级 <input type="text" class="form-control" id="class" name="class" placeholder="班级名称 (如: 2023级1班)">
</label>
<input type="text" id="class" name="class"
placeholder="请输入班级(学生/教师必填)">
</div> </div>
<div class="form-group"> <button type="submit" class="btn btn-primary w-100 btn-register mb-3" id="registerBtn">
<button type="submit" class="btn btn-primary btn-block"> <span class="spinner-border spinner-border-sm d-none me-2" role="status" aria-hidden="true"></span>
<i class="fas fa-user-plus"></i> 注册
</button> </button>
</div>
<div class="auth-footer"> <div class="auth-footer">
<p>已有账户? <a href="/login">立即登录</a></p> 已有账户? <a href="/login">立即登录</a>
</div> </div>
</form> </form>
</div> </div>
</div> </div>
</div>
<!-- Bootstrap 5 JS -->
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
<script src="/public/js/auth.js"></script> <script src="/public/js/auth.js"></script>
</body> </body>
</html> </html>

View File

@@ -3,191 +3,386 @@
<head> <head>
<meta charset="UTF-8"> <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>学生成绩管理系统 - 学生仪表<E4BBAA><E8A1A8>?/title> <title>学生仪表板 - 成绩管理系统</title>
<link rel="stylesheet" href="/public/css/style.css"> <!-- Bootstrap 5 CSS -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css"> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
</head> <!-- Font Awesome -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
<!-- Google Fonts -->
<link href="https://fonts.googleapis.com/css2?family=Noto+Sans+SC:wght@400;500;700&display=swap" rel="stylesheet">
<style>
:root {
--sidebar-width: 260px;
--primary-color: #4e73df;
--secondary-color: #858796;
--success-color: #1cc88a;
--info-color: #36b9cc;
--warning-color: #f6c23e;
--danger-color: #e74a3b;
--light-bg: #f8f9fc;
--primary-gradient: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
}
body {
font-family: 'Noto Sans SC', sans-serif;
background-color: var(--light-bg);
overflow-x: hidden;
}
/* 侧边栏样式 */
.sidebar {
width: var(--sidebar-width);
height: 100vh;
position: fixed;
left: 0;
top: 0;
background: var(--primary-gradient);
color: white;
z-index: 1000;
transition: all 0.3s;
}
.sidebar-header {
padding: 2rem 1.5rem;
text-align: center;
border-bottom: 1px solid rgba(255,255,255,0.1);
}
.sidebar-brand {
font-size: 1.25rem;
font-weight: 700;
color: white;
text-decoration: none;
display: flex;
align-items: center;
justify-content: center;
gap: 10px;
}
.user-profile {
padding: 2rem 1rem;
text-align: center;
}
.user-avatar {
width: 80px;
height: 80px;
background: rgba(255,255,255,0.2);
border-radius: 50%;
display: flex;
align-items: center;
justify-content: center;
margin: 0 auto 1rem;
font-size: 2rem;
}
.user-info h6 {
margin-bottom: 0.25rem;
font-weight: 600;
}
.user-info p {
font-size: 0.85rem;
opacity: 0.8;
margin-bottom: 0;
}
.nav-menu {
padding: 1rem 0;
}
.nav-item {
padding: 0.25rem 1rem;
}
.nav-link {
color: rgba(255,255,255,0.8);
padding: 0.8rem 1.25rem;
border-radius: 0.5rem;
display: flex;
align-items: center;
gap: 12px;
transition: all 0.2s;
}
.nav-link:hover, .nav-link.active {
color: white;
background: rgba(255,255,255,0.15);
}
.nav-link i {
width: 20px;
text-align: center;
}
/* 主内容区 */
.main-content {
margin-left: var(--sidebar-width);
padding: 2rem;
min-height: 100vh;
}
.top-navbar {
background: white;
padding: 1rem 2rem;
border-radius: 1rem;
box-shadow: 0 0.15rem 1.75rem 0 rgba(58, 59, 69, 0.1);
margin-bottom: 2rem;
display: flex;
justify-content: space-between;
align-items: center;
}
.page-heading h4 {
margin-bottom: 0;
font-weight: 700;
color: #333;
}
.stat-card {
border: none;
border-radius: 1rem;
box-shadow: 0 0.15rem 1.75rem 0 rgba(58, 59, 69, 0.1);
transition: transform 0.3s;
}
.stat-card:hover {
transform: translateY(-5px);
}
.stat-icon {
width: 48px;
height: 48px;
border-radius: 0.75rem;
display: flex;
align-items: center;
justify-content: center;
font-size: 1.25rem;
}
.card-table {
border: none;
border-radius: 1rem;
box-shadow: 0 0.15rem 1.75rem 0 rgba(58, 59, 69, 0.1);
}
.card-header {
background-color: white;
border-bottom: 1px solid #f1f1f1;
padding: 1.25rem 1.5rem;
border-radius: 1rem 1rem 0 0 !important;
}
.table thead th {
background-color: #f8f9fc;
font-weight: 600;
text-transform: uppercase;
font-size: 0.75rem;
letter-spacing: 0.05em;
color: #4e73df;
border: none;
padding: 1rem 1.5rem;
}
.table tbody td {
padding: 1rem 1.5rem;
vertical-align: middle;
border-color: #f1f1f1;
}
.badge {
padding: 0.5em 0.8em;
font-weight: 500;
}
@media (max-width: 992px) {
.sidebar {
left: -var(--sidebar-width);
}
.main-content {
margin-left: 0;
}
.sidebar.active {
left: 0;
}
}
</style>
</head> </head>
<body> <body>
<!-- 顶部导航<EFBFBD><EFBFBD>?--> <!-- 侧边栏 -->
<nav class="navbar"> <div class="sidebar">
<div class="navbar-brand">
<i class="fas fa-graduation-cap"></i>
<span>XX学校成绩管理系统</span>
</div>
<div class="navbar-menu">
<a href="/" class="btn btn-secondary">
<i class="fas fa-home"></i> 主页
</a>
<div class="navbar-user">
<span class="user-name" id="userName">加载<EFBFBD><EFBFBD>?..</span>
<button id="logoutBtn" class="btn btn-primary">
<i class="fas fa-sign-out-alt"></i> 退<><E98080>? </button>
</div>
</div>
</nav>
<!-- 仪表板容<E69DBF><E5AEB9>?-->
<div class="dashboard-container">
<!-- 左侧侧边<E4BEA7><E8BEB9>?-->
<aside class="sidebar">
<div class="sidebar-header"> <div class="sidebar-header">
<div class="user-info"> <a href="#" class="sidebar-brand">
<i class="fas fa-graduation-cap"></i>
<span>成绩管理系统</span>
</a>
</div>
<div class="user-profile">
<div class="user-avatar"> <div class="user-avatar">
<i class="fas fa-user-graduate"></i> <i class="fas fa-user-graduate"></i>
</div> </div>
<div class="user-details"> <div class="user-info text-white">
<h3 id="studentName">加载<EFBFBD><EFBFBD>?..</h3> <h6 id="studentName">加载中...</h6>
<p>学生 | 班级<EFBFBD><EFBFBD>?span id="studentClass">加载<E58AA0><E8BDBD>?..</span></p> <p>学生 | <span id="studentClass">加载中...</span></p>
</div>
</div> </div>
</div> </div>
<ul class="sidebar-menu"> <nav class="nav-menu">
<li> <div class="nav-item">
<a href="#" class="active"> <a href="/student/dashboard" class="nav-link active">
<i class="fas fa-tachometer-alt"></i> <i class="fas fa-tachometer-alt"></i>
<span>仪表<EFBFBD><EFBFBD>?/span> <span>仪表</span>
</a> </a>
</li> </div>
<li> <div class="nav-item">
<a href="#"> <a href="#grades-section" class="nav-link">
<i class="fas fa-chart-bar"></i>
<span>成绩查询</span>
</a>
</li>
<li>
<a href="#">
<i class="fas fa-book"></i> <i class="fas fa-book"></i>
<span>课程详情</span> <span>我的课程</span>
</a> </a>
</li> </div>
<li> <div class="nav-item">
<a href="#"> <a href="#stats-section" class="nav-link">
<i class="fas fa-user"></i>
<span>个人信息</span>
</a>
</li>
<li>
<a href="#">
<i class="fas fa-chart-line"></i> <i class="fas fa-chart-line"></i>
<span>成绩分析</span> <span>成绩分析</span>
</a> </a>
</li> </div>
<li> <div class="nav-item">
<a href="#"> <a href="/student/profile" class="nav-link">
<i class="fas fa-download"></i> <i class="fas fa-user"></i>
<span>成绩导出</span> <span>个人中心</span>
</a> </a>
</li> </div>
</ul> <div class="nav-item mt-4">
</aside> <a href="javascript:void(0)" id="logoutBtn" class="nav-link text-warning">
<i class="fas fa-sign-out-alt"></i>
<span>退出登录</span>
</a>
</div>
</nav>
</div>
<!-- 主内容 --> <!-- 主内容 -->
<main class="main-content"> <div class="main-content">
<div class="content-header"> <!-- 顶部导航 -->
<div> <div class="top-navbar">
<h1 class="page-title">学生仪表<EFBFBD><EFBFBD>?/h1> <div class="page-heading">
<div class="breadcrumb"> <h4>学生仪表板</h4>
<a href="/">主页</a>
<i class="fas fa-chevron-right"></i>
<span>学生仪表<EFBFBD><EFBFBD>?/span>
</div> </div>
<div class="d-flex align-items-center gap-3">
<div class="text-end d-none d-md-block">
<div class="small text-muted" id="currentTime"></div>
<div class="fw-bold" id="userName">加载中...</div>
</div>
<div class="vr mx-2 d-none d-md-block"></div>
<button class="btn btn-sm btn-light border rounded-pill px-3">
<i class="fas fa-bell text-secondary"></i>
</button>
</div> </div>
<div class="current-time" id="currentTime"></div>
</div> </div>
<!-- 统计卡片 --> <!-- 统计卡片 -->
<div class="stats-grid"> <div class="row g-4 mb-4" id="stats-section">
<div class="stat-card"> <div class="col-xl-3 col-md-6">
<div class="stat-icon gpa"> <div class="card stat-card h-100 p-3">
<div class="d-flex justify-content-between align-items-start">
<div>
<p class="text-secondary small mb-1 fw-bold">平均绩点 (GPA)</p>
<h3 class="mb-0 fw-bold" id="gpaValue">0.00</h3>
</div>
<div class="stat-icon bg-primary bg-opacity-10 text-primary">
<i class="fas fa-star"></i> <i class="fas fa-star"></i>
</div> </div>
<div class="stat-value" id="gpaValue">3.75</div>
<div class="stat-label">平均绩点</div>
</div> </div>
<div class="stat-card">
<div class="stat-icon courses">
<i class="fas fa-book"></i>
</div> </div>
<div class="stat-value" id="courseCount">8</div>
<div class="stat-label">已修课程</div>
</div> </div>
<div class="col-xl-3 col-md-6">
<div class="stat-card"> <div class="card stat-card h-100 p-3">
<div class="stat-icon credits"> <div class="d-flex justify-content-between align-items-start">
<div>
<p class="text-secondary small mb-1 fw-bold">已修课程</p>
<h3 class="mb-0 fw-bold" id="courseCount">0</h3>
</div>
<div class="stat-icon bg-success bg-opacity-10 text-success">
<i class="fas fa-book-open"></i>
</div>
</div>
</div>
</div>
<div class="col-xl-3 col-md-6">
<div class="card stat-card h-100 p-3">
<div class="d-flex justify-content-between align-items-start">
<div>
<p class="text-secondary small mb-1 fw-bold">获得学分</p>
<h3 class="mb-0 fw-bold" id="creditTotal">0</h3>
</div>
<div class="stat-icon bg-info bg-opacity-10 text-info">
<i class="fas fa-certificate"></i> <i class="fas fa-certificate"></i>
</div> </div>
<div class="stat-value" id="creditTotal">24</div>
<div class="stat-label">总学<EFBFBD><EFBFBD>?/div>
</div> </div>
</div>
<div class="stat-card"> </div>
<div class="stat-icon ranking"> <div class="col-xl-3 col-md-6">
<div class="card stat-card h-100 p-3">
<div class="d-flex justify-content-between align-items-start">
<div>
<p class="text-secondary small mb-1 fw-bold">班级排名</p>
<h3 class="mb-0 fw-bold" id="classRank">-</h3>
</div>
<div class="stat-icon bg-warning bg-opacity-10 text-warning">
<i class="fas fa-trophy"></i> <i class="fas fa-trophy"></i>
</div> </div>
<div class="stat-value" id="classRank">5</div> </div>
<div class="stat-label">班级排名</div> </div>
</div> </div>
</div> </div>
<!-- 成绩表格 --> <!-- 成绩表格 -->
<div class="grades-table"> <div class="card card-table" id="grades-section">
<div class="table-header"> <div class="card-header d-flex justify-content-between align-items-center">
<h2 class="table-title">本学期成<EFBFBD><EFBFBD>?/h2> <h5 class="mb-0 fw-bold"><i class="fas fa-list-ul me-2 text-primary"></i>近期成绩记录</h5>
<div class="table-actions"> <div class="d-flex gap-2">
<select class="form-select" style="width: 150px;"> <select class="form-select form-select-sm" style="width: 160px;">
<option value="all">所有学<EFBFBD><EFBFBD>?/option> <option value="all">所有学</option>
<option value="2023-2" selected>2023-2024学年第二学期</option> <option value="2023-2" selected>2023-2024学期</option>
<option value="2023-1">2023-2024学年第一学期</option> <option value="2023-1">2023-2024学期</option>
</select> </select>
<button class="btn btn-primary"> <button class="btn btn-sm btn-primary px-3">
<i class="fas fa-download"></i> 导出成绩<EFBFBD><EFBFBD>? </button> <i class="fas fa-download me-1"></i> 导出
</button>
</div> </div>
</div> </div>
<div class="table-responsive">
<div class="table-container"> <table class="table table-hover align-middle mb-0">
<table>
<thead> <thead>
<tr> <tr>
<th>课程名称</th> <th>课程名称</th>
<th>课程代码</th> <th>课程代码</th>
<th>学分</th> <th>学分</th>
<th>平时成绩</th> <th>分数</th>
<th>期末成绩</th> <th>等第</th>
<th>总成<EFBFBD><EFBFBD>?/th>
<th>绩点</th> <th>绩点</th>
<th>状态</th>
<th>操作</th> <th>操作</th>
</tr> </tr>
</thead> </thead>
<tbody id="gradesTableBody"> <tbody id="gradesTableBody">
<!-- 成绩数据将通过JavaScript动态加<EFBFBD><EFBFBD>?--> <!-- 数据将JavaScript 填充 -->
<tr>
<td colspan="8" class="text-center py-5 text-muted">
<div class="spinner-border spinner-border-sm me-2" role="status"></div>
数据加载中...
</td>
</tr>
</tbody> </tbody>
</table> </table>
</div> </div>
</div> </div>
</main>
</div> </div>
<script src="/public/js/student.js"></script> <!-- Bootstrap 5 JS -->
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
<script src="/public/js/auth.js"></script> <script src="/public/js/auth.js"></script>
<script> <script src="/public/js/student.js"></script>
// 更新当前时间
function updateCurrentTime() {
const now = new Date();
const options = {
year: 'numeric',
month: 'long',
day: 'numeric',
hour: '2-digit',
minute: '2-digit',
second: '2-digit'
};
document.getElementById('currentTime').textContent = now.toLocaleString('zh-CN', options);
}
setInterval(updateCurrentTime, 1000);
updateCurrentTime();
</script>
</body> </body>
</html> </html>

View File

@@ -0,0 +1,347 @@
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>个人中心 - 成绩管理系统</title>
<!-- Bootstrap 5 CSS -->
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
<!-- Font Awesome -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
<!-- Google Fonts -->
<link href="https://fonts.googleapis.com/css2?family=Noto+Sans+SC:wght@400;500;700&display=swap" rel="stylesheet">
<style>
:root {
--sidebar-width: 260px;
--primary-color: #4e73df;
--secondary-color: #858796;
--light-bg: #f8f9fc;
--student-gradient: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
}
body {
font-family: 'Noto Sans SC', sans-serif;
background-color: var(--light-bg);
overflow-x: hidden;
}
/* 侧边栏样式 */
.sidebar {
width: var(--sidebar-width);
height: 100vh;
position: fixed;
left: 0;
top: 0;
background: var(--student-gradient);
color: white;
z-index: 1000;
transition: all 0.3s;
}
.sidebar-header {
padding: 2rem 1.5rem;
text-align: center;
border-bottom: 1px solid rgba(255,255,255,0.1);
}
.sidebar-brand {
font-size: 1.25rem;
font-weight: 700;
color: white;
text-decoration: none;
display: flex;
align-items: center;
justify-content: center;
gap: 10px;
}
.user-profile {
padding: 2rem 1rem;
text-align: center;
}
.user-avatar {
width: 80px;
height: 80px;
background: rgba(255,255,255,0.2);
border-radius: 50%;
display: flex;
align-items: center;
justify-content: center;
margin: 0 auto 1rem;
font-size: 2rem;
}
.user-info h6 {
margin-bottom: 0.25rem;
font-weight: 600;
}
.user-info p {
font-size: 0.85rem;
opacity: 0.8;
margin-bottom: 0;
}
.nav-menu {
padding: 1rem 0;
}
.nav-item {
padding: 0.25rem 1rem;
}
.nav-link {
color: rgba(255,255,255,0.8);
padding: 0.8rem 1.25rem;
border-radius: 0.5rem;
display: flex;
align-items: center;
gap: 12px;
transition: all 0.2s;
}
.nav-link:hover, .nav-link.active {
color: white;
background: rgba(255,255,255,0.15);
}
.nav-link i {
width: 20px;
text-align: center;
}
/* 主内容区 */
.main-content {
margin-left: var(--sidebar-width);
padding: 2rem;
min-height: 100vh;
}
.top-navbar {
background: white;
padding: 1rem 2rem;
border-radius: 1rem;
box-shadow: 0 0.15rem 1.75rem 0 rgba(58, 59, 69, 0.1);
margin-bottom: 2rem;
display: flex;
justify-content: space-between;
align-items: center;
}
.page-heading h4 {
margin-bottom: 0;
font-weight: 700;
color: #333;
}
.card {
border: none;
border-radius: 1rem;
box-shadow: 0 0.15rem 1.75rem 0 rgba(58, 59, 69, 0.1);
}
.card-header {
background-color: white;
border-bottom: 1px solid #f1f1f1;
padding: 1.25rem 1.5rem;
border-radius: 1rem 1rem 0 0 !important;
font-weight: 600;
}
.form-label {
font-weight: 500;
color: #555;
}
@media (max-width: 992px) {
.sidebar {
left: -var(--sidebar-width);
}
.main-content {
margin-left: 0;
}
.sidebar.active {
left: 0;
}
}
</style>
</head>
<body>
<!-- 侧边栏 -->
<div class="sidebar">
<div class="sidebar-header">
<a href="#" class="sidebar-brand">
<i class="fas fa-graduation-cap"></i>
<span>成绩管理系统</span>
</a>
</div>
<div class="user-profile">
<div class="user-avatar">
<i class="fas fa-user-graduate"></i>
</div>
<div class="user-info text-white">
<h6 id="studentName">加载中...</h6>
<p>学生 | <span id="studentClass">加载中...</span></p>
</div>
</div>
<nav class="nav-menu">
<div class="nav-item">
<a href="/student/dashboard" class="nav-link">
<i class="fas fa-tachometer-alt"></i>
<span>仪表板</span>
</a>
</div>
<div class="nav-item">
<a href="/student/dashboard#grades-section" class="nav-link">
<i class="fas fa-book"></i>
<span>我的课程</span>
</a>
</div>
<div class="nav-item">
<a href="/student/dashboard#stats-section" class="nav-link">
<i class="fas fa-chart-line"></i>
<span>成绩分析</span>
</a>
</div>
<div class="nav-item">
<a href="#" class="nav-link active">
<i class="fas fa-user"></i>
<span>个人中心</span>
</a>
</div>
<div class="nav-item mt-4">
<a href="javascript:void(0)" id="logoutBtn" class="nav-link text-warning">
<i class="fas fa-sign-out-alt"></i>
<span>退出登录</span>
</a>
</div>
</nav>
</div>
<!-- 主内容 -->
<div class="main-content">
<!-- 顶部导航 -->
<div class="top-navbar">
<div class="page-heading">
<h4>个人中心</h4>
</div>
<div class="d-flex align-items-center gap-3">
<div class="text-end d-none d-md-block">
<div class="small text-muted" id="currentTime"></div>
<div class="fw-bold" id="userName">加载中...</div>
</div>
</div>
</div>
<div class="row">
<div class="col-md-4 mb-4">
<div class="card h-100">
<div class="card-body text-center d-flex flex-column align-items-center justify-content-center p-5">
<div class="user-avatar mb-3" style="background: #f8f9fa; color: #4e73df; width: 100px; height: 100px; font-size: 2.5rem;">
<i class="fas fa-user-graduate"></i>
</div>
<h4 class="fw-bold mb-1" id="profileName">加载中...</h4>
<p class="text-muted mb-4" id="profileRole">学生账户</p>
<div class="d-grid gap-2 w-100">
<button class="btn btn-outline-primary"><i class="fas fa-camera me-2"></i>更换头像</button>
</div>
</div>
</div>
</div>
<div class="col-md-8 mb-4">
<div class="card">
<div class="card-header">
<i class="fas fa-user-edit me-2 text-primary"></i> 基本信息
</div>
<div class="card-body p-4">
<form>
<div class="row mb-3">
<div class="col-md-6">
<label class="form-label">学号</label>
<input type="text" class="form-control" id="profileId" readonly disabled>
</div>
<div class="col-md-6">
<label class="form-label">姓名</label>
<input type="text" class="form-control" id="profileNameInput" readonly>
</div>
</div>
<div class="row mb-3">
<div class="col-md-6">
<label class="form-label">班级</label>
<input type="text" class="form-control" id="profileClass" readonly disabled>
</div>
<div class="col-md-6">
<label class="form-label">角色</label>
<input type="text" class="form-control" value="学生" readonly disabled>
</div>
</div>
<hr class="my-4">
<h6 class="mb-3 fw-bold text-secondary">安全设置</h6>
<div class="mb-3">
<label class="form-label">原密码</label>
<input type="password" class="form-control" placeholder="请输入原密码">
</div>
<div class="row mb-4">
<div class="col-md-6">
<label class="form-label">新密码</label>
<input type="password" class="form-control" placeholder="请输入新密码">
</div>
<div class="col-md-6">
<label class="form-label">确认新密码</label>
<input type="password" class="form-control" placeholder="再次输入新密码">
</div>
</div>
<div class="text-end">
<button type="button" class="btn btn-primary px-4" onclick="alert('修改密码功能暂未开放')">
<i class="fas fa-save me-1"></i> 保存更改
</button>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
<!-- Bootstrap 5 JS -->
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
<script src="/public/js/auth.js"></script>
<script>
// 简单的页面初始化脚本
document.addEventListener('DOMContentLoaded', () => {
fetch('/api/auth/me')
.then(res => res.json())
.then(result => {
if (result.success && result.data.user) {
const user = result.data.user;
document.getElementById('userName').textContent = user.name;
document.getElementById('studentName').textContent = user.name;
document.getElementById('profileName').textContent = user.name;
document.getElementById('profileNameInput').value = user.name;
document.getElementById('profileId').value = user.id;
document.getElementById('profileClass').value = user.class || '未知';
document.getElementById('studentClass').textContent = user.class || '未知';
}
});
// 更新时间
const updateTime = () => {
const now = new Date();
document.getElementById('currentTime').textContent = now.toLocaleString('zh-CN', {
year: 'numeric', month: 'long', day: 'numeric',
hour: '2-digit', minute: '2-digit'
});
};
updateTime();
setInterval(updateTime, 1000);
});
</script>
</body>
</html>

View File

@@ -3,505 +3,312 @@
<head> <head>
<meta charset="UTF-8"> <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>学生成绩管理系统 - 教师仪表<E4BBAA><E8A1A8>?/title> <title>教师仪表板 - 成绩管理系统</title>
<link rel="stylesheet" href="/public/css/style.css"> <!-- Bootstrap 5 CSS -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css"> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
</head> <!-- Font Awesome -->
/* 仪表板布局 */ <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
.dashboard-container { <!-- Google Fonts -->
display: flex; <link href="https://fonts.googleapis.com/css2?family=Noto+Sans+SC:wght@400;500;700&display=swap" rel="stylesheet">
min-height: calc(100vh - 80px); <style>
:root {
--sidebar-width: 260px;
--primary-color: #1cc88a;
--secondary-color: #858796;
--light-bg: #f8f9fc;
--teacher-gradient: linear-gradient(135deg, #11998e 0%, #38ef7d 100%);
} }
/* 侧边<E4BEA7><E8BEB9>?*/ body {
font-family: 'Noto Sans SC', sans-serif;
background-color: var(--light-bg);
overflow-x: hidden;
}
/* 侧边栏样式 */
.sidebar { .sidebar {
width: 250px; width: var(--sidebar-width);
background: linear-gradient(180deg, #43e97b 0%, #38f9d7 100%); height: 100vh;
position: fixed;
left: 0;
top: 0;
background: var(--teacher-gradient);
color: white; color: white;
padding: 30px 0; z-index: 1000;
position: sticky; transition: all 0.3s;
top: 80px;
height: calc(100vh - 80px);
overflow-y: auto;
} }
.sidebar-header { .sidebar-header {
padding: 0 25px 30px; padding: 2rem 1.5rem;
border-bottom: 1px solid rgba(255, 255, 255, 0.1); text-align: center;
margin-bottom: 20px; border-bottom: 1px solid rgba(255,255,255,0.1);
} }
.user-info { .sidebar-brand {
display: flex; font-size: 1.25rem;
align-items: center; font-weight: 700;
gap: 15px; color: white;
} text-decoration: none;
.user-avatar {
width: 50px;
height: 50px;
border-radius: 50%;
background: white;
display: flex; display: flex;
align-items: center; align-items: center;
justify-content: center; justify-content: center;
color: #43e97b; gap: 10px;
font-size: 20px;
} }
.user-details h3 { .user-profile {
margin: 0 0 5px; padding: 2rem 1rem;
font-size: 1.1rem; text-align: center;
} }
.user-details p { .user-avatar {
margin: 0; width: 80px;
font-size: 0.9rem; height: 80px;
opacity: 0.8; background: rgba(255,255,255,0.2);
} border-radius: 50%;
.sidebar-menu {
list-style: none;
padding: 0;
margin: 0;
}
.sidebar-menu li {
margin: 5px 0;
}
.sidebar-menu a {
display: flex; display: flex;
align-items: center; align-items: center;
gap: 15px; justify-content: center;
padding: 15px 25px; margin: 0 auto 1rem;
font-size: 2rem;
}
.user-info h6 {
margin-bottom: 0.25rem;
font-weight: 600;
}
.user-info p {
font-size: 0.85rem;
opacity: 0.8;
margin-bottom: 0;
}
.nav-menu {
padding: 1rem 0;
}
.nav-item {
padding: 0.25rem 1rem;
}
.nav-link {
color: rgba(255,255,255,0.8);
padding: 0.8rem 1.25rem;
border-radius: 0.5rem;
display: flex;
align-items: center;
gap: 12px;
transition: all 0.2s;
}
.nav-link:hover, .nav-link.active {
color: white; color: white;
text-decoration: none; background: rgba(255,255,255,0.15);
transition: all 0.3s ease;
border-left: 3px solid transparent;
} }
.sidebar-menu a:hover { .nav-link i {
background: rgba(255, 255, 255, 0.1);
border-left-color: white;
}
.sidebar-menu a.active {
background: rgba(255, 255, 255, 0.2);
border-left-color: white;
}
.sidebar-menu i {
width: 20px; width: 20px;
text-align: center; text-align: center;
} }
/* 主内容区 */ /* 主内容区 */
.main-content { .main-content {
flex: 1; margin-left: var(--sidebar-width);
padding: 30px; padding: 2rem;
background: #f8f9ff; min-height: 100vh;
} }
.content-header { .top-navbar {
background: white;
padding: 1rem 2rem;
border-radius: 1rem;
box-shadow: 0 0.15rem 1.75rem 0 rgba(58, 59, 69, 0.1);
margin-bottom: 2rem;
display: flex; display: flex;
justify-content: space-between; justify-content: space-between;
align-items: center; align-items: center;
margin-bottom: 30px;
} }
.page-title { .page-heading h4 {
font-size: 1.8rem; margin-bottom: 0;
font-weight: 700;
color: #333; color: #333;
margin: 0;
} }
.breadcrumb { .stat-card {
display: flex; border: none;
align-items: center; border-radius: 1rem;
gap: 10px; box-shadow: 0 0.15rem 1.75rem 0 rgba(58, 59, 69, 0.1);
color: #666; transition: transform 0.3s;
font-size: 0.9rem;
} }
.breadcrumb a { .stat-card:hover {
color: #43e97b;
text-decoration: none;
}
.breadcrumb i {
font-size: 0.8rem;
}
/* 功能卡片 */
.function-grid {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
gap: 25px;
margin-bottom: 40px;
}
.function-card {
background: white;
border-radius: 15px;
padding: 30px;
text-align: center;
box-shadow: 0 5px 20px rgba(0, 0, 0, 0.05);
transition: all 0.3s ease;
cursor: pointer;
border: 2px solid transparent;
}
.function-card:hover {
transform: translateY(-5px); transform: translateY(-5px);
box-shadow: 0 15px 30px rgba(0, 0, 0, 0.1);
border-color: #43e97b;
} }
.function-icon { .stat-icon {
width: 80px; width: 48px;
height: 80px; height: 48px;
border-radius: 50%; border-radius: 0.75rem;
background: linear-gradient(135deg, #43e97b 0%, #38f9d7 100%);
display: flex; display: flex;
align-items: center; align-items: center;
justify-content: center; justify-content: center;
margin: 0 auto 20px; font-size: 1.25rem;
font-size: 32px;
color: white;
} }
.function-title { .course-card {
font-size: 1.3rem; transition: transform 0.3s, box-shadow 0.3s;
color: #333; border: none;
margin-bottom: 10px;
} }
.function-description { .course-card:hover {
color: #666; transform: translateY(-5px);
line-height: 1.5; box-shadow: 0 0.5rem 1rem rgba(0,0,0,0.1) !important;
margin-bottom: 20px;
} }
/* 快速操<E9809F><E6938D>?*/
.quick-actions {
background: white;
border-radius: 15px;
padding: 25px;
margin-bottom: 30px;
box-shadow: 0 5px 20px rgba(0, 0, 0, 0.05);
}
.section-title {
font-size: 1.4rem;
color: #333;
margin-bottom: 20px;
display: flex;
align-items: center;
gap: 10px;
}
.section-title i {
color: #43e97b;
}
.action-buttons {
display: flex;
gap: 15px;
flex-wrap: wrap;
}
.action-btn {
padding: 12px 25px;
background: #f8f9ff;
border: 1px solid #e0e0e0;
border-radius: 10px;
color: #333;
text-decoration: none;
display: flex;
align-items: center;
gap: 10px;
transition: all 0.3s ease;
}
.action-btn:hover {
background: #43e97b;
color: white;
border-color: #43e97b;
}
/* 最近活<E8BF91><E6B4BB>?*/
.recent-activities {
background: white;
border-radius: 15px;
padding: 25px;
box-shadow: 0 5px 20px rgba(0, 0, 0, 0.05);
}
.activity-list {
list-style: none;
padding: 0;
margin: 0;
}
.activity-item {
display: flex;
align-items: center;
gap: 15px;
padding: 15px 0;
border-bottom: 1px solid #eee;
}
.activity-item:last-child {
border-bottom: none;
}
.activity-icon {
width: 40px;
height: 40px;
border-radius: 50%;
background: #f8f9ff;
display: flex;
align-items: center;
justify-content: center;
color: #43e97b;
}
.activity-content {
flex: 1;
}
.activity-title {
font-weight: 600;
color: #333;
margin-bottom: 5px;
}
.activity-time {
font-size: 0.9rem;
color: #999;
}
/* 响应式设<E5BC8F><E8AEBE>?*/
@media (max-width: 992px) { @media (max-width: 992px) {
.dashboard-container {
flex-direction: column;
}
.sidebar { .sidebar {
width: 100%; left: -var(--sidebar-width);
height: auto;
position: static;
padding: 20px 0;
} }
.sidebar-menu {
display: flex;
overflow-x: auto;
padding: 0 20px;
}
.sidebar-menu li {
flex-shrink: 0;
}
.sidebar-menu a {
padding: 10px 15px;
border-left: none;
border-bottom: 3px solid transparent;
}
.sidebar-menu a:hover,
.sidebar-menu a.active {
border-left-color: transparent;
border-bottom-color: white;
}
}
@media (max-width: 768px) {
.main-content { .main-content {
padding: 20px; margin-left: 0;
} }
.sidebar.active {
.content-header { left: 0;
flex-direction: column;
align-items: flex-start;
gap: 15px;
}
.function-grid {
grid-template-columns: 1fr;
}
.action-buttons {
flex-direction: column;
}
.action-btn {
justify-content: center;
} }
} }
</style> </style>
</head> </head>
<body> <body>
<!-- 顶部导航<EFBFBD><EFBFBD>?--> <!-- 侧边栏 -->
<nav class="navbar"> <div class="sidebar">
<div class="navbar-brand"> <div class="sidebar-header">
<i class="fas fa-graduation-cap"></i> <a href="#" class="sidebar-brand">
<span>XX学校成绩管理系统</span> <i class="fas fa-chalkboard-teacher"></i>
</div> <span>成绩管理系统</span>
<div class="navbar-menu">
<a href="/" class="btn btn-secondary">
<i class="fas fa-home"></i> 主页
</a> </a>
<div class="navbar-user">
<span class="user-name" id="userName">李老师</span>
<button id="logoutBtn" class="btn btn-primary">
<i class="fas fa-sign-out-alt"></i> 退<><E98080>? </button>
</div> </div>
<div class="user-profile">
<div class="user-avatar">
<i class="fas fa-user-tie"></i>
</div>
<div class="user-info text-white">
<h6 id="teacherName">加载中...</h6>
<p>教师 | <span id="teacherId">工号加载中...</span></p>
</div>
</div>
<nav class="nav-menu">
<div class="nav-item">
<a href="#" class="nav-link active">
<i class="fas fa-tachometer-alt"></i>
<span>教师仪表板</span>
</a>
</div>
<div class="nav-item">
<a href="#" class="nav-link">
<i class="fas fa-list-alt"></i>
<span>课程列表</span>
</a>
</div>
<div class="nav-item">
<a href="#" class="nav-link">
<i class="fas fa-user-edit"></i>
<span>个人资料</span>
</a>
</div>
<div class="nav-item mt-4">
<a href="javascript:void(0)" id="logoutBtn" class="nav-link text-warning">
<i class="fas fa-sign-out-alt"></i>
<span>退出登录</span>
</a>
</div> </div>
</nav> </nav>
</div>
<!-- 仪表板容<EFBFBD><EFBFBD>?--> <!-- 主内容 -->
<div class="dashboard-container"> <div class="main-content">
<!-- 左侧侧边<EFBFBD><EFBFBD>?--> <!-- 顶部导航 -->
<aside class="sidebar"> <div class="top-navbar">
<div class="sidebar-header"> <div class="page-heading">
<div class="user-info"> <h4>教师仪表板</h4>
<div class="user-avatar">
<i class="fas fa-chalkboard-teacher"></i>
</div> </div>
<div class="user-details"> <div class="d-flex align-items-center gap-3">
<h3 id="teacherName">李老师</h3> <div class="text-end d-none d-md-block">
<p>教师 | 部门<E983A8><E997A8>?span id="teacherDept">计算机学<E69CBA><E5ADA6>?/span></p> <div class="small text-muted" id="currentTime"></div>
<div class="fw-bold" id="userName">加载中...</div>
</div> </div>
<div class="vr mx-2 d-none d-md-block"></div>
<button class="btn btn-sm btn-light border rounded-pill px-3">
<i class="fas fa-bell text-secondary"></i>
</button>
</div> </div>
</div> </div>
<ul class="sidebar-menu"> <!-- 统计卡片 -->
<li> <div class="row g-4 mb-4">
<a href="#" class="active"> <div class="col-xl-4 col-md-6">
<i class="fas fa-tachometer-alt"></i> <div class="card stat-card h-100 p-3">
<span>仪表<EFBFBD><EFBFBD>?/span> <div class="d-flex justify-content-between align-items-start">
</a>
</li>
<li>
<a href="/teacher/grade_entry">
<i class="fas fa-edit"></i>
<span>成绩录入</span>
</a>
</li>
<li>
<a href="grade_query.html">
<i class="fas fa-search"></i>
<span>成绩查询</span>
</a>
</li>
<li>
<a href="grade_manage.html">
<i class="fas fa-cog"></i>
<span>成绩管理</span>
</a>
</li>
<li>
<a href="#">
<i class="fas fa-chart-bar"></i>
<span>统计分析</span>
</a>
</li>
<li>
<a href="#">
<i class="fas fa-download"></i>
<span>数据导出</span>
</a>
</li>
<li>
<a href="#">
<i class="fas fa-user"></i>
<span>个人信息</span>
</a>
</li>
</ul>
</aside>
<!-- 主内容区 -->
<main class="main-content">
<div class="content-header">
<div> <div>
<h1 class="page-title">教师仪表<EFBFBD><EFBFBD>?/h1> <p class="text-secondary small mb-1 fw-bold">负责课程</p>
<div class="breadcrumb"> <h3 class="mb-0 fw-bold" id="courseCount">0</h3>
<a href="/">主页</a> </div>
<i class="fas fa-chevron-right"></i> <div class="stat-icon bg-primary bg-opacity-10 text-primary">
<span>教师仪表<EFBFBD><EFBFBD>?/span> <i class="fas fa-book"></i>
</div> </div>
</div> </div>
<div class="current-time" id="currentTime"></div>
</div> </div>
<!-- 功能卡片 -->
<div class="function-grid">
<div class="function-card" onclick="window.location.href='grade_entry.html'">
<div class="function-icon">
<i class="fas fa-edit"></i>
</div> </div>
<h3 class="function-title">成绩录入</h3> <div class="col-xl-4 col-md-6">
<p class="function-description"> <div class="card stat-card h-100 p-3">
为学生录入新的课程成绩支持批量导入和单个录入<E5BD95><E585A5>? </p> <div class="d-flex justify-content-between align-items-start">
<button class="btn btn-primary">开始录<EFBFBD><EFBFBD>?/button> <div>
<p class="text-secondary small mb-1 fw-bold">授课学生总数</p>
<h3 class="mb-0 fw-bold" id="totalStudents">0</h3>
</div> </div>
<div class="stat-icon bg-success bg-opacity-10 text-success">
<div class="function-card" onclick="window.location.href='grade_query.html'"> <i class="fas fa-users"></i>
<div class="function-icon">
<i class="fas fa-search"></i>
</div> </div>
<h3 class="function-title">成绩查询</h3>
<p class="function-description">
查询学生成绩支持按班级、课程、学期等多维度筛选<E7AD9B><E98089>? </p>
<button class="btn btn-primary">开始查<EFBFBD><EFBFBD>?/button>
</div> </div>
<div class="function-card" onclick="window.location.href='grade_manage.html'">
<div class="function-icon">
<i class="fas fa-cog"></i>
</div> </div>
<h3 class="function-title">成绩管理</h3>
<p class="function-description">
修改或删除已录入的成绩管理成绩记录和状态<E78AB6><E68081>? </p>
<button class="btn btn-primary">开始管<EFBFBD><EFBFBD>?/button>
</div> </div>
<div class="col-xl-4 col-md-6">
<div class="function-card" onclick="window.location.href='#'"> <div class="card stat-card h-100 p-3">
<div class="function-icon"> <div class="d-flex justify-content-between align-items-start">
<i class="fas fa-chart-bar"></i> <div>
<p class="text-secondary small mb-1 fw-bold">待处理申请</p>
<h3 class="mb-0 fw-bold">0</h3>
</div>
<div class="stat-icon bg-warning bg-opacity-10 text-warning">
<i class="fas fa-clock"></i>
</div>
</div>
</div> </div>
<h3 class="function-title">统计分析</h3>
<p class="function-description">
查看成绩统计图表分析教学效果和学生表现<E8A1A8><E78EB0>? </p>
<button class="btn btn-primary">查看统计</button>
</div> </div>
</div> </div>
<!-- 快速操<EFBFBD><EFBFBD>?--> <!-- 课程列表 -->
<div class="quick-actions"> <div class="d-flex justify-content-between align-items-center mb-4">
<h2 class="section-title"> <h5 class="mb-0 fw-bold"><i class="fas fa-chalkboard me-2 text-primary"></i>我的负责课程</h5>
<i class="fas fa-bolt"></i> <button class="btn btn-sm btn-primary px-3">
快速操<E9809F><E6938D>? </h2> <i class="fas fa-plus me-1"></i> 新增课程
<div class="action-buttons"> </button>
<a href="/teacher/grade_entry" class="action-btn"> </div>
<i class="fas fa-plus"></i>
录入新成<E696B0><E68890>? </a> <div class="row" id="courseList">
<a href="grade_query.html" class="action-btn"> <!-- 课程数据将由 JavaScript 填充 -->
<i class="fas fa-search"></i> <div class="col-12 text-center py-5">
查询成绩 <div class="spinner-border text-primary" role="status"></div>
</a> <p class="mt-2 text-muted">课程数据加载中...</p>
<a href="#" class="action-btn"> </div>
<i class="fas fa-download"></i>
导出成绩<E68890><E7BBA9>? </a>
<a href="#" class="action-btn">
<i class="fas fa-chart-pie"></i>
生成统计报告
</a>
</div> </div>
</div> </div>
<!-- 最近活<EFBFBD><EFBFBD> <!-- Bootstrap 5 JS -->
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
<script src="/public/js/auth.js"></script>
<script src="/public/js/teacher.js"></script>
</body>
</html>

View File

@@ -1,24 +1,11 @@
@echo off @echo off
setlocal enabledelayedexpansion :: 使用简单的语法避免编码引起的解析错误
cd /d %~dp0
echo Checking if WebWork is already running...
:: 查找占用 3000 端口的进程 PID
for /f "tokens=5" %%a in ('netstat -ano ^| findstr :3000 ^| findstr LISTENING') do (
set PID=%%a
if not "!PID!"=="" (
echo Port 3000 is already in use by PID !PID!. Killing process...
taskkill /F /PID !PID!
)
)
echo Starting WebWork System...
cd ..\backend cd ..\backend
if not exist node_modules ( echo Checking port 3000...
echo node_modules not found, installing dependencies... for /f "tokens=5" %%a in ('netstat -ano ^| findstr :3000 ^| findstr LISTENING') do (
call npm install taskkill /F /PID %%a
) )
echo Starting Backend Server... echo Starting Backend Server...