实现员工规则排班设置

This commit is contained in:
2026-06-26 21:40:13 +08:00
parent dc6e13f0a8
commit 5fc0e35759
21 changed files with 1435 additions and 51 deletions
@@ -0,0 +1,19 @@
package com.xiaowang.fingertipdesigner.core.modules.artist.dto;
import lombok.Data;
import java.time.LocalDate;
import java.time.LocalTime;
@Data
public class ArtistScheduleExceptionDTO {
private Long shopId;
private Long artistId;
private LocalDate workDate;
private String exceptionType;
private LocalTime startTime;
private LocalTime endTime;
private Integer slotMinutes;
private Integer capacity;
private String remark;
}
@@ -0,0 +1,20 @@
package com.xiaowang.fingertipdesigner.core.modules.artist.dto;
import lombok.Data;
import java.time.LocalTime;
import java.util.List;
@Data
public class ArtistScheduleRuleDTO {
private Long shopId;
private Long artistId;
private String presetType;
private List<Integer> workDays;
private LocalTime startTime;
private LocalTime endTime;
private Integer slotMinutes;
private Integer capacity;
private Integer status;
private String remark;
}
@@ -0,0 +1,38 @@
package com.xiaowang.fingertipdesigner.core.modules.artist.entity;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableLogic;
import com.baomidou.mybatisplus.annotation.TableName;
import com.xiaowang.fingertipdesigner.core.common.entity.BaseEntity;
import lombok.Data;
import lombok.EqualsAndHashCode;
import java.time.LocalDate;
import java.time.LocalTime;
@Data
@EqualsAndHashCode(callSuper = true)
@TableName("t_artist_schedule_exception")
public class ArtistScheduleExceptionDO extends BaseEntity {
@TableField("shop_id")
private Long shopId;
@TableField("artist_id")
private Long artistId;
@TableField("work_date")
private LocalDate workDate;
@TableField("exception_type")
private String exceptionType;
@TableField("start_time")
private LocalTime startTime;
@TableField("end_time")
private LocalTime endTime;
@TableField("slot_minutes")
private Integer slotMinutes;
@TableField("capacity")
private Integer capacity;
@TableField("remark")
private String remark;
@TableField("is_delete")
@TableLogic
private Integer isDelete;
}
@@ -0,0 +1,39 @@
package com.xiaowang.fingertipdesigner.core.modules.artist.entity;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableLogic;
import com.baomidou.mybatisplus.annotation.TableName;
import com.xiaowang.fingertipdesigner.core.common.entity.BaseEntity;
import lombok.Data;
import lombok.EqualsAndHashCode;
import java.time.LocalTime;
@Data
@EqualsAndHashCode(callSuper = true)
@TableName("t_artist_schedule_rule")
public class ArtistScheduleRuleDO extends BaseEntity {
@TableField("shop_id")
private Long shopId;
@TableField("artist_id")
private Long artistId;
@TableField("preset_type")
private String presetType;
@TableField("work_days")
private String workDays;
@TableField("start_time")
private LocalTime startTime;
@TableField("end_time")
private LocalTime endTime;
@TableField("slot_minutes")
private Integer slotMinutes;
@TableField("capacity")
private Integer capacity;
@TableField("status")
private Integer status;
@TableField("remark")
private String remark;
@TableField("is_delete")
@TableLogic
private Integer isDelete;
}
@@ -0,0 +1,9 @@
package com.xiaowang.fingertipdesigner.core.modules.artist.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.xiaowang.fingertipdesigner.core.modules.artist.entity.ArtistScheduleExceptionDO;
import org.apache.ibatis.annotations.Mapper;
@Mapper
public interface ArtistScheduleExceptionMapper extends BaseMapper<ArtistScheduleExceptionDO> {
}
@@ -5,6 +5,7 @@ import com.xiaowang.fingertipdesigner.core.modules.artist.entity.ArtistScheduleD
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;
import java.time.LocalDate;
import java.time.LocalTime;
@@ -19,4 +20,28 @@ public interface ArtistScheduleMapper extends BaseMapper<ArtistScheduleDO> {
@Param("workDate") LocalDate workDate,
@Param("startTime") LocalTime startTime,
@Param("endTime") LocalTime endTime);
@Select("SELECT * FROM t_artist_schedule WHERE shop_id = #{shopId} AND artist_id = #{artistId} " +
"AND work_date = #{workDate} AND is_delete = 0 ORDER BY start_time ASC LIMIT 1 FOR UPDATE")
ArtistScheduleDO selectDayScheduleForUpdate(@Param("shopId") Long shopId,
@Param("artistId") Long artistId,
@Param("workDate") LocalDate workDate);
@Select("SELECT * FROM t_artist_schedule WHERE shop_id = #{shopId} AND artist_id = #{artistId} " +
"AND work_date = #{workDate} AND start_time = #{startTime} AND is_delete = 0 LIMIT 1 FOR UPDATE")
ArtistScheduleDO selectSlotScheduleForUpdate(@Param("shopId") Long shopId,
@Param("artistId") Long artistId,
@Param("workDate") LocalDate workDate,
@Param("startTime") LocalTime startTime);
@Update("UPDATE t_artist_schedule SET start_time = #{startTime}, end_time = #{endTime}, " +
"slot_minutes = #{slotMinutes}, capacity = #{capacity}, status = #{status}, remark = #{remark}, " +
"update_time = NOW() WHERE id = #{id} AND is_delete = 0")
int updateGeneratedSchedule(@Param("id") Long id,
@Param("startTime") LocalTime startTime,
@Param("endTime") LocalTime endTime,
@Param("slotMinutes") Integer slotMinutes,
@Param("capacity") Integer capacity,
@Param("status") Integer status,
@Param("remark") String remark);
}
@@ -0,0 +1,9 @@
package com.xiaowang.fingertipdesigner.core.modules.artist.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.xiaowang.fingertipdesigner.core.modules.artist.entity.ArtistScheduleRuleDO;
import org.apache.ibatis.annotations.Mapper;
@Mapper
public interface ArtistScheduleRuleMapper extends BaseMapper<ArtistScheduleRuleDO> {
}
@@ -1,6 +1,11 @@
package com.xiaowang.fingertipdesigner.core.modules.artist.service;
import com.xiaowang.fingertipdesigner.core.modules.artist.dto.ArtistScheduleDTO;
import com.xiaowang.fingertipdesigner.core.modules.artist.dto.ArtistScheduleExceptionDTO;
import com.xiaowang.fingertipdesigner.core.modules.artist.dto.ArtistScheduleRuleDTO;
import com.xiaowang.fingertipdesigner.core.modules.artist.vo.ArtistScheduleExceptionVO;
import com.xiaowang.fingertipdesigner.core.modules.artist.vo.ArtistScheduleRuleSettingVO;
import com.xiaowang.fingertipdesigner.core.modules.artist.vo.ArtistScheduleRuleVO;
import com.xiaowang.fingertipdesigner.core.modules.artist.vo.ArtistScheduleVO;
import java.time.LocalDate;
@@ -10,4 +15,10 @@ public interface ArtistScheduleService {
ArtistScheduleVO saveSchedule(ArtistScheduleDTO dto);
List<ArtistScheduleVO> listSchedules(Long shopId, Long artistId, LocalDate startDate, LocalDate endDate);
ArtistScheduleRuleSettingVO getRuleSetting(Long shopId, Long artistId);
ArtistScheduleRuleVO saveRule(ArtistScheduleRuleDTO dto);
ArtistScheduleExceptionVO saveException(ArtistScheduleExceptionDTO dto);
}
@@ -2,23 +2,56 @@ package com.xiaowang.fingertipdesigner.core.modules.artist.service.impl;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.xiaowang.fingertipdesigner.core.modules.artist.dto.ArtistScheduleDTO;
import com.xiaowang.fingertipdesigner.core.modules.artist.dto.ArtistScheduleExceptionDTO;
import com.xiaowang.fingertipdesigner.core.modules.artist.dto.ArtistScheduleRuleDTO;
import com.xiaowang.fingertipdesigner.core.modules.artist.entity.ArtistScheduleExceptionDO;
import com.xiaowang.fingertipdesigner.core.modules.artist.entity.ArtistScheduleDO;
import com.xiaowang.fingertipdesigner.core.modules.artist.entity.ArtistScheduleRuleDO;
import com.xiaowang.fingertipdesigner.core.modules.artist.mapper.ArtistScheduleExceptionMapper;
import com.xiaowang.fingertipdesigner.core.modules.artist.mapper.ArtistScheduleMapper;
import com.xiaowang.fingertipdesigner.core.modules.artist.mapper.ArtistScheduleRuleMapper;
import com.xiaowang.fingertipdesigner.core.modules.artist.service.ArtistScheduleService;
import com.xiaowang.fingertipdesigner.core.modules.artist.vo.ArtistScheduleExceptionVO;
import com.xiaowang.fingertipdesigner.core.modules.artist.vo.ArtistScheduleRuleSettingVO;
import com.xiaowang.fingertipdesigner.core.modules.artist.vo.ArtistScheduleRuleVO;
import com.xiaowang.fingertipdesigner.core.modules.artist.vo.ArtistScheduleVO;
import com.xiaowang.fingertipdesigner.core.modules.planning.mapper.AppointmentReservationMapper;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.time.DayOfWeek;
import java.time.LocalDate;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.function.Function;
import java.util.stream.Collectors;
@Service
@RequiredArgsConstructor
public class ArtistScheduleServiceImpl implements ArtistScheduleService {
private static final int GENERATED_DAYS = 60;
private static final int DEFAULT_SLOT_MINUTES = 60;
private static final int DEFAULT_CAPACITY = 1;
private static final String PRESET_SINGLE_REST = "SINGLE_REST";
private static final String PRESET_DOUBLE_REST = "DOUBLE_REST";
private static final String PRESET_NINE_TO_FIVE = "NINE_TO_FIVE";
private static final String PRESET_LATE_SHIFT = "LATE_SHIFT";
private static final String PRESET_CUSTOM = "CUSTOM";
private static final String EXCEPTION_REST = "REST";
private static final String EXCEPTION_EXTRA_WORK = "EXTRA_WORK";
private static final String EXCEPTION_CHANGE_SHIFT = "CHANGE_SHIFT";
private final ArtistScheduleMapper artistScheduleMapper;
private final ArtistScheduleRuleMapper ruleMapper;
private final ArtistScheduleExceptionMapper exceptionMapper;
private final AppointmentReservationMapper reservationMapper;
@Override
@Transactional
@@ -33,7 +66,14 @@ public class ArtistScheduleServiceImpl implements ArtistScheduleService {
schedule.setCapacity(dto.getCapacity() == null || dto.getCapacity() < 1 ? 1 : dto.getCapacity());
schedule.setStatus(dto.getStatus() == null ? 1 : dto.getStatus());
schedule.setIsDelete(0);
artistScheduleMapper.insert(schedule);
ArtistScheduleDO existing = artistScheduleMapper.selectSlotScheduleForUpdate(dto.getShopId(), dto.getArtistId(), dto.getWorkDate(), dto.getStartTime());
if (existing == null) {
artistScheduleMapper.insert(schedule);
} else {
schedule.setId(existing.getId());
artistScheduleMapper.updateGeneratedSchedule(existing.getId(), schedule.getStartTime(), schedule.getEndTime(),
schedule.getSlotMinutes(), schedule.getCapacity(), schedule.getStatus(), schedule.getRemark());
}
return toVO(schedule);
}
@@ -63,4 +103,329 @@ public class ArtistScheduleServiceImpl implements ArtistScheduleService {
BeanUtils.copyProperties(schedule, vo);
return vo;
}
@Override
public ArtistScheduleRuleSettingVO getRuleSetting(Long shopId, Long artistId) {
if (shopId == null || artistId == null) {
throw new RuntimeException("排班规则查询参数不完整");
}
ArtistScheduleRuleSettingVO setting = new ArtistScheduleRuleSettingVO();
ArtistScheduleRuleDO rule = selectRule(shopId, artistId);
setting.setRule(rule == null ? defaultRuleVO(shopId, artistId) : toRuleVO(rule));
setting.setExceptions(listExceptions(shopId, artistId, LocalDate.now(), LocalDate.now().plusDays(GENERATED_DAYS - 1L))
.stream()
.map(this::toExceptionVO)
.toList());
return setting;
}
@Override
@Transactional
public ArtistScheduleRuleVO saveRule(ArtistScheduleRuleDTO dto) {
ArtistScheduleRuleDO normalized = normalizeRule(dto);
ArtistScheduleRuleDO existing = selectRule(normalized.getShopId(), normalized.getArtistId());
if (existing == null) {
ruleMapper.insert(normalized);
} else {
normalized.setId(existing.getId());
ruleMapper.updateById(normalized);
}
refreshGeneratedSchedules(normalized);
return toRuleVO(normalized);
}
@Override
@Transactional
public ArtistScheduleExceptionVO saveException(ArtistScheduleExceptionDTO dto) {
ArtistScheduleExceptionDO normalized = normalizeException(dto);
ArtistScheduleRuleDO rule = selectRule(normalized.getShopId(), normalized.getArtistId());
if (rule == null) {
rule = defaultRule(normalized.getShopId(), normalized.getArtistId());
}
ArtistScheduleExceptionDO existing = selectException(normalized.getShopId(), normalized.getArtistId(), normalized.getWorkDate());
if (existing == null) {
exceptionMapper.insert(normalized);
} else {
normalized.setId(existing.getId());
exceptionMapper.updateById(normalized);
}
refreshScheduleForDate(rule, normalized, normalized.getWorkDate());
return toExceptionVO(normalized);
}
private ArtistScheduleRuleDO normalizeRule(ArtistScheduleRuleDTO dto) {
if (dto == null || dto.getShopId() == null || dto.getArtistId() == null) {
throw new RuntimeException("排班规则信息不完整");
}
String presetType = normalizePresetType(dto.getPresetType());
LocalTime startTime = dto.getStartTime() == null ? presetStartTime(presetType) : dto.getStartTime();
LocalTime endTime = dto.getEndTime() == null ? presetEndTime(presetType) : dto.getEndTime();
validateTimeRange(startTime, endTime);
ArtistScheduleRuleDO rule = new ArtistScheduleRuleDO();
rule.setShopId(dto.getShopId());
rule.setArtistId(dto.getArtistId());
rule.setPresetType(presetType);
rule.setWorkDays(encodeWorkDays(resolveWorkDays(dto.getWorkDays(), presetType)));
rule.setStartTime(startTime);
rule.setEndTime(endTime);
rule.setSlotMinutes(normalizeSlotMinutes(dto.getSlotMinutes()));
rule.setCapacity(normalizeCapacity(dto.getCapacity()));
rule.setStatus(dto.getStatus() == null ? 1 : dto.getStatus());
rule.setRemark(trimText(dto.getRemark()));
rule.setIsDelete(0);
return rule;
}
private ArtistScheduleExceptionDO normalizeException(ArtistScheduleExceptionDTO dto) {
if (dto == null || dto.getShopId() == null || dto.getArtistId() == null || dto.getWorkDate() == null) {
throw new RuntimeException("排班例外信息不完整");
}
String exceptionType = normalizeExceptionType(dto.getExceptionType());
LocalTime startTime = dto.getStartTime();
LocalTime endTime = dto.getEndTime();
if (!EXCEPTION_REST.equals(exceptionType)) {
if (startTime == null || endTime == null) {
throw new RuntimeException("临时上班或改班必须填写开始和结束时间");
}
validateTimeRange(startTime, endTime);
}
ArtistScheduleExceptionDO exception = new ArtistScheduleExceptionDO();
exception.setShopId(dto.getShopId());
exception.setArtistId(dto.getArtistId());
exception.setWorkDate(dto.getWorkDate());
exception.setExceptionType(exceptionType);
exception.setStartTime(startTime);
exception.setEndTime(endTime);
exception.setSlotMinutes(normalizeSlotMinutes(dto.getSlotMinutes()));
exception.setCapacity(normalizeCapacity(dto.getCapacity()));
exception.setRemark(trimText(dto.getRemark()));
exception.setIsDelete(0);
return exception;
}
private ArtistScheduleRuleDO selectRule(Long shopId, Long artistId) {
return ruleMapper.selectOne(new LambdaQueryWrapper<ArtistScheduleRuleDO>()
.eq(ArtistScheduleRuleDO::getShopId, shopId)
.eq(ArtistScheduleRuleDO::getArtistId, artistId)
.eq(ArtistScheduleRuleDO::getIsDelete, 0)
.last("LIMIT 1"));
}
private ArtistScheduleExceptionDO selectException(Long shopId, Long artistId, LocalDate workDate) {
return exceptionMapper.selectOne(new LambdaQueryWrapper<ArtistScheduleExceptionDO>()
.eq(ArtistScheduleExceptionDO::getShopId, shopId)
.eq(ArtistScheduleExceptionDO::getArtistId, artistId)
.eq(ArtistScheduleExceptionDO::getWorkDate, workDate)
.eq(ArtistScheduleExceptionDO::getIsDelete, 0)
.last("LIMIT 1"));
}
private List<ArtistScheduleExceptionDO> listExceptions(Long shopId, Long artistId, LocalDate start, LocalDate end) {
return exceptionMapper.selectList(new LambdaQueryWrapper<ArtistScheduleExceptionDO>()
.eq(ArtistScheduleExceptionDO::getShopId, shopId)
.eq(ArtistScheduleExceptionDO::getArtistId, artistId)
.eq(ArtistScheduleExceptionDO::getIsDelete, 0)
.between(ArtistScheduleExceptionDO::getWorkDate, start, end)
.orderByAsc(ArtistScheduleExceptionDO::getWorkDate));
}
private void refreshGeneratedSchedules(ArtistScheduleRuleDO rule) {
LocalDate start = LocalDate.now();
LocalDate end = start.plusDays(GENERATED_DAYS - 1L);
Map<LocalDate, ArtistScheduleExceptionDO> exceptionByDate = listExceptions(rule.getShopId(), rule.getArtistId(), start, end)
.stream()
.collect(Collectors.toMap(ArtistScheduleExceptionDO::getWorkDate, Function.identity(), (a, b) -> a));
LocalDate cursor = start;
while (!cursor.isAfter(end)) {
refreshScheduleForDate(rule, exceptionByDate.get(cursor), cursor);
cursor = cursor.plusDays(1L);
}
}
private void refreshScheduleForDate(ArtistScheduleRuleDO rule, ArtistScheduleExceptionDO exception, LocalDate workDate) {
GeneratedSchedule generated = resolveGeneratedSchedule(rule, exception, workDate);
if (!generated.working()) {
assertNoActiveReservations(rule.getShopId(), rule.getArtistId(), workDate);
upsertGeneratedSchedule(rule, workDate, rule.getStartTime(), rule.getEndTime(), rule.getSlotMinutes(), rule.getCapacity(), 0, generated.remark());
return;
}
assertNoReservationsOutsideSchedule(rule.getShopId(), rule.getArtistId(), workDate, generated.startTime(), generated.endTime());
upsertGeneratedSchedule(rule, workDate, generated.startTime(), generated.endTime(), generated.slotMinutes(), generated.capacity(), 1, generated.remark());
}
private GeneratedSchedule resolveGeneratedSchedule(ArtistScheduleRuleDO rule, ArtistScheduleExceptionDO exception, LocalDate workDate) {
if (exception != null) {
if (EXCEPTION_REST.equals(exception.getExceptionType())) {
return new GeneratedSchedule(false, rule.getStartTime(), rule.getEndTime(), rule.getSlotMinutes(), rule.getCapacity(), exceptionRemark(exception));
}
if (EXCEPTION_EXTRA_WORK.equals(exception.getExceptionType()) || EXCEPTION_CHANGE_SHIFT.equals(exception.getExceptionType())) {
return new GeneratedSchedule(true, exception.getStartTime(), exception.getEndTime(), exception.getSlotMinutes(), exception.getCapacity(), exceptionRemark(exception));
}
}
boolean workingDay = Integer.valueOf(1).equals(rule.getStatus()) && decodeWorkDays(rule.getWorkDays()).contains(workDate.getDayOfWeek().getValue());
return new GeneratedSchedule(workingDay, rule.getStartTime(), rule.getEndTime(), rule.getSlotMinutes(), rule.getCapacity(), "规则生成排班");
}
private void upsertGeneratedSchedule(ArtistScheduleRuleDO rule, LocalDate workDate, LocalTime startTime, LocalTime endTime,
Integer slotMinutes, Integer capacity, Integer status, String remark) {
ArtistScheduleDO schedule = artistScheduleMapper.selectDayScheduleForUpdate(rule.getShopId(), rule.getArtistId(), workDate);
if (schedule == null) {
schedule = new ArtistScheduleDO();
schedule.setShopId(rule.getShopId());
schedule.setArtistId(rule.getArtistId());
schedule.setWorkDate(workDate);
schedule.setStartTime(startTime);
schedule.setEndTime(endTime);
schedule.setSlotMinutes(slotMinutes);
schedule.setCapacity(capacity);
schedule.setStatus(status);
schedule.setRemark(remark);
schedule.setIsDelete(0);
artistScheduleMapper.insert(schedule);
return;
}
artistScheduleMapper.updateGeneratedSchedule(schedule.getId(), startTime, endTime, slotMinutes, capacity, status, remark);
}
private void assertNoActiveReservations(Long shopId, Long artistId, LocalDate workDate) {
int count = reservationMapper.countActiveByArtistAndDateForUpdate(shopId, artistId, workDate);
if (count > 0) {
throw new RuntimeException("该日期已有预约,不能设置为休假:" + workDate + ",预约数:" + count);
}
}
private void assertNoReservationsOutsideSchedule(Long shopId, Long artistId, LocalDate workDate, LocalTime startTime, LocalTime endTime) {
int count = reservationMapper.countActiveOutsideScheduleForUpdate(shopId, artistId, workDate, startTime, endTime);
if (count > 0) {
throw new RuntimeException("该日期已有预约超出新的排班时间:" + workDate + ",冲突预约数:" + count);
}
}
private ArtistScheduleRuleVO defaultRuleVO(Long shopId, Long artistId) {
return toRuleVO(defaultRule(shopId, artistId));
}
private ArtistScheduleRuleDO defaultRule(Long shopId, Long artistId) {
ArtistScheduleRuleDO rule = new ArtistScheduleRuleDO();
rule.setShopId(shopId);
rule.setArtistId(artistId);
rule.setPresetType(PRESET_DOUBLE_REST);
rule.setWorkDays(encodeWorkDays(List.of(1, 2, 3, 4, 5)));
rule.setStartTime(LocalTime.of(9, 0));
rule.setEndTime(LocalTime.of(17, 0));
rule.setSlotMinutes(DEFAULT_SLOT_MINUTES);
rule.setCapacity(DEFAULT_CAPACITY);
rule.setStatus(1);
rule.setIsDelete(0);
return rule;
}
private ArtistScheduleRuleVO toRuleVO(ArtistScheduleRuleDO rule) {
ArtistScheduleRuleVO vo = new ArtistScheduleRuleVO();
BeanUtils.copyProperties(rule, vo);
vo.setWorkDays(decodeWorkDays(rule.getWorkDays()));
return vo;
}
private ArtistScheduleExceptionVO toExceptionVO(ArtistScheduleExceptionDO exception) {
ArtistScheduleExceptionVO vo = new ArtistScheduleExceptionVO();
BeanUtils.copyProperties(exception, vo);
return vo;
}
private String normalizePresetType(String presetType) {
String value = trimText(presetType);
if (value == null || value.isBlank()) {
return PRESET_CUSTOM;
}
return value;
}
private String normalizeExceptionType(String exceptionType) {
String value = trimText(exceptionType);
if (EXCEPTION_REST.equals(value) || EXCEPTION_EXTRA_WORK.equals(value) || EXCEPTION_CHANGE_SHIFT.equals(value)) {
return value;
}
throw new RuntimeException("不支持的排班例外类型:" + value);
}
private List<Integer> resolveWorkDays(List<Integer> inputWorkDays, String presetType) {
List<Integer> presetDays = switch (presetType) {
case PRESET_DOUBLE_REST, PRESET_NINE_TO_FIVE -> List.of(1, 2, 3, 4, 5);
case PRESET_SINGLE_REST, PRESET_LATE_SHIFT -> List.of(1, 2, 3, 4, 5, 6);
default -> inputWorkDays;
};
Set<Integer> normalized = new LinkedHashSet<>();
for (Integer day : presetDays == null ? List.<Integer>of() : presetDays) {
if (day != null && day >= DayOfWeek.MONDAY.getValue() && day <= DayOfWeek.SUNDAY.getValue()) {
normalized.add(day);
}
}
if (normalized.isEmpty()) {
throw new RuntimeException("请至少选择一个工作日");
}
return normalized.stream().sorted().toList();
}
private String encodeWorkDays(List<Integer> workDays) {
return workDays.stream()
.sorted()
.map(String::valueOf)
.collect(Collectors.joining(","));
}
private List<Integer> decodeWorkDays(String workDays) {
if (workDays == null || workDays.isBlank()) {
return new ArrayList<>();
}
return List.of(workDays.split(",")).stream()
.map(String::trim)
.filter(value -> !value.isBlank())
.map(Integer::valueOf)
.sorted()
.toList();
}
private LocalTime presetStartTime(String presetType) {
if (PRESET_NINE_TO_FIVE.equals(presetType)) {
return LocalTime.of(9, 0);
}
return LocalTime.of(10, 0);
}
private LocalTime presetEndTime(String presetType) {
if (PRESET_NINE_TO_FIVE.equals(presetType)) {
return LocalTime.of(17, 0);
}
return LocalTime.of(22, 0);
}
private void validateTimeRange(LocalTime startTime, LocalTime endTime) {
if (startTime == null || endTime == null || !startTime.isBefore(endTime)) {
throw new RuntimeException("排班开始时间必须早于结束时间");
}
}
private Integer normalizeSlotMinutes(Integer slotMinutes) {
return slotMinutes == null || slotMinutes < 15 ? DEFAULT_SLOT_MINUTES : slotMinutes;
}
private Integer normalizeCapacity(Integer capacity) {
return capacity == null || capacity < 1 ? DEFAULT_CAPACITY : capacity;
}
private String trimText(String value) {
return value == null ? null : value.trim();
}
private String exceptionRemark(ArtistScheduleExceptionDO exception) {
if (exception.getRemark() != null && !exception.getRemark().isBlank()) {
return exception.getRemark();
}
return "例外排班:" + exception.getExceptionType();
}
private record GeneratedSchedule(boolean working, LocalTime startTime, LocalTime endTime, Integer slotMinutes,
Integer capacity, String remark) {
}
}
@@ -0,0 +1,22 @@
package com.xiaowang.fingertipdesigner.core.modules.artist.vo;
import lombok.Data;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
@Data
public class ArtistScheduleExceptionVO {
private Long id;
private Long shopId;
private Long artistId;
private LocalDate workDate;
private String exceptionType;
private LocalTime startTime;
private LocalTime endTime;
private Integer slotMinutes;
private Integer capacity;
private String remark;
private LocalDateTime createTime;
}
@@ -0,0 +1,11 @@
package com.xiaowang.fingertipdesigner.core.modules.artist.vo;
import lombok.Data;
import java.util.List;
@Data
public class ArtistScheduleRuleSettingVO {
private ArtistScheduleRuleVO rule;
private List<ArtistScheduleExceptionVO> exceptions;
}
@@ -0,0 +1,23 @@
package com.xiaowang.fingertipdesigner.core.modules.artist.vo;
import lombok.Data;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.List;
@Data
public class ArtistScheduleRuleVO {
private Long id;
private Long shopId;
private Long artistId;
private String presetType;
private List<Integer> workDays;
private LocalTime startTime;
private LocalTime endTime;
private Integer slotMinutes;
private Integer capacity;
private Integer status;
private String remark;
private LocalDateTime createTime;
}
@@ -5,9 +5,14 @@ import com.xiaowang.fingertipdesigner.core.annotation.RequirePermission;
import com.xiaowang.fingertipdesigner.core.common.Result;
import com.xiaowang.fingertipdesigner.core.common.vo.PageResultVO;
import com.xiaowang.fingertipdesigner.core.modules.artist.dto.ArtistScheduleDTO;
import com.xiaowang.fingertipdesigner.core.modules.artist.dto.ArtistScheduleExceptionDTO;
import com.xiaowang.fingertipdesigner.core.modules.artist.dto.ArtistScheduleRuleDTO;
import com.xiaowang.fingertipdesigner.core.modules.artist.dto.NailArtistInfoDTO;
import com.xiaowang.fingertipdesigner.core.modules.artist.service.ArtistScheduleService;
import com.xiaowang.fingertipdesigner.core.modules.artist.service.NailArtistInfoService;
import com.xiaowang.fingertipdesigner.core.modules.artist.vo.ArtistScheduleExceptionVO;
import com.xiaowang.fingertipdesigner.core.modules.artist.vo.ArtistScheduleRuleSettingVO;
import com.xiaowang.fingertipdesigner.core.modules.artist.vo.ArtistScheduleRuleVO;
import com.xiaowang.fingertipdesigner.core.modules.artist.vo.ArtistScheduleVO;
import com.xiaowang.fingertipdesigner.core.modules.manager.dto.ManagerCustomerCreateDTO;
import com.xiaowang.fingertipdesigner.core.modules.planning.dto.PlanningAppointmentCreateDTO;
@@ -218,6 +223,35 @@ public class AdminManagerController {
return Result.success(artistScheduleService.saveSchedule(dto));
}
@GetMapping("/employees/schedule-rule")
@RequirePermission("schedule:view")
public Result<ArtistScheduleRuleSettingVO> scheduleRule(HttpServletRequest request,
@RequestParam Long artistId) {
UserDO currentUser = adminScopeHelper.getCurrentUser(request);
Long shopId = adminScopeHelper.resolveShopScope(currentUser, null);
return Result.success(artistScheduleService.getRuleSetting(shopId, artistId));
}
@PostMapping("/employees/schedule-rule")
@RequirePermission("schedule:edit")
@OperationGuard(action = "manager-artist-schedule-rule-save", ttlSeconds = 10, message = "排班规则保存处理中,请勿重复提交")
public Result<ArtistScheduleRuleVO> saveScheduleRule(HttpServletRequest request,
@RequestBody ArtistScheduleRuleDTO dto) {
UserDO currentUser = adminScopeHelper.getCurrentUser(request);
dto.setShopId(adminScopeHelper.resolveShopScope(currentUser, dto.getShopId()));
return Result.success(artistScheduleService.saveRule(dto));
}
@PostMapping("/employees/schedule-exceptions")
@RequirePermission("schedule:edit")
@OperationGuard(action = "manager-artist-schedule-exception-save", ttlSeconds = 10, message = "排班例外保存处理中,请勿重复提交")
public Result<ArtistScheduleExceptionVO> saveScheduleException(HttpServletRequest request,
@RequestBody ArtistScheduleExceptionDTO dto) {
UserDO currentUser = adminScopeHelper.getCurrentUser(request);
dto.setShopId(adminScopeHelper.resolveShopScope(currentUser, dto.getShopId()));
return Result.success(artistScheduleService.saveException(dto));
}
@GetMapping("/products")
@RequirePermission("product:view")
public Result<PageResultVO<ProductVO>> products(HttpServletRequest request,
@@ -7,6 +7,7 @@ import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;
import java.time.LocalDate;
import java.time.LocalDateTime;
@Mapper
@@ -35,6 +36,23 @@ public interface AppointmentReservationMapper extends BaseMapper<AppointmentRese
@Param("startTime") LocalDateTime startTime,
@Param("endTime") LocalDateTime endTime);
@Select("SELECT COUNT(*) FROM t_appointment_reservation WHERE shop_id = #{shopId} AND artist_id = #{artistId} " +
"AND status IN " + ACTIVE_STATUS_SQL + " AND is_delete = 0 " +
"AND appointment_start_time >= #{workDate} AND appointment_start_time < DATE_ADD(#{workDate}, INTERVAL 1 DAY) FOR UPDATE")
int countActiveByArtistAndDateForUpdate(@Param("shopId") Long shopId,
@Param("artistId") Long artistId,
@Param("workDate") LocalDate workDate);
@Select("SELECT COUNT(*) FROM t_appointment_reservation WHERE shop_id = #{shopId} AND artist_id = #{artistId} " +
"AND status IN " + ACTIVE_STATUS_SQL + " AND is_delete = 0 " +
"AND appointment_start_time >= #{workDate} AND appointment_start_time < DATE_ADD(#{workDate}, INTERVAL 1 DAY) " +
"AND (TIME(appointment_start_time) < #{startTime} OR TIME(appointment_end_time) > #{endTime}) FOR UPDATE")
int countActiveOutsideScheduleForUpdate(@Param("shopId") Long shopId,
@Param("artistId") Long artistId,
@Param("workDate") LocalDate workDate,
@Param("startTime") java.time.LocalTime startTime,
@Param("endTime") java.time.LocalTime endTime);
@Update("UPDATE t_appointment_reservation SET status = #{status}, is_delete = 1, update_time = NOW() " +
"WHERE order_id = #{orderId} AND is_delete = 0")
int releaseByOrderId(@Param("orderId") Long orderId, @Param("status") String status);
@@ -0,0 +1,206 @@
package com.xiaowang.fingertipdesigner.core.modules.artist.service.impl;
import com.xiaowang.fingertipdesigner.core.modules.artist.dto.ArtistScheduleExceptionDTO;
import com.xiaowang.fingertipdesigner.core.modules.artist.dto.ArtistScheduleDTO;
import com.xiaowang.fingertipdesigner.core.modules.artist.dto.ArtistScheduleRuleDTO;
import com.xiaowang.fingertipdesigner.core.modules.artist.entity.ArtistScheduleDO;
import com.xiaowang.fingertipdesigner.core.modules.artist.entity.ArtistScheduleExceptionDO;
import com.xiaowang.fingertipdesigner.core.modules.artist.entity.ArtistScheduleRuleDO;
import com.xiaowang.fingertipdesigner.core.modules.artist.mapper.ArtistScheduleExceptionMapper;
import com.xiaowang.fingertipdesigner.core.modules.artist.mapper.ArtistScheduleMapper;
import com.xiaowang.fingertipdesigner.core.modules.artist.mapper.ArtistScheduleRuleMapper;
import com.xiaowang.fingertipdesigner.core.modules.planning.mapper.AppointmentReservationMapper;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.ArgumentCaptor;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;
import java.time.DayOfWeek;
import java.time.LocalDate;
import java.time.LocalTime;
import java.util.List;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
class ArtistScheduleServiceImplTest {
@Mock
private ArtistScheduleMapper scheduleMapper;
@Mock
private ArtistScheduleRuleMapper ruleMapper;
@Mock
private ArtistScheduleExceptionMapper exceptionMapper;
@Mock
private AppointmentReservationMapper reservationMapper;
private ArtistScheduleServiceImpl service;
@BeforeEach
void setUp() {
MockitoAnnotations.openMocks(this);
service = new ArtistScheduleServiceImpl(scheduleMapper, ruleMapper, exceptionMapper, reservationMapper);
when(ruleMapper.selectOne(any())).thenReturn(null);
when(exceptionMapper.selectList(any())).thenReturn(List.of());
when(scheduleMapper.selectDayScheduleForUpdate(eq(8L), eq(30L), any(LocalDate.class))).thenAnswer(invocation -> existingSchedule(invocation.getArgument(2)));
when(reservationMapper.countActiveByArtistAndDateForUpdate(eq(8L), eq(30L), any(LocalDate.class))).thenReturn(0);
when(reservationMapper.countActiveOutsideScheduleForUpdate(eq(8L), eq(30L), any(LocalDate.class), any(LocalTime.class), any(LocalTime.class))).thenReturn(0);
}
@Test
void saveDoubleRestRuleGeneratesWeekdaySchedulesAndWeekendRestRows() {
service.saveRule(rule("DOUBLE_REST", List.of(1, 2, 3, 4, 5), LocalTime.of(9, 0), LocalTime.of(17, 0)));
ArgumentCaptor<Integer> statusCaptor = ArgumentCaptor.forClass(Integer.class);
verify(scheduleMapper, org.mockito.Mockito.atLeastOnce()).updateGeneratedSchedule(any(), any(), any(), any(), any(), statusCaptor.capture(), any());
assertThat(statusCaptor.getAllValues()).contains(1, 0);
}
@Test
void saveCustomRuleUsesSelectedWeekdaysOnly() {
service.saveRule(rule("CUSTOM", List.of(2, 4), LocalTime.of(10, 0), LocalTime.of(20, 0)));
ArgumentCaptor<LocalDate> dateCaptor = ArgumentCaptor.forClass(LocalDate.class);
ArgumentCaptor<Integer> statusCaptor = ArgumentCaptor.forClass(Integer.class);
verify(scheduleMapper, org.mockito.Mockito.atLeastOnce()).selectDayScheduleForUpdate(eq(8L), eq(30L), dateCaptor.capture());
verify(scheduleMapper, org.mockito.Mockito.atLeastOnce()).updateGeneratedSchedule(any(), any(), any(), any(), any(), statusCaptor.capture(), any());
List<LocalDate> dates = dateCaptor.getAllValues();
List<Integer> statuses = statusCaptor.getAllValues();
for (int index = 0; index < statuses.size(); index++) {
DayOfWeek dayOfWeek = dates.get(index).getDayOfWeek();
if (List.of(DayOfWeek.TUESDAY, DayOfWeek.THURSDAY).contains(dayOfWeek)) {
assertThat(statuses.get(index)).isEqualTo(1);
} else {
assertThat(statuses.get(index)).isEqualTo(0);
}
}
}
@Test
void saveRestExceptionRejectsDateWithActiveReservation() {
LocalDate date = LocalDate.now().plusDays(1L);
when(ruleMapper.selectOne(any())).thenReturn(existingRule());
when(exceptionMapper.selectOne(any())).thenReturn(null);
when(reservationMapper.countActiveByArtistAndDateForUpdate(8L, 30L, date)).thenReturn(2);
assertThatThrownBy(() -> service.saveException(restException(date)))
.isInstanceOf(RuntimeException.class)
.hasMessageContaining(date.toString())
.hasMessageContaining("2");
verify(exceptionMapper).insert(any(ArtistScheduleExceptionDO.class));
verify(scheduleMapper, never()).updateGeneratedSchedule(any(), any(), any(), any(), any(), any(), any());
}
@Test
void saveExtraWorkExceptionGeneratesWorkingScheduleOnRestDay() {
LocalDate sunday = next(DayOfWeek.SUNDAY);
when(ruleMapper.selectOne(any())).thenReturn(existingRule());
when(exceptionMapper.selectOne(any())).thenReturn(null);
service.saveException(extraWorkException(sunday));
verify(scheduleMapper).updateGeneratedSchedule(any(), eq(LocalTime.of(10, 0)), eq(LocalTime.of(18, 0)), eq(30), eq(2), eq(1), any());
}
@Test
void saveScheduleUpdatesExistingSlotInsteadOfDuplicatingGeneratedRow() {
LocalDate date = LocalDate.now().plusDays(1L);
ArtistScheduleDTO dto = new ArtistScheduleDTO();
dto.setShopId(8L);
dto.setArtistId(30L);
dto.setWorkDate(date);
dto.setStartTime(LocalTime.of(9, 0));
dto.setEndTime(LocalTime.of(19, 0));
dto.setSlotMinutes(30);
dto.setCapacity(3);
dto.setStatus(1);
when(scheduleMapper.selectSlotScheduleForUpdate(8L, 30L, date, LocalTime.of(9, 0))).thenReturn(existingSchedule(date));
service.saveSchedule(dto);
verify(scheduleMapper, never()).insert(any(ArtistScheduleDO.class));
verify(scheduleMapper).updateGeneratedSchedule(any(), eq(LocalTime.of(9, 0)), eq(LocalTime.of(19, 0)), eq(30), eq(3), eq(1), any());
}
private ArtistScheduleRuleDTO rule(String presetType, List<Integer> workDays, LocalTime startTime, LocalTime endTime) {
ArtistScheduleRuleDTO dto = new ArtistScheduleRuleDTO();
dto.setShopId(8L);
dto.setArtistId(30L);
dto.setPresetType(presetType);
dto.setWorkDays(workDays);
dto.setStartTime(startTime);
dto.setEndTime(endTime);
dto.setSlotMinutes(60);
dto.setCapacity(1);
return dto;
}
private ArtistScheduleExceptionDTO restException(LocalDate date) {
ArtistScheduleExceptionDTO dto = new ArtistScheduleExceptionDTO();
dto.setShopId(8L);
dto.setArtistId(30L);
dto.setWorkDate(date);
dto.setExceptionType("REST");
return dto;
}
private ArtistScheduleExceptionDTO extraWorkException(LocalDate date) {
ArtistScheduleExceptionDTO dto = new ArtistScheduleExceptionDTO();
dto.setShopId(8L);
dto.setArtistId(30L);
dto.setWorkDate(date);
dto.setExceptionType("EXTRA_WORK");
dto.setStartTime(LocalTime.of(10, 0));
dto.setEndTime(LocalTime.of(18, 0));
dto.setSlotMinutes(30);
dto.setCapacity(2);
return dto;
}
private ArtistScheduleRuleDO existingRule() {
ArtistScheduleRuleDO rule = new ArtistScheduleRuleDO();
rule.setId(1L);
rule.setShopId(8L);
rule.setArtistId(30L);
rule.setPresetType("DOUBLE_REST");
rule.setWorkDays("1,2,3,4,5");
rule.setStartTime(LocalTime.of(9, 0));
rule.setEndTime(LocalTime.of(17, 0));
rule.setSlotMinutes(60);
rule.setCapacity(1);
rule.setStatus(1);
rule.setIsDelete(0);
return rule;
}
private ArtistScheduleDO existingSchedule(LocalDate date) {
ArtistScheduleDO schedule = new ArtistScheduleDO();
schedule.setId(1000L + date.getDayOfYear());
schedule.setShopId(8L);
schedule.setArtistId(30L);
schedule.setWorkDate(date);
schedule.setStartTime(LocalTime.of(9, 0));
schedule.setEndTime(LocalTime.of(17, 0));
schedule.setSlotMinutes(60);
schedule.setCapacity(1);
schedule.setStatus(1);
schedule.setIsDelete(0);
return schedule;
}
private LocalDate next(DayOfWeek dayOfWeek) {
LocalDate cursor = LocalDate.now();
while (cursor.getDayOfWeek() != dayOfWeek) {
cursor = cursor.plusDays(1L);
}
return cursor;
}
}
@@ -3,9 +3,14 @@ package com.xiaowang.fingertipdesigner.core.modules.manager.controller.admin;
import com.xiaowang.fingertipdesigner.core.common.Result;
import com.xiaowang.fingertipdesigner.core.common.vo.PageResultVO;
import com.xiaowang.fingertipdesigner.core.modules.artist.dto.ArtistScheduleDTO;
import com.xiaowang.fingertipdesigner.core.modules.artist.dto.ArtistScheduleExceptionDTO;
import com.xiaowang.fingertipdesigner.core.modules.artist.dto.ArtistScheduleRuleDTO;
import com.xiaowang.fingertipdesigner.core.modules.artist.dto.NailArtistInfoDTO;
import com.xiaowang.fingertipdesigner.core.modules.artist.service.ArtistScheduleService;
import com.xiaowang.fingertipdesigner.core.modules.artist.service.NailArtistInfoService;
import com.xiaowang.fingertipdesigner.core.modules.artist.vo.ArtistScheduleExceptionVO;
import com.xiaowang.fingertipdesigner.core.modules.artist.vo.ArtistScheduleRuleSettingVO;
import com.xiaowang.fingertipdesigner.core.modules.artist.vo.ArtistScheduleRuleVO;
import com.xiaowang.fingertipdesigner.core.modules.artist.vo.ArtistScheduleVO;
import com.xiaowang.fingertipdesigner.core.modules.manager.dto.ManagerCustomerCreateDTO;
import com.xiaowang.fingertipdesigner.core.modules.planning.service.PlanningService;
@@ -175,6 +180,55 @@ class AdminManagerControllerTest {
assertThat(dto.getShopId()).isEqualTo(8L);
}
@Test
void scheduleRuleShouldResolveShopScopeBeforeReading() {
MockHttpServletRequest request = new MockHttpServletRequest();
UserDO manager = new UserDO();
ArtistScheduleRuleSettingVO vo = new ArtistScheduleRuleSettingVO();
when(adminScopeHelper.getCurrentUser(request)).thenReturn(manager);
when(adminScopeHelper.resolveShopScope(manager, null)).thenReturn(8L);
when(artistScheduleService.getRuleSetting(8L, 30L)).thenReturn(vo);
Result<ArtistScheduleRuleSettingVO> result = controller.scheduleRule(request, 30L);
assertThat(result.getData()).isSameAs(vo);
verify(artistScheduleService).getRuleSetting(8L, 30L);
}
@Test
void saveScheduleRuleShouldResolveShopScopeBeforeSaving() {
MockHttpServletRequest request = new MockHttpServletRequest();
UserDO manager = new UserDO();
ArtistScheduleRuleDTO dto = new ArtistScheduleRuleDTO();
dto.setShopId(99L);
ArtistScheduleRuleVO vo = new ArtistScheduleRuleVO();
when(adminScopeHelper.getCurrentUser(request)).thenReturn(manager);
when(adminScopeHelper.resolveShopScope(manager, 99L)).thenReturn(8L);
when(artistScheduleService.saveRule(dto)).thenReturn(vo);
Result<ArtistScheduleRuleVO> result = controller.saveScheduleRule(request, dto);
assertThat(result.getData()).isSameAs(vo);
assertThat(dto.getShopId()).isEqualTo(8L);
}
@Test
void saveScheduleExceptionShouldResolveShopScopeBeforeSaving() {
MockHttpServletRequest request = new MockHttpServletRequest();
UserDO manager = new UserDO();
ArtistScheduleExceptionDTO dto = new ArtistScheduleExceptionDTO();
dto.setShopId(99L);
ArtistScheduleExceptionVO vo = new ArtistScheduleExceptionVO();
when(adminScopeHelper.getCurrentUser(request)).thenReturn(manager);
when(adminScopeHelper.resolveShopScope(manager, 99L)).thenReturn(8L);
when(artistScheduleService.saveException(dto)).thenReturn(vo);
Result<ArtistScheduleExceptionVO> result = controller.saveScheduleException(request, dto);
assertThat(result.getData()).isSameAs(vo);
assertThat(dto.getShopId()).isEqualTo(8L);
}
@Test
void updateShopShouldPreserveAuthorizationExpireTimeForNonPlatformUser() {
MockHttpServletRequest request = new MockHttpServletRequest();