/** * 班级操行分管理系统 - 公共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 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(); // FastAPI 参数校验错误(422)统一转为可读 message if (data && !data.success && !data.message && data.detail) { if (Array.isArray(data.detail)) { data.message = data.detail.map(item => { const field = Array.isArray(item.loc) ? item.loc.filter(p => p !== 'body').join('.') : ''; return (field ? field + ': ' : '') + (item.msg || '参数错误'); }).join(';'); } else if (typeof data.detail === 'string') { data.message = data.detail; } } 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} 全部记录 */ 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} 学期列表 */ 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 ? '' : ''; sorted.forEach(s => { const suffix = s.is_active ? '(当前)' : (s.is_archived ? '(已归档)' : ''); html += ''; }); 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 `${text}`; } 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, '\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 += `« 上一页`; } if (totalPages <= MAX_VISIBLE) { // 总页数不超过最大显示数,全部显示 for (let i = 1; i <= totalPages; i++) { if (i === currentPage) { html += `${i}`; } else { html += `${i}`; } } } else { // 需要省略号 // 始终显示第1页 if (currentPage === 1) { html += `1`; } else { html += `1`; } // 计算中间页码范围 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 += `...`; } // 中间页码 for (let i = start; i <= end; i++) { if (i === currentPage) { html += `${i}`; } else { html += `${i}`; } } // 后省略号 if (end < totalPages - 1) { html += `...`; } // 始终显示最后一页 if (currentPage === totalPages) { html += `${totalPages}`; } else { html += `${totalPages}`; } } // 下一页按钮 if (currentPage < totalPages) { html += `下一页 »`; } // 页码跳转 html += `跳至 / ${totalPages}页`; 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; } };