diff --git a/JY-Core/src/main/java/com/xiaowang/jayucloud/core/modules/artist/support/ArtistScheduleRuleSupport.java b/JY-Core/src/main/java/com/xiaowang/jayucloud/core/modules/artist/support/ArtistScheduleRuleSupport.java index 2258381d..e8ae141d 100644 --- a/JY-Core/src/main/java/com/xiaowang/jayucloud/core/modules/artist/support/ArtistScheduleRuleSupport.java +++ b/JY-Core/src/main/java/com/xiaowang/jayucloud/core/modules/artist/support/ArtistScheduleRuleSupport.java @@ -24,6 +24,8 @@ public final class ArtistScheduleRuleSupport { public static final String EXCEPTION_REST = "REST"; public static final String EXCEPTION_EXTRA_WORK = "EXTRA_WORK"; public static final String EXCEPTION_CHANGE_SHIFT = "CHANGE_SHIFT"; + public static final LocalTime FULL_DAY_START_TIME = LocalTime.MIN; + public static final LocalTime FULL_DAY_END_TIME = LocalTime.of(23, 59, 59); private static final List EVERYDAY_WORK_DAYS = List.of(1, 2, 3, 4, 5, 6, 7); @@ -109,10 +111,10 @@ public final class ArtistScheduleRuleSupport { 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.setPresetType(PRESET_EVERYDAY); + rule.setWorkDays(encodeWorkDays(EVERYDAY_WORK_DAYS)); + rule.setStartTime(FULL_DAY_START_TIME); + rule.setEndTime(FULL_DAY_END_TIME); rule.setSlotMinutes(DEFAULT_SLOT_MINUTES); rule.setCapacity(DEFAULT_CAPACITY); rule.setStatus(1); diff --git a/JY-Core/src/main/java/com/xiaowang/jayucloud/core/modules/planning/service/impl/AppointmentCapacityServiceImpl.java b/JY-Core/src/main/java/com/xiaowang/jayucloud/core/modules/planning/service/impl/AppointmentCapacityServiceImpl.java index 6bd983be..e4c3d9a5 100644 --- a/JY-Core/src/main/java/com/xiaowang/jayucloud/core/modules/planning/service/impl/AppointmentCapacityServiceImpl.java +++ b/JY-Core/src/main/java/com/xiaowang/jayucloud/core/modules/planning/service/impl/AppointmentCapacityServiceImpl.java @@ -15,8 +15,11 @@ import lombok.RequiredArgsConstructor; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; +import java.time.LocalDate; import java.time.LocalDateTime; import java.time.LocalTime; +import java.util.ArrayList; +import java.util.List; @Service @RequiredArgsConstructor @@ -28,6 +31,7 @@ public class AppointmentCapacityServiceImpl implements AppointmentCapacityServic private static final String STATUS_RELEASED = "RELEASED"; private static final String UNAVAILABLE_MESSAGE = "涓嶅彲棰勭害"; private static final String FULL_MESSAGE = "褰撳墠缇庣敳甯堣鏃堕棿娈靛凡绾︽弧锛岃閲嶆柊閫夋嫨棰勭害鏃堕棿"; + private static final LocalTime FULL_DAY_QUERY_END_TIME = LocalTime.of(23, 59); private final AppointmentReservationMapper reservationMapper; private final ArtistScheduleMapper scheduleMapper; @@ -145,21 +149,33 @@ public class AppointmentCapacityServiceImpl implements AppointmentCapacityServic } private int resolveCapacity(Long shopId, Long artistId, LocalDateTime startTime, LocalDateTime endTime) { + List segments = splitAppointmentSegments(startTime, endTime); + int capacity = Integer.MAX_VALUE; + for (AppointmentTimeSegment segment : segments) { + capacity = Math.min(capacity, resolveSegmentCapacity(shopId, artistId, segment)); + } + if (capacity == Integer.MAX_VALUE) { + throw new RuntimeException(UNAVAILABLE_MESSAGE); + } + return capacity; + } + + private int resolveSegmentCapacity(Long shopId, Long artistId, AppointmentTimeSegment segment) { ArtistScheduleDO schedule = scheduleMapper.selectCoveringSchedule( shopId, artistId, - startTime.toLocalDate(), - startTime.toLocalTime(), - endTime.toLocalTime() + segment.workDate(), + segment.startTime(), + toCoverageQueryEndTime(segment.endTime()) ); if (schedule != null && isManualScheduleOverride(schedule)) { return resolveExplicitScheduleCapacity(schedule); } - ArtistScheduleDO daySchedule = scheduleMapper.selectDayScheduleForUpdate(shopId, artistId, startTime.toLocalDate()); + ArtistScheduleDO daySchedule = scheduleMapper.selectDayScheduleForUpdate(shopId, artistId, segment.workDate()); if (daySchedule != null && isManualScheduleOverride(daySchedule)) { throw new RuntimeException(UNAVAILABLE_MESSAGE); } - return resolveRuleCapacity(shopId, artistId, startTime, endTime); + return resolveRuleCapacity(shopId, artistId, segment); } private int resolveExplicitScheduleCapacity(ArtistScheduleDO schedule) { @@ -171,7 +187,7 @@ public class AppointmentCapacityServiceImpl implements AppointmentCapacityServic return schedule.getCapacity(); } - private int resolveRuleCapacity(Long shopId, Long artistId, LocalDateTime startTime, LocalDateTime endTime) { + private int resolveRuleCapacity(Long shopId, Long artistId, AppointmentTimeSegment segment) { ArtistScheduleRuleDO rule = ruleMapper.selectOne(new QueryWrapper() .eq("shop_id", shopId) .eq("artist_id", artistId) @@ -183,17 +199,17 @@ public class AppointmentCapacityServiceImpl implements AppointmentCapacityServic ArtistScheduleExceptionDO exception = exceptionMapper.selectOne(new QueryWrapper() .eq("shop_id", shopId) .eq("artist_id", artistId) - .eq("work_date", startTime.toLocalDate()) + .eq("work_date", segment.workDate()) .eq("is_delete", 0) .last("LIMIT 1")); ArtistScheduleRuleSupport.ResolvedSchedule resolved = ArtistScheduleRuleSupport.resolveGeneratedSchedule( rule, exception, - startTime.toLocalDate() + segment.workDate() ); if (!resolved.working() || resolved.capacity() == null || resolved.capacity() < MIN_CAPACITY - || !isTimeCovered(resolved.startTime(), resolved.endTime(), startTime.toLocalTime(), endTime.toLocalTime())) { + || !isTimeCovered(resolved.startTime(), resolved.endTime(), segment.startTime(), segment.endTime())) { throw new RuntimeException(UNAVAILABLE_MESSAGE); } return resolved.capacity(); @@ -204,7 +220,42 @@ public class AppointmentCapacityServiceImpl implements AppointmentCapacityServic if (scheduleStartTime == null || scheduleEndTime == null || appointmentStartTime == null || appointmentEndTime == null) { return false; } - return !appointmentStartTime.isBefore(scheduleStartTime) && !appointmentEndTime.isAfter(scheduleEndTime); + return !appointmentStartTime.isBefore(scheduleStartTime) && isEndTimeCovered(appointmentEndTime, scheduleEndTime); + } + + private boolean isEndTimeCovered(LocalTime appointmentEndTime, LocalTime scheduleEndTime) { + if (!appointmentEndTime.isAfter(scheduleEndTime)) { + return true; + } + return LocalTime.MAX.equals(appointmentEndTime) && isFullDayEndTime(scheduleEndTime); + } + + private boolean isFullDayEndTime(LocalTime endTime) { + return endTime != null && !endTime.isBefore(FULL_DAY_QUERY_END_TIME); + } + + private LocalTime toCoverageQueryEndTime(LocalTime endTime) { + if (LocalTime.MAX.equals(endTime)) { + return FULL_DAY_QUERY_END_TIME; + } + return endTime; + } + + private List splitAppointmentSegments(LocalDateTime startTime, LocalDateTime endTime) { + if (startTime == null || endTime == null || !startTime.isBefore(endTime)) { + throw new RuntimeException(UNAVAILABLE_MESSAGE); + } + List segments = new ArrayList<>(); + LocalDateTime cursor = startTime; + while (cursor.isBefore(endTime)) { + LocalDate workDate = cursor.toLocalDate(); + LocalDateTime nextDayStart = workDate.plusDays(1L).atStartOfDay(); + LocalDateTime segmentEndDateTime = endTime.isBefore(nextDayStart) ? endTime : nextDayStart; + LocalTime segmentEndTime = segmentEndDateTime.equals(nextDayStart) ? LocalTime.MAX : segmentEndDateTime.toLocalTime(); + segments.add(new AppointmentTimeSegment(workDate, cursor.toLocalTime(), segmentEndTime)); + cursor = segmentEndDateTime; + } + return segments; } private boolean isManualScheduleOverride(ArtistScheduleDO schedule) { @@ -214,4 +265,7 @@ public class AppointmentCapacityServiceImpl implements AppointmentCapacityServic String remark = schedule.getRemark().trim(); return !"规则生成排班".equals(remark) && !remark.startsWith("例外排班:"); } + + private record AppointmentTimeSegment(LocalDate workDate, LocalTime startTime, LocalTime endTime) { + } } diff --git a/JY-Core/src/main/java/com/xiaowang/jayucloud/core/modules/planning/service/impl/PlanningServiceImpl.java b/JY-Core/src/main/java/com/xiaowang/jayucloud/core/modules/planning/service/impl/PlanningServiceImpl.java index 5a133f14..97e79e85 100644 --- a/JY-Core/src/main/java/com/xiaowang/jayucloud/core/modules/planning/service/impl/PlanningServiceImpl.java +++ b/JY-Core/src/main/java/com/xiaowang/jayucloud/core/modules/planning/service/impl/PlanningServiceImpl.java @@ -1138,16 +1138,55 @@ public class PlanningServiceImpl implements PlanningService { private void ensureWithinBusinessHours(Long shopId, LocalDateTime startTime, LocalDateTime endTime) { ShopDO shop = shopMapper.selectById(shopId); - LocalDate workDate = startTime.toLocalDate(); - ShopScheduleSupport.LocalTimeRange hours = ShopScheduleSupport.resolveOpenRange(shop, selectShopScheduleException(shopId, workDate), workDate); - if (!hours.open()) { - throw new RuntimeException("当前日期为店铺休息日,不能预约:" + workDate); + List segments = splitAppointmentSegments(startTime, endTime); + for (AppointmentTimeSegment segment : segments) { + ShopScheduleSupport.LocalTimeRange hours = ShopScheduleSupport.resolveOpenRange( + shop, + selectShopScheduleException(shopId, segment.workDate()), + segment.workDate() + ); + if (!hours.open()) { + throw new RuntimeException("当前日期为店铺休息日,不能预约:" + segment.workDate()); + } + if (!isSegmentWithinBusinessHours(segment, hours)) { + throw new RuntimeException("预约时间超出店铺营业时间:" + segment.workDate()); + } } - LocalTime start = startTime.toLocalTime(); - LocalTime end = endTime.toLocalTime(); - if (start.isBefore(hours.startTime()) || end.isAfter(hours.endTime()) || !startTime.toLocalDate().equals(endTime.toLocalDate())) { - throw new RuntimeException("预约时间超出店铺营业时间"); + } + + private boolean isSegmentWithinBusinessHours(AppointmentTimeSegment segment, ShopScheduleSupport.LocalTimeRange hours) { + if (segment == null || hours == null || hours.startTime() == null || hours.endTime() == null) { + return false; } + return !segment.startTime().isBefore(hours.startTime()) && isSegmentEndCovered(segment.endTime(), hours.endTime()); + } + + private boolean isSegmentEndCovered(LocalTime segmentEndTime, LocalTime businessEndTime) { + if (!segmentEndTime.isAfter(businessEndTime)) { + return true; + } + return LocalTime.MAX.equals(segmentEndTime) && isFullDayBusinessEndTime(businessEndTime); + } + + private boolean isFullDayBusinessEndTime(LocalTime businessEndTime) { + return businessEndTime != null && !businessEndTime.isBefore(LocalTime.of(23, 59)); + } + + private List splitAppointmentSegments(LocalDateTime startTime, LocalDateTime endTime) { + if (startTime == null || endTime == null || !startTime.isBefore(endTime)) { + throw new RuntimeException("预约时间范围不正确"); + } + List segments = new ArrayList<>(); + LocalDateTime cursor = startTime; + while (cursor.isBefore(endTime)) { + LocalDate workDate = cursor.toLocalDate(); + LocalDateTime nextDayStart = workDate.plusDays(1L).atStartOfDay(); + LocalDateTime segmentEndDateTime = endTime.isBefore(nextDayStart) ? endTime : nextDayStart; + LocalTime segmentEndTime = segmentEndDateTime.equals(nextDayStart) ? LocalTime.MAX : segmentEndDateTime.toLocalTime(); + segments.add(new AppointmentTimeSegment(workDate, cursor.toLocalTime(), segmentEndTime)); + cursor = segmentEndDateTime; + } + return segments; } private ShopScheduleExceptionDO selectShopScheduleException(Long shopId, LocalDate workDate) { @@ -1224,6 +1263,9 @@ public class PlanningServiceImpl implements PlanningService { .collect(Collectors.toMap(UserDO::getId, Function.identity(), (a, b) -> a)); } + private record AppointmentTimeSegment(LocalDate workDate, LocalTime startTime, LocalTime endTime) { + } + private String resolveArtistColor(NailArtistInfoDO info, Long artistId, int index) { if (info != null && hasText(info.getColor()) && info.getColor().trim().matches("^#[0-9a-fA-F]{6}$")) { return info.getColor().trim().toUpperCase(); diff --git a/JY-Core/src/main/java/com/xiaowang/jayucloud/core/modules/user/service/impl/UserServiceImpl.java b/JY-Core/src/main/java/com/xiaowang/jayucloud/core/modules/user/service/impl/UserServiceImpl.java index 92169874..e14c9491 100644 --- a/JY-Core/src/main/java/com/xiaowang/jayucloud/core/modules/user/service/impl/UserServiceImpl.java +++ b/JY-Core/src/main/java/com/xiaowang/jayucloud/core/modules/user/service/impl/UserServiceImpl.java @@ -8,6 +8,9 @@ import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import com.xiaowang.jayucloud.core.config.BrandProperties; import com.xiaowang.jayucloud.core.common.dto.*; import com.xiaowang.jayucloud.core.modules.artist.dto.*; +import com.xiaowang.jayucloud.core.modules.artist.entity.ArtistScheduleRuleDO; +import com.xiaowang.jayucloud.core.modules.artist.mapper.ArtistScheduleRuleMapper; +import com.xiaowang.jayucloud.core.modules.artist.support.ArtistScheduleRuleSupport; import com.xiaowang.jayucloud.core.modules.auth.dto.*; import com.xiaowang.jayucloud.core.modules.content.dto.*; import com.xiaowang.jayucloud.core.modules.file.dto.*; @@ -180,6 +183,7 @@ public class UserServiceImpl extends ServiceImpl implements * Variable `nailArtistInfoService`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. */ private final NailArtistInfoService nailArtistInfoService; + private final ArtistScheduleRuleMapper artistScheduleRuleMapper; private final BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder(); /** * Variable `verificationCodeService`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. @@ -471,10 +475,26 @@ public class UserServiceImpl extends ServiceImpl implements nailArtistInfoDTO.setStatus(1); // 默认状态为营业中 nailArtistInfoDTO.setPortfolio(""); // 默认作品集为空 nailArtistInfoService.saveOrUpdateNailArtistInfo(nailArtistInfoDTO); + ensureDefaultArtistScheduleRule(validatedShopId, userDO.getId()); } return userDO.getId(); } + + private void ensureDefaultArtistScheduleRule(Long shopId, Long artistId) { + if (shopId == null || artistId == null) { + throw new RuntimeException("创建员工默认排班缺少店铺或员工ID"); + } + ArtistScheduleRuleDO existingRule = artistScheduleRuleMapper.selectOne(new LambdaQueryWrapper() + .eq(ArtistScheduleRuleDO::getShopId, shopId) + .eq(ArtistScheduleRuleDO::getArtistId, artistId) + .eq(ArtistScheduleRuleDO::getIsDelete, 0) + .last("LIMIT 1")); + if (existingRule != null) { + return; + } + artistScheduleRuleMapper.insert(ArtistScheduleRuleSupport.defaultRule(shopId, artistId)); + } /** * 分配默认权限 diff --git a/JY-Core/src/test/java/com/xiaowang/jayucloud/core/modules/planning/service/impl/AppointmentCapacityServiceImplTest.java b/JY-Core/src/test/java/com/xiaowang/jayucloud/core/modules/planning/service/impl/AppointmentCapacityServiceImplTest.java index 1c23a09e..2f9948ff 100644 --- a/JY-Core/src/test/java/com/xiaowang/jayucloud/core/modules/planning/service/impl/AppointmentCapacityServiceImplTest.java +++ b/JY-Core/src/test/java/com/xiaowang/jayucloud/core/modules/planning/service/impl/AppointmentCapacityServiceImplTest.java @@ -192,6 +192,47 @@ class AppointmentCapacityServiceImplTest { verify(reservationMapper, never()).insert(any(AppointmentReservationDO.class)); } + @Test + void reserveAllowsCrossDayWhenEveryTouchedRuleDayWorks() { + LocalDateTime start = LocalDateTime.of(2026, 7, 2, 23, 30); + LocalDateTime end = LocalDateTime.of(2026, 7, 3, 7, 50); + ArtistScheduleRuleDO rule = rule("EVERYDAY", "1,2,3,4,5,6,7", LocalTime.MIN, LocalTime.of(23, 59, 59)); + when(scheduleMapper.selectCoveringSchedule(9L, 30L, LocalDate.of(2026, 7, 2), LocalTime.of(23, 30), LocalTime.of(23, 59))) + .thenReturn(null); + when(scheduleMapper.selectCoveringSchedule(9L, 30L, LocalDate.of(2026, 7, 3), LocalTime.MIN, LocalTime.of(7, 50))) + .thenReturn(null); + when(scheduleMapper.selectDayScheduleForUpdate(9L, 30L, LocalDate.of(2026, 7, 2))).thenReturn(null); + when(scheduleMapper.selectDayScheduleForUpdate(9L, 30L, LocalDate.of(2026, 7, 3))).thenReturn(null); + when(ruleMapper.selectOne(any())).thenReturn(rule); + when(exceptionMapper.selectOne(any())).thenReturn(null); + when(reservationMapper.countOverlappingActiveForUpdate(30L, start, end)).thenReturn(0); + + service.reserveOrThrow(1L, 10L, 9L, 30L, "French", start, end); + + verify(reservationMapper).insert(any(AppointmentReservationDO.class)); + } + + @Test + void reserveRejectsCrossDayWhenNextDayRuleExceptionRests() { + LocalDateTime start = LocalDateTime.of(2026, 7, 2, 23, 30); + LocalDateTime end = LocalDateTime.of(2026, 7, 3, 7, 50); + ArtistScheduleRuleDO rule = rule("EVERYDAY", "1,2,3,4,5,6,7", LocalTime.MIN, LocalTime.of(23, 59, 59)); + when(scheduleMapper.selectCoveringSchedule(9L, 30L, LocalDate.of(2026, 7, 2), LocalTime.of(23, 30), LocalTime.of(23, 59))) + .thenReturn(null); + when(scheduleMapper.selectCoveringSchedule(9L, 30L, LocalDate.of(2026, 7, 3), LocalTime.MIN, LocalTime.of(7, 50))) + .thenReturn(null); + when(scheduleMapper.selectDayScheduleForUpdate(9L, 30L, LocalDate.of(2026, 7, 2))).thenReturn(null); + when(scheduleMapper.selectDayScheduleForUpdate(9L, 30L, LocalDate.of(2026, 7, 3))).thenReturn(null); + when(ruleMapper.selectOne(any())).thenReturn(rule); + when(exceptionMapper.selectOne(any())).thenReturn(null).thenReturn(restException(LocalDate.of(2026, 7, 3))); + + assertThatThrownBy(() -> service.reserveOrThrow(1L, 10L, 9L, 30L, "French", start, end)) + .isInstanceOf(RuntimeException.class) + .hasMessageContaining("涓嶅彲棰勭害"); + + verify(reservationMapper, never()).insert(any(AppointmentReservationDO.class)); + } + @Test void reserveRejectsWhenCoveringScheduleIsDisabled() { LocalDateTime start = LocalDateTime.of(2026, 6, 1, 10, 0); diff --git a/JY-Core/src/test/java/com/xiaowang/jayucloud/core/modules/planning/service/impl/PlanningServiceImplTest.java b/JY-Core/src/test/java/com/xiaowang/jayucloud/core/modules/planning/service/impl/PlanningServiceImplTest.java index a99986d4..e73ed4ba 100644 --- a/JY-Core/src/test/java/com/xiaowang/jayucloud/core/modules/planning/service/impl/PlanningServiceImplTest.java +++ b/JY-Core/src/test/java/com/xiaowang/jayucloud/core/modules/planning/service/impl/PlanningServiceImplTest.java @@ -24,6 +24,7 @@ import com.xiaowang.jayucloud.core.modules.product.entity.ProductDO; import com.xiaowang.jayucloud.core.modules.product.mapper.ProductMapper; import com.xiaowang.jayucloud.core.modules.security.support.AdminScopeHelper; import com.xiaowang.jayucloud.core.modules.shop.entity.ShopDO; +import com.xiaowang.jayucloud.core.modules.shop.entity.ShopScheduleExceptionDO; import com.xiaowang.jayucloud.core.modules.shop.mapper.ShopMapper; import com.xiaowang.jayucloud.core.modules.shop.mapper.ShopScheduleExceptionMapper; import com.xiaowang.jayucloud.core.modules.user.entity.UserDO; @@ -379,6 +380,115 @@ class PlanningServiceImplTest { .hasMessageContaining("当前日期为店铺休息日"); } + @Test + void createAppointmentAllowsCrossDayWhenTouchedDaysAreOpen() { + UserDO manager = user(2, 8L); + UserDO artist = user(3, 8L); + artist.setId(20L); + UserDO customer = user(0, 8L); + customer.setId(30L); + ShopDO shop = new ShopDO(); + shop.setBusinessHours("00:00-23:59:59"); + shop.setSchedulePresetType("EVERYDAY"); + shop.setScheduleWorkDays("1,2,3,4,5,6,7"); + PlanningAppointmentCreateDTO dto = new PlanningAppointmentCreateDTO(); + dto.setCustomerUserId(30L); + dto.setArtistId(20L); + dto.setAppointmentDate("2026-07-02"); + dto.setAppointmentTime("23:30"); + dto.setDurationMinutes(500); + dto.setManualProductTitle("跨天测试"); + dto.setManualProductPrice(new BigDecimal("100.00")); + + OrderItemDO[] storedItem = new OrderItemDO[1]; + when(adminScopeHelper.resolveShopScope(manager, null)).thenReturn(8L); + when(userMapper.selectById(20L)).thenReturn(artist); + when(userMapper.selectById(30L)).thenReturn(customer); + when(shopMapper.selectById(8L)).thenReturn(shop); + when(shopScheduleExceptionMapper.selectOne(any())).thenReturn(null); + when(snowflakeIdGenerator.nextIdString()).thenReturn("202607020001"); + when(orderMapper.insert(any(OrderDO.class))).thenAnswer(invocation -> { + OrderDO order = invocation.getArgument(0); + order.setId(200L); + return 1; + }); + when(orderItemMapper.insert(any(OrderItemDO.class))).thenAnswer(invocation -> { + OrderItemDO item = invocation.getArgument(0); + item.setId(300L); + storedItem[0] = item; + return 1; + }); + when(orderItemMapper.selectById(300L)).thenAnswer(invocation -> storedItem[0]); + when(orderMapper.selectById(200L)).thenReturn(order(200L, 8L, 30L)); + AppointmentReservationDO reservation = reservation( + 20L, + 200L, + 300L, + LocalDateTime.of(2026, 7, 2, 23, 30), + LocalDateTime.of(2026, 7, 3, 7, 50) + ); + reservation.setProductTitle("跨天测试"); + when(appointmentReservationMapper.selectOne(any())).thenReturn(reservation); + when(userMapper.selectBatchIds(any())).thenReturn(List.of(customer)); + when(userMapper.selectList(any())).thenReturn(List.of(artist)); + when(nailArtistInfoMapper.selectList(any())).thenReturn(List.of()); + when(artistScheduleRuleMapper.selectList(any())) + .thenReturn(List.of(scheduleRule(20L, "EVERYDAY", "1,2,3,4,5,6,7", LocalTime.MIN, LocalTime.of(23, 59, 59)))); + + var appointment = planningService.createAppointment(manager, dto); + + assertThat(storedItem[0].getAppointmentTime()).isEqualTo(LocalDateTime.of(2026, 7, 2, 23, 30)); + assertThat(appointment.getStartTime()).isEqualTo("2026-07-02 23:30:00"); + assertThat(appointment.getEndTime()).isEqualTo("2026-07-03 07:50:00"); + org.mockito.Mockito.verify(appointmentCapacityService).reserveConfirmedOrThrow( + 200L, + 300L, + 8L, + 20L, + "跨天测试", + LocalDateTime.of(2026, 7, 2, 23, 30), + LocalDateTime.of(2026, 7, 3, 7, 50), + null + ); + } + + @Test + void createAppointmentRejectsCrossDayWhenNextDayIsStoreRest() { + UserDO manager = user(2, 8L); + UserDO artist = user(3, 8L); + artist.setId(20L); + UserDO customer = user(0, 8L); + customer.setId(30L); + ShopDO shop = new ShopDO(); + shop.setBusinessHours("00:00-23:59:59"); + shop.setSchedulePresetType("EVERYDAY"); + shop.setScheduleWorkDays("1,2,3,4,5,6,7"); + ShopScheduleExceptionDO restException = new ShopScheduleExceptionDO(); + restException.setShopId(8L); + restException.setWorkDate(LocalDate.of(2026, 7, 3)); + restException.setExceptionType("REST"); + restException.setIsDelete(0); + PlanningAppointmentCreateDTO dto = new PlanningAppointmentCreateDTO(); + dto.setCustomerUserId(30L); + dto.setArtistId(20L); + dto.setAppointmentDate("2026-07-02"); + dto.setAppointmentTime("23:30"); + dto.setDurationMinutes(500); + dto.setManualProductTitle("跨天休息测试"); + dto.setManualProductPrice(new BigDecimal("100.00")); + + when(adminScopeHelper.resolveShopScope(manager, null)).thenReturn(8L); + when(userMapper.selectById(20L)).thenReturn(artist); + when(userMapper.selectById(30L)).thenReturn(customer); + when(shopMapper.selectById(8L)).thenReturn(shop); + when(shopScheduleExceptionMapper.selectOne(any())).thenReturn(null).thenReturn(restException); + + assertThatThrownBy(() -> planningService.createAppointment(manager, dto)) + .hasMessageContaining("当前日期为店铺休息日") + .hasMessageContaining("2026-07-03"); + org.mockito.Mockito.verify(orderMapper, org.mockito.Mockito.never()).insert(any(OrderDO.class)); + } + @Test void updateAppointmentRejectsCompletedOrder() { UserDO manager = user(2, 8L); diff --git a/JY-Core/src/test/java/com/xiaowang/jayucloud/core/modules/user/service/impl/UserServiceImplPermissionAssignmentTest.java b/JY-Core/src/test/java/com/xiaowang/jayucloud/core/modules/user/service/impl/UserServiceImplPermissionAssignmentTest.java index 8d84e9fc..664a415b 100644 --- a/JY-Core/src/test/java/com/xiaowang/jayucloud/core/modules/user/service/impl/UserServiceImplPermissionAssignmentTest.java +++ b/JY-Core/src/test/java/com/xiaowang/jayucloud/core/modules/user/service/impl/UserServiceImplPermissionAssignmentTest.java @@ -1,6 +1,8 @@ package com.xiaowang.jayucloud.core.modules.user.service.impl; import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; +import com.xiaowang.jayucloud.core.modules.artist.entity.ArtistScheduleRuleDO; +import com.xiaowang.jayucloud.core.modules.artist.mapper.ArtistScheduleRuleMapper; import com.xiaowang.jayucloud.core.modules.security.mapper.PermissionMapper; import com.xiaowang.jayucloud.core.config.BrandProperties; import com.xiaowang.jayucloud.core.modules.shop.mapper.ShopMapper; @@ -28,6 +30,7 @@ import com.xiaowang.jayucloud.core.utils.JwtUtil; import org.junit.jupiter.api.AfterEach; 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 org.springframework.data.redis.core.StringRedisTemplate; @@ -79,6 +82,9 @@ class UserServiceImplPermissionAssignmentTest { @Mock private NailArtistInfoService nailArtistInfoService; + @Mock + private ArtistScheduleRuleMapper artistScheduleRuleMapper; + @Mock private VerificationCodeService verificationCodeService; @@ -121,6 +127,7 @@ class UserServiceImplPermissionAssignmentTest { brandProperties, userShopRoleMapper, nailArtistInfoService, + artistScheduleRuleMapper, verificationCodeService, userShopBindingSupport, objectStorageUrlSupport, @@ -201,6 +208,7 @@ class UserServiceImplPermissionAssignmentTest { when(userShopBindingSupport.isShopActive(8L)).thenReturn(true); when(permissionMapper.selectList(any())).thenReturn(existingManagedPermissionsFromCatalog()); when(userPermissionMapper.selectList(any())).thenReturn(List.of()); + when(artistScheduleRuleMapper.selectOne(any())).thenReturn(null); doAnswer(invocation -> { UserDO userDO = invocation.getArgument(0); assertThat(userDO.getPhone()).isNull(); @@ -214,6 +222,14 @@ class UserServiceImplPermissionAssignmentTest { assertThat(userId).isEqualTo(43L); verify(userShopBindingSupport).syncUserShopBindings(43L, List.of(8L)); verify(nailArtistInfoService).saveOrUpdateNailArtistInfo(any()); + ArgumentCaptor ruleCaptor = ArgumentCaptor.forClass(ArtistScheduleRuleDO.class); + verify(artistScheduleRuleMapper).insert(ruleCaptor.capture()); + assertThat(ruleCaptor.getValue().getShopId()).isEqualTo(8L); + assertThat(ruleCaptor.getValue().getArtistId()).isEqualTo(43L); + assertThat(ruleCaptor.getValue().getPresetType()).isEqualTo("EVERYDAY"); + assertThat(ruleCaptor.getValue().getWorkDays()).isEqualTo("1,2,3,4,5,6,7"); + assertThat(ruleCaptor.getValue().getStartTime()).isEqualTo(java.time.LocalTime.MIN); + assertThat(ruleCaptor.getValue().getEndTime()).isEqualTo(java.time.LocalTime.of(23, 59, 59)); } @Test diff --git a/JY-Salon-Front/src/utils/available-times.test.ts b/JY-Salon-Front/src/utils/available-times.test.ts index 80959e18..d93e4ae4 100644 --- a/JY-Salon-Front/src/utils/available-times.test.ts +++ b/JY-Salon-Front/src/utils/available-times.test.ts @@ -91,4 +91,45 @@ describe('available time groups', () => { expect(groups[0]?.times.map(item => item.value)).toEqual(['09:00', '09:15', '09:30']) }) + + it('builds cross-day slots when next day remains available', () => { + const calendar: PlanningCalendar = { + daySummaries: [ + { date: '2026-06-29', totalCount: 0, dayStatus: 'free', businessStartTime: '00:00', businessEndTime: '23:59:59' }, + { date: '2026-06-30', totalCount: 0, dayStatus: 'free', businessStartTime: '00:00', businessEndTime: '23:59:59' } + ], + schedules: [ + { artistId: 1, date: '2026-06-29', startTime: '23:30', endTime: '23:59:59', status: 1 }, + { artistId: 1, date: '2026-06-30', startTime: '00:00', endTime: '23:59:59', status: 1 } + ], + appointments: [ + { orderItemId: 101, artistId: 1, date: '2026-06-30', startTime: '2026-06-30 09:00:00', endTime: '2026-06-30 10:00:00', status: 1 } + ] + } + const form = buildForm() + form.durationMinutes = '500' + + const groups = buildAvailableTimeGroups(calendar, form) + + expect(groups[groups.length - 1]?.times).toContainEqual({ value: '23:30', rangeText: '23:30-次日07:50' }) + }) + + it('rejects cross-day slots when next day is closed', () => { + const calendar: PlanningCalendar = { + daySummaries: [ + { date: '2026-06-29', totalCount: 0, dayStatus: 'free', businessStartTime: '00:00', businessEndTime: '23:59:59' }, + { date: '2026-06-30', totalCount: 0, dayStatus: 'rest', businessStartTime: '00:00', businessEndTime: '23:59:59' } + ], + schedules: [ + { artistId: 1, date: '2026-06-29', startTime: '23:30', endTime: '23:59:59', status: 1 }, + { artistId: 1, date: '2026-06-30', startTime: '00:00', endTime: '23:59:59', status: 1 } + ] + } + const form = buildForm() + form.durationMinutes = '500' + + const groups = buildAvailableTimeGroups(calendar, form) + + expect(groups.flatMap(group => group.times.map(item => item.value))).not.toContain('23:30') + }) }) diff --git a/JY-Salon-Front/src/utils/available-times.ts b/JY-Salon-Front/src/utils/available-times.ts index 9c5299b1..09af9ff6 100644 --- a/JY-Salon-Front/src/utils/available-times.ts +++ b/JY-Salon-Front/src/utils/available-times.ts @@ -1,8 +1,11 @@ import type { Appointment, AppointmentForm, ArtistSchedule, PlanningCalendar } from '@/types/manager' import { extractTimeText, normalizeDuration, resolveAppointmentDate, resolveAppointmentEndMinute, resolveAppointmentStartMinute } from '@/utils/planning' -import { minutesOfDay, timeFromMinutes } from '@/utils/date' +import { addDays, formatDate, minutesOfDay, timeFromMinutes } from '@/utils/date' const TIME_SLOT_MINUTES = 15 +const DAY_MINUTES = 24 * 60 +const DAY_END_COVER_MINUTE = 23 * 60 + 59 +const DAY_MS = 24 * 60 * 60 * 1000 export interface AvailableTime { value: string @@ -15,8 +18,28 @@ export interface AvailableTimeGroup { times: AvailableTime[] } -const buildTimeRangeLabel = (startMinute: number, durationMinutes: number): string => { - return `${timeFromMinutes(startMinute)}-${timeFromMinutes(startMinute + durationMinutes)}` +interface TimeSegment { + date: string + startMinute: number + endMinute: number +} + +interface BusyRange { + startMinute: number + endMinute: number +} + +export const buildAvailableTimeRangeLabel = (startMinute: number, durationMinutes: number): string => { + const endMinute = startMinute + durationMinutes + const endOffset = Math.floor(endMinute / DAY_MINUTES) + const endText = timeFromMinutes(endMinute) + if (endOffset === 0) { + return `${timeFromMinutes(startMinute)}-${endText}` + } + if (endOffset === 1) { + return `${timeFromMinutes(startMinute)}-次日${endText}` + } + return `${timeFromMinutes(startMinute)}-+${endOffset}天${endText}` } const getTimePeriod = (minute: number): { key: string; title: string } => { @@ -31,28 +54,124 @@ const getTimePeriod = (minute: number): { key: string; title: string } => { const isCancelledAppointment = (item: Appointment): boolean => item.status === 3 || item.statusText === '已取消' -const buildBusyRanges = (appointments: Appointment[], form: AppointmentForm): Array<{ startMinute: number; endMinute: number }> => { +const parseDateDayNumber = (dateText: string): number => { + const parts = String(dateText || '').split('-').map(Number) + if (parts.length !== 3 || parts.some(value => !Number.isFinite(value))) { + throw new Error(`无效日期:${dateText}`) + } + return Math.floor(Date.UTC(parts[0], parts[1] - 1, parts[2]) / DAY_MS) +} + +const dateOffset = (baseDate: string, targetDate: string): number => { + return parseDateDayNumber(targetDate) - parseDateDayNumber(baseDate) +} + +const resolveDateByOffset = (baseDate: string, offset: number): string => { + return formatDate(addDays(baseDate, offset)) +} + +const resolveCoverageEndMinute = (timeText: string | undefined): number => { + const minute = minutesOfDay(extractTimeText(timeText)) + return minute >= DAY_END_COVER_MINUTE ? DAY_MINUTES : minute +} + +const resolveAppointmentAbsoluteStartMinute = (item: Appointment, baseDate: string): number => { + return dateOffset(baseDate, resolveAppointmentDate(item)) * DAY_MINUTES + resolveAppointmentStartMinute(item) +} + +const resolveAppointmentAbsoluteEndMinute = (item: Appointment, baseDate: string, startMinute: number): number => { + if (item.endTime) { + const endText = String(item.endTime) + if (/^\d{4}-\d{2}-\d{2}/.test(endText)) { + const absoluteEndMinute = dateOffset(baseDate, endText.slice(0, 10)) * DAY_MINUTES + minutesOfDay(extractTimeText(endText)) + return absoluteEndMinute <= startMinute ? startMinute + Number(item.durationMinutes || 0) : absoluteEndMinute + } + } + if (item.durationMinutes && Number(item.durationMinutes) > 0) { + return startMinute + Number(item.durationMinutes) + } + const localEndMinute = resolveAppointmentEndMinute(item, startMinute % DAY_MINUTES) + const absoluteEndMinute = Math.floor(startMinute / DAY_MINUTES) * DAY_MINUTES + localEndMinute + return absoluteEndMinute <= startMinute ? absoluteEndMinute + DAY_MINUTES : absoluteEndMinute +} + +const buildBusyRanges = (appointments: Appointment[], form: AppointmentForm): BusyRange[] => { return appointments .filter(item => String(item.artistId) === String(form.artistId)) - .filter(item => resolveAppointmentDate(item) === form.appointmentDate) .filter(item => !isCancelledAppointment(item)) .map(item => { - const startMinute = resolveAppointmentStartMinute(item) - return { startMinute, endMinute: resolveAppointmentEndMinute(item, startMinute) } + const startMinute = resolveAppointmentAbsoluteStartMinute(item, form.appointmentDate) + return { startMinute, endMinute: resolveAppointmentAbsoluteEndMinute(item, form.appointmentDate, startMinute) } }) } -const hasBusyConflict = (startMinute: number, endMinute: number, ranges: Array<{ startMinute: number; endMinute: number }>): boolean => { +const hasBusyConflict = (startMinute: number, endMinute: number, ranges: BusyRange[]): boolean => { return ranges.some(range => startMinute < range.endMinute && endMinute > range.startMinute) } -const clampToBusinessHours = (startMinute: number, endMinute: number, businessStartTime?: string, businessEndTime?: string): { startMinute: number; endMinute: number } => { - const businessStartMinute = businessStartTime ? minutesOfDay(businessStartTime) : startMinute - const businessEndMinute = businessEndTime ? minutesOfDay(businessEndTime) : endMinute - return { - startMinute: Math.max(startMinute, businessStartMinute), - endMinute: Math.min(endMinute, businessEndMinute) +const splitWindowSegments = (appointmentDate: string, startMinute: number, durationMinutes: number): TimeSegment[] => { + const segments: TimeSegment[] = [] + const endMinute = startMinute + durationMinutes + let cursor = startMinute + while (cursor < endMinute) { + const offset = Math.floor(cursor / DAY_MINUTES) + const nextDayMinute = (offset + 1) * DAY_MINUTES + const segmentEndAbsoluteMinute = Math.min(endMinute, nextDayMinute) + segments.push({ + date: resolveDateByOffset(appointmentDate, offset), + startMinute: cursor - offset * DAY_MINUTES, + endMinute: segmentEndAbsoluteMinute === nextDayMinute ? DAY_MINUTES : segmentEndAbsoluteMinute - offset * DAY_MINUTES + }) + cursor = segmentEndAbsoluteMinute } + return segments +} + +export const resolveAppointmentCalendarEndDate = (form: AppointmentForm): string => { + const durationMinutes = normalizeDuration(form.durationMinutes) + if (!form.appointmentDate || !durationMinutes) { + return form.appointmentDate + } + const latestCandidateStartMinute = DAY_MINUTES - TIME_SLOT_MINUTES + const endOffset = Math.floor((latestCandidateStartMinute + durationMinutes - 1) / DAY_MINUTES) + return resolveDateByOffset(form.appointmentDate, Math.max(0, endOffset)) +} + +const findDaySummary = (calendar: PlanningCalendar, date: string) => { + return (calendar.daySummaries || []).find(item => item.date === date) +} + +const isBusinessSegmentAvailable = (calendar: PlanningCalendar, segment: TimeSegment): boolean => { + const daySummary = findDaySummary(calendar, segment.date) + if (daySummary?.dayStatus === 'rest') { + return false + } + const businessStartTime = daySummary?.businessStartTime || calendar.businessStartTime + const businessEndTime = daySummary?.businessEndTime || calendar.businessEndTime + const businessStartMinute = businessStartTime ? minutesOfDay(extractTimeText(businessStartTime)) : segment.startMinute + const businessEndMinute = businessEndTime ? resolveCoverageEndMinute(businessEndTime) : segment.endMinute + return segment.startMinute >= businessStartMinute && segment.endMinute <= businessEndMinute +} + +const isScheduleSegmentAvailable = (calendar: PlanningCalendar, form: AppointmentForm, segment: TimeSegment): boolean => { + return (calendar.schedules || []) + .filter((item: ArtistSchedule) => String(item.artistId) === String(form.artistId)) + .filter(item => item.date === segment.date) + .filter(item => item.status === 1 && Number(item.capacity === undefined ? 1 : item.capacity) >= 1) + .some(schedule => { + const scheduleStartMinute = minutesOfDay(extractTimeText(schedule.startTime)) + const scheduleEndMinute = resolveCoverageEndMinute(schedule.endTime) + return segment.startMinute >= scheduleStartMinute && segment.endMinute <= scheduleEndMinute + }) +} + +const isWindowAvailable = (calendar: PlanningCalendar, form: AppointmentForm, startMinute: number, durationMinutes: number, busyRanges: BusyRange[]): boolean => { + const endMinute = startMinute + durationMinutes + if (hasBusyConflict(startMinute, endMinute, busyRanges)) { + return false + } + const segments = splitWindowSegments(form.appointmentDate, startMinute, durationMinutes) + return segments.every(segment => isBusinessSegmentAvailable(calendar, segment) && isScheduleSegmentAvailable(calendar, form, segment)) } export const buildAvailableTimeGroups = (calendar: PlanningCalendar, form: AppointmentForm): AvailableTimeGroup[] => { @@ -60,7 +179,7 @@ export const buildAvailableTimeGroups = (calendar: PlanningCalendar, form: Appoi if (!durationMinutes) { return [] } - const daySummary = (calendar.daySummaries || []).find(item => item.date === form.appointmentDate) + const daySummary = findDaySummary(calendar, form.appointmentDate) if (daySummary?.dayStatus === 'rest') { return [] } @@ -75,21 +194,22 @@ export const buildAvailableTimeGroups = (calendar: PlanningCalendar, form: Appoi evening: { key: 'evening', title: '晚上', times: [] } } schedules.forEach(schedule => { - const range = clampToBusinessHours( + const businessStartTime = daySummary?.businessStartTime || calendar.businessStartTime + const businessEndTime = daySummary?.businessEndTime || calendar.businessEndTime + const scheduleStart = Math.max( minutesOfDay(extractTimeText(schedule.startTime)), - minutesOfDay(extractTimeText(schedule.endTime)), - daySummary?.businessStartTime, - daySummary?.businessEndTime + businessStartTime ? minutesOfDay(extractTimeText(businessStartTime)) : 0 ) - const scheduleStart = range.startMinute - const scheduleEnd = range.endMinute - for (let minute = scheduleStart; minute + durationMinutes <= scheduleEnd; minute += TIME_SLOT_MINUTES) { - const endMinute = minute + durationMinutes - if (!hasBusyConflict(minute, endMinute, busyRanges)) { + const scheduleEnd = Math.min( + resolveCoverageEndMinute(schedule.endTime), + businessEndTime ? resolveCoverageEndMinute(businessEndTime) : DAY_MINUTES + ) + for (let minute = scheduleStart; minute < scheduleEnd; minute += TIME_SLOT_MINUTES) { + if (isWindowAvailable(calendar, form, minute, durationMinutes, busyRanges)) { const period = getTimePeriod(minute) const group = groupMap[period.key] if (group) { - group.times.push({ value: timeFromMinutes(minute), rangeText: buildTimeRangeLabel(minute, durationMinutes) }) + group.times.push({ value: timeFromMinutes(minute), rangeText: buildAvailableTimeRangeLabel(minute, durationMinutes) }) } } } diff --git a/JY-Salon-Front/src/views/AppointmentFormView.vue b/JY-Salon-Front/src/views/AppointmentFormView.vue index e2b87d1c..96285985 100644 --- a/JY-Salon-Front/src/views/AppointmentFormView.vue +++ b/JY-Salon-Front/src/views/AppointmentFormView.vue @@ -280,8 +280,8 @@ import type { Appointment, AppointmentForm, Artist, PlanningCalendar, Product } import type { UserInfo } from '@/types/common' import { useSessionStore } from '@/stores/session' import { useToastStore } from '@/stores/toast' -import { formatDate, minutesOfDay, timeFromMinutes } from '@/utils/date' -import { buildAvailableTimeGroups, type AvailableTimeGroup } from '@/utils/available-times' +import { formatDate } from '@/utils/date' +import { buildAvailableTimeGroups, resolveAppointmentCalendarEndDate, type AvailableTimeGroup } from '@/utils/available-times' import { buildCustomerCreateDraft, buildCustomerSearchText, @@ -1005,7 +1005,11 @@ const refreshAvailableTimes = async (): Promise => { } timeLoading.value = true try { - const calendar = withoutCurrentAppointment(await managerPlanningApi.calendar({ startDate: form.appointmentDate, endDate: form.appointmentDate, artistId: form.artistId })) + const calendar = withoutCurrentAppointment(await managerPlanningApi.calendar({ + startDate: form.appointmentDate, + endDate: resolveAppointmentCalendarEndDate(form), + artistId: form.artistId + })) availableTimeGroups.value = buildAvailableTimeGroups(calendar, form) timeSelectTip.value = availableTimeGroups.value.length > 0 ? '请选择预约时间' : '当前美甲师当天暂无可约时间' } finally { @@ -1033,23 +1037,25 @@ const checkAvailability = async (): Promise<{ ok: boolean; tip?: string }> => { conflictTip.value = '' return { ok: true } } - const startMinute = minutesOfDay(form.appointmentTime) - const endMinute = startMinute + normalizeDuration(form.durationMinutes) - const calendar = withoutCurrentAppointment(await managerPlanningApi.calendar({ startDate: form.appointmentDate, endDate: form.appointmentDate, artistId: form.artistId })) + const calendar = withoutCurrentAppointment(await managerPlanningApi.calendar({ + startDate: form.appointmentDate, + endDate: resolveAppointmentCalendarEndDate(form), + artistId: form.artistId + })) const daySummary = (calendar.daySummaries || []).find(item => item.date === form.appointmentDate) - const businessStartTime = String(daySummary?.businessStartTime || calendar.businessStartTime || '10:00').slice(0, 5) - const businessEndTime = String(daySummary?.businessEndTime || calendar.businessEndTime || '22:00').slice(0, 5) if (daySummary?.dayStatus === 'rest') { conflictTip.value = '当前日期为店铺休息日' conflictLevel.value = 'danger' return { ok: false, tip: conflictTip.value } } - if (startMinute < minutesOfDay(businessStartTime) || endMinute > minutesOfDay(businessEndTime)) { - conflictTip.value = `该时间超出营业时间 ${businessStartTime}-${businessEndTime}` + const availableGroups = buildAvailableTimeGroups(calendar, form) + const selectedTime = availableGroups.flatMap(group => group.times).find(item => item.value === form.appointmentTime) + if (!selectedTime) { + conflictTip.value = '当前时间不可预约,请重新选择可约时间' conflictLevel.value = 'danger' return { ok: false, tip: conflictTip.value } } - conflictTip.value = `当前时段 ${form.appointmentTime}-${timeFromMinutes(endMinute)} 可预约` + conflictTip.value = `当前时段 ${selectedTime.rangeText} 可预约` conflictLevel.value = 'free' return { ok: true, tip: conflictTip.value } } diff --git a/JY-Salon-WeChat/pages/appointment-form/index.js b/JY-Salon-WeChat/pages/appointment-form/index.js index f2e691d5..c1688791 100644 --- a/JY-Salon-WeChat/pages/appointment-form/index.js +++ b/JY-Salon-WeChat/pages/appointment-form/index.js @@ -8,6 +8,9 @@ const { chooseImageFilePaths, uploadObjectFile, resolveUploadedImagePreviewUrl } const DRAFT_STORAGE_PREFIX = 'managerAppointmentDraft' const TIME_SLOT_MINUTES = 15 +const DAY_MINUTES = 24 * 60 +const DAY_END_COVER_MINUTE = 23 * 60 + 59 +const DAY_MS = 24 * 60 * 60 * 1000 const ARTIST_FALLBACK_COLORS = ['#7AA9C2', '#8EB99B', '#BDA7D8', '#D7B17D', '#D98D8D'] const ARTIST_PRESET_LABELS = { EVERYDAY: '每天', @@ -153,7 +156,16 @@ function normalizeDuration(value) { } function buildTimeRangeLabel(startMinute, durationMinutes) { - return `${dateUtil.timeFromMinutes(startMinute)}-${dateUtil.timeFromMinutes(startMinute + durationMinutes)}` + const endMinute = startMinute + durationMinutes + const endOffset = Math.floor(endMinute / DAY_MINUTES) + const endText = dateUtil.timeFromMinutes(endMinute) + if (endOffset === 0) { + return `${dateUtil.timeFromMinutes(startMinute)}-${endText}` + } + if (endOffset === 1) { + return `${dateUtil.timeFromMinutes(startMinute)}-次日${endText}` + } + return `${dateUtil.timeFromMinutes(startMinute)}-+${endOffset}天${endText}` } function getTimePeriod(minute) { @@ -170,6 +182,22 @@ function normalizeAppointmentDate(item) { return item.date || String(item.startTime || '').slice(0, 10) } +function parseDateDayNumber(dateText) { + const parts = String(dateText || '').split('-').map(Number) + if (parts.length !== 3 || parts.some(value => !Number.isFinite(value))) { + throw new Error(`无效日期:${dateText}`) + } + return Math.floor(Date.UTC(parts[0], parts[1] - 1, parts[2]) / DAY_MS) +} + +function dateOffset(baseDate, targetDate) { + return parseDateDayNumber(targetDate) - parseDateDayNumber(baseDate) +} + +function resolveDateByOffset(baseDate, offset) { + return dateUtil.formatDate(dateUtil.addDays(baseDate, offset)) +} + function extractTimeText(value) { const target = String(value || '') if (target.includes('T')) { @@ -198,6 +226,31 @@ function resolveAppointmentEndMinute(item, startMinute) { return startMinute + Number(item.durationMinutes || 60) } +function resolveCoverageEndMinute(timeText) { + const minute = dateUtil.minutesOfDay(extractTimeText(timeText)) + return minute >= DAY_END_COVER_MINUTE ? DAY_MINUTES : minute +} + +function resolveAppointmentAbsoluteStartMinute(item, baseDate) { + return dateOffset(baseDate, normalizeAppointmentDate(item)) * DAY_MINUTES + resolveAppointmentStartMinute(item) +} + +function resolveAppointmentAbsoluteEndMinute(item, baseDate, startMinute) { + if (item.endTime) { + const endText = String(item.endTime) + if (/^\d{4}-\d{2}-\d{2}/.test(endText)) { + const absoluteEndMinute = dateOffset(baseDate, endText.slice(0, 10)) * DAY_MINUTES + dateUtil.minutesOfDay(extractTimeText(endText)) + return absoluteEndMinute <= startMinute ? startMinute + Number(item.durationMinutes || 0) : absoluteEndMinute + } + } + if (item.durationMinutes && Number(item.durationMinutes) > 0) { + return startMinute + Number(item.durationMinutes) + } + const localEndMinute = resolveAppointmentEndMinute(item, startMinute % DAY_MINUTES) + const absoluteEndMinute = Math.floor(startMinute / DAY_MINUTES) * DAY_MINUTES + localEndMinute + return absoluteEndMinute <= startMinute ? absoluteEndMinute + DAY_MINUTES : absoluteEndMinute +} + function isCancelledAppointment(item) { return item.status === 3 || item.statusText === '已取消' } @@ -205,13 +258,12 @@ function isCancelledAppointment(item) { function buildBusyRanges(appointments, form) { return (appointments || []) .filter(item => String(item.artistId) === String(form.artistId)) - .filter(item => normalizeAppointmentDate(item) === form.appointmentDate) .filter(item => !isCancelledAppointment(item)) .map(item => { - const startMinute = resolveAppointmentStartMinute(item) + const startMinute = resolveAppointmentAbsoluteStartMinute(item, form.appointmentDate) return { startMinute, - endMinute: resolveAppointmentEndMinute(item, startMinute) + endMinute: resolveAppointmentAbsoluteEndMinute(item, form.appointmentDate, startMinute) } }) } @@ -220,13 +272,75 @@ function hasBusyConflict(startMinute, endMinute, ranges) { return ranges.some(range => startMinute < range.endMinute && endMinute > range.startMinute) } -function clampToBusinessHours(startMinute, endMinute, businessStartTime, businessEndTime) { - const businessStartMinute = businessStartTime ? dateUtil.minutesOfDay(businessStartTime) : startMinute - const businessEndMinute = businessEndTime ? dateUtil.minutesOfDay(businessEndTime) : endMinute - return { - startMinute: Math.max(startMinute, businessStartMinute), - endMinute: Math.min(endMinute, businessEndMinute) +function splitWindowSegments(appointmentDate, startMinute, durationMinutes) { + const segments = [] + const endMinute = startMinute + durationMinutes + let cursor = startMinute + while (cursor < endMinute) { + const offset = Math.floor(cursor / DAY_MINUTES) + const nextDayMinute = (offset + 1) * DAY_MINUTES + const segmentEndAbsoluteMinute = Math.min(endMinute, nextDayMinute) + segments.push({ + date: resolveDateByOffset(appointmentDate, offset), + startMinute: cursor - offset * DAY_MINUTES, + endMinute: segmentEndAbsoluteMinute === nextDayMinute ? DAY_MINUTES : segmentEndAbsoluteMinute - offset * DAY_MINUTES + }) + cursor = segmentEndAbsoluteMinute } + return segments +} + +function resolveAppointmentCalendarEndDate(form) { + const durationMinutes = normalizeDuration(form.durationMinutes) + if (!form.appointmentDate || !durationMinutes) { + return form.appointmentDate + } + const latestCandidateStartMinute = DAY_MINUTES - TIME_SLOT_MINUTES + const endOffset = Math.floor((latestCandidateStartMinute + durationMinutes - 1) / DAY_MINUTES) + return resolveDateByOffset(form.appointmentDate, Math.max(0, endOffset)) +} + +function findDaySummary(calendar, date) { + return (calendar.daySummaries || []).find(item => item.date === date) +} + +function isBusinessSegmentAvailable(calendar, segment) { + const daySummary = findDaySummary(calendar, segment.date) + if (daySummary && daySummary.dayStatus === 'rest') { + return false + } + const businessStartTime = (daySummary && daySummary.businessStartTime) || calendar.businessStartTime + const businessEndTime = (daySummary && daySummary.businessEndTime) || calendar.businessEndTime + const businessStartMinute = businessStartTime ? dateUtil.minutesOfDay(extractTimeText(businessStartTime)) : segment.startMinute + const businessEndMinute = businessEndTime ? resolveCoverageEndMinute(businessEndTime) : segment.endMinute + return segment.startMinute >= businessStartMinute && segment.endMinute <= businessEndMinute +} + +function isScheduleSegmentAvailable(calendar, form, segment) { + return (calendar.schedules || []) + .filter(item => String(item.artistId) === String(form.artistId)) + .filter(item => item.date === segment.date) + .filter(item => item.status === 1 && Number(item.capacity === undefined ? 1 : item.capacity) >= 1) + .some(schedule => { + const scheduleStartMinute = dateUtil.minutesOfDay(extractTimeText(schedule.startTime)) + const scheduleEndMinute = resolveCoverageEndMinute(schedule.endTime) + return segment.startMinute >= scheduleStartMinute && segment.endMinute <= scheduleEndMinute + }) +} + +function isWindowAvailable(calendar, form, startMinute, durationMinutes, busyRanges) { + const endMinute = startMinute + durationMinutes + if (hasBusyConflict(startMinute, endMinute, busyRanges)) { + return false + } + const segments = splitWindowSegments(form.appointmentDate, startMinute, durationMinutes) + for (let index = 0; index < segments.length; index += 1) { + const segment = segments[index] + if (!isBusinessSegmentAvailable(calendar, segment) || !isScheduleSegmentAvailable(calendar, form, segment)) { + return false + } + } + return true } function getCurrentMinuteOfDay() { @@ -260,7 +374,7 @@ function resolveTimeSelectTip(form, availableTimes) { } function buildAvailableTimeGroups(calendar, form, durationMinutes) { - const daySummary = (calendar.daySummaries || []).find(item => item.date === form.appointmentDate) + const daySummary = findDaySummary(calendar, form.appointmentDate) if (daySummary && daySummary.dayStatus === 'rest') { return [] } @@ -275,17 +389,18 @@ function buildAvailableTimeGroups(calendar, form, durationMinutes) { evening: { key: 'evening', title: '晚上', times: [] } } schedules.forEach(schedule => { - const range = clampToBusinessHours( + const businessStartTime = (daySummary && daySummary.businessStartTime) || calendar.businessStartTime + const businessEndTime = (daySummary && daySummary.businessEndTime) || calendar.businessEndTime + const scheduleStart = Math.max( dateUtil.minutesOfDay(extractTimeText(schedule.startTime)), - dateUtil.minutesOfDay(extractTimeText(schedule.endTime)), - daySummary && daySummary.businessStartTime, - daySummary && daySummary.businessEndTime + businessStartTime ? dateUtil.minutesOfDay(extractTimeText(businessStartTime)) : 0 ) - const scheduleStart = range.startMinute - const scheduleEnd = range.endMinute - for (let minute = scheduleStart; minute + durationMinutes <= scheduleEnd; minute += TIME_SLOT_MINUTES) { - const endMinute = minute + durationMinutes - if (canUseTimeMinute(form, minute) && !hasBusyConflict(minute, endMinute, busyRanges)) { + const scheduleEnd = Math.min( + resolveCoverageEndMinute(schedule.endTime), + businessEndTime ? resolveCoverageEndMinute(businessEndTime) : DAY_MINUTES + ) + for (let minute = scheduleStart; minute < scheduleEnd; minute += TIME_SLOT_MINUTES) { + if (canUseTimeMinute(form, minute) && isWindowAvailable(calendar, form, minute, durationMinutes, busyRanges)) { const period = getTimePeriod(minute) groupMap[period.key].times.push({ value: dateUtil.timeFromMinutes(minute), @@ -446,18 +561,6 @@ function collectManualProductImages(fileIds, imageUrls) { return splitManualImageValues(`${fileIds || ''},${imageUrls || ''}`) } -function isScheduleCoveringTime(schedule, form, startMinute, endMinute) { - if (!schedule || String(schedule.artistId) !== String(form.artistId) || schedule.date !== form.appointmentDate) { - return false - } - if (schedule.status !== 1 || Number(schedule.capacity === undefined ? 1 : schedule.capacity) < 1) { - return false - } - const scheduleStartMinute = dateUtil.minutesOfDay(extractTimeText(schedule.startTime)) - const scheduleEndMinute = dateUtil.minutesOfDay(extractTimeText(schedule.endTime)) - return scheduleStartMinute <= startMinute && scheduleEndMinute >= endMinute -} - function normalizeCustomer(customer) { const name = customer.nickname || customer.name || customer.account || '' const phone = customer.contactPhone || customer.phone || '' @@ -992,7 +1095,7 @@ Page({ try { const calendar = await planningApi.calendar({ startDate: form.appointmentDate, - endDate: form.appointmentDate, + endDate: resolveAppointmentCalendarEndDate(form), artistId: form.artistId }) if (requestSeq !== this._availableTimeRequestSeq) { @@ -1057,8 +1160,6 @@ Page({ this.setData({ conflictTip: '', conflictLevel: 'free' }) return { ok: true } } - const startMinute = dateUtil.minutesOfDay(form.appointmentTime) - const endMinute = startMinute + durationMinutes if (isPastAppointmentTime(form)) { const tip = '请选择当前时间之后的预约时间' this.setData({ conflictTip: tip, conflictLevel: 'danger' }) @@ -1067,44 +1168,23 @@ Page({ try { const calendar = await planningApi.calendar({ startDate: form.appointmentDate, - endDate: form.appointmentDate, + endDate: resolveAppointmentCalendarEndDate(form), artistId: form.artistId }) - const daySummary = (calendar.daySummaries || []).find(item => item.date === form.appointmentDate) - const businessStartTime = String((daySummary && daySummary.businessStartTime) || calendar.businessStartTime || '10:00').slice(0, 5) - const businessEndTime = String((daySummary && daySummary.businessEndTime) || calendar.businessEndTime || '22:00').slice(0, 5) + const daySummary = findDaySummary(calendar, form.appointmentDate) if (daySummary && daySummary.dayStatus === 'rest') { const tip = '当前日期为店铺休息日' this.setData({ conflictTip: tip, conflictLevel: 'danger' }) return { ok: false, tip } } - if (startMinute < dateUtil.minutesOfDay(businessStartTime) || endMinute > dateUtil.minutesOfDay(businessEndTime)) { - const tip = `该时间超出营业时间 ${businessStartTime}-${businessEndTime}` + const availableTimeGroups = buildAvailableTimeGroups(calendar, form, durationMinutes) + const selectedTime = flattenTimeGroups(availableTimeGroups).find(item => item.value === form.appointmentTime) + if (!selectedTime) { + const tip = '当前时间不可预约,请重新选择可约时间' this.setData({ conflictTip: tip, conflictLevel: 'danger' }) return { ok: false, tip } } - const schedule = (calendar.schedules || []).find(item => isScheduleCoveringTime(item, form, startMinute, endMinute)) - if (!schedule) { - const tip = `${this.data.selectedArtist.name || '该美甲师'} 当前时段无可预约排班` - this.setData({ conflictTip: tip, conflictLevel: 'danger' }) - return { ok: false, tip } - } - const conflicts = (calendar.appointments || []).filter(item => { - if (String(item.artistId) !== String(form.artistId) || normalizeAppointmentDate(item) !== form.appointmentDate) return false - if (isCancelledAppointment(item)) return false - const itemStart = resolveAppointmentStartMinute(item) - const itemEnd = resolveAppointmentEndMinute(item, itemStart) - return startMinute < itemEnd && endMinute > itemStart - }) - if (conflicts.length > 0) { - const first = conflicts[0] - const itemStart = resolveAppointmentStartMinute(first) - const itemEnd = resolveAppointmentEndMinute(first, itemStart) - const tip = `${this.data.selectedArtist.name || '该美甲师'} ${dateUtil.timeFromMinutes(itemStart)}-${dateUtil.timeFromMinutes(itemEnd)} 已有预约` - this.setData({ conflictTip: tip, conflictLevel: 'danger' }) - return { ok: false, tip } - } - const tip = `${this.data.selectedArtist.name || '该美甲师'} ${form.appointmentTime}-${dateUtil.timeFromMinutes(endMinute)} 可预约` + const tip = `${this.data.selectedArtist.name || '该美甲师'} ${selectedTime.rangeText} 可预约` this.setData({ conflictTip: tip, conflictLevel: 'free' }) return { ok: true, tip } } catch (error) { diff --git a/JY-Salon-WeChat/utils/date.js b/JY-Salon-WeChat/utils/date.js index a3c4ad6b..8d5b5368 100644 --- a/JY-Salon-WeChat/utils/date.js +++ b/JY-Salon-WeChat/utils/date.js @@ -79,7 +79,8 @@ function minutesOfDay(value) { } function timeFromMinutes(minutes) { - return `${pad(Math.floor(minutes / 60))}:${pad(minutes % 60)}` + const normalized = ((minutes % (24 * 60)) + 24 * 60) % (24 * 60) + return `${pad(Math.floor(normalized / 60))}:${pad(normalized % 60)}` } module.exports = { diff --git a/docs/superpowers/specs/2026-07-22-跨天预约与员工全天排班-design.md b/docs/superpowers/specs/2026-07-22-跨天预约与员工全天排班-design.md new file mode 100644 index 00000000..3c3e9615 --- /dev/null +++ b/docs/superpowers/specs/2026-07-22-跨天预约与员工全天排班-design.md @@ -0,0 +1,35 @@ +# 跨天预约与员工全天排班设计 + +## 背景 + +本次需求包含两条业务规则: + +- 新增员工后默认拥有全周 24 小时可排班规则。 +- 新增预约支持跨天结束,只要预约覆盖到的每一天都不是门店休息日,且员工排班覆盖对应时间段,就允许创建。 + +## 方案 + +后端作为最终约束源: + +- 员工默认排班规则调整为 `EVERYDAY`,工作日为 `1,2,3,4,5,6,7`,开始时间 `00:00`,结束时间使用当天最大时间。 +- 员工创建链路在创建 `type=3` 员工资料后补齐默认排班规则,避免只依赖排班设置页首次读取兜底。 +- 预约创建、修改、改派的营业时间校验按日期切段检查,跨天预约需要每个覆盖日期都在门店营业时间内。 +- 员工容量校验按日期切段检查员工逐日排班或规则排班,任何一段不覆盖则直接拒绝。 + +端侧提供一致的候选时间: + +- 店务 Web 和店务小程序在生成候选时间时,请求覆盖预约预计结束日期的日历数据。 +- 候选时间按完整预约窗口检查门店营业、员工排班和已有预约冲突。 +- 跨天候选结束时间使用 `次日 HH:mm` 或 `+N天 HH:mm` 展示,提交仍保持原有开始日期和开始时间字段。 + +SQL 版本迁移: + +- 在 `scripts/sql/migrations/20260722-员工全周全天排班/` 下新增完整可执行脚本。 +- 已有 `t_user.type = 3` 且绑定门店的员工,更新或补齐 `t_artist_schedule_rule` 为全周全天规则。 + +## 验证 + +- 后端补充跨天营业时间与员工容量覆盖测试。 +- Web 可约时间工具补充跨天候选生成测试。 +- 小程序编辑后至少运行 JS 语法检查。 +- SQL 使用现有 SQL 结构测试或脚本检查确认不回写初始化 SQL。 diff --git a/docs/交接与当前状态.md b/docs/交接与当前状态.md index 3330d76a..9006ab80 100644 --- a/docs/交接与当前状态.md +++ b/docs/交接与当前状态.md @@ -1259,3 +1259,9 @@ rtk node -e "const fs=require('fs');const path=require('path');let n=0;function - 已完成:Web current 已切换到 `/opt/jy-artist-frontend/releases/20260715-180706/dist`,设计师域名和店务域名均可访问。 - 当前可验证状态:`https://yunail.art/health/check` 和 `https://salon.yunail.art/health/check` 均显示 `jy-gateway` 与 `jy-core` 为 3/3 healthy;`https://yunail.art/api/shop/list` 返回业务 JSON。 - 本次未变更:生产数据库、Nacos 配置、证书、域名解析和小程序。 + +## 2026-07-22 跨天预约与员工排班当前状态 + +- 已完成:代码侧已支持员工默认全周全天排班、跨天门店营业时间校验、跨天员工容量校验,以及店务 Web/小程序跨天可约时间计算。 +- 待执行 SQL:发布或更新目标库前需要执行 `scripts/sql/migrations/20260722-员工全周全天排班/员工全周全天排班刷数_20260722.sql`,用于刷新已有员工排班规则。 +- 当前注意:该 SQL 尚未生产执行,未追加 `_生产已执行` 后缀。 diff --git a/docs/项目变更记录.md b/docs/项目变更记录.md index d7feb993..3542bd8e 100644 --- a/docs/项目变更记录.md +++ b/docs/项目变更记录.md @@ -290,3 +290,12 @@ - 旧文件处理:`messagehub开发对接`、`messagehub阿里云模板场景修正`、员工排班、员工预约颜色、店铺排班、账号大小写敏感和预约客户姓名快照等旧迁移未发现生产执行并验证记录;其中部分脚本曾在开发库重置时随 9 个迁移脚本导入,或已通过 `0.0.1` 初始化 SQL 进入生产初始库,但不等同于对应迁移文件在生产执行,因此本次不追加 `_生产已执行` 后缀。 - 影响范围:仅补充执行状态复核记录;不修改 SQL 内容,不执行数据库变更,不修改初始化 SQL。 - 验证方式:核对 `docs/项目变更记录.md`、`docs/测试验收与上线记录.md`、`memory/progress.md`、`git log` 和 `scripts/sql/migrations/` 文件清单,确认无其他旧迁移具备生产执行并验证依据。 + +## 2026-07-22 跨天预约与员工全周全天默认排班 + +- 变更原因:新增员工需要默认全周 24 小时可排班;新增预约需要支持 23:30 开始、500 分钟等跨天场景,只要覆盖日期不是门店休息日且员工排班覆盖即可预约。 +- 后端处理:员工默认排班规则调整为 `EVERYDAY`、`1,2,3,4,5,6,7`、`00:00:00-23:59:59`;创建 `type=3` 员工时同步补齐默认排班规则;预约创建、修改、改派的门店营业时间校验按日期拆段;员工预约容量校验按日期拆段检查手动排班、规则排班和排班例外。 +- 端侧处理:店务 Web 与店务小程序生成可约时间时,按预约时长预取预计结束日期的日历数据;候选时间按完整跨天窗口检查门店营业、员工排班和已有预约冲突;跨天结束时间展示为 `次日HH:mm` 或 `+N天HH:mm`。 +- 数据库变更:新增 `scripts/sql/migrations/20260722-员工全周全天排班/员工全周全天排班刷数_20260722.sql`,用于将已有 active `type=3` 员工补齐或更新为全周全天排班规则;不修改初始化 SQL。 +- 影响范围:影响 `JY-Core` 员工创建、员工排班默认值、预约营业时间校验、预约容量校验;影响 `JY-Salon-Front` 和 `JY-Salon-WeChat` 预约表单可约时间生成和提交前校验。 +- 验证方式:执行后端相关单测、店务 Web 可约时间单测、店务小程序 JS 语法检查、SQL 结构测试、`git diff --check` 和 GitNexus `detect_changes`。本条 SQL 尚未标记生产已执行,发布或目标库更新时需先执行并验证。 diff --git a/memory/progress.md b/memory/progress.md index 756eb5e4..234d89e0 100644 --- a/memory/progress.md +++ b/memory/progress.md @@ -2,19 +2,21 @@ ## 当前任务 -历史迁移 SQL 执行状态复核与标记。 +跨天预约与员工全周全天默认排班改造。 ## 已完成 -- 已核对 `scripts/sql/migrations/` 当前迁移文件清单,确认已有两份预约相关 SQL 带 `_生产已执行` 后缀。 -- 已核对项目变更记录、测试验收记录、轻量记忆和 git 历史,确认旧迁移没有“生产执行并验证通过”的记录。 -- 已补充 `docs/项目变更记录.md`,说明旧迁移中开发库执行或初始化 SQL 吸收不等同于迁移文件在生产执行,因此本次不追加 `_生产已执行` 后缀。 -- 已运行 `git diff --check` 和 GitNexus `detect_changes`,变更范围为文档与轻量记忆,风险为 low,影响流程 0。 -- 已创建 git 提交作为本次历史 SQL 执行状态复核标记。 +- 已读取项目规则、轻量记忆、SQL 迭代规则和错误记忆相关条目。 +- 已刷新 GitNexus 索引,并完成 `defaultRule`、`createUser`、`ensureWithinBusinessHours`、`resolveCapacity`、`buildAvailableTimeGroups` 的 upstream impact,风险均为 LOW。 +- 已落地本次改造设计文档。 +- 已实现后端员工默认全天排班、跨天门店营业校验和跨天员工容量校验。 +- 已实现店务 Web 与店务小程序跨天可约时间生成和提交前校验。 +- 已新增员工全周全天排班刷数迁移 SQL,并补充项目变更记录和交接状态。 +- 已完成后端全量测试、SQL 结构测试、店务 Web 单测/类型检查/构建、小程序 JS 语法检查、`git diff --check` 和 GitNexus staged 变更检测。 ## 下一步 -- 无。 +- 提交本次任务相关暂存文件,并提醒执行员工全周全天排班刷数 SQL。 ## 当前阻塞点 @@ -22,4 +24,4 @@ ## 最近一次重要操作结果 -2026-07-21 历史迁移执行状态复核完成并提交,未发现除两份预约迁移外可追加 `_生产已执行` 的 SQL 文件。 +2026-07-22 12:19 本次代码、SQL、文档和验证已收口;GitNexus staged 检测风险为 medium,主要来自 `UserServiceImpl` 附近权限同步流程索引关联。 diff --git a/scripts/sql/migrations/20260722-员工全周全天排班/员工全周全天排班刷数_20260722.sql b/scripts/sql/migrations/20260722-员工全周全天排班/员工全周全天排班刷数_20260722.sql new file mode 100644 index 00000000..2d7ceb3e --- /dev/null +++ b/scripts/sql/migrations/20260722-员工全周全天排班/员工全周全天排班刷数_20260722.sql @@ -0,0 +1,85 @@ +CREATE DATABASE IF NOT EXISTS jayu_cloud DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci; +USE jayu_cloud; + +DROP TEMPORARY TABLE IF EXISTS tmp_jy_artist_shop; + +CREATE TEMPORARY TABLE tmp_jy_artist_shop +( + artist_id bigint unsigned NOT NULL, + shop_id bigint unsigned NOT NULL, + PRIMARY KEY (artist_id, shop_id) +) ENGINE=Memory; + +INSERT INTO tmp_jy_artist_shop (artist_id, shop_id) +SELECT artist_id, shop_id +FROM ( + SELECT u.id AS artist_id, b.shop_id AS shop_id + FROM t_user u + JOIN t_user_shop_binding b ON b.user_id = u.id + WHERE u.type = 3 + AND IFNULL(u.is_delete, 0) = 0 + AND b.status = 1 + AND IFNULL(b.is_delete, 0) = 0 + AND b.shop_id > 0 + + UNION + + SELECT u.id AS artist_id, u.shop_id AS shop_id + FROM t_user u + WHERE u.type = 3 + AND IFNULL(u.is_delete, 0) = 0 + AND u.shop_id IS NOT NULL + AND u.shop_id > 0 +) artist_shop; + +UPDATE t_artist_schedule_rule r +JOIN tmp_jy_artist_shop a ON a.artist_id = r.artist_id AND a.shop_id = r.shop_id +SET r.preset_type = 'EVERYDAY', + r.work_days = '1,2,3,4,5,6,7', + r.start_time = '00:00:00', + r.end_time = '23:59:59', + r.slot_minutes = 60, + r.capacity = 1, + r.status = 1, + r.remark = '员工默认全周全天排班', + r.update_time = NOW() +WHERE IFNULL(r.is_delete, 0) = 0; + +INSERT INTO t_artist_schedule_rule ( + id, + shop_id, + artist_id, + preset_type, + work_days, + start_time, + end_time, + slot_minutes, + capacity, + status, + remark, + create_time, + update_time, + is_delete +) +SELECT UUID_SHORT() AS id, + a.shop_id, + a.artist_id, + 'EVERYDAY', + '1,2,3,4,5,6,7', + '00:00:00', + '23:59:59', + 60, + 1, + 1, + '员工默认全周全天排班', + NOW(), + NOW(), + 0 +FROM tmp_jy_artist_shop a +LEFT JOIN t_artist_schedule_rule r + ON r.shop_id = a.shop_id + AND r.artist_id = a.artist_id + AND IFNULL(r.is_delete, 0) = 0 +WHERE r.id IS NULL; + +DROP TEMPORARY TABLE IF EXISTS tmp_jy_artist_shop;