/**
* 班级操行分管理系统 - 考勤管理页JS
*
* 开发者: Canglan
* 版权归属: Sea Network Technology Studio
*
* 版权所有 © Sea Network Technology Studio
*/
(function() {
'use strict';
let currentStatus = 'absent';
let studentsData = [];
let existingRecords = [];
// 考勤扣分配置映射(从后端配置注入)
const attendanceDeductionMap = {
absent: window.DEDUCTION_ATTENDANCE_ABSENT || 3,
late: window.DEDUCTION_ATTENDANCE_LATE || 1,
leave: window.DEDUCTION_ATTENDANCE_LEAVE || 0
};
// 初始化按钮文字
function initAttendanceButtons() {
const btnAbsent = document.getElementById('btnAbsent');
const btnLate = document.getElementById('btnLate');
const btnLeave = document.getElementById('btnLeave');
if (btnAbsent) btnAbsent.textContent = '缺勤(' + attendanceDeductionMap.absent + '分)';
if (btnLate) btnLate.textContent = '迟到(' + attendanceDeductionMap.late + '分)';
if (btnLeave) btnLeave.textContent = '请假(' + (attendanceDeductionMap.leave > 0 ? attendanceDeductionMap.leave + '分' : '不扣分') + ')';
if (attendanceDeductionMap.absent > 0) {
document.getElementById('customDeduction').value = attendanceDeductionMap.absent;
}
// 按权限组动态扣分上限限制自定义扣分输入
const limits = getScoreLimits();
const deductionInput = document.getElementById('customDeduction');
if (deductionInput) {
if (limits.max_subtract !== null && limits.max_subtract !== undefined) {
deductionInput.max = limits.max_subtract;
}
if (!limits.can_subtract) {
deductionInput.disabled = true;
}
}
}
function selectStatus(btn) {
document.querySelectorAll('.status-btn').forEach(b => b.classList.remove('active'));
btn.classList.add('active');
currentStatus = btn.dataset.status;
const defaultDeduction = attendanceDeductionMap[currentStatus] || 0;
if (defaultDeduction > 0) {
document.getElementById('customDeduction').value = defaultDeduction;
} else {
document.getElementById('customDeduction').value = '';
}
}
async function loadStudents() {
const res = await apiGet('/api/admin/students', {page_size: 1000});
if (res && res.success) {
studentsData = res.data.students;
renderStudentGrid();
await loadExistingRecords();
} else {
document.getElementById('studentGrid').innerHTML = '
加载学生列表失败
';
}
}
function renderStudentGrid() {
const currentSlot = document.getElementById('attendanceSlot').value;
let html = '';
studentsData.forEach(student => {
const hasRecord = existingRecords.some(r => r.student_id === student.student_id && r.slot === currentSlot);
html += `
${escapeHtml(student.name)}
${escapeHtml(student.student_no)}
`;
});
if (studentsData.length === 0) {
html = '暂无学生数据
';
}
document.getElementById('studentGrid').innerHTML = html;
}
function toggleStudent(cell) {
cell.classList.toggle('selected');
}
function selectAllStudents() {
document.querySelectorAll('.student-cell:not(.has-record)').forEach(cell => {
cell.classList.add('selected');
});
}
function deselectAllStudents() {
document.querySelectorAll('.student-cell').forEach(cell => {
cell.classList.remove('selected');
});
}
async function loadExistingRecords() {
const date = document.getElementById('attendanceDate').value;
const slot = document.getElementById('attendanceSlot').value;
const res = await apiGet('/api/admin/attendance/records', { date, slot });
if (res && res.success) {
existingRecords = res.data.records || [];
renderStudentGrid();
}
}
async function submitAttendance() {
const selectedCells = document.querySelectorAll('.student-cell.selected');
if (selectedCells.length === 0) {
showToast('请先选择有考勤异常的学生', 'warning');
return;
}
const date = document.getElementById('attendanceDate').value;
const slot = document.getElementById('attendanceSlot').value;
const reason = document.getElementById('attendanceReason').value;
const customDeduction = document.getElementById('customDeduction').value;
const customDeductionValue = customDeduction ? parseInt(customDeduction) : null;
const promises = [];
selectedCells.forEach(cell => {
const studentId = parseInt(cell.dataset.id);
const payload = {
student_id: studentId,
date: date,
slot: slot,
status: currentStatus,
reason: reason,
apply_deduction: true
};
if (customDeductionValue !== null && customDeductionValue > 0) {
payload.custom_deduction = customDeductionValue;
}
promises.push(apiPost('/api/admin/attendance', payload));
});
const results = await Promise.allSettled(promises);
const succeeded = results.filter(r => r.status === 'fulfilled' && r.value?.success).length;
const failed = results.length - succeeded;
if (failed === 0) {
showToast(`考勤提交成功(${succeeded}条)`);
} else {
showToast(`提交完成:成功${succeeded}条,失败${failed}条`, 'error');
}
deselectAllStudents();
await loadExistingRecords();
loadAttendanceRecords();
}
async function loadAttendanceRecords() {
const date = document.getElementById('attendanceDate').value;
const res = await apiGet('/api/admin/attendance/records', { date });
if (res && res.success) {
let html = '';
const records = res.data.records || [];
records.forEach(record => {
html += `
| ${escapeHtml(record.student_no)} |
${escapeHtml(record.student_name)} |
${getStatusBadge(record.status, 'attendance')} |
${escapeHtml(record.reason || '-')} |
${escapeHtml(record.recorder_name || '-')} |
${record.deduction_applied ? '已扣分' : '-'} |
`;
});
if (records.length === 0) {
html = '| 暂无考勤记录 |
';
}
document.getElementById('attendanceList').innerHTML = html;
}
}
// 日期或时段变化时重新加载
document.getElementById('attendanceDate').addEventListener('change', function() {
loadExistingRecords();
loadAttendanceRecords();
});
document.getElementById('attendanceSlot').addEventListener('change', function() {
loadExistingRecords();
});
// ========== 日期工具 ==========
function formatDateValue(d) {
const y = d.getFullYear();
const m = String(d.getMonth() + 1).padStart(2, '0');
const day = String(d.getDate()).padStart(2, '0');
return y + '-' + m + '-' + day;
}
// ========== 默认出勤(批量补全) ==========
function openDefaultAttendanceModal() {
const startInput = document.getElementById('defaultStartDate');
const endInput = document.getElementById('defaultEndDate');
if (!startInput.value) {
const today = new Date();
startInput.value = formatDateValue(new Date(today.getFullYear(), today.getMonth(), 1));
endInput.value = formatDateValue(today);
}
document.getElementById('defaultAttendanceModal').style.display = 'flex';
}
async function submitDefaultAttendance() {
const startDate = document.getElementById('defaultStartDate').value;
const endDate = document.getElementById('defaultEndDate').value;
const slots = Array.from(document.querySelectorAll('.defaultSlot:checked')).map(el => el.value);
if (!startDate || !endDate) {
showToast('请选择日期范围', 'warning');
return;
}
if (startDate > endDate) {
showToast('开始日期不能晚于结束日期', 'warning');
return;
}
if (slots.length === 0) {
showToast('请至少选择一个时段', 'warning');
return;
}
const btn = document.getElementById('defaultAttendanceBtn');
btn.disabled = true;
btn.textContent = '补全中...';
try {
const res = await apiPost('/api/admin/attendance/default', {
start_date: startDate,
end_date: endDate,
slots: slots
});
if (res && res.success) {
showToast(res.message || '默认出勤完成');
if (res.data && res.data.api_ok === false) {
setTimeout(function() {
showToast('节假日接口暂时不可用,本次仅按周末与手动设置判断', 'warning');
}, 500);
}
closeModal('defaultAttendanceModal');
await loadExistingRecords();
loadAttendanceRecords();
} else {
showToast((res && (res.message || res.detail)) || '默认出勤失败', 'error');
}
} catch (err) {
showToast('默认出勤失败:' + (err && err.message ? err.message : '未知错误'), 'error');
} finally {
btn.disabled = false;
btn.textContent = '开始补全';
}
}
// ========== 校历(节假日/补课) ==========
function openCalendarModal() {
const startInput = document.getElementById('calendarStartDate');
const endInput = document.getElementById('calendarEndDate');
if (!startInput.value) {
const year = new Date().getFullYear();
startInput.value = year + '-01-01';
endInput.value = year + '-12-31';
}
document.getElementById('calendarModal').style.display = 'flex';
loadCalendar();
}
async function loadCalendar() {
const startDate = document.getElementById('calendarStartDate').value;
const endDate = document.getElementById('calendarEndDate').value;
const area = document.getElementById('calendarListArea');
if (!startDate || !endDate || startDate > endDate) {
area.innerHTML = '请选择正确的日期范围
';
return;
}
area.innerHTML = '加载中...
';
const res = await apiGet('/api/admin/attendance/calendar', { start_date: startDate, end_date: endDate });
if (!res || !res.success) {
area.innerHTML = '' +
escapeHtml((res && res.message) || '加载失败') + '
';
return;
}
renderCalendar(res.data);
}
function renderCalendar(data) {
const holidays = (data && data.holidays) || {};
const workdays = (data && data.workdays) || {};
const manual = (data && data.manual) || {};
const items = [];
Object.keys(holidays).forEach(function(d) {
items.push({ date: d, type: 'holiday', label: '放假', name: holidays[d], manual: false });
});
Object.keys(workdays).forEach(function(d) {
items.push({ date: d, type: 'makeup', label: '调休', name: workdays[d], manual: false });
});
Object.keys(manual).forEach(function(d) {
items.push({
date: d,
type: manual[d].type,
label: manual[d].type === 'holiday' ? '放假' : '补课',
name: manual[d].note || '',
manual: true
});
});
items.sort(function(a, b) { return a.date < b.date ? -1 : (a.date > b.date ? 1 : 0); });
const area = document.getElementById('calendarListArea');
let html = '';
if (data && data.api_ok === false) {
html += '节假日接口暂时不可用,仅显示手动设置
';
}
if (items.length === 0) {
html += '范围内没有节假日/补课记录
';
}
items.forEach(function(item) {
const tagClass = item.type === 'holiday' ? 'calendar-tag-holiday' : 'calendar-tag-makeup';
html += '' +
'' + escapeHtml(item.date) + '' +
'' + item.label + '' +
'' + escapeHtml(item.name) + '' +
(item.manual
? '手动' +
''
: '接口') +
'
';
});
area.innerHTML = html;
}
async function addCalendarDay() {
const day = document.getElementById('calendarNewDate').value;
const dayType = document.getElementById('calendarNewType').value;
const note = document.getElementById('calendarNewNote').value.trim();
if (!day) {
showToast('请选择日期', 'warning');
return;
}
const res = await apiPost('/api/admin/attendance/calendar', {
date: day,
day_type: dayType,
note: note
});
if (res && res.success) {
showToast('已保存');
document.getElementById('calendarNewNote').value = '';
loadCalendar();
} else {
showToast((res && res.message) || '保存失败', 'error');
}
}
async function deleteCalendarDay(day) {
const res = await apiDelete('/api/admin/attendance/calendar?date=' + encodeURIComponent(day));
if (res && res.success) {
showToast('已删除');
loadCalendar();
} else {
showToast((res && res.message) || '删除失败', 'error');
}
}
// ========== 请假(整天) ==========
async function submitFullDayLeave() {
const selectedCells = document.querySelectorAll('.student-cell.selected');
if (selectedCells.length === 0) {
showToast('请先选择请假的学生', 'warning');
return;
}
const date = document.getElementById('attendanceDate').value;
if (!date) {
showToast('请选择日期', 'warning');
return;
}
if (!confirm('确定为选中的学生提交整天请假吗?(按当天实际考勤时段生成:正常上课日3条、假前半天1条、节前上课2条、返校晚修1条;每时段按请假扣分)')) return;
const studentIds = Array.from(selectedCells).map(cell => parseInt(cell.dataset.id));
const reason = document.getElementById('attendanceReason').value;
try {
const res = await apiPost('/api/admin/attendance/full-day-leave', {
date: date,
student_ids: studentIds,
reason: reason
});
if (res && res.success) {
showToast(res.message || '整天请假提交成功');
} else {
showToast((res && (res.message || res.detail)) || '提交失败', 'error');
}
} catch (err) {
showToast('提交失败:' + (err && err.message ? err.message : '未知错误'), 'error');
}
deselectAllStudents();
await loadExistingRecords();
loadAttendanceRecords();
}
// 页面初始化
initAttendanceButtons();
loadStudents();
loadAttendanceRecords();
window.selectStatus = selectStatus;
window.loadStudents = loadStudents;
window.toggleStudent = toggleStudent;
window.selectAllStudents = selectAllStudents;
window.deselectAllStudents = deselectAllStudents;
window.submitAttendance = submitAttendance;
window.loadAttendanceRecords = loadAttendanceRecords;
window.openDefaultAttendanceModal = openDefaultAttendanceModal;
window.submitDefaultAttendance = submitDefaultAttendance;
window.submitFullDayLeave = submitFullDayLeave;
window.openCalendarModal = openCalendarModal;
window.loadCalendar = loadCalendar;
window.addCalendarDay = addCalendarDay;
window.deleteCalendarDay = deleteCalendarDay;
})();