From c952a913e8788c3d398f87cf9b97d120d25fb8f4 Mon Sep 17 00:00:00 2001 From: xiaowang <2161656029@qq.com> Date: Tue, 20 Oct 2026 13:29:55 +0800 Subject: [PATCH] =?UTF-8?q?=E4=BC=98=E5=8C=96=E9=A2=84=E7=BA=A6=E8=A1=A8?= =?UTF-8?q?=E5=8D=95=E5=B9=B6=E6=94=AF=E6=8C=81=E6=95=A3=E5=AE=A2=E9=A2=84?= =?UTF-8?q?=E7=BA=A6?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../dto/PlanningAppointmentCreateDTO.java | 2 + .../service/impl/PlanningServiceImpl.java | 52 +- .../service/impl/PlanningServiceImplTest.java | 348 ++++++++++++ .../components/entity-selector-sheet/index.js | 11 + .../entity-selector-sheet/index.wxml | 13 +- .../entity-selector-sheet/index.wxss | 60 ++ .../product-selector-sheet/index.js | 1 + .../product-selector-sheet/index.wxml | 2 +- .../appointment-form/entity-selector.test.js | 11 +- .../pages/appointment-form/index.js | 529 +++++++++++++----- .../pages/appointment-form/index.wxml | 165 ++---- .../pages/appointment-form/index.wxss | 368 +++++++++++- .../appointment-form/modal-scroll.test.js | 4 +- .../appointment-form/product-selector.test.js | 15 +- .../pages/appointment-form/unassigned.test.js | 26 + .../2026-10-20-salon预约表单与客户身份设计.md | 35 ++ docs/项目变更记录.md | 9 + 17 files changed, 1376 insertions(+), 275 deletions(-) create mode 100644 JC-Salon-Core/src/test/java/com/xiaowang/jayucloud/salon/core/modules/planning/service/impl/PlanningServiceImplTest.java create mode 100644 docs/superpowers/specs/2026-10-20-salon预约表单与客户身份设计.md 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 b11e4eea..ba3d50f1 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 @@ -16,6 +16,8 @@ public class PlanningAppointmentCreateDTO { private String appointmentTime; private String appointmentStartTime; private Integer durationMinutes; + private BigDecimal amount; + private Boolean createCustomerRecord; private String manualProductTitle; private BigDecimal manualProductPrice; private String manualProductDescription; 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 d7a04df9..65bf2bd0 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 @@ -44,6 +44,7 @@ import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import java.math.BigDecimal; +import java.math.RoundingMode; import java.time.Duration; import java.time.LocalDate; import java.time.LocalDateTime; @@ -183,11 +184,18 @@ public class PlanningServiceImpl implements PlanningService { ensureWithinBusinessHours(shopId, startTime, endTime); BigDecimal unitPrice = product.getPrice() == null ? BigDecimal.ZERO : product.getPrice(); - BigDecimal amount = unitPrice.multiply(BigDecimal.valueOf(quantity)); + BigDecimal amount = dto.getAmount() == null + ? unitPrice.multiply(BigDecimal.valueOf(quantity)) + : dto.getAmount(); + if (amount.compareTo(BigDecimal.ZERO) < 0) { + throw new RuntimeException("成交金额不能小于0"); + } OrderDO order = new OrderDO(); order.setOrderNo("ORD" + snowflakeIdGenerator.nextIdString()); - order.setUserId(customer.getId()); + order.setUserId(customer == null ? null : customer.getId()); + order.setCustomerNameSnapshot(customer == null ? trimToNull(dto.getCustomerName()) : null); + order.setCustomerPhoneSnapshot(customer == null ? trimToNull(dto.getPhone()) : null); order.setShopId(shopId); order.setTotalAmount(amount); order.setActualAmount(amount); @@ -208,7 +216,7 @@ public class PlanningServiceImpl implements PlanningService { item.setOrderId(order.getId()); item.setProductId(product.getId()); item.setQuantity(quantity); - item.setPrice(unitPrice); + item.setPrice(amount.divide(BigDecimal.valueOf(quantity), 2, RoundingMode.HALF_UP)); item.setArtistId(artist == null ? null : artist.getId()); item.setAppointmentTime(startTime); item.setIsDelete(0); @@ -295,7 +303,8 @@ public class PlanningServiceImpl implements PlanningService { Map artistMap = listArtists(order.getShopId(), item.getArtistId()).stream() .collect(Collectors.toMap(PlanningArtistVO::getId, Function.identity(), (a, b) -> a)); Map customerMap = order.getUserId() == null ? Map.of() : loadUsers(Set.of(order.getUserId())); - return toAppointmentVO(reservation, item, order, product, customerMap.get(order.getUserId()), artistMap); + UserDO customer = order.getUserId() == null ? null : customerMap.get(order.getUserId()); + return toAppointmentVO(reservation, item, order, product, customer, artistMap); } @Override @@ -516,7 +525,7 @@ public class PlanningServiceImpl implements PlanningService { continue; } ProductDO product = item == null ? null : productMap.get(item.getProductId()); - UserDO customer = customerMap.get(order.getUserId()); + UserDO customer = order.getUserId() == null ? null : customerMap.get(order.getUserId()); result.add(toAppointmentVO(reservation, item, order, product, customer, artistMap)); if (reservation.getOrderItemId() != null) { reservationItemIds.add(reservation.getOrderItemId()); @@ -531,7 +540,7 @@ public class PlanningServiceImpl implements PlanningService { continue; } ProductDO product = productMap.get(item.getProductId()); - UserDO customer = customerMap.get(order.getUserId()); + UserDO customer = order.getUserId() == null ? null : customerMap.get(order.getUserId()); result.add(toAppointmentVO(null, item, order, product, customer, artistMap)); } result.sort(Comparator.comparing(PlanningAppointmentVO::getStartTime, Comparator.nullsLast(String::compareTo)) @@ -731,12 +740,19 @@ public class PlanningServiceImpl implements PlanningService { private ProductDO createManualAppointmentProduct(PlanningAppointmentCreateDTO dto, Long shopId) { String title = trimToNull(dto.getManualProductTitle()); + String imageFileIds = trimToNull(dto.getManualProductImageFileIds()); if (!hasText(title)) { - throw new RuntimeException("请选择预约作品或填写手动作品名称"); + title = firstNonBlank(dto.getCustomerName(), hasText(imageFileIds) ? "散客款式" : null); } - BigDecimal price = dto.getManualProductPrice(); - if (price == null || price.compareTo(BigDecimal.ZERO) < 0) { - throw new RuntimeException("手动作品价格不能小于0"); + if (!hasText(title) && !hasText(imageFileIds)) { + throw new RuntimeException("请填写美甲款式名称或上传款式图片"); + } + BigDecimal price = dto.getManualProductPrice() == null ? dto.getAmount() : dto.getManualProductPrice(); + if (price == null) { + throw new RuntimeException("成交金额不能为空"); + } + if (price.compareTo(BigDecimal.ZERO) < 0) { + throw new RuntimeException("成交金额不能小于0"); } int durationMinutes = requireAppointmentDuration(dto.getDurationMinutes()); ProductDO product = new ProductDO(); @@ -746,7 +762,7 @@ public class PlanningServiceImpl implements PlanningService { product.setTags(trimToNull(dto.getManualProductTags())); product.setTargetAudience(trimToNull(dto.getManualProductTargetAudience())); product.setPrecautions(trimToNull(dto.getManualProductPrecautions())); - product.setImageFileIds(trimToNull(dto.getManualProductImageFileIds())); + product.setImageFileIds(imageFileIds); product.setPrice(price); product.setLikeCount(0); product.setCollectCount(0); @@ -786,11 +802,17 @@ public class PlanningServiceImpl implements PlanningService { } return customer; } - String customerName = firstNonBlank(dto.getCustomerName(), dto.getPhone()); - if (!hasText(customerName)) { - throw new RuntimeException("客户姓名不能为空"); - } + String customerName = trimToNull(dto.getCustomerName()); String phone = trimToNull(dto.getPhone()); + if (!hasText(customerName) && hasText(phone)) { + throw new RuntimeException("填写手机号时请同时填写客户姓名"); + } + if (Boolean.FALSE.equals(dto.getCreateCustomerRecord())) { + return null; + } + if (!hasText(customerName)) { + return null; + } List matches = userService.findCustomerMatches(customerName, phone, shopId); if (matches.size() > 1) { 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 new file mode 100644 index 00000000..599b10c4 --- /dev/null +++ b/JC-Salon-Core/src/test/java/com/xiaowang/jayucloud/salon/core/modules/planning/service/impl/PlanningServiceImplTest.java @@ -0,0 +1,348 @@ +package com.xiaowang.jayucloud.salon.core.modules.planning.service.impl; + +import com.baomidou.mybatisplus.core.conditions.Wrapper; +import com.xiaowang.jayucloud.salon.core.modules.artist.mapper.ArtistScheduleExceptionMapper; +import com.xiaowang.jayucloud.salon.core.modules.artist.mapper.ArtistScheduleMapper; +import com.xiaowang.jayucloud.salon.core.modules.artist.mapper.NailArtistInfoMapper; +import com.xiaowang.jayucloud.salon.core.modules.order.entity.OrderDO; +import com.xiaowang.jayucloud.salon.core.modules.order.entity.OrderItemDO; +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.service.OrderService; +import com.xiaowang.jayucloud.salon.core.modules.order.support.OrderStatus; +import com.xiaowang.jayucloud.salon.core.modules.planning.dto.PlanningAppointmentStatusDTO; +import com.xiaowang.jayucloud.salon.core.modules.planning.dto.PlanningAppointmentCreateDTO; +import com.xiaowang.jayucloud.salon.core.modules.planning.mapper.AppointmentReservationMapper; +import com.xiaowang.jayucloud.salon.core.modules.planning.service.AppointmentCapacityService; +import com.xiaowang.jayucloud.salon.core.modules.product.mapper.ProductMapper; +import com.xiaowang.jayucloud.salon.core.modules.product.entity.ProductDO; +import com.xiaowang.jayucloud.salon.core.modules.security.support.AdminScopeHelper; +import com.xiaowang.jayucloud.salon.core.modules.shop.mapper.ShopMapper; +import com.xiaowang.jayucloud.salon.core.modules.shop.entity.ShopDO; +import com.xiaowang.jayucloud.salon.core.modules.user.entity.UserDO; +import com.xiaowang.jayucloud.salon.core.modules.user.mapper.UserMapper; +import com.xiaowang.jayucloud.salon.core.modules.user.service.UserService; +import com.xiaowang.jayucloud.salon.core.support.id.TimeOrderedSnowflakeIdGenerator; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.Mock; +import org.mockito.ArgumentCaptor; +import org.mockito.junit.jupiter.MockitoExtension; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.doAnswer; +import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.spy; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +@ExtendWith(MockitoExtension.class) +class PlanningServiceImplTest { + + @Mock private AdminScopeHelper adminScopeHelper; + @Mock private UserMapper userMapper; + @Mock private UserService userService; + @Mock private NailArtistInfoMapper nailArtistInfoMapper; + @Mock private ArtistScheduleMapper artistScheduleMapper; + @Mock private ArtistScheduleExceptionMapper artistScheduleExceptionMapper; + @Mock private AppointmentReservationMapper appointmentReservationMapper; + @Mock private OrderMapper orderMapper; + @Mock private OrderItemMapper orderItemMapper; + @Mock private ProductMapper productMapper; + @Mock private ShopMapper shopMapper; + @Mock private AppointmentCapacityService appointmentCapacityService; + @Mock private OrderService orderService; + @Mock private TimeOrderedSnowflakeIdGenerator snowflakeIdGenerator; + + private PlanningServiceImpl service; + + @BeforeEach + void setUp() { + service = new PlanningServiceImpl(adminScopeHelper, userMapper, userService, nailArtistInfoMapper, artistScheduleMapper, + artistScheduleExceptionMapper, appointmentReservationMapper, orderMapper, orderItemMapper, + productMapper, shopMapper, appointmentCapacityService, orderService, snowflakeIdGenerator); + } + + @Test + void rejectsCompletingUnassignedAppointment() { + UserDO operator = new UserDO(); + OrderDO order = order(11L, OrderStatus.PENDING_SERVICE.getCode()); + when(orderMapper.selectById(11L)).thenReturn(order); + when(orderItemMapper.selectCount(any(Wrapper.class))).thenReturn(1L); + PlanningAppointmentStatusDTO dto = new PlanningAppointmentStatusDTO(); + dto.setStatus(OrderStatus.COMPLETED.getCode()); + + RuntimeException error = assertThrows(RuntimeException.class, () -> service.updateStatus(operator, 11L, dto)); + + assertEquals("请先分配员工", error.getMessage()); + verify(orderService, never()).processOrder(11L, OrderStatus.COMPLETED.getCode()); + } + + @Test + void allowsCancellingUnassignedAppointment() { + UserDO operator = new UserDO(); + OrderDO order = order(12L, OrderStatus.PENDING_SERVICE.getCode()); + when(orderMapper.selectById(12L)).thenReturn(order); + PlanningAppointmentStatusDTO dto = new PlanningAppointmentStatusDTO(); + dto.setStatus(OrderStatus.CANCELLED.getCode()); + + service.updateStatus(operator, 12L, dto); + + verify(orderService).processOrder(12L, OrderStatus.CANCELLED.getCode()); + } + + @Test + void createsUnassignedAppointmentWithoutReservation() { + service = spy(service); + UserDO operator = new UserDO(); + operator.setType(2); + UserDO customer = new UserDO(); + customer.setId(31L); + customer.setType(0); + ProductDO product = new ProductDO(); + product.setId(41L); + product.setShopId(21L); + product.setTitle("纯色美甲"); + product.setPrice(java.math.BigDecimal.valueOf(99)); + product.setIsDelete(0); + ShopDO shop = new ShopDO(); + shop.setId(21L); + shop.setBusinessHours("10:00-22:00"); + when(adminScopeHelper.resolveShopScope(operator, null)).thenReturn(21L); + when(productMapper.selectById(41L)).thenReturn(product); + when(userMapper.selectById(31L)).thenReturn(customer); + when(shopMapper.selectById(21L)).thenReturn(shop); + when(snowflakeIdGenerator.nextIdString()).thenReturn("10001"); + doAnswer(invocation -> { + OrderDO value = invocation.getArgument(0); + value.setId(51L); + return 1; + }).when(orderMapper).insert(any(OrderDO.class)); + doAnswer(invocation -> { + OrderItemDO value = invocation.getArgument(0); + value.setId(61L); + return 1; + }).when(orderItemMapper).insert(any(OrderItemDO.class)); + doReturn(new com.xiaowang.jayucloud.salon.core.modules.planning.vo.PlanningAppointmentVO()) + .when(service).getAppointment(operator, 61L); + PlanningAppointmentCreateDTO dto = new PlanningAppointmentCreateDTO(); + dto.setCustomerUserId(31L); + dto.setProductId(41L); + dto.setAppointmentDate("2026-10-13"); + dto.setAppointmentTime("14:00"); + dto.setDurationMinutes(60); + + service.createAppointment(operator, dto); + + ArgumentCaptor itemCaptor = ArgumentCaptor.forClass(OrderItemDO.class); + verify(orderItemMapper).insert(itemCaptor.capture()); + assertNull(itemCaptor.getValue().getArtistId()); + verify(appointmentCapacityService, never()).reserveConfirmedOrThrow( + any(), any(), any(), any(), any(), any(), any(), any()); + } + + @Test + void createsWalkInAppointmentWithPhotoOnlyStyleAndSnapshotAmount() { + service = spy(service); + UserDO operator = new UserDO(); + operator.setType(2); + ShopDO shop = new ShopDO(); + shop.setId(21L); + shop.setBusinessHours("10:00-22:00"); + when(adminScopeHelper.resolveShopScope(operator, null)).thenReturn(21L); + when(shopMapper.selectById(21L)).thenReturn(shop); + when(snowflakeIdGenerator.nextIdString()).thenReturn("10002"); + doAnswer(invocation -> { + ProductDO value = invocation.getArgument(0); + value.setId(42L); + return 1; + }).when(productMapper).insert(any(ProductDO.class)); + doAnswer(invocation -> { + OrderDO value = invocation.getArgument(0); + value.setId(52L); + return 1; + }).when(orderMapper).insert(any(OrderDO.class)); + doAnswer(invocation -> { + OrderItemDO value = invocation.getArgument(0); + value.setId(62L); + return 1; + }).when(orderItemMapper).insert(any(OrderItemDO.class)); + doReturn(new com.xiaowang.jayucloud.salon.core.modules.planning.vo.PlanningAppointmentVO()) + .when(service).getAppointment(operator, 62L); + + PlanningAppointmentCreateDTO dto = new PlanningAppointmentCreateDTO(); + dto.setCustomerName("小鹿"); + dto.setCreateCustomerRecord(false); + dto.setManualProductImageFileIds("file-42"); + dto.setAmount(java.math.BigDecimal.valueOf(168)); + dto.setAppointmentDate("2026-10-22"); + dto.setAppointmentTime("14:00"); + dto.setDurationMinutes(60); + + service.createAppointment(operator, dto); + + ArgumentCaptor productCaptor = ArgumentCaptor.forClass(ProductDO.class); + verify(productMapper).insert(productCaptor.capture()); + assertEquals("小鹿", productCaptor.getValue().getTitle()); + assertEquals("file-42", productCaptor.getValue().getImageFileIds()); + assertEquals(java.math.BigDecimal.valueOf(168), productCaptor.getValue().getPrice()); + + ArgumentCaptor orderCaptor = ArgumentCaptor.forClass(OrderDO.class); + verify(orderMapper).insert(orderCaptor.capture()); + assertNull(orderCaptor.getValue().getUserId()); + assertEquals("小鹿", orderCaptor.getValue().getCustomerNameSnapshot()); + assertEquals(java.math.BigDecimal.valueOf(168), orderCaptor.getValue().getActualAmount()); + + ArgumentCaptor itemCaptor = ArgumentCaptor.forClass(OrderItemDO.class); + verify(orderItemMapper).insert(itemCaptor.capture()); + assertEquals(0, itemCaptor.getValue().getPrice().compareTo(java.math.BigDecimal.valueOf(168))); + verify(userService, never()).createManagerCustomer(any(), any(), any()); + } + + @Test + void createsWalkInAppointmentWithoutCustomerUsingWalkInStyleTitle() { + service = spy(service); + UserDO operator = new UserDO(); + operator.setType(2); + ShopDO shop = new ShopDO(); + shop.setId(21L); + shop.setBusinessHours("10:00-22:00"); + when(adminScopeHelper.resolveShopScope(operator, null)).thenReturn(21L); + when(shopMapper.selectById(21L)).thenReturn(shop); + when(snowflakeIdGenerator.nextIdString()).thenReturn("10003"); + doAnswer(invocation -> { + ProductDO value = invocation.getArgument(0); + value.setId(43L); + return 1; + }).when(productMapper).insert(any(ProductDO.class)); + doAnswer(invocation -> { + OrderDO value = invocation.getArgument(0); + value.setId(53L); + return 1; + }).when(orderMapper).insert(any(OrderDO.class)); + doAnswer(invocation -> { + OrderItemDO value = invocation.getArgument(0); + value.setId(63L); + return 1; + }).when(orderItemMapper).insert(any(OrderItemDO.class)); + doReturn(new com.xiaowang.jayucloud.salon.core.modules.planning.vo.PlanningAppointmentVO()) + .when(service).getAppointment(operator, 63L); + + PlanningAppointmentCreateDTO dto = new PlanningAppointmentCreateDTO(); + dto.setCreateCustomerRecord(false); + dto.setManualProductImageFileIds("file-43"); + dto.setAmount(java.math.BigDecimal.valueOf(88)); + dto.setAppointmentDate("2026-10-22"); + dto.setAppointmentTime("14:00"); + dto.setDurationMinutes(45); + + service.createAppointment(operator, dto); + + ArgumentCaptor productCaptor = ArgumentCaptor.forClass(ProductDO.class); + verify(productMapper).insert(productCaptor.capture()); + assertEquals("散客款式", productCaptor.getValue().getTitle()); + + ArgumentCaptor orderCaptor = ArgumentCaptor.forClass(OrderDO.class); + verify(orderMapper).insert(orderCaptor.capture()); + assertNull(orderCaptor.getValue().getUserId()); + assertNull(orderCaptor.getValue().getCustomerNameSnapshot()); + assertNull(orderCaptor.getValue().getCustomerPhoneSnapshot()); + verify(userService, never()).createManagerCustomer(any(), any(), any()); + } + + @Test + void readsWalkInAppointmentCustomerSnapshotWithoutLookingUpNullUserId() { + UserDO operator = new UserDO(); + operator.setType(2); + OrderDO order = order(54L, OrderStatus.PENDING_SERVICE.getCode()); + order.setCustomerNameSnapshot("散客预约"); + order.setCustomerPhoneSnapshot("13800138000"); + OrderItemDO item = new OrderItemDO(); + item.setId(64L); + item.setOrderId(54L); + item.setQuantity(1); + item.setAppointmentTime(java.time.LocalDateTime.of(2026, 10, 22, 14, 0)); + + when(orderItemMapper.selectById(64L)).thenReturn(item); + when(orderMapper.selectById(54L)).thenReturn(order); + when(userMapper.selectList(any(Wrapper.class))).thenReturn(java.util.List.of()); + + com.xiaowang.jayucloud.salon.core.modules.planning.vo.PlanningAppointmentVO result = + service.getAppointment(operator, 64L); + + assertNull(result.getCustomerId()); + assertEquals("散客预约", result.getCustomerName()); + assertEquals("13800138000", result.getCustomerPhone()); + verify(userMapper, never()).selectById(org.mockito.ArgumentMatchers.isNull()); + } + + @Test + void createsCustomerInAppointmentFlowWhenConfirmed() { + service = spy(service); + UserDO operator = new UserDO(); + operator.setType(2); + UserDO customer = new UserDO(); + customer.setId(71L); + customer.setType(0); + ProductDO product = new ProductDO(); + product.setId(41L); + product.setShopId(21L); + product.setTitle("纯色美甲"); + product.setPrice(java.math.BigDecimal.valueOf(99)); + product.setIsDelete(0); + ShopDO shop = new ShopDO(); + shop.setId(21L); + shop.setBusinessHours("10:00-22:00"); + when(adminScopeHelper.resolveShopScope(operator, null)).thenReturn(21L); + when(productMapper.selectById(41L)).thenReturn(product); + when(userMapper.selectById(71L)).thenReturn(customer); + when(userService.findCustomerMatches("小周", "13800138000", 21L)).thenReturn(java.util.List.of()); + when(userService.createManagerCustomer("小周", "13800138000", 21L)).thenReturn(71L); + when(shopMapper.selectById(21L)).thenReturn(shop); + when(snowflakeIdGenerator.nextIdString()).thenReturn("10004"); + doAnswer(invocation -> { + OrderDO value = invocation.getArgument(0); + value.setId(55L); + return 1; + }).when(orderMapper).insert(any(OrderDO.class)); + doAnswer(invocation -> { + OrderItemDO value = invocation.getArgument(0); + value.setId(65L); + return 1; + }).when(orderItemMapper).insert(any(OrderItemDO.class)); + doReturn(new com.xiaowang.jayucloud.salon.core.modules.planning.vo.PlanningAppointmentVO()) + .when(service).getAppointment(operator, 65L); + + PlanningAppointmentCreateDTO dto = new PlanningAppointmentCreateDTO(); + dto.setCustomerName("小周"); + dto.setPhone("13800138000"); + dto.setCreateCustomerRecord(true); + dto.setProductId(41L); + dto.setAmount(java.math.BigDecimal.valueOf(128)); + dto.setAppointmentDate("2026-10-22"); + dto.setAppointmentTime("14:00"); + dto.setDurationMinutes(60); + + service.createAppointment(operator, dto); + + verify(userService).createManagerCustomer("小周", "13800138000", 21L); + ArgumentCaptor orderCaptor = ArgumentCaptor.forClass(OrderDO.class); + verify(orderMapper).insert(orderCaptor.capture()); + assertEquals(71L, orderCaptor.getValue().getUserId()); + assertNull(orderCaptor.getValue().getCustomerNameSnapshot()); + } + + private OrderDO order(Long id, int status) { + OrderDO order = new OrderDO(); + order.setId(id); + order.setShopId(21L); + order.setStatus(status); + order.setIsDelete(0); + return order; + } +} diff --git a/JC-Salon-WeChat/components/entity-selector-sheet/index.js b/JC-Salon-WeChat/components/entity-selector-sheet/index.js index 45eecd27..943ae555 100644 --- a/JC-Salon-WeChat/components/entity-selector-sheet/index.js +++ b/JC-Salon-WeChat/components/entity-selector-sheet/index.js @@ -10,6 +10,9 @@ Component({ errorText: { type: String, value: '' }, emptyText: { type: String, value: '暂无可选内容' }, actionText: { type: String, value: '' }, + showViewSwitch: { type: Boolean, value: false }, + viewMode: { type: String, value: 'list' }, + sortLabel: { type: String, value: '' }, showSearch: { type: Boolean, value: true } }, @@ -36,6 +39,14 @@ Component({ action() { this.triggerEvent('action') + }, + + changeView(event) { + this.triggerEvent('changeview', { mode: event.currentTarget.dataset.mode }) + }, + + sort() { + this.triggerEvent('sort') } } }) diff --git a/JC-Salon-WeChat/components/entity-selector-sheet/index.wxml b/JC-Salon-WeChat/components/entity-selector-sheet/index.wxml index 051750ac..cdba0c65 100644 --- a/JC-Salon-WeChat/components/entity-selector-sheet/index.wxml +++ b/JC-Salon-WeChat/components/entity-selector-sheet/index.wxml @@ -10,6 +10,14 @@ + + + + + + + + @@ -20,12 +28,13 @@ {{emptyText}} - - + + {{item.title}} + {{item.rightText}} {{item.badge}} {{item.subtitle}} diff --git a/JC-Salon-WeChat/components/entity-selector-sheet/index.wxss b/JC-Salon-WeChat/components/entity-selector-sheet/index.wxss index d20b4840..9917c0fa 100644 --- a/JC-Salon-WeChat/components/entity-selector-sheet/index.wxss +++ b/JC-Salon-WeChat/components/entity-selector-sheet/index.wxss @@ -125,6 +125,35 @@ transform: rotate(45deg); } +.selector-toolbar { + display: flex; + align-items: center; + justify-content: space-between; + gap: 12rpx; + padding: 0 28rpx 16rpx; +} + +.selector-view-switch { + display: flex; + flex: 1; + gap: 8rpx; +} + +.selector-view-switch button, +.selector-sort { + height: 58rpx; + padding: 0 18rpx; + border-radius: 16rpx; + background: #f1f5f3; + color: #687a72; + font-size: 22rpx; + line-height: 58rpx; +} + +.selector-view-switch button { flex: 1; } +.selector-view-switch button.active { background: #dff1e9; color: #247b63; font-weight: 800; } +.selector-sort { flex: 0 0 auto; color: #476259; } + .selector-search { height: 78rpx; flex: 1; @@ -157,6 +186,28 @@ .selector-item:active { transform: scale(0.99); } .selector-item.selected { border-color: #8eafa3; background: #f0f6f3; } +.selector-list.card-view { + display: grid; + grid-template-columns: repeat(2, minmax(0, 1fr)); + gap: 12rpx; +} + +.selector-item.card-view { + position: relative; + display: block; + min-height: 190rpx; + margin: 0; + padding: 18rpx; +} + +.selector-item.card-view .selector-avatar { width: 66rpx; height: 66rpx; margin-bottom: 12rpx; } +.selector-item.card-view .selector-copy { margin-left: 0; } +.selector-item.card-view .selector-title-row { align-items: flex-start; } +.selector-item.card-view .selector-item-title { white-space: normal; } +.selector-item.card-view .selector-subtitle, +.selector-item.card-view .selector-meta { display: block; margin-top: 8rpx; } +.selector-item.card-view .selector-check { position: absolute; right: 18rpx; bottom: 16rpx; } + .selector-avatar { width: 76rpx; height: 76rpx; @@ -180,6 +231,8 @@ } .selector-item-title { + min-width: 0; + flex: 1; overflow: hidden; color: #2b2621; font-size: 28rpx; @@ -188,6 +241,13 @@ white-space: nowrap; } +.selector-right-text { + flex: 0 0 auto; + color: #756e66; + font-size: 23rpx; + font-weight: 600; +} + .selector-badge { flex: 0 0 auto; padding: 5rpx 12rpx; diff --git a/JC-Salon-WeChat/components/product-selector-sheet/index.js b/JC-Salon-WeChat/components/product-selector-sheet/index.js index 9983ecd1..c9e9d6e3 100644 --- a/JC-Salon-WeChat/components/product-selector-sheet/index.js +++ b/JC-Salon-WeChat/components/product-selector-sheet/index.js @@ -13,6 +13,7 @@ Component({ manualForm: { type: Object, value: {} }, manualMoreExpanded: { type: Boolean, value: false }, showManualExtra: { type: Boolean, value: true }, + showManualAction: { type: Boolean, value: true }, manualImageUrl: { type: String, value: '' }, manualImageUploading: { type: Boolean, value: false } }, diff --git a/JC-Salon-WeChat/components/product-selector-sheet/index.wxml b/JC-Salon-WeChat/components/product-selector-sheet/index.wxml index d877e401..5c2a40a1 100644 --- a/JC-Salon-WeChat/components/product-selector-sheet/index.wxml +++ b/JC-Salon-WeChat/components/product-selector-sheet/index.wxml @@ -17,7 +17,7 @@ - + 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 0eba88f5..f503979e 100644 --- a/JC-Salon-WeChat/pages/appointment-form/entity-selector.test.js +++ b/JC-Salon-WeChat/pages/appointment-form/entity-selector.test.js @@ -46,16 +46,13 @@ async function run() { page.onCustomerInput({ currentTarget: { dataset: { field: 'customerName' } }, detail: { value: '新客户' } }) assert.strictEqual(page.data.form.customerUserId, '') assert.strictEqual(page.data.form.customerName, '新客户') - assert.strictEqual(page.data.form.phone, '') + assert.strictEqual(page.data.form.phone, '13800138000') customersApi.matchIdentity = async () => [] - customersApi.create = async payload => { - assert.strictEqual(payload.nickname, '新客户') - assert.strictEqual(payload.phone, undefined) - return '42' - } + customersApi.create = async () => { throw new Error('预约客户建档应随预约请求提交') } assert.strictEqual(await page.ensureCustomerBeforeSubmit(), true) - assert.strictEqual(page.data.form.customerUserId, '42') + assert.strictEqual(page.data.form.customerUserId, '') + assert.strictEqual(page.data.form.createCustomerRecord, true) page.data.form.customerUserId = '' page.data.form.customerName = '小周' diff --git a/JC-Salon-WeChat/pages/appointment-form/index.js b/JC-Salon-WeChat/pages/appointment-form/index.js index 68b7923d..a53209fc 100644 --- a/JC-Salon-WeChat/pages/appointment-form/index.js +++ b/JC-Salon-WeChat/pages/appointment-form/index.js @@ -192,6 +192,113 @@ function flattenTimeGroups(groups) { return (groups || []).reduce((list, group) => list.concat(group.times || []), []) } +function buildTimeValues(durationMinutes) { + const values = [] + const open = dateUtil.minutesOfDay('10:00') + const close = dateUtil.minutesOfDay('22:00') + for (let minute = open; minute + durationMinutes <= close; minute += TIME_SLOT_MINUTES) { + values.push(dateUtil.timeFromMinutes(minute)) + } + return values +} + +function buildTimePickerSlots(calendar, form, durationMinutes) { + const schedules = calendar.schedules || [] + const busyRanges = form.artistId ? buildBusyRanges(calendar.appointments || [], form) : [] + return buildTimeValues(durationMinutes).map(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' + 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' ? '无排班' : '' + } + }) +} + +function buildTimePickerGroups(slots) { + const groupMap = { + morning: { key: 'morning', title: '上午', times: [] }, + afternoon: { key: 'afternoon', title: '下午', times: [] }, + evening: { key: 'evening', title: '晚上', times: [] } + } + ;(slots || []).forEach(slot => groupMap[getTimePeriod(dateUtil.minutesOfDay(slot.value)).key].times.push(slot)) + return Object.keys(groupMap).map(key => groupMap[key]).filter(group => group.times.length > 0) +} + +function buildTimeWheelState(slots, preferredTime) { + if (!slots || slots.length === 0) { + return { + timePickerHours: [], + timePickerMinutes: [], + timePickerValue: [0, 0], + selectedTimeCandidate: '', + timePickerCandidateStatus: 'off-shift' + } + } + const preferredSlot = slots.find(slot => slot.value === preferredTime) || slots.find(slot => slot.value === '14:00') + const firstAvailableSlot = slots.find(slot => slot.status === 'available') + const selectedSlot = preferredSlot && preferredSlot.status === 'available' + ? preferredSlot + : firstAvailableSlot || preferredSlot || slots[0] + const hours = Array.from(new Set(slots.map(slot => slot.hour))) + const selectedHourIndex = Math.max(0, hours.indexOf(selectedSlot.hour)) + const minuteValues = [0, 15, 30, 45] + const minutes = minuteValues.map(minute => { + const slot = slots.find(item => item.hour === selectedSlot.hour && item.minute === minute) + return { + value: minute, + label: String(minute).padStart(2, '0'), + status: slot ? slot.status : 'off-shift', + disabled: !slot || slot.status !== 'available' + } + }) + const selectedMinuteIndex = Math.max(0, minuteValues.indexOf(selectedSlot.minute)) + return { + timePickerHours: hours.map(hour => ({ + value: hour, + label: String(hour).padStart(2, '0'), + disabled: !slots.some(slot => slot.hour === hour && slot.status === 'available') + })), + timePickerMinutes: minutes, + timePickerValue: [selectedHourIndex, selectedMinuteIndex], + selectedTimeCandidate: selectedSlot.value, + timePickerCandidateStatus: selectedSlot.status + } +} + +function timeWheelStateForHour(slots, hour, selectedMinute) { + const minuteValues = [0, 15, 30, 45] + const minutes = minuteValues.map(minute => { + const slot = slots.find(item => item.hour === hour && item.minute === minute) + return { + value: minute, + label: String(minute).padStart(2, '0'), + status: slot ? slot.status : 'off-shift', + disabled: !slot || slot.status !== 'available' + } + }) + const selectedMinuteIndex = Math.max(0, minuteValues.indexOf(selectedMinute)) + return { timePickerMinutes: minutes, selectedMinuteIndex } +} + +function customerCreatedAt(customer) { + return customer.createTime || customer.createdAt || customer.addedAt || '' +} + +function formatCustomerCreatedAt(value) { + if (!value) return '添加时间未知' + return `添加于 ${String(value).replace('T', ' ').slice(0, 16)}` +} + function parseProductTags(product) { if (Array.isArray(product.tagList) && product.tagList.length > 0) { return product.tagList @@ -245,7 +352,8 @@ function normalizeCustomer(customer) { name, phone, displayName: name || phone || '客户', - displayPhone: phone || '未填写手机号' + displayPhone: phone || '未填写手机号', + createdAt: customerCreatedAt(customer) } } @@ -253,8 +361,8 @@ function buildCustomerSelectorItem(customer) { return { ...customer, title: customer.displayName, - subtitle: customer.displayPhone, - badge: '已有客户' + subtitle: formatCustomerCreatedAt(customer.createdAt), + rightText: customer.displayPhone } } @@ -276,6 +384,7 @@ Page({ phone: '', appointmentDate: dateUtil.formatDate(new Date()), appointmentTime: '', + amount: '', productId: '', manualProductTitle: '', manualProductPrice: '', @@ -285,14 +394,18 @@ Page({ manualProductPrecautions: '', manualProductImageFileIds: '', manualProductImageUrl: '', - durationMinutes: '', + durationMinutes: '60', artistId: '', + createCustomerRecord: false, remark: '' }, - manualProductDraft: { title: '', price: '', description: '', tags: '', targetAudience: '', precautions: '', imageFileIds: '', imageUrl: '' }, customerOptions: [], + customerDirectory: [], customerSheetVisible: false, customerKeyword: '', + customerViewMode: 'list', + customerNewestFirst: true, + customerSuggestions: [], customerLoading: false, customerError: '', products: [], @@ -306,8 +419,6 @@ Page({ selectedProductPriceText: '', selectedArtist: {}, productModalVisible: false, - productSelectorMode: 'list', - manualProductMoreExpanded: false, productKeyword: '', productError: '', loadingProducts: false, @@ -317,6 +428,14 @@ Page({ draftSavedAtText: '', manualImageUploading: false, timeSheetVisible: false, + timePickerMode: 'wheel', + timePickerValue: [0, 0], + timePickerHours: [], + timePickerMinutes: [], + timePickerSlots: [], + timePickerGroups: [], + timePickerCandidateStatus: 'off-shift', + selectedTimeCandidate: '', timeLoading: false, timeError: '', timeSelectTip: '请先选择美甲师并填写时长', @@ -330,16 +449,6 @@ Page({ const baseForm = draftForm || {} this.setData({ canCreateAppointment: creatable, - manualProductDraft: { - title: baseForm.manualProductTitle || '', - price: baseForm.manualProductPrice || '', - description: baseForm.manualProductDescription || '', - tags: baseForm.manualProductTags || '', - targetAudience: baseForm.manualProductTargetAudience || '', - precautions: baseForm.manualProductPrecautions || '', - imageFileIds: baseForm.manualProductImageFileIds || '', - imageUrl: baseForm.manualProductImageUrl || '' - }, form: { ...this.data.form, ...baseForm, @@ -375,10 +484,14 @@ Page({ await this.loadArtists() this.refreshProductCards() const selectedProduct = this.data.filteredProducts.find(item => String(item.id) === String(this.data.form.productId)) || {} - this.setData({ + const selectedProductPatch = { selectedProduct, selectedProductPriceText: selectedProduct.priceText || '' - }) + } + if (selectedProduct.id && (this.data.form.amount === '' || this.data.form.amount === undefined)) { + selectedProductPatch['form.amount'] = selectedProduct.price === undefined || selectedProduct.price === null ? '' : String(selectedProduct.price) + } + this.setData(selectedProductPatch) await this.refreshAvailableTimes() this.checkAvailability() }, @@ -420,6 +533,47 @@ Page({ } }, + async loadCustomerDirectory() { + this.setData({ customerLoading: true }) + try { + const size = 100 + const rows = [] + let page = 1 + let total = Number.POSITIVE_INFINITY + while (rows.length < total) { + const result = await customersApi.list({ page, size }) + const currentRows = Array.isArray(result) ? result : (result.list || []) + rows.push(...currentRows) + if (!Array.isArray(result) && Number.isFinite(Number(result.total))) { + total = Number(result.total) + } else if (currentRows.length < size) { + total = rows.length + } + if (currentRows.length === 0) break + page += 1 + } + const directory = rows.map(normalizeCustomer) + this.setData({ + customerDirectory: directory, + customerOptions: this.sortCustomerOptions(directory), + customerError: '' + }) + this.refreshCustomerSuggestions(this.data.form.customerName, this.data.form.phone) + } catch (error) { + this.setData({ customerDirectory: [], customerOptions: [], customerError: error.message || '客户列表加载失败' }) + } finally { + this.setData({ customerLoading: false }) + } + }, + + sortCustomerOptions(customers, newestFirst = this.data.customerNewestFirst) { + return (customers || []).slice().sort((left, right) => { + const leftDate = String(left.createdAt || '') + const rightDate = String(right.createdAt || '') + return newestFirst ? rightDate.localeCompare(leftDate) : leftDate.localeCompare(rightDate) + }).map(buildCustomerSelectorItem) + }, + onInput(event) { const field = event.currentTarget.dataset.field const patch = { @@ -432,18 +586,81 @@ Page({ } }, + onStyleTitleInput(event) { + const patch = { 'form.manualProductTitle': event.detail.value } + if (this.data.form.productId) { + patch['form.productId'] = '' + patch.selectedProduct = {} + patch.selectedProductPriceText = '' + patch['form.manualProductImageFileIds'] = '' + patch['form.manualProductImageUrl'] = '' + } + this.setData(patch) + }, + onCustomerInput(event) { const field = event.currentTarget.dataset.field const patch = { [`form.${field}`]: event.detail.value, - 'form.customerUserId': '' - } - if (field === 'customerName' && this.data.form.customerUserId) { - patch['form.phone'] = '' + 'form.customerUserId': '', + 'form.createCustomerRecord': false } this.setData({ ...patch }) + const customerName = field === 'customerName' ? event.detail.value : this.data.form.customerName + const phone = field === 'phone' ? event.detail.value : this.data.form.phone + this.refreshCustomerSuggestions(customerName, phone) + }, + + refreshCustomerSuggestions(nameValue, phoneValue) { + const name = String(nameValue || '').trim().toLowerCase() + const phone = String(phoneValue || '').trim().toLowerCase() + if (!name && !phone) { + this._customerSuggestionSeq = (this._customerSuggestionSeq || 0) + 1 + clearTimeout(this._suggestionTimer) + this.setData({ customerSuggestions: [] }) + return + } + const suggestions = this.data.customerDirectory + .filter(customer => (!name || customer.name.toLowerCase().includes(name)) && (!phone || customer.phone.toLowerCase().includes(phone))) + .slice(0, 3) + .map(buildCustomerSelectorItem) + this.setData({ customerSuggestions: suggestions }) + const requestSeq = (this._customerSuggestionSeq || 0) + 1 + this._customerSuggestionSeq = requestSeq + clearTimeout(this._suggestionTimer) + this._suggestionTimer = setTimeout(async () => { + try { + const result = await customersApi.list({ 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) + .filter(customer => (!name || customer.name.toLowerCase().includes(name)) && (!phone || customer.phone.toLowerCase().includes(phone))) + .slice(0, 3) + .map(buildCustomerSelectorItem) + this.setData({ customerSuggestions: remoteSuggestions }) + } catch (error) { + if (requestSeq === this._customerSuggestionSeq && suggestions.length === 0) { + this.setData({ customerSuggestions: [] }) + } + } + }, 240) + }, + + selectCustomerSuggestion(event) { + const index = Number(event.currentTarget.dataset.index) + const customer = this.data.customerSuggestions[index] + if (!customer) return + this.setData({ + 'form.customerUserId': customer.id, + 'form.customerName': customer.name, + 'form.phone': customer.phone, + 'form.createCustomerRecord': false, + customerSuggestions: [], + customerSheetVisible: false, + customerKeyword: '' + }) }, openCustomerSheet() { @@ -467,22 +684,24 @@ Page({ return } const keyword = String(keywordValue === undefined ? this.data.customerKeyword : keywordValue || '').trim() - this.setData({ customerLoading: true }) - try { - const data = await customersApi.list({ keyword, page: 1, size: 20 }) - const list = data.list || data || [] - this.setData({ - customerOptions: list.map(normalizeCustomer).map(buildCustomerSelectorItem), - customerError: '' - }) - } catch (error) { - this.setData({ - customerOptions: [], - customerError: error.message || '客户列表加载失败' - }) - } finally { - this.setData({ customerLoading: false }) - } + if (this.data.customerDirectory.length === 0) await this.loadCustomerDirectory() + const matches = this.data.customerDirectory.filter(customer => + !keyword || `${customer.name} ${customer.phone}`.toLowerCase().includes(keyword.toLowerCase()) + ) + this.setData({ customerOptions: this.sortCustomerOptions(matches), customerError: '' }) + }, + + changeCustomerView(event) { + this.setData({ customerViewMode: event.detail.mode || 'list' }) + }, + + toggleCustomerSort() { + const customerNewestFirst = !this.data.customerNewestFirst + const keyword = String(this.data.customerKeyword || '').trim().toLowerCase() + const matches = this.data.customerDirectory.filter(customer => + !keyword || `${customer.name} ${customer.phone}`.toLowerCase().includes(keyword) + ) + this.setData({ customerNewestFirst, customerOptions: this.sortCustomerOptions(matches, customerNewestFirst) }) }, retryCustomerSearch() { @@ -498,8 +717,10 @@ Page({ 'form.customerUserId': customer.id, 'form.customerName': customer.name, 'form.phone': customer.phone, + 'form.createCustomerRecord': false, customerSheetVisible: false, - customerKeyword: '' + customerKeyword: '', + customerSuggestions: [] }) }, @@ -507,6 +728,9 @@ Page({ if (this._customerTimer) { clearTimeout(this._customerTimer) } + if (this._suggestionTimer) { + clearTimeout(this._suggestionTimer) + } }, async onDateChange(event) { @@ -555,29 +779,20 @@ Page({ openProductModal() { this.refreshProductCards() - this.setData({ productModalVisible: true, productSelectorMode: 'list' }) + this.setData({ productModalVisible: true }) }, closeProductModal() { - this.setData({ productModalVisible: false, productSelectorMode: 'list' }) + this.setData({ productModalVisible: false }) }, openManualProduct() { - this.setData({ productSelectorMode: 'manual', manualProductMoreExpanded: false }) - }, - - backToProductList() { - this.setData({ productSelectorMode: 'list' }) - this.refreshProductCards() - }, - - onManualProductInput(event) { - const field = event.detail.field - this.setData({ [`manualProductDraft.${field}`]: event.detail.value }) - }, - - toggleManualProductMore() { - this.setData({ manualProductMoreExpanded: !this.data.manualProductMoreExpanded }) + this.setData({ + productModalVisible: false, + selectedProduct: {}, + selectedProductPriceText: '', + 'form.productId': '' + }) }, stopTap() { @@ -597,16 +812,8 @@ Page({ this.setData({ selectedProduct, selectedProductPriceText: selectedProduct.priceText || '', - manualProductDraft: { title: '', price: '', description: '', tags: '', targetAudience: '', precautions: '', imageFileIds: '', imageUrl: '' }, 'form.productId': selectedProduct.id, - 'form.manualProductTitle': '', - 'form.manualProductPrice': '', - 'form.manualProductDescription': '', - 'form.manualProductTags': '', - 'form.manualProductTargetAudience': '', - 'form.manualProductPrecautions': '', - 'form.manualProductImageFileIds': '', - 'form.manualProductImageUrl': '', + 'form.amount': selectedProduct.price === undefined || selectedProduct.price === null ? '' : String(selectedProduct.price), 'form.durationMinutes': String(selectedDuration || this.data.form.durationMinutes || '') }) this.closeProductModal() @@ -614,33 +821,6 @@ Page({ this.checkAvailability() }, - useManualProduct() { - const draft = this.data.manualProductDraft - const title = String(draft.title || '').trim() - const priceText = String(draft.price === undefined ? '' : draft.price).trim() - const price = Number(priceText) - if (!title || !priceText || !Number.isFinite(price) || price < 0) { - wx.showToast({ title: '请填写手动预约作品名称和价格', icon: 'none' }) - return - } - this.setData({ - selectedProduct: {}, - selectedProductPriceText: `¥${price}`, - 'form.productId': '', - 'form.manualProductTitle': title, - 'form.manualProductPrice': String(price), - 'form.manualProductDescription': String(draft.description || '').trim(), - 'form.manualProductTags': String(draft.tags || '').trim(), - 'form.manualProductTargetAudience': String(draft.targetAudience || '').trim(), - 'form.manualProductPrecautions': String(draft.precautions || '').trim(), - 'form.manualProductImageFileIds': String(draft.imageFileIds || ''), - 'form.manualProductImageUrl': String(draft.imageUrl || '') - }) - this.closeProductModal() - this.refreshAvailableTimes() - this.checkAvailability() - }, - async chooseManualProductImage() { if (this.data.manualImageUploading) { return @@ -658,8 +838,11 @@ Page({ throw new Error('作品图片上传成功但未返回文件ID') } this.setData({ - 'manualProductDraft.imageFileIds': String(fileId), - 'manualProductDraft.imageUrl': fileUrl + 'form.productId': '', + selectedProduct: {}, + selectedProductPriceText: '', + 'form.manualProductImageFileIds': String(fileId), + 'form.manualProductImageUrl': fileUrl }) } catch (error) { wx.showToast({ title: error.message || '图片上传失败', icon: 'none' }) @@ -670,8 +853,8 @@ Page({ removeManualProductImage() { this.setData({ - 'manualProductDraft.imageFileIds': '', - 'manualProductDraft.imageUrl': '' + 'form.manualProductImageFileIds': '', + 'form.manualProductImageUrl': '' }) }, @@ -781,6 +964,13 @@ Page({ if (!form.appointmentDate || !durationMinutes) { const patch = { availableTimeGroups: [], + timePickerGroups: [], + timePickerSlots: [], + timePickerHours: [], + timePickerMinutes: [], + timePickerValue: [0, 0], + selectedTimeCandidate: '', + timePickerCandidateStatus: 'off-shift', timeError: '', timeSelectTip: '请先填写预约日期和时长' } @@ -792,8 +982,12 @@ Page({ } 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: '请选择预约时间,员工可稍后分配' @@ -816,8 +1010,12 @@ Page({ } const availableTimeGroups = buildAvailableTimeGroups(calendar, form, durationMinutes) const availableTimes = flattenTimeGroups(availableTimeGroups).map(item => item.value) + const timePickerSlots = buildTimePickerSlots(calendar, form, durationMinutes) const patch = { availableTimeGroups, + timePickerSlots, + timePickerGroups: buildTimePickerGroups(timePickerSlots), + ...buildTimeWheelState(timePickerSlots, form.appointmentTime), timeSelectTip: availableTimes.length > 0 ? '请选择预约时间' : '当前美甲师当天暂无可约时间' } if (form.appointmentTime && !availableTimes.includes(form.appointmentTime)) { @@ -845,7 +1043,7 @@ Page({ wx.showToast({ title: '请先填写预约日期和时长', icon: 'none' }) return } - this.setData({ timeSheetVisible: true }) + this.setData({ timeSheetVisible: true, timePickerMode: 'wheel' }) await this.refreshAvailableTimes() }, @@ -855,16 +1053,61 @@ Page({ selectAvailableTime(event) { const value = event.currentTarget.dataset.value - this.setData({ - 'form.appointmentTime': value, - timeSheetVisible: false - }) - this.checkAvailability() + const slot = this.data.timePickerSlots.find(item => item.value === value) + if (!slot || slot.status !== 'available') { + wx.showToast({ title: slot && slot.status === 'occupied' ? '该时间已被占用' : '该时间不可预约', icon: 'none' }) + return + } + this.setData({ selectedTimeCandidate: value, timePickerCandidateStatus: slot.status }) }, - async checkAvailability() { + onTimePickerModeChange(event) { + this.setData({ timePickerMode: event.currentTarget.dataset.mode || 'wheel' }) + }, + + onTimePickerChange(event) { + const values = event.detail.value || [0, 0] + const hourItem = this.data.timePickerHours[values[0]] + if (!hourItem) return + const hour = Number(hourItem.value) + const minuteIndex = Number(values[1] || 0) + const minuteItem = this.data.timePickerMinutes[minuteIndex] + const minute = minuteItem ? Number(minuteItem.value) : 0 + const candidate = `${String(hour).padStart(2, '0')}:${String(minute).padStart(2, '0')}` + const slot = this.data.timePickerSlots.find(item => item.value === candidate) + const nextMinutes = timeWheelStateForHour(this.data.timePickerSlots, hour, minute) + this.setData({ + timePickerValue: [Number(values[0]), nextMinutes.selectedMinuteIndex], + timePickerMinutes: nextMinutes.timePickerMinutes, + selectedTimeCandidate: candidate, + timePickerCandidateStatus: slot ? slot.status : 'off-shift' + }) + }, + + confirmTimeSelection() { + const candidate = this.data.selectedTimeCandidate + const slot = this.data.timePickerSlots.find(item => item.value === candidate) + if (!slot || slot.status !== 'available') { + wx.showToast({ title: slot && slot.status === 'occupied' ? '该时间已被占用' : '该时间不可预约', icon: 'none' }) + return + } + this.checkAvailability(candidate).then(availability => { + if (!availability.ok) { + wx.showToast({ + title: availability.tip && availability.tip.includes('已有预约') ? '该时间已被占用' : availability.tip || '该时间不可预约', + icon: 'none' + }) + return + } + this.setData({ 'form.appointmentTime': candidate, timeSheetVisible: false }) + this.checkAvailability() + }) + }, + + async checkAvailability(candidateTime) { const form = this.data.form - if (!form.appointmentDate || !form.appointmentTime) { + const appointmentTime = candidateTime || form.appointmentTime + if (!form.appointmentDate || !appointmentTime) { this.setData({ conflictTip: '', conflictLevel: 'free' }) return { ok: true } } @@ -873,7 +1116,7 @@ Page({ this.setData({ conflictTip: '', conflictLevel: 'free' }) return { ok: true } } - const startMinute = dateUtil.minutesOfDay(form.appointmentTime) + 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' @@ -912,7 +1155,7 @@ Page({ this.setData({ conflictTip: tip, conflictLevel: 'danger' }) return { ok: false, tip } } - const tip = `${this.data.selectedArtist.name || '该美甲师'} ${form.appointmentTime}-${dateUtil.timeFromMinutes(endMinute)} 可预约` + const tip = `${this.data.selectedArtist.name || '该美甲师'} ${appointmentTime}-${dateUtil.timeFromMinutes(endMinute)} 可预约` this.setData({ conflictTip: tip, conflictLevel: 'free' }) return { ok: true, tip } } catch (error) { @@ -925,8 +1168,12 @@ Page({ async ensureCustomerBeforeSubmit() { const name = String(this.data.form.customerName || '').trim() const phone = String(this.data.form.phone || '').trim() + if (!name && !phone) { + this.setData({ 'form.createCustomerRecord': false }) + return true + } if (!name) { - wx.showToast({ title: '请输入客户姓名', icon: 'none' }) + wx.showToast({ title: '填写手机号时请同时填写客户姓名', icon: 'none' }) return false } if (phone && !/^1[3-9]\d{9}$/.test(phone)) { @@ -934,6 +1181,7 @@ Page({ return false } if (this.data.form.customerUserId) { + this.setData({ 'form.createCustomerRecord': false }) return true } @@ -941,6 +1189,20 @@ Page({ try { const matches = await customersApi.matchIdentity(name, phone || undefined) if (matches.length > 1) { + const choice = await new Promise(resolve => { + wx.showModal({ + title: '找到多个同名客户', + content: phone ? '无法确定唯一客户,请选择已有客户或按散客继续。' : '请先补充手机号或选择一个已有客户,也可以按散客继续。', + cancelText: '不关联提交', + confirmText: '选择客户', + success: resolve, + fail: () => resolve({ confirm: false }) + }) + }) + if (!choice.confirm) { + this.setData({ 'form.createCustomerRecord': false }) + return true + } this.setData({ customerOptions: matches.map(normalizeCustomer).map(buildCustomerSelectorItem), customerKeyword: name, @@ -954,20 +1216,22 @@ Page({ wx.showModal({ title: '客户已存在', content: `系统中已有“${name}”${phone ? `(${phone})` : ''},是否使用该客户?`, - cancelText: '取消', + cancelText: '不关联提交', confirmText: '使用已有', success: resolve, fail: () => resolve({ confirm: false }) }) }) - if (!choice.confirm) { - return false + if (choice.confirm) { + this.setData({ + 'form.customerUserId': customer.id, + 'form.customerName': customer.name, + 'form.phone': customer.phone, + 'form.createCustomerRecord': false + }) + } else { + this.setData({ 'form.createCustomerRecord': false }) } - this.setData({ - 'form.customerUserId': customer.id, - 'form.customerName': customer.name, - 'form.phone': customer.phone - }) return true } @@ -981,11 +1245,7 @@ Page({ fail: () => resolve({ confirm: false }) }) }) - if (!createChoice.confirm) { - return false - } - const customerId = await customersApi.create({ nickname: name, phone: phone || undefined }) - this.setData({ 'form.customerUserId': customerId }) + this.setData({ 'form.createCustomerRecord': Boolean(createChoice.confirm) }) return true } catch (error) { wx.showToast({ title: error.message || '客户校验失败,请稍后重试', icon: 'none' }) @@ -1003,13 +1263,25 @@ Page({ wx.showToast({ title: '当前账号仅支持查看预约', icon: 'none' }) return } - const form = this.data.form - const hasManualProduct = String(form.manualProductTitle || '').trim() && String(form.manualProductPrice || '').trim() + let form = this.data.form + const manualProductTitle = String(form.manualProductTitle || '').trim() + const manualProductImageFileIds = String(form.manualProductImageFileIds || '').trim() + const hasManualProduct = Boolean(manualProductTitle || manualProductImageFileIds || String(form.customerName || '').trim()) + const amountText = String(form.amount === undefined || form.amount === null ? '' : form.amount).trim() + const amount = Number(amountText) const durationMinutes = normalizeDuration(form.durationMinutes) - if (!form.customerName || (!form.productId && !hasManualProduct) || !form.appointmentDate || !form.appointmentTime) { + if ((!form.productId && !hasManualProduct) || !form.appointmentDate || !form.appointmentTime || !amountText) { wx.showToast({ title: '请补全预约信息', icon: 'none' }) return } + if (!Number.isFinite(amount) || amount < 0) { + wx.showToast({ title: '请输入不小于0的成交金额', icon: 'none' }) + return + } + if (form.phone && !String(form.customerName || '').trim()) { + wx.showToast({ title: '填写手机号时请同时填写客户姓名', icon: 'none' }) + return + } if (form.phone && !/^1[3-9]\d{9}$/.test(String(form.phone).trim())) { wx.showToast({ title: '请输入正确手机号', icon: 'none' }) return @@ -1039,12 +1311,17 @@ Page({ if (!(await this.ensureCustomerBeforeSubmit())) { return } + form = this.data.form this.setData({ loading: true }) try { const payload = { ...form, customerUserId: form.customerUserId ? String(form.customerUserId) : undefined, artistId: form.artistId ? String(form.artistId) : undefined, + customerName: String(form.customerName || '').trim() || undefined, + phone: String(form.phone || '').trim() || undefined, + amount, + createCustomerRecord: Boolean(form.createCustomerRecord), durationMinutes, clientRequestId: buildClientRequestId('manager-appointment') } @@ -1054,8 +1331,8 @@ Page({ payload.manualProductPrice = undefined } else { payload.productId = undefined - payload.manualProductTitle = String(form.manualProductTitle || '').trim() - payload.manualProductPrice = Number(form.manualProductPrice) + payload.manualProductTitle = manualProductTitle || undefined + payload.manualProductPrice = amount payload.manualProductDescription = String(form.manualProductDescription || '').trim() || undefined payload.manualProductTags = String(form.manualProductTags || '').trim() || undefined payload.manualProductTargetAudience = String(form.manualProductTargetAudience || '').trim() || undefined diff --git a/JC-Salon-WeChat/pages/appointment-form/index.wxml b/JC-Salon-WeChat/pages/appointment-form/index.wxml index 3ecd6fec..4420cff7 100644 --- a/JC-Salon-WeChat/pages/appointment-form/index.wxml +++ b/JC-Salon-WeChat/pages/appointment-form/index.wxml @@ -1,136 +1,67 @@ - - - - 客户姓名 - - - - - - 已关联系统客户 + + + + 美甲款式手动输入为主,也可快速选择已有款式 + - - 预约日期 - - {{form.appointmentDate}} - + + + {{selectedProduct.title}}参考价 {{selectedProductPriceText || '待定'}} · {{selectedProduct.durationText || '时长待定'}} + - - 预约作品 - + + + - - 预计时长 - - 分钟 + + + - - 员工(可稍后分配) - - {{selectedArtist.name || '暂不分配'}} - › - - - - 预约时间 - - - {{form.appointmentTime || timeSelectTip}} - {{form.appointmentDate}} · {{selectedArtist.name || '待分配'}} · {{form.durationMinutes}}分钟 - - › - - - - 备注 -