Skip to content
GitLab
Menu
Projects
Groups
Snippets
Loading...
Help
Help
Support
Community forum
Keyboard shortcuts
?
Submit feedback
Contribute to GitLab
Sign in
Toggle navigation
Menu
Open sidebar
邬吉朋
practical_train
Commits
9e0dacc7
Commit
9e0dacc7
authored
Aug 10, 2026
by
wujipeng
Browse files
Merge remote-tracking branch 'origin/dev-v1.0' into dev-v1.0
parents
4ff3e0e4
1ea1a030
Changes
91
Show whitespace changes
Inline
Side-by-side
practical-business/src/main/java/com/platform/business/service/ClassSubjectAttendanceSessionService.java
0 → 100644
View file @
9e0dacc7
package
com.platform.business.service
;
import
com.baomidou.mybatisplus.extension.service.IService
;
import
com.platform.business.model.entity.ClassSubjectAttendanceSessionEntity
;
public
interface
ClassSubjectAttendanceSessionService
extends
IService
<
ClassSubjectAttendanceSessionEntity
>
{
}
practical-business/src/main/java/com/platform/business/service/LeaveManagementService.java
0 → 100644
View file @
9e0dacc7
package
com.platform.business.service
;
import
com.platform.business.model.dto.LeaveApplyDTO
;
import
com.platform.business.model.dto.LeaveQueryDTO
;
import
com.platform.business.model.dto.LeaveReviewDTO
;
import
com.platform.business.model.vo.LeaveApplicationVO
;
import
java.util.List
;
public
interface
LeaveManagementService
{
LeaveApplicationVO
apply
(
LeaveApplyDTO
request
,
String
studentId
);
LeaveApplicationVO
update
(
LeaveApplyDTO
request
,
String
studentId
);
boolean
withdraw
(
String
leaveId
,
String
studentId
);
LeaveApplicationVO
review
(
String
leaveId
,
LeaveReviewDTO
request
,
String
approverId
,
String
approverRole
);
List
<
LeaveApplicationVO
>
queryApplications
(
LeaveQueryDTO
query
);
LeaveApplicationVO
studentDetail
(
String
leaveId
,
String
studentId
);
LeaveApplicationVO
teacherDetail
(
String
leaveId
,
String
teacherId
);
LeaveApplicationVO
adminDetail
(
String
leaveId
);
}
practical-business/src/main/java/com/platform/business/service/TeachingResourceService.java
0 → 100644
View file @
9e0dacc7
package
com.platform.business.service
;
import
com.baomidou.mybatisplus.extension.service.IService
;
import
com.platform.business.model.dto.TeachingResourceDTO
;
import
com.platform.business.model.entity.TeachingResourceEntity
;
import
com.platform.business.model.entity.UserEntity
;
import
com.platform.business.model.vo.TeachingResourceStatisticsVO
;
import
com.platform.business.model.vo.TeachingResourceVO
;
import
org.springframework.web.multipart.MultipartFile
;
import
java.util.List
;
/**
* 教学资源业务接口,分别提供管理员全量视角和学生本人班级视角。
*/
public
interface
TeachingResourceService
extends
IService
<
TeachingResourceEntity
>
{
/** 查询管理员端资源列表。 */
List
<
TeachingResourceVO
>
adminList
(
TeachingResourceDTO
query
);
/** 查询指定学生所在班级课程关联的资源列表。 */
List
<
TeachingResourceVO
>
studentList
(
String
userId
,
TeachingResourceDTO
query
);
/** 统计所有未删除的教学资源。 */
TeachingResourceStatisticsVO
adminStatistics
();
/** 统计指定学生有权查看的教学资源。 */
TeachingResourceStatisticsVO
studentStatistics
(
String
userId
);
/** 上传文件并创建与课程绑定的教学资源记录。 */
TeachingResourceVO
upload
(
MultipartFile
file
,
String
resourceName
,
Integer
courseId
,
UserEntity
uploader
);
/** 只修改资源名称及绑定课程,不替换文件。 */
boolean
updateResource
(
TeachingResourceDTO
resource
);
/** 同时逻辑删除教学资源记录和文件记录,保留物理文件。 */
boolean
deleteResource
(
String
id
);
/** 管理员下载资源并累计下载次数。 */
void
adminDownload
(
String
id
);
/** 校验学生班级课程权限后下载资源并累计下载次数。 */
void
studentDownload
(
String
id
,
String
userId
);
}
practical-business/src/main/java/com/platform/business/service/TrainingRoomBookingService.java
0 → 100644
View file @
9e0dacc7
package
com.platform.business.service
;
import
com.baomidou.mybatisplus.extension.service.IService
;
import
com.platform.business.model.dto.TrainingRoomBookingCreateDTO
;
import
com.platform.business.model.dto.TrainingRoomBookingDTO
;
import
com.platform.business.model.entity.TrainingRoomBookingEntity
;
import
com.platform.business.model.entity.UserEntity
;
import
com.platform.business.model.vo.TrainingRoomBookingDetailVO
;
import
com.platform.business.model.vo.TrainingRoomBookingStatisticsVO
;
import
com.platform.business.model.vo.TrainingRoomBookingVO
;
import
com.platform.business.model.vo.TrainingRoomSeatVO
;
import
com.platform.business.model.vo.TrainingRoomTimeSlotVO
;
import
java.util.List
;
/** 学员与管理员共用的预约业务服务。 */
public
interface
TrainingRoomBookingService
extends
IService
<
TrainingRoomBookingEntity
>
{
/** 管理员分页查询全部预约记录。 */
List
<
TrainingRoomBookingVO
>
adminList
(
TrainingRoomBookingDTO
query
);
/** 学员分页查询自己的预约记录。 */
List
<
TrainingRoomBookingVO
>
studentList
(
String
studentId
,
TrainingRoomBookingDTO
query
);
/** 管理员查看预约详情和完整操作记录。 */
TrainingRoomBookingDetailVO
adminDetail
(
String
id
);
/** 学员查看自己的预约详情和操作记录。 */
TrainingRoomBookingDetailVO
studentDetail
(
String
id
,
String
studentId
);
/** 获取指定实训室各预约状态的统计数量。 */
TrainingRoomBookingStatisticsVO
adminStatistics
(
String
roomId
);
/** 管理员查看指定日期和时段的机位状态,已停用实训室也可查看。 */
List
<
TrainingRoomSeatVO
>
adminAvailability
(
String
roomId
,
String
bookingDate
,
Integer
slotCode
);
/** 学员查看运行中实训室在可预约日期、时段下的全部机位状态。 */
List
<
TrainingRoomSeatVO
>
availability
(
String
roomId
,
String
bookingDate
,
Integer
slotCode
);
/** 获取系统支持的五个固定预约时段。 */
List
<
TrainingRoomTimeSlotVO
>
timeSlots
();
/** 创建预约,并执行机位冲突、学员冲突和数据库并发约束校验。 */
TrainingRoomBookingVO
createBooking
(
TrainingRoomBookingCreateDTO
request
,
UserEntity
student
);
/** 学员取消本人尚未开始的预约。 */
boolean
studentCancel
(
String
id
,
UserEntity
student
);
/** 学员提前结束本人使用中的预约。 */
boolean
studentSignOut
(
String
id
,
UserEntity
student
);
/** 管理员取消尚未开始的预约。 */
boolean
adminCancel
(
String
id
,
UserEntity
administrator
);
/** 管理员结束使用中的预约。 */
boolean
adminEnd
(
String
id
,
UserEntity
administrator
);
/** 定时任务和查询入口共同调用,用于补偿更新预约状态。 */
void
synchronizeBookingStatuses
();
}
practical-business/src/main/java/com/platform/business/service/TrainingRoomSeatService.java
0 → 100644
View file @
9e0dacc7
package
com.platform.business.service
;
import
com.baomidou.mybatisplus.extension.service.IService
;
import
com.platform.business.model.entity.TrainingRoomSeatEntity
;
/** 机位基础数据服务。 */
public
interface
TrainingRoomSeatService
extends
IService
<
TrainingRoomSeatEntity
>
{
/** 按新的机位总数启用、停用或补充编号连续的机位。 */
void
synchronizeSeats
(
String
roomId
,
Integer
seatCount
);
}
practical-business/src/main/java/com/platform/business/service/TrainingRoomService.java
0 → 100644
View file @
9e0dacc7
package
com.platform.business.service
;
import
com.baomidou.mybatisplus.extension.service.IService
;
import
com.platform.business.model.dto.TrainingRoomDTO
;
import
com.platform.business.model.entity.TrainingRoomEntity
;
import
com.platform.business.model.vo.TrainingRoomStatisticsVO
;
import
com.platform.business.model.vo.TrainingRoomVO
;
import
java.util.Date
;
import
java.util.List
;
/** 实训室管理服务。 */
public
interface
TrainingRoomService
extends
IService
<
TrainingRoomEntity
>
{
/** 管理员分页查询实训室,包含运行中和已停用状态。 */
List
<
TrainingRoomVO
>
adminList
(
TrainingRoomDTO
query
,
Date
now
);
/** 学员分页查询运行中的实训室。 */
List
<
TrainingRoomVO
>
studentList
(
TrainingRoomDTO
query
,
Date
now
);
/** 查询实训室详情及当前动态机位统计。 */
TrainingRoomVO
detail
(
String
id
,
Date
now
);
/** 获取管理员端实训室KPI。 */
TrainingRoomStatisticsVO
adminStatistics
(
Date
now
);
/** 获取学员端运行中实训室KPI。 */
TrainingRoomStatisticsVO
studentStatistics
(
Date
now
);
/** 创建实训室并同步生成连续机位编号。 */
TrainingRoomVO
createRoom
(
TrainingRoomDTO
room
);
/** 编辑实训室基本信息并同步机位数量。 */
boolean
updateRoom
(
TrainingRoomDTO
room
);
/** 单独启用或停用实训室;停用前检查未结束预约。 */
boolean
updateStatus
(
String
id
,
String
status
);
}
practical-business/src/main/java/com/platform/business/service/impl/AttendanceServiceImpl.java
0 → 100644
View file @
9e0dacc7
package
com.platform.business.service.impl
;
import
com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper
;
import
com.baomidou.mybatisplus.core.toolkit.IdWorker
;
import
com.platform.business.config.AttendanceProperties
;
import
com.platform.business.constant.AttendanceConstants
;
import
com.platform.business.mapper.ClassSubjectAttendanceMapper
;
import
com.platform.business.mapper.ClassSubjectAttendanceSessionMapper
;
import
com.platform.business.model.dto.AttendanceCheckInDTO
;
import
com.platform.business.model.dto.AttendanceQueryDTO
;
import
com.platform.business.model.dto.AttendanceStatusUpdateDTO
;
import
com.platform.business.model.entity.ClassEntity
;
import
com.platform.business.model.entity.ClassStudentEntity
;
import
com.platform.business.model.entity.ClassSubjectAttendanceEntity
;
import
com.platform.business.model.entity.ClassSubjectAttendanceSessionEntity
;
import
com.platform.business.model.entity.ClassSubjectEntity
;
import
com.platform.business.model.entity.UserEntity
;
import
com.platform.business.model.vo.AttendanceRecordVO
;
import
com.platform.business.model.vo.AttendanceSessionVO
;
import
com.platform.business.model.vo.AttendanceSummaryVO
;
import
com.platform.business.service.AttendanceService
;
import
com.platform.business.service.ClassService
;
import
com.platform.business.service.ClassStudentService
;
import
com.platform.business.service.ClassSubjectAttendanceService
;
import
com.platform.business.service.ClassSubjectAttendanceSessionService
;
import
com.platform.business.service.ClassSubjectService
;
import
com.platform.business.service.UserService
;
import
com.platform.business.util.ClassSubjectTimeUtils
;
import
com.platform.business.util.IpNetworkMatcher
;
import
com.platform.exception.BusinessException
;
import
lombok.extern.slf4j.Slf4j
;
import
org.springframework.stereotype.Service
;
import
org.springframework.transaction.annotation.Transactional
;
import
javax.annotation.Resource
;
import
java.math.BigDecimal
;
import
java.nio.charset.StandardCharsets
;
import
java.security.MessageDigest
;
import
java.security.SecureRandom
;
import
java.util.ArrayList
;
import
java.util.Calendar
;
import
java.util.Date
;
import
java.util.HashSet
;
import
java.util.List
;
import
java.util.Locale
;
import
java.util.Set
;
@Service
@Slf4j
public
class
AttendanceServiceImpl
implements
AttendanceService
{
private
static
final
SecureRandom
RANDOM
=
new
SecureRandom
();
@Resource
private
AttendanceProperties
attendanceProperties
;
@Resource
private
ClassSubjectService
classSubjectService
;
@Resource
private
ClassStudentService
classStudentService
;
@Resource
private
ClassSubjectAttendanceService
attendanceRecordService
;
@Resource
private
ClassSubjectAttendanceSessionService
attendanceSessionService
;
@Resource
private
ClassSubjectAttendanceMapper
attendanceMapper
;
@Resource
private
ClassSubjectAttendanceSessionMapper
attendanceSessionMapper
;
@Resource
private
UserService
userService
;
@Resource
private
ClassService
classService
;
@Override
@Transactional
public
AttendanceSessionVO
startClass
(
Integer
subjectId
,
String
teacherId
)
{
ClassSubjectEntity
subject
=
requireSubject
(
subjectId
);
requireTeacher
(
subject
,
teacherId
);
ClassSubjectAttendanceSessionEntity
existing
=
findSession
(
subjectId
);
if
(
existing
!=
null
)
{
if
(
existing
.
getVerificationCode
()
==
null
)
{
throw
new
BusinessException
(
"课程已结束,不能开始上课"
);
}
return
toSessionVO
(
existing
,
subject
);
}
ClassSubjectTimeUtils
.
TimeWindow
window
=
ClassSubjectTimeUtils
.
resolve
(
subject
);
Date
now
=
new
Date
();
if
(
now
.
before
(
window
.
getStart
()))
{
throw
new
BusinessException
(
"尚未到课程计划开始时间,不能开始上课"
);
}
if
(!
now
.
before
(
window
.
getEnd
()))
{
throw
new
BusinessException
(
"课程已结束,不能开始上课"
);
}
ClassSubjectAttendanceSessionEntity
session
=
new
ClassSubjectAttendanceSessionEntity
();
session
.
setSubjectId
(
subjectId
);
session
.
setTeacherId
(
teacherId
);
session
.
setVerificationCode
(
String
.
format
(
"%06d"
,
RANDOM
.
nextInt
(
1_000_000
)));
session
.
setScheduledStartTime
(
window
.
getStart
());
session
.
setScheduledEndTime
(
window
.
getEnd
());
session
.
setStartedAt
(
now
);
session
.
setCodeExpiresAt
(
addMinutes
(
window
.
getStart
(),
attendanceProperties
.
getVerificationCodeValidMinutes
()));
session
.
setStatus
(
AttendanceConstants
.
SESSION_ACTIVE
);
session
.
setCreatedTime
(
now
);
session
.
setUpdateTime
(
now
);
session
.
setId
(
IdWorker
.
getIdStr
());
if
(
attendanceSessionMapper
.
insertIgnore
(
session
)
==
0
)
{
session
=
findSession
(
subjectId
);
if
(
session
==
null
)
{
throw
new
BusinessException
(
"开始上课失败,请稍后重试"
);
}
}
return
toSessionVO
(
session
,
subject
);
}
@Override
@Transactional
public
AttendanceRecordVO
checkIn
(
AttendanceCheckInDTO
request
,
String
studentId
,
String
clientIp
)
{
if
(
request
==
null
||
request
.
getSubjectId
()
==
null
)
{
throw
new
BusinessException
(
"课程ID不能为空"
);
}
ClassSubjectEntity
subject
=
requireSubject
(
request
.
getSubjectId
());
requireStudentInClass
(
subject
.
getClassId
(),
studentId
);
ClassSubjectTimeUtils
.
TimeWindow
window
=
ClassSubjectTimeUtils
.
resolve
(
subject
);
Date
now
=
new
Date
();
if
(
now
.
before
(
window
.
getStart
()))
{
throw
new
BusinessException
(
"课程尚未开始,不能签到"
);
}
if
(!
now
.
before
(
window
.
getEnd
()))
{
finalizeSubject
(
subject
,
window
,
now
);
throw
new
BusinessException
(
"课程已结束,未签到记录已转为缺勤"
);
}
ClassSubjectAttendanceSessionEntity
session
=
findSession
(
subject
.
getId
());
if
(
session
==
null
||
!
AttendanceConstants
.
SESSION_ACTIVE
.
equals
(
session
.
getStatus
()))
{
throw
new
BusinessException
(
"教师尚未开始上课,暂不能签到"
);
}
if
(!
IpNetworkMatcher
.
matchesAny
(
clientIp
,
attendanceProperties
.
getAllowedIpCidrs
()))
{
throw
new
BusinessException
(
"当前IP不在允许签到的网段内"
);
}
ClassSubjectAttendanceEntity
existing
=
findRecord
(
subject
.
getId
(),
studentId
);
if
(
existing
!=
null
)
{
if
(
AttendanceConstants
.
isPresent
(
existing
.
getStatus
()))
{
return
requireRecordVO
(
subject
.
getId
(),
studentId
);
}
throw
new
BusinessException
(
"当前出勤状态为"
+
existing
.
getStatus
()
+
",不能重复签到"
);
}
boolean
afterCodeWindow
=
now
.
after
(
session
.
getCodeExpiresAt
());
String
status
;
String
method
;
if
(
afterCodeWindow
)
{
status
=
AttendanceConstants
.
STATUS_LATE
;
method
=
AttendanceConstants
.
METHOD_IP_ONLY
;
}
else
{
String
code
=
request
.
getVerificationCode
()
==
null
?
""
:
request
.
getVerificationCode
().
trim
();
if
(!
code
.
matches
(
"\\d{6}"
))
{
throw
new
BusinessException
(
"请输入教师提供的6位数字验证码"
);
}
if
(!
constantTimeEquals
(
code
,
session
.
getVerificationCode
()))
{
throw
new
BusinessException
(
"签到验证码不正确"
);
}
status
=
AttendanceConstants
.
STATUS_NORMAL
;
method
=
AttendanceConstants
.
METHOD_IP_CODE
;
}
ClassSubjectAttendanceEntity
record
=
new
ClassSubjectAttendanceEntity
();
record
.
setSubjectId
(
subject
.
getId
());
record
.
setUserId
(
studentId
);
record
.
setCheckInTime
(
now
);
record
.
setStatus
(
status
);
record
.
setCheckInMethod
(
method
);
record
.
setCheckInIp
(
clientIp
);
record
.
setTeacherConfirmed
(
false
);
record
.
setCreatedTime
(
now
);
record
.
setUpdateTime
(
now
);
record
.
setId
(
IdWorker
.
getIdStr
());
if
(
attendanceMapper
.
insertIgnore
(
record
)
==
0
)
{
ClassSubjectAttendanceEntity
concurrentRecord
=
findRecord
(
subject
.
getId
(),
studentId
);
if
(
concurrentRecord
!=
null
&&
AttendanceConstants
.
isPresent
(
concurrentRecord
.
getStatus
()))
{
return
requireRecordVO
(
subject
.
getId
(),
studentId
);
}
throw
new
BusinessException
(
"当前课程已有请假或缺勤记录,不能签到"
);
}
return
requireRecordVO
(
subject
.
getId
(),
studentId
);
}
@Override
@Transactional
public
AttendanceRecordVO
updateStatus
(
AttendanceStatusUpdateDTO
request
,
String
teacherId
)
{
if
(
request
==
null
||
request
.
getSubjectId
()
==
null
||
isBlank
(
request
.
getStudentId
()))
{
throw
new
BusinessException
(
"课程ID和学员ID不能为空"
);
}
String
status
=
request
.
getStatus
()
==
null
?
null
:
request
.
getStatus
().
trim
().
toUpperCase
(
Locale
.
ROOT
);
if
(!
AttendanceConstants
.
isTeacherAdjustableStatus
(
status
))
{
throw
new
BusinessException
(
"教师只能设置 NORMAL、LATE 或 ABSENT"
);
}
ClassSubjectEntity
subject
=
requireSubject
(
request
.
getSubjectId
());
requireTeacher
(
subject
,
teacherId
);
requireStudentInClass
(
subject
.
getClassId
(),
request
.
getStudentId
());
Date
now
=
new
Date
();
ClassSubjectTimeUtils
.
TimeWindow
window
=
ClassSubjectTimeUtils
.
resolve
(
subject
);
if
(
now
.
before
(
window
.
getStart
()))
{
throw
new
BusinessException
(
"课程尚未开始,不能调整出勤状态"
);
}
ClassSubjectAttendanceEntity
record
=
findRecord
(
subject
.
getId
(),
request
.
getStudentId
());
if
(
record
!=
null
&&
AttendanceConstants
.
STATUS_LEAVE
.
equals
(
record
.
getStatus
()))
{
throw
new
BusinessException
(
"请假状态由请假模块维护,教师不能在出勤接口中覆盖"
);
}
if
(
record
==
null
)
{
record
=
new
ClassSubjectAttendanceEntity
();
record
.
setId
(
IdWorker
.
getIdStr
());
record
.
setSubjectId
(
subject
.
getId
());
record
.
setUserId
(
request
.
getStudentId
());
record
.
setCheckInMethod
(
AttendanceConstants
.
METHOD_TEACHER
);
record
.
setCreatedTime
(
now
);
if
(!
AttendanceConstants
.
STATUS_ABSENT
.
equals
(
status
))
{
record
.
setCheckInTime
(
now
);
}
}
else
if
(!
AttendanceConstants
.
STATUS_ABSENT
.
equals
(
status
)
&&
record
.
getCheckInTime
()
==
null
)
{
record
.
setCheckInTime
(
now
);
}
record
.
setStatus
(
status
);
record
.
setTeacherConfirmed
(
true
);
record
.
setConfirmedBy
(
teacherId
);
record
.
setConfirmedAt
(
now
);
record
.
setUpdateTime
(
now
);
attendanceMapper
.
upsertTeacherStatus
(
record
);
AttendanceRecordVO
result
=
requireRecordVO
(
subject
.
getId
(),
request
.
getStudentId
());
if
(
AttendanceConstants
.
STATUS_LEAVE
.
equals
(
result
.
getStatus
()))
{
throw
new
BusinessException
(
"请假状态由请假模块维护,教师不能在出勤接口中覆盖"
);
}
return
result
;
}
@Override
public
List
<
AttendanceRecordVO
>
teacherRoster
(
Integer
subjectId
,
String
teacherId
)
{
ClassSubjectEntity
subject
=
requireSubject
(
subjectId
);
requireTeacher
(
subject
,
teacherId
);
ClassSubjectTimeUtils
.
TimeWindow
window
=
ClassSubjectTimeUtils
.
resolve
(
subject
);
if
(!
new
Date
().
before
(
window
.
getEnd
()))
{
finalizeSubject
(
subject
,
window
,
new
Date
());
}
return
attendanceMapper
.
queryTeacherRoster
(
subjectId
);
}
@Override
public
List
<
AttendanceRecordVO
>
queryRecords
(
AttendanceQueryDTO
query
)
{
AttendanceQueryDTO
safeQuery
=
prepareQuery
(
query
);
return
attendanceMapper
.
queryRecords
(
safeQuery
);
}
@Override
public
AttendanceSummaryVO
querySummary
(
AttendanceQueryDTO
query
)
{
AttendanceQueryDTO
safeQuery
=
prepareQuery
(
query
);
finalizeEndedSubjects
(
safeQuery
.
getStartDate
(),
safeQuery
.
getEndDate
());
AttendanceSummaryVO
summary
=
attendanceMapper
.
querySummary
(
safeQuery
);
if
(
summary
==
null
)
{
summary
=
new
AttendanceSummaryVO
();
summary
.
setAttendanceRate
(
BigDecimal
.
ZERO
);
}
else
if
(
summary
.
getAttendanceRate
()
==
null
)
{
summary
.
setAttendanceRate
(
BigDecimal
.
ZERO
);
}
summary
.
setStudentStatistics
(
attendanceMapper
.
queryStudentStatistics
(
safeQuery
));
summary
.
setCourseStatistics
(
attendanceMapper
.
queryCourseStatistics
(
safeQuery
));
return
summary
;
}
@Override
@Transactional
public
void
finalizeEndedSubjects
(
Date
startDate
,
Date
endDate
)
{
Date
[]
range
=
normalizeRange
(
startDate
,
endDate
);
List
<
ClassSubjectEntity
>
subjects
=
classSubjectService
.
list
(
new
LambdaQueryWrapper
<
ClassSubjectEntity
>()
.
ge
(
ClassSubjectEntity:
:
getDate
,
range
[
0
])
.
le
(
ClassSubjectEntity:
:
getDate
,
range
[
1
]));
Date
now
=
new
Date
();
for
(
ClassSubjectEntity
subject
:
subjects
)
{
try
{
ClassSubjectTimeUtils
.
TimeWindow
window
=
ClassSubjectTimeUtils
.
resolve
(
subject
);
if
(!
now
.
before
(
window
.
getEnd
()))
{
finalizeSubject
(
subject
,
window
,
now
);
}
}
catch
(
BusinessException
e
)
{
log
.
warn
(
"跳过无法解析上课时段的课程,subjectId={}, reason={}"
,
subject
.
getId
(),
e
.
getMessage
());
}
}
}
private
void
finalizeSubject
(
ClassSubjectEntity
subject
,
ClassSubjectTimeUtils
.
TimeWindow
window
,
Date
now
)
{
ClassSubjectAttendanceSessionEntity
session
=
findSession
(
subject
.
getId
());
if
(
session
==
null
)
{
session
=
new
ClassSubjectAttendanceSessionEntity
();
session
.
setSubjectId
(
subject
.
getId
());
session
.
setTeacherId
(
subject
.
getTeacherId
());
session
.
setScheduledStartTime
(
window
.
getStart
());
session
.
setScheduledEndTime
(
window
.
getEnd
());
session
.
setStatus
(
AttendanceConstants
.
SESSION_ENDED
);
session
.
setCreatedTime
(
now
);
session
.
setUpdateTime
(
now
);
session
.
setId
(
IdWorker
.
getIdStr
());
if
(
attendanceSessionMapper
.
insertIgnore
(
session
)
==
0
)
{
session
=
findSession
(
subject
.
getId
());
}
}
else
if
(!
AttendanceConstants
.
SESSION_ENDED
.
equals
(
session
.
getStatus
()))
{
session
.
setStatus
(
AttendanceConstants
.
SESSION_ENDED
);
session
.
setUpdateTime
(
now
);
attendanceSessionService
.
updateById
(
session
);
}
List
<
ClassStudentEntity
>
students
=
classStudentService
.
list
(
new
LambdaQueryWrapper
<
ClassStudentEntity
>().
eq
(
ClassStudentEntity:
:
getClassId
,
subject
.
getClassId
()));
List
<
ClassSubjectAttendanceEntity
>
existing
=
attendanceRecordService
.
list
(
new
LambdaQueryWrapper
<
ClassSubjectAttendanceEntity
>()
.
eq
(
ClassSubjectAttendanceEntity:
:
getSubjectId
,
subject
.
getId
()));
Set
<
String
>
recordedUsers
=
new
HashSet
<>();
for
(
ClassSubjectAttendanceEntity
record
:
existing
)
{
recordedUsers
.
add
(
record
.
getUserId
());
}
List
<
ClassSubjectAttendanceEntity
>
absences
=
new
ArrayList
<>();
for
(
ClassStudentEntity
student
:
students
)
{
if
(
recordedUsers
.
contains
(
student
.
getUserId
()))
{
continue
;
}
ClassSubjectAttendanceEntity
absence
=
new
ClassSubjectAttendanceEntity
();
absence
.
setSubjectId
(
subject
.
getId
());
absence
.
setUserId
(
student
.
getUserId
());
absence
.
setStatus
(
AttendanceConstants
.
STATUS_ABSENT
);
absence
.
setCheckInMethod
(
AttendanceConstants
.
METHOD_SYSTEM
);
absence
.
setTeacherConfirmed
(
false
);
absence
.
setCreatedTime
(
now
);
absence
.
setUpdateTime
(
now
);
absence
.
setId
(
IdWorker
.
getIdStr
());
absences
.
add
(
absence
);
}
if
(!
absences
.
isEmpty
())
{
attendanceMapper
.
insertAbsencesIgnore
(
absences
);
}
}
private
AttendanceSessionVO
toSessionVO
(
ClassSubjectAttendanceSessionEntity
session
,
ClassSubjectEntity
subject
)
{
AttendanceSessionVO
result
=
new
AttendanceSessionVO
();
result
.
setSessionId
(
session
.
getId
());
result
.
setSubjectId
(
subject
.
getId
());
result
.
setSubjectName
(
subject
.
getSubjectName
());
result
.
setTeacherId
(
subject
.
getTeacherId
());
result
.
setVerificationCode
(
session
.
getVerificationCode
());
result
.
setScheduledStartTime
(
session
.
getScheduledStartTime
());
result
.
setScheduledEndTime
(
session
.
getScheduledEndTime
());
result
.
setStartedAt
(
session
.
getStartedAt
());
result
.
setCodeExpiresAt
(
session
.
getCodeExpiresAt
());
result
.
setStatus
(
session
.
getStatus
());
ClassEntity
classEntity
=
classService
.
getById
(
subject
.
getClassId
());
if
(
classEntity
!=
null
)
{
result
.
setClassName
(
classEntity
.
getName
());
}
UserEntity
teacher
=
userService
.
getById
(
subject
.
getTeacherId
());
if
(
teacher
!=
null
)
{
result
.
setTeacherName
(
teacher
.
getNickName
());
result
.
setTeacherPhone
(
teacher
.
getPhoneNumber
());
}
return
result
;
}
private
AttendanceRecordVO
requireRecordVO
(
Integer
subjectId
,
String
studentId
)
{
AttendanceQueryDTO
query
=
new
AttendanceQueryDTO
();
query
.
setSubjectId
(
subjectId
);
query
.
setUserId
(
studentId
);
List
<
AttendanceRecordVO
>
records
=
attendanceMapper
.
queryRecords
(
query
);
if
(
records
.
isEmpty
())
{
throw
new
BusinessException
(
"签到记录保存失败"
);
}
return
records
.
get
(
0
);
}
private
ClassSubjectEntity
requireSubject
(
Integer
subjectId
)
{
if
(
subjectId
==
null
)
{
throw
new
BusinessException
(
"课程ID不能为空"
);
}
ClassSubjectEntity
subject
=
classSubjectService
.
getById
(
subjectId
);
if
(
subject
==
null
)
{
throw
new
BusinessException
(
"课程不存在"
);
}
return
subject
;
}
private
void
requireTeacher
(
ClassSubjectEntity
subject
,
String
teacherId
)
{
if
(
isBlank
(
teacherId
)
||
!
teacherId
.
equals
(
subject
.
getTeacherId
()))
{
throw
new
BusinessException
(
"只有本课程授课教师可以执行该操作"
);
}
}
private
void
requireStudentInClass
(
Integer
classId
,
String
studentId
)
{
if
(
isBlank
(
studentId
))
{
throw
new
BusinessException
(
"无法获取当前学员身份"
);
}
long
count
=
classStudentService
.
count
(
new
LambdaQueryWrapper
<
ClassStudentEntity
>()
.
eq
(
ClassStudentEntity:
:
getClassId
,
classId
)
.
eq
(
ClassStudentEntity:
:
getUserId
,
studentId
));
if
(
count
==
0
)
{
throw
new
BusinessException
(
"当前学员不属于该课程班级"
);
}
}
private
ClassSubjectAttendanceSessionEntity
findSession
(
Integer
subjectId
)
{
return
attendanceSessionService
.
getOne
(
new
LambdaQueryWrapper
<
ClassSubjectAttendanceSessionEntity
>()
.
eq
(
ClassSubjectAttendanceSessionEntity:
:
getSubjectId
,
subjectId
),
false
);
}
private
ClassSubjectAttendanceEntity
findRecord
(
Integer
subjectId
,
String
userId
)
{
return
attendanceRecordService
.
getOne
(
new
LambdaQueryWrapper
<
ClassSubjectAttendanceEntity
>()
.
eq
(
ClassSubjectAttendanceEntity:
:
getSubjectId
,
subjectId
)
.
eq
(
ClassSubjectAttendanceEntity:
:
getUserId
,
userId
),
false
);
}
private
Date
[]
normalizeRange
(
Date
startDate
,
Date
endDate
)
{
Calendar
start
=
Calendar
.
getInstance
();
Calendar
end
=
Calendar
.
getInstance
();
if
(
startDate
!=
null
)
{
start
.
setTime
(
startDate
);
}
else
if
(
endDate
!=
null
)
{
start
.
setTime
(
endDate
);
}
if
(
endDate
!=
null
)
{
end
.
setTime
(
endDate
);
}
else
if
(
startDate
!=
null
)
{
end
.
setTime
(
startDate
);
}
start
.
set
(
Calendar
.
HOUR_OF_DAY
,
0
);
start
.
set
(
Calendar
.
MINUTE
,
0
);
start
.
set
(
Calendar
.
SECOND
,
0
);
start
.
set
(
Calendar
.
MILLISECOND
,
0
);
end
.
set
(
Calendar
.
HOUR_OF_DAY
,
23
);
end
.
set
(
Calendar
.
MINUTE
,
59
);
end
.
set
(
Calendar
.
SECOND
,
59
);
end
.
set
(
Calendar
.
MILLISECOND
,
999
);
if
(
end
.
before
(
start
))
{
throw
new
BusinessException
(
"结束日期不能早于开始日期"
);
}
return
new
Date
[]{
start
.
getTime
(),
end
.
getTime
()};
}
private
AttendanceQueryDTO
prepareQuery
(
AttendanceQueryDTO
query
)
{
AttendanceQueryDTO
safeQuery
=
query
==
null
?
new
AttendanceQueryDTO
()
:
query
;
if
(
safeQuery
.
getStartDate
()
==
null
&&
safeQuery
.
getEndDate
()
==
null
)
{
Calendar
start
=
Calendar
.
getInstance
();
start
.
set
(
Calendar
.
DAY_OF_MONTH
,
1
);
start
.
set
(
Calendar
.
HOUR_OF_DAY
,
0
);
start
.
set
(
Calendar
.
MINUTE
,
0
);
start
.
set
(
Calendar
.
SECOND
,
0
);
start
.
set
(
Calendar
.
MILLISECOND
,
0
);
safeQuery
.
setStartDate
(
start
.
getTime
());
safeQuery
.
setEndDate
(
new
Date
());
}
return
safeQuery
;
}
private
static
Date
addMinutes
(
Date
date
,
int
minutes
)
{
return
new
Date
(
date
.
getTime
()
+
minutes
*
60_000L
);
}
private
static
boolean
constantTimeEquals
(
String
left
,
String
right
)
{
if
(
right
==
null
)
{
return
false
;
}
return
MessageDigest
.
isEqual
(
left
.
getBytes
(
StandardCharsets
.
UTF_8
),
right
.
getBytes
(
StandardCharsets
.
UTF_8
));
}
private
static
boolean
isBlank
(
String
value
)
{
return
value
==
null
||
value
.
trim
().
isEmpty
();
}
}
practical-business/src/main/java/com/platform/business/service/impl/BsFileServiceImpl.java
View file @
9e0dacc7
...
...
@@ -5,71 +5,133 @@ import com.platform.business.mapper.BsFileMapper;
import
com.platform.business.model.entity.BsFileEntity
;
import
com.platform.business.service.BsFileService
;
import
com.platform.exception.BusinessException
;
import
lombok.extern.slf4j.Slf4j
;
import
org.springframework.beans.factory.annotation.Value
;
import
org.springframework.http.HttpHeaders
;
import
org.springframework.http.MediaType
;
import
org.springframework.stereotype.Service
;
import
org.springframework.util.StringUtils
;
import
org.springframework.web.multipart.MultipartFile
;
import
org.slf4j.Logger
;
import
org.slf4j.LoggerFactory
;
import
javax.annotation.Resource
;
import
javax.servlet.http.HttpServletResponse
;
import
java.io.File
;
import
java.io.IOException
;
import
java.net.URLEncoder
;
import
java.nio.charset.StandardCharsets
;
import
java.nio.file.Files
;
import
java.nio.file.Path
;
import
java.nio.file.Paths
;
import
java.util.UUID
;
@Slf4j
/**
* 本地文件存储实现。
* 使用随机存储名避免同名覆盖,数据库保留原始文件名用于下载响应。
*/
@Service
public
class
BsFileServiceImpl
extends
ServiceImpl
<
BsFileMapper
,
BsFileEntity
>
implements
BsFileService
{
private
static
final
String
PREFIX
=
"/home/back/practical-train/file/"
;
private
static
final
Logger
log
=
LoggerFactory
.
getLogger
(
BsFileServiceImpl
.
class
);
@Value
(
"${business.file.upload-dir:/home/back/practical-train/file}"
)
private
String
uploadDirectory
;
@Resource
private
HttpServletResponse
response
;
@Override
public
BsFileEntity
uploadFile
(
MultipartFile
file
)
{
if
(
file
.
isEmpty
())
{
throw
new
BusinessException
(
"文件为空"
);
// 业务层校验500MB上限,防止容器上传限制被其他配置覆盖后失效。
if
(
file
==
null
||
file
.
isEmpty
())
{
throw
new
BusinessException
(
"上传文件不能为空"
);
}
if
(
file
.
getSize
()
>
MAX_FILE_SIZE
)
{
throw
new
BusinessException
(
"单个文件不能超过500MB"
);
}
try
{
//获取时间戳,保证不重复
// String time = System.currentTimeMillis() + "/";
// 确保上传目录存在
// File uploadDir = new File(PREFIX + time);
File
uploadDir
=
new
File
(
PREFIX
);
if
(!
uploadDir
.
exists
())
{
boolean
mkdir
=
uploadDir
.
mkdirs
();
log
.
info
(
"创建文件夹"
+
mkdir
);
// 创建并规范化上传目录,所有目标文件必须位于该目录之下。
Path
directory
=
Paths
.
get
(
uploadDirectory
).
toAbsolutePath
().
normalize
();
Files
.
createDirectories
(
directory
);
// 原始文件名只用于展示;磁盘使用UUID文件名,避免重名覆盖和路径穿越。
String
originalFilename
=
safeOriginalFilename
(
file
.
getOriginalFilename
());
String
storedFilename
=
UUID
.
randomUUID
().
toString
().
replace
(
"-"
,
""
)
+
getExtension
(
originalFilename
);
Path
target
=
directory
.
resolve
(
storedFilename
).
normalize
();
if
(!
target
.
startsWith
(
directory
))
{
throw
new
BusinessException
(
"文件保存路径非法"
);
}
// 保存文件到本地
// Path path = Paths.get(PREFIX + time + file.getOriginalFilename());
Path
path
=
Paths
.
get
(
PREFIX
+
file
.
getOriginalFilename
());
Files
.
write
(
path
,
file
.
getBytes
());
//获取文件名
String
fileName
=
file
.
getOriginalFilename
();
//获取文件绝对路径
String
fileUrl
=
path
.
toAbsolutePath
().
toString
();
BsFileEntity
bsFile
=
BsFileEntity
.
builder
().
url
(
fileUrl
).
fileName
(
fileName
).
build
();
save
(
bsFile
);
return
bsFile
;
// transferTo 直接流式落盘,避免大文件一次性加载到JVM内存。
file
.
transferTo
(
target
.
toFile
());
// 文件写入成功后保存元数据;数据库保存失败时清理本次产生的物理文件。
BsFileEntity
bsFile
=
BsFileEntity
.
builder
()
.
url
(
target
.
toString
())
.
fileName
(
originalFilename
)
.
delFlag
(
0
)
.
build
();
if
(!
save
(
bsFile
))
{
Files
.
deleteIfExists
(
target
);
throw
new
BusinessException
(
"文件信息保存失败"
);
}
return
bsFile
;
}
catch
(
IOException
e
)
{
log
.
error
(
"文件上传失败"
,
e
);
throw
new
BusinessException
(
"文件上传失败"
);
}
}
@Resource
private
HttpServletResponse
response
;
@Override
public
void
downloadFile
(
Integer
id
)
{
try
{
// getById 会自动附带 del_flag=0 条件,已逻辑删除的文件不可下载。
BsFileEntity
bsFile
=
getById
(
id
);
String
url
=
bsFile
.
getUrl
();
byte
[]
bytes
=
Files
.
readAllBytes
(
Paths
.
get
(
url
));
response
.
setHeader
(
HttpHeaders
.
CONTENT_DISPOSITION
,
"attachment; filename="
+
URLEncoder
.
encode
(
bsFile
.
getFileName
(),
"utf-8"
));
response
.
getOutputStream
().
write
(
bytes
);
if
(
bsFile
==
null
||
!
StringUtils
.
hasText
(
bsFile
.
getUrl
()))
{
throw
new
BusinessException
(
"文件不存在或已删除"
);
}
try
{
Path
path
=
Paths
.
get
(
bsFile
.
getUrl
()).
toAbsolutePath
().
normalize
();
if
(!
Files
.
isRegularFile
(
path
))
{
throw
new
BusinessException
(
"文件不存在或已删除"
);
}
String
contentType
=
Files
.
probeContentType
(
path
);
response
.
setContentType
(
StringUtils
.
hasText
(
contentType
)
?
contentType
:
MediaType
.
APPLICATION_OCTET_STREAM_VALUE
);
response
.
setContentLengthLong
(
Files
.
size
(
path
));
String
encodedFilename
=
URLEncoder
.
encode
(
safeDownloadFilename
(
bsFile
.
getFileName
()),
StandardCharsets
.
UTF_8
.
name
()).
replace
(
"+"
,
"%20"
);
response
.
setHeader
(
HttpHeaders
.
CONTENT_DISPOSITION
,
"attachment; filename*=UTF-8''"
+
encodedFilename
);
// 以流的方式复制到响应,支持接近500MB的大文件且不占用同等堆内存。
Files
.
copy
(
path
,
response
.
getOutputStream
());
response
.
getOutputStream
().
flush
();
}
catch
(
IOException
e
)
{
log
.
error
(
"文件下载失败,文件ID:{}"
,
id
,
e
);
throw
new
BusinessException
(
"文件下载失败"
);
}
}
/** 去除客户端路径信息和换行符,仅保留安全的原始文件名。 */
private
String
safeOriginalFilename
(
String
originalFilename
)
{
if
(!
StringUtils
.
hasText
(
originalFilename
))
{
return
"unnamed-file"
;
}
String
normalized
=
originalFilename
.
replace
(
'\\'
,
'/'
);
String
filename
=
normalized
.
substring
(
normalized
.
lastIndexOf
(
'/'
)
+
1
).
trim
();
filename
=
safeDownloadFilename
(
filename
);
return
StringUtils
.
hasText
(
filename
)
?
filename
:
"unnamed-file"
;
}
/** 移除响应头文件名中的换行符,防止响应头注入。 */
private
String
safeDownloadFilename
(
String
filename
)
{
if
(
filename
==
null
)
{
return
"unnamed-file"
;
}
return
filename
.
replace
(
"\r"
,
""
).
replace
(
"\n"
,
""
);
}
/** 保留原始扩展名,使磁盘文件仍可被系统识别类型。 */
private
String
getExtension
(
String
filename
)
{
int
dotIndex
=
filename
.
lastIndexOf
(
'.'
);
return
dotIndex
>=
0
?
filename
.
substring
(
dotIndex
)
:
""
;
}
}
practical-business/src/main/java/com/platform/business/service/impl/ClassServiceImpl.java
View file @
9e0dacc7
...
...
@@ -4,6 +4,7 @@ import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import
com.baomidou.mybatisplus.extension.service.impl.ServiceImpl
;
import
com.google.common.collect.Lists
;
import
com.platform.business.mapper.ClassMapper
;
import
com.platform.business.constant.AttendanceConstants
;
import
com.platform.business.model.dto.CalendarDTO
;
import
com.platform.business.model.dto.ClassDTO
;
import
com.platform.business.model.dto.ClassSubjectDTO
;
...
...
@@ -13,6 +14,7 @@ import com.platform.business.model.entity.ClassSubjectAttendanceEntity;
import
com.platform.business.model.entity.SysLevelEntity
;
import
com.platform.business.model.vo.*
;
import
com.platform.business.service.*
;
import
com.platform.business.util.ClassSubjectTimeUtils
;
import
com.platform.exception.BusinessException
;
import
com.platform.utils.DozerUtils
;
import
org.springframework.stereotype.Service
;
...
...
@@ -103,15 +105,16 @@ public class ClassServiceImpl extends ServiceImpl<ClassMapper, ClassEntity> impl
for
(
ClassSubjectVO
classSubjectVO
:
classSubjectList
)
{
if
(
classSubjectVO
.
getDate
().
equals
(
date
))
{
//判断状态
if
(
isBeforeMinTime
(
now
,
classSubjectVO
.
getDate
(),
classSubjectVO
.
getTimeFrame
()))
{
ClassSubjectTimeUtils
.
TimeWindow
window
=
ClassSubjectTimeUtils
.
resolve
(
classSubjectVO
);
if
(
now
.
before
(
window
.
getStart
()))
{
classSubjectVO
.
setStatus
(
classSubjectVO
.
getType
());
}
else
{
if
(
classSubjectAttendanceMap
.
containsKey
(
classSubjectVO
.
getId
()))
{
classSubjectVO
.
setStatus
(
"已签到"
);
}
else
if
(
classSubjectAttendanceMap
.
containsKey
(
classSubjectVO
.
getId
()))
{
classSubjectVO
.
setStatus
(
displayAttendanceStatus
(
classSubjectAttendanceMap
.
get
(
classSubjectVO
.
getId
()).
getStatus
()));
}
else
if
(
now
.
before
(
window
.
getEnd
()))
{
classSubjectVO
.
setStatus
(
"待签到"
);
}
else
{
classSubjectVO
.
setStatus
(
"缺勤"
);
}
}
classSubjectChildList
.
add
(
classSubjectVO
);
}
}
...
...
@@ -144,16 +147,17 @@ public class ClassServiceImpl extends ServiceImpl<ClassMapper, ClassEntity> impl
//设置状态
for
(
ClassSubjectVO
classSubjectVO
:
data
)
{
//判断状态
if
(
isBeforeMinTime
(
now
,
classSubjectVO
.
getDate
(),
classSubjectVO
.
getTimeFrame
()))
{
ClassSubjectTimeUtils
.
TimeWindow
window
=
ClassSubjectTimeUtils
.
resolve
(
classSubjectVO
);
if
(
now
.
before
(
window
.
getStart
()))
{
classSubjectVO
.
setStatus
(
classSubjectVO
.
getType
());
}
else
{
if
(
classSubjectAttendanceMap
.
containsKey
(
classSubjectVO
.
getId
()))
{
classSubjectVO
.
setStatus
(
"已签到"
);
}
else
if
(
classSubjectAttendanceMap
.
containsKey
(
classSubjectVO
.
getId
()))
{
classSubjectVO
.
setStatus
(
displayAttendanceStatus
(
classSubjectAttendanceMap
.
get
(
classSubjectVO
.
getId
()).
getStatus
()));
}
else
if
(
now
.
before
(
window
.
getEnd
()))
{
classSubjectVO
.
setStatus
(
"待签到"
);
}
else
{
classSubjectVO
.
setStatus
(
"缺勤"
);
}
}
}
result
.
setData
(
data
);
result
.
setSubjectNum
(
data
.
size
());
return
result
;
...
...
@@ -261,16 +265,20 @@ public class ClassServiceImpl extends ServiceImpl<ClassMapper, ClassEntity> impl
List
<
ClassSubjectAttendanceEntity
>
classSubjectAttendanceList
=
classSubjectAttendanceService
.
list
(
new
LambdaQueryWrapper
<
ClassSubjectAttendanceEntity
>().
eq
(
ClassSubjectAttendanceEntity:
:
getUserId
,
userId
)
);
HashMap
<
Integer
,
Date
>
classSubjectAttendanceMap
=
new
HashMap
<>();
HashMap
<
Integer
,
ClassSubjectAttendanceEntity
>
classSubjectAttendanceMap
=
new
HashMap
<>();
for
(
ClassSubjectAttendanceEntity
classSubjectAttendanceEntity
:
classSubjectAttendanceList
)
{
classSubjectAttendanceMap
.
put
(
classSubjectAttendanceEntity
.
getSubjectId
(),
classSubjectAttendanceEntity
.
getCheckInTime
()
);
classSubjectAttendanceMap
.
put
(
classSubjectAttendanceEntity
.
getSubjectId
(),
classSubjectAttendanceEntity
);
}
for
(
CalendarVO
calendarVO
:
result
)
{
if
(
classSubjectAttendanceMap
.
containsKey
(
calendarVO
.
getSubjectId
()))
{
calendarVO
.
setSignInTime
(
classSubjectAttendanceMap
.
get
(
calendarVO
.
getSubjectId
()));
calendarVO
.
setIsSignIn
(
true
);
ClassSubjectAttendanceEntity
attendance
=
classSubjectAttendanceMap
.
get
(
calendarVO
.
getSubjectId
());
calendarVO
.
setSignInTime
(
attendance
.
getCheckInTime
());
calendarVO
.
setAttendanceStatus
(
attendance
.
getStatus
());
calendarVO
.
setCheckInMethod
(
attendance
.
getCheckInMethod
());
calendarVO
.
setIsSignIn
(
AttendanceConstants
.
isPresent
(
attendance
.
getStatus
()));
}
else
{
calendarVO
.
setIsSignIn
(
false
);
calendarVO
.
setAttendanceStatus
(
"PENDING"
);
}
}
return
result
;
...
...
@@ -278,11 +286,7 @@ public class ClassServiceImpl extends ServiceImpl<ClassMapper, ClassEntity> impl
@Override
public
Boolean
todayCourseSignIn
(
CalendarDTO
calendarDTO
)
{
ClassSubjectAttendanceEntity
classSubjectAttendance
=
new
ClassSubjectAttendanceEntity
();
classSubjectAttendance
.
setUserId
(
calendarDTO
.
getUserId
());
classSubjectAttendance
.
setSubjectId
(
calendarDTO
.
getSubjectId
());
classSubjectAttendance
.
setCheckInTime
(
new
Date
());
return
classSubjectAttendanceService
.
save
(
classSubjectAttendance
);
throw
new
BusinessException
(
"原签到接口已停用,请使用 /attendance/student/check-in 完成IP和验证码校验"
);
}
@Override
...
...
@@ -297,15 +301,49 @@ public class ClassServiceImpl extends ServiceImpl<ClassMapper, ClassEntity> impl
HashMap
<
String
,
Integer
>
result
=
new
HashMap
<>();
//本月课程
result
.
put
(
"本月课程"
,
classSubjectList
.
size
());
//已签到
result
.
put
(
"已签到"
,
classSubjectAttendanceList
.
size
());
//待签到
result
.
put
(
"待签到"
,
classSubjectList
.
size
()
-
classSubjectAttendanceList
.
size
());
//出勤率
result
.
put
(
"出勤率"
,
classSubjectAttendanceList
.
size
()
/
classSubjectList
.
size
());
Map
<
Integer
,
ClassSubjectAttendanceEntity
>
attendanceMap
=
new
HashMap
<>();
for
(
ClassSubjectAttendanceEntity
attendance
:
classSubjectAttendanceList
)
{
attendanceMap
.
put
(
attendance
.
getSubjectId
(),
attendance
);
}
int
normal
=
0
;
int
late
=
0
;
int
absent
=
0
;
int
leave
=
0
;
int
pending
=
0
;
Date
now
=
new
Date
();
for
(
ClassSubjectVO
subject
:
classSubjectList
)
{
ClassSubjectAttendanceEntity
attendance
=
attendanceMap
.
get
(
subject
.
getId
());
if
(
attendance
!=
null
)
{
if
(
AttendanceConstants
.
STATUS_NORMAL
.
equals
(
attendance
.
getStatus
()))
normal
++;
else
if
(
AttendanceConstants
.
STATUS_LATE
.
equals
(
attendance
.
getStatus
()))
late
++;
else
if
(
AttendanceConstants
.
STATUS_ABSENT
.
equals
(
attendance
.
getStatus
()))
absent
++;
else
if
(
AttendanceConstants
.
STATUS_LEAVE
.
equals
(
attendance
.
getStatus
()))
leave
++;
}
else
if
(
now
.
before
(
ClassSubjectTimeUtils
.
resolve
(
subject
).
getEnd
()))
{
pending
++;
}
else
{
absent
++;
}
}
int
signed
=
normal
+
late
;
int
finished
=
signed
+
absent
+
leave
;
result
.
put
(
"已签到"
,
signed
);
result
.
put
(
"正常签到"
,
normal
);
result
.
put
(
"迟到"
,
late
);
result
.
put
(
"缺勤"
,
absent
);
result
.
put
(
"请假"
,
leave
);
result
.
put
(
"待签到"
,
pending
);
result
.
put
(
"出勤率"
,
finished
==
0
?
0
:
(
int
)
Math
.
round
(
signed
*
100.0
/
finished
));
return
result
;
}
private
static
String
displayAttendanceStatus
(
String
status
)
{
if
(
AttendanceConstants
.
STATUS_NORMAL
.
equals
(
status
))
return
"已签到"
;
if
(
AttendanceConstants
.
STATUS_LATE
.
equals
(
status
))
return
"迟到"
;
if
(
AttendanceConstants
.
STATUS_ABSENT
.
equals
(
status
))
return
"缺勤"
;
if
(
AttendanceConstants
.
STATUS_LEAVE
.
equals
(
status
))
return
"请假"
;
return
"已签到"
;
}
/**
* 方法2: 使用SimpleDateFormat格式化比较
* 将日期格式化为"yyyyMMdd"后比较字符串
...
...
practical-business/src/main/java/com/platform/business/service/impl/ClassSubjectAttendanceSessionServiceImpl.java
0 → 100644
View file @
9e0dacc7
package
com.platform.business.service.impl
;
import
com.baomidou.mybatisplus.extension.service.impl.ServiceImpl
;
import
com.platform.business.mapper.ClassSubjectAttendanceSessionMapper
;
import
com.platform.business.model.entity.ClassSubjectAttendanceSessionEntity
;
import
com.platform.business.service.ClassSubjectAttendanceSessionService
;
import
org.springframework.stereotype.Service
;
@Service
public
class
ClassSubjectAttendanceSessionServiceImpl
extends
ServiceImpl
<
ClassSubjectAttendanceSessionMapper
,
ClassSubjectAttendanceSessionEntity
>
implements
ClassSubjectAttendanceSessionService
{
}
practical-business/src/main/java/com/platform/business/service/impl/LeaveManagementServiceImpl.java
0 → 100644
View file @
9e0dacc7
package
com.platform.business.service.impl
;
import
com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper
;
import
com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper
;
import
com.baomidou.mybatisplus.core.toolkit.IdWorker
;
import
com.platform.business.constant.AttendanceConstants
;
import
com.platform.business.constant.LeaveConstants
;
import
com.platform.business.mapper.ClassSubjectAttendanceMapper
;
import
com.platform.business.mapper.StudentLeaveAttachmentMapper
;
import
com.platform.business.mapper.StudentLeaveApplicationMapper
;
import
com.platform.business.mapper.StudentLeaveSubjectMapper
;
import
com.platform.business.model.dto.LeaveApplyDTO
;
import
com.platform.business.model.dto.LeaveQueryDTO
;
import
com.platform.business.model.dto.LeaveReviewDTO
;
import
com.platform.business.model.entity.BsFileEntity
;
import
com.platform.business.model.entity.ClassSubjectAttendanceEntity
;
import
com.platform.business.model.entity.ClassSubjectEntity
;
import
com.platform.business.model.entity.StudentLeaveAttachmentEntity
;
import
com.platform.business.model.entity.StudentLeaveApplicationEntity
;
import
com.platform.business.model.entity.StudentLeaveSubjectEntity
;
import
com.platform.business.model.vo.LeaveApplicationVO
;
import
com.platform.business.service.BsFileService
;
import
com.platform.business.service.ClassStudentService
;
import
com.platform.business.service.ClassSubjectAttendanceService
;
import
com.platform.business.service.ClassSubjectService
;
import
com.platform.business.service.LeaveManagementService
;
import
com.platform.business.util.ClassSubjectTimeUtils
;
import
com.platform.exception.BusinessException
;
import
org.springframework.stereotype.Service
;
import
org.springframework.transaction.annotation.Transactional
;
import
javax.annotation.Resource
;
import
java.util.ArrayList
;
import
java.util.Calendar
;
import
java.util.Comparator
;
import
java.util.Date
;
import
java.util.LinkedHashSet
;
import
java.util.List
;
import
java.util.Locale
;
import
java.util.Set
;
import
java.util.stream.Collectors
;
@Service
public
class
LeaveManagementServiceImpl
implements
LeaveManagementService
{
@Resource
private
StudentLeaveApplicationMapper
leaveApplicationMapper
;
@Resource
private
StudentLeaveAttachmentMapper
leaveAttachmentMapper
;
@Resource
private
StudentLeaveSubjectMapper
leaveSubjectMapper
;
@Resource
private
ClassStudentService
classStudentService
;
@Resource
private
ClassSubjectService
classSubjectService
;
@Resource
private
ClassSubjectAttendanceService
attendanceRecordService
;
@Resource
private
ClassSubjectAttendanceMapper
attendanceMapper
;
@Resource
private
BsFileService
bsFileService
;
@Override
@Transactional
public
LeaveApplicationVO
apply
(
LeaveApplyDTO
request
,
String
studentId
)
{
validateRequest
(
request
);
List
<
ClassSubjectEntity
>
subjects
=
matchSubjects
(
request
,
studentId
);
ensureNoSignedAttendance
(
subjects
,
studentId
,
false
);
ensureNoOverlappingApplication
(
request
,
studentId
,
null
);
Date
now
=
new
Date
();
StudentLeaveApplicationEntity
leave
=
new
StudentLeaveApplicationEntity
();
leave
.
setId
(
IdWorker
.
getIdStr
());
leave
.
setStudentId
(
studentId
);
leave
.
setLeaveType
(
normalizeType
(
request
.
getLeaveType
()));
leave
.
setStartTime
(
request
.
getStartTime
());
leave
.
setEndTime
(
request
.
getEndTime
());
leave
.
setReason
(
request
.
getReason
().
trim
());
leave
.
setEmergencyContactName
(
trimToNull
(
request
.
getEmergencyContactName
()));
leave
.
setEmergencyContactPhone
(
trimToNull
(
request
.
getEmergencyContactPhone
()));
leave
.
setStatus
(
LeaveConstants
.
STATUS_PENDING
);
leave
.
setAppliedAt
(
now
);
leave
.
setUpdatedAt
(
now
);
leaveApplicationMapper
.
insert
(
leave
);
saveSubjectRelations
(
leave
.
getId
(),
subjects
,
now
);
saveAttachmentRelations
(
leave
.
getId
(),
request
.
getAttachmentFileIds
(),
now
);
return
requireDetail
(
leave
.
getId
());
}
@Override
@Transactional
public
LeaveApplicationVO
update
(
LeaveApplyDTO
request
,
String
studentId
)
{
if
(
request
==
null
||
isBlank
(
request
.
getId
()))
{
throw
new
BusinessException
(
"请假申请ID不能为空"
);
}
StudentLeaveApplicationEntity
current
=
requireLockedApplication
(
request
.
getId
());
requireOwnerAndPending
(
current
,
studentId
);
validateRequest
(
request
);
List
<
ClassSubjectEntity
>
subjects
=
matchSubjects
(
request
,
studentId
);
ensureNoSignedAttendance
(
subjects
,
studentId
,
false
);
ensureNoOverlappingApplication
(
request
,
studentId
,
current
.
getId
());
current
.
setLeaveType
(
normalizeType
(
request
.
getLeaveType
()));
current
.
setStartTime
(
request
.
getStartTime
());
current
.
setEndTime
(
request
.
getEndTime
());
current
.
setReason
(
request
.
getReason
().
trim
());
current
.
setEmergencyContactName
(
trimToNull
(
request
.
getEmergencyContactName
()));
current
.
setEmergencyContactPhone
(
trimToNull
(
request
.
getEmergencyContactPhone
()));
current
.
setUpdatedAt
(
new
Date
());
leaveApplicationMapper
.
updateById
(
current
);
leaveSubjectMapper
.
delete
(
new
LambdaQueryWrapper
<
StudentLeaveSubjectEntity
>()
.
eq
(
StudentLeaveSubjectEntity:
:
getLeaveId
,
current
.
getId
()));
leaveAttachmentMapper
.
delete
(
new
LambdaQueryWrapper
<
StudentLeaveAttachmentEntity
>()
.
eq
(
StudentLeaveAttachmentEntity:
:
getLeaveId
,
current
.
getId
()));
saveSubjectRelations
(
current
.
getId
(),
subjects
,
new
Date
());
saveAttachmentRelations
(
current
.
getId
(),
request
.
getAttachmentFileIds
(),
new
Date
());
return
requireDetail
(
current
.
getId
());
}
@Override
@Transactional
public
boolean
withdraw
(
String
leaveId
,
String
studentId
)
{
StudentLeaveApplicationEntity
current
=
requireLockedApplication
(
leaveId
);
requireOwnerAndPending
(
current
,
studentId
);
int
updated
=
leaveApplicationMapper
.
update
(
null
,
new
LambdaUpdateWrapper
<
StudentLeaveApplicationEntity
>()
.
eq
(
StudentLeaveApplicationEntity:
:
getId
,
leaveId
)
.
eq
(
StudentLeaveApplicationEntity:
:
getStatus
,
LeaveConstants
.
STATUS_PENDING
)
.
set
(
StudentLeaveApplicationEntity:
:
getStatus
,
LeaveConstants
.
STATUS_WITHDRAWN
)
.
set
(
StudentLeaveApplicationEntity:
:
getUpdatedAt
,
new
Date
()));
if
(
updated
==
0
)
{
throw
new
BusinessException
(
"申请状态已变化,无法撤回"
);
}
return
true
;
}
@Override
@Transactional
public
LeaveApplicationVO
review
(
String
leaveId
,
LeaveReviewDTO
request
,
String
approverId
,
String
approverRole
)
{
if
(
request
==
null
||
isBlank
(
request
.
getStatus
()))
{
throw
new
BusinessException
(
"审批结果不能为空"
);
}
String
reviewStatus
=
request
.
getStatus
().
trim
().
toUpperCase
(
Locale
.
ROOT
);
if
(!
LeaveConstants
.
STATUS_APPROVED
.
equals
(
reviewStatus
)
&&
!
LeaveConstants
.
STATUS_REJECTED
.
equals
(
reviewStatus
))
{
throw
new
BusinessException
(
"审批结果只能是 APPROVED 或 REJECTED"
);
}
if
(
request
.
getApprovalOpinion
()
!=
null
&&
request
.
getApprovalOpinion
().
length
()
>
1000
)
{
throw
new
BusinessException
(
"审批意见不能超过1000个字符"
);
}
StudentLeaveApplicationEntity
leave
=
requireLockedApplication
(
leaveId
);
if
(!
LeaveConstants
.
STATUS_PENDING
.
equals
(
leave
.
getStatus
()))
{
throw
new
BusinessException
(
"该申请已被处理,不能重复审批"
);
}
if
(
LeaveConstants
.
ROLE_TEACHER
.
equals
(
approverRole
)
&&
leaveApplicationMapper
.
countTeacherRelatedSubjects
(
leaveId
,
approverId
)
==
0
)
{
throw
new
BusinessException
(
"只能审批本人授课课程关联的请假申请"
);
}
List
<
Integer
>
subjectIds
=
leaveSubjectMapper
.
querySubjectsByLeaveId
(
leaveId
).
stream
()
.
map
(
subject
->
subject
.
getSubjectId
()).
collect
(
Collectors
.
toList
());
if
(
subjectIds
.
isEmpty
())
{
throw
new
BusinessException
(
"请假申请未关联任何课程"
);
}
Date
now
=
new
Date
();
if
(
LeaveConstants
.
STATUS_APPROVED
.
equals
(
reviewStatus
))
{
List
<
ClassSubjectAttendanceEntity
>
lockedRecords
=
attendanceMapper
.
lockRecords
(
subjectIds
,
leave
.
getStudentId
());
if
(
lockedRecords
.
stream
().
anyMatch
(
record
->
AttendanceConstants
.
isPresent
(
record
.
getStatus
())))
{
throw
new
BusinessException
(
"学员已完成正常或迟到签到,无需请假,不能审批通过"
);
}
}
int
updated
=
leaveApplicationMapper
.
reviewPending
(
leaveId
,
reviewStatus
,
approverId
,
approverRole
,
trimToNull
(
request
.
getApprovalOpinion
()),
now
);
if
(
updated
==
0
)
{
throw
new
BusinessException
(
"申请已由其他教师或管理员处理"
);
}
if
(
LeaveConstants
.
STATUS_APPROVED
.
equals
(
reviewStatus
))
{
List
<
ClassSubjectAttendanceEntity
>
leaveRecords
=
new
ArrayList
<>();
for
(
Integer
subjectId
:
subjectIds
)
{
ClassSubjectAttendanceEntity
record
=
new
ClassSubjectAttendanceEntity
();
record
.
setId
(
IdWorker
.
getIdStr
());
record
.
setSubjectId
(
subjectId
);
record
.
setUserId
(
leave
.
getStudentId
());
record
.
setStatus
(
AttendanceConstants
.
STATUS_LEAVE
);
record
.
setCheckInMethod
(
AttendanceConstants
.
METHOD_LEAVE
);
record
.
setTeacherConfirmed
(
true
);
record
.
setConfirmedBy
(
approverId
);
record
.
setConfirmedAt
(
now
);
record
.
setCreatedTime
(
now
);
record
.
setUpdateTime
(
now
);
leaveRecords
.
add
(
record
);
}
attendanceMapper
.
upsertLeaveStatuses
(
leaveRecords
);
List
<
ClassSubjectAttendanceEntity
>
finalRecords
=
attendanceMapper
.
lockRecords
(
subjectIds
,
leave
.
getStudentId
());
if
(
finalRecords
.
stream
().
anyMatch
(
record
->
AttendanceConstants
.
isPresent
(
record
.
getStatus
())))
{
throw
new
BusinessException
(
"审批期间学员已完成签到,请假审批已取消"
);
}
}
return
requireDetail
(
leaveId
);
}
@Override
public
List
<
LeaveApplicationVO
>
queryApplications
(
LeaveQueryDTO
query
)
{
LeaveQueryDTO
safeQuery
=
query
==
null
?
new
LeaveQueryDTO
()
:
query
;
List
<
LeaveApplicationVO
>
applications
=
leaveApplicationMapper
.
queryApplications
(
safeQuery
);
applications
.
forEach
(
application
->
{
application
.
setSubjects
(
leaveSubjectMapper
.
querySubjectsByLeaveId
(
application
.
getId
()));
application
.
setAttachments
(
leaveAttachmentMapper
.
queryAttachmentsByLeaveId
(
application
.
getId
()));
});
return
applications
;
}
@Override
public
LeaveApplicationVO
studentDetail
(
String
leaveId
,
String
studentId
)
{
LeaveApplicationVO
detail
=
requireDetail
(
leaveId
);
if
(!
studentId
.
equals
(
detail
.
getStudentId
()))
{
throw
new
BusinessException
(
"无权查看他人的请假申请"
);
}
return
detail
;
}
@Override
public
LeaveApplicationVO
teacherDetail
(
String
leaveId
,
String
teacherId
)
{
if
(
leaveApplicationMapper
.
countTeacherRelatedSubjects
(
leaveId
,
teacherId
)
==
0
)
{
throw
new
BusinessException
(
"无权查看与本人课程无关的请假申请"
);
}
return
requireDetail
(
leaveId
);
}
@Override
public
LeaveApplicationVO
adminDetail
(
String
leaveId
)
{
return
requireDetail
(
leaveId
);
}
private
List
<
ClassSubjectEntity
>
matchSubjects
(
LeaveApplyDTO
request
,
String
studentId
)
{
List
<
Integer
>
classIds
=
classStudentService
.
queryClassIdByUserId
(
studentId
);
if
(
classIds
==
null
||
classIds
.
isEmpty
())
{
throw
new
BusinessException
(
"当前学员未加入班级,无法申请请假"
);
}
Date
dayStart
=
startOfDay
(
request
.
getStartTime
());
Date
dayEnd
=
endOfDay
(
request
.
getEndTime
());
List
<
ClassSubjectEntity
>
candidates
=
classSubjectService
.
list
(
new
LambdaQueryWrapper
<
ClassSubjectEntity
>()
.
in
(
ClassSubjectEntity:
:
getClassId
,
classIds
)
.
ge
(
ClassSubjectEntity:
:
getDate
,
dayStart
)
.
le
(
ClassSubjectEntity:
:
getDate
,
dayEnd
));
Date
now
=
new
Date
();
List
<
ClassSubjectEntity
>
matched
=
candidates
.
stream
()
.
filter
(
subject
->
overlaps
(
ClassSubjectTimeUtils
.
resolve
(
subject
),
request
.
getStartTime
(),
request
.
getEndTime
()))
.
sorted
(
Comparator
.
comparing
(
subject
->
ClassSubjectTimeUtils
.
resolve
(
subject
).
getStart
()))
.
collect
(
Collectors
.
toList
());
if
(
matched
.
isEmpty
())
{
throw
new
BusinessException
(
"请假时间内没有需要出勤的课程"
);
}
if
(
matched
.
stream
().
anyMatch
(
subject
->
!
ClassSubjectTimeUtils
.
resolve
(
subject
).
getStart
().
after
(
now
)))
{
throw
new
BusinessException
(
"不能为已经开始或结束的课程补交请假"
);
}
return
matched
;
}
private
void
ensureNoSignedAttendance
(
List
<
ClassSubjectEntity
>
subjects
,
String
studentId
,
boolean
lock
)
{
List
<
Integer
>
subjectIds
=
subjects
.
stream
().
map
(
ClassSubjectEntity:
:
getId
).
collect
(
Collectors
.
toList
());
List
<
ClassSubjectAttendanceEntity
>
records
=
lock
?
attendanceMapper
.
lockRecords
(
subjectIds
,
studentId
)
:
attendanceRecordService
.
list
(
new
LambdaQueryWrapper
<
ClassSubjectAttendanceEntity
>()
.
in
(
ClassSubjectAttendanceEntity:
:
getSubjectId
,
subjectIds
)
.
eq
(
ClassSubjectAttendanceEntity:
:
getUserId
,
studentId
));
if
(
records
.
stream
().
anyMatch
(
record
->
AttendanceConstants
.
isPresent
(
record
.
getStatus
())))
{
throw
new
BusinessException
(
"关联课程已完成正常或迟到签到,无需请假"
);
}
}
private
void
ensureNoOverlappingApplication
(
LeaveApplyDTO
request
,
String
studentId
,
String
excludeId
)
{
LambdaQueryWrapper
<
StudentLeaveApplicationEntity
>
wrapper
=
new
LambdaQueryWrapper
<
StudentLeaveApplicationEntity
>()
.
eq
(
StudentLeaveApplicationEntity:
:
getStudentId
,
studentId
)
.
in
(
StudentLeaveApplicationEntity:
:
getStatus
,
LeaveConstants
.
STATUS_PENDING
,
LeaveConstants
.
STATUS_APPROVED
)
.
lt
(
StudentLeaveApplicationEntity:
:
getStartTime
,
request
.
getEndTime
())
.
gt
(
StudentLeaveApplicationEntity:
:
getEndTime
,
request
.
getStartTime
());
if
(!
isBlank
(
excludeId
))
{
wrapper
.
ne
(
StudentLeaveApplicationEntity:
:
getId
,
excludeId
);
}
if
(
leaveApplicationMapper
.
selectCount
(
wrapper
)
>
0
)
{
throw
new
BusinessException
(
"该时间段已有待审批或已批准的请假申请"
);
}
}
private
void
saveSubjectRelations
(
String
leaveId
,
List
<
ClassSubjectEntity
>
subjects
,
Date
now
)
{
for
(
ClassSubjectEntity
subject
:
subjects
)
{
StudentLeaveSubjectEntity
relation
=
new
StudentLeaveSubjectEntity
();
relation
.
setId
(
IdWorker
.
getIdStr
());
relation
.
setLeaveId
(
leaveId
);
relation
.
setSubjectId
(
subject
.
getId
());
relation
.
setCreatedTime
(
now
);
leaveSubjectMapper
.
insert
(
relation
);
}
}
private
void
saveAttachmentRelations
(
String
leaveId
,
List
<
Integer
>
attachmentFileIds
,
Date
now
)
{
if
(
attachmentFileIds
==
null
||
attachmentFileIds
.
isEmpty
())
{
return
;
}
Set
<
Integer
>
fileIds
=
attachmentFileIds
.
stream
()
.
filter
(
fileId
->
fileId
!=
null
)
.
collect
(
Collectors
.
toCollection
(
LinkedHashSet:
:
new
));
if
(
fileIds
.
isEmpty
())
{
return
;
}
List
<
BsFileEntity
>
files
=
bsFileService
.
listByIds
(
fileIds
);
if
(
files
.
size
()
!=
fileIds
.
size
())
{
throw
new
BusinessException
(
"部分证明材料不存在或已删除"
);
}
for
(
Integer
fileId
:
fileIds
)
{
StudentLeaveAttachmentEntity
attachment
=
new
StudentLeaveAttachmentEntity
();
attachment
.
setId
(
IdWorker
.
getIdStr
());
attachment
.
setLeaveId
(
leaveId
);
attachment
.
setFileId
(
fileId
);
attachment
.
setCreatedTime
(
now
);
leaveAttachmentMapper
.
insert
(
attachment
);
}
}
private
LeaveApplicationVO
requireDetail
(
String
leaveId
)
{
if
(
isBlank
(
leaveId
))
{
throw
new
BusinessException
(
"请假申请ID不能为空"
);
}
LeaveQueryDTO
query
=
new
LeaveQueryDTO
();
query
.
setId
(
leaveId
);
List
<
LeaveApplicationVO
>
applications
=
queryApplications
(
query
);
if
(
applications
.
isEmpty
())
{
throw
new
BusinessException
(
"请假申请不存在"
);
}
return
applications
.
get
(
0
);
}
private
StudentLeaveApplicationEntity
requireLockedApplication
(
String
leaveId
)
{
if
(
isBlank
(
leaveId
))
{
throw
new
BusinessException
(
"请假申请ID不能为空"
);
}
StudentLeaveApplicationEntity
application
=
leaveApplicationMapper
.
selectByIdForUpdate
(
leaveId
);
if
(
application
==
null
)
{
throw
new
BusinessException
(
"请假申请不存在"
);
}
return
application
;
}
private
void
requireOwnerAndPending
(
StudentLeaveApplicationEntity
application
,
String
studentId
)
{
if
(!
studentId
.
equals
(
application
.
getStudentId
()))
{
throw
new
BusinessException
(
"无权修改他人的请假申请"
);
}
if
(!
LeaveConstants
.
STATUS_PENDING
.
equals
(
application
.
getStatus
()))
{
throw
new
BusinessException
(
"只有待审批申请可以修改或撤回"
);
}
}
private
void
validateRequest
(
LeaveApplyDTO
request
)
{
if
(
request
==
null
||
request
.
getStartTime
()
==
null
||
request
.
getEndTime
()
==
null
)
{
throw
new
BusinessException
(
"请假开始时间和结束时间不能为空"
);
}
if
(!
request
.
getEndTime
().
after
(
request
.
getStartTime
()))
{
throw
new
BusinessException
(
"请假结束时间必须晚于开始时间"
);
}
if
(!
request
.
getStartTime
().
after
(
new
Date
()))
{
throw
new
BusinessException
(
"不允许补交历史请假"
);
}
String
type
=
normalizeType
(
request
.
getLeaveType
());
if
(!
LeaveConstants
.
isSupportedType
(
type
))
{
throw
new
BusinessException
(
"请假类型只能是 SICK、PERSONAL 或 OTHER"
);
}
if
(
isBlank
(
request
.
getReason
()))
{
throw
new
BusinessException
(
"请假原因不能为空"
);
}
if
(
request
.
getReason
().
trim
().
length
()
<
10
||
request
.
getReason
().
trim
().
length
()
>
200
)
{
throw
new
BusinessException
(
"请假原因须为10至200个字符"
);
}
String
contactName
=
trimToNull
(
request
.
getEmergencyContactName
());
String
contactPhone
=
trimToNull
(
request
.
getEmergencyContactPhone
());
if
((
contactName
==
null
)
!=
(
contactPhone
==
null
))
{
throw
new
BusinessException
(
"紧急联系人姓名和联系电话需要同时填写"
);
}
if
(
contactPhone
!=
null
&&
!
contactPhone
.
matches
(
"^1\\d{10}$"
))
{
throw
new
BusinessException
(
"紧急联系人手机号格式不正确"
);
}
if
(
contactName
!=
null
&&
contactName
.
length
()
>
50
)
{
throw
new
BusinessException
(
"紧急联系人姓名不能超过50个字符"
);
}
if
(
request
.
getAttachmentFileIds
()
!=
null
&&
request
.
getAttachmentFileIds
().
size
()
>
10
)
{
throw
new
BusinessException
(
"证明材料最多上传10个文件"
);
}
boolean
hasAttachment
=
request
.
getAttachmentFileIds
()
!=
null
&&
request
.
getAttachmentFileIds
().
stream
().
anyMatch
(
fileId
->
fileId
!=
null
);
if
(
LeaveConstants
.
TYPE_SICK
.
equals
(
type
)
&&
!
hasAttachment
)
{
throw
new
BusinessException
(
"病假需要上传病历或诊断证明"
);
}
}
private
static
boolean
overlaps
(
ClassSubjectTimeUtils
.
TimeWindow
window
,
Date
start
,
Date
end
)
{
return
window
.
getStart
().
before
(
end
)
&&
window
.
getEnd
().
after
(
start
);
}
private
static
Date
startOfDay
(
Date
date
)
{
Calendar
calendar
=
Calendar
.
getInstance
();
calendar
.
setTime
(
date
);
calendar
.
set
(
Calendar
.
HOUR_OF_DAY
,
0
);
calendar
.
set
(
Calendar
.
MINUTE
,
0
);
calendar
.
set
(
Calendar
.
SECOND
,
0
);
calendar
.
set
(
Calendar
.
MILLISECOND
,
0
);
return
calendar
.
getTime
();
}
private
static
Date
endOfDay
(
Date
date
)
{
Calendar
calendar
=
Calendar
.
getInstance
();
calendar
.
setTime
(
date
);
calendar
.
set
(
Calendar
.
HOUR_OF_DAY
,
23
);
calendar
.
set
(
Calendar
.
MINUTE
,
59
);
calendar
.
set
(
Calendar
.
SECOND
,
59
);
calendar
.
set
(
Calendar
.
MILLISECOND
,
999
);
return
calendar
.
getTime
();
}
private
static
String
normalizeType
(
String
type
)
{
return
type
==
null
?
null
:
type
.
trim
().
toUpperCase
(
Locale
.
ROOT
);
}
private
static
String
trimToNull
(
String
value
)
{
return
isBlank
(
value
)
?
null
:
value
.
trim
();
}
private
static
boolean
isBlank
(
String
value
)
{
return
value
==
null
||
value
.
trim
().
isEmpty
();
}
}
practical-business/src/main/java/com/platform/business/service/impl/TeachingResourceServiceImpl.java
0 → 100644
View file @
9e0dacc7
package
com.platform.business.service.impl
;
import
com.baomidou.mybatisplus.extension.service.impl.ServiceImpl
;
import
com.platform.business.mapper.TeachingResourceMapper
;
import
com.platform.business.model.dto.TeachingResourceDTO
;
import
com.platform.business.model.entity.BsFileEntity
;
import
com.platform.business.model.entity.ClassSubjectEntity
;
import
com.platform.business.model.entity.TeachingResourceEntity
;
import
com.platform.business.model.entity.UserEntity
;
import
com.platform.business.model.vo.TeachingResourceStatisticsVO
;
import
com.platform.business.model.vo.TeachingResourceVO
;
import
com.platform.business.service.BsFileService
;
import
com.platform.business.service.ClassSubjectService
;
import
com.platform.business.service.TeachingResourceService
;
import
com.platform.exception.BusinessException
;
import
org.springframework.stereotype.Service
;
import
org.springframework.transaction.annotation.Transactional
;
import
org.springframework.util.StringUtils
;
import
org.springframework.web.multipart.MultipartFile
;
import
javax.annotation.Resource
;
import
java.util.Arrays
;
import
java.util.Collections
;
import
java.util.HashSet
;
import
java.util.List
;
import
java.util.Locale
;
import
java.util.Set
;
/**
* 教学资源核心业务实现。
*
* <p>管理员查询全部资源;学生查询及下载时,均根据当前用户所在班级和
* {@code class_subject.class_id} 限制资源范围。</p>
*/
@Service
public
class
TeachingResourceServiceImpl
extends
ServiceImpl
<
TeachingResourceMapper
,
TeachingResourceEntity
>
implements
TeachingResourceService
{
/** 文件扩展名与原型资源类型之间的映射。未知扩展名统一归为 other。 */
private
static
final
Set
<
String
>
DOCUMENT_EXTENSIONS
=
Collections
.
unmodifiableSet
(
new
HashSet
<>(
Arrays
.
asList
(
"pdf"
,
"doc"
,
"docx"
,
"xls"
,
"xlsx"
,
"ppt"
,
"pptx"
,
"txt"
,
"csv"
)));
private
static
final
Set
<
String
>
VIDEO_EXTENSIONS
=
Collections
.
unmodifiableSet
(
new
HashSet
<>(
Arrays
.
asList
(
"mp4"
,
"avi"
,
"mov"
,
"wmv"
,
"flv"
,
"mkv"
,
"m4v"
,
"webm"
)));
private
static
final
Set
<
String
>
IMAGE_EXTENSIONS
=
Collections
.
unmodifiableSet
(
new
HashSet
<>(
Arrays
.
asList
(
"jpg"
,
"jpeg"
,
"png"
,
"gif"
,
"bmp"
,
"webp"
,
"svg"
)));
private
static
final
Set
<
String
>
RESOURCE_TYPES
=
Collections
.
unmodifiableSet
(
new
HashSet
<>(
Arrays
.
asList
(
"all"
,
"doc"
,
"video"
,
"image"
,
"other"
)));
@Resource
private
BsFileService
bsFileService
;
@Resource
private
ClassSubjectService
classSubjectService
;
@Override
public
List
<
TeachingResourceVO
>
adminList
(
TeachingResourceDTO
query
)
{
// 统一清洗关键字和资源类型,避免各查询入口出现不同筛选规则。
normalizeQuery
(
query
);
return
baseMapper
.
selectAdminList
(
query
);
}
@Override
public
List
<
TeachingResourceVO
>
studentList
(
String
userId
,
TeachingResourceDTO
query
)
{
requireUserId
(
userId
);
normalizeQuery
(
query
);
// Mapper 使用 class_student 与 class_subject 关系限制学生可见范围。
return
baseMapper
.
selectStudentList
(
userId
,
query
);
}
@Override
public
TeachingResourceStatisticsVO
adminStatistics
()
{
return
baseMapper
.
selectAdminStatistics
();
}
@Override
public
TeachingResourceStatisticsVO
studentStatistics
(
String
userId
)
{
requireUserId
(
userId
);
return
baseMapper
.
selectStudentStatistics
(
userId
);
}
@Override
@Transactional
(
rollbackFor
=
Exception
.
class
)
public
TeachingResourceVO
upload
(
MultipartFile
file
,
String
resourceName
,
Integer
courseId
,
UserEntity
uploader
)
{
// 第一步:先校验展示名称和课程ID,保证资源绑定的是有效 ClassSubjectEntity。
validateResourceName
(
resourceName
);
ClassSubjectEntity
course
=
requireCourse
(
courseId
);
if
(
file
==
null
||
file
.
isEmpty
())
{
throw
new
BusinessException
(
"上传文件不能为空"
);
}
if
(
uploader
==
null
||
!
StringUtils
.
hasText
(
uploader
.
getId
()))
{
throw
new
BusinessException
(
"无法获取当前上传用户"
);
}
// 第二步:根据原始文件扩展名确定类型,再保存文件并取得 bs_file.id。
String
resourceType
=
resolveResourceType
(
file
.
getOriginalFilename
());
BsFileEntity
storedFile
=
bsFileService
.
uploadFile
(
file
);
// 第三步:保存资源业务信息。String 主键由 ASSIGN_ID 雪花算法自动填充。
TeachingResourceEntity
resource
=
new
TeachingResourceEntity
();
resource
.
setFileId
(
storedFile
.
getId
());
resource
.
setResourceName
(
resourceName
.
trim
());
resource
.
setResourceType
(
resourceType
);
resource
.
setCourseId
(
course
.
getId
());
resource
.
setFileSize
(
file
.
getSize
());
resource
.
setUploaderId
(
uploader
.
getId
());
resource
.
setUploaderName
(
resolveUploaderName
(
uploader
));
resource
.
setDownloadCount
(
0L
);
resource
.
setDelFlag
(
0
);
if
(!
save
(
resource
))
{
throw
new
BusinessException
(
"教学资源保存失败"
);
}
// 返回包含课程名、班级名的完整展示对象,上传后前端可直接刷新列表。
return
baseMapper
.
selectAdminById
(
resource
.
getId
());
}
@Override
@Transactional
(
rollbackFor
=
Exception
.
class
)
public
boolean
updateResource
(
TeachingResourceDTO
resource
)
{
// 编辑接口不接收新文件,只允许更新原型要求的资源名称和课程ID。
if
(
resource
==
null
||
resource
.
getId
()
==
null
)
{
throw
new
BusinessException
(
"资源ID不能为空"
);
}
validateResourceName
(
resource
.
getResourceName
());
requireCourse
(
resource
.
getCourseId
());
requireResource
(
resource
.
getId
());
TeachingResourceEntity
update
=
new
TeachingResourceEntity
();
update
.
setId
(
resource
.
getId
());
update
.
setResourceName
(
resource
.
getResourceName
().
trim
());
update
.
setCourseId
(
resource
.
getCourseId
());
if
(!
updateById
(
update
))
{
throw
new
BusinessException
(
"教学资源更新失败"
);
}
return
true
;
}
@Override
@Transactional
(
rollbackFor
=
Exception
.
class
)
public
boolean
deleteResource
(
String
id
)
{
// 删除前同时确认资源和文件记录存在,避免出现只删除一侧的不一致状态。
TeachingResourceEntity
resource
=
requireResource
(
id
);
BsFileEntity
storedFile
=
bsFileService
.
getById
(
resource
.
getFileId
());
if
(
storedFile
==
null
)
{
throw
new
BusinessException
(
"资源文件不存在或已删除"
);
}
// 两个实体均配置 @TableLogic,此处只更新删除标记,不删除磁盘物理文件。
if
(!
removeById
(
id
))
{
throw
new
BusinessException
(
"教学资源删除失败"
);
}
if
(!
bsFileService
.
removeById
(
resource
.
getFileId
()))
{
throw
new
BusinessException
(
"资源文件删除失败"
);
}
return
true
;
}
@Override
public
void
adminDownload
(
String
id
)
{
TeachingResourceEntity
resource
=
requireResource
(
id
);
downloadAndCount
(
resource
);
}
@Override
public
void
studentDownload
(
String
id
,
String
userId
)
{
requireUserId
(
userId
);
TeachingResourceEntity
resource
=
requireResource
(
id
);
// 列表过滤不能代替下载鉴权,防止学生通过猜测资源ID越权下载。
if
(
baseMapper
.
countStudentResource
(
id
,
userId
)
==
0
)
{
throw
new
BusinessException
(
"无权下载非本人班级课程的资源"
);
}
downloadAndCount
(
resource
);
}
/**
* 文件流成功写出后原子递增下载次数;写出失败时不会累计。
*/
private
void
downloadAndCount
(
TeachingResourceEntity
resource
)
{
bsFileService
.
downloadFile
(
resource
.
getFileId
());
if
(
baseMapper
.
incrementDownloadCount
(
resource
.
getId
())
!=
1
)
{
throw
new
BusinessException
(
"下载次数更新失败"
);
}
}
/** 查询未逻辑删除的资源,不存在时统一抛出业务异常。 */
private
TeachingResourceEntity
requireResource
(
String
id
)
{
if
(!
StringUtils
.
hasText
(
id
))
{
throw
new
BusinessException
(
"资源ID不能为空"
);
}
TeachingResourceEntity
resource
=
getById
(
id
);
if
(
resource
==
null
)
{
throw
new
BusinessException
(
"教学资源不存在或已删除"
);
}
return
resource
;
}
/** 校验上传或编辑时绑定的课程ID真实存在。 */
private
ClassSubjectEntity
requireCourse
(
Integer
courseId
)
{
if
(
courseId
==
null
)
{
throw
new
BusinessException
(
"适用课程不能为空"
);
}
ClassSubjectEntity
course
=
classSubjectService
.
getById
(
courseId
);
if
(
course
==
null
)
{
throw
new
BusinessException
(
"适用课程不存在"
);
}
return
course
;
}
/** 校验必填的资源展示名称及数据库字段长度。 */
private
void
validateResourceName
(
String
resourceName
)
{
if
(!
StringUtils
.
hasText
(
resourceName
))
{
throw
new
BusinessException
(
"资源名称不能为空"
);
}
if
(
resourceName
.
trim
().
length
()
>
200
)
{
throw
new
BusinessException
(
"资源名称不能超过200个字符"
);
}
}
/** 标准化列表查询参数并拒绝原型定义之外的资源类型。 */
private
void
normalizeQuery
(
TeachingResourceDTO
query
)
{
if
(
query
==
null
)
{
throw
new
BusinessException
(
"查询条件不能为空"
);
}
if
(
StringUtils
.
hasText
(
query
.
getKeyword
()))
{
query
.
setKeyword
(
query
.
getKeyword
().
trim
());
}
if
(!
StringUtils
.
hasText
(
query
.
getResourceType
()))
{
query
.
setResourceType
(
"all"
);
}
else
{
String
resourceType
=
query
.
getResourceType
().
trim
().
toLowerCase
(
Locale
.
ROOT
);
if
(!
RESOURCE_TYPES
.
contains
(
resourceType
))
{
throw
new
BusinessException
(
"不支持的资源类型"
);
}
query
.
setResourceType
(
resourceType
);
}
}
/** 根据文件扩展名自动识别 doc、video、image、other 四类资源。 */
private
String
resolveResourceType
(
String
originalFilename
)
{
if
(!
StringUtils
.
hasText
(
originalFilename
))
{
return
"other"
;
}
String
filename
=
originalFilename
.
trim
();
int
dotIndex
=
filename
.
lastIndexOf
(
'.'
);
if
(
dotIndex
<
0
||
dotIndex
==
filename
.
length
()
-
1
)
{
return
"other"
;
}
String
extension
=
filename
.
substring
(
dotIndex
+
1
).
toLowerCase
(
Locale
.
ROOT
);
if
(
DOCUMENT_EXTENSIONS
.
contains
(
extension
))
{
return
"doc"
;
}
if
(
VIDEO_EXTENSIONS
.
contains
(
extension
))
{
return
"video"
;
}
if
(
IMAGE_EXTENSIONS
.
contains
(
extension
))
{
return
"image"
;
}
return
"other"
;
}
/** 按昵称、账号、手机号顺序确定列表中展示的上传者名称。 */
private
String
resolveUploaderName
(
UserEntity
uploader
)
{
if
(
StringUtils
.
hasText
(
uploader
.
getNickName
()))
{
return
uploader
.
getNickName
();
}
if
(
StringUtils
.
hasText
(
uploader
.
getUsername
()))
{
return
uploader
.
getUsername
();
}
return
uploader
.
getPhoneNumber
();
}
/** 学生数据范围查询必须使用服务端从令牌解析出的用户ID。 */
private
void
requireUserId
(
String
userId
)
{
if
(!
StringUtils
.
hasText
(
userId
))
{
throw
new
BusinessException
(
"无法获取当前学生信息"
);
}
}
}
practical-business/src/main/java/com/platform/business/service/impl/TrainingRoomBookingServiceImpl.java
0 → 100644
View file @
9e0dacc7
package
com.platform.business.service.impl
;
import
com.baomidou.mybatisplus.core.toolkit.IdWorker
;
import
com.baomidou.mybatisplus.extension.service.impl.ServiceImpl
;
import
com.platform.business.constant.TrainingRoomConstants
;
import
com.platform.business.constant.TrainingRoomTimeSlot
;
import
com.platform.business.mapper.TrainingRoomBookingLogMapper
;
import
com.platform.business.mapper.TrainingRoomBookingMapper
;
import
com.platform.business.mapper.TrainingRoomSeatMapper
;
import
com.platform.business.model.dto.TrainingRoomBookingCreateDTO
;
import
com.platform.business.model.dto.TrainingRoomBookingDTO
;
import
com.platform.business.model.entity.ClassEntity
;
import
com.platform.business.model.entity.TrainingRoomBookingEntity
;
import
com.platform.business.model.entity.TrainingRoomBookingLogEntity
;
import
com.platform.business.model.entity.TrainingRoomEntity
;
import
com.platform.business.model.entity.UserEntity
;
import
com.platform.business.model.vo.TrainingRoomBookingDetailVO
;
import
com.platform.business.model.vo.TrainingRoomBookingStatisticsVO
;
import
com.platform.business.model.vo.TrainingRoomBookingVO
;
import
com.platform.business.model.vo.TrainingRoomSeatVO
;
import
com.platform.business.model.vo.TrainingRoomTimeSlotVO
;
import
com.platform.business.service.ClassService
;
import
com.platform.business.service.ClassStudentService
;
import
com.platform.business.service.TrainingRoomBookingService
;
import
com.platform.business.service.TrainingRoomService
;
import
com.platform.exception.BusinessException
;
import
org.springframework.dao.DuplicateKeyException
;
import
org.springframework.scheduling.annotation.Scheduled
;
import
org.springframework.stereotype.Service
;
import
org.springframework.transaction.annotation.Transactional
;
import
org.springframework.util.StringUtils
;
import
javax.annotation.Resource
;
import
java.time.LocalDate
;
import
java.time.LocalDateTime
;
import
java.time.LocalTime
;
import
java.time.ZoneId
;
import
java.time.format.DateTimeFormatter
;
import
java.time.format.DateTimeParseException
;
import
java.util.ArrayList
;
import
java.util.Collections
;
import
java.util.Date
;
import
java.util.LinkedHashSet
;
import
java.util.List
;
import
java.util.Locale
;
import
java.util.Set
;
import
java.util.stream.Collectors
;
/** 实训室预约、冲突控制与自动状态更新实现。 */
@Service
public
class
TrainingRoomBookingServiceImpl
extends
ServiceImpl
<
TrainingRoomBookingMapper
,
TrainingRoomBookingEntity
>
implements
TrainingRoomBookingService
{
private
static
final
ZoneId
BUSINESS_ZONE
=
ZoneId
.
of
(
"Asia/Shanghai"
);
private
static
final
DateTimeFormatter
DATE_FORMATTER
=
DateTimeFormatter
.
ofPattern
(
"yyyy-MM-dd"
);
private
static
final
DateTimeFormatter
BOOKING_NO_DATE
=
DateTimeFormatter
.
ofPattern
(
"yyyyMMdd"
);
@Resource
private
TrainingRoomService
trainingRoomService
;
@Resource
private
TrainingRoomSeatMapper
trainingRoomSeatMapper
;
@Resource
private
TrainingRoomBookingLogMapper
bookingLogMapper
;
@Resource
private
ClassStudentService
classStudentService
;
@Resource
private
ClassService
classService
;
@Override
@Transactional
(
rollbackFor
=
Exception
.
class
)
public
List
<
TrainingRoomBookingVO
>
adminList
(
TrainingRoomBookingDTO
query
)
{
normalizeQuery
(
query
);
return
baseMapper
.
selectAdminList
(
query
);
}
@Override
@Transactional
(
rollbackFor
=
Exception
.
class
)
public
List
<
TrainingRoomBookingVO
>
studentList
(
String
studentId
,
TrainingRoomBookingDTO
query
)
{
requireUserId
(
studentId
);
normalizeQuery
(
query
);
return
baseMapper
.
selectStudentList
(
studentId
,
query
);
}
@Override
@Transactional
(
rollbackFor
=
Exception
.
class
)
public
TrainingRoomBookingDetailVO
adminDetail
(
String
id
)
{
synchronizeBookingStatuses
();
return
buildDetail
(
requireBookingVO
(
id
));
}
@Override
@Transactional
(
rollbackFor
=
Exception
.
class
)
public
TrainingRoomBookingDetailVO
studentDetail
(
String
id
,
String
studentId
)
{
synchronizeBookingStatuses
();
TrainingRoomBookingVO
booking
=
requireBookingVO
(
id
);
if
(!
booking
.
getStudentId
().
equals
(
studentId
))
{
throw
new
BusinessException
(
"无权查看他人的预约记录"
);
}
return
buildDetail
(
booking
);
}
@Override
@Transactional
(
rollbackFor
=
Exception
.
class
)
public
TrainingRoomBookingStatisticsVO
adminStatistics
(
String
roomId
)
{
synchronizeBookingStatuses
();
requireRoom
(
roomId
);
return
baseMapper
.
selectStatistics
(
roomId
);
}
@Override
@Transactional
(
rollbackFor
=
Exception
.
class
)
public
List
<
TrainingRoomSeatVO
>
adminAvailability
(
String
roomId
,
String
bookingDate
,
Integer
slotCode
)
{
synchronizeBookingStatuses
();
TrainingRoomEntity
room
=
requireRoom
(
roomId
);
BookingTime
bookingTime
=
validateBookingTime
(
room
,
bookingDate
,
slotCode
,
false
);
return
trainingRoomSeatMapper
.
selectAvailability
(
roomId
,
bookingTime
.
date
.
format
(
DATE_FORMATTER
),
slotCode
);
}
@Override
@Transactional
(
rollbackFor
=
Exception
.
class
)
public
List
<
TrainingRoomSeatVO
>
availability
(
String
roomId
,
String
bookingDate
,
Integer
slotCode
)
{
synchronizeBookingStatuses
();
TrainingRoomEntity
room
=
requireRunningRoom
(
roomId
);
BookingTime
bookingTime
=
validateBookingTime
(
room
,
bookingDate
,
slotCode
,
true
);
return
trainingRoomSeatMapper
.
selectAvailability
(
roomId
,
bookingTime
.
date
.
format
(
DATE_FORMATTER
),
slotCode
);
}
@Override
public
List
<
TrainingRoomTimeSlotVO
>
timeSlots
()
{
return
TrainingRoomTimeSlot
.
toVOList
();
}
@Override
@Transactional
(
rollbackFor
=
Exception
.
class
)
public
TrainingRoomBookingVO
createBooking
(
TrainingRoomBookingCreateDTO
request
,
UserEntity
student
)
{
synchronizeBookingStatuses
();
if
(
request
==
null
)
{
throw
new
BusinessException
(
"预约参数不能为空"
);
}
validateStudent
(
student
);
TrainingRoomEntity
room
=
requireRunningRoom
(
request
.
getRoomId
());
BookingTime
bookingTime
=
validateBookingTime
(
room
,
request
.
getBookingDate
(),
request
.
getSlotCode
(),
true
);
if
(
request
.
getSeatNo
()
==
null
||
request
.
getSeatNo
()
<
1
||
trainingRoomSeatMapper
.
selectEnabledSeat
(
room
.
getId
(),
request
.
getSeatNo
())
==
null
)
{
throw
new
BusinessException
(
"所选机位不存在"
);
}
if
(
StringUtils
.
hasText
(
request
.
getNote
())
&&
request
.
getNote
().
trim
().
length
()
>
500
)
{
throw
new
BusinessException
(
"预约备注不能超过500个字符"
);
}
String
date
=
bookingTime
.
date
.
format
(
DATE_FORMATTER
);
if
(
baseMapper
.
countSeatConflict
(
room
.
getId
(),
date
,
request
.
getSlotCode
(),
request
.
getSeatNo
())
>
0
)
{
throw
new
BusinessException
(
"该机位在所选时段已被预约"
);
}
if
(
baseMapper
.
countStudentConflict
(
student
.
getId
(),
date
,
request
.
getSlotCode
())
>
0
)
{
throw
new
BusinessException
(
"同一时段只能预约一个机位"
);
}
TrainingRoomBookingEntity
booking
=
new
TrainingRoomBookingEntity
();
String
bookingId
=
IdWorker
.
getIdStr
();
booking
.
setId
(
bookingId
);
booking
.
setBookingNo
(
"B"
+
bookingTime
.
date
.
format
(
BOOKING_NO_DATE
)
+
bookingId
);
booking
.
setRoomId
(
room
.
getId
());
booking
.
setStudentId
(
student
.
getId
());
booking
.
setStudentName
(
resolveUserName
(
student
));
booking
.
setStudentNo
(
student
.
getId
());
booking
.
setClassName
(
resolveClassNames
(
student
.
getId
()));
booking
.
setBookingDate
(
date
);
booking
.
setSlotCode
(
request
.
getSlotCode
());
booking
.
setStartTime
(
toDate
(
bookingTime
.
start
));
booking
.
setEndTime
(
toDate
(
bookingTime
.
end
));
booking
.
setSeatNo
(
request
.
getSeatNo
());
booking
.
setNote
(
StringUtils
.
hasText
(
request
.
getNote
())
?
request
.
getNote
().
trim
()
:
null
);
booking
.
setStatus
(
TrainingRoomConstants
.
BOOKING_BOOKED
);
booking
.
setActiveFlag
(
1
);
booking
.
setDelFlag
(
0
);
try
{
if
(!
save
(
booking
))
{
throw
new
BusinessException
(
"预约创建失败"
);
}
}
catch
(
DuplicateKeyException
e
)
{
// 数据库唯一约束是并发场景下的最终保护,转换为前端可理解的提示。
throw
new
BusinessException
(
"该机位或当前学员在所选时段已有有效预约"
);
}
addLog
(
booking
.
getId
(),
TrainingRoomConstants
.
ACTION_CREATE
,
null
,
TrainingRoomConstants
.
BOOKING_BOOKED
,
student
.
getId
(),
resolveUserName
(
student
),
new
Date
(),
"学员发起预约"
);
return
requireBookingVO
(
booking
.
getId
());
}
@Override
@Transactional
(
rollbackFor
=
Exception
.
class
)
public
boolean
studentCancel
(
String
id
,
UserEntity
student
)
{
synchronizeBookingStatuses
();
TrainingRoomBookingEntity
booking
=
requireBooking
(
id
);
requireOwner
(
booking
,
student
);
return
cancelBooking
(
booking
,
student
,
TrainingRoomConstants
.
ACTION_STUDENT_CANCEL
,
"学员取消预约"
);
}
@Override
@Transactional
(
rollbackFor
=
Exception
.
class
)
public
boolean
studentSignOut
(
String
id
,
UserEntity
student
)
{
synchronizeBookingStatuses
();
TrainingRoomBookingEntity
booking
=
requireBooking
(
id
);
requireOwner
(
booking
,
student
);
return
finishBooking
(
booking
,
student
,
TrainingRoomConstants
.
ACTION_STUDENT_SIGN_OUT
,
"学员提前签退"
);
}
@Override
@Transactional
(
rollbackFor
=
Exception
.
class
)
public
boolean
adminCancel
(
String
id
,
UserEntity
administrator
)
{
synchronizeBookingStatuses
();
TrainingRoomBookingEntity
booking
=
requireBooking
(
id
);
validateStudent
(
administrator
);
return
cancelBooking
(
booking
,
administrator
,
TrainingRoomConstants
.
ACTION_ADMIN_CANCEL
,
"管理员取消预约"
);
}
@Override
@Transactional
(
rollbackFor
=
Exception
.
class
)
public
boolean
adminEnd
(
String
id
,
UserEntity
administrator
)
{
synchronizeBookingStatuses
();
TrainingRoomBookingEntity
booking
=
requireBooking
(
id
);
validateStudent
(
administrator
);
return
finishBooking
(
booking
,
administrator
,
TrainingRoomConstants
.
ACTION_ADMIN_END
,
"管理员结束实训"
);
}
/**
* 每分钟自动执行;所有查询入口也会调用本方法,弥补服务停机期间错过的状态变化。
*/
@Override
@Scheduled
(
cron
=
"0 * * * * ?"
)
@Transactional
(
rollbackFor
=
Exception
.
class
)
public
void
synchronizeBookingStatuses
()
{
Date
now
=
new
Date
();
List
<
TrainingRoomBookingEntity
>
dueBooked
=
baseMapper
.
selectDueBooked
(
now
);
for
(
TrainingRoomBookingEntity
booking
:
dueBooked
)
{
if
(!
now
.
before
(
booking
.
getEndTime
()))
{
// 服务恢复时若整个时段已经过去,一次补齐开始、完成状态和时间线。
if
(
baseMapper
.
finishExpiredBooked
(
booking
.
getId
())
==
1
)
{
addLog
(
booking
.
getId
(),
TrainingRoomConstants
.
ACTION_AUTO_START
,
TrainingRoomConstants
.
BOOKING_BOOKED
,
TrainingRoomConstants
.
BOOKING_USING
,
"system"
,
"系统"
,
booking
.
getStartTime
(),
"到达预约开始时间,自动开始使用"
);
addLog
(
booking
.
getId
(),
TrainingRoomConstants
.
ACTION_AUTO_FINISH
,
TrainingRoomConstants
.
BOOKING_USING
,
TrainingRoomConstants
.
BOOKING_DONE
,
"system"
,
"系统"
,
booking
.
getEndTime
(),
"到达预约结束时间,自动完成"
);
}
}
else
if
(
baseMapper
.
startBooking
(
booking
.
getId
(),
now
)
==
1
)
{
addLog
(
booking
.
getId
(),
TrainingRoomConstants
.
ACTION_AUTO_START
,
TrainingRoomConstants
.
BOOKING_BOOKED
,
TrainingRoomConstants
.
BOOKING_USING
,
"system"
,
"系统"
,
now
,
"到达预约开始时间,自动开始使用"
);
}
}
List
<
TrainingRoomBookingEntity
>
dueUsing
=
baseMapper
.
selectDueUsing
(
now
);
for
(
TrainingRoomBookingEntity
booking
:
dueUsing
)
{
if
(
baseMapper
.
finishUsingBooking
(
booking
.
getId
(),
now
)
==
1
)
{
addLog
(
booking
.
getId
(),
TrainingRoomConstants
.
ACTION_AUTO_FINISH
,
TrainingRoomConstants
.
BOOKING_USING
,
TrainingRoomConstants
.
BOOKING_DONE
,
"system"
,
"系统"
,
now
,
"到达预约结束时间,自动完成"
);
}
}
}
/**
* 取消尚未开始的预约。更新语句同时校验状态和开始时间,避免与自动开始任务并发冲突。
*/
private
boolean
cancelBooking
(
TrainingRoomBookingEntity
booking
,
UserEntity
operator
,
String
action
,
String
remark
)
{
if
(!
TrainingRoomConstants
.
BOOKING_BOOKED
.
equals
(
booking
.
getStatus
()))
{
throw
new
BusinessException
(
"只有未开始的预约可以取消"
);
}
Date
now
=
new
Date
();
if
(
baseMapper
.
cancelBooked
(
booking
.
getId
(),
now
,
operator
.
getId
())
!=
1
)
{
throw
new
BusinessException
(
"预约已开始或状态已变化,无法取消"
);
}
addLog
(
booking
.
getId
(),
action
,
TrainingRoomConstants
.
BOOKING_BOOKED
,
TrainingRoomConstants
.
BOOKING_CANCELED
,
operator
.
getId
(),
resolveUserName
(
operator
),
now
,
remark
);
return
true
;
}
/**
* 提前结束使用中的预约,并将activeFlag置空以释放机位和学员唯一约束。
*/
private
boolean
finishBooking
(
TrainingRoomBookingEntity
booking
,
UserEntity
operator
,
String
action
,
String
remark
)
{
if
(!
TrainingRoomConstants
.
BOOKING_USING
.
equals
(
booking
.
getStatus
()))
{
throw
new
BusinessException
(
"只有使用中的预约可以结束"
);
}
Date
now
=
new
Date
();
if
(
baseMapper
.
finishUsingBooking
(
booking
.
getId
(),
now
)
!=
1
)
{
throw
new
BusinessException
(
"预约状态已变化,请刷新后重试"
);
}
addLog
(
booking
.
getId
(),
action
,
TrainingRoomConstants
.
BOOKING_USING
,
TrainingRoomConstants
.
BOOKING_DONE
,
operator
.
getId
(),
resolveUserName
(
operator
),
now
,
remark
);
return
true
;
}
/** 查询实训室并校验其状态为运行中。 */
private
TrainingRoomEntity
requireRunningRoom
(
String
roomId
)
{
TrainingRoomEntity
room
=
requireRoom
(
roomId
);
if
(!
TrainingRoomConstants
.
ROOM_RUNNING
.
equals
(
room
.
getStatus
()))
{
throw
new
BusinessException
(
"已停用的实训室不可预约"
);
}
return
room
;
}
/** 查询未逻辑删除的实训室,不限制运行状态。 */
private
TrainingRoomEntity
requireRoom
(
String
roomId
)
{
if
(!
StringUtils
.
hasText
(
roomId
))
{
throw
new
BusinessException
(
"实训室ID不能为空"
);
}
TrainingRoomEntity
room
=
trainingRoomService
.
getById
(
roomId
);
if
(
room
==
null
)
{
throw
new
BusinessException
(
"实训室不存在"
);
}
return
room
;
}
/** 校验只能预约今天至后天、时段未开始且位于实训室开放时间内。 */
private
BookingTime
validateBookingTime
(
TrainingRoomEntity
room
,
String
bookingDate
,
Integer
slotCode
,
boolean
rejectStartedSlot
)
{
LocalDate
date
=
parseDate
(
bookingDate
);
LocalDate
today
=
LocalDate
.
now
(
BUSINESS_ZONE
);
if
(
date
.
isBefore
(
today
)
||
date
.
isAfter
(
today
.
plusDays
(
2
)))
{
throw
new
BusinessException
(
"只能预约今天、明天或后天"
);
}
TrainingRoomTimeSlot
slot
=
TrainingRoomTimeSlot
.
fromCode
(
slotCode
);
if
(!
Boolean
.
TRUE
.
equals
(
room
.
getAllDay
()))
{
LocalTime
openStart
=
LocalTime
.
parse
(
room
.
getOpenStart
());
LocalTime
openEnd
=
LocalTime
.
parse
(
room
.
getOpenEnd
());
if
(
slot
.
getStartTime
().
isBefore
(
openStart
)
||
slot
.
getEndTime
().
isAfter
(
openEnd
))
{
throw
new
BusinessException
(
"所选时段不在实训室开放时间内"
);
}
}
LocalDateTime
start
=
LocalDateTime
.
of
(
date
,
slot
.
getStartTime
());
LocalDateTime
end
=
LocalDateTime
.
of
(
date
,
slot
.
getEndTime
());
if
(
rejectStartedSlot
&&
!
start
.
isAfter
(
LocalDateTime
.
now
(
BUSINESS_ZONE
)))
{
throw
new
BusinessException
(
"已开始或已结束的时段不可预约"
);
}
return
new
BookingTime
(
date
,
start
,
end
);
}
/** 将yyyy-MM-dd文本解析为业务时区使用的日期。 */
private
LocalDate
parseDate
(
String
value
)
{
if
(!
StringUtils
.
hasText
(
value
))
{
throw
new
BusinessException
(
"预约日期不能为空"
);
}
try
{
return
LocalDate
.
parse
(
value
.
trim
(),
DATE_FORMATTER
);
}
catch
(
DateTimeParseException
e
)
{
throw
new
BusinessException
(
"预约日期格式必须为yyyy-MM-dd"
);
}
}
/** 根据ID获取预约实体,不存在时统一抛出业务异常。 */
private
TrainingRoomBookingEntity
requireBooking
(
String
id
)
{
if
(!
StringUtils
.
hasText
(
id
))
{
throw
new
BusinessException
(
"预约ID不能为空"
);
}
TrainingRoomBookingEntity
booking
=
getById
(
id
);
if
(
booking
==
null
)
{
throw
new
BusinessException
(
"预约记录不存在"
);
}
return
booking
;
}
/** 获取包含实训室展示字段的预约详情。 */
private
TrainingRoomBookingVO
requireBookingVO
(
String
id
)
{
if
(!
StringUtils
.
hasText
(
id
))
{
throw
new
BusinessException
(
"预约ID不能为空"
);
}
TrainingRoomBookingVO
booking
=
baseMapper
.
selectDetail
(
id
);
if
(
booking
==
null
)
{
throw
new
BusinessException
(
"预约记录不存在"
);
}
return
booking
;
}
/** 组合预约基本信息和操作时间线。 */
private
TrainingRoomBookingDetailVO
buildDetail
(
TrainingRoomBookingVO
booking
)
{
TrainingRoomBookingDetailVO
detail
=
new
TrainingRoomBookingDetailVO
();
detail
.
setBooking
(
booking
);
detail
.
setOperationLogs
(
bookingLogMapper
.
selectByBookingId
(
booking
.
getId
()));
return
detail
;
}
/** 校验当前登录用户是否为预约本人。 */
private
void
requireOwner
(
TrainingRoomBookingEntity
booking
,
UserEntity
student
)
{
validateStudent
(
student
);
if
(!
student
.
getId
().
equals
(
booking
.
getStudentId
()))
{
throw
new
BusinessException
(
"无权操作他人的预约记录"
);
}
}
/** 校验控制器传入的登录用户信息是否有效。 */
private
void
validateStudent
(
UserEntity
user
)
{
if
(
user
==
null
||
!
StringUtils
.
hasText
(
user
.
getId
()))
{
throw
new
BusinessException
(
"无法获取当前登录用户"
);
}
}
/** 校验学员ID,避免列表查询意外越权为查询全部。 */
private
void
requireUserId
(
String
userId
)
{
if
(!
StringUtils
.
hasText
(
userId
))
{
throw
new
BusinessException
(
"无法获取当前学员信息"
);
}
}
/**
* 查询学员当前所属班级并保存名称快照;多班级使用中文顿号连接。
*/
private
String
resolveClassNames
(
String
studentId
)
{
List
<
Integer
>
classIds
=
classStudentService
.
queryClassIdByUserId
(
studentId
);
if
(
classIds
==
null
||
classIds
.
isEmpty
())
{
return
"—"
;
}
List
<
ClassEntity
>
classes
=
classService
.
listByIds
(
classIds
);
Set
<
String
>
names
=
classes
.
stream
()
.
map
(
ClassEntity:
:
getName
)
.
filter
(
StringUtils:
:
hasText
)
.
collect
(
Collectors
.
toCollection
(
LinkedHashSet:
:
new
));
return
names
.
isEmpty
()
?
"—"
:
String
.
join
(
"、"
,
names
);
}
/** 按昵称、用户名、手机号的优先级解析操作人展示名称。 */
private
String
resolveUserName
(
UserEntity
user
)
{
if
(
StringUtils
.
hasText
(
user
.
getNickName
()))
{
return
user
.
getNickName
();
}
if
(
StringUtils
.
hasText
(
user
.
getUsername
()))
{
return
user
.
getUsername
();
}
return
user
.
getPhoneNumber
();
}
/** 保存预约状态操作记录,供详情页面展示完整时间线。 */
private
void
addLog
(
String
bookingId
,
String
action
,
String
fromStatus
,
String
toStatus
,
String
operatorId
,
String
operatorName
,
Date
operateTime
,
String
remark
)
{
TrainingRoomBookingLogEntity
log
=
new
TrainingRoomBookingLogEntity
();
log
.
setBookingId
(
bookingId
);
log
.
setAction
(
action
);
log
.
setFromStatus
(
fromStatus
);
log
.
setToStatus
(
toStatus
);
log
.
setOperatorId
(
operatorId
);
log
.
setOperatorName
(
operatorName
);
log
.
setOperateTime
(
operateTime
);
log
.
setRemark
(
remark
);
if
(
bookingLogMapper
.
insert
(
log
)
!=
1
)
{
throw
new
BusinessException
(
"预约操作记录保存失败"
);
}
}
/** 将业务时区的LocalDateTime转换为持久层使用的Date。 */
private
Date
toDate
(
LocalDateTime
value
)
{
return
Date
.
from
(
value
.
atZone
(
BUSINESS_ZONE
).
toInstant
());
}
/** 清理预约查询关键字并校验状态筛选值。 */
private
void
normalizeQuery
(
TrainingRoomBookingDTO
query
)
{
if
(
query
==
null
)
{
throw
new
BusinessException
(
"查询参数不能为空"
);
}
if
(
StringUtils
.
hasText
(
query
.
getKeyword
()))
{
query
.
setKeyword
(
query
.
getKeyword
().
trim
());
}
if
(
StringUtils
.
hasText
(
query
.
getStatus
()))
{
String
status
=
query
.
getStatus
().
trim
().
toLowerCase
(
Locale
.
ROOT
);
List
<
String
>
statuses
=
new
ArrayList
<>();
Collections
.
addAll
(
statuses
,
"all"
,
TrainingRoomConstants
.
BOOKING_BOOKED
,
TrainingRoomConstants
.
BOOKING_USING
,
TrainingRoomConstants
.
BOOKING_DONE
,
TrainingRoomConstants
.
BOOKING_CANCELED
);
if
(!
statuses
.
contains
(
status
))
{
throw
new
BusinessException
(
"不支持的预约状态"
);
}
query
.
setStatus
(
status
);
}
}
/** 已解析且校验通过的预约起止时间。 */
private
static
final
class
BookingTime
{
private
final
LocalDate
date
;
private
final
LocalDateTime
start
;
private
final
LocalDateTime
end
;
private
BookingTime
(
LocalDate
date
,
LocalDateTime
start
,
LocalDateTime
end
)
{
this
.
date
=
date
;
this
.
start
=
start
;
this
.
end
=
end
;
}
}
}
practical-business/src/main/java/com/platform/business/service/impl/TrainingRoomSeatServiceImpl.java
0 → 100644
View file @
9e0dacc7
package
com.platform.business.service.impl
;
import
com.baomidou.mybatisplus.extension.service.impl.ServiceImpl
;
import
com.platform.business.mapper.TrainingRoomSeatMapper
;
import
com.platform.business.model.entity.TrainingRoomSeatEntity
;
import
com.platform.business.service.TrainingRoomSeatService
;
import
org.springframework.stereotype.Service
;
import
org.springframework.transaction.annotation.Transactional
;
import
java.util.ArrayList
;
import
java.util.HashSet
;
import
java.util.List
;
import
java.util.Set
;
/** 机位编号同步实现。 */
@Service
public
class
TrainingRoomSeatServiceImpl
extends
ServiceImpl
<
TrainingRoomSeatMapper
,
TrainingRoomSeatEntity
>
implements
TrainingRoomSeatService
{
@Override
@Transactional
(
rollbackFor
=
Exception
.
class
)
public
void
synchronizeSeats
(
String
roomId
,
Integer
seatCount
)
{
// 先读取包含停用机位在内的全部历史编号,避免扩容时重复插入相同编号。
List
<
TrainingRoomSeatEntity
>
existingSeats
=
baseMapper
.
selectAllByRoom
(
roomId
);
Set
<
Integer
>
existingNumbers
=
new
HashSet
<>();
for
(
TrainingRoomSeatEntity
seat
:
existingSeats
)
{
existingNumbers
.
add
(
seat
.
getSeatNo
());
}
// 扩容时先恢复曾被停用的编号,缩容时停用超出范围的编号。
baseMapper
.
enableSeatsUpTo
(
roomId
,
seatCount
);
baseMapper
.
disableSeatsAbove
(
roomId
,
seatCount
);
List
<
TrainingRoomSeatEntity
>
newSeats
=
new
ArrayList
<>();
// 仅补充数据库中从未创建过的编号,所有新增ID由MyBatis-Plus生成字符串雪花ID。
for
(
int
seatNo
=
1
;
seatNo
<=
seatCount
;
seatNo
++)
{
if
(!
existingNumbers
.
contains
(
seatNo
))
{
TrainingRoomSeatEntity
seat
=
new
TrainingRoomSeatEntity
();
seat
.
setRoomId
(
roomId
);
seat
.
setSeatNo
(
seatNo
);
seat
.
setEnabled
(
true
);
newSeats
.
add
(
seat
);
}
}
if
(!
newSeats
.
isEmpty
())
{
saveBatch
(
newSeats
);
}
}
}
practical-business/src/main/java/com/platform/business/service/impl/TrainingRoomServiceImpl.java
0 → 100644
View file @
9e0dacc7
package
com.platform.business.service.impl
;
import
com.baomidou.mybatisplus.extension.service.impl.ServiceImpl
;
import
com.platform.business.constant.TrainingRoomConstants
;
import
com.platform.business.mapper.TrainingRoomMapper
;
import
com.platform.business.model.dto.TrainingRoomDTO
;
import
com.platform.business.model.entity.TrainingRoomEntity
;
import
com.platform.business.model.entity.UserEntity
;
import
com.platform.business.model.vo.TrainingRoomStatisticsVO
;
import
com.platform.business.model.vo.TrainingRoomVO
;
import
com.platform.business.service.TrainingRoomSeatService
;
import
com.platform.business.service.TrainingRoomService
;
import
com.platform.business.service.UserService
;
import
com.platform.exception.BusinessException
;
import
org.springframework.stereotype.Service
;
import
org.springframework.transaction.annotation.Transactional
;
import
org.springframework.util.StringUtils
;
import
javax.annotation.Resource
;
import
java.math.BigDecimal
;
import
java.time.LocalTime
;
import
java.time.format.DateTimeFormatter
;
import
java.time.format.DateTimeParseException
;
import
java.util.Date
;
import
java.util.List
;
import
java.util.Locale
;
import
java.util.Objects
;
/** 实训室管理业务实现。 */
@Service
public
class
TrainingRoomServiceImpl
extends
ServiceImpl
<
TrainingRoomMapper
,
TrainingRoomEntity
>
implements
TrainingRoomService
{
private
static
final
DateTimeFormatter
TIME_FORMATTER
=
DateTimeFormatter
.
ofPattern
(
"HH:mm:ss"
);
@Resource
private
TrainingRoomSeatService
trainingRoomSeatService
;
@Resource
private
UserService
userService
;
@Override
public
List
<
TrainingRoomVO
>
adminList
(
TrainingRoomDTO
query
,
Date
now
)
{
normalizeQuery
(
query
,
false
);
return
baseMapper
.
selectAdminList
(
query
,
now
);
}
@Override
public
List
<
TrainingRoomVO
>
studentList
(
TrainingRoomDTO
query
,
Date
now
)
{
normalizeQuery
(
query
,
true
);
return
baseMapper
.
selectStudentList
(
query
,
now
);
}
@Override
public
TrainingRoomVO
detail
(
String
id
,
Date
now
)
{
requireRoom
(
id
);
return
baseMapper
.
selectDetail
(
id
,
now
);
}
@Override
public
TrainingRoomStatisticsVO
adminStatistics
(
Date
now
)
{
return
baseMapper
.
selectAdminStatistics
(
now
);
}
@Override
public
TrainingRoomStatisticsVO
studentStatistics
(
Date
now
)
{
return
baseMapper
.
selectStudentStatistics
(
now
);
}
@Override
@Transactional
(
rollbackFor
=
Exception
.
class
)
public
TrainingRoomVO
createRoom
(
TrainingRoomDTO
request
)
{
validateAndNormalizeRoom
(
request
);
if
(
baseMapper
.
countSameName
(
request
.
getName
(),
null
)
>
0
)
{
throw
new
BusinessException
(
"实训室名称已存在"
);
}
TrainingRoomEntity
room
=
copyEditableFields
(
request
);
room
.
setStatus
(
StringUtils
.
hasText
(
request
.
getStatus
())
?
request
.
getStatus
()
:
TrainingRoomConstants
.
ROOM_RUNNING
);
validateRoomStatus
(
room
.
getStatus
());
room
.
setDelFlag
(
0
);
if
(!
save
(
room
))
{
throw
new
BusinessException
(
"实训室创建失败"
);
}
// 创建实训室后生成1至seatCount的连续机位编号。
trainingRoomSeatService
.
synchronizeSeats
(
room
.
getId
(),
room
.
getSeatCount
());
return
baseMapper
.
selectDetail
(
room
.
getId
(),
new
Date
());
}
@Override
@Transactional
(
rollbackFor
=
Exception
.
class
)
public
boolean
updateRoom
(
TrainingRoomDTO
request
)
{
if
(
request
==
null
||
!
StringUtils
.
hasText
(
request
.
getId
()))
{
throw
new
BusinessException
(
"实训室ID不能为空"
);
}
TrainingRoomEntity
current
=
requireRoom
(
request
.
getId
());
validateAndNormalizeRoom
(
request
);
if
(
baseMapper
.
countSameName
(
request
.
getName
(),
request
.
getId
())
>
0
)
{
throw
new
BusinessException
(
"实训室名称已存在"
);
}
boolean
reducingSeats
=
request
.
getSeatCount
()
<
current
.
getSeatCount
();
boolean
changingOpenTime
=
!
Objects
.
equals
(
request
.
getAllDay
(),
current
.
getAllDay
())
||
!
Objects
.
equals
(
request
.
getOpenStart
(),
current
.
getOpenStart
())
||
!
Objects
.
equals
(
request
.
getOpenEnd
(),
current
.
getOpenEnd
());
if
((
reducingSeats
||
changingOpenTime
)
&&
baseMapper
.
countActiveBookingsAfter
(
current
.
getId
(),
new
Date
())
>
0
)
{
throw
new
BusinessException
(
"存在未结束预约,请先取消相关预约后再缩减机位或修改开放时间"
);
}
TrainingRoomEntity
update
=
copyEditableFields
(
request
);
update
.
setId
(
current
.
getId
());
// 状态只能通过单独的启用/停用接口修改,避免编辑表单绕过预约检查。
update
.
setStatus
(
current
.
getStatus
());
update
.
setUpdateTime
(
new
Date
());
if
(!
updateById
(
update
))
{
throw
new
BusinessException
(
"实训室更新失败"
);
}
trainingRoomSeatService
.
synchronizeSeats
(
current
.
getId
(),
request
.
getSeatCount
());
return
true
;
}
@Override
@Transactional
(
rollbackFor
=
Exception
.
class
)
public
boolean
updateStatus
(
String
id
,
String
status
)
{
TrainingRoomEntity
room
=
requireRoom
(
id
);
String
normalizedStatus
=
status
==
null
?
""
:
status
.
trim
().
toLowerCase
(
Locale
.
ROOT
);
validateRoomStatus
(
normalizedStatus
);
if
(
Objects
.
equals
(
room
.
getStatus
(),
normalizedStatus
))
{
return
true
;
}
if
(
TrainingRoomConstants
.
ROOM_DISABLED
.
equals
(
normalizedStatus
)
&&
baseMapper
.
countActiveBookingsAfter
(
id
,
new
Date
())
>
0
)
{
throw
new
BusinessException
(
"存在未结束预约,请先取消相关预约后再停用实训室"
);
}
TrainingRoomEntity
update
=
new
TrainingRoomEntity
();
update
.
setId
(
id
);
update
.
setStatus
(
normalizedStatus
);
update
.
setUpdateTime
(
new
Date
());
if
(!
updateById
(
update
))
{
throw
new
BusinessException
(
"实训室状态更新失败"
);
}
return
true
;
}
/** 根据ID查询未逻辑删除的实训室,不存在时统一抛出业务异常。 */
private
TrainingRoomEntity
requireRoom
(
String
id
)
{
if
(!
StringUtils
.
hasText
(
id
))
{
throw
new
BusinessException
(
"实训室ID不能为空"
);
}
TrainingRoomEntity
room
=
getById
(
id
);
if
(
room
==
null
)
{
throw
new
BusinessException
(
"实训室不存在"
);
}
return
room
;
}
/** 校验必填字段,并将开放时间统一规范为 HH:mm:ss。 */
private
void
validateAndNormalizeRoom
(
TrainingRoomDTO
room
)
{
if
(
room
==
null
)
{
throw
new
BusinessException
(
"实训室参数不能为空"
);
}
if
(!
StringUtils
.
hasText
(
room
.
getName
()))
{
throw
new
BusinessException
(
"实训室名称不能为空"
);
}
if
(!
StringUtils
.
hasText
(
room
.
getLocation
()))
{
throw
new
BusinessException
(
"实训室位置不能为空"
);
}
room
.
setName
(
room
.
getName
().
trim
());
room
.
setLocation
(
room
.
getLocation
().
trim
());
if
(
room
.
getName
().
length
()
>
100
||
room
.
getLocation
().
length
()
>
200
)
{
throw
new
BusinessException
(
"实训室名称或位置长度超出限制"
);
}
if
(
room
.
getSeatCount
()
==
null
||
room
.
getSeatCount
()
<
1
)
{
throw
new
BusinessException
(
"机位总数必须大于0"
);
}
if
(
room
.
getArea
()
!=
null
&&
room
.
getArea
().
compareTo
(
BigDecimal
.
ZERO
)
<
0
)
{
throw
new
BusinessException
(
"实训室面积不能小于0"
);
}
validateManager
(
room
.
getManagerId
());
boolean
allDay
=
Boolean
.
TRUE
.
equals
(
room
.
getAllDay
());
room
.
setAllDay
(
allDay
);
if
(
allDay
)
{
room
.
setOpenStart
(
null
);
room
.
setOpenEnd
(
null
);
}
else
{
LocalTime
start
=
parseTime
(
room
.
getOpenStart
(),
"开放开始时间"
);
LocalTime
end
=
parseTime
(
room
.
getOpenEnd
(),
"开放结束时间"
);
if
(!
start
.
isBefore
(
end
))
{
throw
new
BusinessException
(
"开放开始时间必须早于结束时间"
);
}
room
.
setOpenStart
(
start
.
format
(
TIME_FORMATTER
));
room
.
setOpenEnd
(
end
.
format
(
TIME_FORMATTER
));
}
}
/** 管理员字段可以为空;有值时必须关联到有效的user.id。 */
private
void
validateManager
(
String
managerId
)
{
if
(!
StringUtils
.
hasText
(
managerId
))
{
return
;
}
UserEntity
manager
=
userService
.
getById
(
managerId
);
if
(
manager
==
null
||
Boolean
.
TRUE
.
equals
(
manager
.
getDelFlag
()))
{
throw
new
BusinessException
(
"实训室管理员不存在"
);
}
}
/** 实训室状态仅允许running和disabled。 */
private
void
validateRoomStatus
(
String
status
)
{
if
(!
TrainingRoomConstants
.
ROOM_RUNNING
.
equals
(
status
)
&&
!
TrainingRoomConstants
.
ROOM_DISABLED
.
equals
(
status
))
{
throw
new
BusinessException
(
"实训室状态只支持运行中或已停用"
);
}
}
/** 兼容HH:mm和HH:mm:ss输入,并统一转换为HH:mm:ss。 */
private
LocalTime
parseTime
(
String
value
,
String
fieldName
)
{
if
(!
StringUtils
.
hasText
(
value
))
{
throw
new
BusinessException
(
fieldName
+
"不能为空"
);
}
try
{
String
normalized
=
value
.
trim
().
length
()
==
5
?
value
.
trim
()
+
":00"
:
value
.
trim
();
return
LocalTime
.
parse
(
normalized
,
TIME_FORMATTER
);
}
catch
(
DateTimeParseException
e
)
{
throw
new
BusinessException
(
fieldName
+
"格式必须为HH:mm"
);
}
}
/** 只复制管理员允许编辑的字段,防止覆盖逻辑删除和审计字段。 */
private
TrainingRoomEntity
copyEditableFields
(
TrainingRoomDTO
source
)
{
TrainingRoomEntity
target
=
new
TrainingRoomEntity
();
target
.
setName
(
source
.
getName
());
target
.
setLocation
(
source
.
getLocation
());
target
.
setArea
(
source
.
getArea
());
target
.
setAllDay
(
source
.
getAllDay
());
target
.
setOpenStart
(
source
.
getOpenStart
());
target
.
setOpenEnd
(
source
.
getOpenEnd
());
target
.
setSeatCount
(
source
.
getSeatCount
());
target
.
setLayoutDescription
(
StringUtils
.
hasText
(
source
.
getLayoutDescription
())
?
source
.
getLayoutDescription
().
trim
()
:
source
.
getSeatCount
()
+
"个机位"
);
target
.
setManagerId
(
StringUtils
.
hasText
(
source
.
getManagerId
())
?
source
.
getManagerId
().
trim
()
:
null
);
target
.
setRemark
(
StringUtils
.
hasText
(
source
.
getRemark
())
?
source
.
getRemark
().
trim
()
:
null
);
return
target
;
}
/** 清理列表查询参数,并分别校验管理员端状态和学员端动态状态。 */
private
void
normalizeQuery
(
TrainingRoomDTO
query
,
boolean
student
)
{
if
(
query
==
null
)
{
throw
new
BusinessException
(
"查询参数不能为空"
);
}
if
(
StringUtils
.
hasText
(
query
.
getKeyword
()))
{
query
.
setKeyword
(
query
.
getKeyword
().
trim
());
}
if
(
student
&&
StringUtils
.
hasText
(
query
.
getAvailabilityStatus
()))
{
String
status
=
query
.
getAvailabilityStatus
().
trim
().
toLowerCase
(
Locale
.
ROOT
);
if
(!
"all"
.
equals
(
status
)
&&
!
"free"
.
equals
(
status
)
&&
!
"busy"
.
equals
(
status
)
&&
!
"full"
.
equals
(
status
))
{
throw
new
BusinessException
(
"不支持的实训室可用状态"
);
}
query
.
setAvailabilityStatus
(
status
);
}
if
(!
student
&&
StringUtils
.
hasText
(
query
.
getStatus
()))
{
String
status
=
query
.
getStatus
().
trim
().
toLowerCase
(
Locale
.
ROOT
);
if
(!
"all"
.
equals
(
status
))
{
validateRoomStatus
(
status
);
}
query
.
setStatus
(
status
);
}
}
}
practical-business/src/main/java/com/platform/business/task/AttendanceAutoCloseTask.java
0 → 100644
View file @
9e0dacc7
package
com.platform.business.task
;
import
com.platform.business.service.AttendanceService
;
import
org.springframework.scheduling.annotation.Scheduled
;
import
org.springframework.stereotype.Component
;
import
javax.annotation.Resource
;
@Component
public
class
AttendanceAutoCloseTask
{
@Resource
private
AttendanceService
attendanceService
;
/** 每分钟将已结束课程中仍无签到记录的学员自动记为缺勤。 */
@Scheduled
(
cron
=
"0 * * * * ?"
)
public
void
closeEndedSubjects
()
{
attendanceService
.
finalizeEndedSubjects
(
null
,
null
);
}
}
practical-business/src/main/java/com/platform/business/util/ClassSubjectTimeUtils.java
0 → 100644
View file @
9e0dacc7
package
com.platform.business.util
;
import
com.platform.business.model.entity.ClassSubjectEntity
;
import
com.platform.exception.BusinessException
;
import
java.time.Instant
;
import
java.time.LocalDate
;
import
java.time.LocalDateTime
;
import
java.time.LocalTime
;
import
java.time.ZoneId
;
import
java.time.format.DateTimeFormatter
;
import
java.time.format.DateTimeParseException
;
import
java.util.Date
;
public
final
class
ClassSubjectTimeUtils
{
private
static
final
DateTimeFormatter
TIME_FORMATTER
=
DateTimeFormatter
.
ofPattern
(
"H:mm"
);
private
ClassSubjectTimeUtils
()
{
}
public
static
TimeWindow
resolve
(
ClassSubjectEntity
subject
)
{
if
(
subject
==
null
||
subject
.
getDate
()
==
null
||
subject
.
getTimeFrame
()
==
null
||
subject
.
getTimeFrame
().
trim
().
isEmpty
())
{
throw
new
BusinessException
(
"课程日期或上课时段未配置"
);
}
LocalDate
date
=
Instant
.
ofEpochMilli
(
subject
.
getDate
().
getTime
())
.
atZone
(
ZoneId
.
systemDefault
()).
toLocalDate
();
LocalTime
earliest
=
null
;
LocalTime
latest
=
null
;
String
normalized
=
subject
.
getTimeFrame
().
replace
(
'—'
,
'-'
).
replace
(
'–'
,
'-'
);
for
(
String
frame
:
normalized
.
split
(
","
))
{
String
[]
times
=
frame
.
trim
().
split
(
"-"
,
-
1
);
if
(
times
.
length
!=
2
)
{
continue
;
}
try
{
LocalTime
start
=
LocalTime
.
parse
(
times
[
0
].
trim
(),
TIME_FORMATTER
);
LocalTime
end
=
LocalTime
.
parse
(
times
[
1
].
trim
(),
TIME_FORMATTER
);
if
(!
end
.
isAfter
(
start
))
{
throw
new
BusinessException
(
"课程结束时间必须晚于开始时间"
);
}
if
(
earliest
==
null
||
start
.
isBefore
(
earliest
))
{
earliest
=
start
;
}
if
(
latest
==
null
||
end
.
isAfter
(
latest
))
{
latest
=
end
;
}
}
catch
(
DateTimeParseException
e
)
{
throw
new
BusinessException
(
"课程时段格式不正确,应为 HH:mm-HH:mm"
);
}
}
if
(
earliest
==
null
||
latest
==
null
)
{
throw
new
BusinessException
(
"课程时段格式不正确,应为 HH:mm-HH:mm"
);
}
ZoneId
zone
=
ZoneId
.
systemDefault
();
return
new
TimeWindow
(
Date
.
from
(
LocalDateTime
.
of
(
date
,
earliest
).
atZone
(
zone
).
toInstant
()),
Date
.
from
(
LocalDateTime
.
of
(
date
,
latest
).
atZone
(
zone
).
toInstant
()));
}
public
static
final
class
TimeWindow
{
private
final
Date
start
;
private
final
Date
end
;
private
TimeWindow
(
Date
start
,
Date
end
)
{
this
.
start
=
start
;
this
.
end
=
end
;
}
public
Date
getStart
()
{
return
start
;
}
public
Date
getEnd
()
{
return
end
;
}
}
}
practical-business/src/main/java/com/platform/business/util/IpNetworkMatcher.java
0 → 100644
View file @
9e0dacc7
package
com.platform.business.util
;
import
com.platform.exception.BusinessException
;
import
java.util.List
;
/** 只接受数字形式的IPv4地址,避免通过InetAddress触发DNS解析。 */
public
final
class
IpNetworkMatcher
{
private
IpNetworkMatcher
()
{
}
public
static
boolean
matchesAny
(
String
ip
,
List
<
String
>
cidrs
)
{
if
(
cidrs
==
null
||
cidrs
.
isEmpty
())
{
throw
new
BusinessException
(
"签到允许网段尚未配置"
);
}
long
ipValue
=
parseIpv4
(
ip
);
for
(
String
cidr
:
cidrs
)
{
if
(
cidr
==
null
||
cidr
.
trim
().
isEmpty
())
{
continue
;
}
if
(
matches
(
ipValue
,
cidr
.
trim
()))
{
return
true
;
}
}
return
false
;
}
private
static
boolean
matches
(
long
ipValue
,
String
cidr
)
{
String
[]
parts
=
cidr
.
split
(
"/"
,
-
1
);
long
network
=
parseIpv4
(
parts
[
0
]);
int
prefix
=
parts
.
length
==
1
?
32
:
parsePrefix
(
parts
[
1
]);
long
mask
=
prefix
==
0
?
0L
:
(
0xFFFFFFFF
L
<<
(
32
-
prefix
))
&
0xFFFFFFFF
L
;
return
(
ipValue
&
mask
)
==
(
network
&
mask
);
}
private
static
int
parsePrefix
(
String
value
)
{
try
{
int
prefix
=
Integer
.
parseInt
(
value
);
if
(
prefix
<
0
||
prefix
>
32
)
{
throw
new
BusinessException
(
"签到网段配置不合法: /"
+
value
);
}
return
prefix
;
}
catch
(
NumberFormatException
e
)
{
throw
new
BusinessException
(
"签到网段配置不合法: /"
+
value
);
}
}
private
static
long
parseIpv4
(
String
ip
)
{
if
(
ip
==
null
)
{
throw
new
BusinessException
(
"无法获取签到IP地址"
);
}
String
[]
octets
=
ip
.
trim
().
split
(
"\\."
,
-
1
);
if
(
octets
.
length
!=
4
)
{
throw
new
BusinessException
(
"暂不支持该签到IP地址格式: "
+
ip
);
}
long
value
=
0L
;
for
(
String
octet
:
octets
)
{
try
{
if
(
octet
.
isEmpty
()
||
(
octet
.
length
()
>
1
&&
octet
.
charAt
(
0
)
==
'0'
))
{
throw
new
NumberFormatException
();
}
int
part
=
Integer
.
parseInt
(
octet
);
if
(
part
<
0
||
part
>
255
)
{
throw
new
NumberFormatException
();
}
value
=
(
value
<<
8
)
|
part
;
}
catch
(
NumberFormatException
e
)
{
throw
new
BusinessException
(
"签到IP地址不合法: "
+
ip
);
}
}
return
value
;
}
}
practical-business/src/main/resources/attendance-api.md
0 → 100644
View file @
9e0dacc7
# 出勤管理接口
所有人员均由登录令牌解析出的用户
`id`
标识;响应中的学员、教师展示字段使用完整手机号,不使用学号或教师号。
## 教师端
-
`POST /attendance/teacher/course/{subjectId}/start`
:到达计划开始时间后开始上课。首次调用生成6位验证码;后续调用返回同一课次原验证码。
-
`GET /attendance/teacher/course/{subjectId}/roster`
:查询学员姓名、完整手机号、签到时间、方式、IP和状态。
-
`PUT /attendance/teacher/status`
:教师手动设置
`NORMAL`
、
`LATE`
或
`ABSENT`
。
状态调整请求示例:
```
json
{
"subjectId"
:
1001
,
"studentId"
:
"190000000000000001"
,
"status"
:
"LATE"
}
```
## 学员端
-
`POST /attendance/student/check-in`
:课程开始15分钟内同时校验IP和验证码;超过15分钟且未到课程结束时间时只校验IP并自动记为
`LATE`
。
-
`POST /attendance/student/records`
:查询当前登录学员的出勤记录。
签到请求示例:
```
json
{
"subjectId"
:
1001
,
"verificationCode"
:
"123456"
}
```
## 管理端
-
`POST /attendance/admin/records/page`
:按班级、课程、状态、日期范围分页查询。
-
`POST /attendance/admin/statistics`
:统计应到、正常、迟到、缺勤、请假及出勤率。管理员接口不修改出勤状态。
## IP网段配置
在配置中心为业务服务补充:
```
yaml
attendance
:
verification-code-valid-minutes
:
15
allowed-ip-cidrs
:
-
192.168.10.0/24
trust-forwarded-headers
:
false
```
`allowed-ip-cidrs`
为空时系统会拒绝签到。只有入口网关会清洗并重写转发头时,才能把
`trust-forwarded-headers`
设为
`true`
。
审批通过的请假会把所关联课程的出勤状态同步为
`LEAVE`
。统计时,请假计入应到和请假次数,但不计入出勤人数,因此会降低出勤率。
practical-business/src/main/resources/bootstrap.yml
View file @
9e0dacc7
spring
:
profiles
:
active
:
dev
servlet
:
multipart
:
max-file-size
:
500MB
max-request-size
:
510MB
# 出勤签到配置。allowed-ip-cidrs 为空时签到会安全拒绝,部署前请补充实际网段。
attendance
:
verification-code-valid-minutes
:
15
allowed-ip-cidrs
:
[]
# 只有网关已清洗 X-Forwarded-For / X-Real-IP 时才开启。
trust-forwarded-headers
:
false
Prev
1
2
3
4
5
Next
Write
Preview
Markdown
is supported
0%
Try again
or
attach a new file
.
Attach a file
Cancel
You are about to add
0
people
to the discussion. Proceed with caution.
Finish editing this message first!
Cancel
Please
register
or
sign in
to comment