diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/manager/controller/admin/AdminManagerController.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/manager/controller/admin/AdminManagerController.java index 00fa11c2..81194408 100644 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/manager/controller/admin/AdminManagerController.java +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/manager/controller/admin/AdminManagerController.java @@ -27,8 +27,12 @@ import com.xiaowang.jayucloud.salon.core.modules.product.service.ProductService; import com.xiaowang.jayucloud.salon.core.modules.product.vo.ProductVO; import com.xiaowang.jayucloud.salon.core.modules.security.support.AdminScopeHelper; import com.xiaowang.jayucloud.salon.core.modules.shop.dto.ShopDTO; +import com.xiaowang.jayucloud.salon.core.modules.shop.dto.ShopAppointmentSettingsDTO; +import com.xiaowang.jayucloud.salon.core.modules.shop.dto.ShopNameUpdateDTO; import com.xiaowang.jayucloud.salon.core.modules.shop.service.ShopService; import com.xiaowang.jayucloud.salon.core.modules.shop.vo.ShopVO; +import com.xiaowang.jayucloud.salon.core.modules.shop.vo.ShopAppointmentSettingsVO; +import com.xiaowang.jayucloud.salon.core.modules.manager.vo.AppointmentCustomerOptionVO; import com.xiaowang.jayucloud.salon.core.modules.user.dto.UserDTO; import com.xiaowang.jayucloud.salon.core.modules.user.entity.UserDO; import com.xiaowang.jayucloud.salon.core.modules.user.service.UserService; @@ -151,6 +155,30 @@ public class AdminManagerController { return Result.success(userService.findCustomerMatches(nickname, phone, shopId)); } + @GetMapping("/customers/identity-matches") + @RequirePermission("user:view") + public Result> customerIdentityMatches(HttpServletRequest request, + @RequestParam String nickname, + @RequestParam(required = false) String wechatId, + @RequestParam(required = false) String phone) { + UserDO currentUser = adminScopeHelper.getCurrentUser(request); + adminScopeHelper.requireShopContext(currentUser); + Long shopId = adminScopeHelper.resolveShopScope(currentUser, null); + return Result.success(userService.findCustomerIdentityMatches(nickname, wechatId, phone, shopId)); + } + + @GetMapping("/customers/appointment-options") + @RequirePermission("user:view") + public Result> appointmentCustomerOptions(HttpServletRequest request, + @RequestParam(defaultValue = "1") Integer page, + @RequestParam(defaultValue = "30") Integer size, + @RequestParam(required = false) String keyword) { + UserDO currentUser = adminScopeHelper.getCurrentUser(request); + Long shopId = adminScopeHelper.resolveShopScope(currentUser, null); + adminScopeHelper.requireShopContext(currentUser); + return Result.success(userService.listCustomersForAppointment(page, size, keyword, shopId)); + } + @GetMapping("/customers/{id}") @RequirePermission("user:view") public Result customer(HttpServletRequest request, @PathVariable Long id) { @@ -327,4 +355,33 @@ public class AdminManagerController { } return Result.success(shopService.updateShop(shopId, dto)); } + + @GetMapping("/shop/appointment-settings") + @RequirePermission("shop:view") + public Result appointmentSettings(HttpServletRequest request) { + UserDO currentUser = adminScopeHelper.getCurrentUser(request); + adminScopeHelper.requireShopContext(currentUser); + Long shopId = adminScopeHelper.resolveShopScope(currentUser, null); + return Result.success(shopService.getAppointmentSettings(shopId)); + } + + @PutMapping("/shop/appointment-settings") + @RequirePermission("shop:edit") + @OperationGuard(action = "manager-shop-appointment-settings-update", ttlSeconds = 10, message = "预约设置正在保存,请勿重复提交") + public Result updateAppointmentSettings(HttpServletRequest request, @RequestBody ShopAppointmentSettingsDTO dto) { + UserDO currentUser = adminScopeHelper.getCurrentUser(request); + adminScopeHelper.requireShopContext(currentUser); + Long shopId = adminScopeHelper.resolveShopScope(currentUser, null); + return Result.success(shopService.updateAppointmentSettings(shopId, dto)); + } + + @PutMapping("/shop/name") + @RequirePermission("shop:edit") + @OperationGuard(action = "manager-shop-name-review", ttlSeconds = 10, message = "门店名称正在提交审核,请勿重复操作") + public Result updateShopName(HttpServletRequest request, @RequestBody ShopNameUpdateDTO dto) { + UserDO currentUser = adminScopeHelper.getCurrentUser(request); + adminScopeHelper.requireShopContext(currentUser); + Long shopId = adminScopeHelper.resolveShopScope(currentUser, null); + return Result.success(shopService.updateShopName(shopId, dto)); + } } diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/manager/vo/AppointmentCustomerOptionVO.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/manager/vo/AppointmentCustomerOptionVO.java new file mode 100644 index 00000000..3831ab2f --- /dev/null +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/manager/vo/AppointmentCustomerOptionVO.java @@ -0,0 +1,17 @@ +package com.xiaowang.jayucloud.salon.core.modules.manager.vo; + +import com.fasterxml.jackson.databind.annotation.JsonSerialize; +import com.fasterxml.jackson.databind.ser.std.ToStringSerializer; +import lombok.Data; + +import java.time.LocalDateTime; + +@Data +public class AppointmentCustomerOptionVO { + @JsonSerialize(using = ToStringSerializer.class) + private Long id; + private String name; + private String phone; + private String avatar; + private LocalDateTime createdAt; +} diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/planning/dto/PlanningAppointmentCreateDTO.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/planning/dto/PlanningAppointmentCreateDTO.java index ba3d50f1..0c7c28fd 100644 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/planning/dto/PlanningAppointmentCreateDTO.java +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/planning/dto/PlanningAppointmentCreateDTO.java @@ -8,6 +8,7 @@ import java.math.BigDecimal; public class PlanningAppointmentCreateDTO { private Long customerUserId; private String customerName; + private String wechatId; private String phone; private Long productId; private Integer quantity; diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/planning/service/impl/PlanningServiceImpl.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/planning/service/impl/PlanningServiceImpl.java index d6ef017c..20d95484 100644 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/planning/service/impl/PlanningServiceImpl.java +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/planning/service/impl/PlanningServiceImpl.java @@ -111,7 +111,8 @@ public class PlanningServiceImpl implements PlanningService { Long shopId = requirePlanningShopId(currentUser); ShopDO shop = shopMapper.selectById(shopId); PlanningCalendarSupport.BusinessHours businessHours = PlanningCalendarSupport.parseBusinessHours( - shop == null ? null : shop.getBusinessHours() + shop == null ? null : (StringUtils.hasText(shop.getAppointmentBusinessHours()) + ? shop.getAppointmentBusinessHours() : shop.getBusinessHours()) ); List artists = listArtists(shopId, artistId); @@ -136,6 +137,8 @@ public class PlanningServiceImpl implements PlanningService { PlanningCalendarVO vo = new PlanningCalendarVO(); vo.setBusinessStartTime(businessHours.start().toString()); vo.setBusinessEndTime(businessHours.end().toString()); + vo.setDefaultAppointmentDurationMinutes(shop == null || shop.getDefaultAppointmentDurationMinutes() == null + || shop.getDefaultAppointmentDurationMinutes() <= 0 ? DEFAULT_DURATION_MINUTES : shop.getDefaultAppointmentDurationMinutes()); vo.setSlotMinutes(DEFAULT_SLOT_MINUTES); vo.setArtists(artists); vo.setSchedules(scheduleVos); @@ -176,16 +179,23 @@ public class PlanningServiceImpl implements PlanningService { } Long shopId = requirePlanningShopId(currentUser); shopBusinessExpiryService.assertShopActive(shopId); - requireAppointmentDuration(dto.getDurationMinutes()); - ProductDO product = resolveAppointmentProduct(dto, shopId); - UserDO artist = dto.getArtistId() == null ? null : requireActiveArtist(dto.getArtistId(), shopId); - UserDO customer = resolveCustomer(shopId, dto); - + ShopDO shop = shopMapper.selectById(shopId); + int shopDefaultDuration = resolveShopDefaultDuration(shop); int quantity = dto.getQuantity() == null || dto.getQuantity() <= 0 ? 1 : dto.getQuantity(); - int durationMinutes = resolveDurationMinutes(product, dto.getDurationMinutes()) * quantity; + ProductDO product = dto.getProductId() == null ? null : requireActiveProduct(dto.getProductId(), shopId); + int durationMinutes = resolveDurationMinutes(product, dto.getDurationMinutes(), shopDefaultDuration) * quantity; LocalDateTime startTime = parseAppointmentStart(dto.getAppointmentStartTime(), dto.getAppointmentDate(), dto.getAppointmentTime()); LocalDateTime endTime = startTime.plusMinutes(durationMinutes); + ensureFutureAppointmentTime(startTime); ensureWithinBusinessHours(shopId, startTime, endTime); + if (product == null) { + product = createManualAppointmentProduct(dto, shopId, shopDefaultDuration); + durationMinutes = resolveDurationMinutes(product, dto.getDurationMinutes(), shopDefaultDuration) * quantity; + endTime = startTime.plusMinutes(durationMinutes); + ensureWithinBusinessHours(shopId, startTime, endTime); + } + UserDO artist = dto.getArtistId() == null ? null : requireActiveArtist(dto.getArtistId(), shopId); + UserDO customer = resolveCustomer(currentUser, shopId, dto); BigDecimal unitPrice = product.getPrice() == null ? BigDecimal.ZERO : product.getPrice(); BigDecimal amount = dto.getAmount() == null @@ -325,7 +335,8 @@ public class PlanningServiceImpl implements PlanningService { ProductDO product = requireActiveProduct(item.getProductId(), order.getShopId()); Long targetArtistId = dto.getArtistId() == null ? item.getArtistId() : dto.getArtistId(); UserDO artist = requireActiveArtist(targetArtistId, order.getShopId()); - int durationMinutes = resolveDurationMinutes(product, dto.getDurationMinutes()) * + ShopDO shop = shopMapper.selectById(order.getShopId()); + int durationMinutes = resolveDurationMinutes(product, dto.getDurationMinutes(), resolveShopDefaultDuration(shop)) * Math.max(1, item.getQuantity() == null ? 1 : item.getQuantity()); LocalDateTime startTime = hasText(dto.getAppointmentStartTime()) || hasText(dto.getAppointmentDate()) || hasText(dto.getAppointmentTime()) ? parseAppointmentStart(dto.getAppointmentStartTime(), dto.getAppointmentDate(), dto.getAppointmentTime()) @@ -334,6 +345,7 @@ public class PlanningServiceImpl implements PlanningService { throw new RuntimeException("预约时间不能为空"); } LocalDateTime endTime = startTime.plusMinutes(durationMinutes); + ensureFutureAppointmentTime(startTime); ensureWithinBusinessHours(order.getShopId(), startTime, endTime); appointmentCapacityService.moveReservationForArtistChange( @@ -559,7 +571,8 @@ public class PlanningServiceImpl implements PlanningService { if (start == null && item != null) { start = item.getAppointmentTime(); } - int durationMinutes = resolveDurationMinutes(product, null) * Math.max(1, item == null || item.getQuantity() == null ? 1 : item.getQuantity()); + ShopDO shop = order == null || order.getShopId() == null ? null : shopMapper.selectById(order.getShopId()); + int durationMinutes = resolveDurationMinutes(product, null, resolveShopDefaultDuration(shop)) * Math.max(1, item == null || item.getQuantity() == null ? 1 : item.getQuantity()); LocalDateTime end = reservation == null ? null : reservation.getAppointmentEndTime(); if (end == null && start != null) { end = start.plusMinutes(durationMinutes); @@ -736,14 +749,14 @@ public class PlanningServiceImpl implements PlanningService { return product; } - private ProductDO resolveAppointmentProduct(PlanningAppointmentCreateDTO dto, Long shopId) { + private ProductDO resolveAppointmentProduct(PlanningAppointmentCreateDTO dto, Long shopId, int defaultDurationMinutes) { if (dto.getProductId() != null) { return requireActiveProduct(dto.getProductId(), shopId); } - return createManualAppointmentProduct(dto, shopId); + return createManualAppointmentProduct(dto, shopId, defaultDurationMinutes); } - private ProductDO createManualAppointmentProduct(PlanningAppointmentCreateDTO dto, Long shopId) { + private ProductDO createManualAppointmentProduct(PlanningAppointmentCreateDTO dto, Long shopId, int defaultDurationMinutes) { String title = trimToNull(dto.getManualProductTitle()); String imageFileIds = trimToNull(dto.getManualProductImageFileIds()); if (!hasText(title)) { @@ -759,7 +772,8 @@ public class PlanningServiceImpl implements PlanningService { if (price.compareTo(BigDecimal.ZERO) < 0) { throw new RuntimeException("成交金额不能小于0"); } - int durationMinutes = requireAppointmentDuration(dto.getDurationMinutes()); + int durationMinutes = dto.getDurationMinutes() == null || dto.getDurationMinutes() <= 0 + ? defaultDurationMinutes : dto.getDurationMinutes(); ProductDO product = new ProductDO(); product.setShopId(shopId); product.setTitle(title); @@ -780,13 +794,6 @@ public class PlanningServiceImpl implements PlanningService { return product; } - private int requireAppointmentDuration(Integer durationMinutes) { - if (durationMinutes == null || durationMinutes <= 0) { - throw new RuntimeException("预约时长不能为空且必须大于0分钟"); - } - return durationMinutes; - } - private UserDO requireActiveArtist(Long artistId, Long shopId) { if (artistId == null) { throw new RuntimeException("请选择美甲师"); @@ -799,8 +806,9 @@ public class PlanningServiceImpl implements PlanningService { return artist; } - private UserDO resolveCustomer(Long shopId, PlanningAppointmentCreateDTO dto) { + private UserDO resolveCustomer(UserDO currentUser, Long shopId, PlanningAppointmentCreateDTO dto) { if (dto.getCustomerUserId() != null) { + adminScopeHelper.ensureUserAccessibleInCurrentShop(currentUser, dto.getCustomerUserId(), "客户不属于当前店铺"); UserDO customer = userMapper.selectById(dto.getCustomerUserId()); if (customer == null || Integer.valueOf(1).equals(customer.getIsDelete()) || !Integer.valueOf(0).equals(customer.getType())) { throw new RuntimeException("客户不存在"); @@ -808,6 +816,7 @@ public class PlanningServiceImpl implements PlanningService { return customer; } String customerName = trimToNull(dto.getCustomerName()); + String wechatId = trimToNull(dto.getWechatId()); String phone = trimToNull(dto.getPhone()); if (!hasText(customerName) && hasText(phone)) { throw new RuntimeException("填写手机号时请同时填写客户姓名"); @@ -818,15 +827,15 @@ public class PlanningServiceImpl implements PlanningService { if (!hasText(customerName)) { return null; } - List matches = - userService.findCustomerMatches(customerName, phone, shopId); + List matches = + userService.findCustomerIdentityMatches(customerName, dto.getWechatId(), phone, shopId); if (matches.size() > 1) { throw new RuntimeException("存在多个匹配客户,请先选择已有客户"); } if (!matches.isEmpty()) { return userMapper.selectById(matches.get(0).getId()); } - Long customerId = userService.createManagerCustomer(customerName, phone, shopId); + Long customerId = userService.createManagerCustomer(customerName, wechatId, phone, shopId); return userMapper.selectById(customerId); } @@ -851,7 +860,9 @@ public class PlanningServiceImpl implements PlanningService { private void ensureWithinBusinessHours(Long shopId, LocalDateTime startTime, LocalDateTime endTime) { ShopDO shop = shopMapper.selectById(shopId); - PlanningCalendarSupport.BusinessHours hours = PlanningCalendarSupport.parseBusinessHours(shop == null ? null : shop.getBusinessHours()); + String configuredHours = shop == null ? null : (StringUtils.hasText(shop.getAppointmentBusinessHours()) + ? shop.getAppointmentBusinessHours() : shop.getBusinessHours()); + PlanningCalendarSupport.BusinessHours hours = PlanningCalendarSupport.parseBusinessHours(configuredHours); LocalTime start = startTime.toLocalTime(); LocalTime end = endTime.toLocalTime(); if (start.isBefore(hours.start()) || end.isAfter(hours.end()) || !startTime.toLocalDate().equals(endTime.toLocalDate())) { @@ -859,6 +870,21 @@ public class PlanningServiceImpl implements PlanningService { } } + private void ensureFutureAppointmentTime(LocalDateTime startTime) { + LocalDate today = LocalDate.now(); + if (startTime.toLocalDate().isBefore(today)) { + throw new RuntimeException("历史日期请使用历史补单"); + } + if (!startTime.isAfter(LocalDateTime.now())) { + throw new RuntimeException("预约时间已过,请使用历史补单"); + } + } + + private int resolveShopDefaultDuration(ShopDO shop) { + return shop == null || shop.getDefaultAppointmentDurationMinutes() == null || shop.getDefaultAppointmentDurationMinutes() <= 0 + ? DEFAULT_DURATION_MINUTES : shop.getDefaultAppointmentDurationMinutes(); + } + private LocalDateTime parseAppointmentStart(String appointmentStartTime, String appointmentDate, String appointmentTime) { if (hasText(appointmentStartTime)) { String normalized = appointmentStartTime.trim().replace('T', ' '); @@ -880,10 +906,14 @@ public class PlanningServiceImpl implements PlanningService { } private int resolveDurationMinutes(ProductDO product, Integer overrideMinutes) { + return resolveDurationMinutes(product, overrideMinutes, DEFAULT_DURATION_MINUTES); + } + + private int resolveDurationMinutes(ProductDO product, Integer overrideMinutes, int defaultMinutes) { if (overrideMinutes != null && overrideMinutes > 0) { return overrideMinutes; } - return PlanningCalendarSupport.parseDurationMinutes(product == null ? null : product.getApproximateDuration(), DEFAULT_DURATION_MINUTES); + return PlanningCalendarSupport.parseDurationMinutes(product == null ? null : product.getApproximateDuration(), defaultMinutes); } private boolean isVisibleOrder(OrderDO order, Long shopId) { diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/planning/vo/PlanningCalendarVO.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/planning/vo/PlanningCalendarVO.java index 26f412c1..0370d736 100644 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/planning/vo/PlanningCalendarVO.java +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/planning/vo/PlanningCalendarVO.java @@ -8,6 +8,7 @@ import java.util.List; public class PlanningCalendarVO { private String businessStartTime; private String businessEndTime; + private Integer defaultAppointmentDurationMinutes; private Integer slotMinutes; private List artists; private List schedules; diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/registration/service/impl/WorkbenchRegistrationServiceImpl.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/registration/service/impl/WorkbenchRegistrationServiceImpl.java index 9f018b65..57ec282d 100644 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/registration/service/impl/WorkbenchRegistrationServiceImpl.java +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/registration/service/impl/WorkbenchRegistrationServiceImpl.java @@ -486,7 +486,11 @@ public class WorkbenchRegistrationServiceImpl implements WorkbenchRegistrationSe } private WorkbenchRegistrationStatusVO toStatus(WorkbenchRegistrationApplicationDO application) { - return new WorkbenchRegistrationStatusVO(application.getId(), application.getApplicationNo(), application.getRoleType(), application.getStatus(), application.getRejectReason(), application.getShopId(), application.getShopName()); + ContentModerationRecordDO moderation = application.getContentModerationRecordId() == null + ? null : contentModerationRecordMapper.selectById(application.getContentModerationRecordId()); + return new WorkbenchRegistrationStatusVO(application.getId(), application.getApplicationNo(), application.getRoleType(), + application.getStatus(), application.getRejectReason(), application.getShopId(), application.getShopName(), + moderation == null ? null : moderation.getStatus(), moderation == null ? null : moderation.getReason()); } private WorkbenchRegistrationReviewVO toReviewVO(WorkbenchRegistrationApplicationDO application, UserDO applicant, diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/registration/vo/WorkbenchRegistrationStatusVO.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/registration/vo/WorkbenchRegistrationStatusVO.java index d23342fa..133d0e1c 100644 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/registration/vo/WorkbenchRegistrationStatusVO.java +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/registration/vo/WorkbenchRegistrationStatusVO.java @@ -13,4 +13,6 @@ public class WorkbenchRegistrationStatusVO { private String rejectReason; private Long shopId; private String shopName; + private String contentModerationStatus; + private String contentModerationReason; } diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/shop/dto/ShopAppointmentSettingsDTO.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/shop/dto/ShopAppointmentSettingsDTO.java new file mode 100644 index 00000000..8ea218ea --- /dev/null +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/shop/dto/ShopAppointmentSettingsDTO.java @@ -0,0 +1,9 @@ +package com.xiaowang.jayucloud.salon.core.modules.shop.dto; + +import lombok.Data; + +@Data +public class ShopAppointmentSettingsDTO { + private String businessHours; + private Integer defaultAppointmentDurationMinutes; +} diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/shop/dto/ShopNameUpdateDTO.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/shop/dto/ShopNameUpdateDTO.java new file mode 100644 index 00000000..1c43a3f5 --- /dev/null +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/shop/dto/ShopNameUpdateDTO.java @@ -0,0 +1,8 @@ +package com.xiaowang.jayucloud.salon.core.modules.shop.dto; + +import lombok.Data; + +@Data +public class ShopNameUpdateDTO { + private String shopName; +} diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/shop/entity/ShopDO.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/shop/entity/ShopDO.java index 7b17afe9..1540d7d2 100644 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/shop/entity/ShopDO.java +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/shop/entity/ShopDO.java @@ -76,6 +76,12 @@ public class ShopDO extends BaseEntity { @TableField("business_hours") private String businessHours; + @TableField("appointment_business_hours") + private String appointmentBusinessHours; + + @TableField("default_appointment_duration_minutes") + private Integer defaultAppointmentDurationMinutes; + /** * 店铺封面图文件ID集合(Banner图),多个ID以逗号分隔 */ diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/shop/service/ShopService.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/shop/service/ShopService.java index 75ee4706..43fb26fb 100644 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/shop/service/ShopService.java +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/shop/service/ShopService.java @@ -6,6 +6,9 @@ import com.xiaowang.jayucloud.salon.core.modules.shop.dto.ShopDTO; import com.xiaowang.jayucloud.salon.core.common.vo.PageResultVO; import com.xiaowang.jayucloud.salon.core.modules.shop.vo.ShopTrustProfileVO; import com.xiaowang.jayucloud.salon.core.modules.shop.vo.ShopVO; +import com.xiaowang.jayucloud.salon.core.modules.shop.dto.ShopAppointmentSettingsDTO; +import com.xiaowang.jayucloud.salon.core.modules.shop.dto.ShopNameUpdateDTO; +import com.xiaowang.jayucloud.salon.core.modules.shop.vo.ShopAppointmentSettingsVO; import java.util.List; @@ -51,6 +54,12 @@ public interface ShopService extends IService { */ ShopVO getShopById(Long id); + ShopAppointmentSettingsVO getAppointmentSettings(Long id); + + boolean updateAppointmentSettings(Long id, ShopAppointmentSettingsDTO settings); + + boolean updateShopName(Long id, ShopNameUpdateDTO request); + /** Public shop detail with the approved-content visibility gate applied. */ ShopVO getPublicShopById(Long id); diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/shop/service/impl/ShopServiceImpl.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/shop/service/impl/ShopServiceImpl.java index 646ee44d..de38d8dd 100644 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/shop/service/impl/ShopServiceImpl.java +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/shop/service/impl/ShopServiceImpl.java @@ -7,6 +7,8 @@ import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import com.fasterxml.jackson.core.type.TypeReference; import com.xiaowang.jayucloud.salon.core.config.AppCacheProperties; import com.xiaowang.jayucloud.salon.core.modules.shop.dto.ShopDTO; +import com.xiaowang.jayucloud.salon.core.modules.shop.dto.ShopAppointmentSettingsDTO; +import com.xiaowang.jayucloud.salon.core.modules.shop.dto.ShopNameUpdateDTO; import com.xiaowang.jayucloud.salon.core.modules.order.entity.OrderArtistReviewDO; import com.xiaowang.jayucloud.salon.core.modules.product.entity.ProductDO; import com.xiaowang.jayucloud.salon.core.modules.shop.entity.ShopDO; @@ -34,6 +36,9 @@ import com.xiaowang.jayucloud.salon.core.modules.file.vo.ObjectStorageFileVO; import com.xiaowang.jayucloud.salon.core.common.vo.PageResultVO; import com.xiaowang.jayucloud.salon.core.modules.shop.vo.ShopTrustProfileVO; import com.xiaowang.jayucloud.salon.core.modules.shop.vo.ShopVO; +import com.xiaowang.jayucloud.salon.core.modules.shop.vo.ShopAppointmentSettingsVO; +import com.xiaowang.jayucloud.salon.core.modules.privacy.entity.ContentModerationRecordDO; +import com.xiaowang.jayucloud.salon.core.modules.privacy.mapper.ContentModerationRecordMapper; import lombok.RequiredArgsConstructor; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; @@ -44,6 +49,8 @@ import java.math.RoundingMode; import java.time.Duration; import java.time.LocalDate; import java.time.LocalDateTime; +import java.time.LocalTime; +import java.time.format.DateTimeParseException; import java.util.ArrayList; import java.util.Collections; import java.util.LinkedHashSet; @@ -88,6 +95,7 @@ public class ShopServiceImpl extends ServiceImpl implements * Variable `shopMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. */ private final ShopMapper shopMapper; + private final ContentModerationRecordMapper contentModerationRecordMapper; private final ShopBusinessExpiryService shopBusinessExpiryService; /** * Variable `couponService`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. @@ -208,6 +216,97 @@ public class ShopServiceImpl extends ServiceImpl implements return updated; } + @Override + public ShopAppointmentSettingsVO getAppointmentSettings(Long id) { + ShopDO shop = shopMapper.selectById(id); + if (shop == null || Integer.valueOf(1).equals(shop.getIsDelete())) { + throw new IllegalArgumentException("门店不存在"); + } + ShopAppointmentSettingsVO result = new ShopAppointmentSettingsVO(); + result.setShopName(shop.getShopName()); + ContentModerationRecordDO latestReview = contentModerationRecordMapper.selectOne(Wrappers.lambdaQuery(ContentModerationRecordDO.class) + .eq(ContentModerationRecordDO::getContentType, "SHOP") + .eq(ContentModerationRecordDO::getBusinessId, id) + .eq(ContentModerationRecordDO::getIsDelete, 0) + .orderByDesc(ContentModerationRecordDO::getVersionNo) + .last("limit 1")); + result.setShopNameModerationStatus(latestReview == null ? shop.getModerationStatus() : latestReview.getStatus()); + if (latestReview != null && StringUtils.hasText(latestReview.getPayloadJson())) { + try { + result.setPendingShopName(objectMapper.readTree(latestReview.getPayloadJson()).path("shopName").asText(null)); + } catch (Exception ignored) { + result.setPendingShopName(null); + } + } + result.setBusinessHours(StringUtils.hasText(shop.getAppointmentBusinessHours()) + ? shop.getAppointmentBusinessHours() : shop.getBusinessHours()); + result.setDefaultAppointmentDurationMinutes(shop.getDefaultAppointmentDurationMinutes() == null + || shop.getDefaultAppointmentDurationMinutes() <= 0 ? 60 : shop.getDefaultAppointmentDurationMinutes()); + return result; + } + + @Override + @Transactional(rollbackFor = Exception.class) + public boolean updateAppointmentSettings(Long id, ShopAppointmentSettingsDTO settings) { + if (settings == null) throw new IllegalArgumentException("预约设置不能为空"); + ShopDO shop = shopMapper.selectById(id); + if (shop == null || Integer.valueOf(1).equals(shop.getIsDelete())) { + throw new IllegalArgumentException("门店不存在"); + } + String businessHours = normalizeAppointmentBusinessHours(settings.getBusinessHours()); + Integer duration = settings.getDefaultAppointmentDurationMinutes(); + if (duration == null || duration < 15 || duration > 720) { + throw new IllegalArgumentException("默认预约时长需在15至720分钟之间"); + } + shop.setAppointmentBusinessHours(businessHours); + shop.setDefaultAppointmentDurationMinutes(duration); + return shopMapper.updateById(shop) > 0; + } + + @Override + @Transactional(rollbackFor = Exception.class) + public boolean updateShopName(Long id, ShopNameUpdateDTO request) { + if (request == null || !StringUtils.hasText(request.getShopName())) { + throw new IllegalArgumentException("门店名称不能为空"); + } + ShopDO shop = shopMapper.selectById(id); + if (shop == null || Integer.valueOf(1).equals(shop.getIsDelete())) { + throw new IllegalArgumentException("门店不存在"); + } + ShopDTO profile = new ShopDTO(); + profile.setShopName(request.getShopName().trim()); + profile.setDescription(shop.getDescription()); + profile.setAddress(shop.getAddress()); + profile.setMapProvider(shop.getMapProvider()); + profile.setLongitude(shop.getLongitude()); + profile.setLatitude(shop.getLatitude()); + profile.setBusinessHours(shop.getBusinessHours()); + profile.setCoverImageFileId(shop.getCoverImageFileId()); + profile.setImageFileIds(shop.getImageFileIds()); + profile.setThemePrimaryColor(shop.getThemePrimaryColor()); + profile.setThemeSecondaryColor(shop.getThemeSecondaryColor()); + profile.setThemeAccentColor(shop.getThemeAccentColor()); + profile.setThemePageBgColor(shop.getThemePageBgColor()); + profile.setThemeCardBgColor(shop.getThemeCardBgColor()); + profile.setThemeBackgroundImageFileId(shop.getThemeBackgroundImageFileId()); + submitShopSnapshot(shop, profile); + return true; + } + + private String normalizeAppointmentBusinessHours(String value) { + if (!StringUtils.hasText(value)) throw new IllegalArgumentException("请设置门店营业时间"); + String[] parts = value.trim().split("-"); + if (parts.length != 2) throw new IllegalArgumentException("营业时间格式不正确"); + try { + LocalTime start = LocalTime.parse(parts[0].trim()); + LocalTime end = LocalTime.parse(parts[1].trim()); + if (!start.isBefore(end)) throw new IllegalArgumentException("营业结束时间必须晚于开始时间"); + return start + "-" + end; + } catch (DateTimeParseException exception) { + throw new IllegalArgumentException("营业时间格式不正确,请使用小时和分钟"); + } + } + private boolean updateShopOperationalFields(ShopDO current, ShopDTO dto) { boolean changed = false; if (dto.getStatus() != null) { @@ -226,6 +325,7 @@ public class ShopServiceImpl extends ServiceImpl implements target.setId(source.getId()); target.setShopName(source.getShopName()); target.setDescription(source.getDescription()); target.setAddress(source.getAddress()); target.setMapProvider(source.getMapProvider()); target.setLongitude(source.getLongitude()); target.setLatitude(source.getLatitude()); target.setBusinessHours(source.getBusinessHours()); target.setCoverImageFileId(source.getCoverImageFileId()); + target.setAppointmentBusinessHours(source.getAppointmentBusinessHours()); target.setDefaultAppointmentDurationMinutes(source.getDefaultAppointmentDurationMinutes()); target.setImageFileIds(source.getImageFileIds()); target.setThemePrimaryColor(source.getThemePrimaryColor()); target.setThemeSecondaryColor(source.getThemeSecondaryColor()); target.setThemeAccentColor(source.getThemeAccentColor()); target.setThemePageBgColor(source.getThemePageBgColor()); target.setThemeCardBgColor(source.getThemeCardBgColor()); @@ -903,6 +1003,7 @@ public class ShopServiceImpl extends ServiceImpl implements shopVO.setLatitude(shopDO.getLatitude()); shopVO.setNavigationUrls(mapService.buildNavigationUrls(shopDO.getShopName(), shopDO.getAddress(), shopDO.getLongitude(), shopDO.getLatitude())); shopVO.setBusinessHours(shopDO.getBusinessHours()); + shopVO.setModerationStatus(shopDO.getModerationStatus()); shopVO.setCoverImageFileId(shopDO.getCoverImageFileId()); shopVO.setCoverImageUrls(new java.util.ArrayList<>()); shopVO.setImageFileIds(shopDO.getImageFileIds()); diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/shop/vo/ShopAppointmentSettingsVO.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/shop/vo/ShopAppointmentSettingsVO.java new file mode 100644 index 00000000..2a039666 --- /dev/null +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/shop/vo/ShopAppointmentSettingsVO.java @@ -0,0 +1,12 @@ +package com.xiaowang.jayucloud.salon.core.modules.shop.vo; + +import lombok.Data; + +@Data +public class ShopAppointmentSettingsVO { + private String shopName; + private String shopNameModerationStatus; + private String pendingShopName; + private String businessHours; + private Integer defaultAppointmentDurationMinutes; +} diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/shop/vo/ShopVO.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/shop/vo/ShopVO.java index 34bcb7c4..d3ebbd5b 100644 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/shop/vo/ShopVO.java +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/shop/vo/ShopVO.java @@ -70,6 +70,8 @@ public class ShopVO { */ private String businessHours; + private String moderationStatus; + /** * 店铺封面图文件ID集合(Banner图),多个ID以逗号分隔 */ diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/user/service/UserService.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/user/service/UserService.java index b48332e9..2949fa53 100644 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/user/service/UserService.java +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/user/service/UserService.java @@ -17,6 +17,7 @@ import com.xiaowang.jayucloud.salon.core.common.vo.PageResultVO; import com.xiaowang.jayucloud.salon.core.modules.user.vo.UserStatisticsVO; import com.xiaowang.jayucloud.salon.core.modules.user.vo.UserRelationVO; import com.xiaowang.jayucloud.salon.core.modules.user.vo.UserVO; +import com.xiaowang.jayucloud.salon.core.modules.manager.vo.AppointmentCustomerOptionVO; import java.util.List; @@ -42,6 +43,10 @@ public interface UserService extends IService { List findCustomerMatches(String nickname, String phone, Long shopId); + List findCustomerIdentityMatches(String nickname, String wechatId, String phone, Long shopId); + + PageResultVO listCustomersForAppointment(Integer page, Integer size, String keyword, Long shopId); + /** * Update an existing record. diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/user/service/impl/UserServiceImpl.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/user/service/impl/UserServiceImpl.java index 3e3cb4ca..06a107ef 100644 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/user/service/impl/UserServiceImpl.java +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/user/service/impl/UserServiceImpl.java @@ -57,6 +57,7 @@ import com.xiaowang.jayucloud.salon.core.modules.auth.vo.LoginResponseVO; import com.xiaowang.jayucloud.salon.core.common.vo.PageResultVO; import com.xiaowang.jayucloud.salon.core.modules.shop.vo.ShopSimpleVO; import com.xiaowang.jayucloud.salon.core.modules.user.vo.UserVO; +import com.xiaowang.jayucloud.salon.core.modules.manager.vo.AppointmentCustomerOptionVO; import com.xiaowang.jayucloud.salon.core.modules.shop.vo.ShopVO; import com.xiaowang.jayucloud.salon.core.modules.user.vo.UserRelationVO; import com.xiaowang.jayucloud.salon.core.modules.user.vo.UserStatisticsVO; @@ -606,6 +607,75 @@ public class UserServiceImpl extends ServiceImpl implements }).collect(Collectors.toList()); } + @Override + public List findCustomerIdentityMatches(String nickname, String wechatId, String phone, Long shopId) { + if (!StringUtils.hasText(nickname)) return List.of(); + LambdaQueryWrapper wrapper = Wrappers.lambdaQuery(UserDO.class) + .eq(UserDO::getNickname, nickname.trim()) + .eq(UserDO::getType, 0) + .eq(UserDO::getIsDelete, 0); + applyCustomerShopScope(wrapper, shopId); + String normalizedName = nickname.trim(); + String normalizedWechatId = UserProfileFieldSupport.normalizeOptionalText(wechatId); + String normalizedPhone = StringUtils.hasText(phone) ? phone.trim() : null; + return userMapper.selectList(wrapper).stream() + .filter(user -> Objects.equals(normalizedName, user.getNickname())) + .filter(user -> Objects.equals(normalizedWechatId, UserProfileFieldSupport.normalizeOptionalText(user.getWechatId()))) + .filter(user -> Objects.equals(normalizedPhone, decryptPhone(user.getPhone()))) + .map(user -> { + AppointmentCustomerOptionVO customer = new AppointmentCustomerOptionVO(); + customer.setId(user.getId()); + customer.setName(user.getNickname()); + String contactPhone = decryptPhone(user.getContactPhone()); + customer.setPhone(StringUtils.hasText(contactPhone) ? contactPhone : decryptPhone(user.getPhone())); + customer.setAvatar(resolveAccessibleAvatar(user.getAvatar())); + customer.setCreatedAt(user.getCreateTime()); + return customer; + }).collect(Collectors.toList()); + } + + @Override + public PageResultVO listCustomersForAppointment(Integer page, Integer size, String keyword, Long shopId) { + int safePage = page == null || page < 1 ? 1 : page; + int safeSize = size == null ? 30 : Math.max(1, Math.min(size, 100)); + LambdaQueryWrapper wrapper = Wrappers.lambdaQuery(UserDO.class) + .eq(UserDO::getType, 0) + .eq(UserDO::getIsDelete, 0) + .orderByDesc(UserDO::getCreateTime); + applyCustomerShopScope(wrapper, shopId); + if (StringUtils.hasText(keyword)) { + String search = keyword.trim(); + wrapper.and(query -> { + query.like(UserDO::getNickname, search); + if (search.matches(PHONE_REGEX)) query.or(phoneQuery -> addPhoneMatch(phoneQuery, search)); + }); + } + Page users = userMapper.selectPage(new Page<>(safePage, safeSize), wrapper); + PageResultVO result = new PageResultVO<>(); + result.setList(users.getRecords().stream().map(user -> { + AppointmentCustomerOptionVO option = new AppointmentCustomerOptionVO(); + option.setId(user.getId()); + option.setName(user.getNickname()); + String contactPhone = decryptPhone(user.getContactPhone()); + String phone = StringUtils.hasText(contactPhone) ? contactPhone : decryptPhone(user.getPhone()); + option.setPhone(phone); + option.setAvatar(resolveAccessibleAvatar(user.getAvatar())); + option.setCreatedAt(user.getCreateTime()); + return option; + }).collect(Collectors.toList())); + result.setTotal(users.getTotal()); + result.setPage(safePage); + result.setSize(safeSize); + return result; + } + + private void applyCustomerShopScope(LambdaQueryWrapper wrapper, Long shopId) { + if (shopId == null || shopId <= 0) return; + List shopUserIds = userShopBindingSupport.listUserIdsByShopId(shopId, true); + if (shopUserIds.isEmpty()) wrapper.eq(UserDO::getShopId, shopId); + else wrapper.and(query -> query.eq(UserDO::getShopId, shopId).or().in(UserDO::getId, shopUserIds)); + } + /** * 分配默认权限 * @param userId 用户ID diff --git a/JC-Salon-Core/src/main/resources/db/migration/V10__预约运营设置和客户选择_20261030.sql b/JC-Salon-Core/src/main/resources/db/migration/V10__预约运营设置和客户选择_20261030.sql new file mode 100644 index 00000000..a6ba4104 --- /dev/null +++ b/JC-Salon-Core/src/main/resources/db/migration/V10__预约运营设置和客户选择_20261030.sql @@ -0,0 +1,35 @@ +SET @column_exists = ( + SELECT COUNT(1) + FROM information_schema.columns + WHERE table_schema = DATABASE() + AND table_name = 't_shop' + AND column_name = 'appointment_business_hours' +); +SET @migration_sql = IF( + @column_exists = 0, + 'ALTER TABLE t_shop ADD COLUMN appointment_business_hours VARCHAR(20) NULL COMMENT ''预约运营营业时间'' AFTER business_hours', + 'SELECT 1' +); +PREPARE migration_statement FROM @migration_sql; +EXECUTE migration_statement; +DEALLOCATE PREPARE migration_statement; + +SET @column_exists = ( + SELECT COUNT(1) + FROM information_schema.columns + WHERE table_schema = DATABASE() + AND table_name = 't_shop' + AND column_name = 'default_appointment_duration_minutes' +); +SET @migration_sql = IF( + @column_exists = 0, + 'ALTER TABLE t_shop ADD COLUMN default_appointment_duration_minutes INT NOT NULL DEFAULT 60 COMMENT ''默认预约服务时长(分钟)'' AFTER business_hours', + 'SELECT 1' +); +PREPARE migration_statement FROM @migration_sql; +EXECUTE migration_statement; +DEALLOCATE PREPARE migration_statement; + +UPDATE t_shop +SET default_appointment_duration_minutes = 60 +WHERE default_appointment_duration_minutes IS NULL OR default_appointment_duration_minutes <= 0; diff --git a/JC-Salon-Core/src/test/java/com/xiaowang/jayucloud/salon/core/modules/planning/service/impl/PlanningServiceImplTest.java b/JC-Salon-Core/src/test/java/com/xiaowang/jayucloud/salon/core/modules/planning/service/impl/PlanningServiceImplTest.java index 5dca8565..70abe1a6 100644 --- a/JC-Salon-Core/src/test/java/com/xiaowang/jayucloud/salon/core/modules/planning/service/impl/PlanningServiceImplTest.java +++ b/JC-Salon-Core/src/test/java/com/xiaowang/jayucloud/salon/core/modules/planning/service/impl/PlanningServiceImplTest.java @@ -193,7 +193,7 @@ class PlanningServiceImplTest { PlanningAppointmentCreateDTO dto = new PlanningAppointmentCreateDTO(); dto.setCustomerUserId(31L); dto.setProductId(41L); - dto.setAppointmentDate("2026-10-13"); + dto.setAppointmentDate(java.time.LocalDate.now().plusDays(2).toString()); dto.setAppointmentTime("14:00"); dto.setDurationMinutes(60); @@ -240,7 +240,7 @@ class PlanningServiceImplTest { dto.setCreateCustomerRecord(false); dto.setManualProductImageFileIds("file-42"); dto.setAmount(java.math.BigDecimal.valueOf(168)); - dto.setAppointmentDate("2026-10-22"); + dto.setAppointmentDate(java.time.LocalDate.now().plusDays(2).toString()); dto.setAppointmentTime("14:00"); dto.setDurationMinutes(60); @@ -297,7 +297,7 @@ class PlanningServiceImplTest { dto.setCreateCustomerRecord(false); dto.setManualProductImageFileIds("file-43"); dto.setAmount(java.math.BigDecimal.valueOf(88)); - dto.setAppointmentDate("2026-10-22"); + dto.setAppointmentDate(java.time.LocalDate.now().plusDays(2).toString()); dto.setAppointmentTime("14:00"); dto.setDurationMinutes(45); @@ -361,8 +361,8 @@ class PlanningServiceImplTest { when(adminScopeHelper.resolveShopScope(operator, null)).thenReturn(21L); when(productMapper.selectById(41L)).thenReturn(product); when(userMapper.selectById(71L)).thenReturn(customer); - when(userService.findCustomerMatches("小周", "13800138000", 21L)).thenReturn(java.util.List.of()); - when(userService.createManagerCustomer("小周", "13800138000", 21L)).thenReturn(71L); + when(userService.findCustomerIdentityMatches("小周", null, "13800138000", 21L)).thenReturn(java.util.List.of()); + when(userService.createManagerCustomer("小周", null, "13800138000", 21L)).thenReturn(71L); when(shopMapper.selectById(21L)).thenReturn(shop); when(snowflakeIdGenerator.nextIdString()).thenReturn("10004"); doAnswer(invocation -> { @@ -384,13 +384,13 @@ class PlanningServiceImplTest { dto.setCreateCustomerRecord(true); dto.setProductId(41L); dto.setAmount(java.math.BigDecimal.valueOf(128)); - dto.setAppointmentDate("2026-10-22"); + dto.setAppointmentDate(java.time.LocalDate.now().plusDays(2).toString()); dto.setAppointmentTime("14:00"); dto.setDurationMinutes(60); service.createAppointment(operator, dto); - verify(userService).createManagerCustomer("小周", "13800138000", 21L); + verify(userService).createManagerCustomer("小周", null, "13800138000", 21L); ArgumentCaptor orderCaptor = ArgumentCaptor.forClass(OrderDO.class); verify(orderMapper).insert(orderCaptor.capture()); assertEquals(71L, orderCaptor.getValue().getUserId()); diff --git a/JC-Salon-Core/src/test/java/com/xiaowang/jayucloud/salon/core/modules/user/service/impl/UserServiceCustomerMatchingTest.java b/JC-Salon-Core/src/test/java/com/xiaowang/jayucloud/salon/core/modules/user/service/impl/UserServiceCustomerMatchingTest.java index 02c3d468..980920d0 100644 --- a/JC-Salon-Core/src/test/java/com/xiaowang/jayucloud/salon/core/modules/user/service/impl/UserServiceCustomerMatchingTest.java +++ b/JC-Salon-Core/src/test/java/com/xiaowang/jayucloud/salon/core/modules/user/service/impl/UserServiceCustomerMatchingTest.java @@ -73,4 +73,26 @@ class UserServiceCustomerMatchingTest { () -> ensureUnique.invoke(userService, "周女士", "wx-existing", "13800138000", null)); assertEquals("客户已存在,请选择已有客户", duplicate.getCause().getMessage()); } + + @Test + void appointmentIdentityLookupReturnsOnlyExactTupleAndFullPhone() { + UserDO existing = new UserDO(); + existing.setId(92L); + existing.setNickname("周女士"); + existing.setWechatId("wx-zhou"); + existing.setPhone("encrypted-phone"); + existing.setType(0); + existing.setIsDelete(0); + when(userMapper.selectList(any(Wrapper.class))).thenReturn(List.of(existing)); + when(phoneCrypto.decrypt("encrypted-phone")).thenReturn("13800138000"); + + List matches = + userService.findCustomerIdentityMatches("周女士", "wx-zhou", "13800138000", null); + List wrongWechat = + userService.findCustomerIdentityMatches("周女士", "wx-another", "13800138000", null); + + assertEquals(1, matches.size()); + assertEquals("13800138000", matches.get(0).getPhone()); + assertTrue(wrongWechat.isEmpty()); + } } diff --git a/JC-Salon-WeChat/api/customers.js b/JC-Salon-WeChat/api/customers.js index 8d4c25cd..c76e2c53 100644 --- a/JC-Salon-WeChat/api/customers.js +++ b/JC-Salon-WeChat/api/customers.js @@ -8,6 +8,17 @@ module.exports = { }) }, + listForAppointment(params) { + return request({ + url: '/manager/customers/appointment-options', + params + }) + }, + + matchIdentityForAppointment(nickname, wechatId, phone) { + return request({ url: '/manager/customers/identity-matches', params: { nickname, wechatId, phone } }) + }, + detail(id) { return request({ url: `/manager/customers/${id}` @@ -21,6 +32,20 @@ module.exports = { }) }, + matchExactIdentity(nickname, wechatId, phone) { + return request({ + url: '/manager/customers/identity-matches', + params: { nickname, wechatId, phone } + }) + }, + + appointmentOptions(params) { + return request({ + url: '/manager/customers/appointment-options', + params + }) + }, + create(data) { return request({ url: '/manager/customers', diff --git a/JC-Salon-WeChat/api/shop.js b/JC-Salon-WeChat/api/shop.js index 52a8542f..a06d40ce 100644 --- a/JC-Salon-WeChat/api/shop.js +++ b/JC-Salon-WeChat/api/shop.js @@ -15,6 +15,18 @@ module.exports = { }) }, + appointmentSettings() { + return request({ url: '/manager/shop/appointment-settings' }) + }, + + saveAppointmentSettings(data) { + return request({ url: '/manager/shop/appointment-settings', method: 'PUT', data }) + }, + + updateName(shopName) { + return request({ url: '/manager/shop/name', method: 'PUT', data: { shopName } }) + }, + exportData(params) { return request({ url: '/export', diff --git a/JC-Salon-WeChat/pages/account-settings/index.js b/JC-Salon-WeChat/pages/account-settings/index.js index ce14e22c..750d7796 100644 --- a/JC-Salon-WeChat/pages/account-settings/index.js +++ b/JC-Salon-WeChat/pages/account-settings/index.js @@ -14,17 +14,22 @@ Page({ timer: null, smsExpanded: false, unbindMode: false, - closureRequest: null + closureRequest: null, + closureLoading: true, + closureError: '' }, onShow() { this.loadProfile(); this.loadClosureRequest() }, async loadClosureRequest() { + this.setData({ closureLoading: true, closureError: '' }) try { const closureRequest = await userApi.getAccountClosure() this.setData({ closureRequest: closureRequest || null }) } catch (error) { - this.setData({ closureRequest: null }) + this.setData({ closureError: error.message || '注销状态加载失败' }) + } finally { + this.setData({ closureLoading: false }) } }, @@ -62,7 +67,7 @@ Page({ this.setData({ loading: true }) try { const profile = await profileCache.getProfile(options) - this.setData({ profile, 'smsForm.phone': profile.phone || '' }) + this.setData({ profile, 'smsForm.phone': '' }) const app = getApp() const session = auth.getSession() app.setSession({ ...session, userInfo: { ...(session.userInfo || {}), ...profile } }) diff --git a/JC-Salon-WeChat/pages/account-settings/index.test.js b/JC-Salon-WeChat/pages/account-settings/index.test.js index 06ea929a..9bfeed6a 100644 --- a/JC-Salon-WeChat/pages/account-settings/index.test.js +++ b/JC-Salon-WeChat/pages/account-settings/index.test.js @@ -13,6 +13,7 @@ global.getApp = () => ({ setSession: () => {} }) const profileCache = require('../../utils/profile-cache') profileCache.getProfile = async () => currentProfile +const userApi = require('../../api/user') require('./index') async function loadProfile(profile) { @@ -47,6 +48,18 @@ async function run() { shopBusinessRemainingDays: 66 }) assert.strictEqual(active.profile.shopBusinessExpireTime, '2026-12-31T23:59:59') + + userApi.getAccountClosure = async () => { throw new Error('注销状态暂时无法读取') } + const closurePage = { + data: { ...pageDefinition.data }, + setData(values) { Object.assign(this.data, values) } + } + await pageDefinition.loadClosureRequest.call(closurePage) + assert.strictEqual(closurePage.data.closureError, '注销状态暂时无法读取') + assert.strictEqual(closurePage.data.closureLoading, false) + const accountWxml = require('fs').readFileSync(require('path').join(__dirname, 'index.wxml'), 'utf8') + assert(accountWxml.includes('closureError')) + assert(accountWxml.includes('bindtap="loadClosureRequest"')) } run().catch(error => { diff --git a/JC-Salon-WeChat/pages/account-settings/index.wxml b/JC-Salon-WeChat/pages/account-settings/index.wxml index eccf4059..2a17fd95 100644 --- a/JC-Salon-WeChat/pages/account-settings/index.wxml +++ b/JC-Salon-WeChat/pages/account-settings/index.wxml @@ -19,12 +19,16 @@ 账号注销 - 申请处理中,{{closureRequest.processingTargetText || '以管理人员审核和门店交接进度为准'}} - 账号资料已完成清理。 - 上次申请未通过:{{closureRequest.reviewerNote || '请联系管理人员'}} - 可申请注销工作台账号。提交后可在管理人员处理前撤回。 - - + 正在读取注销申请状态… + {{closureError}} + + 申请处理中,{{closureRequest.processingTargetText || '以管理人员审核和门店交接进度为准'}} + 账号资料已完成清理。 + 上次申请未通过:{{closureRequest.reviewerNote || '请联系管理人员'}} + 可申请注销工作台账号。提交后可在管理人员处理前撤回。 + + + diff --git a/JC-Salon-WeChat/pages/account-settings/index.wxss b/JC-Salon-WeChat/pages/account-settings/index.wxss index e5a31a34..b2830890 100644 --- a/JC-Salon-WeChat/pages/account-settings/index.wxss +++ b/JC-Salon-WeChat/pages/account-settings/index.wxss @@ -14,3 +14,5 @@ .closure-card { margin-top: 20rpx; padding: 28rpx; } .closure-btn { height: 76rpx; margin-top: 18rpx; border-radius: 12rpx; background: #fff1ef; color: #9a5147; font-size: 24rpx; line-height: 76rpx; } .closure-btn.secondary { background: #eef4f0; color: #426c57; } +.closure-error { color: #a24f42; } +.closure-retry { display: inline-block; margin: 0 0 0 12rpx; padding: 0; background: transparent; color: #397055; font-size: 22rpx; line-height: 1.6; } diff --git a/JC-Salon-WeChat/pages/appointment-form/entity-selector.test.js b/JC-Salon-WeChat/pages/appointment-form/entity-selector.test.js index f503979e..a09e6503 100644 --- a/JC-Salon-WeChat/pages/appointment-form/entity-selector.test.js +++ b/JC-Salon-WeChat/pages/appointment-form/entity-selector.test.js @@ -48,7 +48,7 @@ async function run() { assert.strictEqual(page.data.form.customerName, '新客户') assert.strictEqual(page.data.form.phone, '13800138000') - customersApi.matchIdentity = async () => [] + customersApi.matchIdentityForAppointment = async () => [] customersApi.create = async () => { throw new Error('预约客户建档应随预约请求提交') } assert.strictEqual(await page.ensureCustomerBeforeSubmit(), true) assert.strictEqual(page.data.form.customerUserId, '') @@ -57,10 +57,11 @@ async function run() { page.data.form.customerUserId = '' page.data.form.customerName = '小周' page.data.form.phone = '13800138000' - customersApi.matchIdentity = async (name, phone) => { + customersApi.matchIdentityForAppointment = async (name, wechatId, phone) => { assert.strictEqual(name, '小周') + assert.strictEqual(wechatId, undefined) assert.strictEqual(phone, '13800138000') - return [{ id: '18', nickname: '小周', phone: '13800138000' }] + return [{ id: '18', name: '小周', phone: '13800138000' }] } assert.strictEqual(await page.ensureCustomerBeforeSubmit(), true) assert.strictEqual(page.data.form.customerUserId, '18') diff --git a/JC-Salon-WeChat/pages/appointment-form/index.js b/JC-Salon-WeChat/pages/appointment-form/index.js index 993c1bc7..bf0cb952 100644 --- a/JC-Salon-WeChat/pages/appointment-form/index.js +++ b/JC-Salon-WeChat/pages/appointment-form/index.js @@ -211,6 +211,11 @@ function buildAvailableTimeGroups(calendar, form, durationMinutes) { .filter(item => item.date === form.appointmentDate) .filter(item => item.status === 1 && Number(item.capacity === undefined ? 1 : item.capacity) >= 1) const busyRanges = buildBusyRanges(calendar.appointments || [], form) + const today = dateUtil.formatDate(new Date()) + const now = new Date() + const currentMinute = now.getHours() * 60 + now.getMinutes() + const businessStart = dateUtil.minutesOfDay(calendar.businessStartTime || '10:00') + const businessEnd = dateUtil.minutesOfDay(calendar.businessEndTime || '22:00') const groupMap = { morning: { key: 'morning', title: '上午', times: [] }, afternoon: { key: 'afternoon', title: '下午', times: [] }, @@ -220,6 +225,8 @@ function buildAvailableTimeGroups(calendar, form, durationMinutes) { const scheduleStart = dateUtil.minutesOfDay(extractTimeText(schedule.startTime)) const scheduleEnd = dateUtil.minutesOfDay(extractTimeText(schedule.endTime)) for (let minute = scheduleStart; minute + durationMinutes <= scheduleEnd; minute += TIME_SLOT_MINUTES) { + if (minute < businessStart || minute + durationMinutes > businessEnd) continue + if (form.appointmentDate < today || (form.appointmentDate === today && minute <= currentMinute)) continue const endMinute = minute + durationMinutes if (!hasBusyConflict(minute, endMinute, busyRanges)) { const period = getTimePeriod(minute) @@ -238,19 +245,25 @@ function buildAvailableTimeGroups(calendar, form, durationMinutes) { .filter(group => group.times.length > 0) } -function buildUnassignedTimeGroups(durationMinutes) { +function buildUnassignedTimeGroups(durationMinutes, businessStart = '10:00', businessEnd = '22:00', appointmentDate) { 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 start = dateUtil.minutesOfDay(businessStart) + const end = dateUtil.minutesOfDay(businessEnd) + const now = new Date() + const today = dateUtil.formatDate(now) + const currentMinute = now.getHours() * 60 + now.getMinutes() + for (let minute = start; minute + durationMinutes <= end; minute += TIME_SLOT_MINUTES) { + if (appointmentDate && appointmentDate < today) continue const period = getTimePeriod(minute) groupMap[period.key].times.push({ value: dateUtil.timeFromMinutes(minute), - rangeText: buildTimeRangeLabel(minute, durationMinutes) + rangeText: buildTimeRangeLabel(minute, durationMinutes), + status: appointmentDate === today && minute <= currentMinute ? 'past' : 'available', + statusText: appointmentDate === today && minute <= currentMinute ? '已过时' : '' }) } return Object.keys(groupMap).map(key => groupMap[key]).filter(group => group.times.length > 0) @@ -260,12 +273,16 @@ function flattenTimeGroups(groups) { return (groups || []).reduce((list, group) => list.concat(group.times || []), []) } -function buildTimeValues(durationMinutes) { +function buildTimeValues(durationMinutes, businessStart = '10:00', businessEnd = '22:00', appointmentDate) { const values = [] - const open = dateUtil.minutesOfDay('10:00') - const close = dateUtil.minutesOfDay('22:00') + const open = dateUtil.minutesOfDay(businessStart) + const close = dateUtil.minutesOfDay(businessEnd) + const now = new Date() + const today = dateUtil.formatDate(now) + const currentMinute = now.getHours() * 60 + now.getMinutes() for (let minute = open; minute + durationMinutes <= close; minute += TIME_SLOT_MINUTES) { - values.push(dateUtil.timeFromMinutes(minute)) + if (appointmentDate && appointmentDate < today) continue + values.push({ value: dateUtil.timeFromMinutes(minute), past: appointmentDate === today && minute <= currentMinute }) } return values } @@ -273,21 +290,25 @@ function buildTimeValues(durationMinutes) { function buildTimePickerSlots(calendar, form, durationMinutes) { const schedules = calendar.schedules || [] const busyRanges = form.artistId ? buildBusyRanges(calendar.appointments || [], form) : [] - return buildTimeValues(durationMinutes).map(value => { + const businessHours = String(calendar.businessHours || '10:00-22:00').split('-') + const businessStart = calendar.businessStartTime || businessHours[0] || '10:00' + const businessEnd = calendar.businessEndTime || businessHours[1] || '22:00' + return buildTimeValues(durationMinutes, businessStart, businessEnd, form.appointmentDate).map(time => { + const value = time.value const startMinute = dateUtil.minutesOfDay(value) const endMinute = startMinute + durationMinutes const occupied = hasBusyConflict(startMinute, endMinute, busyRanges) const scheduled = !form.artistId || schedules.some(schedule => isScheduleCoveringTime(schedule, form, startMinute, endMinute) ) - const status = occupied ? 'occupied' : scheduled ? 'available' : 'off-shift' + const status = time.past ? 'past' : occupied ? 'occupied' : scheduled ? 'available' : 'off-shift' return { value, hour: Number(value.slice(0, 2)), minute: Number(value.slice(3, 5)), rangeText: buildTimeRangeLabel(startMinute, durationMinutes), status, - statusText: status === 'occupied' ? '已占用' : status === 'off-shift' ? '无排班' : '' + statusText: status === 'past' ? '已过时' : status === 'occupied' ? '已占用' : status === 'off-shift' ? '无排班' : '' } }) } @@ -484,6 +505,7 @@ Page({ manualProductImageUrl: '', manualProductImages: [], durationMinutes: '60', + wechatId: '', artistId: '', createCustomerRecord: false, remark: '' @@ -491,6 +513,10 @@ Page({ unifiedStyleDescription: '', customerOptions: [], customerDirectory: [], + businessStartTime: '10:00', + businessEndTime: '22:00', + defaultAppointmentDurationMinutes: 60, + durationManuallyChanged: false, customerSheetVisible: false, customerKeyword: '', customerViewMode: 'list', @@ -540,6 +566,12 @@ Page({ }, onLoad(options) { + const today = dateUtil.formatDate(new Date()) + if (options && options.date && options.date < today) { + this._pendingHistoricalArtistId = options.artistId || '' + this.showBackfillPrompt(options.date, '所选日期已经过去') + return + } const creatable = canCreateAppointment() const draftForm = creatable && !hasPresetOptions(options) ? readDraftForm() : null const baseForm = draftForm || {} @@ -559,6 +591,7 @@ Page({ appointmentDate, artistId: options.artistId || baseForm.artistId || '' }, + durationManuallyChanged: Boolean(baseForm.durationMinutes && !baseForm.productId), manualProductTitleLength: String(baseForm.manualProductTitle || '').length, unifiedStyleDescription: String(baseForm.remark || baseForm.manualProductDescription || ''), draftSavedAtText: draftForm ? '已恢复本机草稿' : '', @@ -617,6 +650,8 @@ Page({ endDate: this.data.form.appointmentDate }) let artists = getCalendarArtists(calendar) + const hours = String(calendar.businessHours || '10:00-22:00').split('-') + const defaultDuration = Number(calendar.defaultAppointmentDurationMinutes) || 60 const requestedId = preferredArtistId || this.data.form.artistId if (fallbackEmployee && requestedId && !findArtist(artists, requestedId).id) { artists = artists.concat({ @@ -629,6 +664,12 @@ Page({ ? findArtist(artists, requestedId) : unassignedSelection this.setData({ + businessStartTime: calendar.businessStartTime || hours[0] || '10:00', + businessEndTime: calendar.businessEndTime || hours[1] || '22:00', + defaultAppointmentDurationMinutes: defaultDuration, + ...(!this.data.durationManuallyChanged && !this.data.form.productId && !this.data.form.appointmentTime + ? { 'form.durationMinutes': String(defaultDuration) } + : {}), artists, artistSelectorItems: this.filterArtistItems(artists, this.data.artistKeyword), selectedArtist, @@ -657,7 +698,7 @@ Page({ let page = 1 let total = Number.POSITIVE_INFINITY while (rows.length < total) { - const result = await customersApi.list({ page, size }) + const result = await customersApi.listForAppointment({ page, size }) const currentRows = Array.isArray(result) ? result : (result.list || []) rows.push(...currentRows) if (!Array.isArray(result) && Number.isFinite(Number(result.total))) { @@ -697,6 +738,7 @@ Page({ } this.setData(patch) if (field === 'durationMinutes') { + this.setData({ durationManuallyChanged: true }) this.refreshAvailableTimes() this.checkAvailability() } @@ -763,7 +805,7 @@ Page({ clearTimeout(this._suggestionTimer) this._suggestionTimer = setTimeout(async () => { try { - const result = await customersApi.list({ page: 1, size: 50, keyword: name || phone }) + const result = await customersApi.listForAppointment({ page: 1, size: 50, keyword: name || phone }) if (requestSeq !== this._customerSuggestionSeq) return const rows = Array.isArray(result) ? result : (result.list || []) const remoteSuggestions = rows.map(normalizeCustomer) @@ -786,7 +828,7 @@ Page({ this.setData({ 'form.customerUserId': customer.id, 'form.customerName': customer.name, - 'form.phone': customer.phone, + 'form.phone': customer.phone || '', 'form.createCustomerRecord': false, customerSuggestions: [], customerSheetVisible: false, @@ -847,7 +889,7 @@ Page({ this.setData({ 'form.customerUserId': customer.id, 'form.customerName': customer.name, - 'form.phone': customer.phone, + 'form.phone': customer.phone || '', 'form.createCustomerRecord': false, customerSheetVisible: false, customerKeyword: '', @@ -1021,7 +1063,8 @@ Page({ 'form.manualProductImageUrl': '', 'form.manualProductImages': [], 'form.amount': selectedProduct.price === undefined || selectedProduct.price === null ? '' : String(selectedProduct.price), - 'form.durationMinutes': String(selectedDuration || this.data.form.durationMinutes || '') + 'form.durationMinutes': String(selectedDuration || this.data.defaultAppointmentDurationMinutes || 60), + durationManuallyChanged: false }) this.closeProductModal() this.refreshAvailableTimes() @@ -1219,17 +1262,30 @@ Page({ return } if (!form.artistId) { - const availableTimeGroups = buildUnassignedTimeGroups(durationMinutes) - const timePickerSlots = buildTimePickerSlots({ schedules: [], appointments: [] }, form, durationMinutes) - this.setData({ - availableTimeGroups, - timePickerSlots, - timePickerGroups: buildTimePickerGroups(timePickerSlots), - ...buildTimeWheelState(timePickerSlots, form.appointmentTime), - timeError: '', - timeLoading: false, - timeSelectTip: '请选择预约时间,美甲师可稍后分配' - }) + this.setData({ timeLoading: true, timeError: '', timeSelectTip: '正在加载营业时间...' }) + try { + const calendar = await planningApi.calendar({ startDate: form.appointmentDate, endDate: form.appointmentDate }) + if (requestSeq !== this._availableTimeRequestSeq) return + const hours = String(calendar.businessHours || `${this.data.businessStartTime}-${this.data.businessEndTime}`).split('-') + const businessStartTime = calendar.businessStartTime || hours[0] || '10:00' + const businessEndTime = calendar.businessEndTime || hours[1] || '22:00' + this.setData({ businessStartTime, businessEndTime }) + const availableTimeGroups = buildUnassignedTimeGroups(durationMinutes, businessStartTime, businessEndTime, form.appointmentDate) + const timePickerSlots = buildTimePickerSlots(calendar, form, durationMinutes) + this.setData({ + availableTimeGroups, + timePickerSlots, + timePickerGroups: buildTimePickerGroups(timePickerSlots), + ...buildTimeWheelState(timePickerSlots, form.appointmentTime), + timeError: '', + timeLoading: false, + timeSelectTip: availableTimeGroups.length ? '请选择预约时间,美甲师可稍后分配' : '当前日期没有可选时段' + }) + } catch (error) { + if (requestSeq === this._availableTimeRequestSeq) { + this.setData({ availableTimeGroups: [], timePickerSlots: [], timePickerGroups: [], timeError: error.message || '营业时间加载失败', timeLoading: false, timeSelectTip: '营业时间加载失败' }) + } + } return } this.setData({ @@ -1293,6 +1349,10 @@ Page({ const value = event.currentTarget.dataset.value const slot = this.data.timePickerSlots.find(item => item.value === value) if (!slot || slot.status !== 'available') { + if (slot && slot.status === 'past') { + this.showBackfillPrompt(this.data.form.appointmentDate, '所选时段已经过去') + return + } wx.showToast({ title: slot && slot.status === 'occupied' ? '该时间已被占用' : '该时间不可预约', icon: 'none' }) return } @@ -1326,6 +1386,10 @@ Page({ const candidate = this.data.selectedTimeCandidate const slot = this.data.timePickerSlots.find(item => item.value === candidate) if (!slot || slot.status !== 'available') { + if (slot && slot.status === 'past') { + this.showBackfillPrompt(this.data.form.appointmentDate, '所选时段已经过去') + return + } wx.showToast({ title: slot && slot.status === 'occupied' ? '该时间已被占用' : '该时间不可预约', icon: 'none' }) return } @@ -1342,6 +1406,22 @@ Page({ }) }, + async showBackfillPrompt(serviceDate, reason = '该日期或时段已过去') { + const result = await new Promise(resolve => wx.showModal({ + title: '转为历史补单', + content: `${reason},普通预约不能使用过去时间。可以前往补录历史订单,或取消继续选择未来时间。`, + cancelText: '取消', + confirmText: '去补录', + success: resolve, + fail: () => resolve({ confirm: false }) + })) + if (!result.confirm) return + const query = [`serviceDate=${encodeURIComponent(serviceDate || dateUtil.formatDate(new Date()))}`] + const artistId = this.data.form.artistId || this._pendingHistoricalArtistId + if (artistId) query.push(`artistId=${encodeURIComponent(artistId)}`) + wx.navigateTo({ url: `/pages/backfill-order/index?${query.join('&')}` }) + }, + async checkAvailability(candidateTime) { const form = this.data.form const appointmentTime = candidateTime || form.appointmentTime @@ -1356,8 +1436,15 @@ Page({ } const startMinute = dateUtil.minutesOfDay(appointmentTime) const endMinute = startMinute + durationMinutes - if (startMinute < dateUtil.minutesOfDay('10:00') || endMinute > dateUtil.minutesOfDay('22:00')) { - const tip = '该时间超出营业时间 10:00-22:00' + if (startMinute < dateUtil.minutesOfDay(this.data.businessStartTime) || endMinute > dateUtil.minutesOfDay(this.data.businessEndTime)) { + const tip = `该时间超出营业时间 ${this.data.businessStartTime}-${this.data.businessEndTime}` + this.setData({ conflictTip: tip, conflictLevel: 'danger' }) + return { ok: false, tip } + } + const now = new Date() + const today = dateUtil.formatDate(now) + if (form.appointmentDate < today || (form.appointmentDate === today && startMinute <= now.getHours() * 60 + now.getMinutes())) { + const tip = '该时间已过,请改选未来时段或使用历史补单' this.setData({ conflictTip: tip, conflictLevel: 'danger' }) return { ok: false, tip } } @@ -1406,7 +1493,13 @@ Page({ async ensureCustomerBeforeSubmit() { const name = String(this.data.form.customerName || '').trim() const phone = String(this.data.form.phone || '').trim() - if (!name && !phone) { + const wechatId = String(this.data.form.wechatId || '').trim() + if (!name && (phone || wechatId)) { + this.setData({ 'form.createCustomerRecord': false }) + wx.showToast({ title: '填写联系方式时请同时填写客户姓名', icon: 'none' }) + return false + } + if (!name) { this.setData({ 'form.createCustomerRecord': false }) return true } @@ -1425,7 +1518,7 @@ Page({ this.setData({ loading: true }) try { - const matches = await customersApi.matchIdentity(name, phone || undefined) + const matches = await customersApi.matchIdentityForAppointment(name, wechatId || undefined, phone || undefined) if (matches.length > 1) { const choice = await new Promise(resolve => { wx.showModal({ @@ -1506,6 +1599,13 @@ Page({ return } let form = this.data.form + const today = dateUtil.formatDate(new Date()) + const now = new Date() + const selectedMinute = form.appointmentTime ? dateUtil.minutesOfDay(form.appointmentTime) : -1 + if (form.appointmentDate < today || (form.appointmentDate === today && selectedMinute <= now.getHours() * 60 + now.getMinutes())) { + await this.showBackfillPrompt(form.appointmentDate, form.appointmentDate < today ? '所选日期已经过去' : '所选时段已经过去') + return + } const manualProductTitle = String(form.manualProductTitle || '').trim() const manualProductImageFileIds = String(form.manualProductImageFileIds || '').trim() const hasManualProduct = Boolean(manualProductTitle || manualProductImageFileIds || String(form.customerName || '').trim()) @@ -1561,6 +1661,7 @@ Page({ customerUserId: form.customerUserId ? String(form.customerUserId) : undefined, artistId: form.artistId ? String(form.artistId) : undefined, customerName: String(form.customerName || '').trim() || undefined, + wechatId: String(form.wechatId || '').trim() || undefined, phone: String(form.phone || '').trim() || undefined, amount, createCustomerRecord: Boolean(form.createCustomerRecord), diff --git a/JC-Salon-WeChat/pages/appointment-form/index.wxml b/JC-Salon-WeChat/pages/appointment-form/index.wxml index b1a5f8ad..84a3d2c6 100644 --- a/JC-Salon-WeChat/pages/appointment-form/index.wxml +++ b/JC-Salon-WeChat/pages/appointment-form/index.wxml @@ -60,11 +60,12 @@ - 客户可留空,留空时系统会生成临时客户以便报表查询 + 客户可留空,留空时按散客记录且不新建客户档案 + @@ -140,7 +141,7 @@ {{timeError}} {{item.label}}{{item.label}} - {{selectedTimeCandidate || '请选择时间'}} · 已被占用 · 当前无排班 + {{selectedTimeCandidate || '请选择时间'}} · 已被占用 · 已过时 · 当前无排班 {{item.title}}{{time.value}}{{time.statusText || time.rangeText}} diff --git a/JC-Salon-WeChat/pages/appointment-form/index.wxss b/JC-Salon-WeChat/pages/appointment-form/index.wxss index ebdace43..f6209a64 100644 --- a/JC-Salon-WeChat/pages/appointment-form/index.wxss +++ b/JC-Salon-WeChat/pages/appointment-form/index.wxss @@ -910,11 +910,12 @@ button.full{ display: grid; min-width: 0; flex: 1; - grid-template-columns: minmax(0, 1.2fr) minmax(0, 1fr); + grid-template-columns: minmax(0, 1.15fr) minmax(0, 1fr) minmax(0, 1.1fr); gap: 12rpx; } .customer-entry .customer-name-input, +.customer-entry .customer-wechat-input, .customer-entry .customer-phone-input { box-sizing: border-box; width: 100%; @@ -1387,7 +1388,7 @@ button.manual-style-add-image { } .customer-fields { - grid-template-columns: minmax(0, 1fr) minmax(0, 0.9fr); + grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 8rpx; } diff --git a/JC-Salon-WeChat/pages/appointment-form/unassigned.test.js b/JC-Salon-WeChat/pages/appointment-form/unassigned.test.js index 34897154..77ac8e75 100644 --- a/JC-Salon-WeChat/pages/appointment-form/unassigned.test.js +++ b/JC-Salon-WeChat/pages/appointment-form/unassigned.test.js @@ -38,6 +38,10 @@ function createPage() { } async function run() { + const tomorrow = new Date() + tomorrow.setDate(tomorrow.getDate() + 2) + const futureDate = `${tomorrow.getFullYear()}-${String(tomorrow.getMonth() + 1).padStart(2, '0')}-${String(tomorrow.getDate()).padStart(2, '0')}` + planningApi.calendar = async () => ({ businessStartTime: '09:30', businessEndTime: '18:00', artists: [], schedules: [], appointments: [] }) const appointmentWxml = fs.readFileSync(path.join(__dirname, 'index.wxml'), 'utf8') const appointmentWxss = fs.readFileSync(path.join(__dirname, 'index.wxss'), 'utf8') assert.match(appointmentWxml, /已选择暂不分配美甲师/) @@ -60,7 +64,7 @@ async function run() { customerName: '测试客户', phone: '13800138000', productId: '41', - appointmentDate: '2026-10-13', + appointmentDate: futureDate, appointmentTime: '14:00', amount: '120', durationMinutes: '60', @@ -69,6 +73,7 @@ async function run() { await page.refreshAvailableTimes() assert.strictEqual(page.data.availableTimeGroups.length > 0, true) + assert.strictEqual(page.data.availableTimeGroups[0].times[0].value, '09:30') assert.strictEqual(page.data.timeSelectTip, '请选择预约时间,美甲师可稍后分配') const availability = await page.checkAvailability() assert.strictEqual(availability.ok, true) @@ -121,7 +126,7 @@ async function run() { const walkInPage = createPage() Object.assign(walkInPage.data.form, { productId: '41', - appointmentDate: '2026-10-13', + appointmentDate: futureDate, appointmentTime: '15:00', amount: '88', durationMinutes: '45', diff --git a/JC-Salon-WeChat/pages/customers/index.js b/JC-Salon-WeChat/pages/customers/index.js index bafb92b9..87a88a3e 100644 --- a/JC-Salon-WeChat/pages/customers/index.js +++ b/JC-Salon-WeChat/pages/customers/index.js @@ -6,6 +6,8 @@ Page({ customers: [], loadError: '', createModalVisible: false, + duplicateModalVisible: false, + duplicateCustomers: [], creating: false, createForm: { nickname: '', @@ -60,6 +62,17 @@ Page({ this.setData({ createModalVisible: false }) }, + closeDuplicateModal() { + this.setData({ duplicateModalVisible: false }) + }, + + selectDuplicateCustomer(event) { + const customerId = event.currentTarget.dataset.id + if (!customerId) return + this.setData({ duplicateModalVisible: false }) + this.openDetail({ currentTarget: { dataset: { id: customerId } } }) + }, + stopTap() { }, @@ -94,12 +107,37 @@ Page({ } this.setData({ creating: true }) try { + const matches = await customersApi.matchExactIdentity(nickname, wechatId || undefined, phone || undefined) + if (Array.isArray(matches) && matches.length) { + this.setData({ + createModalVisible: false, + duplicateCustomers: matches.map(item => ({ + id: item.id, + name: item.name || item.nickname || nickname, + phone: item.phone || '未填写手机号' + })), + duplicateModalVisible: true + }) + return + } await customersApi.create({ nickname, wechatId: wechatId || undefined, phone: phone || undefined }) wx.showToast({ title: '客户已新增', icon: 'success' }) this.resetCreateForm() this.setData({ createModalVisible: false }) await this.loadCustomers() } catch (error) { + if (/客户已存在|重复|相同/.test(String(error.message || ''))) { + try { + const matches = await customersApi.matchExactIdentity(nickname, wechatId || undefined, phone || undefined) + if (Array.isArray(matches) && matches.length) { + this.setData({ createModalVisible: false, duplicateCustomers: matches.map(item => ({ id: item.id, name: item.name || item.nickname || nickname, phone: item.phone || '未填写手机号' })), duplicateModalVisible: true }) + return + } + } catch (lookupError) { + wx.showToast({ title: lookupError.message || '客户重复,请重新查询已有客户', icon: 'none' }) + return + } + } wx.showToast({ title: error.message || '新增失败', icon: 'none' }) } finally { this.setData({ creating: false }) diff --git a/JC-Salon-WeChat/pages/customers/index.test.js b/JC-Salon-WeChat/pages/customers/index.test.js index adcda100..6602c304 100644 --- a/JC-Salon-WeChat/pages/customers/index.test.js +++ b/JC-Salon-WeChat/pages/customers/index.test.js @@ -31,6 +31,7 @@ async function run() { global.wx.showToast = options => { toast = options.title } customersApi.create = async value => { submitted = value } customersApi.list = async () => ({ list: [] }) + customersApi.matchExactIdentity = async () => [] page.setData({ 'createForm.nickname': '小周', 'createForm.wechatId': 'wx_zhou' }) await page.submitCustomer() @@ -41,6 +42,23 @@ async function run() { await page.submitCustomer() assert.strictEqual(submitted, undefined) assert.strictEqual(toast, '请填写客户姓名') + + let lookedUp + customersApi.matchExactIdentity = async (...args) => { + lookedUp = args + return [{ id: '29', name: '小周', phone: '13800138000' }] + } + const duplicatePage = { + ...definition, + data: JSON.parse(JSON.stringify(definition.data)), + setData(values) { Object.assign(this.data, values) } + } + duplicatePage.data.createForm = { nickname: '小周', wechatId: 'wx-zhou', phone: '13800138000' } + await definition.submitCustomer.call(duplicatePage) + assert.deepStrictEqual(lookedUp, ['小周', 'wx-zhou', '13800138000']) + assert.strictEqual(duplicatePage.data.duplicateModalVisible, true) + assert.deepStrictEqual(duplicatePage.data.duplicateCustomers, [{ id: '29', name: '小周', phone: '13800138000' }]) + assert.strictEqual(submitted, undefined) } run().catch(error => { diff --git a/JC-Salon-WeChat/pages/customers/index.wxml b/JC-Salon-WeChat/pages/customers/index.wxml index d063165a..90bd78f9 100644 --- a/JC-Salon-WeChat/pages/customers/index.wxml +++ b/JC-Salon-WeChat/pages/customers/index.wxml @@ -45,4 +45,12 @@ + + + + 客户已存在姓名、微信号和手机号完全一致× + {{item.name}}{{item.phone}}› + + + diff --git a/JC-Salon-WeChat/pages/customers/index.wxss b/JC-Salon-WeChat/pages/customers/index.wxss index 5381bb90..92861313 100644 --- a/JC-Salon-WeChat/pages/customers/index.wxss +++ b/JC-Salon-WeChat/pages/customers/index.wxss @@ -147,3 +147,12 @@ .modal-submit { margin-top: 22rpx; } + +.duplicate-modal { max-height: 76vh; overflow: hidden; } +.duplicate-hint { display: block; margin-top: 7rpx; color: #7a8981; font-size: 21rpx; font-weight: 400; } +.duplicate-list { max-height: 48vh; overflow-y: auto; } +.duplicate-customer { display: flex; align-items: center; justify-content: space-between; min-height: 86rpx; border-bottom: 1rpx solid #e8eee9; } +.duplicate-name,.duplicate-phone { display: block; } +.duplicate-name { color: #26342d; font-size: 25rpx; font-weight: 700; } +.duplicate-phone { margin-top: 6rpx; color: #77867e; font-size: 21rpx; } +.duplicate-cancel { margin-top: 20rpx; background: #eaf3ed; color: #397055; } diff --git a/JC-Salon-WeChat/pages/employee-create/index.js b/JC-Salon-WeChat/pages/employee-create/index.js index 00e5290a..dba2f3a7 100644 --- a/JC-Salon-WeChat/pages/employee-create/index.js +++ b/JC-Salon-WeChat/pages/employee-create/index.js @@ -206,7 +206,7 @@ Page({ startTime: '00:00', endTime: '23:59', status: 1, - remark: '新建美甲师默认全天可预约,可在排班设置中调整' + remark: '新建美甲师默认全年全天排班,预约仍受门店营业时间限制,可在排班设置中调整' }).then(() => { this.finishCreated(this.data.pickerMode, true) }).catch(error => { diff --git a/JC-Salon-WeChat/pages/employee-create/index.wxml b/JC-Salon-WeChat/pages/employee-create/index.wxml index 772cd2fe..ba8f37fb 100644 --- a/JC-Salon-WeChat/pages/employee-create/index.wxml +++ b/JC-Salon-WeChat/pages/employee-create/index.wxml @@ -50,9 +50,9 @@ ✓ 美甲师已创建 {{pickerMode ? '设置常规排班后,可继续把当前预约分配给该美甲师。' : '为新美甲师设置首个常规排班,之后即可正常承接预约。'}} - 不立即设置时,将默认全年无休、全天可预约(00:00-23:59),之后可在排班设置中调整。 + 不立即设置时,将默认全年无休、全天排班(00:00-23:59);实际预约仍受门店营业时间限制,之后可在排班设置中调整。 - + diff --git a/JC-Salon-WeChat/pages/employees/index.js b/JC-Salon-WeChat/pages/employees/index.js index 681eeae3..ac3ec785 100644 --- a/JC-Salon-WeChat/pages/employees/index.js +++ b/JC-Salon-WeChat/pages/employees/index.js @@ -266,7 +266,7 @@ Page({ name: item.nickname || item.name || item.artistName || `美甲师${index + 1}`, shortName: (item.nickname || item.name || '师').slice(-1), avatar: item.avatar || item.avatarUrl || '', - color: EMPLOYEE_COLORS[index % EMPLOYEE_COLORS.length], + color: item.color || item.artistColor || (item.artist && item.artist.color) || EMPLOYEE_COLORS[index % EMPLOYEE_COLORS.length], monthOrders: item.monthOrders || item.orderCount || 0, monthAmount: item.monthAmount || item.turnover || 0, scheduleSummary: buildScheduleSummary(item), diff --git a/JC-Salon-WeChat/pages/register/index.js b/JC-Salon-WeChat/pages/register/index.js index 41133414..4261e3e1 100644 --- a/JC-Salon-WeChat/pages/register/index.js +++ b/JC-Salon-WeChat/pages/register/index.js @@ -16,7 +16,11 @@ Page({ selectedShopName: '', loading: false, avatarUploading: false, - ticketInvalid: false + ticketInvalid: false, + registrationStatus: null, + registrationStatusText: '', + contentStatusText: '', + contentStatusReason: '' }, async onLoad(options) { @@ -95,6 +99,29 @@ Page({ goBackStep() { this.setData({ step: 1 }) }, + mapRegistrationStatus(result) { + const statusText = { + APPROVED: '已通过', + REJECTED: '已驳回', + PENDING_ADMIN: '待平台审核', + PENDING_MANAGER: '待店长审核' + }[String(result && result.status || '').toUpperCase()] || '状态未知' + const moderationStatus = String(result && result.contentModerationStatus || '').toUpperCase() + const contentStatusText = { + APPROVED: '资料内容审核已通过', + REJECTED: '资料内容审核未通过', + PENDING: '资料内容正在审核,审核完成前不会展示', + RETRY: '资料内容待重新审核,审核完成前不会展示', + MISSING: '资料尚未进入审核,请联系门店负责人确认' + }[moderationStatus] || '' + return { + registrationStatus: result || null, + registrationStatusText: statusText, + contentStatusText, + contentStatusReason: result && result.contentModerationReason || '' + } + }, + async submit() { const form = this.data.form if (!this.data.registrationTicket) { @@ -109,7 +136,7 @@ Page({ } this.setData({ loading: true }) try { - await authApi.register({ + const result = await authApi.register({ registrationTicket: this.data.registrationTicket, applicationId: this.data.applicationId || undefined, shopName: String(form.shopName || '').trim(), @@ -120,9 +147,14 @@ Page({ applicantAvatarFileId: this.data.role === 'staff' ? form.applicantAvatarFileId || undefined : undefined, agreementAccepted: true }) - this.setData({ step: 3, registrationTicket: '' }) + this.setData({ step: 3, registrationTicket: '', ...this.mapRegistrationStatus(result) }) } catch (error) { - wx.showToast({ title: error.message || '提交失败', icon: 'none' }) + const message = String(error.message || '提交失败') + if (/注册票据|注册凭证|一次性.*(失效|消费)|票据.*(失效|过期|已使用)/.test(message)) { + this.setData({ ticketInvalid: true }) + return + } + wx.showToast({ title: message, icon: 'none' }) } finally { this.setData({ loading: false }) } diff --git a/JC-Salon-WeChat/pages/register/index.test.js b/JC-Salon-WeChat/pages/register/index.test.js new file mode 100644 index 00000000..84fea232 --- /dev/null +++ b/JC-Salon-WeChat/pages/register/index.test.js @@ -0,0 +1,57 @@ +const assert = require('assert') +const authApi = require('../../api/auth') + +let definition +let toast +global.Page = value => { definition = value } +global.wx = { showToast: options => { toast = options.title } } +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.data.registrationTicket = 'valid-ticket' + page.data.role = 'staff' + page.data.form.shopId = '20' + authApi.register = async () => ({ + applicationId: '88', + status: 'APPROVED', + rejectReason: null, + contentModerationStatus: 'PENDING', + contentModerationReason: '图片审核仍在处理' + }) + await page.submit() + assert.strictEqual(page.data.registrationStatusText, '已通过') + assert.strictEqual(page.data.contentStatusText, '资料内容正在审核,审核完成前不会展示') + assert.strictEqual(page.data.contentStatusReason, '图片审核仍在处理') + assert.strictEqual(page.data.step, 3) + + const expired = createPage() + expired.data.registrationTicket = 'spent-ticket' + expired.data.role = 'staff' + expired.data.form.shopId = '20' + authApi.register = async () => { throw new Error('注册票据已失效,请重新发起快捷登录') } + await expired.submit() + assert.strictEqual(expired.data.ticketInvalid, true) + assert.strictEqual(expired.data.step, 1) + assert.strictEqual(toast, undefined) +} + +run().catch(error => { + console.error(error) + process.exitCode = 1 +}) diff --git a/JC-Salon-WeChat/pages/register/index.wxml b/JC-Salon-WeChat/pages/register/index.wxml index 0bbc7934..eef0e598 100644 --- a/JC-Salon-WeChat/pages/register/index.wxml +++ b/JC-Salon-WeChat/pages/register/index.wxml @@ -1,10 +1,10 @@ Salon用微信身份申请门店工作权限 - 123 - !申请入口已失效请返回登录页重新点击微信快捷登录,获取新的申请凭证。 + 123 + !申请入口已失效这次注册凭证已过期或已使用,请返回登录页重新点击微信快捷登录获取新凭证。 选择工作身份无需手机号和密码,审核人会根据你的身份处理申请店店长创建并负责一家 Salon 门店{{role === 'manager' ? '✓' : '○'}}员店员加入已有门店协同工作{{role === 'staff' ? '✓' : '○'}} {{role === 'manager' ? '完善店铺资料' : '选择要加入的店铺'}}{{role === 'manager' ? '提交后由平台管理员审核' : '提交后由对应店长审核,昵称和头像均为可选资料'}}店铺名称店铺地址选择店铺{{selectedShopName || '请选择要加入的店铺'}}›申请昵称(选填)申请头像(选填)审核通过前不会获得门店业务权限返回上一步 - ✓申请已提交{{role === 'manager' ? '平台管理员审核通过后,即可使用快捷登录。' : '店长审核通过后,即可使用快捷登录。'}}当前状态:等待审核 + {{registrationStatusText === '已驳回' ? '!' : registrationStatusText === '已通过' ? '✓' : '…'}}{{registrationStatusText === '已通过' ? '申请已通过' : registrationStatusText === '已驳回' ? '申请未通过' : '申请已提交'}}{{registrationStatusText === '已通过' ? '现在可以返回登录页,使用微信快捷登录。' : registrationStatusText === '已驳回' ? (registrationStatus.rejectReason || '请联系对应审核人了解原因。') : (role === 'manager' ? '申请由平台管理员处理,通过后即可使用快捷登录。' : '申请由门店店长处理,通过后即可使用快捷登录。')}}当前状态:{{registrationStatusText}}{{contentStatusText}}{{contentStatusReason}} OpenID 仅用于识别你的微信身份,不会在页面中展示。 diff --git a/JC-Salon-WeChat/pages/register/index.wxss b/JC-Salon-WeChat/pages/register/index.wxss index 3062f472..edcace57 100644 --- a/JC-Salon-WeChat/pages/register/index.wxss +++ b/JC-Salon-WeChat/pages/register/index.wxss @@ -251,6 +251,10 @@ font-size: 48rpx; font-weight: 800; } +.result-icon.approved { background: #e5f4ed; color: #247b63; } +.result-icon.rejected { background: #fff0ed; color: #a24f42; } +.content-review-status { width: 100%; box-sizing: border-box; margin-top: 16rpx; padding: 16rpx 20rpx; border-radius: 12rpx; background: #f3f7f4; color: #587061; font-size: 22rpx; line-height: 1.5; } +.content-review-reason { display: block; margin-top: 6rpx; color: #a24f42; } .result-card .section-title { margin-top: 24rpx; } .result-status { margin-top: 28rpx; padding: 18rpx 28rpx; border-radius: 12rpx; background: #e5f4ed; color: #75887b; font-size: 24rpx; } diff --git a/JC-Salon-WeChat/pages/shop-settings/index.js b/JC-Salon-WeChat/pages/shop-settings/index.js index 4400f0d3..45630dda 100644 --- a/JC-Salon-WeChat/pages/shop-settings/index.js +++ b/JC-Salon-WeChat/pages/shop-settings/index.js @@ -1,17 +1,37 @@ const { BRAND_CONFIG } = require('../../utils/config') const profileCache = require('../../utils/profile-cache') +const shopApi = require('../../api/shop') + +function resolveNameStatus(value) { + const status = String(value || '').toUpperCase() + if (status === 'PENDING' || status === 'RETRY') return '名称审核中' + if (status === 'REJECTED') return '名称审核未通过' + if (status === 'APPROVED') return '名称已通过审核' + return '尚未提交审核' +} Page({ data: { profile: {}, businessExpireDateText: '未设置', businessExpiryStatusText: '有效期未设置', - form: { shopName: BRAND_CONFIG.defaultShopName, startTime: '10:00', endTime: '22:00', defaultDuration: 60, rule: '必须选择已有作品作为项目来源' } + nameModerationText: '尚未提交审核', + settingsLoading: false, + settingsSaving: false, + nameSaving: false, + settingsError: '', + form: { shopName: BRAND_CONFIG.defaultShopName, pendingShopName: '', startTime: '10:00', endTime: '22:00', defaultDuration: 60 } }, - onShow() { this.loadProfile() }, - async loadProfile(options = {}) { + + onShow() { this.loadProfileAndSettings() }, + + async loadProfileAndSettings(options = {}) { + this.setData({ settingsLoading: true, settingsError: '' }) try { - const profile = await profileCache.getProfile(options) + const [profile, settings] = await Promise.all([ + profileCache.getProfile(options), + shopApi.appointmentSettings() + ]) const businessExpireDateText = profile.shopBusinessExpireTime ? String(profile.shopBusinessExpireTime).slice(0, 10) : '未设置' const remainingDays = profile.shopBusinessRemainingDays const hasRemainingDays = remainingDays !== null && remainingDays !== undefined && remainingDays !== '' && Number.isFinite(Number(remainingDays)) @@ -20,30 +40,79 @@ Page({ : hasRemainingDays ? `剩余 ${remainingDays} 天` : '有效期未设置' - this.setData({ profile, businessExpireDateText, businessExpiryStatusText }) + const [startTime, endTime] = String(settings.businessHours || '10:00-22:00').split('-') + this.setData({ + profile, + businessExpireDateText, + businessExpiryStatusText, + nameModerationText: resolveNameStatus(settings.shopNameModerationStatus), + form: { + ...this.data.form, + shopName: settings.pendingShopName || settings.shopName || profile.shopName || BRAND_CONFIG.defaultShopName, + pendingShopName: settings.pendingShopName || '', + startTime: startTime || '10:00', + endTime: endTime || '22:00', + defaultDuration: Number(settings.defaultAppointmentDurationMinutes) || 60 + } + }) } catch (error) { - this.setData({ profile: {} }) + this.setData({ settingsError: error.message || '设置加载失败' }) + } finally { + this.setData({ settingsLoading: false }) } }, + onInput(event) { this.setData({ [`form.${event.currentTarget.dataset.field}`]: event.detail.value }) }, onStartChange(event) { this.setData({ 'form.startTime': event.detail.value }) }, onEndChange(event) { this.setData({ 'form.endTime': event.detail.value }) }, + + async saveAppointmentSettings() { + const { startTime, endTime, defaultDuration } = this.data.form + const duration = Number(defaultDuration) + if (startTime >= endTime) { + wx.showToast({ title: '营业结束时间必须晚于开始时间', icon: 'none' }) + return + } + if (!Number.isInteger(duration) || duration < 15 || duration > 720) { + wx.showToast({ title: '默认时长需在15至720分钟之间', icon: 'none' }) + return + } + this.setData({ settingsSaving: true }) + try { + await shopApi.saveAppointmentSettings({ businessHours: `${startTime}-${endTime}`, defaultAppointmentDurationMinutes: duration }) + wx.showToast({ title: '预约设置已生效', icon: 'success' }) + } catch (error) { + wx.showToast({ title: error.message || '保存失败,请重试', icon: 'none' }) + } finally { + this.setData({ settingsSaving: false }) + } + }, + + async submitShopName() { + const shopName = String(this.data.form.shopName || '').trim() + if (!shopName) { + wx.showToast({ title: '请输入店铺名称', icon: 'none' }) + return + } + this.setData({ nameSaving: true }) + try { + await shopApi.updateName(shopName) + wx.showToast({ title: '店铺名称已提交审核', icon: 'success' }) + await this.loadProfileAndSettings({ force: true }) + } catch (error) { + wx.showToast({ title: error.message || '提交审核失败', icon: 'none' }) + } finally { + this.setData({ nameSaving: false }) + } + }, + explainDefaultDuration() { wx.showModal({ title: '默认时长', - content: '用于手动创建预约或未选择作品时的默认服务时长,会影响可约时间校验和预约结束时间估算。', + content: '用于新建预约表单的初始值和未设置款式时的后备时长。已选款式的时长或你在预约中修改的时长优先。', showCancel: false, confirmText: '知道了' }) }, - explainBookingRule() { - wx.showModal({ - title: '预约规则', - content: '这是店铺给美甲师看的预约备注或说明文案,不参与自动排班、容量或冲突校验。', - showCancel: false, - confirmText: '知道了' - }) - }, - save() { wx.showToast({ title: '已保存' }) }, back() { wx.navigateBack() } }) diff --git a/JC-Salon-WeChat/pages/shop-settings/index.test.js b/JC-Salon-WeChat/pages/shop-settings/index.test.js index 57c512be..9681999a 100644 --- a/JC-Salon-WeChat/pages/shop-settings/index.test.js +++ b/JC-Salon-WeChat/pages/shop-settings/index.test.js @@ -10,6 +10,14 @@ global.wx = { showToast: () => {} } const profileCache = require('../../utils/profile-cache') profileCache.getProfile = async () => currentProfile +const shopApi = require('../../api/shop') +shopApi.appointmentSettings = async () => ({ + shopName: '薄荷美甲', + businessHours: '09:30-21:30', + defaultAppointmentDurationMinutes: 75, + shopNameModerationStatus: 'PENDING', + pendingShopName: '薄荷指尖' +}) require('./index') async function loadProfile(profile) { @@ -24,7 +32,7 @@ async function loadProfile(profile) { }) } } - await pageDefinition.loadProfile.call(page) + await pageDefinition.loadProfileAndSettings.call(page) return page.data } @@ -54,11 +62,19 @@ async function run() { shopBusinessRemainingDays: 0 }) assert.strictEqual(expired.businessExpiryStatusText, '已过期,暂不能新增预约') + assert.strictEqual(expired.form.startTime, '09:30') + assert.strictEqual(expired.form.endTime, '21:30') + assert.strictEqual(expired.form.defaultDuration, 75) + assert.strictEqual(expired.nameModerationText, '名称审核中') + assert.strictEqual(expired.form.pendingShopName, '薄荷指尖') const shopSettingsWxml = fs.readFileSync(path.join(__dirname, 'index.wxml'), 'utf8') const accountSettingsWxml = fs.readFileSync(path.join(__dirname, '../account-settings/index.wxml'), 'utf8') assert(shopSettingsWxml.includes('wx:if="{{profile.type == 2}}" class="card business-expiry-card"')) assert(!accountSettingsWxml.includes('business-expiry-card')) + assert(!shopSettingsWxml.includes('预约规则')) + assert(shopSettingsWxml.includes('提交名称审核')) + assert(shopSettingsWxml.includes('保存预约设置')) } run().catch(error => { diff --git a/JC-Salon-WeChat/pages/shop-settings/index.wxml b/JC-Salon-WeChat/pages/shop-settings/index.wxml index e555991d..147c260f 100644 --- a/JC-Salon-WeChat/pages/shop-settings/index.wxml +++ b/JC-Salon-WeChat/pages/shop-settings/index.wxml @@ -1,28 +1,21 @@ + {{settingsError}} 门店经营有效期{{businessExpiryStatusText}} 有效期至{{businessExpireDateText}} 到期后暂不可新增普通预约,历史订单、查询和补录不受影响。请联系平台管理员办理续期。 - - 店铺名称 - 营业开始{{form.startTime}} - 营业结束{{form.endTime}} - - - 默认时长 - ? - - - 分钟 - - - - 预约规则 - ? - - - + + 门店名称名称修改需审核,通过后对外展示{{nameModerationText}} + + 审核中的名称:{{form.pendingShopName}} + + + + 预约运营设置保存后立即生效,不需要门店资料审核 + 营业时间{{form.startTime}}至{{form.endTime}} + 默认预约时长?分钟 + - + 正在加载店铺设置… diff --git a/JC-Salon-WeChat/pages/shop-settings/index.wxss b/JC-Salon-WeChat/pages/shop-settings/index.wxss index 67414de8..c8af52a5 100644 --- a/JC-Salon-WeChat/pages/shop-settings/index.wxss +++ b/JC-Salon-WeChat/pages/shop-settings/index.wxss @@ -1,6 +1,29 @@ .business-expiry-card { margin-top:20rpx; padding:26rpx; }.business-expiry-head,.business-expiry-date { display:flex; align-items:center; justify-content:space-between; gap:16rpx; }.business-expiry-status { color:#397055; font-size:22rpx; }.business-expiry-status.expired { color:#a24f42; }.business-expiry-date { margin-top:20rpx; padding-top:18rpx; border-top:1rpx solid #e5ebe7; color:#71807a; font-size:23rpx; }.business-expiry-date strong { color:#17211f; font-size:25rpx; }.business-expiry-note { display:block; margin-top:14rpx; color:#a24f42; font-size:21rpx; line-height:1.6; } +.settings-section { margin-top: 24rpx; padding: 0 8rpx 36rpx; } +.settings-section-head { display: flex; align-items: center; justify-content: space-between; gap: 20rpx; } +.settings-section-head > view { display: flex; min-width: 0; flex-direction: column; } +.settings-section-note { margin-top: 8rpx; color: #7a8981; font-size: 21rpx; line-height: 1.45; } +.moderation-status { flex: none; color: #58826a; font-size: 21rpx; } +.shop-name-field { margin-top: 20rpx; } +.shop-name-field input { box-sizing: border-box; width: 100%; height: 82rpx; padding: 0 20rpx; border: 1rpx solid #dce8e0; border-radius: 12rpx; background: #f7faf8; color: #17211f; font-size: 25rpx; } +.pending-name-note { margin-top: 12rpx; color: #8b7554; font-size: 21rpx; } +.settings-action { height: 76rpx; margin: 18rpx 0 0; padding: 0 26rpx; border-radius: 12rpx; background: #247b63; color: #fff; font-size: 24rpx; line-height: 76rpx; } +.settings-action.secondary { background: #e9f3ed; color: #397055; } +.settings-divider { height: 1rpx; margin: 32rpx 0 28rpx; background: #e4ebe6; } +.settings-field-row { display: flex; min-height: 90rpx; align-items: center; justify-content: space-between; gap: 20rpx; border-bottom: 1rpx solid #e8eee9; } +.settings-label { color: #26342d; font-size: 24rpx; font-weight: 600; } +.time-range { display: flex; align-items: center; gap: 15rpx; color: #859189; font-size: 21rpx; } +.time-value { min-width: 102rpx; padding: 13rpx 14rpx; border-radius: 10rpx; background: #f0f6f2; color: #247b63; font-size: 24rpx; text-align: center; } +.duration-row { align-items: center; } +.duration-input { display: flex; align-items: center; gap: 12rpx; color: #748279; font-size: 22rpx; } +.duration-input input { box-sizing: border-box; width: 150rpx; height: 68rpx; padding: 0 16rpx; border: 1rpx solid #dce8e0; border-radius: 10rpx; background: #f7faf8; color: #17211f; text-align: right; } +.label-with-help { display: flex; align-items: center; } +.settings-error { display: flex; align-items: center; justify-content: space-between; gap: 16rpx; padding: 18rpx 8rpx; color: #a24f42; font-size: 22rpx; } +.settings-error button { margin: 0; color: #397055; font-size: 21rpx; } +.settings-loading { padding: 40rpx 8rpx; color: #71807a; font-size: 23rpx; } + .label-with-help { display: flex; align-items: center;