diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/analytics/service/impl/OperationsAnalyticsServiceImpl.java b/JC-Salon-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/analytics/service/impl/OperationsAnalyticsServiceImpl.java index d4b0036c..45aec5d6 100644 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/analytics/service/impl/OperationsAnalyticsServiceImpl.java +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/analytics/service/impl/OperationsAnalyticsServiceImpl.java @@ -53,7 +53,7 @@ public class OperationsAnalyticsServiceImpl implements OperationsAnalyticsServic vo.setCartCount(0L); vo.setOrderCount((long) orders.size()); vo.setPaidOrderCount(orders.stream().filter(order -> "PAID".equals(order.getPaymentStatus())).count()); - vo.setCompletedOrderCount(orders.stream().filter(order -> Integer.valueOf(2).equals(order.getStatus())).count()); + vo.setCompletedOrderCount(orders.stream().filter(order -> Integer.valueOf(2).equals(order.getStatus()) || Integer.valueOf(4).equals(order.getStatus())).count()); vo.setReviewCount(userGrowthRecordMapper.selectCount(new LambdaQueryWrapper() .eq(UserGrowthRecordDO::getSourceType, "REVIEW"))); vo.setRebookCount(userGrowthRecordMapper.selectCount(new LambdaQueryWrapper() diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/analytics/service/impl/WorkbenchServiceImpl.java b/JC-Salon-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/analytics/service/impl/WorkbenchServiceImpl.java index 1f0d5599..a8a62d1e 100644 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/analytics/service/impl/WorkbenchServiceImpl.java +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/analytics/service/impl/WorkbenchServiceImpl.java @@ -53,7 +53,7 @@ public class WorkbenchServiceImpl implements WorkbenchService { vo.setLowStockItemCount(countLowStock(shopId)); vo.setScheduleReminderCount(countMissingSchedules(shopId, artistId, todayStart.toLocalDate())); vo.setTodayServiceCount(countTodayServices(artistId, todayStart, tomorrowStart)); - vo.setCompletedServiceCount(orders.stream().filter(order -> Integer.valueOf(2).equals(order.getStatus())).count()); + vo.setCompletedServiceCount(orders.stream().filter(order -> Integer.valueOf(2).equals(order.getStatus()) || Integer.valueOf(4).equals(order.getStatus())).count()); vo.setServiceAmount(orders.stream() .map(order -> order.getActualAmount() == null ? BigDecimal.ZERO : order.getActualAmount()) .reduce(BigDecimal.ZERO, BigDecimal::add)); diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/manager/controller/admin/AdminManagerController.java b/JC-Salon-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/manager/controller/admin/AdminManagerController.java index 2229f502..d5dca64a 100644 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/manager/controller/admin/AdminManagerController.java +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/manager/controller/admin/AdminManagerController.java @@ -18,6 +18,7 @@ import com.xiaowang.jacyucloudsalon.core.modules.manager.dto.ManagerCustomerCrea import com.xiaowang.jacyucloudsalon.core.modules.planning.dto.PlanningAppointmentCreateDTO; import com.xiaowang.jacyucloudsalon.core.modules.planning.dto.PlanningAppointmentMoveDTO; import com.xiaowang.jacyucloudsalon.core.modules.planning.dto.PlanningAppointmentStatusDTO; +import com.xiaowang.jacyucloudsalon.core.modules.planning.dto.PlanningBackfillOrderCreateDTO; import com.xiaowang.jacyucloudsalon.core.modules.planning.service.PlanningService; import com.xiaowang.jacyucloudsalon.core.modules.planning.vo.PlanningAppointmentVO; import com.xiaowang.jacyucloudsalon.core.modules.planning.vo.PlanningCalendarVO; @@ -89,6 +90,15 @@ public class AdminManagerController { return Result.success(planningService.createAppointment(currentUser, dto)); } + @PostMapping("/planning/backfill-orders") + @RequirePermission("order:process") + @OperationGuard(action = "manager-planning-create-backfill-order", ttlSeconds = 10, message = "补单创建处理中,请勿重复提交") + public Result createBackfillOrder(HttpServletRequest request, + @RequestBody PlanningBackfillOrderCreateDTO dto) { + UserDO currentUser = adminScopeHelper.getCurrentUser(request); + return Result.success(planningService.createBackfillOrder(currentUser, dto)); + } + @GetMapping("/planning/appointments/{orderItemId}") @RequirePermission("order:view") public Result appointment(HttpServletRequest request, diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/order/entity/OrderDO.java b/JC-Salon-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/order/entity/OrderDO.java index 5942252a..1360fc69 100644 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/order/entity/OrderDO.java +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/order/entity/OrderDO.java @@ -54,7 +54,10 @@ public class OrderDO extends BaseEntity { private String paymentOrderNo; private String refundStatus; private String customerRemark; + private String customerNameSnapshot; + private String customerPhoneSnapshot; private String quoteStatus; + private String orderSource; private Integer quoteUserConfirmed; private Integer quoteShopConfirmed; private LocalDateTime quoteExpireTime; diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/order/entity/OrderItemDO.java b/JC-Salon-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/order/entity/OrderItemDO.java index 96cd8983..1c23588a 100644 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/order/entity/OrderItemDO.java +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/order/entity/OrderItemDO.java @@ -44,6 +44,7 @@ public class OrderItemDO extends BaseEntity { * Field `appointmentTime` (LocalDateTime): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. */ private LocalDateTime appointmentTime; + private java.time.LocalDate serviceDate; /** * Field `createTime` (LocalDateTime): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/order/service/impl/OrderServiceImpl.java b/JC-Salon-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/order/service/impl/OrderServiceImpl.java index d0f69fd2..f7c8571c 100644 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/order/service/impl/OrderServiceImpl.java +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/order/service/impl/OrderServiceImpl.java @@ -1519,7 +1519,7 @@ public class OrderServiceImpl implements OrderService { */ throw new RuntimeException("订单不存在"); } - if (status != 2 && status != 3) { + if (status != 2 && status != 3 && status != 4) { /** * Run business method `RuntimeException`. * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. @@ -1528,7 +1528,13 @@ public class OrderServiceImpl implements OrderService { throw new RuntimeException("无效的订单状态"); } OrderStatus targetStatus = OrderStatus.requireKnown(status); + if (status == OrderStatus.IN_SERVICE.getCode() + && !"HISTORICAL_BACKFILL".equals(order.getOrderSource())) { + throw new RuntimeException("普通预约不能进入服务中状态"); + } if (!Integer.valueOf(OrderStatus.PENDING_SERVICE.getCode()).equals(order.getStatus()) + && !(Integer.valueOf(OrderStatus.IN_SERVICE.getCode()).equals(order.getStatus()) + && (status == OrderStatus.COMPLETED.getCode() || status == OrderStatus.CANCELLED.getCode())) && !(Integer.valueOf(OrderStatus.PRICE_CONFIRMING.getCode()).equals(order.getStatus()) && Integer.valueOf(OrderStatus.CANCELLED.getCode()).equals(status))) { /** @@ -3278,6 +3284,9 @@ public class OrderServiceImpl implements OrderService { if (Integer.valueOf(3).equals(status)) { return "已取消"; } + if (Integer.valueOf(4).equals(status)) { + return "服务中"; + } return "未知状态"; } @@ -3327,6 +3336,7 @@ public class OrderServiceImpl implements OrderService { orderVO.setCustomerNickname(resolveCustomerNickname(customer)); orderVO.setCustomerPhoneMasked(maskPhone(customer == null ? null : customer.getPhone())); orderVO.setStatus(order.getStatus()); + orderVO.setOrderSource(order.getOrderSource()); switch (order.getStatus()) { case 0: @@ -3341,6 +3351,9 @@ public class OrderServiceImpl implements OrderService { case 3: orderVO.setStatusText("已取消"); break; + case 4: + orderVO.setStatusText("服务中"); + break; default: orderVO.setStatusText("未知状态"); } @@ -3395,6 +3408,8 @@ public class OrderServiceImpl implements OrderService { itemVO.setPrice(displayPrice); itemVO.setTotalPrice(displayPrice.multiply(BigDecimal.valueOf(item.getQuantity()))); itemVO.setAppointmentTime(formatAppointmentTime(item.getAppointmentTime())); + itemVO.setServiceDate(item.getServiceDate() == null ? null : item.getServiceDate().toString()); + itemVO.setHistoricalBackfill("HISTORICAL_BACKFILL".equals(order.getOrderSource())); String occupancyStatus = resolveOrderItemOccupancyStatus(order); itemVO.setOccupancyStatus(occupancyStatus); itemVO.setCanEdit(canEditOrderItem(order)); @@ -3453,6 +3468,9 @@ public class OrderServiceImpl implements OrderService { if (Integer.valueOf(OrderStatus.COMPLETED.getCode()).equals(order.getStatus())) { return "COMPLETED"; } + if (Integer.valueOf(OrderStatus.IN_SERVICE.getCode()).equals(order.getStatus())) { + return "HISTORICAL_BACKFILL"; + } return "UNKNOWN"; } diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/order/support/OrderStateMachine.java b/JC-Salon-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/order/support/OrderStateMachine.java index e754889c..74769225 100644 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/order/support/OrderStateMachine.java +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/order/support/OrderStateMachine.java @@ -19,7 +19,10 @@ public final class OrderStateMachine { if (from == OrderStatus.PRICE_CONFIRMING) { return to == OrderStatus.PENDING_SERVICE || to == OrderStatus.CANCELLED; } - return from == OrderStatus.PENDING_SERVICE + if (from == OrderStatus.PENDING_SERVICE) { + return to == OrderStatus.COMPLETED || to == OrderStatus.CANCELLED; + } + return from == OrderStatus.IN_SERVICE && (to == OrderStatus.COMPLETED || to == OrderStatus.CANCELLED); } diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/order/support/OrderStatus.java b/JC-Salon-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/order/support/OrderStatus.java index 2e1ada17..708fc6e4 100644 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/order/support/OrderStatus.java +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/order/support/OrderStatus.java @@ -10,7 +10,8 @@ public enum OrderStatus { PRICE_CONFIRMING(0), PENDING_SERVICE(1), COMPLETED(2), - CANCELLED(3); + CANCELLED(3), + IN_SERVICE(4); /** * Purpose: code supports OrderStatus.java by holding or executing the code business role. diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/order/vo/OrderItemVO.java b/JC-Salon-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/order/vo/OrderItemVO.java index 398f5cb0..3ee9c283 100644 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/order/vo/OrderItemVO.java +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/order/vo/OrderItemVO.java @@ -57,6 +57,8 @@ public class OrderItemVO { * Field `appointmentTime` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. */ private String appointmentTime; + private String serviceDate; + private Boolean historicalBackfill; private String occupancyStatus; private Boolean canEdit; private Boolean canCancel; diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/order/vo/OrderVO.java b/JC-Salon-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/order/vo/OrderVO.java index 927772c4..554fd187 100644 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/order/vo/OrderVO.java +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/order/vo/OrderVO.java @@ -66,6 +66,7 @@ public class OrderVO { private String refundStatus; private String customerRemark; private String quoteStatus; + private String orderSource; private String quoteStatusText; private Boolean quoteUserConfirmed; private Boolean quoteShopConfirmed; diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/planning/controller/admin/AdminPlanningController.java b/JC-Salon-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/planning/controller/admin/AdminPlanningController.java index bb38691b..214bda15 100644 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/planning/controller/admin/AdminPlanningController.java +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/planning/controller/admin/AdminPlanningController.java @@ -4,6 +4,7 @@ import com.xiaowang.jacyucloudsalon.core.annotation.OperationGuard; import com.xiaowang.jacyucloudsalon.core.annotation.RequirePermission; import com.xiaowang.jacyucloudsalon.core.common.Result; import com.xiaowang.jacyucloudsalon.core.modules.planning.dto.PlanningAppointmentCreateDTO; +import com.xiaowang.jacyucloudsalon.core.modules.planning.dto.PlanningBackfillOrderCreateDTO; import com.xiaowang.jacyucloudsalon.core.modules.planning.dto.PlanningAppointmentMoveDTO; import com.xiaowang.jacyucloudsalon.core.modules.planning.dto.PlanningAppointmentStatusDTO; import com.xiaowang.jacyucloudsalon.core.modules.user.entity.UserDO; @@ -53,6 +54,15 @@ public class AdminPlanningController { return Result.success(planningService.createAppointment(currentUser, dto)); } + @PostMapping("/backfill-orders") + @RequirePermission("order:process") + @OperationGuard(action = "admin-planning-create-backfill-order", ttlSeconds = 10, message = "补单创建处理中,请勿重复提交") + public Result createBackfillOrder(HttpServletRequest request, + @RequestBody PlanningBackfillOrderCreateDTO dto) { + UserDO currentUser = adminScopeHelper.getCurrentUser(request); + return Result.success(planningService.createBackfillOrder(currentUser, dto)); + } + @GetMapping("/appointments/{orderItemId}") @RequirePermission("order:view") public Result appointment(HttpServletRequest request, diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/planning/dto/PlanningBackfillOrderCreateDTO.java b/JC-Salon-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/planning/dto/PlanningBackfillOrderCreateDTO.java new file mode 100644 index 00000000..69c5c8ec --- /dev/null +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/planning/dto/PlanningBackfillOrderCreateDTO.java @@ -0,0 +1,21 @@ +package com.xiaowang.jacyucloudsalon.core.modules.planning.dto; + +import lombok.Data; + +import java.math.BigDecimal; + +@Data +public class PlanningBackfillOrderCreateDTO { + private Long productId; + private String manualProductTitle; + private BigDecimal manualProductPrice; + private Long customerUserId; + private String customerName; + private String phone; + private String serviceDate; + private String serviceTime; + private Long artistId; + private BigDecimal amount; + private Integer status; + private String remark; +} diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/planning/service/PlanningService.java b/JC-Salon-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/planning/service/PlanningService.java index b6548d8c..94dd5146 100644 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/planning/service/PlanningService.java +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/planning/service/PlanningService.java @@ -1,6 +1,7 @@ package com.xiaowang.jacyucloudsalon.core.modules.planning.service; import com.xiaowang.jacyucloudsalon.core.modules.planning.dto.PlanningAppointmentCreateDTO; +import com.xiaowang.jacyucloudsalon.core.modules.planning.dto.PlanningBackfillOrderCreateDTO; import com.xiaowang.jacyucloudsalon.core.modules.planning.dto.PlanningAppointmentMoveDTO; import com.xiaowang.jacyucloudsalon.core.modules.planning.dto.PlanningAppointmentStatusDTO; import com.xiaowang.jacyucloudsalon.core.modules.user.entity.UserDO; @@ -17,6 +18,8 @@ public interface PlanningService { PlanningAppointmentVO createAppointment(UserDO currentUser, PlanningAppointmentCreateDTO dto); + PlanningAppointmentVO createBackfillOrder(UserDO currentUser, PlanningBackfillOrderCreateDTO dto); + PlanningAppointmentVO getAppointment(UserDO currentUser, Long orderItemId); PlanningAppointmentVO moveAppointment(UserDO currentUser, Long orderItemId, PlanningAppointmentMoveDTO dto); diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/planning/service/impl/PlanningServiceImpl.java b/JC-Salon-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/planning/service/impl/PlanningServiceImpl.java index fd210d6a..879453b4 100644 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/planning/service/impl/PlanningServiceImpl.java +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/planning/service/impl/PlanningServiceImpl.java @@ -4,6 +4,7 @@ import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; import com.xiaowang.jacyucloudsalon.core.modules.planning.dto.PlanningAppointmentCreateDTO; import com.xiaowang.jacyucloudsalon.core.modules.planning.dto.PlanningAppointmentMoveDTO; import com.xiaowang.jacyucloudsalon.core.modules.planning.dto.PlanningAppointmentStatusDTO; +import com.xiaowang.jacyucloudsalon.core.modules.planning.dto.PlanningBackfillOrderCreateDTO; import com.xiaowang.jacyucloudsalon.core.modules.planning.entity.AppointmentReservationDO; import com.xiaowang.jacyucloudsalon.core.modules.artist.entity.ArtistScheduleDO; import com.xiaowang.jacyucloudsalon.core.modules.artist.entity.ArtistScheduleExceptionDO; @@ -67,6 +68,8 @@ public class PlanningServiceImpl implements PlanningService { private static final int MONTH_AVAILABLE_MINUTES = 90; private static final String RESERVATION_PENDING_QUOTE = "PENDING_QUOTE"; private static final String RESERVATION_CONFIRMED = "CONFIRMED"; + private static final String RESERVATION_UNASSIGNED = "UNASSIGNED"; + private static final String ASSIGNMENT_ASSIGNED = "ASSIGNED"; private static final String PRODUCT_SOURCE_TYPE_MANAGER_APPOINTMENT = "MANAGER_APPOINTMENT"; private static final String ENCODED_UNSET_PASSWORD = "$2a$10$EixZaYVK1fsbw1ZfbX3OXePaWxn96p36WQoeG6Lruj3vjPGga31lW"; private static final List ACTIVE_RESERVATION_STATUS = List.of("LOCKED", RESERVATION_PENDING_QUOTE, RESERVATION_CONFIRMED); @@ -169,7 +172,7 @@ public class PlanningServiceImpl implements PlanningService { Long shopId = requirePlanningShopId(currentUser); requireAppointmentDuration(dto.getDurationMinutes()); ProductDO product = resolveAppointmentProduct(dto, shopId); - UserDO artist = requireActiveArtist(dto.getArtistId(), shopId); + UserDO artist = dto.getArtistId() == null ? null : requireActiveArtist(dto.getArtistId(), shopId); UserDO customer = resolveCustomer(shopId, dto); int quantity = dto.getQuantity() == null || dto.getQuantity() <= 0 ? 1 : dto.getQuantity(); @@ -196,6 +199,7 @@ public class PlanningServiceImpl implements PlanningService { order.setPayAmount(amount); order.setPaidAmount(BigDecimal.ZERO); order.setStatus(OrderStatus.PENDING_SERVICE.getCode()); + order.setOrderSource("NORMAL_APPOINTMENT"); order.setIsDelete(0); orderMapper.insert(order); @@ -204,25 +208,77 @@ public class PlanningServiceImpl implements PlanningService { item.setProductId(product.getId()); item.setQuantity(quantity); item.setPrice(unitPrice); - item.setArtistId(artist.getId()); + item.setArtistId(artist == null ? null : artist.getId()); item.setAppointmentTime(startTime); item.setIsDelete(0); orderItemMapper.insert(item); - appointmentCapacityService.reserveConfirmedOrThrow( - order.getId(), - item.getId(), - shopId, - artist.getId(), - product.getTitle(), - startTime, - endTime, - trimToNull(dto.getClientRequestId()) - ); + if (artist != null) { + appointmentCapacityService.reserveConfirmedOrThrow( + order.getId(), + item.getId(), + shopId, + artist.getId(), + product.getTitle(), + startTime, + endTime, + trimToNull(dto.getClientRequestId()) + ); + } return getAppointment(currentUser, item.getId()); } + @Override + @Transactional + public PlanningAppointmentVO createBackfillOrder(UserDO currentUser, PlanningBackfillOrderCreateDTO dto) { + if (dto == null) throw new RuntimeException("补单信息不能为空"); + if (Integer.valueOf(3).equals(currentUser.getType())) throw new RuntimeException("美甲师账号不能创建补单"); + Long shopId = requirePlanningShopId(currentUser); + if (!hasText(dto.getServiceDate())) throw new RuntimeException("服务日期不能为空"); + LocalDate serviceDate; + try { serviceDate = LocalDate.parse(dto.getServiceDate()); } + catch (DateTimeParseException ex) { throw new RuntimeException("服务日期格式不正确"); } + UserDO artist = requireActiveArtist(dto.getArtistId(), shopId); + ProductDO product; + if (dto.getProductId() != null) product = requireActiveProduct(dto.getProductId(), shopId); + else { + String title = trimToNull(dto.getManualProductTitle()); + if (!hasText(title)) throw new RuntimeException("请选择项目或填写项目名称"); + BigDecimal price = dto.getManualProductPrice() == null ? dto.getAmount() : dto.getManualProductPrice(); + if (price == null || price.compareTo(BigDecimal.ZERO) < 0) throw new RuntimeException("项目金额不能小于0"); + product = new ProductDO(); product.setShopId(shopId); product.setTitle(title); product.setPrice(price); + product.setSourceType(PRODUCT_SOURCE_TYPE_MANAGER_APPOINTMENT); product.setFrontVisible(0); + product.setLikeCount(0); product.setCollectCount(0); product.setIsDelete(0); productMapper.insert(product); + } + if (dto.getAmount() == null || dto.getAmount().compareTo(BigDecimal.ZERO) < 0) throw new RuntimeException("金额不能为空且不能小于0"); + int status = dto.getStatus() == null ? OrderStatus.COMPLETED.getCode() : dto.getStatus(); + if (status != OrderStatus.IN_SERVICE.getCode() && status != OrderStatus.COMPLETED.getCode()) throw new RuntimeException("补单状态只能为服务中或已完成"); + UserDO customer = null; + if (dto.getCustomerUserId() != null) { + customer = userMapper.selectById(dto.getCustomerUserId()); + if (customer == null || Integer.valueOf(1).equals(customer.getIsDelete())) throw new RuntimeException("客户不存在"); + } + LocalDateTime appointmentTime = null; + if (hasText(dto.getServiceTime())) { + try { appointmentTime = LocalDateTime.of(serviceDate, LocalTime.parse(dto.getServiceTime())); } + catch (DateTimeParseException ex) { throw new RuntimeException("服务时间格式不正确"); } + } + OrderDO order = new OrderDO(); order.setOrderNo("ORD" + snowflakeIdGenerator.nextIdString()); + order.setUserId(customer == null ? null : customer.getId()); order.setShopId(shopId); + order.setTotalAmount(dto.getAmount()); order.setActualAmount(dto.getAmount()); order.setPayAmount(dto.getAmount()); + order.setPaidAmount(dto.getAmount()); order.setPaymentStatus("PAID"); order.setQuoteStatus("CONFIRMED"); + order.setQuoteUserConfirmed(1); order.setQuoteShopConfirmed(1); order.setQuoteConfirmedTime(LocalDateTime.now()); + order.setStatus(status); order.setOrderSource("HISTORICAL_BACKFILL"); order.setCustomerRemark(trimToNull(dto.getRemark())); + order.setCustomerNameSnapshot(trimToNull(dto.getCustomerName())); + order.setCustomerPhoneSnapshot(trimToNull(dto.getPhone())); + order.setIsDelete(0); orderMapper.insert(order); + OrderItemDO item = new OrderItemDO(); item.setOrderId(order.getId()); item.setProductId(product.getId()); + item.setQuantity(1); item.setPrice(dto.getAmount()); item.setArtistId(artist.getId()); item.setServiceDate(serviceDate); + item.setAppointmentTime(appointmentTime); item.setIsDelete(0); orderItemMapper.insert(item); + return getAppointment(currentUser, item.getId()); + } + @Override public PlanningAppointmentVO getAppointment(UserDO currentUser, Long orderItemId) { if (orderItemId == null) { @@ -237,7 +293,7 @@ public class PlanningServiceImpl implements PlanningService { AppointmentReservationDO reservation = findActiveReservation(orderItemId); Map artistMap = listArtists(order.getShopId(), item.getArtistId()).stream() .collect(Collectors.toMap(PlanningArtistVO::getId, Function.identity(), (a, b) -> a)); - Map customerMap = loadUsers(Set.of(order.getUserId())); + Map customerMap = order.getUserId() == null ? Map.of() : loadUsers(Set.of(order.getUserId())); return toAppointmentVO(reservation, item, order, product, customerMap.get(order.getUserId()), artistMap); } @@ -291,6 +347,9 @@ public class PlanningServiceImpl implements PlanningService { } OrderDO order = requireAccessibleOrder(currentUser, orderId); int targetStatus = dto.getStatus(); + if (targetStatus != OrderStatus.CANCELLED.getCode() && hasUnassignedOrderItem(orderId)) { + throw new RuntimeException("请先分配员工"); + } if (targetStatus == OrderStatus.PENDING_SERVICE.getCode()) { if (!Integer.valueOf(OrderStatus.PENDING_SERVICE.getCode()).equals(order.getStatus())) { orderMapper.updateStatusIfCurrent(order.getId(), order.getStatus(), OrderStatus.PENDING_SERVICE.getCode()); @@ -399,9 +458,9 @@ public class PlanningServiceImpl implements PlanningService { QueryWrapper itemWrapper = new QueryWrapper<>(); itemWrapper.eq("is_delete", 0) - .isNotNull("appointment_time") - .ge("appointment_time", rangeStart) - .lt("appointment_time", rangeEnd) + .and(wrapper -> wrapper + .and(q -> q.isNotNull("appointment_time").ge("appointment_time", rangeStart).lt("appointment_time", rangeEnd)) + .or(q -> q.isNotNull("service_date").ge("service_date", rangeStart.toLocalDate()).lt("service_date", rangeEnd.toLocalDate()))) .orderByAsc("appointment_time"); if (artistId != null && artistId > 0) { itemWrapper.eq("artist_id", artistId); @@ -501,24 +560,28 @@ public class PlanningServiceImpl implements PlanningService { vo.setOrderNo(order == null ? null : order.getOrderNo()); vo.setOrderItemId(item == null ? reservation == null ? null : reservation.getOrderItemId() : item.getId()); vo.setCustomerId(customer == null ? order == null ? null : order.getUserId() : customer.getId()); - vo.setCustomerName(customer == null ? "到店客户" : firstNonBlank(customer.getNickname(), customer.getAccount(), "到店客户")); - vo.setCustomerPhone(customer == null ? null : firstNonBlank(customer.getContactPhone(), customer.getPhone(), "")); + vo.setCustomerName(customer == null ? firstNonBlank(order == null ? null : order.getCustomerNameSnapshot(), "散客") : firstNonBlank(customer.getNickname(), customer.getAccount(), "到店客户")); + vo.setCustomerPhone(customer == null ? order == null ? null : order.getCustomerPhoneSnapshot() : firstNonBlank(customer.getContactPhone(), customer.getPhone(), "")); vo.setProductId(product == null ? item == null ? null : item.getProductId() : product.getId()); vo.setProductTitle(reservation != null && hasText(reservation.getProductTitle()) ? reservation.getProductTitle() : product == null ? "预约作品" : product.getTitle()); vo.setArtistId(artistId); - vo.setArtistName(artist == null ? "未分配" : artist.getName()); - vo.setArtistColor(artist == null ? ARTIST_COLORS.get(0) : artist.getColor()); - vo.setDate(start == null ? null : start.toLocalDate().toString()); + boolean unassigned = artistId == null; + vo.setArtistName(unassigned ? "待分配" : artist == null ? "美甲师" : artist.getName()); + vo.setArtistColor(unassigned ? "#D59A52" : artist == null ? "#7BA7C7" : artist.getColor()); + vo.setAssignmentStatus(unassigned ? RESERVATION_UNASSIGNED : ASSIGNMENT_ASSIGNED); + vo.setHistoricalBackfill(order != null && "HISTORICAL_BACKFILL".equals(order.getOrderSource())); + LocalDate serviceDate = item == null ? null : item.getServiceDate(); + vo.setDate(start == null ? serviceDate == null ? null : serviceDate.toString() : start.toLocalDate().toString()); vo.setStartTime(start == null ? null : DATE_TIME_FORMATTER.format(start)); vo.setEndTime(end == null ? null : DATE_TIME_FORMATTER.format(end)); vo.setStartMinute(start == null ? null : start.toLocalTime().toSecondOfDay() / 60); vo.setDurationMinutes(start == null || end == null ? durationMinutes : Math.toIntExact(Duration.between(start, end).toMinutes())); vo.setStatus(order == null ? null : order.getStatus()); vo.setStatusText(statusText(order == null ? null : order.getStatus())); - String occupancyStatus = resolveOccupancyStatus(reservation, order); - vo.setOccupancyStatus(occupancyStatus); + String occupancyStatus = unassigned ? RESERVATION_UNASSIGNED : resolveOccupancyStatus(reservation, order); + vo.setOccupancyStatus(Boolean.TRUE.equals(vo.getHistoricalBackfill()) ? "HISTORICAL_BACKFILL" : occupancyStatus); vo.setCanEdit(canEditAppointment(order, occupancyStatus)); vo.setCanCancel(canCancelAppointment(order, occupancyStatus)); vo.setConflictReason(resolveAppointmentConflictReason(occupancyStatus)); @@ -575,12 +638,16 @@ public class PlanningServiceImpl implements PlanningService { artistCounts.add(countVO); } int total = dayAppointments.size(); + int unassignedCount = Math.toIntExact(dayAppointments.stream() + .filter(appointment -> appointment.getArtistId() == null) + .count()); boolean hasWorkingSchedule = workingArtistCount > 0; boolean allFull = workingArtistCount > 0 && fullWorkingArtistCount == workingArtistCount; PlanningDaySummaryVO summary = new PlanningDaySummaryVO(); summary.setDate(date); summary.setTotalCount(total); + summary.setUnassignedCount(unassignedCount); summary.setArtistCounts(artistCounts); summary.setDayStatus(PlanningCalendarSupport.resolveDayStatus(total, hasWorkingSchedule, allFull)); summaries.add(summary); @@ -853,12 +920,18 @@ public class PlanningServiceImpl implements PlanningService { if (Integer.valueOf(OrderStatus.COMPLETED.getCode()).equals(status)) { return "已完成"; } + if (Integer.valueOf(OrderStatus.IN_SERVICE.getCode()).equals(status)) { + return "服务中"; + } if (Integer.valueOf(OrderStatus.CANCELLED.getCode()).equals(status)) { return "已取消"; } if (Integer.valueOf(OrderStatus.PRICE_CONFIRMING.getCode()).equals(status)) { return "待确认"; } + if (Integer.valueOf(OrderStatus.IN_SERVICE.getCode()).equals(status)) { + return "服务中"; + } return "未知"; } @@ -883,14 +956,20 @@ public class PlanningServiceImpl implements PlanningService { private Boolean canEditAppointment(OrderDO order, String occupancyStatus) { return order != null - && (RESERVATION_PENDING_QUOTE.equals(occupancyStatus) || RESERVATION_CONFIRMED.equals(occupancyStatus)) + && !"HISTORICAL_BACKFILL".equals(order.getOrderSource()) + && (RESERVATION_PENDING_QUOTE.equals(occupancyStatus) + || RESERVATION_CONFIRMED.equals(occupancyStatus) + || RESERVATION_UNASSIGNED.equals(occupancyStatus)) && !Integer.valueOf(OrderStatus.COMPLETED.getCode()).equals(order.getStatus()) && !Integer.valueOf(OrderStatus.CANCELLED.getCode()).equals(order.getStatus()); } private Boolean canCancelAppointment(OrderDO order, String occupancyStatus) { return order != null - && (RESERVATION_PENDING_QUOTE.equals(occupancyStatus) || RESERVATION_CONFIRMED.equals(occupancyStatus)) + && (!"HISTORICAL_BACKFILL".equals(order.getOrderSource()) || Integer.valueOf(OrderStatus.IN_SERVICE.getCode()).equals(order.getStatus())) + && (RESERVATION_PENDING_QUOTE.equals(occupancyStatus) + || RESERVATION_CONFIRMED.equals(occupancyStatus) + || RESERVATION_UNASSIGNED.equals(occupancyStatus)) && !Integer.valueOf(OrderStatus.COMPLETED.getCode()).equals(order.getStatus()) && !Integer.valueOf(OrderStatus.CANCELLED.getCode()).equals(order.getStatus()); } @@ -905,6 +984,15 @@ public class PlanningServiceImpl implements PlanningService { return null; } + private boolean hasUnassignedOrderItem(Long orderId) { + QueryWrapper wrapper = new QueryWrapper<>(); + wrapper.eq("order_id", orderId) + .eq("is_delete", 0) + .isNull("artist_id") + .last("LIMIT 1"); + return orderItemMapper.selectCount(wrapper) > 0; + } + private List safeList(List list) { return list == null ? List.of() : list; } diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/planning/vo/PlanningAppointmentVO.java b/JC-Salon-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/planning/vo/PlanningAppointmentVO.java index b9e2d708..a7d216cc 100644 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/planning/vo/PlanningAppointmentVO.java +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/planning/vo/PlanningAppointmentVO.java @@ -17,6 +17,8 @@ public class PlanningAppointmentVO { private Long artistId; private String artistName; private String artistColor; + private String assignmentStatus; + private Boolean historicalBackfill; private String date; private String startTime; private String endTime; diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/planning/vo/PlanningDaySummaryVO.java b/JC-Salon-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/planning/vo/PlanningDaySummaryVO.java index 2ea3d5f7..3502eaef 100644 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/planning/vo/PlanningDaySummaryVO.java +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/planning/vo/PlanningDaySummaryVO.java @@ -8,6 +8,7 @@ import java.util.List; public class PlanningDaySummaryVO { private String date; private Integer totalCount; + private Integer unassignedCount; private List artistCounts; private String dayStatus; } diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/registration/controller/AdminWorkbenchRegistrationController.java b/JC-Salon-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/registration/controller/AdminWorkbenchRegistrationController.java index f28b3584..88d74924 100644 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/registration/controller/AdminWorkbenchRegistrationController.java +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/registration/controller/AdminWorkbenchRegistrationController.java @@ -2,8 +2,9 @@ package com.xiaowang.jacyucloudsalon.core.modules.registration.controller; import com.xiaowang.jacyucloudsalon.core.common.Result; import com.xiaowang.jacyucloudsalon.core.modules.registration.dto.WorkbenchRegistrationRejectDTO; -import com.xiaowang.jacyucloudsalon.core.modules.registration.entity.WorkbenchRegistrationApplicationDO; import com.xiaowang.jacyucloudsalon.core.modules.registration.service.WorkbenchRegistrationService; +import com.xiaowang.jacyucloudsalon.core.modules.registration.vo.WorkbenchRegistrationReviewSummaryVO; +import com.xiaowang.jacyucloudsalon.core.modules.registration.vo.WorkbenchRegistrationReviewVO; import com.xiaowang.jacyucloudsalon.core.modules.user.entity.UserDO; import com.xiaowang.jacyucloudsalon.core.modules.user.mapper.UserMapper; import org.springframework.web.bind.annotation.GetMapping; @@ -28,12 +29,17 @@ public class AdminWorkbenchRegistrationController { } @GetMapping("/list") - public Result> list(HttpServletRequest request) { + public Result> list(HttpServletRequest request) { Long userId = requireUserId(request); UserDO user = userMapper.selectById(userId); return Result.success(registrationService.listForReviewer(userId, isPlatformAdmin(user))); } + @GetMapping("/summary") + public Result summary(HttpServletRequest request) { + return Result.success(registrationService.getReviewSummary(requireUserId(request))); + } + @PostMapping("/{id}/approve") public Result approve(HttpServletRequest request, @PathVariable Long id) { Long userId = requireUserId(request); diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/registration/mapper/WorkbenchRegistrationApplicationMapper.java b/JC-Salon-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/registration/mapper/WorkbenchRegistrationApplicationMapper.java index 565ce2fe..2484cca4 100644 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/registration/mapper/WorkbenchRegistrationApplicationMapper.java +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/registration/mapper/WorkbenchRegistrationApplicationMapper.java @@ -2,6 +2,11 @@ package com.xiaowang.jacyucloudsalon.core.modules.registration.mapper; import com.baomidou.mybatisplus.core.mapper.BaseMapper; import com.xiaowang.jacyucloudsalon.core.modules.registration.entity.WorkbenchRegistrationApplicationDO; +import org.apache.ibatis.annotations.Param; +import org.apache.ibatis.annotations.Select; public interface WorkbenchRegistrationApplicationMapper extends BaseMapper { + + @Select("SELECT * FROM t_workbench_registration_application WHERE id = #{id} AND is_delete = 0 FOR UPDATE") + WorkbenchRegistrationApplicationDO selectByIdForUpdate(@Param("id") Long id); } diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/registration/service/WorkbenchRegistrationService.java b/JC-Salon-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/registration/service/WorkbenchRegistrationService.java index 1779df78..b879bedd 100644 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/registration/service/WorkbenchRegistrationService.java +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/registration/service/WorkbenchRegistrationService.java @@ -1,7 +1,8 @@ package com.xiaowang.jacyucloudsalon.core.modules.registration.service; import com.xiaowang.jacyucloudsalon.core.modules.registration.dto.WorkbenchRegistrationRequestDTO; -import com.xiaowang.jacyucloudsalon.core.modules.registration.entity.WorkbenchRegistrationApplicationDO; +import com.xiaowang.jacyucloudsalon.core.modules.registration.vo.WorkbenchRegistrationReviewSummaryVO; +import com.xiaowang.jacyucloudsalon.core.modules.registration.vo.WorkbenchRegistrationReviewVO; import com.xiaowang.jacyucloudsalon.core.modules.registration.vo.WorkbenchRegistrationStatusVO; import java.util.List; @@ -10,7 +11,8 @@ public interface WorkbenchRegistrationService { WorkbenchRegistrationStatusVO register(WorkbenchRegistrationRequestDTO request); WorkbenchRegistrationStatusVO getStatus(Long userId); WorkbenchRegistrationStatusVO resubmit(WorkbenchRegistrationRequestDTO request); - List listForReviewer(Long reviewerId, boolean platformAdmin); + List listForReviewer(Long reviewerId, boolean platformAdmin); + WorkbenchRegistrationReviewSummaryVO getReviewSummary(Long reviewerId); boolean approve(Long reviewerId, boolean platformAdmin, Long applicationId); boolean reject(Long reviewerId, boolean platformAdmin, Long applicationId, String reason); } diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/registration/service/impl/WorkbenchRegistrationServiceImpl.java b/JC-Salon-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/registration/service/impl/WorkbenchRegistrationServiceImpl.java index 9aff03ff..204018fc 100644 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/registration/service/impl/WorkbenchRegistrationServiceImpl.java +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/registration/service/impl/WorkbenchRegistrationServiceImpl.java @@ -7,6 +7,8 @@ import com.xiaowang.jacyucloudsalon.core.modules.registration.entity.WorkbenchRe import com.xiaowang.jacyucloudsalon.core.modules.registration.entity.WorkbenchRegistrationStatus; import com.xiaowang.jacyucloudsalon.core.modules.registration.mapper.WorkbenchRegistrationApplicationMapper; import com.xiaowang.jacyucloudsalon.core.modules.registration.service.WorkbenchRegistrationService; +import com.xiaowang.jacyucloudsalon.core.modules.registration.vo.WorkbenchRegistrationReviewSummaryVO; +import com.xiaowang.jacyucloudsalon.core.modules.registration.vo.WorkbenchRegistrationReviewVO; import com.xiaowang.jacyucloudsalon.core.modules.registration.vo.WorkbenchRegistrationStatusVO; import com.xiaowang.jacyucloudsalon.core.modules.integration.service.WechatMiniAuthService; import com.xiaowang.jacyucloudsalon.core.modules.integration.dto.WechatMiniRegistrationTicket; @@ -18,13 +20,19 @@ import com.xiaowang.jacyucloudsalon.core.modules.shop.mapper.UserShopBindingMapp import com.xiaowang.jacyucloudsalon.core.modules.user.entity.UserDO; import com.xiaowang.jacyucloudsalon.core.modules.user.mapper.UserMapper; import com.xiaowang.jacyucloudsalon.core.modules.user.service.UserService; +import com.xiaowang.jacyucloudsalon.core.modules.system.service.SystemParameterConfigService; +import org.springframework.beans.BeanUtils; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import org.springframework.util.StringUtils; import java.time.LocalDateTime; import java.util.List; +import java.util.Map; +import java.util.Objects; import java.util.UUID; +import java.util.function.Function; +import java.util.stream.Collectors; @Service public class WorkbenchRegistrationServiceImpl implements WorkbenchRegistrationService { @@ -35,6 +43,7 @@ public class WorkbenchRegistrationServiceImpl implements WorkbenchRegistrationSe private final UserShopBindingSupport userShopBindingSupport; private final UserShopBindingMapper userShopBindingMapper; private final WechatMiniAuthService wechatMiniAuthService; + private final SystemParameterConfigService systemParameterConfigService; public WorkbenchRegistrationServiceImpl( WorkbenchRegistrationApplicationMapper applicationMapper, @@ -43,7 +52,8 @@ public class WorkbenchRegistrationServiceImpl implements WorkbenchRegistrationSe UserService userService, UserShopBindingSupport userShopBindingSupport, UserShopBindingMapper userShopBindingMapper, - WechatMiniAuthService wechatMiniAuthService + WechatMiniAuthService wechatMiniAuthService, + SystemParameterConfigService systemParameterConfigService ) { this.applicationMapper = applicationMapper; this.userMapper = userMapper; @@ -52,6 +62,7 @@ public class WorkbenchRegistrationServiceImpl implements WorkbenchRegistrationSe this.userShopBindingSupport = userShopBindingSupport; this.userShopBindingMapper = userShopBindingMapper; this.wechatMiniAuthService = wechatMiniAuthService; + this.systemParameterConfigService = systemParameterConfigService; } @Override @@ -158,13 +169,38 @@ public class WorkbenchRegistrationServiceImpl implements WorkbenchRegistrationSe } @Override - public List listForReviewer(Long reviewerId, boolean platformAdmin) { + public List listForReviewer(Long reviewerId, boolean platformAdmin) { + List applications; if (platformAdmin) { - return applicationMapper.selectList(Wrappers.lambdaQuery(WorkbenchRegistrationApplicationDO.class).eq(WorkbenchRegistrationApplicationDO::getStatus, WorkbenchRegistrationStatus.PENDING_ADMIN).eq(WorkbenchRegistrationApplicationDO::getIsDelete, 0).orderByAsc(WorkbenchRegistrationApplicationDO::getCreateTime)); + applications = applicationMapper.selectList(Wrappers.lambdaQuery(WorkbenchRegistrationApplicationDO.class).eq(WorkbenchRegistrationApplicationDO::getStatus, WorkbenchRegistrationStatus.PENDING_ADMIN).eq(WorkbenchRegistrationApplicationDO::getIsDelete, 0).orderByAsc(WorkbenchRegistrationApplicationDO::getCreateTime)); + } else { + UserDO reviewer = requireManager(reviewerId); + applications = applicationMapper.selectList(Wrappers.lambdaQuery(WorkbenchRegistrationApplicationDO.class).eq(WorkbenchRegistrationApplicationDO::getStatus, WorkbenchRegistrationStatus.PENDING_MANAGER).eq(WorkbenchRegistrationApplicationDO::getShopId, reviewer.getShopId()).eq(WorkbenchRegistrationApplicationDO::getIsDelete, 0).orderByAsc(WorkbenchRegistrationApplicationDO::getCreateTime)); } - UserDO reviewer = userMapper.selectById(reviewerId); - require(reviewer != null && Integer.valueOf(2).equals(reviewer.getType()), "仅店长可以审核店员申请"); - return applicationMapper.selectList(Wrappers.lambdaQuery(WorkbenchRegistrationApplicationDO.class).eq(WorkbenchRegistrationApplicationDO::getStatus, WorkbenchRegistrationStatus.PENDING_MANAGER).eq(WorkbenchRegistrationApplicationDO::getShopId, reviewer.getShopId()).eq(WorkbenchRegistrationApplicationDO::getIsDelete, 0).orderByAsc(WorkbenchRegistrationApplicationDO::getCreateTime)); + List applicantIds = applications.stream() + .map(WorkbenchRegistrationApplicationDO::getUserId) + .filter(Objects::nonNull) + .distinct() + .collect(Collectors.toList()); + Map applicants = applicantIds.isEmpty() + ? Map.of() + : userMapper.selectBatchIds(applicantIds).stream() + .collect(Collectors.toMap(UserDO::getId, Function.identity())); + return applications.stream() + .map(application -> toReviewVO(application, applicants.get(application.getUserId()))) + .collect(Collectors.toList()); + } + + @Override + public WorkbenchRegistrationReviewSummaryVO getReviewSummary(Long reviewerId) { + UserDO reviewer = requireManager(reviewerId); + Long pendingCount = applicationMapper.selectCount(Wrappers.lambdaQuery(WorkbenchRegistrationApplicationDO.class) + .eq(WorkbenchRegistrationApplicationDO::getStatus, WorkbenchRegistrationStatus.PENDING_MANAGER) + .eq(WorkbenchRegistrationApplicationDO::getShopId, reviewer.getShopId()) + .eq(WorkbenchRegistrationApplicationDO::getIsDelete, 0)); + boolean noticeEnabled = "true".equalsIgnoreCase(systemParameterConfigService.getEnabledValue( + "WORKBENCH", "MANAGER_REGISTRATION_REVIEW_NOTICE")); + return new WorkbenchRegistrationReviewSummaryVO(pendingCount == null ? 0L : pendingCount, noticeEnabled); } @Override @@ -204,14 +240,16 @@ public class WorkbenchRegistrationServiceImpl implements WorkbenchRegistrationSe } private WorkbenchRegistrationApplicationDO loadReviewable(Long reviewerId, boolean platformAdmin, Long applicationId) { - WorkbenchRegistrationApplicationDO application = applicationMapper.selectById(applicationId); - require(application != null && WorkbenchRegistrationStatus.REJECTED.equals(application.getStatus()) == false, "审核申请不存在或已处理"); + WorkbenchRegistrationApplicationDO application = applicationMapper.selectByIdForUpdate(applicationId); + require(application != null, "审核申请不存在或已处理"); if (platformAdmin) { require(WorkbenchRegistrationStatus.PENDING_ADMIN.equals(application.getStatus()), "管理员只能审核店长申请"); + require(WorkbenchRegistrationRole.MANAGER.equals(application.getRoleType()), "管理员只能审核店长申请"); } else { - UserDO reviewer = userMapper.selectById(reviewerId); - require(reviewer != null && Integer.valueOf(2).equals(reviewer.getType()) && reviewer.getShopId().equals(application.getShopId()), "无权审核该店铺申请"); + UserDO reviewer = requireManager(reviewerId); + require(Objects.equals(reviewer.getShopId(), application.getShopId()), "无权审核该店铺申请"); require(WorkbenchRegistrationStatus.PENDING_MANAGER.equals(application.getStatus()), "店长只能审核店员申请"); + require(WorkbenchRegistrationRole.STAFF.equals(application.getRoleType()), "店长只能审核店员申请"); } return application; } @@ -224,6 +262,31 @@ public class WorkbenchRegistrationServiceImpl implements WorkbenchRegistrationSe return new WorkbenchRegistrationStatusVO(application.getId(), application.getApplicationNo(), application.getRoleType(), application.getStatus(), application.getRejectReason(), application.getShopId(), application.getShopName()); } + private WorkbenchRegistrationReviewVO toReviewVO(WorkbenchRegistrationApplicationDO application, UserDO applicant) { + WorkbenchRegistrationReviewVO review = new WorkbenchRegistrationReviewVO(); + BeanUtils.copyProperties(application, review); + if (applicant != null) { + review.setApplicantNickname(applicant.getNickname()); + review.setApplicantAvatar(applicant.getAvatar()); + review.setApplicantMaskedPhone(maskPhone(applicant.getPhone())); + } + return review; + } + + private UserDO requireManager(Long reviewerId) { + UserDO reviewer = userMapper.selectById(reviewerId); + require(reviewer != null && Integer.valueOf(2).equals(reviewer.getType()) && reviewer.getShopId() != null, + "仅店长可以审核店员申请"); + return reviewer; + } + + private String maskPhone(String phone) { + if (!StringUtils.hasText(phone) || phone.length() < 7) { + return ""; + } + return phone.substring(0, 3) + "****" + phone.substring(phone.length() - 4); + } + private String requireText(String value, String message) { require(StringUtils.hasText(value), message); return value.trim(); diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/registration/vo/WorkbenchRegistrationReviewSummaryVO.java b/JC-Salon-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/registration/vo/WorkbenchRegistrationReviewSummaryVO.java new file mode 100644 index 00000000..0d85a5f4 --- /dev/null +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/registration/vo/WorkbenchRegistrationReviewSummaryVO.java @@ -0,0 +1,11 @@ +package com.xiaowang.jacyucloudsalon.core.modules.registration.vo; + +import lombok.AllArgsConstructor; +import lombok.Getter; + +@Getter +@AllArgsConstructor +public class WorkbenchRegistrationReviewSummaryVO { + private final long pendingCount; + private final boolean noticeEnabled; +} diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/registration/vo/WorkbenchRegistrationReviewVO.java b/JC-Salon-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/registration/vo/WorkbenchRegistrationReviewVO.java new file mode 100644 index 00000000..c58dd35b --- /dev/null +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jacyucloudsalon/core/modules/registration/vo/WorkbenchRegistrationReviewVO.java @@ -0,0 +1,27 @@ +package com.xiaowang.jacyucloudsalon.core.modules.registration.vo; + +import lombok.Getter; +import lombok.Setter; + +import java.time.LocalDateTime; + +@Getter +@Setter +public class WorkbenchRegistrationReviewVO { + private Long id; + private String applicationNo; + private Long userId; + private String roleType; + private Long shopId; + private String shopName; + private String shopAddress; + private String status; + private Long reviewerId; + private LocalDateTime reviewedAt; + private String rejectReason; + private LocalDateTime createTime; + private LocalDateTime updateTime; + private String applicantNickname; + private String applicantAvatar; + private String applicantMaskedPhone; +} diff --git a/JC-Salon-Core/src/test/java/com/xiaowang/jacyucloudsalon/core/modules/planning/service/impl/PlanningServiceImplTest.java b/JC-Salon-Core/src/test/java/com/xiaowang/jacyucloudsalon/core/modules/planning/service/impl/PlanningServiceImplTest.java new file mode 100644 index 00000000..cef2a25b --- /dev/null +++ b/JC-Salon-Core/src/test/java/com/xiaowang/jacyucloudsalon/core/modules/planning/service/impl/PlanningServiceImplTest.java @@ -0,0 +1,153 @@ +package com.xiaowang.jacyucloudsalon.core.modules.planning.service.impl; + +import com.baomidou.mybatisplus.core.conditions.Wrapper; +import com.xiaowang.jacyucloudsalon.core.modules.artist.mapper.ArtistScheduleExceptionMapper; +import com.xiaowang.jacyucloudsalon.core.modules.artist.mapper.ArtistScheduleMapper; +import com.xiaowang.jacyucloudsalon.core.modules.artist.mapper.NailArtistInfoMapper; +import com.xiaowang.jacyucloudsalon.core.modules.order.entity.OrderDO; +import com.xiaowang.jacyucloudsalon.core.modules.order.entity.OrderItemDO; +import com.xiaowang.jacyucloudsalon.core.modules.order.mapper.OrderItemMapper; +import com.xiaowang.jacyucloudsalon.core.modules.order.mapper.OrderMapper; +import com.xiaowang.jacyucloudsalon.core.modules.order.service.OrderService; +import com.xiaowang.jacyucloudsalon.core.modules.order.support.OrderStatus; +import com.xiaowang.jacyucloudsalon.core.modules.planning.dto.PlanningAppointmentStatusDTO; +import com.xiaowang.jacyucloudsalon.core.modules.planning.dto.PlanningAppointmentCreateDTO; +import com.xiaowang.jacyucloudsalon.core.modules.planning.mapper.AppointmentReservationMapper; +import com.xiaowang.jacyucloudsalon.core.modules.planning.service.AppointmentCapacityService; +import com.xiaowang.jacyucloudsalon.core.modules.product.mapper.ProductMapper; +import com.xiaowang.jacyucloudsalon.core.modules.product.entity.ProductDO; +import com.xiaowang.jacyucloudsalon.core.modules.security.support.AdminScopeHelper; +import com.xiaowang.jacyucloudsalon.core.modules.shop.mapper.ShopMapper; +import com.xiaowang.jacyucloudsalon.core.modules.shop.entity.ShopDO; +import com.xiaowang.jacyucloudsalon.core.modules.user.entity.UserDO; +import com.xiaowang.jacyucloudsalon.core.modules.user.mapper.UserMapper; +import com.xiaowang.jacyucloudsalon.core.support.id.TimeOrderedSnowflakeIdGenerator; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.Mock; +import org.mockito.ArgumentCaptor; +import org.mockito.junit.jupiter.MockitoExtension; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.doAnswer; +import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.spy; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +@ExtendWith(MockitoExtension.class) +class PlanningServiceImplTest { + + @Mock private AdminScopeHelper adminScopeHelper; + @Mock private UserMapper userMapper; + @Mock private NailArtistInfoMapper nailArtistInfoMapper; + @Mock private ArtistScheduleMapper artistScheduleMapper; + @Mock private ArtistScheduleExceptionMapper artistScheduleExceptionMapper; + @Mock private AppointmentReservationMapper appointmentReservationMapper; + @Mock private OrderMapper orderMapper; + @Mock private OrderItemMapper orderItemMapper; + @Mock private ProductMapper productMapper; + @Mock private ShopMapper shopMapper; + @Mock private AppointmentCapacityService appointmentCapacityService; + @Mock private OrderService orderService; + @Mock private TimeOrderedSnowflakeIdGenerator snowflakeIdGenerator; + + private PlanningServiceImpl service; + + @BeforeEach + void setUp() { + service = new PlanningServiceImpl(adminScopeHelper, userMapper, nailArtistInfoMapper, artistScheduleMapper, + artistScheduleExceptionMapper, appointmentReservationMapper, orderMapper, orderItemMapper, + productMapper, shopMapper, appointmentCapacityService, orderService, snowflakeIdGenerator); + } + + @Test + void rejectsCompletingUnassignedAppointment() { + UserDO operator = new UserDO(); + OrderDO order = order(11L, OrderStatus.PENDING_SERVICE.getCode()); + when(orderMapper.selectById(11L)).thenReturn(order); + when(orderItemMapper.selectCount(any(Wrapper.class))).thenReturn(1L); + PlanningAppointmentStatusDTO dto = new PlanningAppointmentStatusDTO(); + dto.setStatus(OrderStatus.COMPLETED.getCode()); + + RuntimeException error = assertThrows(RuntimeException.class, () -> service.updateStatus(operator, 11L, dto)); + + assertEquals("请先分配员工", error.getMessage()); + verify(orderService, never()).processOrder(11L, OrderStatus.COMPLETED.getCode()); + } + + @Test + void allowsCancellingUnassignedAppointment() { + UserDO operator = new UserDO(); + OrderDO order = order(12L, OrderStatus.PENDING_SERVICE.getCode()); + when(orderMapper.selectById(12L)).thenReturn(order); + PlanningAppointmentStatusDTO dto = new PlanningAppointmentStatusDTO(); + dto.setStatus(OrderStatus.CANCELLED.getCode()); + + service.updateStatus(operator, 12L, dto); + + verify(orderService).processOrder(12L, OrderStatus.CANCELLED.getCode()); + } + + @Test + void createsUnassignedAppointmentWithoutReservation() { + service = spy(service); + UserDO operator = new UserDO(); + operator.setType(2); + UserDO customer = new UserDO(); + customer.setId(31L); + ProductDO product = new ProductDO(); + product.setId(41L); + product.setShopId(21L); + product.setTitle("纯色美甲"); + product.setPrice(java.math.BigDecimal.valueOf(99)); + product.setIsDelete(0); + ShopDO shop = new ShopDO(); + shop.setId(21L); + shop.setBusinessHours("10:00-22:00"); + when(adminScopeHelper.resolveShopScope(operator, null)).thenReturn(21L); + when(productMapper.selectById(41L)).thenReturn(product); + when(userMapper.selectById(31L)).thenReturn(customer); + when(shopMapper.selectById(21L)).thenReturn(shop); + when(snowflakeIdGenerator.nextIdString()).thenReturn("10001"); + doAnswer(invocation -> { + OrderDO value = invocation.getArgument(0); + value.setId(51L); + return 1; + }).when(orderMapper).insert(any(OrderDO.class)); + doAnswer(invocation -> { + OrderItemDO value = invocation.getArgument(0); + value.setId(61L); + return 1; + }).when(orderItemMapper).insert(any(OrderItemDO.class)); + doReturn(new com.xiaowang.jacyucloudsalon.core.modules.planning.vo.PlanningAppointmentVO()) + .when(service).getAppointment(operator, 61L); + PlanningAppointmentCreateDTO dto = new PlanningAppointmentCreateDTO(); + dto.setCustomerUserId(31L); + dto.setProductId(41L); + dto.setAppointmentDate("2026-10-13"); + dto.setAppointmentTime("14:00"); + dto.setDurationMinutes(60); + + service.createAppointment(operator, dto); + + ArgumentCaptor itemCaptor = ArgumentCaptor.forClass(OrderItemDO.class); + verify(orderItemMapper).insert(itemCaptor.capture()); + assertEquals(null, itemCaptor.getValue().getArtistId()); + verify(appointmentCapacityService, never()).reserveConfirmedOrThrow( + any(), any(), any(), any(), any(), any(), any(), any()); + } + + private OrderDO order(Long id, int status) { + OrderDO order = new OrderDO(); + order.setId(id); + order.setShopId(21L); + order.setStatus(status); + order.setIsDelete(0); + return order; + } +} diff --git a/JC-Salon-Core/src/test/java/com/xiaowang/jacyucloudsalon/core/modules/registration/controller/WorkbenchRegistrationControllerMappingTest.java b/JC-Salon-Core/src/test/java/com/xiaowang/jacyucloudsalon/core/modules/registration/controller/WorkbenchRegistrationControllerMappingTest.java index 23be5eef..9938e2d3 100644 --- a/JC-Salon-Core/src/test/java/com/xiaowang/jacyucloudsalon/core/modules/registration/controller/WorkbenchRegistrationControllerMappingTest.java +++ b/JC-Salon-Core/src/test/java/com/xiaowang/jacyucloudsalon/core/modules/registration/controller/WorkbenchRegistrationControllerMappingTest.java @@ -27,5 +27,10 @@ class WorkbenchRegistrationControllerMappingTest { GetMapping listMapping = listMethod.getAnnotation(GetMapping.class); assertNotNull(listMapping); assertEquals("/list", Arrays.stream(listMapping.value()).findFirst().orElse("")); + + Method summaryMethod = AdminWorkbenchRegistrationController.class.getMethod("summary", javax.servlet.http.HttpServletRequest.class); + GetMapping summaryMapping = summaryMethod.getAnnotation(GetMapping.class); + assertNotNull(summaryMapping); + assertEquals("/summary", Arrays.stream(summaryMapping.value()).findFirst().orElse("")); } } diff --git a/JC-Salon-Frontend/src/api/admin.ts b/JC-Salon-Frontend/src/api/admin.ts index d4240b76..90a90a39 100644 --- a/JC-Salon-Frontend/src/api/admin.ts +++ b/JC-Salon-Frontend/src/api/admin.ts @@ -1983,6 +1983,10 @@ export interface WorkbenchRegistrationApplication { status: 'PENDING_ADMIN' | 'PENDING_MANAGER' | 'APPROVED' | 'REJECTED' rejectReason?: string createTime?: string + updateTime?: string + applicantNickname?: string + applicantAvatar?: string + applicantMaskedPhone?: string } export const adminWorkbenchRegistrationApi = { diff --git a/JC-Salon-Frontend/src/views/OrderDetailView.vue b/JC-Salon-Frontend/src/views/OrderDetailView.vue index 1367717a..2728927e 100644 --- a/JC-Salon-Frontend/src/views/OrderDetailView.vue +++ b/JC-Salon-Frontend/src/views/OrderDetailView.vue @@ -34,7 +34,7 @@ const formatMoney = (value?: number | string) => { const formatDateTime = (value?: string) => value ? String(value).replace('T', ' ').slice(0, 16) : '--' const isQuoteStatus = (status?: unknown) => Number(status) === 0 const isQuoteConfirming = computed(() => isQuoteStatus(order.value?.status)) -const statusClass = (status?: number) => isQuoteStatus(status) ? 'quote' : status === 2 ? 'done' : status === 3 ? 'cancelled' : 'pending' +const statusClass = (status?: number) => isQuoteStatus(status) ? 'quote' : status === 2 ? 'done' : status === 3 ? 'cancelled' : status === 4 ? 'in-service' : 'pending' const isOrderPaid = (target: any) => String(target?.paymentStatus || '').toUpperCase() === 'PAID' const canPreparePayment = computed(() => !isQuoteConfirming.value && Number(order.value?.status) === 1 && !isOrderPaid(order.value)) const canMockPay = computed(() => !isQuoteConfirming.value && Number(order.value?.status) === 1 && String(order.value?.paymentStatus || '').toUpperCase() === 'PAYING') diff --git a/JC-Salon-Frontend/src/views/ServiceProgressView.vue b/JC-Salon-Frontend/src/views/ServiceProgressView.vue index e894389d..d8d6e99d 100644 --- a/JC-Salon-Frontend/src/views/ServiceProgressView.vue +++ b/JC-Salon-Frontend/src/views/ServiceProgressView.vue @@ -31,7 +31,7 @@ const nodes = computed(() => { { key: 'created', title: '订单创建', desc: formatTime(current.createTime), done: true, active: false }, { key: 'appointment', title: '预约确认', desc: formatTime(firstAppointment.value), done: Boolean(firstAppointment.value), active: status === 1 }, { key: 'artist', title: '服务安排', desc: latestChangeText.value, done: changes.value.length > 0 || items.value.some((item: any) => item.artistName), active: changes.value.some(item => item.status === 'PENDING') }, - { key: 'service', title: status === 3 ? '订单取消' : '服务完成', desc: formatTime(current.completeTime || current.cancelTime || current.updateTime), done: status === 2 || status === 3, active: status === 2 || status === 3 }, + { key: 'service', title: status === 3 ? '订单取消' : status === 4 ? '服务中' : '服务完成', desc: formatTime(current.completeTime || current.cancelTime || current.updateTime), done: status === 2 || status === 3, active: status === 2 || status === 3 || status === 4 }, { key: 'after-sale', title: '售后/评价', desc: afterSales.value.length ? `${afterSales.value.length} 条售后` : (reviews.value.length ? `${reviews.value.length} 条评价` : '暂无记录'), done: afterSales.value.length > 0 || reviews.value.length > 0, active: afterSales.value.some(item => item.status === 'PENDING') || reviews.value.some(item => !item.rating) } ] }) diff --git a/JC-Salon-Frontend/src/views/admin/OrdersView.vue b/JC-Salon-Frontend/src/views/admin/OrdersView.vue index b510ea02..d678ce27 100644 --- a/JC-Salon-Frontend/src/views/admin/OrdersView.vue +++ b/JC-Salon-Frontend/src/views/admin/OrdersView.vue @@ -108,6 +108,22 @@ > 取消订单 + + 完成补单 + + + 取消补单 + @@ -175,6 +191,8 @@ > 取消 + 完成补单 + 取消补单 @@ -195,6 +213,7 @@ {{ formatMoney(currentOrder.actualAmount) }} {{ currentOrder.couponName || '无' }} {{ orderStatusText(currentOrder) }} + {{ currentOrder.orderSource === 'HISTORICAL_BACKFILL' ? '历史补单' : '正常订单' }} {{ currentOrder.createTime }} @@ -496,7 +515,8 @@ const statusOptions = [ { label: '待报价', value: '0' }, { label: '待完成', value: '1' }, { label: '已完成', value: '2' }, - { label: '已取消', value: '3' } + { label: '已取消', value: '3' }, + { label: '服务中', value: '4' } ] const activeFilterCount = computed(() => [ @@ -623,6 +643,7 @@ const statusColor = (status: number) => { if (normalized === 1) return 'orange' if (normalized === 2) return 'green' if (normalized === 3) return 'red' + if (normalized === 4) return 'processing' return 'default' } diff --git a/JC-Salon-Frontend/src/views/admin/SystemSettingsView.vue b/JC-Salon-Frontend/src/views/admin/SystemSettingsView.vue index e0aebab3..51efcef9 100644 --- a/JC-Salon-Frontend/src/views/admin/SystemSettingsView.vue +++ b/JC-Salon-Frontend/src/views/admin/SystemSettingsView.vue @@ -27,6 +27,20 @@ 保存默认密码 + + + + + + + 保存审核提醒设置 + + @@ -38,7 +52,9 @@ import { adminSystemParameterConfigApi, type SystemParameterConfigVO } from '@/a const loading = ref(false) const saving = ref(false) const savingSmsProvider = ref(false) +const savingReviewNotice = ref(false) const enabled = ref(true) +const reviewNoticeEnabled = ref(true) const form = reactive({ configGroup: 'USER', configKey: 'DEFAULT_PASSWORD', @@ -55,13 +71,22 @@ const smsProviderForm = reactive({ configGroup: 'SMS', configKey: 'SMS_PROVIDER', configName: '短信供应商', configValue: 'SPUG', enabled: 1, remark: '全局切换短信供应商时同步验证码模板和 MessageHub 通道' }) +const reviewNoticeForm = reactive({ + configGroup: 'WORKBENCH', + configKey: 'MANAGER_REGISTRATION_REVIEW_NOTICE', + configName: '店长员工审核提醒', + configValue: 'true', + enabled: 1, + remark: '控制店长登录小程序后是否显式提示当前门店的待审核员工申请' +}) const load = async () => { loading.value = true try { - const [configs, smsConfigs] = await Promise.all([ + const [configs, smsConfigs, workbenchConfigs] = await Promise.all([ adminSystemParameterConfigApi.listConfigs('USER'), - adminSystemParameterConfigApi.listConfigs('SMS') + adminSystemParameterConfigApi.listConfigs('SMS'), + adminSystemParameterConfigApi.listConfigs('WORKBENCH') ]) const config = configs.find(item => item.configKey === 'DEFAULT_PASSWORD') if (config) { @@ -70,6 +95,11 @@ const load = async () => { } const smsProvider = smsConfigs.find(item => item.configKey === 'SMS_PROVIDER') if (smsProvider) Object.assign(smsProviderForm, smsProvider) + const reviewNotice = workbenchConfigs.find(item => item.configKey === 'MANAGER_REGISTRATION_REVIEW_NOTICE') + if (reviewNotice) { + Object.assign(reviewNoticeForm, reviewNotice) + reviewNoticeEnabled.value = reviewNotice.enabled === 1 && String(reviewNotice.configValue).toLowerCase() === 'true' + } } catch (error) { message.error(error instanceof Error ? error.message : '默认密码加载失败') } finally { @@ -113,6 +143,23 @@ const save = async () => { } } +const saveReviewNotice = async () => { + savingReviewNotice.value = true + try { + await adminSystemParameterConfigApi.saveConfig({ + ...reviewNoticeForm, + configValue: 'true', + enabled: reviewNoticeEnabled.value ? 1 : 0 + }) + message.success(reviewNoticeEnabled.value ? '店长员工审核提醒已开启' : '店长员工审核提醒已关闭') + await load() + } catch (error) { + message.error(error instanceof Error ? error.message : '审核提醒设置保存失败') + } finally { + savingReviewNotice.value = false + } +} + onMounted(() => { void load() }) diff --git a/JC-Salon-WeChat/api/employees.js b/JC-Salon-WeChat/api/employees.js index 9f3f02b4..6e86502b 100644 --- a/JC-Salon-WeChat/api/employees.js +++ b/JC-Salon-WeChat/api/employees.js @@ -66,5 +66,32 @@ module.exports = { method: 'POST', data }) + }, + + reviewSummary() { + return request({ + url: '/user/workbench/registration/summary' + }) + }, + + reviewApplications() { + return request({ + url: '/user/workbench/registration/list' + }) + }, + + approveApplication(id) { + return request({ + url: `/user/workbench/registration/${id}/approve`, + method: 'POST' + }) + }, + + rejectApplication(id, reason) { + return request({ + url: `/user/workbench/registration/${id}/reject`, + method: 'POST', + data: { reason } + }) } } diff --git a/JC-Salon-WeChat/api/planning.js b/JC-Salon-WeChat/api/planning.js index 265e4ab1..3495472d 100644 --- a/JC-Salon-WeChat/api/planning.js +++ b/JC-Salon-WeChat/api/planning.js @@ -22,6 +22,14 @@ module.exports = { }) }, + createBackfillOrder(data) { + return request({ + url: '/manager/planning/backfill-orders', + method: 'POST', + data + }) + }, + appointment(orderItemId) { return request({ url: `/manager/planning/appointments/${orderItemId}` diff --git a/JC-Salon-WeChat/app-login-flow.test.js b/JC-Salon-WeChat/app-login-flow.test.js index 1d55b4dd..3f9e4270 100644 --- a/JC-Salon-WeChat/app-login-flow.test.js +++ b/JC-Salon-WeChat/app-login-flow.test.js @@ -27,6 +27,8 @@ function reset(preference) { navigations.length = 0 appDefinition.globalData.userInfo = null appDefinition.globalData.wechatLoginState = null + appDefinition.globalData.reviewNoticeShown = true + appDefinition.globalData.openEmployeeReview = true codeSequence = 0 } @@ -40,6 +42,8 @@ async function run() { assert.strictEqual(appDefinition.globalData.userInfo.id, 1) assert.strictEqual(statusCalled, false) assert.strictEqual(codeSequence, 1) + assert.strictEqual(appDefinition.globalData.reviewNoticeShown, false) + assert.strictEqual(appDefinition.globalData.openEmployeeReview, false) reset({ rememberMe: false }) let quickLoginCalled = false @@ -66,6 +70,7 @@ async function run() { appDefinition.logoutDevice() assert.strictEqual(storage[LOGIN_PREFERENCE_KEY], undefined) assert.strictEqual(appDefinition.globalData.userInfo, null) + assert.strictEqual(appDefinition.globalData.reviewNoticeShown, false) } run().catch(error => { diff --git a/JC-Salon-WeChat/app.js b/JC-Salon-WeChat/app.js index ad652d57..b2c39486 100644 --- a/JC-Salon-WeChat/app.js +++ b/JC-Salon-WeChat/app.js @@ -9,7 +9,9 @@ App({ shopName: BRAND_CONFIG.defaultShopName, userInfo: null, planningNeedRefresh: false, - wechatLoginState: null + wechatLoginState: null, + reviewNoticeShown: false, + openEmployeeReview: false }, onLaunch() { @@ -55,7 +57,7 @@ App({ }) this.publishWechatLoginState(result) if (result.status === 'SUCCESS' && result.accessToken) { - this.setSession(result) + this.setSession(result, true) wx.reLaunch({ url: '/pages/planning/index' }) return } @@ -96,7 +98,11 @@ App({ } }, - setSession(session) { + setSession(session, newLoginSession = false) { + if (newLoginSession) { + this.globalData.reviewNoticeShown = false + this.globalData.openEmployeeReview = false + } auth.setSession(session) this.bootstrapSession() }, @@ -105,6 +111,8 @@ App({ auth.clearSession() profileCache.invalidate() this.globalData.userInfo = null + this.globalData.reviewNoticeShown = false + this.globalData.openEmployeeReview = false }, logoutDevice() { @@ -112,5 +120,7 @@ App({ profileCache.invalidate() this.globalData.userInfo = null this.globalData.wechatLoginState = null + this.globalData.reviewNoticeShown = false + this.globalData.openEmployeeReview = false } }) diff --git a/JC-Salon-WeChat/app.json b/JC-Salon-WeChat/app.json index 2d288c15..dbda0847 100644 --- a/JC-Salon-WeChat/app.json +++ b/JC-Salon-WeChat/app.json @@ -5,11 +5,13 @@ "pages/register/index", "pages/planning/index", "pages/appointment-form/index", + "pages/backfill-order/index", "pages/appointment-detail/index", "pages/artist-transfer/index", "pages/customers/index", "pages/customer-detail/index", "pages/employees/index", + "pages/employee-create/index", "pages/employee-detail/index", "pages/schedule-setting/index", "pages/leave-management/index", diff --git a/JC-Salon-WeChat/assets/images/default-user-avatar.png b/JC-Salon-WeChat/assets/images/default-user-avatar.png new file mode 100644 index 00000000..703b5b23 Binary files /dev/null and b/JC-Salon-WeChat/assets/images/default-user-avatar.png differ diff --git a/JC-Salon-WeChat/components/entity-selector-sheet/index.js b/JC-Salon-WeChat/components/entity-selector-sheet/index.js new file mode 100644 index 00000000..45eecd27 --- /dev/null +++ b/JC-Salon-WeChat/components/entity-selector-sheet/index.js @@ -0,0 +1,41 @@ +Component({ + properties: { + visible: { type: Boolean, value: false }, + title: { type: String, value: '请选择' }, + keyword: { type: String, value: '' }, + placeholder: { type: String, value: '搜索' }, + items: { type: Array, value: [] }, + selectedId: { type: null, value: '' }, + loading: { type: Boolean, value: false }, + errorText: { type: String, value: '' }, + emptyText: { type: String, value: '暂无可选内容' }, + actionText: { type: String, value: '' }, + showSearch: { type: Boolean, value: true } + }, + + methods: { + close() { + this.triggerEvent('close') + }, + + stopEvent() { + }, + + onSearch(event) { + this.triggerEvent('search', { value: event.detail.value }) + }, + + selectItem(event) { + const item = this.data.items[Number(event.currentTarget.dataset.index)] + if (item) this.triggerEvent('select', { item }) + }, + + retry() { + this.triggerEvent('retry') + }, + + action() { + this.triggerEvent('action') + } + } +}) diff --git a/JC-Salon-WeChat/components/entity-selector-sheet/index.json b/JC-Salon-WeChat/components/entity-selector-sheet/index.json new file mode 100644 index 00000000..467ce294 --- /dev/null +++ b/JC-Salon-WeChat/components/entity-selector-sheet/index.json @@ -0,0 +1,3 @@ +{ + "component": true +} diff --git a/JC-Salon-WeChat/components/entity-selector-sheet/index.test.js b/JC-Salon-WeChat/components/entity-selector-sheet/index.test.js new file mode 100644 index 00000000..30eccce7 --- /dev/null +++ b/JC-Salon-WeChat/components/entity-selector-sheet/index.test.js @@ -0,0 +1,36 @@ +const assert = require('assert') +const fs = require('fs') +const path = require('path') + +let definition +global.Component = value => { definition = value } +require('./index') + +const events = [] +const component = { + data: { + items: [{ id: 7, title: '小周' }] + }, + triggerEvent(name, detail) { + events.push({ name, detail }) + } +} +Object.assign(component, definition.methods) + +component.onSearch({ detail: { value: '周' } }) +component.selectItem({ currentTarget: { dataset: { index: 0 } } }) +component.retry() +component.action() +component.close() + +assert.deepStrictEqual(events.map(item => item.name), ['search', 'select', 'retry', 'action', 'close']) +assert.strictEqual(events[0].detail.value, '周') +assert.strictEqual(events[1].detail.item.id, 7) + +const wxml = fs.readFileSync(path.join(__dirname, 'index.wxml'), 'utf8') +const wxss = fs.readFileSync(path.join(__dirname, 'index.wxss'), 'utf8') +assert.match(wxml, /class="selector-mask"[^>]*catchtouchmove="stopEvent"/) +assert.match(wxml, /]*catchtouchmove/) +assert.match(wxss, /\.selector-sheet\s*\{[^}]*height:\s*88vh;[^}]*flex-direction:\s*column;[^}]*overflow:\s*hidden;/s) +assert.match(wxss, /\.selector-scroll\s*\{[^}]*min-height:\s*0;[^}]*flex:\s*1;/s) diff --git a/JC-Salon-WeChat/components/entity-selector-sheet/index.wxml b/JC-Salon-WeChat/components/entity-selector-sheet/index.wxml new file mode 100644 index 00000000..71d24b93 --- /dev/null +++ b/JC-Salon-WeChat/components/entity-selector-sheet/index.wxml @@ -0,0 +1,44 @@ + + + + + {{title}} + + + + + + + + + + + + 正在加载... + + + {{errorText}} + + + {{emptyText}} + + + + + + {{item.title}} + {{item.badge}} + + {{item.subtitle}} + {{item.meta}} + + {{selectedId == item.id ? '✓' : '›'}} + + + + + + + + + diff --git a/JC-Salon-WeChat/components/entity-selector-sheet/index.wxss b/JC-Salon-WeChat/components/entity-selector-sheet/index.wxss new file mode 100644 index 00000000..0328e0ee --- /dev/null +++ b/JC-Salon-WeChat/components/entity-selector-sheet/index.wxss @@ -0,0 +1,289 @@ +.selector-mask, +.selector-sheet, +.selector-head, +.selector-search-wrap, +.selector-scroll, +.selector-list, +.selector-item, +.selector-copy, +.selector-footer, +.selector-close, +.selector-retry, +.selector-action, +.selector-search { + box-sizing: border-box; +} + +.selector-close, +.selector-retry, +.selector-action { + margin: 0; + padding: 0; +} + +.selector-close::after, +.selector-retry::after, +.selector-action::after { + border: 0; +} + +.selector-mask { + position: fixed; + inset: 0; + z-index: 120; + display: flex; + align-items: flex-end; + background: rgba(25, 22, 18, 0.5); + animation: selectorMaskIn 180ms ease both; +} + +.selector-sheet { + display: flex; + width: 100%; + height: 88vh; + max-height: 88vh; + flex-direction: column; + overflow: hidden; + border-radius: 34rpx 34rpx 0 0; + background: #fffdf8; + box-shadow: 0 -20rpx 48rpx rgba(44, 35, 27, 0.18); + animation: selectorSheetUp 220ms ease both; +} + +.selector-handle { + width: 72rpx; + height: 7rpx; + margin: 14rpx auto 2rpx; + border-radius: 999rpx; + background: #ddd6cd; +} + +.selector-head { + display: flex; + align-items: center; + justify-content: space-between; + min-height: 92rpx; + padding: 0 28rpx; +} + +.selector-title { + color: #29241f; + font-size: 34rpx; + font-weight: 900; + letter-spacing: 1rpx; +} + +.selector-close { + position: relative; + width: 52rpx; + min-width: 52rpx; + height: 52rpx; + min-height: 52rpx; + margin: 0; + padding: 0; + border: 1rpx solid #e6dfd6; + border-radius: 50%; + background: #f8f4ee; +} + +.selector-close::before, +.selector-close::after { + content: ""; + position: absolute; + top: 24rpx; + left: 14rpx; + width: 22rpx; + height: 3rpx; + border-radius: 999rpx; + background: #665e56; +} + +.selector-close::before { transform: rotate(45deg); } +.selector-close::after { transform: rotate(-45deg); } + +.selector-search-wrap { + display: flex; + align-items: center; + min-height: 80rpx; + margin: 0 28rpx 18rpx; + padding: 0 22rpx; + border: 1rpx solid #e7e0d7; + border-radius: 22rpx; + background: #f7f3ed; +} + +.selector-search-icon { + position: relative; + width: 26rpx; + height: 26rpx; + margin-right: 18rpx; + border: 3rpx solid #8e877f; + border-radius: 50%; +} + +.selector-search-icon::after { + content: ""; + position: absolute; + right: -9rpx; + bottom: -6rpx; + width: 12rpx; + height: 3rpx; + border-radius: 999rpx; + background: #8e877f; + transform: rotate(45deg); +} + +.selector-search { + height: 78rpx; + flex: 1; + color: #29241f; + font-size: 27rpx; +} + +.selector-scroll { + height: 0; + min-height: 0; + flex: 1; +} + +.selector-list { + padding: 0 28rpx 24rpx; +} + +.selector-item { + display: flex; + align-items: center; + min-height: 112rpx; + margin-bottom: 14rpx; + padding: 20rpx; + border: 1rpx solid #ece5dc; + border-radius: 24rpx; + background: #fff; + transition: transform 140ms ease, border-color 140ms ease, background 140ms ease; +} + +.selector-item:active { transform: scale(0.99); } +.selector-item.selected { border-color: #8eafa3; background: #f0f6f3; } + +.selector-avatar { + width: 76rpx; + height: 76rpx; + flex: 0 0 auto; + border-radius: 50%; + background: #eee9e2; +} + +.selector-copy { + min-width: 0; + flex: 1; + margin-left: 18rpx; +} + +.selector-copy.without-avatar { margin-left: 2rpx; } + +.selector-title-row { + display: flex; + align-items: center; + gap: 12rpx; +} + +.selector-item-title { + overflow: hidden; + color: #2b2621; + font-size: 28rpx; + font-weight: 800; + text-overflow: ellipsis; + white-space: nowrap; +} + +.selector-badge { + flex: 0 0 auto; + padding: 5rpx 12rpx; + border-radius: 999rpx; + background: #e7f0ec; + color: #55786d; + font-size: 19rpx; + font-weight: 800; +} + +.selector-subtitle, +.selector-meta { + display: block; + margin-top: 7rpx; + overflow: hidden; + color: #7f7870; + font-size: 23rpx; + text-overflow: ellipsis; + white-space: nowrap; +} + +.selector-meta { color: #a19990; font-size: 21rpx; } + +.selector-check { + width: 52rpx; + color: #8c857d; + font-size: 32rpx; + font-weight: 800; + text-align: right; +} + +.selector-item.selected .selector-check { color: #2f6f62; } + +.selector-state { + display: flex; + min-height: 360rpx; + flex-direction: column; + align-items: center; + justify-content: center; + padding: 40rpx 48rpx; + color: #9a9289; + font-size: 25rpx; + line-height: 1.6; + text-align: center; +} + +.selector-error { color: #a8554e; } + +.selector-retry { + min-width: 180rpx; + height: 64rpx; + margin-top: 22rpx; + padding: 0 28rpx; + border: 1rpx solid #d8d1c8; + border-radius: 999rpx; + background: #fff; + color: #514b44; + font-size: 23rpx; + font-weight: 800; + line-height: 64rpx; +} + +.selector-loading-dot { + width: 20rpx; + height: 20rpx; + margin-bottom: 20rpx; + border-radius: 50%; + background: #6f8f83; + box-shadow: -30rpx 0 #c9d8d2, 30rpx 0 #9eb9af; +} + +.selector-footer { + padding: 16rpx 28rpx calc(18rpx + env(safe-area-inset-bottom)); + border-top: 1rpx solid #eee7de; + background: #fffdf8; +} + +.selector-action { + width: 100%; + height: 78rpx; + border: 1rpx solid #cbdad4; + border-radius: 22rpx; + background: #edf4f1; + color: #2f6f62; + font-size: 26rpx; + font-weight: 900; + line-height: 78rpx; +} + +@keyframes selectorMaskIn { from { opacity: 0; } to { opacity: 1; } } +@keyframes selectorSheetUp { from { transform: translateY(48rpx); } to { transform: translateY(0); } } diff --git a/JC-Salon-WeChat/employees-review.test.js b/JC-Salon-WeChat/employees-review.test.js new file mode 100644 index 00000000..39852986 --- /dev/null +++ b/JC-Salon-WeChat/employees-review.test.js @@ -0,0 +1,37 @@ +const assert = require('assert') + +const requests = [] +const storage = {} +global.wx = { + getAccountInfoSync: () => ({ miniProgram: { envVersion: 'develop' } }), + getDeviceInfo: () => ({ platform: 'devtools' }), + getStorageSync: key => storage[key] || '', + setStorageSync: (key, value) => { storage[key] = value }, + removeStorageSync: key => { delete storage[key] }, + request: options => { + requests.push(options) + options.success({ statusCode: 200, data: { code: 200, data: {} } }) + } +} +global.getApp = () => ({ clearSession: () => {}, goLogin: () => {} }) + +const employeesApi = require('./api/employees') + +async function run() { + await employeesApi.reviewSummary() + await employeesApi.reviewApplications() + await employeesApi.approveApplication(12) + await employeesApi.rejectApplication(12, '资料不完整') + + assert.deepStrictEqual(requests.map(item => [item.method || 'GET', item.url, item.data]), [ + ['GET', 'http://127.0.0.1:80/api/admin/user/workbench/registration/summary', undefined], + ['GET', 'http://127.0.0.1:80/api/admin/user/workbench/registration/list', undefined], + ['POST', 'http://127.0.0.1:80/api/admin/user/workbench/registration/12/approve', undefined], + ['POST', 'http://127.0.0.1:80/api/admin/user/workbench/registration/12/reject', { reason: '资料不完整' }] + ]) +} + +run().catch(error => { + console.error(error) + process.exitCode = 1 +}) diff --git a/JC-Salon-WeChat/pages/appointment-detail/index.js b/JC-Salon-WeChat/pages/appointment-detail/index.js index e1864860..7b01fd80 100644 --- a/JC-Salon-WeChat/pages/appointment-detail/index.js +++ b/JC-Salon-WeChat/pages/appointment-detail/index.js @@ -7,6 +7,7 @@ Page({ appointment: {}, avatarText: '', timeText: '', + isUnassigned: false, loadError: '' }, @@ -32,13 +33,18 @@ Page({ applyAppointment(appointment) { this.setData({ appointment, + isUnassigned: appointment.assignmentStatus === 'UNASSIGNED' || !appointment.artistId, avatarText: String(appointment.customerName || '客').slice(0, 1), - timeText: `${(appointment.startTime || '').slice(0, 16)} - ${(appointment.endTime || '').slice(11, 16)}`, + timeText: appointment.historicalBackfill && !appointment.startTime ? '时间未记录' : `${(appointment.startTime || '').slice(0, 16)} - ${(appointment.endTime || '').slice(11, 16)}`, loadError: '' }) }, async updateStatus(status) { + if (status !== 3 && this.data.isUnassigned) { + wx.showToast({ title: '请先分配员工', icon: 'none' }) + return + } try { await planningApi.updateStatus(this.data.appointment.orderId, status) markPlanningRefresh() @@ -50,6 +56,7 @@ Page({ }, confirm() { + if (this.data.appointment.historicalBackfill) return this.updateStatus(1) }, @@ -62,6 +69,7 @@ Page({ }, goTransfer() { + if (this.data.appointment.historicalBackfill) return wx.navigateTo({ url: `/pages/artist-transfer/index?id=${this.data.id}` }) }, diff --git a/JC-Salon-WeChat/pages/appointment-detail/index.wxml b/JC-Salon-WeChat/pages/appointment-detail/index.wxml index 7b21f317..da49d540 100644 --- a/JC-Salon-WeChat/pages/appointment-detail/index.wxml +++ b/JC-Salon-WeChat/pages/appointment-detail/index.wxml @@ -14,8 +14,9 @@ - {{appointment.statusText}} - + 历史补单 · {{appointment.statusText}} + {{appointment.statusText}} + @@ -25,7 +26,7 @@ 美甲师 - {{appointment.artistName}} + {{isUnassigned ? '待分配' : appointment.artistName}} 时间 @@ -44,8 +45,8 @@ - - + + diff --git a/JC-Salon-WeChat/pages/appointment-form/entity-selector.test.js b/JC-Salon-WeChat/pages/appointment-form/entity-selector.test.js new file mode 100644 index 00000000..128b531b --- /dev/null +++ b/JC-Salon-WeChat/pages/appointment-form/entity-selector.test.js @@ -0,0 +1,63 @@ +const assert = require('assert') + +global.wx = { + getAccountInfoSync: () => ({ miniProgram: { envVersion: 'develop' } }), + getDeviceInfo: () => ({ platform: 'devtools' }), + getStorageSync: () => '', + setStorageSync: () => {}, + removeStorageSync: () => {}, + showToast: () => {}, + navigateTo: () => {} +} +global.getApp = () => ({ globalData: { userInfo: { type: 2, id: 1, shopId: 2 } } }) + +let definition +global.Page = value => { definition = value } +require('./index') + +function createPage() { + return { + ...definition, + data: JSON.parse(JSON.stringify(definition.data)), + setData(values) { + Object.entries(values).forEach(([key, value]) => { + const parts = key.split('.') + let target = this.data + for (let index = 0; index < parts.length - 1; index += 1) target = target[parts[index]] + target[parts[parts.length - 1]] = value + }) + } + } +} + +async function run() { + const page = createPage() + page.selectCustomer({ detail: { item: { id: 18, name: '小周', phone: '13800138000' } } }) + assert.strictEqual(page.data.form.customerUserId, 18) + assert.strictEqual(page.data.form.customerName, '小周') + assert.strictEqual(page.data.form.phone, '13800138000') + assert.strictEqual(page.data.customerSheetVisible, false) + + page.data.form.customerUserId = 18 + page.data.manualCustomerForm = { name: '新客户', phone: '13900139000' } + page.useManualCustomer() + assert.strictEqual(page.data.form.customerUserId, '') + assert.strictEqual(page.data.form.customerName, '新客户') + assert.strictEqual(page.data.form.phone, '13900139000') + + page.data.artists = [{ id: 1, name: '小周' }, { id: 2, name: '小李' }] + page.onArtistSearch({ detail: { value: '李' } }) + assert.deepStrictEqual(page.data.artistSelectorItems.map(item => item.id), [2]) + + page.refreshAvailableTimes = async () => {} + page.checkAvailability = () => {} + page.selectArtist({ detail: { item: { id: 2, name: '小李' } } }) + assert.strictEqual(page.data.form.artistId, 2) + assert.strictEqual(page.data.selectedArtist.name, '小李') + assert.strictEqual(page.data.artistSheetVisible, false) +} + +run().catch(error => { + console.error(error) + process.exitCode = 1 +}) diff --git a/JC-Salon-WeChat/pages/appointment-form/index.js b/JC-Salon-WeChat/pages/appointment-form/index.js index a027f887..a1766c3a 100644 --- a/JC-Salon-WeChat/pages/appointment-form/index.js +++ b/JC-Salon-WeChat/pages/appointment-form/index.js @@ -170,6 +170,24 @@ function buildAvailableTimeGroups(calendar, form, durationMinutes) { .filter(group => group.times.length > 0) } +function buildUnassignedTimeGroups(durationMinutes) { + const groupMap = { + morning: { key: 'morning', title: '上午', times: [] }, + afternoon: { key: 'afternoon', title: '下午', times: [] }, + evening: { key: 'evening', title: '晚上', times: [] } + } + const businessStart = dateUtil.minutesOfDay('10:00') + const businessEnd = dateUtil.minutesOfDay('22:00') + for (let minute = businessStart; minute + durationMinutes <= businessEnd; minute += TIME_SLOT_MINUTES) { + const period = getTimePeriod(minute) + groupMap[period.key].times.push({ + value: dateUtil.timeFromMinutes(minute), + rangeText: buildTimeRangeLabel(minute, durationMinutes) + }) + } + return Object.keys(groupMap).map(key => groupMap[key]).filter(group => group.times.length > 0) +} + function flattenTimeGroups(groups) { return (groups || []).reduce((list, group) => list.concat(group.times || []), []) } @@ -231,6 +249,25 @@ function normalizeCustomer(customer) { } } +function buildCustomerSelectorItem(customer) { + return { + ...customer, + title: customer.displayName, + subtitle: customer.displayPhone, + badge: '已有客户' + } +} + +function buildArtistSelectorItem(artist) { + return { + ...artist, + title: artist.name || '未命名员工', + subtitle: artist.statusText || '可用于指定预约', + meta: artist.workStartTime && artist.workEndTime ? `${artist.workStartTime.slice(0, 5)}-${artist.workEndTime.slice(0, 5)}` : '', + avatar: artist.avatar || artist.avatarUrl || '/assets/images/default-user-avatar.png' + } +} + Page({ data: { form: { @@ -253,12 +290,19 @@ Page({ remark: '' }, customerOptions: [], - customerDropdownVisible: false, + customerSheetVisible: false, + customerKeyword: '', customerLoading: false, customerError: '', + manualCustomerVisible: false, + manualCustomerForm: { name: '', phone: '' }, products: [], filteredProducts: [], artists: [], + artistSelectorItems: [], + artistSheetVisible: false, + artistKeyword: '', + artistError: '', selectedProduct: {}, selectedArtist: {}, productModalVisible: false, @@ -298,7 +342,6 @@ Page({ return } this.loadOptions() - this.searchCustomers() }, async loadOptions() { @@ -319,21 +362,37 @@ Page({ this.checkAvailability() }, - async loadArtists() { + async loadArtists(preferredArtistId, fallbackEmployee) { try { const calendar = await planningApi.calendar({ startDate: this.data.form.appointmentDate, endDate: this.data.form.appointmentDate }) - const artists = getCalendarArtists(calendar) - const selectedArtist = this.data.form.artistId ? findArtist(artists, this.data.form.artistId) : {} - this.setData({ artists, selectedArtist }) + let artists = getCalendarArtists(calendar) + const requestedId = preferredArtistId || this.data.form.artistId + if (fallbackEmployee && requestedId && !findArtist(artists, requestedId).id) { + artists = artists.concat({ + id: requestedId, + name: fallbackEmployee.name || fallbackEmployee.title, + avatar: fallbackEmployee.avatar || '' + }) + } + const selectedArtist = requestedId ? findArtist(artists, requestedId) : {} + this.setData({ + artists, + artistSelectorItems: this.filterArtistItems(artists, this.data.artistKeyword), + selectedArtist, + artistError: '', + 'form.artistId': selectedArtist.id || '' + }) this.refreshProductCards() } catch (error) { this.setData({ artists: [], + artistSelectorItems: [], selectedArtist: {}, 'form.artistId': '', + artistError: error.message || '员工列表加载失败', conflictTip: error.message || '美甲师列表加载失败', conflictLevel: 'danger' }) @@ -345,44 +404,40 @@ Page({ const patch = { [`form.${field}`]: event.detail.value } - if (field === 'customerName' || field === 'phone') { - patch['form.customerUserId'] = '' - patch.customerDropdownVisible = true - } this.setData(patch) - if (field === 'customerName' || field === 'phone') { - this.scheduleCustomerSearch(field) - } if (field === 'durationMinutes') { this.refreshAvailableTimes() this.checkAvailability() } }, - onCustomerFocus(event) { - const field = event.currentTarget.dataset.field - this.setData({ customerDropdownVisible: true }) - this.searchCustomers(field) + openCustomerSheet() { + this.setData({ customerSheetVisible: true }) + this.searchCustomers(this.data.customerKeyword) }, - scheduleCustomerSearch(field) { + closeCustomerSheet() { + this.setData({ customerSheetVisible: false }) + }, + + onCustomerSearch(event) { + const keyword = event.detail.value + this.setData({ customerKeyword: keyword }) clearTimeout(this._customerTimer) - this._customerTimer = setTimeout(() => this.searchCustomers(field), 250) + this._customerTimer = setTimeout(() => this.searchCustomers(keyword), 250) }, - async searchCustomers(preferredField) { + async searchCustomers(keywordValue) { if (!this.data.canCreateAppointment) { return } - const form = this.data.form - const sourceValue = preferredField === 'phone' ? form.phone : form.customerName || form.phone - const keyword = String(sourceValue || '').trim() + const keyword = String(keywordValue === undefined ? this.data.customerKeyword : keywordValue || '').trim() this.setData({ customerLoading: true }) try { const data = await customersApi.list({ keyword, page: 1, size: 20 }) const list = data.list || data || [] this.setData({ - customerOptions: list.map(normalizeCustomer), + customerOptions: list.map(normalizeCustomer).map(buildCustomerSelectorItem), customerError: '' }) } catch (error) { @@ -395,8 +450,12 @@ Page({ } }, + retryCustomerSearch() { + this.searchCustomers(this.data.customerKeyword) + }, + selectCustomer(event) { - const customer = this.data.customerOptions.find(item => String(item.id) === String(event.currentTarget.dataset.id)) + const customer = event.detail.item if (!customer) { return } @@ -404,14 +463,48 @@ Page({ 'form.customerUserId': customer.id, 'form.customerName': customer.name, 'form.phone': customer.phone, - customerDropdownVisible: false + customerSheetVisible: false, + customerKeyword: '' }) }, - hideCustomerDropdown() { - setTimeout(() => { - this.setData({ customerDropdownVisible: false }) - }, 180) + openManualCustomer() { + this.setData({ + customerSheetVisible: false, + manualCustomerVisible: true, + manualCustomerForm: { + name: this.data.form.customerName || '', + phone: this.data.form.phone || '' + } + }) + }, + + closeManualCustomer() { + this.setData({ manualCustomerVisible: false }) + }, + + onManualCustomerInput(event) { + this.setData({ [`manualCustomerForm.${event.currentTarget.dataset.field}`]: event.detail.value }) + }, + + useManualCustomer() { + const name = String(this.data.manualCustomerForm.name || '').trim() + const phone = String(this.data.manualCustomerForm.phone || '').trim() + if (!name) { + wx.showToast({ title: '请输入客户姓名', icon: 'none' }) + return + } + if (!/^1[3-9]\d{9}$/.test(phone)) { + wx.showToast({ title: '请输入正确手机号', icon: 'none' }) + return + } + this.setData({ + 'form.customerUserId': '', + 'form.customerName': name, + 'form.phone': phone, + manualCustomerVisible: false, + customerKeyword: '' + }) }, onUnload() { @@ -454,6 +547,9 @@ Page({ stopTap() { }, + stopTouchMove() { + }, + onProductSearch(event) { this.setData({ productKeyword: event.detail.value }) this.refreshProductCards() @@ -531,20 +627,102 @@ Page({ }) }, - onArtistChange(event) { - const selectedArtist = this.data.artists[Number(event.detail.value)] || {} + filterArtistItems(artists, keywordValue) { + const keyword = String(keywordValue || '').trim().toLowerCase() + const items = (artists || []) + .filter(item => !keyword || String(item.name || '').toLowerCase().includes(keyword)) + .map(buildArtistSelectorItem) + if (!keyword || '暂不分配'.includes(keyword)) { + items.unshift({ id: '__unassigned__', title: '暂不分配', subtitle: '先记录预约,后续再分配员工', badge: '待分配' }) + } + return items + }, + + openArtistSheet() { + this.setData({ + artistSheetVisible: true, + artistSelectorItems: this.filterArtistItems(this.data.artists, this.data.artistKeyword) + }) + }, + + closeArtistSheet() { + this.setData({ artistSheetVisible: false }) + }, + + retryArtists() { + this.loadArtists() + }, + + onArtistSearch(event) { + const artistKeyword = event.detail.value + this.setData({ + artistKeyword, + artistSelectorItems: this.filterArtistItems(this.data.artists, artistKeyword) + }) + }, + + selectArtist(event) { + const selectedArtist = event.detail.item || {} + if (selectedArtist.id === '__unassigned__') { + this.setData({ + selectedArtist: {}, + 'form.artistId': '', + artistSheetVisible: false, + conflictTip: '', + conflictLevel: 'free' + }) + this.refreshAvailableTimes() + return + } this.setData({ selectedArtist, 'form.artistId': selectedArtist.id, - 'form.appointmentTime': '' + 'form.appointmentTime': '', + artistSheetVisible: false }) this.refreshAvailableTimes() this.checkAvailability() }, + addEmployeeFromSelector() { + this.setData({ artistSheetVisible: false }) + wx.navigateTo({ + url: `/pages/employee-create/index?picker=1&date=${encodeURIComponent(this.data.form.appointmentDate || '')}&time=${encodeURIComponent(this.data.form.appointmentTime || '')}&durationMinutes=${encodeURIComponent(this.data.form.durationMinutes || '')}`, + success: result => { + result.eventChannel.on('employeeCreated', employee => this.handleEmployeeCreated(employee)) + } + }) + }, + + async handleEmployeeCreated(employee) { + const originalTime = this.data.form.appointmentTime + await this.loadArtists(employee.autoSelect === false ? '' : employee.id, employee) + if (employee.autoSelect === false) { + this.setData({ selectedArtist: {}, 'form.artistId': '' }) + await this.refreshAvailableTimes() + return + } + if (employee.scheduleSaved && originalTime) { + const availability = await this.checkAvailability() + if (!availability.ok) { + this.setData({ + selectedArtist: {}, + 'form.artistId': '', + 'form.appointmentTime': originalTime, + conflictTip: `${availability.tip || '新员工当前排班无法承接'},预约已保持待分配`, + conflictLevel: 'danger' + }) + } + } else { + this.setData({ 'form.appointmentTime': '' }) + } + await this.refreshAvailableTimes() + if (this.data.form.artistId) this.checkAvailability() + }, + canOpenTimeSheet() { const form = this.data.form - return Boolean(form.appointmentDate && form.artistId && normalizeDuration(form.durationMinutes)) + return Boolean(form.appointmentDate && normalizeDuration(form.durationMinutes)) }, async refreshAvailableTimes() { @@ -552,11 +730,11 @@ Page({ const durationMinutes = normalizeDuration(form.durationMinutes) const requestSeq = (this._availableTimeRequestSeq || 0) + 1 this._availableTimeRequestSeq = requestSeq - if (!form.appointmentDate || !form.artistId || !durationMinutes) { + if (!form.appointmentDate || !durationMinutes) { const patch = { availableTimeGroups: [], timeError: '', - timeSelectTip: '请先选择美甲师并填写时长' + timeSelectTip: '请先填写预约日期和时长' } if (form.appointmentTime) { patch['form.appointmentTime'] = '' @@ -564,6 +742,16 @@ Page({ this.setData(patch) return } + if (!form.artistId) { + const availableTimeGroups = buildUnassignedTimeGroups(durationMinutes) + this.setData({ + availableTimeGroups, + timeError: '', + timeLoading: false, + timeSelectTip: '请选择预约时间,员工可稍后分配' + }) + return + } this.setData({ timeLoading: true, timeError: '', @@ -606,7 +794,7 @@ Page({ async openTimeSheet() { if (!this.canOpenTimeSheet()) { - wx.showToast({ title: '请先选择美甲师并填写时长', icon: 'none' }) + wx.showToast({ title: '请先填写预约日期和时长', icon: 'none' }) return } this.setData({ timeSheetVisible: true }) @@ -628,7 +816,7 @@ Page({ async checkAvailability() { const form = this.data.form - if (!form.appointmentDate || !form.appointmentTime || !form.artistId) { + if (!form.appointmentDate || !form.appointmentTime) { this.setData({ conflictTip: '', conflictLevel: 'free' }) return { ok: true } } @@ -644,6 +832,11 @@ Page({ this.setData({ conflictTip: tip, conflictLevel: 'danger' }) return { ok: false, tip } } + if (!form.artistId) { + const tip = '预约将保存为待分配,当前不会占用员工时间' + this.setData({ conflictTip: tip, conflictLevel: 'free' }) + return { ok: true, tip } + } try { const calendar = await planningApi.calendar({ startDate: form.appointmentDate, @@ -689,7 +882,7 @@ Page({ const form = this.data.form const hasManualProduct = String(form.manualProductTitle || '').trim() && String(form.manualProductPrice || '').trim() const durationMinutes = normalizeDuration(form.durationMinutes) - if (!form.customerName || !form.phone || (!form.productId && !hasManualProduct) || !form.artistId) { + if (!form.customerName || !form.phone || (!form.productId && !hasManualProduct) || !form.appointmentDate || !form.appointmentTime) { wx.showToast({ title: '请补全预约信息', icon: 'none' }) return } @@ -706,12 +899,25 @@ Page({ wx.showToast({ title: availability.tip || '该时段已被预约', icon: 'none' }) return } + if (!form.artistId) { + const result = await new Promise(resolve => { + wx.showModal({ + title: '保存为待分配预约', + content: '当前未指定员工,预约会正常保存,但不会占用员工时间。可以稍后在预约详情中分配。', + cancelText: '返回选择', + confirmText: '继续保存', + success: resolve, + fail: () => resolve({ confirm: false }) + }) + }) + if (!result.confirm) return + } this.setData({ loading: true }) try { const payload = { ...form, customerUserId: form.customerUserId ? String(form.customerUserId) : undefined, - artistId: String(form.artistId), + artistId: form.artistId ? String(form.artistId) : undefined, durationMinutes, clientRequestId: buildClientRequestId('manager-appointment') } diff --git a/JC-Salon-WeChat/pages/appointment-form/index.json b/JC-Salon-WeChat/pages/appointment-form/index.json index 9b43ad76..a2d4a1db 100644 --- a/JC-Salon-WeChat/pages/appointment-form/index.json +++ b/JC-Salon-WeChat/pages/appointment-form/index.json @@ -1,3 +1,6 @@ { - "navigationBarTitleText": "新建预约" + "navigationBarTitleText": "新建预约", + "usingComponents": { + "entity-selector-sheet": "/components/entity-selector-sheet/index" + } } diff --git a/JC-Salon-WeChat/pages/appointment-form/index.wxml b/JC-Salon-WeChat/pages/appointment-form/index.wxml index 47fa1bc3..1d9d3d97 100644 --- a/JC-Salon-WeChat/pages/appointment-form/index.wxml +++ b/JC-Salon-WeChat/pages/appointment-form/index.wxml @@ -1,27 +1,14 @@ - - - 客户姓名 - - - - 手机号 - - - - 正在搜索客户... - {{customerError}},可继续手动输入 - - - - {{item.displayName}} - {{item.displayPhone}} - - 选择 - - 暂无匹配客户,可继续手动输入 + + 客户 + + + {{form.customerName || '请选择客户'}} + {{form.phone || '搜索已有客户或手动录入'}} + 已有 + › @@ -43,17 +30,18 @@ 分钟 - 指定员工 - - {{selectedArtist.name || '请选择美甲师'}} - + 员工(可稍后分配) + + {{selectedArtist.name || '暂不分配'}} + › + 预约时间 {{form.appointmentTime || timeSelectTip}} - {{form.appointmentDate}} · {{selectedArtist.name}} · {{form.durationMinutes}}分钟 + {{form.appointmentDate}} · {{selectedArtist.name || '待分配'}} · {{form.durationMinutes}}分钟 › @@ -66,7 +54,7 @@ 容量校验 - 提交预约时会校验营业时间、美甲师休息和同时间段容量,冲突会直接拦截。 + 已指定员工时会校验排班和冲突;暂不分配时只校验营业时间,后续分配时再完整校验。 @@ -79,7 +67,66 @@ {{conflictTip}} - + + + + + + + + + 手动录入客户 + 录入后将直接带回本次预约 + + × + + + + 客户姓名 + + + + 手机号 + + + + + + + + @@ -88,44 +135,46 @@ × - - {{productError}} - - - 图 - - - {{item.title}} - {{item.priceText}} - - {{item.artistText}} · {{item.durationText || '时长待定'}} - - {{tag}} + + + {{productError}} + + + 图 + + + {{item.title}} + {{item.priceText}} + + {{item.artistText}} · {{item.durationText || '时长待定'}} + + {{tag}} + + 暂无匹配作品 + + + 手动新增预约作品 + + + + +