From 69ea01eaa494c3d500bfdaace50308a76a051dac Mon Sep 17 00:00:00 2001 From: xiaowang <2161656029@qq.com> Date: Mon, 9 Nov 2026 15:18:27 +0800 Subject: [PATCH] =?UTF-8?q?=E5=B0=8F=E7=A8=8B=E5=BA=8F=E9=A2=84=E7=BA=A6?= =?UTF-8?q?=E8=AF=A6=E6=83=85=E6=94=AF=E6=8C=81=E5=9B=BE=E7=89=87=E9=A2=84?= =?UTF-8?q?=E8=A7=88=E3=80=81=E7=BC=96=E8=BE=91=E9=A2=84=E7=BA=A6=E4=B8=8E?= =?UTF-8?q?=E5=AE=8C=E6=88=90=E6=94=B6=E6=AC=BE=E6=8B=86=E5=88=86?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../admin/AdminManagerController.java | 26 +++ .../order/dto/OrderOfflinePaymentDTO.java | 2 +- .../order/service/impl/OrderServiceImpl.java | 22 +-- .../planning/service/PlanningService.java | 2 + .../service/impl/PlanningServiceImpl.java | 151 +++++++++++++++++ .../planning/vo/PlanningAppointmentVO.java | 14 ++ .../OrderServiceImplOfflinePaymentTest.java | 31 +++- JC-Salon-WeChat/api/planning.js | 16 ++ .../components/action-modal/index.js | 6 +- .../components/action-modal/index.wxml | 2 +- .../pages/appointment-detail/index.js | 130 +++++++++++++- .../pages/appointment-detail/index.test.js | 42 ++++- .../pages/appointment-detail/index.wxml | 39 ++++- .../pages/appointment-detail/index.wxss | 44 +++++ .../pages/appointment-form/edit-mode.test.js | 155 +++++++++++++++++ .../pages/appointment-form/index.js | 160 ++++++++++++++++-- .../pages/appointment-form/index.wxml | 18 +- JC-Salon-WeChat/utils/action-modal.js | 2 + 18 files changed, 801 insertions(+), 61 deletions(-) create mode 100644 JC-Salon-WeChat/pages/appointment-form/edit-mode.test.js 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 deec7bfa..e1d0afb0 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 @@ -2,6 +2,7 @@ package com.xiaowang.jayucloud.salon.core.modules.manager.controller.admin; import com.xiaowang.jayucloud.salon.core.annotation.OperationGuard; import com.xiaowang.jayucloud.salon.core.annotation.RequirePermission; +import com.xiaowang.jayucloud.salon.core.common.BusinessException; import com.xiaowang.jayucloud.salon.core.common.Result; import com.xiaowang.jayucloud.salon.core.common.vo.PageResultVO; import com.xiaowang.jayucloud.salon.core.modules.artist.dto.ArtistColorUpdateDTO; @@ -16,6 +17,7 @@ import com.xiaowang.jayucloud.salon.core.modules.artist.vo.ArtistScheduleRuleSet import com.xiaowang.jayucloud.salon.core.modules.artist.vo.ArtistScheduleRuleVO; import com.xiaowang.jayucloud.salon.core.modules.artist.vo.ArtistScheduleVO; import com.xiaowang.jayucloud.salon.core.modules.manager.dto.ManagerCustomerCreateDTO; +import com.xiaowang.jayucloud.salon.core.modules.order.dto.OrderOfflinePaymentDTO; import com.xiaowang.jayucloud.salon.core.modules.order.service.OrderService; import com.xiaowang.jayucloud.salon.core.modules.order.vo.OrderVO; import com.xiaowang.jayucloud.salon.core.modules.planning.dto.PlanningAppointmentCreateDTO; @@ -120,6 +122,30 @@ public class AdminManagerController { return Result.success(planningService.getAppointment(currentUser, orderItemId)); } + @PutMapping("/planning/appointments/{orderItemId}") + @RequirePermission("order:process") + @OperationGuard(action = "manager-planning-update-appointment", ttlSeconds = 10, message = "预约保存处理中,请勿重复提交") + public Result updateAppointment(HttpServletRequest request, + @PathVariable Long orderItemId, + @RequestBody PlanningAppointmentCreateDTO dto) { + UserDO currentUser = adminScopeHelper.getCurrentUser(request); + return Result.success(planningService.updateAppointment(currentUser, orderItemId, dto)); + } + + @PostMapping("/orders/{orderId}/offline-payment") + @RequirePermission("order:process") + @OperationGuard(action = "manager-order-offline-payment", ttlSeconds = 10, message = "收款登记处理中,请勿重复提交") + public Result registerOfflinePayment(HttpServletRequest request, + @PathVariable Long orderId, + @RequestBody OrderOfflinePaymentDTO dto) { + UserDO currentUser = adminScopeHelper.getCurrentUser(request); + if (Integer.valueOf(3).equals(currentUser.getType())) { + throw new BusinessException(403, "美甲师账号不能登记收款"); + } + Long scopedShopId = adminScopeHelper.resolveShopScope(currentUser, null); + return Result.success(orderService.registerOfflinePayment(orderId, currentUser.getId(), scopedShopId, dto)); + } + @PutMapping("/planning/appointments/{orderItemId}/time-artist") @RequirePermission("order:process") @OperationGuard(action = "manager-planning-move-appointment", ttlSeconds = 10, message = "预约调整处理中,请勿重复提交") diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/order/dto/OrderOfflinePaymentDTO.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/order/dto/OrderOfflinePaymentDTO.java index 1f1bd70f..dd3ff993 100644 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/order/dto/OrderOfflinePaymentDTO.java +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/order/dto/OrderOfflinePaymentDTO.java @@ -7,7 +7,7 @@ import java.time.LocalDateTime; /** * 线下收款登记入参。 - * 当前仅支持 payMethod=OFFLINE,paidAmount 必须与订单应付金额一致。 + * payMethod 可选 OFFLINE、CASH、WECHAT、ALIPAY;paidAmount 为实收金额,允许与订单应付金额不一致。 */ @Data public class OrderOfflinePaymentDTO { diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/order/service/impl/OrderServiceImpl.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/order/service/impl/OrderServiceImpl.java index 2e705d4d..60893ee9 100644 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/order/service/impl/OrderServiceImpl.java +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/order/service/impl/OrderServiceImpl.java @@ -1827,8 +1827,11 @@ public class OrderServiceImpl implements OrderService { throw new RuntimeException("收款登记信息不能为空"); } String payMethod = dto.getPayMethod() == null ? "" : dto.getPayMethod().trim().toUpperCase(); - if (!PAYMENT_METHOD_OFFLINE.equals(payMethod)) { - throw new RuntimeException("当前仅支持线下收款,payMethod 只能为 OFFLINE"); + if (!PAYMENT_METHOD_OFFLINE.equals(payMethod) + && !"CASH".equals(payMethod) + && !"WECHAT".equals(payMethod) + && !"ALIPAY".equals(payMethod)) { + throw new RuntimeException("payMethod 只能为 OFFLINE、CASH、WECHAT 或 ALIPAY"); } if (dto.getPaidAmount() == null) { throw new RuntimeException("实收金额不能为空"); @@ -1852,31 +1855,22 @@ public class OrderServiceImpl implements OrderService { throw new RuntimeException("订单已取消,不能登记收款"); } - BigDecimal expectedAmount = order.getPayAmount() == null ? order.getActualAmount() : order.getPayAmount(); - if (expectedAmount == null) { - expectedAmount = BigDecimal.ZERO; - } - if (dto.getPaidAmount().compareTo(expectedAmount) != 0) { - throw new RuntimeException("实收金额必须等于订单应付金额 " - + expectedAmount.stripTrailingZeros().toPlainString() + " 元"); - } - LocalDateTime paidAt = (dto.getPaidAt() == null ? LocalDateTime.now() : dto.getPaidAt()).withNano(0); if (PAYMENT_STATUS_PAID.equals(order.getPaymentStatus())) { - boolean sameMethod = PAYMENT_METHOD_OFFLINE.equals(order.getPaymentMethod()); + boolean sameMethod = payMethod.equals(order.getPaymentMethod()); boolean sameAmount = order.getPaidAmount() != null && order.getPaidAmount().compareTo(dto.getPaidAmount()) == 0; boolean sameTime = order.getPayTime() != null && order.getPayTime().withNano(0).equals(paidAt); if (sameMethod && sameAmount && sameTime) { return buildOrderVO(order); } - throw new RuntimeException("该订单已登记线下收款,金额或收款时间与首次登记不一致,不能重复登记"); + throw new RuntimeException("该订单已登记收款,金额或收款方式与首次登记不一致,不能重复登记"); } if (order.getPaymentStatus() != null && !PAYMENT_STATUS_UNPAID.equals(order.getPaymentStatus())) { throw new RuntimeException("订单当前支付状态为 " + order.getPaymentStatus() + ",不能登记线下收款"); } order.setPaymentStatus(PAYMENT_STATUS_PAID); - order.setPaymentMethod(PAYMENT_METHOD_OFFLINE); + order.setPaymentMethod(payMethod); order.setPaidAmount(dto.getPaidAmount()); order.setPayTime(paidAt); order.setPaidBy(operatorId); diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/planning/service/PlanningService.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/planning/service/PlanningService.java index 3de9d6d6..35861e04 100644 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/planning/service/PlanningService.java +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/planning/service/PlanningService.java @@ -22,6 +22,8 @@ public interface PlanningService { PlanningAppointmentVO getAppointment(UserDO currentUser, Long orderItemId); + PlanningAppointmentVO updateAppointment(UserDO currentUser, Long orderItemId, PlanningAppointmentCreateDTO dto); + PlanningAppointmentVO moveAppointment(UserDO currentUser, Long orderItemId, PlanningAppointmentMoveDTO dto); Boolean updateStatus(UserDO currentUser, Long orderId, PlanningAppointmentStatusDTO dto); 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 a736cd76..8d4552cd 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 @@ -349,6 +349,146 @@ public class PlanningServiceImpl implements PlanningService { return toAppointmentVO(reservation, item, order, product, customer, artistMap); } + @Override + @Transactional + public PlanningAppointmentVO updateAppointment(UserDO currentUser, Long orderItemId, PlanningAppointmentCreateDTO dto) { + if (dto == null) { + throw new RuntimeException("预约信息不能为空"); + } + if (orderItemId == null) { + throw new RuntimeException("预约ID不能为空"); + } + if (Integer.valueOf(3).equals(currentUser.getType())) { + throw new RuntimeException("美甲师账号只能查看预约,不能编辑预约"); + } + OrderItemDO item = orderItemMapper.selectByIdForUpdate(orderItemId); + if (item == null || Integer.valueOf(1).equals(item.getIsDelete())) { + throw new RuntimeException("预约不存在"); + } + OrderDO order = requireAccessibleOrder(currentUser, item.getOrderId()); + if ("HISTORICAL_BACKFILL".equals(order.getOrderSource())) { + throw new RuntimeException("历史补单不支持编辑预约"); + } + int currentStatus = order.getStatus() == null ? -1 : order.getStatus(); + if (currentStatus == OrderStatus.COMPLETED.getCode()) { + throw new RuntimeException("预约已完成,不能编辑"); + } + if (currentStatus == OrderStatus.CANCELLED.getCode()) { + throw new RuntimeException("预约已取消,不能编辑"); + } + if (currentStatus == OrderStatus.IN_SERVICE.getCode()) { + throw new RuntimeException("服务中的预约不能编辑"); + } + if (currentStatus != OrderStatus.PRICE_CONFIRMING.getCode() + && currentStatus != OrderStatus.PENDING_SERVICE.getCode()) { + throw new RuntimeException("当前状态不可编辑预约"); + } + + Long shopId = order.getShopId(); + ShopDO shop = shopMapper.selectById(shopId); + int shopDefaultDuration = resolveShopDefaultDuration(shop); + int quantity = item.getQuantity() == null || item.getQuantity() <= 0 ? 1 : item.getQuantity(); + ProductDO product = resolveUpdateProduct(dto, item, shopId, shopDefaultDuration); + int durationMinutes = resolveDurationMinutes(product, dto.getDurationMinutes(), shopDefaultDuration) * quantity; + LocalDateTime startTime = parseAppointmentStart(dto.getAppointmentStartTime(), dto.getAppointmentDate(), dto.getAppointmentTime()); + LocalDateTime endTime = startTime.plusMinutes(durationMinutes); + + boolean timeChanged = item.getAppointmentTime() == null || !item.getAppointmentTime().equals(startTime); + if (timeChanged) { + ensureFutureAppointmentTime(startTime); + } + ensureWithinBusinessHours(shopId, startTime, endTime); + + UserDO artist = dto.getArtistId() == null ? null : requireActiveArtist(dto.getArtistId(), shopId); + boolean artistChanged = !Objects.equals(item.getArtistId(), artist == null ? null : artist.getId()); + + BigDecimal unitPrice = product.getPrice() == null ? BigDecimal.ZERO : product.getPrice(); + BigDecimal amount = dto.getAmount() == null + ? unitPrice.multiply(BigDecimal.valueOf(quantity)) + : dto.getAmount(); + if (amount.compareTo(BigDecimal.ZERO) < 0) { + throw new RuntimeException("成交金额不能小于0"); + } + boolean paid = "PAID".equals(order.getPaymentStatus()); + BigDecimal currentAmount = order.getActualAmount(); + if (paid && (currentAmount == null || currentAmount.compareTo(amount) != 0)) { + throw new RuntimeException("订单已收款,不能修改成交金额"); + } + + UserDO customer = resolveCustomer(currentUser, shopId, dto); + order.setUserId(customer == null ? null : customer.getId()); + order.setCustomerNameSnapshot(customer == null ? trimToNull(dto.getCustomerName()) : null); + order.setCustomerPhoneSnapshot(customer == null ? trimToNull(dto.getPhone()) : null); + order.setCustomerRemark(trimToNull(dto.getRemark())); + if (!paid) { + order.setTotalAmount(amount); + order.setActualAmount(amount); + order.setPayAmount(amount); + } + orderMapper.updateById(order); + + item.setProductId(product.getId()); + item.setPrice(amount.divide(BigDecimal.valueOf(quantity), 2, RoundingMode.HALF_UP)); + item.setArtistId(artist == null ? null : artist.getId()); + item.setAppointmentTime(startTime); + item.setIsDelete(0); + orderItemMapper.updateById(item); + + if (artist != null && (artistChanged || timeChanged)) { + appointmentCapacityService.moveReservationForArtistChange( + order.getId(), + item.getId(), + shopId, + artist.getId(), + artist.getId(), + product.getTitle(), + startTime, + endTime + ); + } else if (artist == null && artistChanged) { + appointmentReservationMapper.releaseByOrderItem(item.getId(), "RELEASED"); + } + return getAppointment(currentUser, item.getId()); + } + + private ProductDO resolveUpdateProduct(PlanningAppointmentCreateDTO dto, OrderItemDO item, Long shopId, int shopDefaultDuration) { + if (dto.getProductId() != null) { + return requireActiveProduct(dto.getProductId(), shopId); + } + String title = trimToNull(dto.getManualProductTitle()); + if (!hasText(title)) { + throw new RuntimeException("请填写美甲款式名称"); + } + ProductDO existing = item.getProductId() == null ? null : productMapper.selectById(item.getProductId()); + boolean editableManualProduct = existing != null + && PRODUCT_SOURCE_TYPE_MANAGER_APPOINTMENT.equals(existing.getSourceType()) + && !Integer.valueOf(1).equals(existing.getIsDelete()) + && shopId.equals(existing.getShopId()); + if (!editableManualProduct) { + return createManualAppointmentProduct(dto, shopId, shopDefaultDuration); + } + BigDecimal price = dto.getManualProductPrice() == null ? dto.getAmount() : dto.getManualProductPrice(); + if (price == null) { + price = BigDecimal.ZERO; + } + if (price.compareTo(BigDecimal.ZERO) < 0) { + throw new RuntimeException("成交金额不能小于0"); + } + int durationMinutes = dto.getDurationMinutes() == null || dto.getDurationMinutes() <= 0 + ? shopDefaultDuration : dto.getDurationMinutes(); + existing.setTitle(title); + existing.setDescription(trimToNull(dto.getManualProductDescription())); + existing.setTags(trimToNull(dto.getManualProductTags())); + existing.setTargetAudience(trimToNull(dto.getManualProductTargetAudience())); + existing.setPrecautions(trimToNull(dto.getManualProductPrecautions())); + existing.setImageFileIds(trimToNull(dto.getManualProductImageFileIds())); + existing.setPrice(price); + existing.setApproximateDuration(durationMinutes + "分钟"); + existing.setBookableArtists(dto.getArtistId() == null ? null : String.valueOf(dto.getArtistId())); + productMapper.updateById(existing); + return existing; + } + @Override @Transactional public PlanningAppointmentVO moveAppointment(UserDO currentUser, Long orderItemId, PlanningAppointmentMoveDTO dto) { @@ -658,6 +798,17 @@ public class PlanningServiceImpl implements PlanningService { vo.setAmount(order == null ? null : order.getActualAmount()); vo.setRemark(order == null ? null : order.getCustomerRemark()); vo.setCancelReason(order == null ? null : order.getCancelReason()); + vo.setProductSourceType(product == null ? null : product.getSourceType()); + vo.setProductDescription(product == null ? null : product.getDescription()); + vo.setProductTags(product == null ? null : product.getTags()); + vo.setProductTargetAudience(product == null ? null : product.getTargetAudience()); + vo.setProductPrecautions(product == null ? null : product.getPrecautions()); + vo.setProductImageFileIds(product == null ? null : product.getImageFileIds()); + vo.setPaymentStatus(order == null ? null : order.getPaymentStatus()); + vo.setPaymentMethod(order == null ? null : order.getPaymentMethod()); + vo.setPayAmount(order == null ? null : order.getPayAmount()); + vo.setPaidAmount(order == null ? null : order.getPaidAmount()); + vo.setPayTime(order == null || order.getPayTime() == null ? null : DATE_TIME_FORMATTER.format(order.getPayTime())); return vo; } diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/planning/vo/PlanningAppointmentVO.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/planning/vo/PlanningAppointmentVO.java index e3f1b93c..a4053c29 100644 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/planning/vo/PlanningAppointmentVO.java +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/planning/vo/PlanningAppointmentVO.java @@ -39,4 +39,18 @@ public class PlanningAppointmentVO { private BigDecimal amount; private String remark; private String cancelReason; + /** 风格库来源,MANAGER_APPOINTMENT 表示手动录入的款式 */ + private String productSourceType; + private String productDescription; + private String productTags; + private String productTargetAudience; + private String productPrecautions; + private String productImageFileIds; + /** 支付状态:UNPAID / PAID */ + private String paymentStatus; + /** 收款方式:OFFLINE / CASH / WECHAT / ALIPAY */ + private String paymentMethod; + private BigDecimal payAmount; + private BigDecimal paidAmount; + private String payTime; } diff --git a/JC-Salon-Core/src/test/java/com/xiaowang/jayucloud/salon/core/modules/order/service/impl/OrderServiceImplOfflinePaymentTest.java b/JC-Salon-Core/src/test/java/com/xiaowang/jayucloud/salon/core/modules/order/service/impl/OrderServiceImplOfflinePaymentTest.java index d23ee5ba..f6ec598a 100644 --- a/JC-Salon-Core/src/test/java/com/xiaowang/jayucloud/salon/core/modules/order/service/impl/OrderServiceImplOfflinePaymentTest.java +++ b/JC-Salon-Core/src/test/java/com/xiaowang/jayucloud/salon/core/modules/order/service/impl/OrderServiceImplOfflinePaymentTest.java @@ -2,8 +2,11 @@ package com.xiaowang.jayucloud.salon.core.modules.order.service.impl; import com.xiaowang.jayucloud.salon.core.modules.order.dto.OrderOfflinePaymentDTO; import com.xiaowang.jayucloud.salon.core.modules.order.entity.OrderDO; +import com.xiaowang.jayucloud.salon.core.modules.order.mapper.OrderItemMapper; import com.xiaowang.jayucloud.salon.core.modules.order.mapper.OrderMapper; import com.xiaowang.jayucloud.salon.core.modules.order.support.OrderStatus; +import com.xiaowang.jayucloud.salon.core.modules.shop.mapper.ShopMapper; +import com.xiaowang.jayucloud.salon.core.modules.user.mapper.UserMapper; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.InjectMocks; @@ -23,31 +26,43 @@ class OrderServiceImplOfflinePaymentTest { @Mock private OrderMapper orderMapper; + @Mock + private OrderItemMapper orderItemMapper; + + @Mock + private ShopMapper shopMapper; + + @Mock + private UserMapper userMapper; + @InjectMocks private OrderServiceImpl service; @Test - void rejectsNonOfflinePaymentMethod() { + void rejectsUnknownPaymentMethod() { OrderOfflinePaymentDTO dto = offlinePayment(new BigDecimal("100"), LocalDateTime.now()); - dto.setPayMethod("WECHAT"); + dto.setPayMethod("CARD"); RuntimeException error = assertThrows(RuntimeException.class, () -> service.registerOfflinePayment(1L, 9L, 2L, dto)); - assertEquals("当前仅支持线下收款,payMethod 只能为 OFFLINE", error.getMessage()); + assertEquals("payMethod 只能为 OFFLINE、CASH、WECHAT 或 ALIPAY", error.getMessage()); } @Test - void rejectsAmountMismatch() { + void allowsAmountAdjustment() { OrderDO order = order(1L, OrderStatus.PENDING_SERVICE.getCode(), "UNPAID"); order.setPayAmount(new BigDecimal("100.00")); when(orderMapper.selectByIdForUpdate(1L)).thenReturn(order); + when(orderItemMapper.selectByOrderId(1L)).thenReturn(java.util.Collections.emptyList()); OrderOfflinePaymentDTO dto = offlinePayment(new BigDecimal("90"), LocalDateTime.now()); + dto.setPayMethod("CASH"); - RuntimeException error = assertThrows(RuntimeException.class, - () -> service.registerOfflinePayment(1L, 9L, 2L, dto)); + service.registerOfflinePayment(1L, 9L, 2L, dto); - assertEquals("实收金额必须等于订单应付金额 100 元", error.getMessage()); + assertEquals("PAID", order.getPaymentStatus()); + assertEquals("CASH", order.getPaymentMethod()); + assertEquals(new BigDecimal("90"), order.getPaidAmount()); } @Test @@ -76,7 +91,7 @@ class OrderServiceImplOfflinePaymentTest { RuntimeException error = assertThrows(RuntimeException.class, () -> service.registerOfflinePayment(1L, 9L, 2L, dto)); - assertEquals("该订单已登记线下收款,金额或收款时间与首次登记不一致,不能重复登记", error.getMessage()); + assertEquals("该订单已登记收款,金额或收款方式与首次登记不一致,不能重复登记", error.getMessage()); } @Test diff --git a/JC-Salon-WeChat/api/planning.js b/JC-Salon-WeChat/api/planning.js index 67469d32..f9aaed25 100644 --- a/JC-Salon-WeChat/api/planning.js +++ b/JC-Salon-WeChat/api/planning.js @@ -51,6 +51,22 @@ module.exports = { }) }, + updateAppointment(orderItemId, data) { + return request({ + url: `/manager/planning/appointments/${orderItemId}`, + method: 'PUT', + data + }) + }, + + registerOfflinePayment(orderId, data) { + return request({ + url: `/manager/orders/${orderId}/offline-payment`, + method: 'POST', + data + }) + }, + updateStatus(orderId, status, cancelReason) { return request({ url: `/manager/planning/appointments/${orderId}/status`, diff --git a/JC-Salon-WeChat/components/action-modal/index.js b/JC-Salon-WeChat/components/action-modal/index.js index 6f5d0b2f..e702987f 100644 --- a/JC-Salon-WeChat/components/action-modal/index.js +++ b/JC-Salon-WeChat/components/action-modal/index.js @@ -10,7 +10,8 @@ Component({ layout: 'column', editable: false, placeholderText: '', - inputValue: '' + inputValue: '', + inputType: 'text' }, methods: { @@ -27,7 +28,8 @@ Component({ layout: options.layout || (options.cancelText ? 'row' : 'column'), editable: options.editable === true, placeholderText: options.placeholderText || '', - inputValue: '' + inputValue: options.inputValue === undefined || options.inputValue === null ? '' : String(options.inputValue), + inputType: options.inputType || 'text' }) }, diff --git a/JC-Salon-WeChat/components/action-modal/index.wxml b/JC-Salon-WeChat/components/action-modal/index.wxml index 80452d9e..05a475b1 100644 --- a/JC-Salon-WeChat/components/action-modal/index.wxml +++ b/JC-Salon-WeChat/components/action-modal/index.wxml @@ -3,7 +3,7 @@ {{icon === 'warning' ? '!' : 'i'}} {{title}} {{content}} - + diff --git a/JC-Salon-WeChat/pages/appointment-detail/index.js b/JC-Salon-WeChat/pages/appointment-detail/index.js index c803ed1e..ba8c23c3 100644 --- a/JC-Salon-WeChat/pages/appointment-detail/index.js +++ b/JC-Salon-WeChat/pages/appointment-detail/index.js @@ -15,6 +15,17 @@ function formatAmount(value) { return amount ? `¥${amount}` : '未记录' } +function isPaid(appointment) { + return String((appointment && appointment.paymentStatus) || '').toUpperCase() === 'PAID' +} + +const PAY_METHODS = [ + { label: '现金', value: 'CASH' }, + { label: '微信', value: 'WECHAT' }, + { label: '支付宝', value: 'ALIPAY' }, + { label: '线下其他', value: 'OFFLINE' } +] + Page({ data: { id: '', @@ -25,10 +36,13 @@ Page({ timeText: '', isUnassigned: false, showTransfer: false, + showEdit: false, showConfirm: false, + showCollect: false, showComplete: false, showCancel: false, updating: false, + paying: false, dialing: false, loadError: '' }, @@ -38,6 +52,13 @@ Page({ this.loadDetail() }, + onShow() { + if (this._needReload && this.data.id) { + this._needReload = false + this.loadDetail() + } + }, + async loadDetail() { try { const appointment = await planningApi.appointment(this.data.id) @@ -75,11 +96,16 @@ Page({ amountText: formatAmount(safeAppointment.amount), statusText: displayValue(safeAppointment.statusText, '状态未知'), remarkText: displayValue(safeAppointment.remark, '暂无备注'), - cancelReasonText: displayValue(safeAppointment.cancelReason, '') + cancelReasonText: displayValue(safeAppointment.cancelReason, ''), + paymentStatusText: isPaid(safeAppointment) + ? `已收款${safeAppointment.paidAmount !== null && safeAppointment.paidAmount !== undefined ? ` ¥${safeAppointment.paidAmount}` : ''}` + : '未收款' } const coverImages = Array.isArray(safeAppointment.coverImages) ? safeAppointment.coverImages.filter(item => Boolean(item)) : [] + const paid = isPaid(safeAppointment) + const canOperateService = !isUnassigned && (status === 1 || status === 4) this.setData({ appointment: normalizedAppointment, coverImages, @@ -88,8 +114,10 @@ Page({ avatarText: normalizedAppointment.customerNameText.slice(0, 1), timeText, showTransfer: Boolean(safeAppointment.canEdit) && !historicalBackfill, + showEdit: Boolean(safeAppointment.canEdit) && !historicalBackfill && (status === 0 || status === 1), showConfirm: Boolean(safeAppointment.canEdit) && !historicalBackfill && !isUnassigned && status === 0, - showComplete: !isUnassigned && (status === 1 || status === 4), + showCollect: canOperateService && !paid, + showComplete: canOperateService && paid, showCancel: Boolean(safeAppointment.canCancel), loadError: '' }) @@ -99,6 +127,29 @@ Page({ this.setData({ coverIndex: Number(event.detail.current) || 0 }) }, + onCoverImageError(event) { + const index = Number(event.currentTarget.dataset.index) + if (!Number.isFinite(index)) return + if (!this._coverFailedIndexes) this._coverFailedIndexes = {} + this._coverFailedIndexes[index] = true + }, + + previewCoverImage(event) { + const index = Number(event.currentTarget.dataset.index) + const failed = this._coverFailedIndexes || {} + const images = (this.data.coverImages || []).filter((url, itemIndex) => url && !failed[itemIndex]) + if (!images.length) { + wx.showToast({ title: '暂无可预览的图片', icon: 'none' }) + return + } + const target = (this.data.coverImages || [])[Number.isFinite(index) ? index : 0] + wx.previewImage({ + current: target && images.indexOf(target) >= 0 ? target : images[0], + urls: images, + fail: () => wx.showToast({ title: '图片预览失败', icon: 'none' }) + }) + }, + async updateStatus(status) { if (this.data.updating || !this.data.appointment.orderId) return if (status !== 3 && this.data.isUnassigned) { @@ -125,9 +176,84 @@ Page({ complete() { if (!this.data.showComplete || this.data.updating) return + if (!isPaid(this.data.appointment)) { + wx.showToast({ title: '请先完成收款', icon: 'none' }) + return + } this.updateStatus(2) }, + choosePayMethod() { + return new Promise(resolve => { + wx.showActionSheet({ + itemList: PAY_METHODS.map(item => item.label), + success: result => resolve(PAY_METHODS[result.tapIndex] || PAY_METHODS[0]), + fail: () => resolve(null) + }) + }) + }, + + async collect() { + if (!this.data.showCollect || this.data.paying || this.data.updating) return + const appointment = this.data.appointment || {} + const orderId = appointment.orderId + if (!orderId) return + const method = await this.choosePayMethod() + if (!method) return + const defaultAmount = appointment.payAmount !== null && appointment.payAmount !== undefined + ? appointment.payAmount + : appointment.amount + const input = await showActionModal(this, { + title: '登记收款', + content: `收款方式:${method.label}`, + editable: true, + inputType: 'digit', + inputValue: defaultAmount === null || defaultAmount === undefined ? '' : defaultAmount, + placeholderText: '请输入实收金额', + cancelText: '取消', + confirmText: '确认收款' + }) + if (!input.confirm) return + const text = String(input.content || '').trim() + const paidAmount = Number(text) + if (!text || !Number.isFinite(paidAmount) || paidAmount < 0) { + wx.showToast({ title: '请输入正确的收款金额', icon: 'none' }) + return + } + this.setData({ paying: true }) + try { + await planningApi.registerOfflinePayment(orderId, { + payMethod: method.value, + paidAmount + }) + markPlanningRefresh() + const result = await showActionModal(this, { + title: '收款已登记', + content: `实收 ¥${paidAmount},是否同时完成服务?`, + cancelText: '暂不完成', + confirmText: '同时完成服务' + }) + if (result.confirm) { + await planningApi.updateStatus(orderId, 2, '') + markPlanningRefresh() + wx.showToast({ title: '已完成服务' }) + } else { + wx.showToast({ title: '收款已登记', icon: 'success' }) + } + this.loadDetail() + } catch (error) { + showErrorToast(error, '收款登记失败') + } finally { + this.setData({ paying: false }) + } + }, + + goEdit() { + if (!this.data.showEdit) return + this._needReload = true + wx.navigateTo({ url: `/pages/appointment-form/index?mode=edit&id=${this.data.appointment.orderItemId || this.data.id}` }) + }, + async cancel() { if (!this.data.showCancel || this.data.updating) return this._cancelReason = '' diff --git a/JC-Salon-WeChat/pages/appointment-detail/index.test.js b/JC-Salon-WeChat/pages/appointment-detail/index.test.js index 2b3be24d..f9d95a8c 100644 --- a/JC-Salon-WeChat/pages/appointment-detail/index.test.js +++ b/JC-Salon-WeChat/pages/appointment-detail/index.test.js @@ -82,20 +82,58 @@ page.applyAppointment({ assignmentStatus: 'ASSIGNED', status: 4, statusText: '服务中', - historicalBackfill: true, + paymentStatus: 'UNPAID', + payAmount: 268, canEdit: false, canCancel: true }) assert.strictEqual(page.data.showTransfer, false) -assert.strictEqual(page.data.showComplete, true) +assert.strictEqual(page.data.showCollect, true) +assert.strictEqual(page.data.showComplete, false) assert.strictEqual(page.data.showCancel, true) +assert.strictEqual(page.data.appointment.paymentStatusText, '未收款') + +page.applyAppointment({ + artistId: 9, + assignmentStatus: 'ASSIGNED', + status: 1, + statusText: '待服务', + paymentStatus: 'PAID', + paidAmount: 268, + canEdit: true, + canCancel: true +}) +assert.strictEqual(page.data.showCollect, false) +assert.strictEqual(page.data.showComplete, true) +assert.strictEqual(page.data.showEdit, true) +assert.strictEqual(page.data.appointment.paymentStatusText, '已收款 ¥268') + +global.wx.previewImage = options => { + global.__preview = options +} +page.data.coverImages = ['https://cdn/a.png', 'https://cdn/b.png', 'https://cdn/c.png'] +page._coverFailedIndexes = { 1: true } +page.previewCoverImage({ currentTarget: { dataset: { index: 2 } } }) +assert.deepStrictEqual(global.__preview.urls, ['https://cdn/a.png', 'https://cdn/c.png']) +assert.strictEqual(global.__preview.current, 'https://cdn/c.png') + +page.data.coverImages = ['', ''] +let toastTitle = '' +global.wx.showToast = options => { toastTitle = options.title } +page.previewCoverImage({ currentTarget: { dataset: { index: 0 } } }) +assert.strictEqual(toastTitle, '暂无可预览的图片') const markup = fs.readFileSync(path.join(__dirname, 'index.wxml'), 'utf8') const styles = fs.readFileSync(path.join(__dirname, 'index.wxss'), 'utf8') ;['订单编号', '服务项目', '美甲师', '时长', '成交金额', '取消原因', 'remarkText', 'customerPhoneText'].forEach(text => assert(markup.includes(text))) assert.match(markup, /class="primary-btn transfer-action"/) assert.match(markup, /class="danger-btn"/) +assert.match(markup, /bindtap="previewCoverImage"/) +assert.match(markup, /class="cover-thumb/) +assert.match(markup, /bindtap="collect">完成收款/) +assert.match(markup, /bindtap="goEdit"/) assert.match(markup, /appointment\.customerPhoneAvailable && appointment\.orderId/) assert.strictEqual(markup.includes('appointment.customerId && appointment.orderId'), false) assert.match(styles, /\.transfer-action\s*\{[^}]*box-shadow/) assert.match(styles, /\.call-btn\s*\{/) +assert.match(styles, /\.cover-thumb\s*\{/) diff --git a/JC-Salon-WeChat/pages/appointment-detail/index.wxml b/JC-Salon-WeChat/pages/appointment-detail/index.wxml index dd94bf71..b86e9368 100644 --- a/JC-Salon-WeChat/pages/appointment-detail/index.wxml +++ b/JC-Salon-WeChat/pages/appointment-detail/index.wxml @@ -22,7 +22,10 @@ - {{appointment.historicalBackfill ? '历史补单 · ' : ''}}{{appointment.statusText}} + + + {{appointment.historicalBackfill ? '历史补单 · ' : ''}}{{appointment.statusText}} + @@ -49,6 +52,10 @@ 成交金额 {{appointment.amountText}} + + 收款状态 + {{appointment.paymentStatusText}} + 取消原因 @@ -64,14 +71,35 @@ - + - 左滑查看更多项目图 + + + + + + 点击图片可放大查看 @@ -79,10 +107,11 @@ {{appointment.remarkText}} - + - + + diff --git a/JC-Salon-WeChat/pages/appointment-detail/index.wxss b/JC-Salon-WeChat/pages/appointment-detail/index.wxss index 8986f73c..508ccc2f 100644 --- a/JC-Salon-WeChat/pages/appointment-detail/index.wxss +++ b/JC-Salon-WeChat/pages/appointment-detail/index.wxss @@ -96,6 +96,25 @@ font-weight: 800; } +.head-actions { + display: flex; + align-items: center; + flex-shrink: 0; + gap: 10rpx; +} + +.edit-btn { + margin: 0; + padding: 0 16rpx; + border: 1rpx solid #247b63; + border-radius: 20rpx; + background: #ffffff; + color: #247b63; + font-size: 21rpx; + font-weight: 600; + line-height: 40rpx; +} + .status-tag.completed { background: #eef2f1; color: #67766f; @@ -233,6 +252,31 @@ font-size: 20rpx; } +.cover-thumbs { + margin-top: 12rpx; + width: 100%; + white-space: nowrap; +} + +.cover-thumb-list { + display: flex; + align-items: center; + gap: 12rpx; +} + +.cover-thumb { + flex-shrink: 0; + width: 104rpx; + height: 104rpx; + border: 2rpx solid transparent; + border-radius: 12rpx; + background: #e5f4ed; +} + +.cover-thumb.active { + border-color: #247b63; +} + .note-card { padding: 24rpx; color: #71807a; diff --git a/JC-Salon-WeChat/pages/appointment-form/edit-mode.test.js b/JC-Salon-WeChat/pages/appointment-form/edit-mode.test.js new file mode 100644 index 00000000..13a47c03 --- /dev/null +++ b/JC-Salon-WeChat/pages/appointment-form/edit-mode.test.js @@ -0,0 +1,155 @@ +const assert = require('assert') +const fs = require('fs') +const path = require('path') +const planningApi = require('../../api/planning') + +let appGlobalData = { userInfo: { type: 2 } } +global.wx = { + getAccountInfoSync: () => ({ miniProgram: { envVersion: 'develop' } }), + getDeviceInfo: () => ({ platform: 'devtools' }), + removeStorageSync: () => {}, + setStorageSync: () => {}, + showToast: () => {}, + showModal: options => { if (options.success) options.success({ confirm: true }) }, + navigateTo: () => {}, + navigateBack: () => {}, + setNavigationBarTitle: () => {}, + redirectTo: () => {} +} +global.getApp = () => ({ globalData: appGlobalData }) +global.getCurrentPages = () => [] + +let definition +global.Page = value => { definition = value } +require('./index') + +function createPage() { + return { + ...definition, + data: JSON.parse(JSON.stringify(definition.data)), + setData(values) { + Object.entries(values).forEach(([key, value]) => { + const parts = key.split('.') + let target = this.data + for (let index = 0; index < parts.length - 1; index += 1) target = target[parts[index]] + target[parts[parts.length - 1]] = value + }) + } + } +} + +async function run() { + const appointmentWxml = fs.readFileSync(path.join(__dirname, 'index.wxml'), 'utf8') + const artistIndex = appointmentWxml.indexOf('bindtap="openArtistSheet"') + const timeIndex = appointmentWxml.indexOf('bindtap="openTimeSheet"') + assert.ok(artistIndex > -1 && timeIndex > -1) + assert.ok(artistIndex < timeIndex, '美甲师字段应位于预约时间之前') + assert.match(appointmentWxml, /editMode \? '保存修改' : '提交预约'/) + + planningApi.appointment = async () => ({ + orderItemId: 88, + orderId: 77, + orderNo: 'SALON-088', + customerUserId: 31, + customerName: '测试客户', + customerPhone: '138****8000', + customerPhoneAvailable: false, + artistId: 9, + artistName: '小李', + startTime: '2027-05-01T10:30:00', + endTime: '2027-05-01T11:30:00', + durationMinutes: 60, + amount: 268, + productId: 41, + productTitle: '猫眼甲', + productSourceType: 'LIBRARY', + remark: '加急', + status: 1, + canEdit: true + }) + planningApi.calendar = async () => ({ + businessStartTime: '09:00', + businessEndTime: '20:00', + artists: [{ id: 9, name: '小李' }], + schedules: [{ artistId: 9, date: '2027-05-01', status: 1, capacity: 1, startTime: '09:00', endTime: '20:00' }], + appointments: [{ orderItemId: 88, artistId: 9, startTime: '2027-05-01T10:30:00', endTime: '2027-05-01T11:30:00' }] + }) + planningApi.products = async () => ({ list: [{ id: 41, title: '猫眼甲', price: 268, approximateDuration: '60分钟' }] }) + + const page = createPage() + page.data.form.durationMinutes = '60' + await page.loadEditAppointment(88) + + assert.strictEqual(page.data.editMode, true) + assert.strictEqual(page._editMode, true) + assert.strictEqual(page.data.form.customerName, '测试客户') + assert.strictEqual(page.data.form.phone, '') + assert.strictEqual(page.data.form.appointmentDate, '2027-05-01') + assert.strictEqual(page.data.form.appointmentTime, '10:30') + assert.strictEqual(String(page.data.form.artistId), '9') + assert.strictEqual(String(page.data.form.productId), '41') + assert.strictEqual(page.data.form.amount, '268') + assert.ok(Object.keys(page.data.availableTimeGroups).length > -1 || page._editOriginalSchedule) + + const availability = await page.checkAvailability() + assert.strictEqual(availability.ok, true) + + let updatedPayload = null + let updatedId = '' + let creatorCalled = false + planningApi.updateAppointment = async (id, payload) => { + updatedId = id + updatedPayload = payload + return { orderItemId: 88 } + } + planningApi.createAppointment = async () => { + creatorCalled = true + return {} + } + page.cancelDraftSave = () => {} + await page.submit() + + assert.strictEqual(creatorCalled, false) + assert.strictEqual(updatedId, '88') + assert.strictEqual(updatedPayload.customerName, '测试客户') + assert.strictEqual(updatedPayload.amount, 268) + assert.strictEqual(updatedPayload.appointmentTime, '10:30') + + const original = page.isEditOriginalSchedule('2027-05-01', '10:30') + assert.strictEqual(original, true) + assert.strictEqual(page.isEditOriginalSchedule('2027-05-01', '11:00'), false) + + const manualPage = createPage() + planningApi.appointment = async () => ({ + orderItemId: 89, + customerName: '散客', + customerPhoneAvailable: false, + artistId: null, + startTime: '2027-05-02T09:00:00', + durationMinutes: 90, + amount: 150, + productId: 55, + productSourceType: 'MANAGER_APPOINTMENT', + productTitle: '手绘款', + productDescription: '渐变', + productImageFileIds: 'f1,f2', + coverImages: ['https://cdn/f1.png'], + status: 1, + canEdit: true + }) + planningApi.products = async () => ({ list: [] }) + planningApi.calendar = async () => ({ businessStartTime: '09:00', businessEndTime: '20:00', artists: [], schedules: [], appointments: [] }) + await manualPage.loadEditAppointment(89) + + assert.strictEqual(manualPage.data.form.productId, '') + assert.strictEqual(manualPage.data.form.manualProductTitle, '手绘款') + assert.strictEqual(manualPage.data.form.manualProductDescription, '渐变') + assert.strictEqual(manualPage.data.form.manualProductImages.length, 2) + assert.strictEqual(manualPage.data.form.artistId, '') + assert.strictEqual(manualPage.data.selectedArtist.id, '__unassigned__') +} + +run().catch(error => { + console.error(error) + process.exitCode = 1 +}) diff --git a/JC-Salon-WeChat/pages/appointment-form/index.js b/JC-Salon-WeChat/pages/appointment-form/index.js index 2b8fb3d0..be1683fd 100644 --- a/JC-Salon-WeChat/pages/appointment-form/index.js +++ b/JC-Salon-WeChat/pages/appointment-form/index.js @@ -236,8 +236,9 @@ function isCancelledAppointment(item) { return item.status === 3 || item.statusText === '已取消' } -function buildBusyRanges(appointments, form) { +function buildBusyRanges(appointments, form, excludeOrderItemId) { return (appointments || []) + .filter(item => !excludeOrderItemId || String(item.orderItemId) !== String(excludeOrderItemId)) .filter(item => String(item.artistId) === String(form.artistId)) .filter(item => normalizeAppointmentDate(item) === form.appointmentDate) .filter(item => !isCancelledAppointment(item)) @@ -278,12 +279,12 @@ function resolveBusinessHours(calendar, targetDate) { return { start, end } } -function buildAvailableTimeGroups(calendar, form, durationMinutes) { +function buildAvailableTimeGroups(calendar, form, durationMinutes, excludeOrderItemId) { const schedules = (calendar.schedules || []) .filter(item => String(item.artistId) === String(form.artistId)) .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 busyRanges = buildBusyRanges(calendar.appointments || [], form, excludeOrderItemId) const today = dateUtil.formatDate(new Date()) const now = new Date() const currentMinute = now.getHours() * 60 + now.getMinutes() @@ -366,9 +367,9 @@ function buildTimeValues(durationMinutes, businessStart, businessEnd, appointmen return values } -function buildTimePickerSlots(calendar, form, durationMinutes) { +function buildTimePickerSlots(calendar, form, durationMinutes, excludeOrderItemId) { const schedules = calendar.schedules || [] - const busyRanges = form.artistId ? buildBusyRanges(calendar.appointments || [], form) : [] + const busyRanges = form.artistId ? buildBusyRanges(calendar.appointments || [], form, excludeOrderItemId) : [] const businessHours = resolveBusinessHours(calendar, form.appointmentDate) if (!businessHours.start) return [] const businessStart = businessHours.start @@ -648,10 +649,33 @@ Page({ appointmentDateBadge: '', appointmentDateLong: '', availableTimeGroups: [], - loading: false + loading: false, + editMode: false }, onLoad(options = {}) { + const editId = options && options.mode === 'edit' ? String(options.id || '') : '' + if (editId) { + if (!canCreateAppointment()) { + wx.showToast({ title: '当前账号仅支持查看预约', icon: 'none' }) + wx.navigateBack() + return + } + this._editMode = true + this._editAppointmentId = editId + this._draftReady = false + this._draftPersistenceDisabled = true + this.setData({ + editMode: true, + canCreateAppointment: canCreateAppointment(), + canManageShopSettings: isShopManager(), + 'form.durationMinutes': '60', + draftSavedAtText: '' + }) + wx.setNavigationBarTitle({ title: '编辑预约' }) + this.loadEditAppointment(editId) + return + } const manualDateMode = options && options.dateMode === 'manual' const today = dateUtil.formatDate(new Date()) if (options && options.date && options.date < today) { @@ -748,6 +772,88 @@ Page({ wx.navigateTo({ url: '/pages/shop-settings/index' }) }, + async loadEditAppointment(id) { + this._editMode = true + this._editAppointmentId = String(id || '') + this._draftPersistenceDisabled = true + this.setData({ loading: true, editMode: true }) + try { + const appointment = await planningApi.appointment(id) + const startTime = String(appointment.startTime || '') + const appointmentDate = startTime ? startTime.slice(0, 10) : String(appointment.date || '') + const appointmentTime = startTime ? startTime.slice(11, 16) : '' + const manualProduct = String(appointment.productSourceType || '') === 'MANAGER_APPOINTMENT' + const manualImages = String(appointment.productImageFileIds || '') + .split(',') + .map(fileId => fileId.trim()) + .filter(Boolean) + .slice(0, 9) + .map((fileId, index) => ({ + fileId, + fileUrl: index === 0 && appointment.coverImages && appointment.coverImages[0] ? String(appointment.coverImages[0]) : '', + previewUrl: index === 0 && appointment.coverImages && appointment.coverImages[0] ? String(appointment.coverImages[0]) : '' + })) + const form = { + ...this.data.form, + customerUserId: appointment.customerUserId ? String(appointment.customerUserId) : '', + customerName: appointment.customerName || '', + phone: appointment.customerPhoneAvailable ? String(appointment.customerPhone || '') : '', + wechatId: '', + appointmentDate, + appointmentTime, + amount: appointment.amount === null || appointment.amount === undefined ? '' : String(appointment.amount), + productId: manualProduct ? '' : (appointment.productId ? String(appointment.productId) : ''), + manualProductTitle: manualProduct ? String(appointment.productTitle || '') : '', + manualProductPrice: manualProduct ? (appointment.amount === null || appointment.amount === undefined ? '' : String(appointment.amount)) : '', + manualProductDescription: manualProduct ? String(appointment.productDescription || '') : '', + manualProductTags: manualProduct ? String(appointment.productTags || '') : '', + manualProductTargetAudience: manualProduct ? String(appointment.productTargetAudience || '') : '', + manualProductPrecautions: manualProduct ? String(appointment.productPrecautions || '') : '', + manualProductImageFileIds: manualImages.map(image => image.fileId).join(','), + manualProductImageUrl: manualImages[0] ? manualImages[0].previewUrl || manualImages[0].fileUrl : '', + manualProductImages: manualImages, + durationMinutes: appointment.durationMinutes ? String(appointment.durationMinutes) : '60', + artistId: appointment.artistId ? String(appointment.artistId) : '', + createCustomerRecord: false, + remark: appointment.remark || '' + } + this._editOriginalSchedule = { + appointmentDate, + appointmentTime, + artistId: form.artistId, + durationMinutes: form.durationMinutes + } + const dateLabels = buildAppointmentDateLabels(appointmentDate) + this.setData({ + form, + unifiedStyleDescription: String(appointment.remark || appointment.productDescription || ''), + manualProductTitleLength: String(form.manualProductTitle).length, + selectedArtist: appointment.artistId + ? { id: String(appointment.artistId), name: appointment.artistName || '' } + : { id: '__unassigned__', name: '暂不分配美甲师' }, + draftSavedAtText: '', + appointmentDayLabel: dateLabels.day, + appointmentDateBadge: dateLabels.badge, + appointmentDateLong: dateLabels.long, + durationManuallyChanged: true, + canCreateAppointment: canCreateAppointment() + }) + await this.loadOptions() + } catch (error) { + this.setData({ loading: false }) + wx.showToast({ title: toUserMessage(error, '预约加载失败'), icon: 'none' }) + return + } + this.setData({ loading: false }) + }, + + isEditOriginalSchedule(date, time) { + const origin = this._editOriginalSchedule + return Boolean(this._editMode && origin + && String(date || '') === String(origin.appointmentDate || '') + && String(time || '') === String(origin.appointmentTime || '')) + }, + async loadOptions() { this.setData({ loadingProducts: true }) try { @@ -1099,6 +1205,7 @@ Page({ }, persistDraft(showToast) { + if (this._editMode) return try { if (!hasDraftContent( this.data.form, @@ -1595,7 +1702,7 @@ Page({ timePickerHours: [], timePickerMinutes: [], selectedTimeCandidate: '', - 'form.appointmentTime': '', + 'form.appointmentTime': this.isEditOriginalSchedule(form.appointmentDate, form.appointmentTime) ? form.appointmentTime : '', timeError: message, businessHoursMissing: !closed, timeLoading: false, @@ -1665,7 +1772,7 @@ Page({ timePickerHours: [], timePickerMinutes: [], selectedTimeCandidate: '', - 'form.appointmentTime': '', + 'form.appointmentTime': this.isEditOriginalSchedule(form.appointmentDate, form.appointmentTime) ? form.appointmentTime : '', timeError: message, businessHoursMissing: !closed, timeLoading: false, @@ -1673,9 +1780,9 @@ Page({ }) return } - const availableTimeGroups = buildAvailableTimeGroups(calendar, form, durationMinutes) + const availableTimeGroups = buildAvailableTimeGroups(calendar, form, durationMinutes, this._editAppointmentId) const availableTimes = flattenTimeGroups(availableTimeGroups).map(item => item.value) - const timePickerSlots = buildTimePickerSlots(calendar, form, durationMinutes) + const timePickerSlots = buildTimePickerSlots(calendar, form, durationMinutes, this._editAppointmentId) const patch = { availableTimeGroups, timePickerSlots, @@ -1685,7 +1792,8 @@ Page({ businessHoursMissing: false, timeSelectTip: availableTimes.length > 0 ? '请选择预约时间' : '当前美甲师当天暂无可约时间' } - if (form.appointmentTime && !availableTimes.includes(form.appointmentTime)) { + if (form.appointmentTime && !availableTimes.includes(form.appointmentTime) + && !this.isEditOriginalSchedule(form.appointmentDate, form.appointmentTime)) { patch['form.appointmentTime'] = '' } this.setData(patch) @@ -1816,21 +1924,28 @@ Page({ } const startMinute = dateUtil.minutesOfDay(appointmentTime) const endMinute = startMinute + durationMinutes + const editOriginalSchedule = this.isEditOriginalSchedule(form.appointmentDate, appointmentTime) if (!this.data.businessStartTime || !this.data.businessEndTime) { + if (editOriginalSchedule) { + this.setData({ conflictTip: '沿用当前预约时间', conflictLevel: 'free' }) + return { ok: true } + } const tip = this.data.businessHoursMissing ? '门店营业时间尚未设置,请先完成设置' : '营业时间暂不可用,请稍后重试' this.setData({ conflictTip: tip, conflictLevel: 'danger' }) return { ok: false, tip } } - if (startMinute < dateUtil.minutesOfDay(this.data.businessStartTime) || endMinute > dateUtil.minutesOfDay(this.data.businessEndTime)) { + if (!editOriginalSchedule + && (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())) { + if (!editOriginalSchedule && (form.appointmentDate < today + || (form.appointmentDate === today && startMinute <= now.getHours() * 60 + now.getMinutes()))) { const tip = '该时间已过,请改选未来时段或使用历史补单' this.setData({ conflictTip: tip, conflictLevel: 'danger' }) return { ok: false, tip } @@ -1853,6 +1968,7 @@ Page({ return { ok: false, tip } } const conflicts = (calendar.appointments || []).filter(item => { + if (this._editMode && String(item.orderItemId) === String(this._editAppointmentId)) return false if (String(item.artistId) !== String(form.artistId) || normalizeAppointmentDate(item) !== form.appointmentDate) return false if (isCancelledAppointment(item)) return false const itemStart = resolveAppointmentStartMinute(item) @@ -1968,7 +2084,7 @@ Page({ wx.showToast({ title: '当前账号仅支持查看预约', icon: 'none' }) return } - if (isShopBusinessExpired()) { + if (!this._editMode && isShopBusinessExpired()) { await showBusinessExpiryNotice(this) return } @@ -1976,7 +2092,9 @@ Page({ 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())) { + const editOriginalSchedule = this.isEditOriginalSchedule(form.appointmentDate, form.appointmentTime) + if (!editOriginalSchedule && (form.appointmentDate < today + || (form.appointmentDate === today && selectedMinute <= now.getHours() * 60 + now.getMinutes()))) { await this.showBackfillPrompt(form.appointmentDate, form.appointmentDate < today ? '所选日期已经过去' : '所选时段已经过去') return } @@ -2059,7 +2177,15 @@ Page({ payload.manualProductPrecautions = String(form.manualProductPrecautions || '').trim() || undefined payload.manualProductImageFileIds = String(form.manualProductImageFileIds || '').trim() || undefined } - const result = await planningApi.createAppointment(payload) + const result = this._editMode + ? await planningApi.updateAppointment(this._editAppointmentId, payload) + : await planningApi.createAppointment(payload) + if (this._editMode) { + markPlanningRefresh() + wx.showToast({ title: '已保存修改', icon: 'success' }) + wx.navigateBack() + return + } this.cancelDraftSave() this._draftReady = false this._draftPersistenceDisabled = true @@ -2074,7 +2200,7 @@ Page({ if ((error.message || '').includes('有效期') || (error.message || '').includes('到期')) { await showBusinessExpiryNotice(this) } else { - showErrorToast(error, '提交失败') + showErrorToast(error, this._editMode ? '保存失败' : '提交失败') } } finally { this.setData({ loading: false }) diff --git a/JC-Salon-WeChat/pages/appointment-form/index.wxml b/JC-Salon-WeChat/pages/appointment-form/index.wxml index 0123d243..9f0e2c53 100644 --- a/JC-Salon-WeChat/pages/appointment-form/index.wxml +++ b/JC-Salon-WeChat/pages/appointment-form/index.wxml @@ -1,8 +1,8 @@ - NEW APPOINTMENT - 安排一场美甲 + {{editMode ? 'EDIT APPOINTMENT' : 'NEW APPOINTMENT'}} + {{editMode ? '调整这场预约' : '安排一场美甲'}} ◷{{appointmentDateBadge}} @@ -47,16 +47,16 @@ › - - ◷ - *预约时间{{appointmentDayLabel}} {{form.appointmentTime}} · {{form.durationMinutes}}分钟{{timeSelectTip}}{{selectedArtist.name || '暂不分配美甲师'}} - › - ♙ 服务美甲师(选填)已选择暂不分配美甲师{{selectedArtist.name || '请选择美甲师或暂不分配'}} › + + ◷ + *预约时间{{appointmentDayLabel}} {{form.appointmentTime}} · {{form.durationMinutes}}分钟{{timeSelectTip}}{{selectedArtist.name || '暂不分配美甲师'}} + › + @@ -75,7 +75,7 @@ 已选择系统客户 - {{draftSavedAtText}} + {{draftSavedAtText}} 时段检查{{conflictTip}} @@ -148,6 +148,6 @@ - + diff --git a/JC-Salon-WeChat/utils/action-modal.js b/JC-Salon-WeChat/utils/action-modal.js index dc8ea084..a1bc9968 100644 --- a/JC-Salon-WeChat/utils/action-modal.js +++ b/JC-Salon-WeChat/utils/action-modal.js @@ -12,6 +12,8 @@ function showActionModal(page, options = {}) { layout: options.layout, editable: options.editable, placeholderText: options.placeholderText, + inputValue: options.inputValue, + inputType: options.inputType, onClose: resolve }) })