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 20d95484..9b5ea787 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 @@ -110,10 +110,9 @@ public class PlanningServiceImpl implements PlanningService { Long shopId = requirePlanningShopId(currentUser); ShopDO shop = shopMapper.selectById(shopId); - PlanningCalendarSupport.BusinessHours businessHours = PlanningCalendarSupport.parseBusinessHours( + PlanningCalendarSupport.BusinessHours businessHours = parseConfiguredBusinessHours( shop == null ? null : (StringUtils.hasText(shop.getAppointmentBusinessHours()) - ? shop.getAppointmentBusinessHours() : shop.getBusinessHours()) - ); + ? shop.getAppointmentBusinessHours() : shop.getBusinessHours())); List artists = listArtists(shopId, artistId); List schedules = listSchedules(shopId, start, end, artistId); @@ -135,8 +134,8 @@ public class PlanningServiceImpl implements PlanningService { artists.forEach(artist -> artist.setRangeCount(countByArtist.getOrDefault(artist.getId(), 0L).intValue())); PlanningCalendarVO vo = new PlanningCalendarVO(); - vo.setBusinessStartTime(businessHours.start().toString()); - vo.setBusinessEndTime(businessHours.end().toString()); + vo.setBusinessStartTime(businessHours == null ? null : businessHours.start().toString()); + vo.setBusinessEndTime(businessHours == null ? null : businessHours.end().toString()); vo.setDefaultAppointmentDurationMinutes(shop == null || shop.getDefaultAppointmentDurationMinutes() == null || shop.getDefaultAppointmentDurationMinutes() <= 0 ? DEFAULT_DURATION_MINUTES : shop.getDefaultAppointmentDurationMinutes()); vo.setSlotMinutes(DEFAULT_SLOT_MINUTES); @@ -862,7 +861,12 @@ public class PlanningServiceImpl implements PlanningService { ShopDO shop = shopMapper.selectById(shopId); String configuredHours = shop == null ? null : (StringUtils.hasText(shop.getAppointmentBusinessHours()) ? shop.getAppointmentBusinessHours() : shop.getBusinessHours()); - PlanningCalendarSupport.BusinessHours hours = PlanningCalendarSupport.parseBusinessHours(configuredHours); + PlanningCalendarSupport.BusinessHours hours = parseConfiguredBusinessHours(configuredHours); + if (hours == null) { + throw new RuntimeException(StringUtils.hasText(configuredHours) + ? "门店营业时间格式无效,请先完成设置" + : "门店营业时间未设置,请先完成设置"); + } LocalTime start = startTime.toLocalTime(); LocalTime end = endTime.toLocalTime(); if (start.isBefore(hours.start()) || end.isAfter(hours.end()) || !startTime.toLocalDate().equals(endTime.toLocalDate())) { @@ -870,6 +874,19 @@ public class PlanningServiceImpl implements PlanningService { } } + private PlanningCalendarSupport.BusinessHours parseConfiguredBusinessHours(String value) { + if (!StringUtils.hasText(value)) return null; + String[] parts = value.trim().split("-"); + if (parts.length != 2) return null; + try { + LocalTime start = LocalTime.parse(parts[0].trim()); + LocalTime end = LocalTime.parse(parts[1].trim()); + return start.isBefore(end) ? new PlanningCalendarSupport.BusinessHours(start, end) : null; + } catch (RuntimeException ignored) { + return null; + } + } + private void ensureFutureAppointmentTime(LocalDateTime startTime) { LocalDate today = LocalDate.now(); if (startTime.toLocalDate().isBefore(today)) { diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/shop/service/impl/ShopServiceImpl.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/shop/service/impl/ShopServiceImpl.java index de38d8dd..99f8e165 100644 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/shop/service/impl/ShopServiceImpl.java +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/shop/service/impl/ShopServiceImpl.java @@ -227,7 +227,6 @@ public class ShopServiceImpl extends ServiceImpl implements ContentModerationRecordDO latestReview = contentModerationRecordMapper.selectOne(Wrappers.lambdaQuery(ContentModerationRecordDO.class) .eq(ContentModerationRecordDO::getContentType, "SHOP") .eq(ContentModerationRecordDO::getBusinessId, id) - .eq(ContentModerationRecordDO::getIsDelete, 0) .orderByDesc(ContentModerationRecordDO::getVersionNo) .last("limit 1")); result.setShopNameModerationStatus(latestReview == null ? shop.getModerationStatus() : latestReview.getStatus()); diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/user/service/impl/UserServiceImpl.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/user/service/impl/UserServiceImpl.java index 06a107ef..f0d91a77 100644 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/user/service/impl/UserServiceImpl.java +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/user/service/impl/UserServiceImpl.java @@ -621,13 +621,12 @@ public class UserServiceImpl extends ServiceImpl implements return userMapper.selectList(wrapper).stream() .filter(user -> Objects.equals(normalizedName, user.getNickname())) .filter(user -> Objects.equals(normalizedWechatId, UserProfileFieldSupport.normalizeOptionalText(user.getWechatId()))) - .filter(user -> Objects.equals(normalizedPhone, decryptPhone(user.getPhone()))) + .filter(user -> Objects.equals(normalizedPhone, resolveCustomerPhone(user))) .map(user -> { AppointmentCustomerOptionVO customer = new AppointmentCustomerOptionVO(); customer.setId(user.getId()); customer.setName(user.getNickname()); - String contactPhone = decryptPhone(user.getContactPhone()); - customer.setPhone(StringUtils.hasText(contactPhone) ? contactPhone : decryptPhone(user.getPhone())); + customer.setPhone(resolveCustomerPhone(user)); customer.setAvatar(resolveAccessibleAvatar(user.getAvatar())); customer.setCreatedAt(user.getCreateTime()); return customer; @@ -656,9 +655,7 @@ public class UserServiceImpl extends ServiceImpl implements AppointmentCustomerOptionVO option = new AppointmentCustomerOptionVO(); option.setId(user.getId()); option.setName(user.getNickname()); - String contactPhone = decryptPhone(user.getContactPhone()); - String phone = StringUtils.hasText(contactPhone) ? contactPhone : decryptPhone(user.getPhone()); - option.setPhone(phone); + option.setPhone(resolveCustomerPhone(user)); option.setAvatar(resolveAccessibleAvatar(user.getAvatar())); option.setCreatedAt(user.getCreateTime()); return option; @@ -676,6 +673,11 @@ public class UserServiceImpl extends ServiceImpl implements else wrapper.and(query -> query.eq(UserDO::getShopId, shopId).or().in(UserDO::getId, shopUserIds)); } + private String resolveCustomerPhone(UserDO customer) { + String contactPhone = decryptPhone(customer.getContactPhone()); + return StringUtils.hasText(contactPhone) ? contactPhone : decryptPhone(customer.getPhone()); + } + /** * 分配默认权限 * @param userId 用户ID diff --git a/JC-Salon-Core/src/test/java/com/xiaowang/jayucloud/salon/core/modules/planning/service/impl/PlanningServiceImplTest.java b/JC-Salon-Core/src/test/java/com/xiaowang/jayucloud/salon/core/modules/planning/service/impl/PlanningServiceImplTest.java index 70abe1a6..1122e8f5 100644 --- a/JC-Salon-Core/src/test/java/com/xiaowang/jayucloud/salon/core/modules/planning/service/impl/PlanningServiceImplTest.java +++ b/JC-Salon-Core/src/test/java/com/xiaowang/jayucloud/salon/core/modules/planning/service/impl/PlanningServiceImplTest.java @@ -102,6 +102,111 @@ class PlanningServiceImplTest { verify(orderItemMapper, never()).insert(any(OrderItemDO.class)); } + @Test + void rejectsCreatingAppointmentForPastDate() { + 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); + PlanningAppointmentCreateDTO dto = new PlanningAppointmentCreateDTO(); + dto.setAppointmentDate(java.time.LocalDate.now().minusDays(1).toString()); + dto.setAppointmentTime("14:00"); + + RuntimeException error = assertThrows(RuntimeException.class, () -> service.createAppointment(operator, dto)); + + assertEquals("历史日期请使用历史补单", error.getMessage()); + verify(orderMapper, never()).insert(any(OrderDO.class)); + } + + @Test + void rejectsAppointmentOutsideBusinessHours() { + UserDO operator = new UserDO(); + operator.setType(2); + ShopDO shop = new ShopDO(); + shop.setId(21L); + shop.setAppointmentBusinessHours("10:00-20:00"); + when(adminScopeHelper.resolveShopScope(operator, null)).thenReturn(21L); + when(shopMapper.selectById(21L)).thenReturn(shop); + PlanningAppointmentCreateDTO dto = new PlanningAppointmentCreateDTO(); + dto.setAppointmentDate(java.time.LocalDate.now().plusDays(2).toString()); + dto.setAppointmentTime("19:30"); + dto.setDurationMinutes(60); + + RuntimeException error = assertThrows(RuntimeException.class, () -> service.createAppointment(operator, dto)); + + assertEquals("预约时间超出店铺营业时间", error.getMessage()); + verify(orderMapper, never()).insert(any(OrderDO.class)); + } + + @Test + void rejectsAppointmentWhenShopBusinessHoursAreMissing() { + UserDO operator = new UserDO(); + operator.setType(2); + ShopDO shop = new ShopDO(); + shop.setId(21L); + when(adminScopeHelper.resolveShopScope(operator, null)).thenReturn(21L); + when(shopMapper.selectById(21L)).thenReturn(shop); + PlanningAppointmentCreateDTO dto = new PlanningAppointmentCreateDTO(); + dto.setAppointmentDate(java.time.LocalDate.now().plusDays(2).toString()); + dto.setAppointmentTime("14:00"); + dto.setDurationMinutes(60); + + RuntimeException error = assertThrows(RuntimeException.class, () -> service.createAppointment(operator, dto)); + + assertEquals("门店营业时间未设置,请先完成设置", error.getMessage()); + verify(orderMapper, never()).insert(any(OrderDO.class)); + } + + @Test + void usesShopDefaultDurationWhenRequestOmitsDuration() { + UserDO operator = new UserDO(); + operator.setType(2); + ShopDO shop = new ShopDO(); + shop.setId(21L); + shop.setAppointmentBusinessHours("10:00-22:00"); + shop.setDefaultAppointmentDurationMinutes(90); + when(adminScopeHelper.resolveShopScope(operator, null)).thenReturn(21L); + when(shopMapper.selectById(21L)).thenReturn(shop); + PlanningAppointmentCreateDTO dto = new PlanningAppointmentCreateDTO(); + dto.setAppointmentDate(java.time.LocalDate.now().plusDays(2).toString()); + dto.setAppointmentTime("21:00"); + + RuntimeException error = assertThrows(RuntimeException.class, () -> service.createAppointment(operator, dto)); + + assertEquals("预约时间超出店铺营业时间", error.getMessage()); + verify(orderMapper, never()).insert(any(OrderDO.class)); + } + + @Test + void productDurationTakesPriorityOverShopDefaultWhenRequestOmitsDuration() { + UserDO operator = new UserDO(); + operator.setType(2); + ShopDO shop = new ShopDO(); + shop.setId(21L); + shop.setAppointmentBusinessHours("10:00-22:00"); + shop.setDefaultAppointmentDurationMinutes(60); + ProductDO product = new ProductDO(); + product.setId(41L); + product.setShopId(21L); + product.setIsDelete(0); + product.setApproximateDuration("120分钟"); + when(adminScopeHelper.resolveShopScope(operator, null)).thenReturn(21L); + when(shopMapper.selectById(21L)).thenReturn(shop); + when(productMapper.selectById(41L)).thenReturn(product); + PlanningAppointmentCreateDTO dto = new PlanningAppointmentCreateDTO(); + dto.setProductId(41L); + dto.setAppointmentDate(java.time.LocalDate.now().plusDays(2).toString()); + dto.setAppointmentTime("21:00"); + + RuntimeException error = assertThrows(RuntimeException.class, () -> service.createAppointment(operator, dto)); + + assertEquals("预约时间超出店铺营业时间", error.getMessage()); + verify(orderMapper, never()).insert(any(OrderDO.class)); + } + @Test void backfillOrderDoesNotCheckShopBusinessExpiry() { service = spy(service); diff --git a/JC-Salon-Core/src/test/java/com/xiaowang/jayucloud/salon/core/modules/shop/service/impl/ShopAppointmentSettingsTest.java b/JC-Salon-Core/src/test/java/com/xiaowang/jayucloud/salon/core/modules/shop/service/impl/ShopAppointmentSettingsTest.java new file mode 100644 index 00000000..f1a639a1 --- /dev/null +++ b/JC-Salon-Core/src/test/java/com/xiaowang/jayucloud/salon/core/modules/shop/service/impl/ShopAppointmentSettingsTest.java @@ -0,0 +1,100 @@ +package com.xiaowang.jayucloud.salon.core.modules.shop.service.impl; + +import com.baomidou.mybatisplus.core.conditions.Wrapper; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.xiaowang.jayucloud.salon.core.config.AppCacheProperties; +import com.xiaowang.jayucloud.salon.core.modules.artist.service.NailArtistInfoService; +import com.xiaowang.jayucloud.salon.core.modules.content.mapper.CommentMapper; +import com.xiaowang.jayucloud.salon.core.modules.file.service.ObjectStorageFileService; +import com.xiaowang.jayucloud.salon.core.modules.file.support.ObjectStorageUrlSupport; +import com.xiaowang.jayucloud.salon.core.modules.integration.service.MapService; +import com.xiaowang.jayucloud.salon.core.modules.marketing.mapper.CouponMapper; +import com.xiaowang.jayucloud.salon.core.modules.marketing.mapper.UserCouponMapper; +import com.xiaowang.jayucloud.salon.core.modules.marketing.service.CouponService; +import com.xiaowang.jayucloud.salon.core.modules.order.mapper.OrderArtistReviewMapper; +import com.xiaowang.jayucloud.salon.core.modules.privacy.entity.ContentModerationRecordDO; +import com.xiaowang.jayucloud.salon.core.modules.privacy.mapper.ContentModerationRecordMapper; +import com.xiaowang.jayucloud.salon.core.modules.privacy.service.ContentModerationService; +import com.xiaowang.jayucloud.salon.core.modules.product.mapper.ProductMapper; +import com.xiaowang.jayucloud.salon.core.modules.product.mapper.TagMapper; +import com.xiaowang.jayucloud.salon.core.modules.shop.dto.ShopAppointmentSettingsDTO; +import com.xiaowang.jayucloud.salon.core.modules.shop.entity.ShopDO; +import com.xiaowang.jayucloud.salon.core.modules.shop.mapper.ShopMapper; +import com.xiaowang.jayucloud.salon.core.modules.shop.service.ShopBusinessExpiryService; +import com.xiaowang.jayucloud.salon.core.modules.shop.support.UserShopBindingSupport; +import com.xiaowang.jayucloud.salon.core.modules.shop.vo.ShopAppointmentSettingsVO; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.ArgumentCaptor; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.verifyNoInteractions; +import static org.mockito.Mockito.when; + +@ExtendWith(MockitoExtension.class) +class ShopAppointmentSettingsTest { + + @Mock private ShopMapper shopMapper; + @Mock private ContentModerationRecordMapper contentModerationRecordMapper; + @Mock private ShopBusinessExpiryService shopBusinessExpiryService; + @Mock private CouponService couponService; + @Mock private CouponMapper couponMapper; + @Mock private ProductMapper productMapper; + @Mock private TagMapper tagMapper; + @Mock private CommentMapper commentMapper; + @Mock private UserCouponMapper userCouponMapper; + @Mock private OrderArtistReviewMapper orderArtistReviewMapper; + @Mock private ObjectStorageFileService objectStorageFileService; + @Mock private ObjectStorageUrlSupport objectStorageUrlSupport; + @Mock private UserShopBindingSupport userShopBindingSupport; + @Mock private NailArtistInfoService nailArtistInfoService; + @Mock private com.xiaowang.jayucloud.salon.core.support.cache.MultiLevelCacheService multiLevelCacheService; + @Mock private AppCacheProperties appCacheProperties; + @Mock private MapService mapService; + @Mock private ContentModerationService contentModerationService; + @Mock private ObjectMapper objectMapper; + + @InjectMocks + private ShopServiceImpl shopService; + + @Test + void savesAppointmentSettingsWithoutSubmittingPublicProfileForReview() { + ShopDO shop = new ShopDO(); + shop.setId(21L); + shop.setBusinessHours("10:00-22:00"); + when(shopMapper.selectById(21L)).thenReturn(shop); + when(shopMapper.updateById(any(ShopDO.class))).thenReturn(1); + ShopAppointmentSettingsDTO dto = new ShopAppointmentSettingsDTO(); + dto.setBusinessHours("09:30-21:00"); + dto.setDefaultAppointmentDurationMinutes(75); + + assertTrue(shopService.updateAppointmentSettings(21L, dto)); + + ArgumentCaptor saved = ArgumentCaptor.forClass(ShopDO.class); + verify(shopMapper).updateById(saved.capture()); + assertEquals("09:30-21:00", saved.getValue().getAppointmentBusinessHours()); + assertEquals(75, saved.getValue().getDefaultAppointmentDurationMinutes()); + verifyNoInteractions(contentModerationService); + } + + @Test + void returnsDefaultDurationForExistingShopWithoutConfiguredValue() { + ShopDO shop = new ShopDO(); + shop.setId(21L); + shop.setShopName("薄荷美甲"); + shop.setBusinessHours("09:00-21:00"); + when(shopMapper.selectById(21L)).thenReturn(shop); + when(contentModerationRecordMapper.selectOne(any(Wrapper.class))).thenReturn(null); + + ShopAppointmentSettingsVO settings = shopService.getAppointmentSettings(21L); + + assertEquals("09:00-21:00", settings.getBusinessHours()); + assertEquals(60, settings.getDefaultAppointmentDurationMinutes()); + } +} diff --git a/JC-Salon-Core/src/test/java/com/xiaowang/jayucloud/salon/core/modules/user/service/impl/UserServiceCustomerMatchingTest.java b/JC-Salon-Core/src/test/java/com/xiaowang/jayucloud/salon/core/modules/user/service/impl/UserServiceCustomerMatchingTest.java index 980920d0..f32bae0f 100644 --- a/JC-Salon-Core/src/test/java/com/xiaowang/jayucloud/salon/core/modules/user/service/impl/UserServiceCustomerMatchingTest.java +++ b/JC-Salon-Core/src/test/java/com/xiaowang/jayucloud/salon/core/modules/user/service/impl/UserServiceCustomerMatchingTest.java @@ -95,4 +95,23 @@ class UserServiceCustomerMatchingTest { assertEquals("13800138000", matches.get(0).getPhone()); assertTrue(wrongWechat.isEmpty()); } + + @Test + void appointmentIdentityLookupFallsBackToLegacyContactPhone() { + UserDO existing = new UserDO(); + existing.setId(93L); + existing.setNickname("周女士"); + existing.setWechatId("wx-zhou"); + existing.setContactPhone("encrypted-contact-phone"); + existing.setType(0); + existing.setIsDelete(0); + when(userMapper.selectList(any(Wrapper.class))).thenReturn(List.of(existing)); + when(phoneCrypto.decrypt("encrypted-contact-phone")).thenReturn("13800138000"); + + List matches = + userService.findCustomerIdentityMatches("周女士", "wx-zhou", "13800138000", null); + + assertEquals(1, matches.size()); + assertEquals("13800138000", matches.get(0).getPhone()); + } } diff --git a/JC-Salon-WeChat/pages/appointment-form/index.js b/JC-Salon-WeChat/pages/appointment-form/index.js index bf0cb952..3ba4316d 100644 --- a/JC-Salon-WeChat/pages/appointment-form/index.js +++ b/JC-Salon-WeChat/pages/appointment-form/index.js @@ -26,6 +26,11 @@ function canCreateAppointment() { return Number(userInfo.type) !== 3 } +function isShopManager() { + const userInfo = getApp().globalData.userInfo || {} + return Number(userInfo.type) === 2 +} + function isShopBusinessExpired() { const userInfo = getApp().globalData.userInfo || {} return Number(userInfo.type) === 2 && userInfo.shopBusinessExpired === true @@ -205,6 +210,22 @@ function hasBusyConflict(startMinute, endMinute, ranges) { return ranges.some(range => startMinute < range.endMinute && endMinute > range.startMinute) } +function resolveBusinessHours(calendar) { + const source = calendar || {} + const parts = String(source.businessHours || '').split('-') + const start = String(source.businessStartTime || parts[0] || '').trim() + const end = String(source.businessEndTime || parts[1] || '').trim() + const valid = value => { + if (!/^\d{1,2}:[0-5]\d$/.test(value)) return false + const hour = Number(value.split(':')[0]) + return hour >= 0 && hour <= 23 + } + if (!valid(start) || !valid(end) || dateUtil.minutesOfDay(end) <= dateUtil.minutesOfDay(start)) { + return { start: '', end: '' } + } + return { start, end } +} + function buildAvailableTimeGroups(calendar, form, durationMinutes) { const schedules = (calendar.schedules || []) .filter(item => String(item.artistId) === String(form.artistId)) @@ -214,8 +235,10 @@ function buildAvailableTimeGroups(calendar, form, durationMinutes) { const today = dateUtil.formatDate(new Date()) const now = new Date() const currentMinute = now.getHours() * 60 + now.getMinutes() - const businessStart = dateUtil.minutesOfDay(calendar.businessStartTime || '10:00') - const businessEnd = dateUtil.minutesOfDay(calendar.businessEndTime || '22:00') + const businessHours = resolveBusinessHours(calendar) + if (!businessHours.start) return [] + const businessStart = dateUtil.minutesOfDay(businessHours.start) + const businessEnd = dateUtil.minutesOfDay(businessHours.end) const groupMap = { morning: { key: 'morning', title: '上午', times: [] }, afternoon: { key: 'afternoon', title: '下午', times: [] }, @@ -245,14 +268,16 @@ function buildAvailableTimeGroups(calendar, form, durationMinutes) { .filter(group => group.times.length > 0) } -function buildUnassignedTimeGroups(durationMinutes, businessStart = '10:00', businessEnd = '22:00', appointmentDate) { +function buildUnassignedTimeGroups(durationMinutes, businessStart, businessEnd, appointmentDate) { const groupMap = { morning: { key: 'morning', title: '上午', times: [] }, afternoon: { key: 'afternoon', title: '下午', times: [] }, evening: { key: 'evening', title: '晚上', times: [] } } + if (!businessStart || !businessEnd) return [] const start = dateUtil.minutesOfDay(businessStart) const end = dateUtil.minutesOfDay(businessEnd) + if (end <= start) return [] const now = new Date() const today = dateUtil.formatDate(now) const currentMinute = now.getHours() * 60 + now.getMinutes() @@ -273,10 +298,12 @@ function flattenTimeGroups(groups) { return (groups || []).reduce((list, group) => list.concat(group.times || []), []) } -function buildTimeValues(durationMinutes, businessStart = '10:00', businessEnd = '22:00', appointmentDate) { +function buildTimeValues(durationMinutes, businessStart, businessEnd, appointmentDate) { const values = [] + if (!businessStart || !businessEnd) return values const open = dateUtil.minutesOfDay(businessStart) const close = dateUtil.minutesOfDay(businessEnd) + if (close <= open) return values const now = new Date() const today = dateUtil.formatDate(now) const currentMinute = now.getHours() * 60 + now.getMinutes() @@ -290,9 +317,10 @@ function buildTimeValues(durationMinutes, businessStart = '10:00', businessEnd = function buildTimePickerSlots(calendar, form, durationMinutes) { const schedules = calendar.schedules || [] const busyRanges = form.artistId ? buildBusyRanges(calendar.appointments || [], form) : [] - const businessHours = String(calendar.businessHours || '10:00-22:00').split('-') - const businessStart = calendar.businessStartTime || businessHours[0] || '10:00' - const businessEnd = calendar.businessEndTime || businessHours[1] || '22:00' + const businessHours = resolveBusinessHours(calendar) + if (!businessHours.start) return [] + const businessStart = businessHours.start + const businessEnd = businessHours.end return buildTimeValues(durationMinutes, businessStart, businessEnd, form.appointmentDate).map(time => { const value = time.value const startMinute = dateUtil.minutesOfDay(value) @@ -513,8 +541,8 @@ Page({ unifiedStyleDescription: '', customerOptions: [], customerDirectory: [], - businessStartTime: '10:00', - businessEndTime: '22:00', + businessStartTime: '', + businessEndTime: '', defaultAppointmentDurationMinutes: 60, durationManuallyChanged: false, customerSheetVisible: false, @@ -544,6 +572,7 @@ Page({ conflictTip: '', conflictLevel: 'free', canCreateAppointment: true, + canManageShopSettings: false, draftSavedAtText: '', manualImageUploading: false, timeSheetVisible: false, @@ -557,6 +586,7 @@ Page({ selectedTimeCandidate: '', timeLoading: false, timeError: '', + businessHoursMissing: false, timeSelectTip: '请先选择美甲师并填写时长', appointmentDayLabel: '', appointmentDateBadge: '', @@ -580,6 +610,7 @@ Page({ const dateLabels = buildAppointmentDateLabels(appointmentDate) this.setData({ canCreateAppointment: creatable, + canManageShopSettings: isShopManager(), form: { ...this.data.form, ...baseForm, @@ -606,6 +637,21 @@ Page({ this.loadOptions() }, + onShow() { + if (!this._refreshTimesAfterSettings) return + this._refreshTimesAfterSettings = false + this.refreshAvailableTimes() + }, + + openShopSettings() { + if (!this.data.canManageShopSettings) { + wx.showToast({ title: '请联系店长设置门店营业时间', icon: 'none' }) + return + } + this._refreshTimesAfterSettings = true + wx.navigateTo({ url: '/pages/shop-settings/index' }) + }, + async loadOptions() { this.setData({ loadingProducts: true }) try { @@ -650,7 +696,7 @@ Page({ endDate: this.data.form.appointmentDate }) let artists = getCalendarArtists(calendar) - const hours = String(calendar.businessHours || '10:00-22:00').split('-') + const businessHours = resolveBusinessHours(calendar) const defaultDuration = Number(calendar.defaultAppointmentDurationMinutes) || 60 const requestedId = preferredArtistId || this.data.form.artistId if (fallbackEmployee && requestedId && !findArtist(artists, requestedId).id) { @@ -664,8 +710,8 @@ Page({ ? findArtist(artists, requestedId) : unassignedSelection this.setData({ - businessStartTime: calendar.businessStartTime || hours[0] || '10:00', - businessEndTime: calendar.businessEndTime || hours[1] || '22:00', + businessStartTime: businessHours.start, + businessEndTime: businessHours.end, defaultAppointmentDurationMinutes: defaultDuration, ...(!this.data.durationManuallyChanged && !this.data.form.productId && !this.data.form.appointmentTime ? { 'form.durationMinutes': String(defaultDuration) } @@ -681,6 +727,8 @@ Page({ this.setData({ artists: [], artistSelectorItems: this.filterArtistItems([], this.data.artistKeyword), + businessStartTime: '', + businessEndTime: '', selectedArtist: unassignedSelection, 'form.artistId': '', artistError: error.message || '美甲师列表加载失败', @@ -1253,6 +1301,7 @@ Page({ selectedTimeCandidate: '', timePickerCandidateStatus: 'off-shift', timeError: '', + businessHoursMissing: false, timeSelectTip: '请先填写预约日期和时长' } if (form.appointmentTime) { @@ -1266,9 +1315,27 @@ Page({ try { const calendar = await planningApi.calendar({ startDate: form.appointmentDate, endDate: form.appointmentDate }) if (requestSeq !== this._availableTimeRequestSeq) return - const hours = String(calendar.businessHours || `${this.data.businessStartTime}-${this.data.businessEndTime}`).split('-') - const businessStartTime = calendar.businessStartTime || hours[0] || '10:00' - const businessEndTime = calendar.businessEndTime || hours[1] || '22:00' + const businessHours = resolveBusinessHours(calendar) + const businessStartTime = businessHours.start + const businessEndTime = businessHours.end + if (!businessStartTime) { + this.setData({ + businessStartTime: '', + businessEndTime: '', + availableTimeGroups: [], + timePickerSlots: [], + timePickerGroups: [], + timePickerHours: [], + timePickerMinutes: [], + selectedTimeCandidate: '', + 'form.appointmentTime': '', + timeError: '门店营业时间尚未设置,请先完成设置', + businessHoursMissing: true, + timeLoading: false, + timeSelectTip: '请先设置门店营业时间' + }) + return + } this.setData({ businessStartTime, businessEndTime }) const availableTimeGroups = buildUnassignedTimeGroups(durationMinutes, businessStartTime, businessEndTime, form.appointmentDate) const timePickerSlots = buildTimePickerSlots(calendar, form, durationMinutes) @@ -1278,12 +1345,27 @@ Page({ timePickerGroups: buildTimePickerGroups(timePickerSlots), ...buildTimeWheelState(timePickerSlots, form.appointmentTime), timeError: '', + businessHoursMissing: false, timeLoading: false, timeSelectTip: availableTimeGroups.length ? '请选择预约时间,美甲师可稍后分配' : '当前日期没有可选时段' }) } catch (error) { if (requestSeq === this._availableTimeRequestSeq) { - this.setData({ availableTimeGroups: [], timePickerSlots: [], timePickerGroups: [], timeError: error.message || '营业时间加载失败', timeLoading: false, timeSelectTip: '营业时间加载失败' }) + this.setData({ + businessStartTime: '', + businessEndTime: '', + availableTimeGroups: [], + timePickerSlots: [], + timePickerGroups: [], + timePickerHours: [], + timePickerMinutes: [], + selectedTimeCandidate: '', + 'form.appointmentTime': '', + timeError: error.message || '营业时间加载失败', + businessHoursMissing: false, + timeLoading: false, + timeSelectTip: '营业时间加载失败' + }) } } return @@ -1291,6 +1373,7 @@ Page({ this.setData({ timeLoading: true, timeError: '', + businessHoursMissing: false, timeSelectTip: '正在计算可约时间...' }) try { @@ -1302,6 +1385,25 @@ Page({ if (requestSeq !== this._availableTimeRequestSeq) { return } + const businessHours = resolveBusinessHours(calendar) + if (!businessHours.start) { + this.setData({ + businessStartTime: '', + businessEndTime: '', + availableTimeGroups: [], + timePickerSlots: [], + timePickerGroups: [], + timePickerHours: [], + timePickerMinutes: [], + selectedTimeCandidate: '', + 'form.appointmentTime': '', + timeError: '门店营业时间尚未设置,请先完成设置', + businessHoursMissing: true, + timeLoading: false, + timeSelectTip: '请先设置门店营业时间' + }) + return + } const availableTimeGroups = buildAvailableTimeGroups(calendar, form, durationMinutes) const availableTimes = flattenTimeGroups(availableTimeGroups).map(item => item.value) const timePickerSlots = buildTimePickerSlots(calendar, form, durationMinutes) @@ -1310,6 +1412,8 @@ Page({ timePickerSlots, timePickerGroups: buildTimePickerGroups(timePickerSlots), ...buildTimeWheelState(timePickerSlots, form.appointmentTime), + timeError: '', + businessHoursMissing: false, timeSelectTip: availableTimes.length > 0 ? '请选择预约时间' : '当前美甲师当天暂无可约时间' } if (form.appointmentTime && !availableTimes.includes(form.appointmentTime)) { @@ -1321,8 +1425,17 @@ Page({ return } this.setData({ + businessStartTime: '', + businessEndTime: '', availableTimeGroups: [], + timePickerSlots: [], + timePickerGroups: [], + timePickerHours: [], + timePickerMinutes: [], + selectedTimeCandidate: '', + 'form.appointmentTime': '', timeError: error.message || '可约时间加载失败', + businessHoursMissing: false, timeSelectTip: '可约时间加载失败' }) } finally { @@ -1436,6 +1549,13 @@ Page({ } const startMinute = dateUtil.minutesOfDay(appointmentTime) const endMinute = startMinute + durationMinutes + if (!this.data.businessStartTime || !this.data.businessEndTime) { + 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)) { const tip = `该时间超出营业时间 ${this.data.businessStartTime}-${this.data.businessEndTime}` this.setData({ conflictTip: tip, conflictLevel: 'danger' }) diff --git a/JC-Salon-WeChat/pages/appointment-form/index.wxml b/JC-Salon-WeChat/pages/appointment-form/index.wxml index 84a3d2c6..b3149b13 100644 --- a/JC-Salon-WeChat/pages/appointment-form/index.wxml +++ b/JC-Salon-WeChat/pages/appointment-form/index.wxml @@ -138,7 +138,7 @@ 选择预约时间{{form.appointmentDate}} · {{selectedArtist.name || '待分配'}} · {{form.durationMinutes}}分钟 正在计算可约时间... - {{timeError}} + {{businessHoursMissing && !canManageShopSettings ? '门店营业时间尚未设置,请联系店长完成设置' : timeError}} {{item.label}}{{item.label}} {{selectedTimeCandidate || '请选择时间'}} · 已被占用 · 已过时 · 当前无排班 diff --git a/JC-Salon-WeChat/pages/appointment-form/index.wxss b/JC-Salon-WeChat/pages/appointment-form/index.wxss index f6209a64..1447727d 100644 --- a/JC-Salon-WeChat/pages/appointment-form/index.wxss +++ b/JC-Salon-WeChat/pages/appointment-form/index.wxss @@ -418,6 +418,7 @@ .time-empty { min-height: 220rpx; display: flex; + flex-direction: column; align-items: center; justify-content: center; padding: 40rpx 20rpx; @@ -428,6 +429,19 @@ text-align: center; } +.time-empty-action { + flex: 0 0 auto; + height: 62rpx; + margin: 14rpx 0 0; + padding: 0 24rpx; + border-radius: 999rpx; + background: #247b63; + color: #fff; + font-size: 22rpx; + font-weight: 700; + line-height: 62rpx; +} + .action-row { display: flex; gap: 16rpx; diff --git a/JC-Salon-WeChat/pages/appointment-form/unassigned.test.js b/JC-Salon-WeChat/pages/appointment-form/unassigned.test.js index 77ac8e75..e4185048 100644 --- a/JC-Salon-WeChat/pages/appointment-form/unassigned.test.js +++ b/JC-Salon-WeChat/pages/appointment-form/unassigned.test.js @@ -13,6 +13,7 @@ global.wx = { setStorageSync: () => {}, showToast: () => {}, showModal: options => { lastModal = options; if (options.success) options.success({ confirm: true }) }, + navigateTo: () => {}, redirectTo: ({ url }) => { redirectedTo = url } } global.getApp = () => ({ globalData: appGlobalData }) @@ -79,6 +80,38 @@ async function run() { assert.strictEqual(availability.ok, true) assert.strictEqual(page.data.conflictTip.includes('待分配'), true) + appGlobalData.userInfo = { type: 2 } + const managerRolePage = createPage() + managerRolePage.loadOptions = () => {} + managerRolePage.onLoad({ date: futureDate }) + assert.strictEqual(managerRolePage.data.canManageShopSettings, true) + appGlobalData.userInfo = { type: 3 } + const staffRolePage = createPage() + staffRolePage.loadOptions = () => {} + staffRolePage.onLoad({ date: futureDate }) + assert.strictEqual(staffRolePage.data.canManageShopSettings, false) + appGlobalData = {} + + planningApi.calendar = async () => ({ artists: [], schedules: [], appointments: [] }) + const missingHoursPage = createPage() + Object.assign(missingHoursPage.data.form, { + appointmentDate: futureDate, + durationMinutes: '60', + artistId: '' + }) + await missingHoursPage.refreshAvailableTimes() + assert.strictEqual(missingHoursPage.data.timePickerSlots.length, 0) + assert.strictEqual(missingHoursPage.data.timeError, '门店营业时间尚未设置,请先完成设置') + assert.strictEqual(missingHoursPage.data.businessHoursMissing, true) + missingHoursPage.data.canManageShopSettings = true + missingHoursPage.openShopSettings() + assert.strictEqual(missingHoursPage._refreshTimesAfterSettings, true) + const staffMissingHoursPage = createPage() + staffMissingHoursPage.data.businessHoursMissing = true + staffMissingHoursPage.openShopSettings() + assert.strictEqual(staffMissingHoursPage._refreshTimesAfterSettings, undefined) + assert.match(appointmentWxml, /businessHoursMissing && canManageShopSettings\}\}.*前往店铺设置/) + const unassignedPage = createPage() Object.assign(unassignedPage.data.form, { appointmentTime: '14:00' }) unassignedPage.data.artists = [{ id: 2, name: '小李' }] @@ -124,6 +157,8 @@ async function run() { assert.strictEqual(redirectedTo, '/pages/appointment-detail/index?id=61') const walkInPage = createPage() + walkInPage.data.businessStartTime = '09:30' + walkInPage.data.businessEndTime = '18:00' Object.assign(walkInPage.data.form, { productId: '41', appointmentDate: futureDate, diff --git a/JC-Salon-WeChat/pages/planning/index.js b/JC-Salon-WeChat/pages/planning/index.js index 17488e10..b2026e6f 100644 --- a/JC-Salon-WeChat/pages/planning/index.js +++ b/JC-Salon-WeChat/pages/planning/index.js @@ -47,6 +47,22 @@ function resolveAppointmentTimeText(item) { return `${startText}-${endText}` } +function resolveBusinessHours(calendar = {}) { + const parts = String(calendar.businessHours || '').split('-') + const normalizeTime = value => { + const match = /^(\d{1,2}):(\d{2})(?::\d{2})?$/.exec(String(value || '').trim()) + if (!match) return '' + const hour = Number(match[1]) + const minute = Number(match[2]) + if (hour > 23 || minute > 59) return '' + return `${String(hour).padStart(2, '0')}:${String(minute).padStart(2, '0')}` + } + const start = normalizeTime(calendar.businessStartTime || parts[0]) + const end = normalizeTime(calendar.businessEndTime || parts[1]) + if (!start || !end || dateUtil.minutesOfDay(end) <= dateUtil.minutesOfDay(start)) return null + return { start, end } +} + function layoutAppointmentBlocks(items, startMinute, minuteScale, laneHeaderHeight, defaultLaneWidth) { const entries = (items || []) .filter(item => item.startTime) @@ -124,13 +140,16 @@ Page({ dateTitle: '', rangeText: '', weekRange: '', - businessStartTime: '10:00', - businessEndTime: '22:00', + businessStartTime: '', + businessEndTime: '', + businessHoursConfigured: false, + businessHoursText: '营业时间未设置', artists: [], monthDays: [], weekDays: [], dayLanes: [], hours: [], + hasTimedAppointments: false, timelineHeight: 720, laneWidth: 720, laneItemWidth: 240, @@ -143,6 +162,7 @@ Page({ rangeUnassignedCount: 0, nearestUnassignedDate: '', canCreateAppointment: true, + canManageShopSettings: false, loading: false, calendarError: '', phoneBannerVisible: false, @@ -152,7 +172,11 @@ Page({ }, onLoad() { - this.setData({ canCreateAppointment: canCreateAppointment() }) + const userInfo = getApp().globalData.userInfo || {} + this.setData({ + canCreateAppointment: canCreateAppointment(), + canManageShopSettings: Number(userInfo.type) === 2 + }) this.loadCalendar() }, @@ -165,6 +189,10 @@ Page({ wx.removeStorageSync('planningNeedRefresh') this.loadCalendar() } + if (this._refreshCalendarOnShow) { + this._refreshCalendarOnShow = false + this.loadCalendar() + } this.refreshAccountPrompts() }, @@ -302,6 +330,10 @@ Page({ this.openBackfillOrder(appointmentDate) return } + if (!this.data.businessHoursConfigured) { + wx.showToast({ title: '请先在店铺设置中配置营业时间', icon: 'none' }) + return + } this.openAppointmentForm(appointmentDate) }, @@ -376,13 +408,16 @@ Page({ clearCalendarView() { this._calendarData = { artists: [], appointments: [], daySummaries: [] } this.setData({ - businessStartTime: '10:00', - businessEndTime: '22:00', + businessStartTime: '', + businessEndTime: '', + businessHoursConfigured: false, + businessHoursText: '营业时间暂不可用', artists: [], monthDays: [], weekDays: [], dayLanes: [], hours: [], + hasTimedAppointments: false, dayTotal: 0, freeArtistCount: 0, pendingCount: 0, @@ -410,9 +445,11 @@ Page({ }, applyCalendar(calendar) { + const businessHours = resolveBusinessHours(calendar) const snapshot = { - businessStartTime: (calendar.businessStartTime || '10:00').slice(0, 5), - businessEndTime: (calendar.businessEndTime || '22:00').slice(0, 5), + businessStartTime: businessHours ? businessHours.start : '', + businessEndTime: businessHours ? businessHours.end : '', + businessHoursConfigured: Boolean(businessHours), artists: Array.isArray(calendar.artists) ? calendar.artists : [], appointments: Array.isArray(calendar.appointments) ? calendar.appointments : [], daySummaries: Array.isArray(calendar.daySummaries) ? calendar.daySummaries : [] @@ -421,6 +458,10 @@ Page({ this.setData({ businessStartTime: snapshot.businessStartTime, businessEndTime: snapshot.businessEndTime, + businessHoursConfigured: snapshot.businessHoursConfigured, + businessHoursText: snapshot.businessHoursConfigured + ? `${snapshot.businessStartTime}-${snapshot.businessEndTime}` + : '营业时间未设置', artists: snapshot.artists, calendarError: '', rangeUnassignedCount: snapshot.appointments.filter(item => !item.artistId).length, @@ -445,6 +486,7 @@ Page({ dateTitle: title, rangeText: this.data.viewMode === 'month' ? '月视图' : this.data.viewMode === 'week' ? '周视图' : '日视图', weekRange: `${formatMonthDay(range.start)} - ${formatMonthDay(range.end)}`, + businessHoursConfigured: Boolean(resolveBusinessHours(calendar)), monthDays: [], weekDays: [], dayLanes: [], @@ -521,8 +563,46 @@ Page({ buildDayView(calendar) { const minuteScale = 4 - const startMinute = dateUtil.minutesOfDay(calendar.businessStartTime || '10:00') - const endMinute = dateUtil.minutesOfDay(calendar.businessEndTime || '22:00') + const businessHours = resolveBusinessHours(calendar) + const filteredArtists = this.data.selectedArtistId + ? (calendar.artists || []).filter(item => String(item.id) === String(this.data.selectedArtistId)) + : (calendar.artists || []) + const dayAppointments = (calendar.appointments || []).filter(item => resolveAppointmentDate(item) === this.data.currentDateText) + const historicalBackfillItems = dayAppointments.filter(item => item.historicalBackfill) + const timedAppointments = dayAppointments + .filter(item => item.startTime) + .filter(item => !this.data.selectedArtistId || String(item.artistId) === String(this.data.selectedArtistId)) + const startMinutes = timedAppointments + .map(resolveAppointmentStartMinute) + .filter(value => Number.isFinite(value) && value >= 0 && value < 1440) + if (!businessHours && !startMinutes.length) { + const pendingCount = dayAppointments.filter(item => item.status === 0).length + return { + dayLanes: [], + hours: [], + hasTimedAppointments: false, + timelineHeight: 0, + laneHeaderHeight: 54, + laneItemWidth: 248, + laneWidth: 720, + dayTotal: dayAppointments.length, + freeArtistCount: 0, + pendingCount, + unassignedCount: dayAppointments.filter(item => !item.artistId).length, + historicalBackfillItems + } + } + const startMinute = businessHours + ? dateUtil.minutesOfDay(businessHours.start) + : Math.floor(Math.min(...startMinutes) / 60) * 60 + const latestAppointmentEnd = timedAppointments.reduce((latest, item) => { + const start = resolveAppointmentStartMinute(item) + const duration = Number(item.durationMinutes || 60) + return Math.max(latest, start + (Number.isFinite(duration) ? duration : 60)) + }, startMinute) + const endMinute = businessHours + ? dateUtil.minutesOfDay(businessHours.end) + : Math.min(1440, Math.max(startMinute + 60, Math.ceil(latestAppointmentEnd / 60) * 60)) const timelineHeight = Math.max(560, (endMinute - startMinute) * minuteScale) const laneHeaderHeight = 54 const hours = [] @@ -533,11 +613,6 @@ Page({ top: (cursor - startMinute) * minuteScale + laneHeaderHeight }) } - const filteredArtists = this.data.selectedArtistId - ? (calendar.artists || []).filter(item => String(item.id) === String(this.data.selectedArtistId)) - : (calendar.artists || []) - const dayAppointments = (calendar.appointments || []).filter(item => resolveAppointmentDate(item) === this.data.currentDateText) - const historicalBackfillItems = dayAppointments.filter(item => item.historicalBackfill) const employeeLanes = filteredArtists.map(artist => { const blocks = dayAppointments .filter(item => String(item.artistId) === String(artist.id)) @@ -578,6 +653,7 @@ Page({ return { dayLanes: lanes, hours, + hasTimedAppointments: timedAppointments.length > 0, timelineHeight: timelineHeight + laneHeaderHeight, laneHeaderHeight, laneItemWidth: 248, @@ -683,6 +759,10 @@ Page({ wx.showToast({ title: '当前账号仅支持查看预约', icon: 'none' }) return } + if (!this.data.businessHoursConfigured) { + wx.showToast({ title: '请先在店铺设置中配置营业时间', icon: 'none' }) + return + } this.openAppointmentForm(this.data.currentDateText) }, @@ -706,6 +786,11 @@ Page({ wx.navigateTo({ url: `/pages/appointment-form/index?${query.join('&')}` }) }, + openShopSettings() { + this._refreshCalendarOnShow = true + wx.navigateTo({ url: '/pages/shop-settings/index' }) + }, + openAppointment(event) { wx.navigateTo({ url: `/pages/appointment-detail/index?id=${event.currentTarget.dataset.id}` diff --git a/JC-Salon-WeChat/pages/planning/index.test.js b/JC-Salon-WeChat/pages/planning/index.test.js index 21435ba1..25ee3077 100644 --- a/JC-Salon-WeChat/pages/planning/index.test.js +++ b/JC-Salon-WeChat/pages/planning/index.test.js @@ -109,6 +109,24 @@ async function run() { const shortAppointmentLane = shortAppointmentState.dayLanes.find(lane => lane.artistId === 1) assert.strictEqual(shortAppointmentLane.blocks[0].height, 60) assert.strictEqual(shortAppointmentLane.blocks[0].compact, true) + const missingHoursPage = createPage({ viewMode: 'day', currentDateText: '2026-10-12' }) + const missingHoursEmptyState = missingHoursPage.buildDayView({ + artists: [{ id: 1, name: '美甲师', color: '#000' }], + appointments: [] + }) + assert.strictEqual(missingHoursEmptyState.hours.length, 0) + assert.strictEqual(missingHoursEmptyState.dayLanes.length, 0) + assert.strictEqual(missingHoursEmptyState.hasTimedAppointments, false) + missingHoursPage.clearCalendarView() + assert.strictEqual(missingHoursPage.data.businessHoursText, '营业时间暂不可用') + const missingHoursWithBookingState = missingHoursPage.buildDayView({ + artists: [{ id: 1, name: '美甲师', color: '#000' }], + appointments: [{ orderItemId: 10, date: '2026-10-12', startTime: '2026-10-12 15:30:00', durationMinutes: 60, artistId: 1 }] + }) + assert.strictEqual(missingHoursWithBookingState.hasTimedAppointments, true) + assert.strictEqual(missingHoursWithBookingState.hours[0].label, '15:00') + assert.strictEqual(missingHoursWithBookingState.hours[1].label, '16:00') + assert.strictEqual(missingHoursWithBookingState.dayLanes.find(lane => lane.artistId === 1).blocks.length, 1) assert.match(planningWxml, /class="hour-line" style="top: \{\{hour\.top\}\}rpx;"/) assert.match(planningWxml, /class="time-label" style="top: \{\{item\.top\}\}rpx;"/) assert.match(planningWxss, /\.hour-line\s*\{[^}]*transform:\s*translateY\(-50%\);/) @@ -136,6 +154,8 @@ async function run() { }) }) assert.match(planningWxml, /class="lane-unassigned-tag">不占档期/) + assert.match(planningWxml, /门店营业时间未设置/) + assert.match(planningWxml, /bindtap="openShopSettings"/) assert.match(planningWxml, /class="week-unassigned-count">待分配 \{\{item\.unassignedCount\}\}/) assert.match(planningWxml, /class="month-unassigned-count">待 \{\{item\.unassignedCount\}\}/) assert.doesNotMatch(planningWxss, /background-size:\s*100% 240rpx/) @@ -172,7 +192,7 @@ async function run() { global.wx.navigateTo = options => navigations.push(options.url) global.wx.showToast = options => toasts.push(options.title) - const quickCreatePage = createPage({ canCreateAppointment: true, selectedArtistId: '88' }) + const quickCreatePage = createPage({ canCreateAppointment: true, businessHoursConfigured: true, selectedArtistId: '88' }) const today = dateUtil.formatDate(new Date()) quickCreatePage.quickCreateAppointment({ currentTarget: { dataset: { date: today } } }) assert.strictEqual(navigations.pop(), `/pages/appointment-form/index?date=${today}&artistId=88`) @@ -190,14 +210,22 @@ async function run() { quickCreatePage.quickCreateAppointment({ currentTarget: { dataset: { date: '2000-01-01' } } }) assert.strictEqual(navigations.pop(), '/pages/backfill-order/index?serviceDate=2000-01-01') - const readonlyPage = createPage({ canCreateAppointment: false, selectedArtistId: '88' }) + const readonlyPage = createPage({ canCreateAppointment: false, businessHoursConfigured: true, selectedArtistId: '88' }) readonlyPage.quickCreateAppointment({ currentTarget: { dataset: { date: '2099-12-31' } } }) assert.strictEqual(navigations.length, 0) assert.strictEqual(toasts.pop(), '当前账号仅支持查看预约') - const fabPage = createPage({ canCreateAppointment: true, currentDateText: '2026-10-12', selectedArtistId: '99' }) + const fabPage = createPage({ canCreateAppointment: true, businessHoursConfigured: true, currentDateText: '2026-10-12', selectedArtistId: '99' }) fabPage.createAppointment() assert.strictEqual(navigations.pop(), '/pages/appointment-form/index?date=2026-10-12&artistId=99') + + const unconfiguredPage = createPage({ canCreateAppointment: true, businessHoursConfigured: false }) + unconfiguredPage.quickCreateAppointment({ currentTarget: { dataset: { date: '2099-12-31' } } }) + assert.strictEqual(navigations.length, 0) + assert.strictEqual(toasts.pop(), '请先在店铺设置中配置营业时间') + unconfiguredPage.openShopSettings() + assert.strictEqual(navigations.pop(), '/pages/shop-settings/index') + assert.strictEqual(unconfiguredPage._refreshCalendarOnShow, true) } run().catch(error => { diff --git a/JC-Salon-WeChat/pages/planning/index.wxml b/JC-Salon-WeChat/pages/planning/index.wxml index f19d0841..1ab0532e 100644 --- a/JC-Salon-WeChat/pages/planning/index.wxml +++ b/JC-Salon-WeChat/pages/planning/index.wxml @@ -10,7 +10,7 @@ {{dateTitle}} - {{businessStartTime}}-{{businessEndTime}} + {{businessHoursText}} @@ -35,6 +35,11 @@ + + 门店营业时间未设置设置后才能安排普通预约,历史订单与补录不受影响。 + + + 完善你的工作名片头像和昵称会用于门店协作展示,可暂时跳过。 @@ -83,7 +88,11 @@ - + + 预约时间轴暂不可用 + 请先设置门店营业时间,再安排普通预约。 + + {{item.label}} @@ -197,5 +206,5 @@ - + diff --git a/JC-Salon-WeChat/pages/planning/index.wxss b/JC-Salon-WeChat/pages/planning/index.wxss index 0acea536..58eaffec 100644 --- a/JC-Salon-WeChat/pages/planning/index.wxss +++ b/JC-Salon-WeChat/pages/planning/index.wxss @@ -171,6 +171,74 @@ font-size: 20rpx; } +.business-hours-notice { + display: flex; + align-items: center; + justify-content: space-between; + gap: 18rpx; + margin-top: 16rpx; + padding: 16rpx 18rpx; + border-left: 6rpx solid #d2a34e; + border-radius: 10rpx; + background: #fff9ea; +} + +.business-hours-notice-copy { + display: flex; + min-width: 0; + flex-direction: column; + gap: 4rpx; +} + +.business-hours-notice-title { + color: #775a25; + font-size: 23rpx; + font-weight: 800; +} + +.business-hours-notice-desc { + color: #8a7751; + font-size: 20rpx; + line-height: 1.4; +} + +.business-hours-action { + flex: 0 0 auto; + height: 54rpx; + margin: 0; + padding: 0 18rpx; + border-radius: 999rpx; + background: #247b63; + color: #fff; + font-size: 21rpx; + font-weight: 700; + line-height: 54rpx; +} + +.business-hours-empty { + display: flex; + min-height: 240rpx; + flex-direction: column; + align-items: center; + justify-content: center; + gap: 10rpx; + box-sizing: border-box; + padding: 36rpx 24rpx; + text-align: center; +} + +.business-hours-empty-title { + color: #26342d; + font-size: 25rpx; + font-weight: 800; +} + +.business-hours-empty-desc { + color: #71807a; + font-size: 21rpx; + line-height: 1.5; +} + .segmented { display: grid; grid-template-columns: repeat(3, 1fr); diff --git a/JC-Salon-WeChat/pages/shop-settings/index.js b/JC-Salon-WeChat/pages/shop-settings/index.js index 45630dda..d66eb3d9 100644 --- a/JC-Salon-WeChat/pages/shop-settings/index.js +++ b/JC-Salon-WeChat/pages/shop-settings/index.js @@ -10,6 +10,22 @@ function resolveNameStatus(value) { return '尚未提交审核' } +function resolveBusinessHours(value) { + const parts = String(value || '').split('-') + const normalizeTime = value => { + const match = /^(\d{1,2}):(\d{2})(?::\d{2})?$/.exec(String(value || '').trim()) + if (!match) return '' + const hour = Number(match[1]) + const minute = Number(match[2]) + if (hour > 23 || minute > 59) return '' + return `${String(hour).padStart(2, '0')}:${String(minute).padStart(2, '0')}` + } + const start = normalizeTime(parts[0]) + const end = normalizeTime(parts[1]) + if (!start || !end || start >= end) return null + return { start, end } +} + Page({ data: { profile: {}, @@ -18,9 +34,10 @@ Page({ nameModerationText: '尚未提交审核', settingsLoading: false, settingsSaving: false, + businessHoursConfigured: false, nameSaving: false, settingsError: '', - form: { shopName: BRAND_CONFIG.defaultShopName, pendingShopName: '', startTime: '10:00', endTime: '22:00', defaultDuration: 60 } + form: { shopName: BRAND_CONFIG.defaultShopName, pendingShopName: '', startTime: '', endTime: '', defaultDuration: 60 } }, onShow() { this.loadProfileAndSettings() }, @@ -40,9 +57,10 @@ Page({ : hasRemainingDays ? `剩余 ${remainingDays} 天` : '有效期未设置' - const [startTime, endTime] = String(settings.businessHours || '10:00-22:00').split('-') + const businessHours = resolveBusinessHours(settings.businessHours) this.setData({ profile, + businessHoursConfigured: Boolean(businessHours), businessExpireDateText, businessExpiryStatusText, nameModerationText: resolveNameStatus(settings.shopNameModerationStatus), @@ -50,13 +68,18 @@ Page({ ...this.data.form, shopName: settings.pendingShopName || settings.shopName || profile.shopName || BRAND_CONFIG.defaultShopName, pendingShopName: settings.pendingShopName || '', - startTime: startTime || '10:00', - endTime: endTime || '22:00', + startTime: businessHours ? businessHours.start : '', + endTime: businessHours ? businessHours.end : '', defaultDuration: Number(settings.defaultAppointmentDurationMinutes) || 60 } }) } catch (error) { - this.setData({ settingsError: error.message || '设置加载失败' }) + this.setData({ + settingsError: error.message || '设置加载失败', + businessHoursConfigured: false, + 'form.startTime': '', + 'form.endTime': '' + }) } finally { this.setData({ settingsLoading: false }) } @@ -69,8 +92,9 @@ Page({ async saveAppointmentSettings() { const { startTime, endTime, defaultDuration } = this.data.form const duration = Number(defaultDuration) - if (startTime >= endTime) { - wx.showToast({ title: '营业结束时间必须晚于开始时间', icon: 'none' }) + const businessHours = resolveBusinessHours(`${startTime}-${endTime}`) + if (!businessHours) { + wx.showToast({ title: '请设置完整有效的营业时间', icon: 'none' }) return } if (!Number.isInteger(duration) || duration < 15 || duration > 720) { @@ -79,7 +103,8 @@ Page({ } this.setData({ settingsSaving: true }) try { - await shopApi.saveAppointmentSettings({ businessHours: `${startTime}-${endTime}`, defaultAppointmentDurationMinutes: duration }) + await shopApi.saveAppointmentSettings({ businessHours: `${businessHours.start}-${businessHours.end}`, defaultAppointmentDurationMinutes: duration }) + this.setData({ businessHoursConfigured: true }) wx.showToast({ title: '预约设置已生效', icon: 'success' }) } catch (error) { wx.showToast({ title: error.message || '保存失败,请重试', icon: 'none' }) diff --git a/JC-Salon-WeChat/pages/shop-settings/index.test.js b/JC-Salon-WeChat/pages/shop-settings/index.test.js index 9681999a..1dbf086f 100644 --- a/JC-Salon-WeChat/pages/shop-settings/index.test.js +++ b/JC-Salon-WeChat/pages/shop-settings/index.test.js @@ -4,20 +4,18 @@ const path = require('path') let pageDefinition let currentProfile +let currentSettings +let savedSettings +let toastTitle global.Page = definition => { pageDefinition = definition } -global.wx = { showToast: () => {} } +global.wx = { showToast: options => { toastTitle = options.title } } const profileCache = require('../../utils/profile-cache') profileCache.getProfile = async () => currentProfile const shopApi = require('../../api/shop') -shopApi.appointmentSettings = async () => ({ - shopName: '薄荷美甲', - businessHours: '09:30-21:30', - defaultAppointmentDurationMinutes: 75, - shopNameModerationStatus: 'PENDING', - pendingShopName: '薄荷指尖' -}) +shopApi.appointmentSettings = async () => ({ ...currentSettings }) +shopApi.saveAppointmentSettings = async settings => { savedSettings = settings } require('./index') async function loadProfile(profile) { @@ -37,6 +35,13 @@ async function loadProfile(profile) { } async function run() { + currentSettings = { + shopName: '薄荷美甲', + businessHours: '09:30-21:30', + defaultAppointmentDurationMinutes: 75, + shopNameModerationStatus: 'PENDING', + pendingShopName: '薄荷指尖' + } const empty = await loadProfile({ type: 2, shopBusinessExpireTime: null, @@ -64,17 +69,51 @@ async function run() { assert.strictEqual(expired.businessExpiryStatusText, '已过期,暂不能新增预约') assert.strictEqual(expired.form.startTime, '09:30') assert.strictEqual(expired.form.endTime, '21:30') + assert.strictEqual(expired.businessHoursConfigured, true) assert.strictEqual(expired.form.defaultDuration, 75) assert.strictEqual(expired.nameModerationText, '名称审核中') assert.strictEqual(expired.form.pendingShopName, '薄荷指尖') const shopSettingsWxml = fs.readFileSync(path.join(__dirname, 'index.wxml'), 'utf8') const accountSettingsWxml = fs.readFileSync(path.join(__dirname, '../account-settings/index.wxml'), 'utf8') + assert(shopSettingsWxml.includes('预约运营设置')) + assert(shopSettingsWxml.includes('营业时间')) + assert(shopSettingsWxml.includes('默认预约时长')) + assert(shopSettingsWxml.includes('catchtap="explainDefaultDuration"')) assert(shopSettingsWxml.includes('wx:if="{{profile.type == 2}}" class="card business-expiry-card"')) assert(!accountSettingsWxml.includes('business-expiry-card')) assert(!shopSettingsWxml.includes('预约规则')) assert(shopSettingsWxml.includes('提交名称审核')) assert(shopSettingsWxml.includes('保存预约设置')) + assert(shopSettingsWxml.includes('设置开始时间')) + assert(shopSettingsWxml.includes('营业时间尚未设置')) + + currentSettings = { shopName: '新门店', businessHours: null, defaultAppointmentDurationMinutes: 60 } + const unconfigured = await loadProfile({ type: 2 }) + assert.strictEqual(unconfigured.form.startTime, '') + assert.strictEqual(unconfigured.form.endTime, '') + assert.strictEqual(unconfigured.businessHoursConfigured, false) + + const savePage = { + data: { ...pageDefinition.data, businessHoursConfigured: false, form: { ...pageDefinition.data.form, startTime: '', endTime: '' } }, + setData(values) { + Object.entries(values).forEach(([key, value]) => { + const parts = key.split('.') + if (parts.length === 1) this.data[key] = value + else this.data[parts[0]] = { ...this.data[parts[0]], [parts[1]]: value } + }) + } + } + savedSettings = undefined + await pageDefinition.saveAppointmentSettings.call(savePage) + assert.strictEqual(savedSettings, undefined) + assert.strictEqual(toastTitle, '请设置完整有效的营业时间') + + savePage.data.form.startTime = '09:00' + savePage.data.form.endTime = '21:30' + await pageDefinition.saveAppointmentSettings.call(savePage) + assert.deepStrictEqual(savedSettings, { businessHours: '09:00-21:30', defaultAppointmentDurationMinutes: 60 }) + assert.strictEqual(savePage.data.businessHoursConfigured, true) } run().catch(error => { diff --git a/JC-Salon-WeChat/pages/shop-settings/index.wxml b/JC-Salon-WeChat/pages/shop-settings/index.wxml index 147c260f..0d2f9da2 100644 --- a/JC-Salon-WeChat/pages/shop-settings/index.wxml +++ b/JC-Salon-WeChat/pages/shop-settings/index.wxml @@ -13,7 +13,8 @@ 预约运营设置保存后立即生效,不需要门店资料审核 - 营业时间{{form.startTime}}至{{form.endTime}} + 营业时间{{form.startTime || '设置开始时间'}}至{{form.endTime || '设置结束时间'}} + 营业时间尚未设置,保存后才能创建普通预约。 默认预约时长?分钟 diff --git a/JC-Salon-WeChat/pages/shop-settings/index.wxss b/JC-Salon-WeChat/pages/shop-settings/index.wxss index c8af52a5..b17e8c6b 100644 --- a/JC-Salon-WeChat/pages/shop-settings/index.wxss +++ b/JC-Salon-WeChat/pages/shop-settings/index.wxss @@ -16,6 +16,8 @@ .settings-label { color: #26342d; font-size: 24rpx; font-weight: 600; } .time-range { display: flex; align-items: center; gap: 15rpx; color: #859189; font-size: 21rpx; } .time-value { min-width: 102rpx; padding: 13rpx 14rpx; border-radius: 10rpx; background: #f0f6f2; color: #247b63; font-size: 24rpx; text-align: center; } +.time-value.unconfigured { color: #89958e; } +.appointment-hours-note { display: block; margin-top: 10rpx; color: #8a7751; font-size: 20rpx; line-height: 1.4; } .duration-row { align-items: center; } .duration-input { display: flex; align-items: center; gap: 12rpx; color: #748279; font-size: 22rpx; } .duration-input input { box-sizing: border-box; width: 150rpx; height: 68rpx; padding: 0 16rpx; border: 1rpx solid #dce8e0; border-radius: 10rpx; background: #f7faf8; color: #17211f; text-align: right; } diff --git a/docs/scripts/运行与发布配置总说明.md b/docs/scripts/运行与发布配置总说明.md index 3cf1bdc9..b0f08f0a 100644 --- a/docs/scripts/运行与发布配置总说明.md +++ b/docs/scripts/运行与发布配置总说明.md @@ -89,6 +89,8 @@ MessageHub 的地址、交换机、路由和来源系统放在对应环境 `core - 内容审核代码同时提供 DEV 本地确定性 mock 和微信 Provider。当前 DEV 配置使用 mock,未命中模拟标记时默认通过;可用显式标记覆盖通过、拒绝、待复核和故障结果。SIT/PROD 默认 fail-closed;只有在目标环境完成微信资质、回调域名、隐私指引和 Nacos 敏感配置后,才可将 Provider 切换为 `wechat`。微信 Provider 通过统一客户端缓存 access_token,图片审核使用对象存储短时 HTTPS 地址并由加密回调更新,业务模块不得直接调用微信接口。审核数据库变更依次由 Flyway V2(审核结构和存量复审)、V3(存量数据安全修正与协议版本)、V4(门店存量逐图任务完整性校验)和 V5(美甲师资料审核状态及存量资料隔离)管理。V5 对标签 ID 匹配显式统一到 `utf8mb4_unicode_ci`,并对可能在失败前已落库的字段和索引做存在性检查。MySQL 上失败的迁移需先核对部分 DDL,再运行 Flyway `repair` 清理失败历史记录;`repair` 不会撤销已执行的 DDL。具体参数和密钥维护说明见 `docs/scripts/Salon合规整改配置说明_20261021.md`。 - 店长审核模式和新店经营有效期通过 `t_system_parameter_config` 管理;Flyway V6 增加门店有效期字段、店长申请内容审核关联和默认参数,V7 修复无效默认天数并补齐已有门店的空有效期。自动批准仅在绑定的门店资料内容审核通过后生效;过期或未配置有效期的门店不能新增普通预约,补录和查询仍可用。参数默认值、发布验证和业务边界见 `docs/scripts/Salon店长审核与门店有效期配置说明_20261026.md`。 - Flyway V8 增加客户联系方式组合去重和美甲师专属颜色;V9 增加美甲师注册申请与门店员工档案的预关联字段,以及待审核目标员工唯一索引。V9 审核通过时将申请人的微信身份转移到已选员工档案,未关联员工不允许通过手机号登录;头像经注册票据受限上传并通过内容审核后才展示。两个迁移均为向前兼容版本 SQL,不修改初始化 SQL。 +- Flyway V10 增加门店预约运营营业时间和默认预约时长字段;老门店时长初始化为60分钟,迁移可重复执行,不修改冻结初始化 SQL。店长通过独立预约运营设置接口保存营业时间和时长,不触发门店公开资料审核;门店名称仍通过内容审核流程提交。普通预约时长优先使用明确选择值、再使用款式时长、最后使用门店默认值;历史日期和已过时间由小程序与 Core 双重拒绝,需转历史补单。 +- 预约选择客户使用门店范围专用接口返回完整联系电话,普通客户列表仍脱敏;客户预约建档与客户页保持姓名/微信号/手机号三字段完全一致才判重。预约日历以门店运营营业时间生成可选时段;接口无有效营业时间时不生成默认时段,页面明确提示先到店铺设置完成配置。 ## 8. 操作前检查 diff --git a/docs/项目变更记录.md b/docs/项目变更记录.md index a2a5500c..50178521 100644 --- a/docs/项目变更记录.md +++ b/docs/项目变更记录.md @@ -1,5 +1,16 @@ # 项目变更记录 +## 2026-10-30 Salon 注册、预约、客户与设置闭环修复 + +- 注册提交结果按服务端实际申请状态和资料审核状态展示;一次性票据失效时提示重新快捷登录获取凭证。 +- 普通预约日历读取门店配置营业时间,不再虚构默认时段;缺少有效配置时停止选择并提示重试。历史日期、当天已过时间以及超出营业时间的普通预约在小程序和 Core 同时拦截,改走历史补单。 +- 未配置营业时间时,规划页仅向店长提供设置入口;预约时间弹层按身份显示设置快捷入口或联系店长提示,避免员工进入无权设置页面。 +- 默认预约时长读取门店设置并作为缺省后备,已明确修改的时长和作品时长优先。预约运营设置与门店公开资料审核分离,门店名称继续走审核流程。 +- 预约选客户使用门店范围专用接口展示完整联系电话,普通客户列表仍脱敏;客户重复记录提供快速选择,散客预约说明与实际“不创建客户档案”行为一致。 +- 员工列表优先显示已保存专属颜色;排班引导明确门店营业时间限制。手机号绑定不预填脱敏号码,注销状态读取失败时提供错误提示和重试,不显示未知状态下的误导操作。 +- 新增 Flyway V10 `JC-Salon-Core/src/main/resources/db/migration/V10__预约运营设置和客户选择_20261030.sql`,添加营业时间和默认时长字段,历史门店默认60分钟;不修改冻结初始化 SQL。 +- Core clean test 76 项通过;小程序26个测试文件通过;新增服务端过去日期、营业时段、默认时长及预约设置测试,并覆盖缺少营业时间时不可选的回归场景。 + ## 2026-10-30 Salon 美甲师注册申请与员工微信账号关联 - 店长新增美甲师时创建无登录账号的员工档案,保留排班、预约和业绩使用的员工 ID;新增后可从本店待审核申请中选择并预关联,稍后仍可在审核时处理。