实现员工规则排班设置

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();
+23
View File
@@ -43,5 +43,28 @@ module.exports = {
method: 'POST',
data
})
},
scheduleRule(params) {
return request({
url: '/manager/employees/schedule-rule',
params
})
},
saveScheduleRule(data) {
return request({
url: '/manager/employees/schedule-rule',
method: 'POST',
data
})
},
saveScheduleException(data) {
return request({
url: '/manager/employees/schedule-exceptions',
method: 'POST',
data
})
}
}
@@ -1,13 +1,286 @@
const employeesApi = require('../../api/employees')
const dateUtil = require('../../utils/date')
const PRESETS = [
{ value: 'DOUBLE_REST', label: '双休', workDays: [1, 2, 3, 4, 5], startTime: '09:00', endTime: '17:00' },
{ value: 'SINGLE_REST', label: '单休', workDays: [1, 2, 3, 4, 5, 6], startTime: '10:00', endTime: '22:00' },
{ value: 'NINE_TO_FIVE', label: '朝九晚五', workDays: [1, 2, 3, 4, 5], startTime: '09:00', endTime: '17:00' },
{ value: 'LATE_SHIFT', label: '晚班', workDays: [1, 2, 3, 4, 5, 6], startTime: '10:00', endTime: '22:00' },
{ value: 'CUSTOM', label: '自定义', workDays: [1, 2, 3, 4, 5], startTime: '10:00', endTime: '22:00' }
]
const WEEKDAYS = [
{ value: 1, label: '周一' },
{ value: 2, label: '周二' },
{ value: 3, label: '周三' },
{ value: 4, label: '周四' },
{ value: 5, label: '周五' },
{ value: 6, label: '周六' },
{ value: 7, label: '周日' }
]
const EXCEPTION_TYPES = [
{ value: 'REST', label: '休假' },
{ value: 'EXTRA_WORK', label: '临时上班' },
{ value: 'CHANGE_SHIFT', label: '临时改班' }
]
function copyWorkDays(days) {
return (days || []).map(day => Number(day)).filter(day => day >= 1 && day <= 7)
}
function buildPreset(value) {
return PRESETS.find(item => item.value === value) || PRESETS[0]
}
function buildPresetOptions(presetType) {
return PRESETS.map(item => ({
...item,
active: item.value === presetType
}))
}
function buildWeekdayOptions(workDays) {
const selected = copyWorkDays(workDays)
return WEEKDAYS.map(item => ({
...item,
active: selected.includes(item.value)
}))
}
function buildExceptionTypeLabel(exceptionType) {
const option = EXCEPTION_TYPES.find(item => item.value === exceptionType) || EXCEPTION_TYPES[0]
return option.label
}
function buildExceptionSummary(item) {
const type = EXCEPTION_TYPES.find(option => option.value === item.exceptionType)
if (!item) {
return ''
}
if (item.exceptionType === 'REST') {
return `${item.workDate} ${type ? type.label : '休假'}`
}
return `${item.workDate} ${type ? type.label : '例外'} ${String(item.startTime || '').slice(0, 5)}-${String(item.endTime || '').slice(0, 5)}`
}
Page({
data: {
form: { workDate: dateUtil.formatDate(new Date()), startTime: '10:00', endTime: '22:00', capacity: 1 }
artistId: '',
presets: PRESETS,
presetOptions: buildPresetOptions('DOUBLE_REST'),
weekdays: WEEKDAYS,
weekdayOptions: buildWeekdayOptions([1, 2, 3, 4, 5]),
exceptionTypes: EXCEPTION_TYPES,
exceptionTypeIndex: 0,
exceptionTypeLabel: '休假',
exceptions: [],
loading: false,
saving: false,
form: {
presetType: 'DOUBLE_REST',
workDays: [1, 2, 3, 4, 5],
startTime: '09:00',
endTime: '17:00',
slotMinutes: 60,
capacity: 1,
remark: ''
},
exceptionForm: {
workDate: dateUtil.formatDate(new Date()),
exceptionType: 'REST',
startTime: '10:00',
endTime: '18:00',
slotMinutes: 60,
capacity: 1,
remark: ''
}
},
onInput(event) { this.setData({ [`form.${event.currentTarget.dataset.field}`]: event.detail.value }) },
onDateChange(event) { this.setData({ 'form.workDate': event.detail.value }) },
onStartChange(event) { this.setData({ 'form.startTime': event.detail.value }) },
onEndChange(event) { this.setData({ 'form.endTime': event.detail.value }) },
save() { wx.showToast({ title: '已保存' }) },
back() { wx.navigateBack() }
onLoad(options) {
this.setData({ artistId: options.id || '' })
this.loadRule()
},
async loadRule() {
if (!this.data.artistId) {
wx.showToast({ title: '缺少美甲师ID', icon: 'none' })
return
}
this.setData({ loading: true })
try {
const setting = await employeesApi.scheduleRule({ artistId: this.data.artistId })
const rule = setting.rule || {}
const preset = buildPreset(rule.presetType)
const form = {
presetType: rule.presetType || preset.value,
workDays: copyWorkDays(rule.workDays || preset.workDays),
startTime: String(rule.startTime || preset.startTime).slice(0, 5),
endTime: String(rule.endTime || preset.endTime).slice(0, 5),
slotMinutes: rule.slotMinutes || 60,
capacity: rule.capacity || 1,
remark: rule.remark || ''
}
this.setData({
form,
presetOptions: buildPresetOptions(form.presetType),
weekdayOptions: buildWeekdayOptions(form.workDays),
exceptions: (setting.exceptions || []).map(item => ({
...item,
startTime: item.startTime ? String(item.startTime).slice(0, 5) : '',
endTime: item.endTime ? String(item.endTime).slice(0, 5) : '',
summary: buildExceptionSummary(item)
}))
})
} catch (error) {
wx.showToast({ title: error.message || '排班规则加载失败', icon: 'none' })
} finally {
this.setData({ loading: false })
}
},
selectPreset(event) {
const preset = buildPreset(event.currentTarget.dataset.value)
const form = {
...this.data.form,
presetType: preset.value,
workDays: copyWorkDays(preset.workDays),
startTime: preset.startTime,
endTime: preset.endTime
}
this.setData({
form,
presetOptions: buildPresetOptions(form.presetType),
weekdayOptions: buildWeekdayOptions(form.workDays)
})
},
toggleWeekday(event) {
const day = Number(event.currentTarget.dataset.value)
const workDays = copyWorkDays(this.data.form.workDays)
const exists = workDays.includes(day)
const nextDays = exists ? workDays.filter(item => item !== day) : [...workDays, day].sort()
this.setData({
'form.presetType': 'CUSTOM',
'form.workDays': nextDays,
presetOptions: buildPresetOptions('CUSTOM'),
weekdayOptions: buildWeekdayOptions(nextDays)
})
},
onStartChange(event) {
this.setData({
'form.startTime': event.detail.value,
'form.presetType': 'CUSTOM',
presetOptions: buildPresetOptions('CUSTOM')
})
},
onEndChange(event) {
this.setData({
'form.endTime': event.detail.value,
'form.presetType': 'CUSTOM',
presetOptions: buildPresetOptions('CUSTOM')
})
},
onInput(event) {
const field = event.currentTarget.dataset.field
this.setData({ [`form.${field}`]: event.detail.value })
},
onExceptionInput(event) {
const field = event.currentTarget.dataset.field
this.setData({ [`exceptionForm.${field}`]: event.detail.value })
},
onExceptionDateChange(event) {
this.setData({ 'exceptionForm.workDate': event.detail.value })
},
onExceptionStartChange(event) {
this.setData({ 'exceptionForm.startTime': event.detail.value })
},
onExceptionEndChange(event) {
this.setData({ 'exceptionForm.endTime': event.detail.value })
},
onExceptionTypeChange(event) {
const index = Number(event.detail.value)
const option = this.data.exceptionTypes[index] || this.data.exceptionTypes[0]
this.setData({
exceptionTypeIndex: index,
exceptionTypeLabel: buildExceptionTypeLabel(option.value),
'exceptionForm.exceptionType': option.value
})
},
async save() {
const form = this.data.form
const workDays = copyWorkDays(form.workDays)
if (!workDays.length) {
wx.showToast({ title: '请选择工作日', icon: 'none' })
return
}
if (!form.startTime || !form.endTime || form.startTime >= form.endTime) {
wx.showToast({ title: '请填写正确的排班时间', icon: 'none' })
return
}
this.setData({ saving: true })
try {
await employeesApi.saveScheduleRule({
artistId: this.data.artistId,
presetType: form.presetType,
workDays,
startTime: form.startTime,
endTime: form.endTime,
slotMinutes: Number(form.slotMinutes) || 60,
capacity: Number(form.capacity) || 1,
status: 1,
remark: String(form.remark || '').trim()
})
wx.showToast({ title: '排班规则已保存', icon: 'success' })
await this.loadRule()
} catch (error) {
wx.showToast({ title: error.message || '保存失败', icon: 'none' })
} finally {
this.setData({ saving: false })
}
},
async saveException() {
const form = this.data.exceptionForm
if (!form.workDate || !form.exceptionType) {
wx.showToast({ title: '请补全例外日期', icon: 'none' })
return
}
if (form.exceptionType !== 'REST' && (!form.startTime || !form.endTime || form.startTime >= form.endTime)) {
wx.showToast({ title: '请填写正确的例外时间', icon: 'none' })
return
}
this.setData({ saving: true })
try {
await employeesApi.saveScheduleException({
artistId: this.data.artistId,
workDate: form.workDate,
exceptionType: form.exceptionType,
startTime: form.exceptionType === 'REST' ? null : form.startTime,
endTime: form.exceptionType === 'REST' ? null : form.endTime,
slotMinutes: Number(form.slotMinutes) || 60,
capacity: Number(form.capacity) || 1,
remark: String(form.remark || '').trim()
})
wx.showToast({ title: '例外已保存', icon: 'success' })
await this.loadRule()
} catch (error) {
wx.showToast({ title: error.message || '例外保存失败', icon: 'none' })
} finally {
this.setData({ saving: false })
}
},
back() {
wx.navigateBack()
}
})
@@ -1,34 +1,84 @@
<view class="page no-tab">
<view class="card form-card">
<view class="field">
<view class="field-label-wrap">
<text class="field-label">日期</text>
<text class="field-hint">点击可编辑</text>
<view class="section">
<view class="section-title">常规排班</view>
<view class="card rule-card">
<view class="preset-grid">
<view wx:for="{{presetOptions}}" wx:key="value" class="preset-chip {{item.active ? 'active' : ''}}" data-value="{{item.value}}" bindtap="selectPreset">{{item.label}}</view>
</view>
<picker mode="date" value="{{form.workDate}}" bindchange="onDateChange"><view class="field-value">{{form.workDate}}</view></picker>
</view>
<view class="field">
<view class="field-label-wrap">
<view class="field-block">
<view class="field-title">工作日</view>
<view class="weekday-grid">
<view wx:for="{{weekdayOptions}}" wx:key="value" class="weekday-chip {{item.active ? 'active' : ''}}" data-value="{{item.value}}" bindtap="toggleWeekday">{{item.label}}</view>
</view>
</view>
<view class="field">
<text class="field-label">开始时间</text>
<text class="field-hint">点击可编辑</text>
<picker mode="time" value="{{form.startTime}}" bindchange="onStartChange"><view class="field-value">{{form.startTime}}</view></picker>
</view>
<picker mode="time" value="{{form.startTime}}" bindchange="onStartChange"><view class="field-value">{{form.startTime}}</view></picker>
</view>
<view class="field">
<view class="field-label-wrap">
<view class="field">
<text class="field-label">结束时间</text>
<text class="field-hint">点击可编辑</text>
<picker mode="time" value="{{form.endTime}}" bindchange="onEndChange"><view class="field-value">{{form.endTime}}</view></picker>
</view>
<picker mode="time" value="{{form.endTime}}" bindchange="onEndChange"><view class="field-value">{{form.endTime}}</view></picker>
</view>
<view class="field capacity-field">
<view class="field-label-wrap">
<view class="field">
<text class="field-label">预约间隔</text>
<input type="number" value="{{form.slotMinutes}}" data-field="slotMinutes" bindinput="onInput" />
</view>
<view class="field">
<text class="field-label">容量</text>
<text class="field-desc">同一时间段最多可同时接待的预约数</text>
<text class="field-hint">点击可编辑</text>
<input type="number" value="{{form.capacity}}" data-field="capacity" bindinput="onInput" />
</view>
<view class="field">
<text class="field-label">备注</text>
<input value="{{form.remark}}" data-field="remark" bindinput="onInput" placeholder="可选" />
</view>
<input type="number" value="{{form.capacity}}" data-field="capacity" bindinput="onInput" />
</view>
</view>
<view class="fixed-bottom"><button class="primary-btn" bindtap="save">保存排班</button></view>
<view class="section">
<view class="section-title">特殊日期</view>
<view class="card rule-card">
<view class="field">
<text class="field-label">日期</text>
<picker mode="date" value="{{exceptionForm.workDate}}" bindchange="onExceptionDateChange"><view class="field-value">{{exceptionForm.workDate}}</view></picker>
</view>
<view class="field">
<text class="field-label">类型</text>
<picker range="{{exceptionTypes}}" range-key="label" value="{{exceptionTypeIndex}}" bindchange="onExceptionTypeChange"><view class="field-value">{{exceptionTypeLabel}}</view></picker>
</view>
<view wx:if="{{exceptionForm.exceptionType !== 'REST'}}" class="field">
<text class="field-label">开始时间</text>
<picker mode="time" value="{{exceptionForm.startTime}}" bindchange="onExceptionStartChange"><view class="field-value">{{exceptionForm.startTime}}</view></picker>
</view>
<view wx:if="{{exceptionForm.exceptionType !== 'REST'}}" class="field">
<text class="field-label">结束时间</text>
<picker mode="time" value="{{exceptionForm.endTime}}" bindchange="onExceptionEndChange"><view class="field-value">{{exceptionForm.endTime}}</view></picker>
</view>
<view wx:if="{{exceptionForm.exceptionType !== 'REST'}}" class="field">
<text class="field-label">预约间隔</text>
<input type="number" value="{{exceptionForm.slotMinutes}}" data-field="slotMinutes" bindinput="onExceptionInput" />
</view>
<view wx:if="{{exceptionForm.exceptionType !== 'REST'}}" class="field">
<text class="field-label">容量</text>
<input type="number" value="{{exceptionForm.capacity}}" data-field="capacity" bindinput="onExceptionInput" />
</view>
<view class="field">
<text class="field-label">备注</text>
<input value="{{exceptionForm.remark}}" data-field="remark" bindinput="onExceptionInput" placeholder="可选" />
</view>
<button class="secondary-btn exception-btn" loading="{{saving}}" bindtap="saveException">保存特殊日期</button>
</view>
<view wx:if="{{exceptions.length}}" class="exception-list">
<view wx:for="{{exceptions}}" wx:key="id" class="card exception-card">
<text>{{item.summary}}</text>
<text wx:if="{{item.remark}}" class="exception-remark">{{item.remark}}</text>
</view>
</view>
</view>
<view class="fixed-bottom">
<button class="primary-btn" loading="{{saving}}" bindtap="save">保存排班规则</button>
</view>
</view>
@@ -1,34 +1,77 @@
.field-label-wrap {
.rule-card {
padding: 20rpx 24rpx;
}
.preset-grid,
.weekday-grid {
display: flex;
flex-direction: column;
flex-wrap: wrap;
gap: 16rpx;
}
.preset-chip,
.weekday-chip {
display: flex;
align-items: center;
justify-content: center;
width: 260rpx;
flex-shrink: 0;
gap: 6rpx;
min-width: 128rpx;
height: 60rpx;
padding: 0 22rpx;
border: 1rpx solid #e3ddd4;
border-radius: 999rpx;
background: #fbf7f0;
color: #5f5951;
font-size: 24rpx;
font-weight: 700;
}
.field-label-wrap .field-label {
width: auto;
.preset-chip.active,
.weekday-chip.active {
border-color: #6f8f83;
background: #e5eee9;
color: #55786d;
}
.field-hint {
color: #a39b91;
font-size: 20rpx;
font-weight: 500;
.field-block {
padding: 26rpx 0 12rpx;
border-bottom: 1rpx solid #eee8df;
}
.field-desc {
max-width: 240rpx;
color: #7f786f;
font-size: 20rpx;
line-height: 1.25;
}
.capacity-field {
min-height: 136rpx;
.field-title {
margin-bottom: 16rpx;
color: #625c55;
font-size: 26rpx;
font-weight: 700;
}
.field input,
.field-value {
text-align: right;
}
.exception-btn {
margin-top: 22rpx;
}
.exception-list {
display: flex;
flex-direction: column;
gap: 14rpx;
margin-top: 18rpx;
}
.exception-card {
display: flex;
flex-direction: column;
gap: 8rpx;
padding: 20rpx 24rpx;
color: #4c4740;
font-size: 24rpx;
font-weight: 700;
}
.exception-remark {
color: #8d857b;
font-size: 22rpx;
font-weight: 500;
}
@@ -0,0 +1,92 @@
-- 员工排班规则和例外,保留 t_artist_schedule 作为预约校验使用的具体日期排班表。
DROP PROCEDURE IF EXISTS sp_fd_add_index_if_not_exists;
DELIMITER $$
CREATE PROCEDURE sp_fd_add_index_if_not_exists(
IN p_table_name varchar(128),
IN p_index_name varchar(128),
IN p_index_sql varchar(1000)
)
BEGIN
IF NOT EXISTS (
SELECT 1
FROM information_schema.statistics
WHERE table_schema = DATABASE()
AND table_name = p_table_name
AND index_name = p_index_name
) THEN
SET @fd_sql = CONCAT('ALTER TABLE ', p_table_name, ' ADD INDEX ', p_index_name, ' ', p_index_sql);
PREPARE fd_stmt FROM @fd_sql;
EXECUTE fd_stmt;
DEALLOCATE PREPARE fd_stmt;
END IF;
END$$
DELIMITER ;
DROP PROCEDURE IF EXISTS sp_fd_add_unique_index_if_not_exists;
DELIMITER $$
CREATE PROCEDURE sp_fd_add_unique_index_if_not_exists(
IN p_table_name varchar(128),
IN p_index_name varchar(128),
IN p_index_sql varchar(1000)
)
BEGIN
IF NOT EXISTS (
SELECT 1
FROM information_schema.statistics
WHERE table_schema = DATABASE()
AND table_name = p_table_name
AND index_name = p_index_name
) THEN
SET @fd_sql = CONCAT('ALTER TABLE ', p_table_name, ' ADD UNIQUE INDEX ', p_index_name, ' ', p_index_sql);
PREPARE fd_stmt FROM @fd_sql;
EXECUTE fd_stmt;
DEALLOCATE PREPARE fd_stmt;
END IF;
END$$
DELIMITER ;
CREATE TABLE IF NOT EXISTS t_artist_schedule_rule
(
id bigint unsigned NOT NULL COMMENT '排班规则ID',
shop_id bigint unsigned NOT NULL COMMENT '店铺ID',
artist_id bigint unsigned NOT NULL COMMENT '美甲师用户ID',
preset_type varchar(32) NOT NULL COMMENT '预设类型',
work_days varchar(32) NOT NULL COMMENT '工作星期,1-7逗号分隔',
start_time time NOT NULL COMMENT '常规开始时间',
end_time time NOT NULL COMMENT '常规结束时间',
slot_minutes int NOT NULL DEFAULT 60 COMMENT '预约间隔分钟',
capacity int NOT NULL DEFAULT 1 COMMENT '同一时间段容量',
status tinyint NOT NULL DEFAULT 1 COMMENT '状态:1启用,0停用',
remark varchar(255) NULL COMMENT '备注',
create_time datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
update_time datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
is_delete tinyint NOT NULL DEFAULT 0 COMMENT '逻辑删除',
PRIMARY KEY (id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='美甲师常规排班规则表';
CREATE TABLE IF NOT EXISTS t_artist_schedule_exception
(
id bigint unsigned NOT NULL COMMENT '排班例外ID',
shop_id bigint unsigned NOT NULL COMMENT '店铺ID',
artist_id bigint unsigned NOT NULL COMMENT '美甲师用户ID',
work_date date NOT NULL COMMENT '例外日期',
exception_type varchar(32) NOT NULL COMMENT '例外类型:REST/EXTRA_WORK/CHANGE_SHIFT',
start_time time NULL COMMENT '例外开始时间',
end_time time NULL COMMENT '例外结束时间',
slot_minutes int NOT NULL DEFAULT 60 COMMENT '预约间隔分钟',
capacity int NOT NULL DEFAULT 1 COMMENT '同一时间段容量',
remark varchar(255) NULL COMMENT '备注',
create_time datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
update_time datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
is_delete tinyint NOT NULL DEFAULT 0 COMMENT '逻辑删除',
PRIMARY KEY (id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='美甲师排班例外表';
CALL sp_fd_add_unique_index_if_not_exists('t_artist_schedule_rule', 'uk_artist_schedule_rule_artist', '(`shop_id`, `artist_id`, `is_delete`)');
CALL sp_fd_add_index_if_not_exists('t_artist_schedule_rule', 'idx_artist_schedule_rule_shop_status', '(`shop_id`, `status`, `is_delete`)');
CALL sp_fd_add_unique_index_if_not_exists('t_artist_schedule_exception', 'uk_artist_schedule_exception_date', '(`shop_id`, `artist_id`, `work_date`, `is_delete`)');
CALL sp_fd_add_index_if_not_exists('t_artist_schedule_exception', 'idx_artist_schedule_exception_artist_date', '(`artist_id`, `work_date`, `is_delete`)');
DROP PROCEDURE IF EXISTS sp_fd_add_index_if_not_exists;
DROP PROCEDURE IF EXISTS sp_fd_add_unique_index_if_not_exists;