整天请假按当天实际考勤时段提交(修复常规周五生成3条的问题)
1. 新增后端接口 /api/admin/attendance/full-day-leave:按作息判断当天实际时段后再提交请假 2. 时段规则:正常上课日3段、放假前一天1段(仅上午)、节前上课2段(早+中)、返校晚修1段 3. 每时段按"请假"配置扣分;已有对应时段记录会更新为请假 4. 前端整天请假改为调用新接口;文档同步
This commit is contained in:
1 parent
ad50f82c7b
commit
97f2de5d83
5 files changed
+165
-69
No files matched your search
+33
-1
@@ -29,7 +29,7 @@ from utils.redis_client import RedisClient
|
|||||||
from schemas.admin import (
|
from schemas.admin import (
|
||||||
AddPointsRequest, RevokeRequest, AddAdminRequest,
|
AddPointsRequest, RevokeRequest, AddAdminRequest,
|
||||||
AddStudentRequest, UpdateStudentRequest,
|
AddStudentRequest, UpdateStudentRequest,
|
||||||
AddAttendanceRequest, DefaultAttendanceRequest, CalendarDayRequest,
|
AddAttendanceRequest, DefaultAttendanceRequest, FullDayLeaveRequest, CalendarDayRequest,
|
||||||
HomeworkRegisterRequest,
|
HomeworkRegisterRequest,
|
||||||
UpdateAdminRequest, ResetPasswordRequest,
|
UpdateAdminRequest, ResetPasswordRequest,
|
||||||
UnlockUserRequest, PermissionGroupRequest, EmailTestRequest,
|
UnlockUserRequest, PermissionGroupRequest, EmailTestRequest,
|
||||||
@@ -594,6 +594,38 @@ async def default_attendance(request: Request, req: DefaultAttendanceRequest):
|
|||||||
return error_response(message=result["message"])
|
return error_response(message=result["message"])
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("/attendance/full-day-leave")
|
||||||
|
async def full_day_leave(request: Request, req: FullDayLeaveRequest):
|
||||||
|
"""整天请假:按当天实际考勤时段提交请假(正常日3段/假前1段/节前上课2段/返校晚修1段)"""
|
||||||
|
user = await get_current_user(request)
|
||||||
|
if not await PermissionChecker.check_permission(user["user_id"], "manage_attendance"):
|
||||||
|
return error_response(message="无考勤管理权限", code=403)
|
||||||
|
result = await AttendanceService.full_day_leave(
|
||||||
|
date_str=str(req.date),
|
||||||
|
student_ids=req.student_ids,
|
||||||
|
reason=req.reason,
|
||||||
|
recorder_id=user["user_id"]
|
||||||
|
)
|
||||||
|
if result["success"]:
|
||||||
|
data = result.get("data", {})
|
||||||
|
try:
|
||||||
|
await LogService.write_operation_log(
|
||||||
|
operator_id=user["user_id"], operator_name=user["real_name"],
|
||||||
|
operator_role=await PermissionChecker.get_user_role(user["user_id"]) or "管理员",
|
||||||
|
operation_type="add_attendance", target_type="attendance",
|
||||||
|
details=(
|
||||||
|
f"全天请假: {req.date}, {data.get('students', 0)}人 × "
|
||||||
|
f"{len(data.get('slots', []))}时段, 共{data.get('created', 0)}条"
|
||||||
|
),
|
||||||
|
ip=request.client.host
|
||||||
|
)
|
||||||
|
except Exception as e:
|
||||||
|
logger.error(f"写入全天请假日志失败: {e}")
|
||||||
|
return success_response(data=data, message=result["message"])
|
||||||
|
else:
|
||||||
|
return error_response(message=result["message"])
|
||||||
|
|
||||||
|
|
||||||
@router.get("/attendance/calendar")
|
@router.get("/attendance/calendar")
|
||||||
async def get_attendance_calendar(
|
async def get_attendance_calendar(
|
||||||
request: Request,
|
request: Request,
|
||||||
|
|||||||
@@ -81,6 +81,13 @@ class DefaultAttendanceRequest(BaseModel):
|
|||||||
slots: Optional[List[str]] = Field(None, description="时段列表(morning/afternoon/evening),默认全部")
|
slots: Optional[List[str]] = Field(None, description="时段列表(morning/afternoon/evening),默认全部")
|
||||||
|
|
||||||
|
|
||||||
|
class FullDayLeaveRequest(BaseModel):
|
||||||
|
"""整天请假请求"""
|
||||||
|
date: date
|
||||||
|
student_ids: List[int] = Field(..., min_length=1, max_length=200, description="请假学生ID列表")
|
||||||
|
reason: Optional[str] = Field(None, max_length=255, description="原因")
|
||||||
|
|
||||||
|
|
||||||
class CalendarDayRequest(BaseModel):
|
class CalendarDayRequest(BaseModel):
|
||||||
"""校历手动设置请求"""
|
"""校历手动设置请求"""
|
||||||
date: date
|
date: date
|
||||||
|
|||||||
@@ -239,6 +239,98 @@ class AttendanceService:
|
|||||||
return True
|
return True
|
||||||
return day.weekday() < 5
|
return day.weekday() < 5
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def _slots_for_date(
|
||||||
|
day: date,
|
||||||
|
calendar_info: Dict[str, Any],
|
||||||
|
selected_slots: Optional[list] = None
|
||||||
|
) -> list:
|
||||||
|
"""按学校常规作息返回某天实际考勤时段
|
||||||
|
|
||||||
|
- 上课日且次日仍上课:所选时段(早/中/晚)
|
||||||
|
- 放假前一天(次日不上课):仅上午;手动设为 pre_holiday 时按早+中
|
||||||
|
- 返校日(非上课日、次日上课):仅晚修
|
||||||
|
- 其他休息日:无
|
||||||
|
"""
|
||||||
|
selected = [s for s in (selected_slots or VALID_SLOTS) if s in VALID_SLOTS]
|
||||||
|
next_day = day + timedelta(days=1)
|
||||||
|
school_today = AttendanceService._is_school_day(day, calendar_info)
|
||||||
|
school_next = AttendanceService._is_school_day(next_day, calendar_info)
|
||||||
|
|
||||||
|
if school_today:
|
||||||
|
if school_next:
|
||||||
|
return list(selected)
|
||||||
|
manual_type = calendar_info['manual'].get(day.isoformat(), {}).get('type')
|
||||||
|
if manual_type == 'pre_holiday':
|
||||||
|
return [s for s in selected if s in ('morning', 'afternoon')]
|
||||||
|
return [s for s in selected if s == 'morning']
|
||||||
|
if school_next:
|
||||||
|
return [s for s in selected if s == 'evening']
|
||||||
|
return []
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
async def full_day_leave(
|
||||||
|
date_str: str,
|
||||||
|
student_ids: list,
|
||||||
|
reason: Optional[str],
|
||||||
|
recorder_id: int
|
||||||
|
) -> Dict[str, Any]:
|
||||||
|
"""全天请假:按当天实际考勤时段为选中学生提交请假(每个时段按请假配置扣分)"""
|
||||||
|
try:
|
||||||
|
day = date.fromisoformat(date_str)
|
||||||
|
except ValueError:
|
||||||
|
return {"success": False, "message": "日期格式不正确"}
|
||||||
|
if not student_ids:
|
||||||
|
return {"success": False, "message": "请选择请假的学生"}
|
||||||
|
if len(student_ids) > 200:
|
||||||
|
return {"success": False, "message": "单次最多选择200名学生"}
|
||||||
|
|
||||||
|
calendar_info = await AttendanceService.get_calendar(
|
||||||
|
date_str, (day + timedelta(days=1)).isoformat()
|
||||||
|
)
|
||||||
|
slots = AttendanceService._slots_for_date(day, calendar_info)
|
||||||
|
if not slots:
|
||||||
|
return {"success": False, "message": "该日期没有考勤时段(休息日)"}
|
||||||
|
|
||||||
|
created_count = 0
|
||||||
|
last_error = None
|
||||||
|
for student_id in student_ids:
|
||||||
|
for slot in slots:
|
||||||
|
result = await AttendanceService.add_attendance(
|
||||||
|
student_id=student_id,
|
||||||
|
date=date_str,
|
||||||
|
status='leave',
|
||||||
|
reason=reason,
|
||||||
|
apply_deduction=True,
|
||||||
|
recorder_id=recorder_id,
|
||||||
|
custom_deduction=None,
|
||||||
|
slot=slot
|
||||||
|
)
|
||||||
|
if result.get("success"):
|
||||||
|
created_count += 1
|
||||||
|
else:
|
||||||
|
last_error = result.get("message", "未知错误")
|
||||||
|
|
||||||
|
if created_count == 0:
|
||||||
|
return {"success": False, "message": last_error or "提交失败"}
|
||||||
|
|
||||||
|
per_student = len(slots) * settings.DEDUCTION_ATTENDANCE_LEAVE
|
||||||
|
points_text = f",每人{per_student}分" if per_student > 0 else ""
|
||||||
|
logger.info(
|
||||||
|
f"用户[{recorder_id}] 全天请假 {date_str}: {len(student_ids)}人 × {len(slots)}时段"
|
||||||
|
f"({','.join(slots)}), 共{created_count}条"
|
||||||
|
)
|
||||||
|
return {
|
||||||
|
"success": True,
|
||||||
|
"message": f"整天请假提交成功:{len(student_ids)}人 × {len(slots)}个时段,共{created_count}条{points_text}",
|
||||||
|
"data": {
|
||||||
|
"slots": slots,
|
||||||
|
"created": created_count,
|
||||||
|
"students": len(student_ids),
|
||||||
|
"deduction_per_student": per_student
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
async def batch_default_attendance(
|
async def batch_default_attendance(
|
||||||
start_date: str,
|
start_date: str,
|
||||||
@@ -285,38 +377,20 @@ class AttendanceService:
|
|||||||
rest_days = 0
|
rest_days = 0
|
||||||
cursor_day = start
|
cursor_day = start
|
||||||
while cursor_day <= end:
|
while cursor_day <= end:
|
||||||
next_day = cursor_day + timedelta(days=1)
|
slots_today = AttendanceService._slots_for_date(cursor_day, calendar_info, selected_slots)
|
||||||
school_today = AttendanceService._is_school_day(cursor_day, calendar_info)
|
if slots_today:
|
||||||
school_next = AttendanceService._is_school_day(next_day, calendar_info)
|
school_today = AttendanceService._is_school_day(cursor_day, calendar_info)
|
||||||
|
school_next = AttendanceService._is_school_day(cursor_day + timedelta(days=1), calendar_info)
|
||||||
if school_today:
|
if school_today and school_next:
|
||||||
manual_type = calendar_info['manual'].get(cursor_day.isoformat(), {}).get('type')
|
|
||||||
if school_next:
|
|
||||||
slots_today = list(selected_slots)
|
|
||||||
full_days += 1
|
full_days += 1
|
||||||
elif manual_type == 'pre_holiday':
|
elif school_today:
|
||||||
# 例外:假前需下午上课(早+中,无晚修),不按半天处理
|
half_days += 1
|
||||||
slots_today = [s for s in selected_slots if s in ('morning', 'afternoon')]
|
elif school_next:
|
||||||
if slots_today:
|
|
||||||
half_days += 1
|
|
||||||
else:
|
|
||||||
rest_days += 1
|
|
||||||
else:
|
|
||||||
slots_today = [s for s in selected_slots if s == 'morning']
|
|
||||||
if slots_today:
|
|
||||||
half_days += 1
|
|
||||||
else:
|
|
||||||
rest_days += 1
|
|
||||||
if slots_today:
|
|
||||||
day_slots.append((cursor_day, slots_today))
|
|
||||||
else:
|
|
||||||
slots_today = [s for s in selected_slots if s == 'evening'] if school_next else []
|
|
||||||
if slots_today:
|
|
||||||
return_evenings += 1
|
return_evenings += 1
|
||||||
day_slots.append((cursor_day, slots_today))
|
day_slots.append((cursor_day, slots_today))
|
||||||
else:
|
else:
|
||||||
rest_days += 1
|
rest_days += 1
|
||||||
cursor_day = next_day
|
cursor_day += timedelta(days=1)
|
||||||
|
|
||||||
if not day_slots:
|
if not day_slots:
|
||||||
return {"success": False, "message": "所选范围内没有需要默认出勤的时段(均为休息日或未选对应时段)"}
|
return {"success": False, "message": "所选范围内没有需要默认出勤的时段(均为休息日或未选对应时段)"}
|
||||||
|
|||||||
+7
-3
@@ -163,11 +163,15 @@
|
|||||||
7. 点击"提交考勤"批量提交
|
7. 点击"提交考勤"批量提交
|
||||||
|
|
||||||
#### 请假(整天)
|
#### 请假(整天)
|
||||||
用于"请一整天假"的常见情况,一键标记三个时段:
|
按学生**当天实际考勤时段**一键请假(不再固定 3 条):
|
||||||
|
|
||||||
1. 在学生方格中**点击选择**请假的学生
|
1. 在学生方格中**点击选择**请假的学生
|
||||||
2. 点击工具栏"请假(整天)"按钮
|
2. 点击工具栏"请假(整天)"按钮,系统按当天作息提交:
|
||||||
3. 确认后系统按 **早上 / 中午 / 晚修** 各提交一条请假记录(每个时段按"请假"扣分,若请假扣1分则一天共3分)
|
- 正常上课日(次日仍上课)→ **早/中/晚 3 条**
|
||||||
|
- 放假前一天(半天)→ **仅上午 1 条**
|
||||||
|
- 节前上课(校历手动标记"节前上课(早+中)")→ **早+中 2 条**
|
||||||
|
- 返校日晚修 → **晚修 1 条**
|
||||||
|
3. 每个时段按"请假"配置扣分(如 1 分/次:半天 1 分、正常日 3 分)
|
||||||
|
|
||||||
> 已有的对应时段记录会被更新为请假;如需只标记某个时段,仍用普通"请假"按钮 + 时段选择。
|
> 已有的对应时段记录会被更新为请假;如需只标记某个时段,仍用普通"请假"按钮 + 时段选择。
|
||||||
|
|
||||||
|
|||||||
@@ -389,45 +389,24 @@ async function submitFullDayLeave() {
|
|||||||
showToast('请选择日期', 'warning');
|
showToast('请选择日期', 'warning');
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
if (!confirm('确定为选中的学生提交整天请假吗?(按当天实际考勤时段生成:正常上课日3条、假前半天1条、节前上课2条、返校晚修1条;每时段按请假扣分)')) return;
|
||||||
|
|
||||||
// 整天请假 = 早/中/晚 三个时段,各按"请假"扣分
|
const studentIds = Array.from(selectedCells).map(cell => parseInt(cell.dataset.id));
|
||||||
const perDeduction = attendanceDeductionMap.leave || 0;
|
|
||||||
const totalPerStudent = perDeduction * 3;
|
|
||||||
const confirmText = perDeduction > 0
|
|
||||||
? '确定为选中的学生提交整天请假吗?(早/中/晚各扣' + perDeduction + '分,共' + totalPerStudent + '分/人)'
|
|
||||||
: '确定为选中的学生提交整天请假吗?(早/中/晚三个时段)';
|
|
||||||
if (!confirm(confirmText)) return;
|
|
||||||
|
|
||||||
const reason = document.getElementById('attendanceReason').value;
|
const reason = document.getElementById('attendanceReason').value;
|
||||||
const slots = ['morning', 'afternoon', 'evening'];
|
|
||||||
const promises = [];
|
|
||||||
|
|
||||||
selectedCells.forEach(cell => {
|
try {
|
||||||
const studentId = parseInt(cell.dataset.id);
|
const res = await apiPost('/api/admin/attendance/full-day-leave', {
|
||||||
slots.forEach(slot => {
|
date: date,
|
||||||
const payload = {
|
student_ids: studentIds,
|
||||||
student_id: studentId,
|
reason: reason
|
||||||
date: date,
|
|
||||||
slot: slot,
|
|
||||||
status: 'leave',
|
|
||||||
reason: reason,
|
|
||||||
apply_deduction: true
|
|
||||||
};
|
|
||||||
if (perDeduction > 0) {
|
|
||||||
payload.custom_deduction = perDeduction;
|
|
||||||
}
|
|
||||||
promises.push(apiPost('/api/admin/attendance', payload));
|
|
||||||
});
|
});
|
||||||
});
|
if (res && res.success) {
|
||||||
|
showToast(res.message || '整天请假提交成功');
|
||||||
const results = await Promise.allSettled(promises);
|
} else {
|
||||||
const succeeded = results.filter(r => r.status === 'fulfilled' && r.value?.success).length;
|
showToast((res && (res.message || res.detail)) || '提交失败', 'error');
|
||||||
const failed = results.length - succeeded;
|
}
|
||||||
|
} catch (err) {
|
||||||
if (failed === 0) {
|
showToast('提交失败:' + (err && err.message ? err.message : '未知错误'), 'error');
|
||||||
showToast(`整天请假提交成功(${succeeded}条` + (perDeduction > 0 ? `,${totalPerStudent}分/人` : '') + ')');
|
|
||||||
} else {
|
|
||||||
showToast(`提交完成:成功${succeeded}条,失败${failed}条`, 'error');
|
|
||||||
}
|
}
|
||||||
|
|
||||||
deselectAllStudents();
|
deselectAllStudents();
|
||||||
|
|||||||
Reference in new issue
Block a user