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
65288165
Commit
65288165
authored
Aug 07, 2026
by
王蔡翾
Browse files
出勤管理,请假管理,实验室管理
parent
903ab81c
Changes
73
Hide whitespace changes
Inline
Side-by-side
practical-business/src/main/java/com/platform/business/mapper/ClassSubjectAttendanceSessionMapper.java
0 → 100644
View file @
65288165
package
com.platform.business.mapper
;
import
com.baomidou.mybatisplus.core.mapper.BaseMapper
;
import
com.platform.business.model.entity.ClassSubjectAttendanceSessionEntity
;
import
org.apache.ibatis.annotations.Mapper
;
@Mapper
public
interface
ClassSubjectAttendanceSessionMapper
extends
BaseMapper
<
ClassSubjectAttendanceSessionEntity
>
{
int
insertIgnore
(
ClassSubjectAttendanceSessionEntity
session
);
}
practical-business/src/main/java/com/platform/business/mapper/StudentLeaveApplicationMapper.java
0 → 100644
View file @
65288165
package
com.platform.business.mapper
;
import
com.baomidou.mybatisplus.core.mapper.BaseMapper
;
import
com.platform.business.model.dto.LeaveQueryDTO
;
import
com.platform.business.model.entity.StudentLeaveApplicationEntity
;
import
com.platform.business.model.vo.LeaveApplicationVO
;
import
org.apache.ibatis.annotations.Mapper
;
import
org.apache.ibatis.annotations.Param
;
import
java.util.Date
;
import
java.util.List
;
@Mapper
public
interface
StudentLeaveApplicationMapper
extends
BaseMapper
<
StudentLeaveApplicationEntity
>
{
List
<
LeaveApplicationVO
>
queryApplications
(
LeaveQueryDTO
query
);
StudentLeaveApplicationEntity
selectByIdForUpdate
(
@Param
(
"id"
)
String
id
);
int
reviewPending
(
@Param
(
"id"
)
String
id
,
@Param
(
"status"
)
String
status
,
@Param
(
"approverId"
)
String
approverId
,
@Param
(
"approverRole"
)
String
approverRole
,
@Param
(
"approvalOpinion"
)
String
approvalOpinion
,
@Param
(
"reviewedAt"
)
Date
reviewedAt
);
int
countTeacherRelatedSubjects
(
@Param
(
"leaveId"
)
String
leaveId
,
@Param
(
"teacherId"
)
String
teacherId
);
}
practical-business/src/main/java/com/platform/business/mapper/StudentLeaveAttachmentMapper.java
0 → 100644
View file @
65288165
package
com.platform.business.mapper
;
import
com.baomidou.mybatisplus.core.mapper.BaseMapper
;
import
com.platform.business.model.entity.StudentLeaveAttachmentEntity
;
import
com.platform.business.model.vo.LeaveAttachmentVO
;
import
org.apache.ibatis.annotations.Mapper
;
import
org.apache.ibatis.annotations.Param
;
import
java.util.List
;
@Mapper
public
interface
StudentLeaveAttachmentMapper
extends
BaseMapper
<
StudentLeaveAttachmentEntity
>
{
List
<
LeaveAttachmentVO
>
queryAttachmentsByLeaveId
(
@Param
(
"leaveId"
)
String
leaveId
);
}
practical-business/src/main/java/com/platform/business/mapper/StudentLeaveSubjectMapper.java
0 → 100644
View file @
65288165
package
com.platform.business.mapper
;
import
com.baomidou.mybatisplus.core.mapper.BaseMapper
;
import
com.platform.business.model.entity.StudentLeaveSubjectEntity
;
import
com.platform.business.model.vo.LeaveSubjectVO
;
import
org.apache.ibatis.annotations.Mapper
;
import
org.apache.ibatis.annotations.Param
;
import
java.util.List
;
@Mapper
public
interface
StudentLeaveSubjectMapper
extends
BaseMapper
<
StudentLeaveSubjectEntity
>
{
List
<
LeaveSubjectVO
>
querySubjectsByLeaveId
(
@Param
(
"leaveId"
)
String
leaveId
);
}
practical-business/src/main/java/com/platform/business/mapper/TrainingRoomBookingLogMapper.java
0 → 100644
View file @
65288165
package
com.platform.business.mapper
;
import
com.baomidou.mybatisplus.core.mapper.BaseMapper
;
import
com.platform.business.model.entity.TrainingRoomBookingLogEntity
;
import
org.apache.ibatis.annotations.Mapper
;
import
org.apache.ibatis.annotations.Param
;
import
java.util.List
;
/** 预约操作时间线数据访问接口。 */
@Mapper
public
interface
TrainingRoomBookingLogMapper
extends
BaseMapper
<
TrainingRoomBookingLogEntity
>
{
/** 查询指定预约的完整操作时间线,并按操作时间升序返回。 */
List
<
TrainingRoomBookingLogEntity
>
selectByBookingId
(
@Param
(
"bookingId"
)
String
bookingId
);
}
practical-business/src/main/java/com/platform/business/mapper/TrainingRoomBookingMapper.java
0 → 100644
View file @
65288165
package
com.platform.business.mapper
;
import
com.baomidou.mybatisplus.core.mapper.BaseMapper
;
import
com.platform.business.model.dto.TrainingRoomBookingDTO
;
import
com.platform.business.model.entity.TrainingRoomBookingEntity
;
import
com.platform.business.model.vo.TrainingRoomBookingStatisticsVO
;
import
com.platform.business.model.vo.TrainingRoomBookingVO
;
import
org.apache.ibatis.annotations.Mapper
;
import
org.apache.ibatis.annotations.Param
;
import
java.util.Date
;
import
java.util.List
;
/** 预约查询、冲突校验和状态流转数据访问接口。 */
@Mapper
public
interface
TrainingRoomBookingMapper
extends
BaseMapper
<
TrainingRoomBookingEntity
>
{
/** 管理员按实训室、日期、状态和关键字查询预约列表。 */
List
<
TrainingRoomBookingVO
>
selectAdminList
(
@Param
(
"query"
)
TrainingRoomBookingDTO
query
);
/** 查询指定学员自己的预约列表。 */
List
<
TrainingRoomBookingVO
>
selectStudentList
(
@Param
(
"studentId"
)
String
studentId
,
@Param
(
"query"
)
TrainingRoomBookingDTO
query
);
/** 查询预约详情及关联的实训室信息。 */
TrainingRoomBookingVO
selectDetail
(
@Param
(
"id"
)
String
id
);
/** 按状态统计指定实训室的预约数量。 */
TrainingRoomBookingStatisticsVO
selectStatistics
(
@Param
(
"roomId"
)
String
roomId
);
/** 统计同一实训室、日期、时段和机位上的有效预约,用于冲突校验。 */
int
countSeatConflict
(
@Param
(
"roomId"
)
String
roomId
,
@Param
(
"bookingDate"
)
String
bookingDate
,
@Param
(
"slotCode"
)
Integer
slotCode
,
@Param
(
"seatNo"
)
Integer
seatNo
);
/** 统计同一学员、日期和时段上的有效预约,用于冲突校验。 */
int
countStudentConflict
(
@Param
(
"studentId"
)
String
studentId
,
@Param
(
"bookingDate"
)
String
bookingDate
,
@Param
(
"slotCode"
)
Integer
slotCode
);
/** 查询已经到达开始时间、但状态仍为booked的预约。 */
List
<
TrainingRoomBookingEntity
>
selectDueBooked
(
@Param
(
"now"
)
Date
now
);
/** 查询已经到达结束时间、但状态仍为using的预约。 */
List
<
TrainingRoomBookingEntity
>
selectDueUsing
(
@Param
(
"now"
)
Date
now
);
/** 以条件更新方式将预约从booked变更为using。 */
int
startBooking
(
@Param
(
"id"
)
String
id
,
@Param
(
"actualStartTime"
)
Date
actualStartTime
);
/** 以条件更新方式将预约从using变更为done并释放唯一约束。 */
int
finishUsingBooking
(
@Param
(
"id"
)
String
id
,
@Param
(
"actualEndTime"
)
Date
actualEndTime
);
/** 服务停机跨过完整预约时段时,将booked预约直接补偿为done。 */
int
finishExpiredBooked
(
@Param
(
"id"
)
String
id
);
/** 仅在预约尚未开始时将其取消,并释放唯一约束。 */
int
cancelBooked
(
@Param
(
"id"
)
String
id
,
@Param
(
"cancelTime"
)
Date
cancelTime
,
@Param
(
"cancelBy"
)
String
cancelBy
);
}
practical-business/src/main/java/com/platform/business/mapper/TrainingRoomMapper.java
0 → 100644
View file @
65288165
package
com.platform.business.mapper
;
import
com.baomidou.mybatisplus.core.mapper.BaseMapper
;
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
org.apache.ibatis.annotations.Mapper
;
import
org.apache.ibatis.annotations.Param
;
import
java.util.Date
;
import
java.util.List
;
/** 实训室列表、详情与KPI数据访问接口。 */
@Mapper
public
interface
TrainingRoomMapper
extends
BaseMapper
<
TrainingRoomEntity
>
{
/** 管理员查询全部有效实训室及当前使用情况。 */
List
<
TrainingRoomVO
>
selectAdminList
(
@Param
(
"query"
)
TrainingRoomDTO
query
,
@Param
(
"now"
)
Date
now
);
/** 学员查询运行中的实训室及当前使用情况。 */
List
<
TrainingRoomVO
>
selectStudentList
(
@Param
(
"query"
)
TrainingRoomDTO
query
,
@Param
(
"now"
)
Date
now
);
/** 查询单个实训室详情及动态统计数据。 */
TrainingRoomVO
selectDetail
(
@Param
(
"id"
)
String
id
,
@Param
(
"now"
)
Date
now
);
/** 查询管理员端实训室KPI。 */
TrainingRoomStatisticsVO
selectAdminStatistics
(
@Param
(
"now"
)
Date
now
);
/** 查询学员端运行中实训室KPI。 */
TrainingRoomStatisticsVO
selectStudentStatistics
(
@Param
(
"now"
)
Date
now
);
/** 检查有效实训室名称是否重复,编辑时排除当前ID。 */
int
countSameName
(
@Param
(
"name"
)
String
name
,
@Param
(
"excludeId"
)
String
excludeId
);
/** 统计指定实训室当前尚未结束的有效预约。 */
int
countActiveBookingsAfter
(
@Param
(
"roomId"
)
String
roomId
,
@Param
(
"now"
)
Date
now
);
}
practical-business/src/main/java/com/platform/business/mapper/TrainingRoomSeatMapper.java
0 → 100644
View file @
65288165
package
com.platform.business.mapper
;
import
com.baomidou.mybatisplus.core.mapper.BaseMapper
;
import
com.platform.business.model.entity.TrainingRoomSeatEntity
;
import
com.platform.business.model.vo.TrainingRoomSeatVO
;
import
org.apache.ibatis.annotations.Mapper
;
import
org.apache.ibatis.annotations.Param
;
import
java.util.List
;
/** 机位定义与指定时段可用状态查询。 */
@Mapper
public
interface
TrainingRoomSeatMapper
extends
BaseMapper
<
TrainingRoomSeatEntity
>
{
/** 查询实训室的全部机位定义,包括缩容后停用的机位。 */
List
<
TrainingRoomSeatEntity
>
selectAllByRoom
(
@Param
(
"roomId"
)
String
roomId
);
/** 校验指定编号是否为当前启用机位。 */
TrainingRoomSeatEntity
selectEnabledSeat
(
@Param
(
"roomId"
)
String
roomId
,
@Param
(
"seatNo"
)
Integer
seatNo
);
/** 一次返回指定实训室、日期和时段下的全部启用机位及动态状态。 */
List
<
TrainingRoomSeatVO
>
selectAvailability
(
@Param
(
"roomId"
)
String
roomId
,
@Param
(
"bookingDate"
)
String
bookingDate
,
@Param
(
"slotCode"
)
Integer
slotCode
);
/** 扩容时重新启用编号不大于新机位总数的历史机位。 */
int
enableSeatsUpTo
(
@Param
(
"roomId"
)
String
roomId
,
@Param
(
"seatCount"
)
Integer
seatCount
);
/** 缩容时停用编号大于新机位总数的机位。 */
int
disableSeatsAbove
(
@Param
(
"roomId"
)
String
roomId
,
@Param
(
"seatCount"
)
Integer
seatCount
);
}
practical-business/src/main/java/com/platform/business/service/AttendanceService.java
0 → 100644
View file @
65288165
package
com.platform.business.service
;
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.vo.AttendanceRecordVO
;
import
com.platform.business.model.vo.AttendanceSessionVO
;
import
com.platform.business.model.vo.AttendanceSummaryVO
;
import
java.util.Date
;
import
java.util.List
;
public
interface
AttendanceService
{
AttendanceSessionVO
startClass
(
Integer
subjectId
,
String
teacherId
);
AttendanceRecordVO
checkIn
(
AttendanceCheckInDTO
request
,
String
studentId
,
String
clientIp
);
AttendanceRecordVO
updateStatus
(
AttendanceStatusUpdateDTO
request
,
String
teacherId
);
List
<
AttendanceRecordVO
>
teacherRoster
(
Integer
subjectId
,
String
teacherId
);
List
<
AttendanceRecordVO
>
queryRecords
(
AttendanceQueryDTO
query
);
AttendanceSummaryVO
querySummary
(
AttendanceQueryDTO
query
);
void
finalizeEndedSubjects
(
Date
startDate
,
Date
endDate
);
}
practical-business/src/main/java/com/platform/business/service/ClassSubjectAttendanceSessionService.java
0 → 100644
View file @
65288165
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 @
65288165
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/TrainingRoomBookingService.java
0 → 100644
View file @
65288165
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 @
65288165
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 @
65288165
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 @
65288165
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/ClassSubjectAttendanceSessionServiceImpl.java
0 → 100644
View file @
65288165
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 @
65288165
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/TrainingRoomBookingServiceImpl.java
0 → 100644
View file @
65288165
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 @
65288165
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 @
65288165
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
);
}
}
}
Prev
1
2
3
4
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