1. 权限重构:自定义权限组(14项功能权限+允许加分/加分上限/允许扣分/扣分上限),管理员账号绑定权限组,预置六组且班主任组锁定;全站前后端改为权限驱动,权限变更60秒内自动生效 2. 新增班主任导出学生名单(导出前自选字段) 3. 加减分/考勤上限改为按权限组动态校验,弹窗实时提示并限制输入 4. 导出按学期隔离(默认当前学期,可选历史/全部),历史导出不再受1000条限制 5. 新增管理端个人查询:基础分/加分/扣分/月度分/月度理由汇总及明细导出 6. 版本升级至4.0(sql/upgrades/v4.0.sql)
580 lines
19 KiB
JavaScript
580 lines
19 KiB
JavaScript
/**
|
||
* 班级操行分管理系统 - 公共JS
|
||
*
|
||
* 开发者: Canglan
|
||
* 联系方式: admin@sea-studio.top
|
||
* 版权归属: Sea Network Technology Studio
|
||
* 许可证: MIT License
|
||
*
|
||
* 版权所有 © Sea Network Technology Studio
|
||
*/
|
||
|
||
function getToken() {
|
||
return localStorage.getItem(window.JWT_STORAGE_KEY || 'class_system_token');
|
||
}
|
||
|
||
function getUserInfo() {
|
||
const userStr = localStorage.getItem(window.USER_STORAGE_KEY || 'class_system_user');
|
||
if (!userStr) return null;
|
||
try {
|
||
return JSON.parse(userStr);
|
||
} catch {
|
||
return null;
|
||
}
|
||
}
|
||
|
||
function setUserInfo(user) {
|
||
localStorage.setItem(window.USER_STORAGE_KEY || 'class_system_user', JSON.stringify(user));
|
||
}
|
||
|
||
function clearAuth() {
|
||
localStorage.removeItem(window.JWT_STORAGE_KEY || 'class_system_token');
|
||
localStorage.removeItem(window.USER_STORAGE_KEY || 'class_system_user');
|
||
}
|
||
|
||
async function apiRequest(url, options = {}) {
|
||
const token = getToken();
|
||
const headers = {
|
||
'Content-Type': 'application/json',
|
||
...options.headers
|
||
};
|
||
if (token) {
|
||
headers['Authorization'] = `Bearer ${token}`;
|
||
}
|
||
|
||
const baseUrl = window.API_BASE_URL;
|
||
const fullUrl = `${baseUrl}${url}`;
|
||
|
||
try {
|
||
const response = await fetch(fullUrl, { ...options, headers });
|
||
const data = await response.json();
|
||
|
||
if (response.status === 401) {
|
||
clearAuth();
|
||
|
||
// 同步清除 PHP Session,防止 index.php 302 重定向循环
|
||
try {
|
||
await fetch('/api/clear_session.php', {
|
||
method: 'POST',
|
||
headers: { 'Content-Type': 'application/json' }
|
||
});
|
||
} catch (e) {
|
||
console.warn('[Auth] 清除PHP Session失败:', e);
|
||
}
|
||
|
||
// 防循环机制:检查是否已在登录页
|
||
if (window.location.pathname === '/index.php' || window.location.pathname === '/') {
|
||
console.warn('[Auth] 已在登录页收到401,停止重定向');
|
||
return null;
|
||
}
|
||
|
||
// 防循环机制:5秒内重复401则停止重定向
|
||
const now = Date.now();
|
||
const lastRedirect = parseInt(sessionStorage.getItem('_last_401_redirect') || '0');
|
||
if (now - lastRedirect < 5000) {
|
||
console.warn('[Auth] 5秒内重复401,停止重定向。请检查Token是否有效。');
|
||
return null;
|
||
}
|
||
sessionStorage.setItem('_last_401_redirect', now.toString());
|
||
|
||
window.location.href = '/index.php';
|
||
return null;
|
||
}
|
||
return data;
|
||
} catch (error) {
|
||
console.error('API请求错误:', error);
|
||
showToast('网络错误,请稍后重试', 'error');
|
||
return null;
|
||
}
|
||
}
|
||
|
||
function apiGet(url, params = {}) {
|
||
const queryString = new URLSearchParams(params).toString();
|
||
const fullUrl = queryString ? `${url}?${queryString}` : url;
|
||
return apiRequest(fullUrl, { method: 'GET' });
|
||
}
|
||
|
||
function apiPost(url, data = {}) {
|
||
return apiRequest(url, {
|
||
method: 'POST',
|
||
body: JSON.stringify(data)
|
||
});
|
||
}
|
||
|
||
function apiPut(url, data = {}) {
|
||
return apiRequest(url, {
|
||
method: 'PUT',
|
||
body: JSON.stringify(data)
|
||
});
|
||
}
|
||
|
||
function apiDelete(url) {
|
||
return apiRequest(url, { method: 'DELETE' });
|
||
}
|
||
|
||
/**
|
||
* 分页拉取接口全部记录(用于导出等需要完整数据的场景)
|
||
* @param {string} url 接口地址
|
||
* @param {object} params 查询参数(page/page_size 会被自动覆盖)
|
||
* @returns {Promise<Array>} 全部记录
|
||
*/
|
||
async function apiGetAll(url, params = {}) {
|
||
const allRecords = [];
|
||
const pageSize = 1000;
|
||
let page = 1;
|
||
while (page <= 100) {
|
||
const pageParams = { ...params, page: page, page_size: pageSize };
|
||
const res = await apiGet(url, pageParams);
|
||
if (!res || !res.success || !res.data || !Array.isArray(res.data.records)) {
|
||
break;
|
||
}
|
||
allRecords.push(...res.data.records);
|
||
const total = res.data.total || 0;
|
||
if (allRecords.length >= total || res.data.records.length < pageSize) {
|
||
break;
|
||
}
|
||
page++;
|
||
}
|
||
return allRecords;
|
||
}
|
||
|
||
/**
|
||
* CSV字段转义
|
||
*/
|
||
function csvEscape(value) {
|
||
if (value === null || value === undefined) return '';
|
||
let str = String(value).replace(/[\r\n]+/g, ' ');
|
||
str = str.replace(/"/g, '""');
|
||
if (/[\,\;\"\s]/.test(str)) {
|
||
str = '"' + str + '"';
|
||
}
|
||
return str;
|
||
}
|
||
|
||
/**
|
||
* 下载CSV文件(自动添加BOM以兼容Excel)
|
||
*/
|
||
function downloadCsv(filename, csvContent) {
|
||
const blob = new Blob(['\uFEFF' + csvContent], { type: 'text/csv;charset=utf-8;' });
|
||
const url = URL.createObjectURL(blob);
|
||
const link = document.createElement('a');
|
||
link.href = url;
|
||
link.download = filename;
|
||
document.body.appendChild(link);
|
||
link.click();
|
||
document.body.removeChild(link);
|
||
URL.revokeObjectURL(url);
|
||
}
|
||
|
||
/**
|
||
* 加载学期下拉选项
|
||
* @param {string|HTMLElement} select 下拉框DOM或ID
|
||
* @param {object} options { includeAll: 是否包含"全部学期", selectedValue: 默认选中值 }
|
||
* @returns {Promise<Array>} 学期列表
|
||
*/
|
||
async function loadSemesterOptions(select, options = {}) {
|
||
const el = typeof select === 'string' ? document.getElementById(select) : select;
|
||
if (!el) return [];
|
||
const res = await apiGet('/api/semester/options');
|
||
const semesters = (res && res.success && Array.isArray(res.data)) ? res.data : [];
|
||
const sorted = semesters.slice().sort((a, b) => (b.is_active ? 1 : 0) - (a.is_active ? 1 : 0));
|
||
const includeAll = options.includeAll !== false;
|
||
let html = includeAll ? '<option value="">全部学期</option>' : '';
|
||
sorted.forEach(s => {
|
||
const suffix = s.is_active ? '(当前)' : (s.is_archived ? '(已归档)' : '');
|
||
html += '<option value="' + s.semester_id + '">' + escapeHtml(s.semester_name + suffix) + '</option>';
|
||
});
|
||
el.innerHTML = html;
|
||
let value = options.selectedValue;
|
||
if (value === undefined) {
|
||
const active = sorted.find(s => s.is_active);
|
||
value = active ? active.semester_id : '';
|
||
}
|
||
el.value = (value === null || value === undefined) ? '' : String(value);
|
||
return semesters;
|
||
}
|
||
|
||
/**
|
||
* 当前用户是否拥有指定权限
|
||
*/
|
||
function hasPermission(perm) {
|
||
return !!(window.USER_PERMISSIONS && window.USER_PERMISSIONS[perm]);
|
||
}
|
||
|
||
/**
|
||
* 当前权限组加减分上限配置
|
||
*/
|
||
function getScoreLimits() {
|
||
return window.USER_SCORE_LIMITS || {
|
||
can_add: true, max_add: null,
|
||
can_subtract: true, max_subtract: null
|
||
};
|
||
}
|
||
|
||
/**
|
||
* 生成加减分上限提示文本
|
||
*/
|
||
function describeScoreLimits() {
|
||
const limits = getScoreLimits();
|
||
if (!limits.can_add && !limits.can_subtract) return '当前权限组不允许加减分';
|
||
if (!limits.can_add) {
|
||
return '仅限扣分' + (limits.max_subtract ? (',单次最多扣' + limits.max_subtract + '分') : '');
|
||
}
|
||
if (!limits.can_subtract) {
|
||
return '仅限加分' + (limits.max_add ? (',单次最多加' + limits.max_add + '分') : '');
|
||
}
|
||
const parts = [];
|
||
parts.push(limits.max_add ? ('单次加分上限' + limits.max_add + '分') : '加分无限制');
|
||
parts.push(limits.max_subtract ? ('单次扣分上限' + limits.max_subtract + '分') : '扣分无限制');
|
||
return parts.join(',');
|
||
}
|
||
|
||
/**
|
||
* 将权限组上限应用到分数输入框(min/max)
|
||
*/
|
||
function applyScoreLimits(inputEl) {
|
||
if (!inputEl) return;
|
||
const limits = getScoreLimits();
|
||
if (limits.max_add !== null && limits.max_add !== undefined) {
|
||
inputEl.max = limits.max_add;
|
||
} else {
|
||
inputEl.removeAttribute('max');
|
||
}
|
||
if (limits.max_subtract !== null && limits.max_subtract !== undefined) {
|
||
inputEl.min = -limits.max_subtract;
|
||
} else {
|
||
inputEl.removeAttribute('min');
|
||
}
|
||
}
|
||
|
||
/**
|
||
* 校验分值是否符合权限组上限,返回错误信息(空字符串表示通过)
|
||
*/
|
||
function validateScoreChange(value) {
|
||
const limits = getScoreLimits();
|
||
if (!value || value === 0) return '分值不能为0';
|
||
if (value > 0) {
|
||
if (!limits.can_add) return '当前权限组仅允许扣分';
|
||
if (limits.max_add !== null && limits.max_add !== undefined && value > limits.max_add) {
|
||
return '单次加分不能超过' + limits.max_add + '分';
|
||
}
|
||
} else {
|
||
if (!limits.can_subtract) return '当前权限组仅允许加分';
|
||
if (limits.max_subtract !== null && limits.max_subtract !== undefined && Math.abs(value) > limits.max_subtract) {
|
||
return '单次扣分不能超过' + limits.max_subtract + '分';
|
||
}
|
||
}
|
||
return '';
|
||
}
|
||
|
||
function showToast(message, type = 'success') {
|
||
const toast = document.createElement('div');
|
||
toast.className = `toast toast-${type}`;
|
||
toast.textContent = message;
|
||
document.body.appendChild(toast);
|
||
setTimeout(() => toast.remove(), 3000);
|
||
}
|
||
|
||
function formatDate(dateStr) {
|
||
if (!dateStr) return '-';
|
||
const date = new Date(dateStr);
|
||
return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`;
|
||
}
|
||
|
||
function formatDateTime(dateStr) {
|
||
if (!dateStr) return '-';
|
||
const date = new Date(dateStr);
|
||
return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')} ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}`;
|
||
}
|
||
|
||
function getStatusBadge(status, type = 'attendance') {
|
||
const statusMap = {
|
||
attendance: {
|
||
'present': '出勤',
|
||
'absent': '缺勤',
|
||
'late': '迟到',
|
||
'leave': '请假'
|
||
}
|
||
};
|
||
const texts = statusMap[type] || statusMap.attendance;
|
||
const text = texts[status] || status;
|
||
let className = 'status-badge ';
|
||
switch (status) {
|
||
case 'present':
|
||
className += 'status-submitted';
|
||
break;
|
||
case 'absent':
|
||
className += 'status-not_submitted';
|
||
break;
|
||
case 'late':
|
||
className += 'status-late';
|
||
break;
|
||
case 'leave':
|
||
className += 'status-leave';
|
||
break;
|
||
default:
|
||
className += 'status-not_submitted';
|
||
}
|
||
return `<span class="${className}">${text}</span>`;
|
||
}
|
||
|
||
async function logout() {
|
||
// 清除 PHP Session
|
||
try {
|
||
await fetch('/api/clear_session.php', {
|
||
method: 'POST',
|
||
headers: { 'Content-Type': 'application/json' }
|
||
});
|
||
} catch (e) {
|
||
console.warn('清除Session失败', e);
|
||
}
|
||
|
||
// 清除后端 Token
|
||
try {
|
||
await apiPost('/api/auth/logout');
|
||
} catch (e) {
|
||
console.warn('后端登出失败', e);
|
||
}
|
||
|
||
// 清除 localStorage
|
||
clearAuth();
|
||
|
||
// 跳转回登录页
|
||
window.location.href = '/index.php';
|
||
}
|
||
|
||
function escapeHtml(str) {
|
||
if (!str) return '';
|
||
return String(str)
|
||
.replace(/&/g, '\x26amp;')
|
||
.replace(/</g, '\x26lt;')
|
||
.replace(/>/g, '\x26gt;')
|
||
.replace(/"/g, '\x26quot;')
|
||
.replace(/'/g, '\x26#x27;');
|
||
}
|
||
|
||
/**
|
||
* 智能分页渲染(最多显示7个页码 + 跳转输入框)
|
||
* @param {string|HTMLElement} container - 分页容器ID或DOM元素
|
||
* @param {number} currentPage - 当前页码
|
||
* @param {number} totalPages - 总页数
|
||
* @param {function} onPageChange - 页码变化回调函数,参数为新的页码
|
||
*/
|
||
function renderSmartPagination(container, currentPage, totalPages, onPageChange) {
|
||
if (typeof container === 'string') {
|
||
container = document.getElementById(container);
|
||
}
|
||
if (!container || totalPages <= 1) {
|
||
if (container) container.innerHTML = '';
|
||
return;
|
||
}
|
||
|
||
const MAX_VISIBLE = 7;
|
||
let html = '';
|
||
|
||
// 上一页按钮
|
||
if (currentPage > 1) {
|
||
html += `<a href="#" class="page-nav" data-page="${currentPage - 1}">« 上一页</a>`;
|
||
}
|
||
|
||
if (totalPages <= MAX_VISIBLE) {
|
||
// 总页数不超过最大显示数,全部显示
|
||
for (let i = 1; i <= totalPages; i++) {
|
||
if (i === currentPage) {
|
||
html += `<span class="active">${i}</span>`;
|
||
} else {
|
||
html += `<a href="#" data-page="${i}">${i}</a>`;
|
||
}
|
||
}
|
||
} else {
|
||
// 需要省略号
|
||
// 始终显示第1页
|
||
if (currentPage === 1) {
|
||
html += `<span class="active">1</span>`;
|
||
} else {
|
||
html += `<a href="#" data-page="1">1</a>`;
|
||
}
|
||
|
||
// 计算中间页码范围
|
||
let start = Math.max(2, currentPage - 2);
|
||
let end = Math.min(totalPages - 1, currentPage + 2);
|
||
|
||
// 调整确保中间至少有3个页码(加上首尾共5-7个)
|
||
if (currentPage <= 3) {
|
||
end = Math.min(5, totalPages - 1);
|
||
}
|
||
if (currentPage >= totalPages - 2) {
|
||
start = Math.max(2, totalPages - 4);
|
||
}
|
||
|
||
// 前省略号
|
||
if (start > 2) {
|
||
html += `<span class="ellipsis">...</span>`;
|
||
}
|
||
|
||
// 中间页码
|
||
for (let i = start; i <= end; i++) {
|
||
if (i === currentPage) {
|
||
html += `<span class="active">${i}</span>`;
|
||
} else {
|
||
html += `<a href="#" data-page="${i}">${i}</a>`;
|
||
}
|
||
}
|
||
|
||
// 后省略号
|
||
if (end < totalPages - 1) {
|
||
html += `<span class="ellipsis">...</span>`;
|
||
}
|
||
|
||
// 始终显示最后一页
|
||
if (currentPage === totalPages) {
|
||
html += `<span class="active">${totalPages}</span>`;
|
||
} else {
|
||
html += `<a href="#" data-page="${totalPages}">${totalPages}</a>`;
|
||
}
|
||
}
|
||
|
||
// 下一页按钮
|
||
if (currentPage < totalPages) {
|
||
html += `<a href="#" class="page-nav" data-page="${currentPage + 1}">下一页 »</a>`;
|
||
}
|
||
|
||
// 页码跳转
|
||
html += `<span class="page-jump">跳至 <input type="number" min="1" max="${totalPages}" placeholder="页码"> / ${totalPages}页</span>`;
|
||
|
||
container.innerHTML = html;
|
||
|
||
// 绑定页码点击事件
|
||
container.querySelectorAll('a[data-page]').forEach(link => {
|
||
link.addEventListener('click', function(e) {
|
||
e.preventDefault();
|
||
const page = parseInt(this.dataset.page);
|
||
if (page && page !== currentPage && page >= 1 && page <= totalPages) {
|
||
onPageChange(page);
|
||
}
|
||
});
|
||
});
|
||
|
||
// 绑定跳转输入框事件
|
||
const jumpInput = container.querySelector('.page-jump input');
|
||
if (jumpInput) {
|
||
jumpInput.addEventListener('keydown', function(e) {
|
||
if (e.key === 'Enter') {
|
||
e.preventDefault();
|
||
const page = parseInt(this.value);
|
||
if (page && page >= 1 && page <= totalPages) {
|
||
onPageChange(page);
|
||
} else {
|
||
showToast(`请输入1-${totalPages}之间的页码`, 'warning');
|
||
}
|
||
}
|
||
});
|
||
}
|
||
}
|
||
|
||
document.addEventListener('DOMContentLoaded', () => {
|
||
const user = getUserInfo();
|
||
const userNameSpan = document.getElementById('userName');
|
||
if (userNameSpan && user) {
|
||
userNameSpan.textContent = user.real_name || user.username;
|
||
}
|
||
const logoutBtn = document.getElementById('logoutBtn');
|
||
if (logoutBtn) {
|
||
logoutBtn.addEventListener('click', logout);
|
||
}
|
||
});
|
||
|
||
function toggleActionDropdown(el) {
|
||
var dropdown = el.closest('.action-dropdown');
|
||
if (!dropdown) return;
|
||
var menu = dropdown.querySelector('.action-dropdown-menu');
|
||
if (!menu) return;
|
||
|
||
var isOpen = menu.classList.contains('show');
|
||
// 先关闭所有
|
||
closeAllDropdowns();
|
||
|
||
if (!isOpen) {
|
||
// 使用 fixed 定位,避免被 overflow 容器裁剪
|
||
var rect = el.getBoundingClientRect();
|
||
// 先显示以便测量高度
|
||
menu.classList.add('show');
|
||
menu.style.position = 'fixed';
|
||
menu.style.bottom = 'auto';
|
||
menu.style.right = 'auto';
|
||
menu.style.transform = 'none';
|
||
var menuHeight = menu.offsetHeight;
|
||
// 智能判断:按钮在上半部分则菜单显示在下方,否则显示在上方
|
||
if (rect.top < window.innerHeight / 2) {
|
||
menu.style.top = rect.bottom + 'px';
|
||
} else {
|
||
menu.style.top = (rect.top - menuHeight) + 'px';
|
||
}
|
||
menu.style.left = Math.min(rect.left, window.innerWidth - 130) + 'px';
|
||
el.classList.add('open');
|
||
}
|
||
}
|
||
|
||
function closeAllDropdowns() {
|
||
document.querySelectorAll('.action-dropdown-menu.show').forEach(function(m) {
|
||
m.classList.remove('show');
|
||
m.style.position = '';
|
||
m.style.left = '';
|
||
m.style.top = '';
|
||
m.style.bottom = '';
|
||
m.style.right = '';
|
||
m.style.transform = '';
|
||
var toggle = m.closest('.action-dropdown');
|
||
if (toggle) {
|
||
var btn = toggle.querySelector('.action-dropdown-toggle');
|
||
if (btn) btn.classList.remove('open');
|
||
}
|
||
});
|
||
}
|
||
|
||
document.addEventListener('click', function(e) {
|
||
if (!e.target.closest('.action-dropdown')) {
|
||
closeAllDropdowns();
|
||
}
|
||
});
|
||
|
||
// 全局textarea键盘事件:Enter提交表单,Ctrl+Enter换行
|
||
document.addEventListener('keydown', function(e) {
|
||
if (e.target.tagName !== 'TEXTAREA') return;
|
||
|
||
if (e.key === 'Enter' && !e.ctrlKey && !e.shiftKey && !e.metaKey) {
|
||
// Enter键提交表单
|
||
e.preventDefault();
|
||
var form = e.target.closest('form');
|
||
if (form) {
|
||
// 触发form的submit事件
|
||
var submitEvent = new Event('submit', { cancelable: true, bubbles: true });
|
||
form.dispatchEvent(submitEvent);
|
||
}
|
||
}
|
||
// Ctrl+Enter和Shift+Enter保持默认换行行为(不拦截)
|
||
});
|
||
|
||
window.selectDeductionType = function(points, reason) {
|
||
var pointsEl = document.getElementById('pointsChange');
|
||
var reasonEl = document.getElementById('pointsReason');
|
||
if (points === 0 && reason === '') {
|
||
// 自定义模式 - 清空分值和原因,聚焦原因输入框
|
||
if (pointsEl) pointsEl.value = '';
|
||
if (reasonEl) {
|
||
reasonEl.value = '';
|
||
reasonEl.focus();
|
||
}
|
||
} else if (points === null || points === undefined) {
|
||
// 类别模式 - 仅填充原因,聚焦分值输入框
|
||
if (reasonEl) reasonEl.value = reason;
|
||
if (pointsEl) {
|
||
pointsEl.value = '';
|
||
pointsEl.focus();
|
||
}
|
||
} else {
|
||
// 预设模式 - 同时填充分值和原因
|
||
if (pointsEl) pointsEl.value = points;
|
||
if (reasonEl) reasonEl.value = reason;
|
||
}
|
||
}; |