完善小程序登录排班与个人资料流程

This commit is contained in:
2026-11-03 15:33:03 +08:00
parent 6aafbd4eac
commit 19e2cd2594
37 changed files with 779 additions and 195 deletions
@@ -10,6 +10,8 @@ import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import java.io.InputStream;
@Service
@RequiredArgsConstructor
public class ObjectStorageDirectUploadService {
@@ -22,26 +24,43 @@ public class ObjectStorageDirectUploadService {
public ObjectStorageFileVO upload(MultipartFile file) throws Exception {
uploadSecurityValidator.validate(file);
String originalFilename = file.getOriginalFilename();
String fileExtension = originalFilename.substring(originalFilename.lastIndexOf("."));
String objectName = snowflakeIdGenerator.nextIdString() + fileExtension;
return upload(file.getOriginalFilename(), file.getInputStream(), file.getSize(), file.getContentType(), "");
}
public ObjectStorageFileVO uploadUserProfileImage(MultipartFile file, Long userId) throws Exception {
uploadSecurityValidator.validate(file);
return upload(file.getOriginalFilename(), file.getInputStream(), file.getSize(), file.getContentType(), "profile/" + userId + "/");
}
public ObjectStorageFileVO uploadUserProfileImage(String fileName, InputStream inputStream, long fileSize,
String contentType, Long userId) throws Exception {
uploadSecurityValidator.validateMetadata(fileName, contentType, fileSize);
return upload(fileName, inputStream, fileSize, contentType, "profile/" + userId + "/");
}
private ObjectStorageFileVO upload(String fileName, InputStream inputStream, long fileSize,
String contentType, String objectNamePrefix) throws Exception {
String extension = "";
if (fileName != null && fileName.lastIndexOf('.') >= 0) {
extension = fileName.substring(fileName.lastIndexOf('.'));
}
String objectName = objectNamePrefix + snowflakeIdGenerator.nextIdString() + extension;
ObjectStorageUploadOutcome uploadOutcome = objectStorageOrchestrationService.uploadPrimary(
file.getInputStream(),
file.getSize(),
file.getContentType(),
inputStream,
fileSize,
contentType,
objectName
);
ObjectStorageFileDTO dto = new ObjectStorageFileDTO();
dto.setFileName(originalFilename);
dto.setFileName(fileName);
dto.setFileUrl(uploadOutcome.getPrimaryUrl());
dto.setObjectName(objectName);
dto.setPrimaryProvider(uploadOutcome.getPrimaryProvider());
dto.setPrimaryUrl(uploadOutcome.getPrimaryUrl());
dto.setBackupProvider(String.join(",", objectStorageProperties.getReplicaRequiredProviders()));
dto.setContentType(file.getContentType());
dto.setFileSize(file.getSize());
dto.setContentType(contentType);
dto.setFileSize(fileSize);
dto.setPrimaryUploadStatus(1);
dto.setBackupUploadStatus(0);
dto.setBackupRetryCount(0);
@@ -117,12 +117,16 @@ public class PlanningServiceImpl implements PlanningService {
Long shopId = requirePlanningShopId(currentUser);
ShopDO shop = shopMapper.selectById(shopId);
PlanningCalendarSupport.BusinessHours businessHours = parseConfiguredBusinessHours(
shop == null ? null : (StringUtils.hasText(shop.getAppointmentBusinessHours())
? shop.getAppointmentBusinessHours() : shop.getBusinessHours()));
Map<Integer, ShopBusinessHoursDayVO> weeklyHours = shopBusinessScheduleService.mapByDay(
shopId, shop == null ? null : (StringUtils.hasText(shop.getAppointmentBusinessHours())
? shop.getAppointmentBusinessHours() : shop.getBusinessHours()));
PlanningCalendarSupport.BusinessHours businessHours = null;
for (int dayOfWeek = 1; dayOfWeek <= 7 && businessHours == null; dayOfWeek++) {
ShopBusinessHoursDayVO day = weeklyHours.get(dayOfWeek);
if (day != null && Boolean.TRUE.equals(day.getOpen())) {
businessHours = parseConfiguredBusinessHours(day.getStartTime() + "-" + day.getEndTime());
}
}
List<PlanningArtistVO> artists = listArtists(shopId, artistId);
List<ArtistScheduleDO> schedules = listSchedules(shopId, start, end, artistId);
@@ -81,6 +81,7 @@ public class WorkbenchRegistrationServiceImpl implements WorkbenchRegistrationSe
ContentModerationService contentModerationService,
ContentModerationRecordMapper contentModerationRecordMapper,
ShopBusinessExpiryService shopBusinessExpiryService,
ShopBusinessScheduleService shopBusinessScheduleService,
PlatformTransactionManager transactionManager,
WechatMiniBindingMapper wechatMiniBindingMapper,
ObjectStorageFileService objectStorageFileService,
@@ -97,6 +98,7 @@ public class WorkbenchRegistrationServiceImpl implements WorkbenchRegistrationSe
this.contentModerationService = contentModerationService;
this.contentModerationRecordMapper = contentModerationRecordMapper;
this.shopBusinessExpiryService = shopBusinessExpiryService;
this.shopBusinessScheduleService = shopBusinessScheduleService;
this.transactionTemplate = new TransactionTemplate(transactionManager);
this.wechatMiniBindingMapper = wechatMiniBindingMapper;
this.objectStorageFileService = objectStorageFileService;
@@ -15,6 +15,8 @@ import com.xiaowang.jayucloud.salon.core.modules.user.vo.UserVO;
import com.xiaowang.jayucloud.salon.core.modules.user.vo.InviteCodeVO;
import com.xiaowang.jayucloud.salon.core.modules.integration.vo.WechatMiniLoginResultVO;
import com.xiaowang.jayucloud.salon.core.modules.file.service.PrimaryObjectStorageService;
import com.xiaowang.jayucloud.salon.core.modules.file.service.ObjectStorageDirectUploadService;
import com.xiaowang.jayucloud.salon.core.modules.file.vo.ObjectStorageFileVO;
import com.xiaowang.jayucloud.salon.core.modules.user.service.UserService;
import com.xiaowang.jayucloud.salon.core.modules.security.service.ShopRoleService;
import com.xiaowang.jayucloud.salon.core.modules.auth.service.VerificationCodeService;
@@ -59,6 +61,7 @@ import com.xiaowang.jayucloud.salon.core.modules.integration.dto.WechatMiniQuick
import com.xiaowang.jayucloud.salon.core.modules.integration.dto.WechatMiniBindPhoneRequestDTO;
import com.xiaowang.jayucloud.salon.core.modules.user.dto.UserDTO;
import com.xiaowang.jayucloud.salon.core.modules.user.vo.UserAgreementConsentVO;
import com.xiaowang.jayucloud.salon.core.modules.user.vo.ProfileImageUploadVO;
/**
* 系统用户信息表 Controller
* 对应数据库表 t_user
@@ -78,6 +81,7 @@ public class UserController {
* Variable `primaryObjectStorageService`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls.
*/
private final PrimaryObjectStorageService primaryObjectStorageService;
private final ObjectStorageDirectUploadService objectStorageDirectUploadService;
/**
* Variable `chunkUploadService`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls.
*/
@@ -780,14 +784,12 @@ public class UserController {
try (ChunkUploadService.PreparedUploadFile preparedUploadFile =
chunkUploadService.prepareUserAvatarFile(userId, requestDTO.getUploadId());
FileInputStream inputStream = new FileInputStream(preparedUploadFile.getFile())) {
String originalFilename = preparedUploadFile.getFileName();
String fileExtension = originalFilename.substring(originalFilename.lastIndexOf("."));
String objectName = "avatar/" + userId + "/" + snowflakeIdGenerator.nextIdString() + fileExtension;
String avatarUrl = primaryObjectStorageService.uploadStream(inputStream, preparedUploadFile.getFileSize(), preparedUploadFile.getContentType(), objectName);
userService.updateUserAvatar(userId, avatarUrl);
ObjectStorageFileVO file = objectStorageDirectUploadService.uploadUserProfileImage(
preparedUploadFile.getFileName(), inputStream, preparedUploadFile.getFileSize(),
preparedUploadFile.getContentType(), userId);
userService.updateUserAvatar(userId, file.getObjectName());
chunkUploadService.clearUserAvatarUpload(userId, requestDTO.getUploadId());
return Result.success(objectStorageUrlSupport.toAccessibleUrl(avatarUrl));
return Result.success(objectStorageUrlSupport.getSignedUrlOrThrow(file, 60));
} catch (Exception e) {
e.printStackTrace();
return Result.error("头像上传失败: " + e.getMessage());
@@ -818,14 +820,9 @@ public class UserController {
public Result<String> uploadAvatar(HttpServletRequest request, @RequestParam("file") MultipartFile file) {
try {
Long userId = (Long) request.getAttribute("userId");
String originalFilename = file.getOriginalFilename();
String fileExtension = originalFilename.substring(originalFilename.lastIndexOf("."));
String objectName = "avatar/" + userId + "/" + snowflakeIdGenerator.nextIdString() + fileExtension;
String avatarUrl = primaryObjectStorageService.uploadFile(file, objectName);
userService.updateUserAvatar(userId, avatarUrl);
return Result.success(objectStorageUrlSupport.toAccessibleUrl(avatarUrl));
ObjectStorageFileVO uploaded = objectStorageDirectUploadService.uploadUserProfileImage(file, userId);
userService.updateUserAvatar(userId, uploaded.getObjectName());
return Result.success(objectStorageUrlSupport.getSignedUrlOrThrow(uploaded, 60));
} catch (Exception e) {
e.printStackTrace();
return Result.error("头像上传失败: " + e.getMessage());
@@ -862,20 +859,16 @@ public class UserController {
@PostMapping("/upload-profile-image/complete")
@OperationGuard(action = "user-profile-image-upload-complete", ttlSeconds = 30, message = "上传处理中,请勿重复操作")
public Result<String> completeProfileImageUpload(HttpServletRequest request, @Valid @RequestBody ChunkUploadCompleteRequestDTO requestDTO) {
public Result<ProfileImageUploadVO> completeProfileImageUpload(HttpServletRequest request, @Valid @RequestBody ChunkUploadCompleteRequestDTO requestDTO) {
Long userId = (Long) request.getAttribute("userId");
try (ChunkUploadService.PreparedUploadFile preparedUploadFile =
chunkUploadService.prepareUserProfileImageFile(userId, requestDTO.getUploadId());
FileInputStream inputStream = new FileInputStream(preparedUploadFile.getFile())) {
String originalFilename = preparedUploadFile.getFileName();
String fileExtension = "";
if (originalFilename != null && originalFilename.lastIndexOf(".") >= 0) {
fileExtension = originalFilename.substring(originalFilename.lastIndexOf("."));
}
String objectName = "profile/" + userId + "/" + snowflakeIdGenerator.nextIdString() + fileExtension;
String imageUrl = primaryObjectStorageService.uploadStream(inputStream, preparedUploadFile.getFileSize(), preparedUploadFile.getContentType(), objectName);
ObjectStorageFileVO file = objectStorageDirectUploadService.uploadUserProfileImage(
preparedUploadFile.getFileName(), inputStream, preparedUploadFile.getFileSize(),
preparedUploadFile.getContentType(), userId);
chunkUploadService.clearUserProfileImageUpload(userId, requestDTO.getUploadId());
return Result.success(objectStorageUrlSupport.toAccessibleUrl(imageUrl));
return Result.success(toProfileImageUploadVO(file));
} catch (Exception e) {
e.printStackTrace();
return Result.error("资料图片上传失败: " + e.getMessage());
@@ -892,26 +885,27 @@ public class UserController {
@PostMapping("/upload-profile-image")
@OperationGuard(action = "user-profile-image-upload", ttlSeconds = 30, message = "上传处理中,请勿重复操作")
public Result<String> uploadProfileImage(HttpServletRequest request, @RequestParam("file") MultipartFile file) {
public Result<ProfileImageUploadVO> uploadProfileImage(HttpServletRequest request, @RequestParam("file") MultipartFile file) {
try {
if (file == null || file.isEmpty()) {
return Result.error("请选择要上传的图片");
}
Long userId = (Long) request.getAttribute("userId");
String originalFilename = file.getOriginalFilename();
String fileExtension = "";
if (originalFilename != null && originalFilename.lastIndexOf(".") >= 0) {
fileExtension = originalFilename.substring(originalFilename.lastIndexOf("."));
}
String objectName = "profile/" + userId + "/" + snowflakeIdGenerator.nextIdString() + fileExtension;
String imageUrl = primaryObjectStorageService.uploadFile(file, objectName);
return Result.success(objectStorageUrlSupport.toAccessibleUrl(imageUrl));
ObjectStorageFileVO uploaded = objectStorageDirectUploadService.uploadUserProfileImage(file, userId);
return Result.success(toProfileImageUploadVO(uploaded));
} catch (Exception e) {
e.printStackTrace();
return Result.error("资料图片上传失败: " + e.getMessage());
}
}
private ProfileImageUploadVO toProfileImageUploadVO(ObjectStorageFileVO file) {
ProfileImageUploadVO result = new ProfileImageUploadVO();
result.setFileId(file.getId());
result.setFileUrl(objectStorageUrlSupport.getSignedUrlOrThrow(file, 60));
return result;
}
/**
* 重置用户密码。
*/
@@ -48,6 +48,9 @@ public class UserDTO {
*/
private String avatar;
/** 当前用户本人上传的头像文件 ID。 */
private Long avatarFileId;
/**
* 用户签名
*/
@@ -39,6 +39,7 @@ import com.xiaowang.jayucloud.salon.core.modules.registration.mapper.WorkbenchRe
import com.xiaowang.jayucloud.salon.core.modules.system.support.AdminDefaultPasswordSupport;
import com.xiaowang.jayucloud.salon.core.modules.file.support.ObjectStorageUrlSupport;
import com.xiaowang.jayucloud.salon.core.modules.file.service.ObjectStorageFileService;
import com.xiaowang.jayucloud.salon.core.modules.file.vo.ObjectStorageFileVO;
import com.xiaowang.jayucloud.salon.core.modules.security.support.PermissionCatalog;
import com.xiaowang.jayucloud.salon.core.support.security.UserSessionService;
import com.xiaowang.jayucloud.salon.core.support.id.TimeOrderedSnowflakeIdGenerator;
@@ -1950,17 +1951,29 @@ public class UserServiceImpl extends ServiceImpl<UserMapper, UserDO> implements
*/
assertUserAvailable(userDO);
String avatarForUpdate = userDTO.getAvatarFileId() == null
? userDTO.getAvatar()
: resolveOwnedProfileFileReference(userId, userDTO.getAvatarFileId());
if (avatarForUpdate != null && !avatarForUpdate.isEmpty()) {
avatarForUpdate = normalizeOwnedProfileImage(userId, avatarForUpdate, userDO.getAvatar());
}
String qrForUpdate = userDTO.getWechatQrCode();
if (qrForUpdate != null && !qrForUpdate.isEmpty()) {
qrForUpdate = normalizeOwnedProfileImage(userId, qrForUpdate, userDO.getWechatQrCode());
}
boolean profileApproved = true;
if (userDTO.getNickname() != null || userDTO.getSignature() != null
|| (userDTO.getAvatar() != null && !userDTO.getAvatar().isEmpty()) || userDTO.getWechatQrCode() != null) {
|| (userDTO.getAvatar() != null && !userDTO.getAvatar().isEmpty()) || userDTO.getAvatarFileId() != null
|| userDTO.getWechatQrCode() != null) {
Map<String, String> content = new java.util.LinkedHashMap<>();
content.put("nickname", userDTO.getNickname() == null ? userDO.getNickname() : userDTO.getNickname());
content.put("signature", userDTO.getSignature() == null ? userDO.getSignature() : userDTO.getSignature());
content.put("avatar", userDTO.getAvatar() == null
content.put("avatar", avatarForUpdate == null
? userDO.getAvatar()
: (userDTO.getAvatar().isEmpty() ? null : normalizeStoredAvatar(userDTO.getAvatar())));
: (avatarForUpdate.isEmpty() ? null : avatarForUpdate));
content.put("wechatQrCode", userDTO.getWechatQrCode() == null
? userDO.getWechatQrCode() : normalizeStoredProfileImage(userDTO.getWechatQrCode()));
? userDO.getWechatQrCode() : (qrForUpdate.isEmpty() ? null : qrForUpdate));
String serialized = serializeModerationPayload(content);
List<Long> profileImages = new ArrayList<>();
addImageFileId(profileImages, content.get("avatar"));
@@ -1974,11 +1987,11 @@ public class UserServiceImpl extends ServiceImpl<UserMapper, UserDO> implements
if (profileApproved && userDTO.getNickname() != null) {
userDO.setNickname(userDTO.getNickname());
}
if (profileApproved && userDTO.getAvatar() != null) {
if (userDTO.getAvatar().isEmpty()) {
if (profileApproved && (userDTO.getAvatar() != null || userDTO.getAvatarFileId() != null)) {
if (avatarForUpdate == null || avatarForUpdate.isEmpty()) {
userDO.setAvatar(null);
} else {
userDO.setAvatar(normalizeStoredAvatar(userDTO.getAvatar()));
userDO.setAvatar(avatarForUpdate);
}
}
if (profileApproved && userDTO.getSignature() != null) {
@@ -1994,7 +2007,7 @@ public class UserServiceImpl extends ServiceImpl<UserMapper, UserDO> implements
userDO.setWechatId(UserProfileFieldSupport.normalizeOptionalText(userDTO.getWechatId()));
}
if (profileApproved && userDTO.getWechatQrCode() != null) {
userDO.setWechatQrCode(normalizeStoredProfileImage(userDTO.getWechatQrCode()));
userDO.setWechatQrCode(qrForUpdate.isEmpty() ? null : qrForUpdate);
}
UserProfileFieldSupport.requireWechatIdForServiceUser(userDO.getType(), userDO.getWechatId());
@@ -2448,7 +2461,7 @@ public class UserServiceImpl extends ServiceImpl<UserMapper, UserDO> implements
* @return result consumed by the caller or returned to the frontend
*/
assertUserAvailable(userDO);
String storedAvatar = normalizeStoredAvatar(avatarUrl);
String storedAvatar = normalizeOwnedProfileImage(userId, avatarUrl, userDO.getAvatar());
List<Long> imageIds = new ArrayList<>();
addImageFileId(imageIds, storedAvatar);
ContentModerationResultVO moderation = contentModerationService.assessVersion("USER_AVATAR", userId, userId,
@@ -2466,6 +2479,45 @@ public class UserServiceImpl extends ServiceImpl<UserMapper, UserDO> implements
if (!imageIds.contains(fileId)) imageIds.add(fileId);
}
private String resolveOwnedProfileFileReference(Long userId, Long fileId) {
if (fileId == null || fileId <= 0) {
throw new IllegalArgumentException("个人资料图片文件无效");
}
ObjectStorageFileVO file = objectStorageFileService.getObjectStorageFileById(fileId);
String objectName = file == null ? null : file.getObjectName();
String prefix = "profile/" + userId + "/";
if (file == null || !Integer.valueOf(1).equals(file.getStatus()) || !StringUtils.hasText(objectName)
|| !objectName.startsWith(prefix)) {
throw new IllegalArgumentException("个人资料图片必须引用本人上传的文件");
}
return objectName;
}
private String normalizeOwnedProfileImage(Long userId, String reference, String existingReference) {
if (!StringUtils.hasText(reference) || DEFAULT_AVATAR_URL.equals(reference)) return reference;
Long fileId;
if (reference.trim().matches("\\d+")) {
try {
fileId = Long.parseLong(reference.trim());
} catch (NumberFormatException exception) {
throw new IllegalArgumentException("个人资料图片文件无效");
}
} else {
fileId = objectStorageFileService.findFileIdByReference(reference);
}
if (fileId == null || fileId <= 0) throw new IllegalArgumentException("个人资料图片必须引用已上传文件");
ObjectStorageFileVO file = objectStorageFileService.getObjectStorageFileById(fileId);
if (file == null || !Integer.valueOf(1).equals(file.getStatus()) || !StringUtils.hasText(file.getObjectName())) {
throw new IllegalArgumentException("个人资料图片不存在或不可用");
}
String normalized = normalizeStoredProfileImage(file.getObjectName());
boolean unchanged = Objects.equals(reference, existingReference) || Objects.equals(normalized, existingReference);
if (!unchanged && !file.getObjectName().startsWith("profile/" + userId + "/")) {
throw new IllegalArgumentException("个人资料图片必须引用本人上传的文件");
}
return normalized;
}
private String serializeModerationPayload(Object payload) {
try {
return objectMapper.writeValueAsString(payload);
@@ -0,0 +1,9 @@
package com.xiaowang.jayucloud.salon.core.modules.user.vo;
import lombok.Data;
@Data
public class ProfileImageUploadVO {
private Long fileId;
private String fileUrl;
}
@@ -23,6 +23,8 @@ import com.xiaowang.jayucloud.salon.core.modules.security.support.AdminScopeHelp
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.shop.service.ShopBusinessExpiryService;
import com.xiaowang.jayucloud.salon.core.modules.shop.service.ShopBusinessScheduleService;
import com.xiaowang.jayucloud.salon.core.modules.shop.vo.ShopBusinessHoursDayVO;
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;
@@ -39,6 +41,7 @@ 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.lenient;
import static org.mockito.Mockito.doAnswer;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.spy;
@@ -60,6 +63,7 @@ class PlanningServiceImplTest {
@Mock private ProductMapper productMapper;
@Mock private ShopMapper shopMapper;
@Mock private ShopBusinessExpiryService shopBusinessExpiryService;
@Mock private ShopBusinessScheduleService shopBusinessScheduleService;
@Mock private AppointmentCapacityService appointmentCapacityService;
@Mock private OrderService orderService;
@Mock private WechatSubscribeMessageService wechatSubscribeMessageService;
@@ -72,8 +76,14 @@ class PlanningServiceImplTest {
void setUp() {
service = new PlanningServiceImpl(adminScopeHelper, userMapper, userService, nailArtistInfoMapper, artistScheduleMapper,
artistScheduleExceptionMapper, appointmentReservationMapper, orderMapper, orderItemMapper,
productMapper, shopMapper, shopBusinessExpiryService, appointmentCapacityService, orderService, wechatSubscribeMessageService, snowflakeIdGenerator,
productMapper, shopMapper, shopBusinessExpiryService, shopBusinessScheduleService, appointmentCapacityService, orderService, wechatSubscribeMessageService, snowflakeIdGenerator,
objectStorageUrlSupport);
ShopBusinessHoursDayVO defaultOpenDay = new ShopBusinessHoursDayVO();
defaultOpenDay.setOpen(true);
defaultOpenDay.setStartTime("10:00");
defaultOpenDay.setEndTime("22:00");
lenient().when(shopBusinessScheduleService.forDate(any(), any(), org.mockito.ArgumentMatchers.nullable(String.class)))
.thenReturn(defaultOpenDay);
}
@Test
@@ -139,6 +149,13 @@ class PlanningServiceImplTest {
dto.setAppointmentDate(java.time.LocalDate.now().plusDays(2).toString());
dto.setAppointmentTime("19:30");
dto.setDurationMinutes(60);
ShopBusinessHoursDayVO openDay = new ShopBusinessHoursDayVO();
openDay.setOpen(true);
openDay.setStartTime("10:00");
openDay.setEndTime("20:00");
when(shopBusinessScheduleService.forDate(org.mockito.ArgumentMatchers.eq(21L),
org.mockito.ArgumentMatchers.eq(java.time.LocalDate.parse(dto.getAppointmentDate())),
org.mockito.ArgumentMatchers.nullable(String.class))).thenReturn(openDay);
RuntimeException error = assertThrows(RuntimeException.class, () -> service.createAppointment(operator, dto));
@@ -147,7 +164,7 @@ class PlanningServiceImplTest {
}
@Test
void rejectsAppointmentWhenShopBusinessHoursAreMissing() {
void rejectsAppointmentWhenShopIsClosedOnRequestedWeekday() {
UserDO operator = new UserDO();
operator.setType(2);
ShopDO shop = new ShopDO();
@@ -158,13 +175,68 @@ class PlanningServiceImplTest {
dto.setAppointmentDate(java.time.LocalDate.now().plusDays(2).toString());
dto.setAppointmentTime("14:00");
dto.setDurationMinutes(60);
ShopBusinessHoursDayVO closedDay = new ShopBusinessHoursDayVO();
closedDay.setOpen(false);
when(shopBusinessScheduleService.forDate(org.mockito.ArgumentMatchers.eq(21L),
org.mockito.ArgumentMatchers.eq(java.time.LocalDate.parse(dto.getAppointmentDate())),
org.mockito.ArgumentMatchers.nullable(String.class))).thenReturn(closedDay);
RuntimeException error = assertThrows(RuntimeException.class, () -> service.createAppointment(operator, dto));
assertEquals("门店营业时间未设置,请先完成设置", error.getMessage());
assertEquals("预约日期门店休息,暂不可新建普通预约", error.getMessage());
verify(orderMapper, never()).insert(any(OrderDO.class));
}
@Test
void calendarHasNoFallbackHoursWhenEveryShopDayIsClosed() {
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(shopBusinessScheduleService.mapByDay(21L, "10:00-22:00")).thenReturn(closedWeeklySchedule());
mockEmptyCalendarRows();
com.xiaowang.jayucloud.salon.core.modules.planning.vo.PlanningCalendarVO calendar = service.getCalendar(
operator, java.time.LocalDate.of(2026, 11, 2), java.time.LocalDate.of(2026, 11, 2), null);
assertNull(calendar.getBusinessStartTime());
assertNull(calendar.getBusinessEndTime());
assertEquals(false, calendar.getDaySummaries().get(0).getShopOpen());
assertEquals("rest", calendar.getDaySummaries().get(0).getDayStatus());
}
@Test
void calendarUsesWeeklyHoursInsteadOfLegacyHoursWhenAnyShopDayIsOpen() {
UserDO operator = new UserDO();
operator.setType(2);
ShopDO shop = new ShopDO();
shop.setId(21L);
shop.setBusinessHours("10:00-22:00");
java.util.Map<Integer, ShopBusinessHoursDayVO> weeklyHours = closedWeeklySchedule();
ShopBusinessHoursDayVO monday = new ShopBusinessHoursDayVO();
monday.setDayOfWeek(1);
monday.setOpen(true);
monday.setStartTime("12:00");
monday.setEndTime("19:00");
weeklyHours.put(1, monday);
when(adminScopeHelper.resolveShopScope(operator, null)).thenReturn(21L);
when(shopMapper.selectById(21L)).thenReturn(shop);
when(shopBusinessScheduleService.mapByDay(21L, "10:00-22:00")).thenReturn(weeklyHours);
mockEmptyCalendarRows();
com.xiaowang.jayucloud.salon.core.modules.planning.vo.PlanningCalendarVO calendar = service.getCalendar(
operator, java.time.LocalDate.of(2026, 11, 2), java.time.LocalDate.of(2026, 11, 2), null);
assertEquals("12:00", calendar.getBusinessStartTime());
assertEquals("19:00", calendar.getBusinessEndTime());
assertEquals(true, calendar.getDaySummaries().get(0).getShopOpen());
assertEquals("12:00", calendar.getDaySummaries().get(0).getShopStartTime());
assertEquals("19:00", calendar.getDaySummaries().get(0).getShopEndTime());
}
@Test
void usesShopDefaultDurationWhenRequestOmitsDuration() {
UserDO operator = new UserDO();
@@ -515,4 +587,22 @@ class PlanningServiceImplTest {
order.setIsDelete(0);
return order;
}
private java.util.Map<Integer, ShopBusinessHoursDayVO> closedWeeklySchedule() {
java.util.Map<Integer, ShopBusinessHoursDayVO> days = new java.util.HashMap<>();
for (int dayOfWeek = 1; dayOfWeek <= 7; dayOfWeek++) {
ShopBusinessHoursDayVO day = new ShopBusinessHoursDayVO();
day.setDayOfWeek(dayOfWeek);
day.setOpen(false);
days.put(dayOfWeek, day);
}
return days;
}
private void mockEmptyCalendarRows() {
when(userMapper.selectList(any(Wrapper.class))).thenReturn(java.util.List.of());
when(artistScheduleMapper.selectList(any(Wrapper.class))).thenReturn(java.util.List.of());
when(appointmentReservationMapper.selectList(any(Wrapper.class))).thenReturn(java.util.List.of());
when(orderItemMapper.selectList(any(Wrapper.class))).thenReturn(java.util.List.of());
}
}
@@ -19,6 +19,7 @@ import com.xiaowang.jayucloud.salon.core.modules.registration.vo.WorkbenchRegist
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.shop.service.ShopBusinessExpiryService;
import com.xiaowang.jayucloud.salon.core.modules.shop.service.ShopBusinessScheduleService;
import com.xiaowang.jayucloud.salon.core.modules.shop.mapper.UserShopBindingMapper;
import com.xiaowang.jayucloud.salon.core.modules.shop.support.UserShopBindingSupport;
import com.xiaowang.jayucloud.salon.core.modules.system.service.SystemParameterConfigService;
@@ -55,6 +56,7 @@ class WorkbenchRegistrationServiceImplTest {
@Mock private ContentModerationService contentModerationService;
@Mock private ContentModerationRecordMapper contentModerationRecordMapper;
@Mock private ShopBusinessExpiryService shopBusinessExpiryService;
@Mock private ShopBusinessScheduleService shopBusinessScheduleService;
@Mock private PlatformTransactionManager transactionManager;
@Mock private WechatMiniBindingMapper wechatMiniBindingMapper;
@Mock private ObjectStorageFileService objectStorageFileService;
@@ -66,7 +68,7 @@ class WorkbenchRegistrationServiceImplTest {
void setUp() {
service = new WorkbenchRegistrationServiceImpl(applicationMapper, userMapper, shopMapper, userService,
userShopBindingSupport, userShopBindingMapper, wechatMiniAuthService, systemParameterConfigService,
contentModerationService, contentModerationRecordMapper, shopBusinessExpiryService, transactionManager,
contentModerationService, contentModerationRecordMapper, shopBusinessExpiryService, shopBusinessScheduleService, transactionManager,
wechatMiniBindingMapper, objectStorageFileService, objectStorageUrlSupport);
}
@@ -21,6 +21,8 @@ import com.xiaowang.jayucloud.salon.core.modules.shop.dto.ShopAppointmentSetting
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.service.ShopBusinessScheduleService;
import com.xiaowang.jayucloud.salon.core.modules.shop.vo.ShopBusinessHoursDayVO;
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;
@@ -36,6 +38,7 @@ import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.verifyNoInteractions;
import static org.mockito.Mockito.when;
import static org.mockito.ArgumentMatchers.eq;
@ExtendWith(MockitoExtension.class)
class ShopAppointmentSettingsTest {
@@ -43,6 +46,7 @@ class ShopAppointmentSettingsTest {
@Mock private ShopMapper shopMapper;
@Mock private ContentModerationRecordMapper contentModerationRecordMapper;
@Mock private ShopBusinessExpiryService shopBusinessExpiryService;
@Mock private ShopBusinessScheduleService shopBusinessScheduleService;
@Mock private CouponService couponService;
@Mock private CouponMapper couponMapper;
@Mock private ProductMapper productMapper;
@@ -71,8 +75,9 @@ class ShopAppointmentSettingsTest {
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.setWeeklyHours(weeklyHours("09:30", "21:00"));
dto.setDefaultAppointmentDurationMinutes(75);
when(shopBusinessScheduleService.list(21L, "10:00-22:00")).thenReturn(weeklyHoursVO("09:30", "21:00"));
assertTrue(shopService.updateAppointmentSettings(21L, dto));
@@ -80,6 +85,7 @@ class ShopAppointmentSettingsTest {
verify(shopMapper).updateById(saved.capture());
assertEquals("09:30-21:00", saved.getValue().getAppointmentBusinessHours());
assertEquals(75, saved.getValue().getDefaultAppointmentDurationMinutes());
verify(shopBusinessScheduleService).save(eq(21L), eq(dto.getWeeklyHours()), eq(null));
verifyNoInteractions(contentModerationService);
}
@@ -91,10 +97,38 @@ class ShopAppointmentSettingsTest {
shop.setBusinessHours("09:00-21:00");
when(shopMapper.selectById(21L)).thenReturn(shop);
when(contentModerationRecordMapper.selectOne(any(Wrapper.class))).thenReturn(null);
when(shopBusinessScheduleService.list(21L, "09:00-21:00")).thenReturn(weeklyHoursVO("09:00", "21:00"));
ShopAppointmentSettingsVO settings = shopService.getAppointmentSettings(21L);
assertEquals("09:00-21:00", settings.getBusinessHours());
assertEquals(7, settings.getWeeklyHours().size());
assertEquals(60, settings.getDefaultAppointmentDurationMinutes());
}
private java.util.List<com.xiaowang.jayucloud.salon.core.modules.shop.dto.ShopBusinessHoursDayDTO> weeklyHours(String start, String end) {
java.util.List<com.xiaowang.jayucloud.salon.core.modules.shop.dto.ShopBusinessHoursDayDTO> result = new java.util.ArrayList<>();
for (int day = 1; day <= 7; day++) {
com.xiaowang.jayucloud.salon.core.modules.shop.dto.ShopBusinessHoursDayDTO item = new com.xiaowang.jayucloud.salon.core.modules.shop.dto.ShopBusinessHoursDayDTO();
item.setDayOfWeek(day);
item.setOpen(true);
item.setStartTime(start);
item.setEndTime(end);
result.add(item);
}
return result;
}
private java.util.List<ShopBusinessHoursDayVO> weeklyHoursVO(String start, String end) {
java.util.List<ShopBusinessHoursDayVO> result = new java.util.ArrayList<>();
for (int day = 1; day <= 7; day++) {
ShopBusinessHoursDayVO item = new ShopBusinessHoursDayVO();
item.setDayOfWeek(day);
item.setOpen(true);
item.setStartTime(start);
item.setEndTime(end);
result.add(item);
}
return result;
}
}
@@ -4,6 +4,7 @@ import com.xiaowang.jayucloud.salon.core.common.Result;
import com.xiaowang.jayucloud.salon.core.modules.auth.service.VerificationCodeService;
import com.xiaowang.jayucloud.salon.core.modules.file.service.ChunkUploadService;
import com.xiaowang.jayucloud.salon.core.modules.file.service.PrimaryObjectStorageService;
import com.xiaowang.jayucloud.salon.core.modules.file.service.ObjectStorageDirectUploadService;
import com.xiaowang.jayucloud.salon.core.modules.file.support.ObjectStorageUrlSupport;
import com.xiaowang.jayucloud.salon.core.modules.integration.service.WechatMiniAuthService;
import com.xiaowang.jayucloud.salon.core.modules.privacy.service.AccountClosureService;
@@ -39,7 +40,7 @@ class UserControllerPhonePrivacyTest {
profile.setShopBusinessRemainingDays(66);
when(userService.getCurrentUserInfo()).thenReturn(profile);
UserController controller = new UserController(userService,
mock(PrimaryObjectStorageService.class), mock(ChunkUploadService.class),
mock(PrimaryObjectStorageService.class), mock(ObjectStorageDirectUploadService.class), mock(ChunkUploadService.class),
mock(VerificationCodeService.class), mock(UserMapper.class), mock(AdminScopeHelper.class),
mock(ShopRoleService.class), mock(TimeOrderedSnowflakeIdGenerator.class),
mock(WechatMiniAuthService.class), mock(ObjectStorageUrlSupport.class),
@@ -70,7 +71,7 @@ class UserControllerPhonePrivacyTest {
AccountClosureService accountClosureService = mock(AccountClosureService.class);
SecurityAuditLogService securityAuditLogService = mock(SecurityAuditLogService.class);
UserController controller = new UserController(userService, primaryObjectStorageService,
chunkUploadService, verificationCodeService, userMapper, adminScopeHelper, shopRoleService,
mock(ObjectStorageDirectUploadService.class), chunkUploadService, verificationCodeService, userMapper, adminScopeHelper, shopRoleService,
idGenerator, wechatMiniAuthService, objectStorageUrlSupport, requestThrottleService,
legalAgreementService, accountClosureService, securityAuditLogService);
@@ -95,7 +96,7 @@ class UserControllerPhonePrivacyTest {
@Test
void rejectsPasswordCodeRequestWithoutAuthenticatedUser() {
UserController controller = new UserController(mock(UserService.class),
mock(PrimaryObjectStorageService.class), mock(ChunkUploadService.class),
mock(PrimaryObjectStorageService.class), mock(ObjectStorageDirectUploadService.class), mock(ChunkUploadService.class),
mock(VerificationCodeService.class), mock(UserMapper.class), mock(AdminScopeHelper.class),
mock(ShopRoleService.class), mock(TimeOrderedSnowflakeIdGenerator.class),
mock(WechatMiniAuthService.class), mock(ObjectStorageUrlSupport.class),
+1 -1
View File
@@ -65,7 +65,7 @@ App({
agreementVersions: preference.agreementVersions || {},
clientType: 'WECHAT_MINI'
})
this.publishWechatLoginState(result)
this.publishWechatLoginState({ ...result, autoLogin: true })
if (result.status === 'SUCCESS' && result.accessToken) {
this.setSession(result, true)
wx.reLaunch({ url: '/pages/planning/index' })
+8
View File
@@ -26,6 +26,14 @@
"pages/about/index"
],
"lazyCodeLoading": "requiredComponents",
"permission": {
"scope.userLocation": {
"desc": "用于地图选点填写门店地址"
}
},
"requiredPrivateInfos": [
"chooseLocation"
],
"window": {
"navigationBarTitleText": "甲屿手纪",
"navigationBarBackgroundColor": "#F3F7F4",
@@ -1,5 +1,4 @@
const userApi = require('../../api/user')
const authApi = require('../../api/auth')
const auth = require('../../utils/auth')
const profileCache = require('../../utils/profile-cache')
@@ -185,13 +184,5 @@ Page({
}
},
async logout() {
const confirmed = await new Promise(resolve => wx.showModal({ title: '退出登录', content: '退出后将关闭自动登录,并清除本机提醒设置。', success: result => resolve(result.confirm), fail: () => resolve(false) }))
if (!confirmed) return
try { await authApi.logout() } catch (error) {}
getApp().logoutDevice()
wx.reLaunch({ url: '/pages/login/index' })
},
onUnload() { if (this.data.timer) clearInterval(this.data.timer) }
})
@@ -30,5 +30,4 @@
<button wx:elif="{{!closureRequest || closureRequest.status === 'REJECTED'}}" class="closure-btn" bindtap="requestClosure">申请注销账号</button>
</block>
</view>
<button class="logout-btn" bindtap="logout">退出登录</button>
</view>
+24 -12
View File
@@ -254,8 +254,16 @@ function hasBusyConflict(startMinute, endMinute, ranges) {
return ranges.some(range => startMinute < range.endMinute && endMinute > range.startMinute)
}
function resolveBusinessHours(calendar) {
function resolveBusinessHours(calendar, targetDate) {
const source = calendar || {}
const day = targetDate && (source.daySummaries || []).find(item => item.date === targetDate)
if (day) {
if (day.shopOpen === false) return { start: '', end: '', closed: true }
const dayStart = String(day.shopStartTime || '').trim()
const dayEnd = String(day.shopEndTime || '').trim()
if (/^\d{1,2}:[0-5]\d$/.test(dayStart) && /^\d{1,2}:[0-5]\d$/.test(dayEnd)
&& dateUtil.minutesOfDay(dayEnd) > dateUtil.minutesOfDay(dayStart)) return { start: dayStart, end: dayEnd }
}
const parts = String(source.businessHours || '').split('-')
const start = String(source.businessStartTime || parts[0] || '').trim()
const end = String(source.businessEndTime || parts[1] || '').trim()
@@ -279,7 +287,7 @@ function buildAvailableTimeGroups(calendar, form, durationMinutes) {
const today = dateUtil.formatDate(new Date())
const now = new Date()
const currentMinute = now.getHours() * 60 + now.getMinutes()
const businessHours = resolveBusinessHours(calendar)
const businessHours = resolveBusinessHours(calendar, form.appointmentDate)
if (!businessHours.start) return []
const businessStart = dateUtil.minutesOfDay(businessHours.start)
const businessEnd = dateUtil.minutesOfDay(businessHours.end)
@@ -361,7 +369,7 @@ function buildTimeValues(durationMinutes, businessStart, businessEnd, appointmen
function buildTimePickerSlots(calendar, form, durationMinutes) {
const schedules = calendar.schedules || []
const busyRanges = form.artistId ? buildBusyRanges(calendar.appointments || [], form) : []
const businessHours = resolveBusinessHours(calendar)
const businessHours = resolveBusinessHours(calendar, form.appointmentDate)
if (!businessHours.start) return []
const businessStart = businessHours.start
const businessEnd = businessHours.end
@@ -783,7 +791,7 @@ Page({
endDate: this.data.form.appointmentDate || dateUtil.formatDate(new Date())
})
let artists = getCalendarArtists(calendar)
const businessHours = resolveBusinessHours(calendar)
const businessHours = resolveBusinessHours(calendar, this.data.form.appointmentDate)
const defaultDuration = Number(calendar.defaultAppointmentDurationMinutes) || 60
const requestedId = preferredArtistId || this.data.form.artistId
if (fallbackEmployee && requestedId && !findArtist(artists, requestedId).id) {
@@ -1551,10 +1559,12 @@ Page({
try {
const calendar = await planningApi.calendar({ startDate: form.appointmentDate, endDate: form.appointmentDate })
if (requestSeq !== this._availableTimeRequestSeq) return
const businessHours = resolveBusinessHours(calendar)
const businessHours = resolveBusinessHours(calendar, form.appointmentDate)
const businessStartTime = businessHours.start
const businessEndTime = businessHours.end
if (!businessStartTime) {
const closed = businessHours.closed === true
const message = closed ? '预约日期门店休息,不能新建普通预约' : '门店营业时间尚未设置,请先完成设置'
this.setData({
businessStartTime: '',
businessEndTime: '',
@@ -1565,10 +1575,10 @@ Page({
timePickerMinutes: [],
selectedTimeCandidate: '',
'form.appointmentTime': '',
timeError: '门店营业时间尚未设置,请先完成设置',
businessHoursMissing: true,
timeError: message,
businessHoursMissing: !closed,
timeLoading: false,
timeSelectTip: '请先设置门店营业时间'
timeSelectTip: closed ? '门店休息日不可预约' : '请先设置门店营业时间'
})
return
}
@@ -1621,8 +1631,10 @@ Page({
if (requestSeq !== this._availableTimeRequestSeq) {
return
}
const businessHours = resolveBusinessHours(calendar)
const businessHours = resolveBusinessHours(calendar, form.appointmentDate)
if (!businessHours.start) {
const closed = businessHours.closed === true
const message = closed ? '预约日期门店休息,不能新建普通预约' : '门店营业时间尚未设置,请先完成设置'
this.setData({
businessStartTime: '',
businessEndTime: '',
@@ -1633,10 +1645,10 @@ Page({
timePickerMinutes: [],
selectedTimeCandidate: '',
'form.appointmentTime': '',
timeError: '门店营业时间尚未设置,请先完成设置',
businessHoursMissing: true,
timeError: message,
businessHoursMissing: !closed,
timeLoading: false,
timeSelectTip: '请先设置门店营业时间'
timeSelectTip: closed ? '门店休息日不可预约' : '请先设置门店营业时间'
})
return
}
+2 -2
View File
@@ -165,7 +165,7 @@ Page({
},
async handleResult(result) {
if (result.status === 'SUCCESS' && result.accessToken) return this.finishLogin(result)
if (result.status === 'SUCCESS' && result.accessToken) return this.finishLogin(result, result.autoLogin !== true)
if (result.status === 'REJECTED' && this._resumeRegistrationAfterRejected && result.registrationTicket) {
this._resumeRegistrationAfterRejected = false
this.navigateToRegistration(result)
@@ -230,7 +230,7 @@ Page({
...this.agreementPayload()
})
if (result.status !== 'SUCCESS' || !result.accessToken) throw new Error(result.message || '进入门店失败')
this.finishLogin(result)
await this.finishLogin(result, true)
} catch (error) {
wx.showToast({ title: error.message || '进入门店失败', icon: 'none' })
} finally {
+45 -1
View File
@@ -9,6 +9,10 @@ let modalOptions
let navigatedTo
let modalChoice = { confirm: false, cancel: true }
let modalCount = 0
const loginEvents = []
let subscriptionResult = 'accept'
global.getApp = () => ({ setSession: () => loginEvents.push('session') })
global.Page = value => { definition = value }
global.wx = {
@@ -25,9 +29,19 @@ global.wx = {
},
navigateTo(options) {
navigatedTo = options.url
}
},
requestSubscribeMessage(options) {
loginEvents.push('subscribe')
if (subscriptionResult === 'error') options.fail(new Error('user deny'))
else options.success({})
},
reLaunch() { loginEvents.push('reLaunch') },
getStorageSync: () => ({}),
setStorageSync: () => {},
removeStorageSync: () => {}
}
const authApi = require('../../api/auth')
require('./index')
function createPage() {
@@ -92,6 +106,36 @@ async function run() {
assert.match(template, /data-type="USER_TERMS" catchtap="openAgreement"/)
assert.match(template, /data-type="PRIVACY_POLICY" catchtap="openAgreement"/)
assert.doesNotMatch(template, /class="state-line"/)
loginEvents.length = 0
const manualLogin = createPage()
await manualLogin.handleResult({ status: 'SUCCESS', accessToken: 'manual-token' })
assert.deepStrictEqual(loginEvents, ['session', 'subscribe', 'reLaunch'])
loginEvents.length = 0
const automaticLogin = createPage()
await automaticLogin.handleResult({ status: 'SUCCESS', accessToken: 'automatic-token', autoLogin: true })
assert.deepStrictEqual(loginEvents, ['session', 'reLaunch'])
loginEvents.length = 0
const shopLogin = createPage()
shopLogin.data.loginTicket = 'shop-ticket'
authApi.wechatConfirmLogin = async () => ({ status: 'SUCCESS', accessToken: 'shop-token' })
await shopLogin.selectShop({ currentTarget: { dataset: { id: 21 } } })
assert.deepStrictEqual(loginEvents, ['session', 'subscribe', 'reLaunch'])
loginEvents.length = 0
subscriptionResult = 'error'
const deniedSubscription = createPage()
await deniedSubscription.handleResult({ status: 'SUCCESS', accessToken: 'manual-token' })
assert.deepStrictEqual(loginEvents, ['session', 'subscribe', 'reLaunch'])
subscriptionResult = 'accept'
loginEvents.length = 0
const failedLogin = createPage()
failedLogin.quickLogin = () => loginEvents.push('retry')
await failedLogin.handleResult({ status: 'ERROR', message: '登录失败' })
assert.strictEqual(loginEvents.includes('subscribe'), false)
}
run().catch(error => {
+70 -23
View File
@@ -47,22 +47,38 @@ 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')}`
function 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')}`
}
function resolveBusinessHours(calendar = {}, targetDate) {
const day = targetDate && (calendar.daySummaries || []).find(item => item.date === targetDate)
if (day) {
if (day.shopOpen === false) return null
const dayStart = normalizeTime(day.shopStartTime)
const dayEnd = normalizeTime(day.shopEndTime)
if (dayStart && dayEnd && dateUtil.minutesOfDay(dayEnd) > dateUtil.minutesOfDay(dayStart)) return { start: dayStart, end: dayEnd }
}
const parts = String(calendar.businessHours || '').split('-')
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 hasBusinessHours(calendar = {}) {
const summaries = Array.isArray(calendar.daySummaries) ? calendar.daySummaries : []
if (summaries.length) {
return summaries.some(day => day.shopOpen !== false && Boolean(resolveBusinessHours(calendar, day.date)))
}
return Boolean(resolveBusinessHours(calendar))
}
function layoutAppointmentBlocks(items, startMinute, minuteScale, laneHeaderHeight, defaultLaneWidth) {
const entries = (items || [])
.filter(item => item.startTime)
@@ -168,7 +184,7 @@ Page({
phoneBannerVisible: false,
profilePromptVisible: false,
profileSaving: false,
profileForm: { nickname: '', avatar: '' }
profileForm: { nickname: '', avatar: '', avatarFileId: '' }
},
onLoad() {
@@ -211,7 +227,7 @@ Page({
this.setData({
phoneBannerVisible: Number(profile.phoneVerified) !== 1 && dismissed !== today,
profilePromptVisible: false,
profileForm: { nickname: missingNickname ? '' : profile.nickname, avatar }
profileForm: { nickname: missingNickname ? '' : profile.nickname, avatar, avatarFileId: '' }
})
} catch (error) {
// 资料提醒失败不影响日程数据。
@@ -264,8 +280,11 @@ Page({
if (!filePath) return
this.setData({ profileSaving: true })
try {
const avatar = await uploadProfileImage(filePath)
this.setData({ 'profileForm.avatar': avatar })
const uploaded = await uploadProfileImage(filePath)
this.setData({
'profileForm.avatar': filePath,
'profileForm.avatarFileId': uploaded && uploaded.fileId ? String(uploaded.fileId) : ''
})
} catch (error) {
wx.showToast({ title: error.message || '头像上传失败', icon: 'none' })
} finally {
@@ -285,12 +304,15 @@ Page({
}
this.setData({ profileSaving: true })
try {
await userApi.updateInfo({ nickname, avatar: this.data.profileForm.avatar })
await userApi.updateInfo({
nickname,
avatarFileId: this.data.profileForm.avatarFileId || undefined
})
profileCache.invalidate()
this.setData({ profilePromptVisible: false })
wx.showToast({ title: '资料已保存' })
wx.showToast({ title: '资料已保存', duration: 3000 })
} catch (error) {
wx.showToast({ title: error.message || '资料保存失败', icon: 'none' })
wx.showToast({ title: error.message || '资料保存失败', icon: 'none', duration: 3000 })
} finally {
this.setData({ profileSaving: false })
}
@@ -457,7 +479,7 @@ Page({
const snapshot = {
businessStartTime: businessHours ? businessHours.start : '',
businessEndTime: businessHours ? businessHours.end : '',
businessHoursConfigured: Boolean(businessHours),
businessHoursConfigured: hasBusinessHours(calendar),
artists: Array.isArray(calendar.artists) ? calendar.artists : [],
appointments: Array.isArray(calendar.appointments) ? calendar.appointments : [],
daySummaries: Array.isArray(calendar.daySummaries) ? calendar.daySummaries : []
@@ -467,9 +489,6 @@ Page({
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,
@@ -494,12 +513,20 @@ Page({
dateTitle: title,
rangeText: this.data.viewMode === 'month' ? '月视图' : this.data.viewMode === 'week' ? '周视图' : '日视图',
weekRange: `${formatMonthDay(range.start)} - ${formatMonthDay(range.end)}`,
businessHoursConfigured: Boolean(resolveBusinessHours(calendar)),
businessHoursConfigured: hasBusinessHours(calendar),
currentShopOpen: true,
businessHoursText: '营业时间暂不可用',
monthDays: [],
weekDays: [],
dayLanes: [],
hours: []
}
const daySummary = this.summaryMap(calendar)[current]
const dailyHours = resolveBusinessHours(calendar, current)
state.currentShopOpen = !daySummary || daySummary.shopOpen !== false
state.businessHoursText = !state.currentShopOpen
? '门店休息'
: dailyHours ? `${dailyHours.start}-${dailyHours.end}` : '营业时间暂不可用'
if (this.data.viewMode === 'month') {
state.monthDays = this.buildMonthDays(calendar)
return state
@@ -534,7 +561,7 @@ Page({
isPast: day.date < todayText,
totalCount: summary.totalCount || 0,
unassignedCount,
dayStatus: summary.dayStatus || 'free',
dayStatus: this.resolveDisplayStatus(summary, artistCounts),
artistCounts,
expandedBlocks: this.data.monthDisplayMode === 'blocks' ? this.buildExpandedBlocks(artistCounts) : [],
rowBlocks: this.data.monthDisplayMode === 'rows' ? this.buildRowBlocks(artistCounts) : []
@@ -560,6 +587,10 @@ Page({
day: target.getDate(),
totalCount: summary.totalCount || 0,
unassignedCount,
shopOpen: summary.shopOpen !== false,
statusText: this.resolveDisplayStatus(summary, artistCounts) === 'rest'
? '休'
: this.resolveDisplayStatus(summary, artistCounts) === 'full' ? '满' : '营业',
artistCounts: artistCounts.map(count => ({
...count,
width: Math.max(12, Math.min(100, count.count * 22)),
@@ -571,7 +602,8 @@ Page({
buildDayView(calendar) {
const minuteScale = 4
const businessHours = resolveBusinessHours(calendar)
const daySummary = this.summaryMap(calendar)[this.data.currentDateText] || null
const businessHours = resolveBusinessHours(calendar, this.data.currentDateText)
const filteredArtists = this.data.selectedArtistId
? (calendar.artists || []).filter(item => String(item.id) === String(this.data.selectedArtistId))
: (calendar.artists || [])
@@ -597,6 +629,7 @@ Page({
freeArtistCount: 0,
pendingCount,
unassignedCount: dayAppointments.filter(item => !item.artistId).length,
shopClosed: Boolean(daySummary && daySummary.shopOpen === false),
historicalBackfillItems
}
}
@@ -670,10 +703,20 @@ Page({
freeArtistCount: employeeLanes.filter(item => item.blocks.every(block => block.historicalBackfill)).length,
pendingCount,
unassignedCount: unassignedBlocks.length,
shopClosed: Boolean(daySummary && daySummary.shopOpen === false),
historicalBackfillItems
}
},
resolveDisplayStatus(summary = {}, artistCounts = []) {
if (summary.shopOpen === false || summary.dayStatus === 'rest') return 'rest'
if (this.data.selectedArtistId) {
const selected = artistCounts.find(item => String(item.artistId) === String(this.data.selectedArtistId))
return selected ? selected.status : 'rest'
}
return summary.dayStatus === 'full' ? 'full' : 'working'
},
withUnassignedCount(artistCounts, unassignedCount) {
if (!unassignedCount) return artistCounts
return [{
@@ -771,6 +814,10 @@ Page({
wx.showToast({ title: '请先在店铺设置中配置营业时间', icon: 'none' })
return
}
if (this.data.viewMode === 'day' && this.data.currentShopOpen === false) {
wx.showToast({ title: '该日期门店休息,不能新建普通预约', icon: 'none' })
return
}
this.openAppointmentForm(this.data.viewMode === 'day' ? this.data.currentDateText : '')
},
+46 -2
View File
@@ -68,6 +68,34 @@ async function run() {
page.buildViewState({ artists: [], appointments: [], daySummaries: [] })
assert.deepStrictEqual([monthBuilds, weekBuilds, dayBuilds], [0, 1, 0])
const closedWeekPage = createPage({ viewMode: 'week', currentDateText: '2026-10-12' })
const closedWeek = Array.from({ length: 7 }, (_, index) => ({
date: dateUtil.formatDate(dateUtil.addDays(dateUtil.startOfWeek(closedWeekPage.data.currentDateText), index)),
shopOpen: false,
shopStartTime: null,
shopEndTime: null
}))
const closedWeekState = closedWeekPage.buildViewState({
businessStartTime: '10:00',
businessEndTime: '22:00',
artists: [],
appointments: [],
daySummaries: closedWeek
})
assert.strictEqual(closedWeekState.businessHoursConfigured, false)
assert.strictEqual(closedWeekState.weekDays.every(day => day.statusText === '休'), true)
const openWeekState = closedWeekPage.buildViewState({
businessStartTime: '10:00',
businessEndTime: '22:00',
artists: [],
appointments: [],
daySummaries: closedWeek.map((day, index) => index === 2
? { ...day, shopOpen: true, shopStartTime: '10:00', shopEndTime: '22:00' }
: day)
})
assert.strictEqual(openWeekState.businessHoursConfigured, true)
page.data.viewMode = 'month'
page.data.monthDisplayMode = 'count'
const monthDays = definition.buildMonthDays.call(page, {
@@ -117,6 +145,16 @@ async function run() {
assert.strictEqual(missingHoursEmptyState.hours.length, 0)
assert.strictEqual(missingHoursEmptyState.dayLanes.length, 0)
assert.strictEqual(missingHoursEmptyState.hasTimedAppointments, false)
const closedDaySummaryPage = createPage({ currentDateText: '2026-10-12' })
const closedDayState = closedDaySummaryPage.buildViewState({
businessStartTime: '10:00',
businessEndTime: '22:00',
artists: [],
appointments: [],
daySummaries: [{ date: '2026-10-12', shopOpen: false, shopStartTime: null, shopEndTime: null }]
})
assert.strictEqual(closedDayState.businessHoursConfigured, false)
assert.strictEqual(closedDayState.currentShopOpen, false)
missingHoursPage.clearCalendarView()
assert.strictEqual(missingHoursPage.data.businessHoursText, '营业时间暂不可用')
const missingHoursWithBookingState = missingHoursPage.buildDayView({
@@ -156,7 +194,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="week-unassigned-count">待 \{\{item\.unassignedCount\}\}/)
assert.match(planningWxml, /wx:if="\{\{canCreateAppointment && businessHoursConfigured && !calendarError && \(viewMode !== 'day' \|\| currentShopOpen\)\}\}" class="fab" bindtap="createAppointment"/)
assert.match(planningWxml, /class="month-unassigned-count">待 \{\{item\.unassignedCount\}\}/)
assert.doesNotMatch(planningWxss, /background-size:\s*100% 240rpx/)
assert.match(planningWxss, /\.control-card\s*\{[^}]*padding:\s*8rpx 14rpx;/)
@@ -239,9 +278,14 @@ async function run() {
assert.strictEqual(navigations.pop(), '/pages/shop-settings/index')
assert.strictEqual(unconfiguredPage._refreshCalendarOnShow, true)
const closedDayAppointmentPage = createPage({ viewMode: 'day', canCreateAppointment: true, businessHoursConfigured: true, currentShopOpen: false })
closedDayAppointmentPage.createAppointment()
assert.strictEqual(navigations.length, 0)
assert.strictEqual(toasts.pop(), '该日期门店休息,不能新建普通预约')
assert.match(planningWxml, /bindtap="selectMonthDate" aria-label="查看\{\{item\.date\}\}日程"/)
assert.match(planningWxml, /bindtap="selectWeekDate" aria-label="查看\{\{item\.date\}\}日程"/)
assert.match(planningWxml, /class="fab" bindtap="createAppointment"/)
assert.match(planningWxss, /grid-template-columns:\s*repeat\(7,\s*minmax\(0,\s*1fr\)\)/)
}
run().catch(error => {
+9 -19
View File
@@ -88,7 +88,11 @@
</view>
</view>
<view wx:if="{{!businessHoursConfigured && !hasTimedAppointments}}" class="day-board card business-hours-empty">
<view wx:if="{{shopClosed && !hasTimedAppointments}}" class="day-board card business-hours-empty">
<text class="business-hours-empty-title">门店今日休息</text>
<text class="business-hours-empty-desc">休息日不能创建普通预约,可通过历史补录记录已完成的服务。</text>
</view>
<view wx:elif="{{!businessHoursConfigured && !hasTimedAppointments}}" class="day-board card business-hours-empty">
<text class="business-hours-empty-title">预约时间轴暂不可用</text>
<text class="business-hours-empty-desc">请先设置门店营业时间,再安排普通预约。</text>
</view>
@@ -128,30 +132,16 @@
</view>
<view wx:if="{{viewMode === 'week'}}" class="section">
<scroll-view class="week-strip" scroll-x enable-flex>
<view class="week-strip">
<view wx:for="{{weekDays}}" wx:key="date" class="week-day-card card {{item.date === currentDateText ? 'active' : ''}}" data-date="{{item.date}}" bindtap="selectWeekDate" aria-label="查看{{item.date}}日程">
<text class="week-name">{{item.weekName}}</text>
<view class="week-card-head"><text class="week-name">{{item.weekName}}</text><text class="week-status {{item.statusText === '休' ? 'rest' : ''}}">{{item.statusText}}</text></view>
<text class="week-date">{{item.day}}</text>
<text class="week-total">{{item.totalCount}}单</text>
<text wx:if="{{item.unassignedCount > 0}}" class="week-unassigned-count">待分配 {{item.unassignedCount}}</text>
<text wx:if="{{item.unassignedCount > 0}}" class="week-unassigned-count">待 {{item.unassignedCount}}</text>
<view class="week-bars {{item.totalCount === 0 ? 'empty' : ''}}">
<view wx:for="{{item.artistCounts}}" wx:for-item="count" wx:key="artistId" class="week-bar" style="background: {{count.color}}; width: {{count.width}}%;"></view>
</view>
</view>
</scroll-view>
<view class="card week-grid">
<view class="week-grid-head">
<text>本周排班密度</text>
<text class="muted">{{weekRange}}</text>
</view>
<view wx:for="{{weekDays}}" wx:key="date" class="week-line">
<view class="week-line-date">{{item.weekName}} {{item.day}}</view>
<view class="week-line-bars {{item.totalCount === 0 ? 'empty' : ''}}">
<view wx:for="{{item.artistCounts}}" wx:for-item="count" wx:key="artistId" class="week-count-bar" style="background: {{count.color}}; width: {{count.barWidth}}%;">
<text>{{count.shortName}}{{count.count}}</text>
</view>
</view>
</view>
</view>
</view>
@@ -206,5 +196,5 @@
</view>
</block>
<button wx:if="{{canCreateAppointment && businessHoursConfigured && !calendarError}}" class="fab" bindtap="createAppointment">+</button>
<button wx:if="{{canCreateAppointment && businessHoursConfigured && !calendarError && (viewMode !== 'day' || currentShopOpen)}}" class="fab" bindtap="createAppointment">+</button>
</view>
+25 -17
View File
@@ -556,17 +556,20 @@
}
.week-strip {
display: grid;
grid-template-columns: repeat(7, minmax(0, 1fr));
gap: 6rpx;
width: 100%;
white-space: nowrap;
}
.week-day-card {
display: inline-flex;
display: flex;
flex-direction: column;
width: 148rpx;
min-height: 164rpx;
margin-right: 12rpx;
padding: 16rpx;
min-width: 0;
min-height: 104rpx;
margin: 0;
padding: 8rpx 4rpx;
align-items: center;
}
.week-day-card.active {
@@ -576,42 +579,47 @@
.week-name,
.week-total {
color: #8f877e;
font-size: 22rpx;
font-size: 18rpx;
}
.week-card-head { display:flex; width:100%; align-items:center; justify-content:space-between; gap:2rpx; }
.week-status { color:#247b63; font-size:17rpx; font-weight:800; }
.week-status.rest { color:#a08a78; }
.week-unassigned-count {
display: inline-flex;
align-self: flex-start;
margin-top: 8rpx;
padding: 4rpx 8rpx;
margin-top: 4rpx;
padding: 2rpx 4rpx;
border-radius: 6rpx;
background: #fff1dc;
color: #a56b24;
font-size: 18rpx;
font-size: 15rpx;
font-weight: 800;
}
.week-date {
margin: 8rpx 0;
margin: 3rpx 0;
color: #17211f;
font-size: 38rpx;
font-size: 24rpx;
font-weight: 800;
}
.week-bars {
display: flex;
flex-direction: column;
gap: 6rpx;
margin-top: 12rpx;
min-height: 22rpx;
gap: 3rpx;
width: 90%;
margin-top: 3rpx;
min-height: 10rpx;
}
.week-bars.empty {
min-height: 22rpx;
min-height: 10rpx;
}
.week-bar {
height: 8rpx;
height: 5rpx;
border-radius: 999rpx;
}
+25 -9
View File
@@ -25,6 +25,8 @@ function buildPageState(profile, fallbackShopName) {
form: {
nickname: source.nickname || '',
avatar: normalizeAvatar(source.avatar),
avatarFileId: '',
avatarChanged: false,
wechatId: source.wechatId || '',
signature: source.signature || ''
}
@@ -41,7 +43,7 @@ Page({
roleText: '管理端',
shopName: BRAND_CONFIG.defaultShopName,
phoneDisplay: '未绑定',
form: { nickname: '', avatar: '', wechatId: '', signature: '' }
form: { nickname: '', avatar: '', avatarFileId: '', avatarChanged: false, wechatId: '', signature: '' }
},
onLoad() {
@@ -116,12 +118,21 @@ Page({
async uploadAvatar(filePath) {
if (!filePath) return
const previousAvatar = this.data.form.avatar
const previousAvatarFileId = this.data.form.avatarFileId
this.setData({ avatarUploading: true, 'form.avatar': filePath })
try {
const avatar = await uploadProfileImage(filePath)
this.setData({ 'form.avatar': avatar })
const uploaded = await uploadProfileImage(filePath)
this.setData({
'form.avatar': filePath,
'form.avatarFileId': uploaded && uploaded.fileId ? String(uploaded.fileId) : '',
'form.avatarChanged': true
})
} catch (error) {
this.setData({ 'form.avatar': previousAvatar })
this.setData({
'form.avatar': previousAvatar,
'form.avatarFileId': previousAvatarFileId,
'form.avatarChanged': false
})
throw error
} finally {
this.setData({ avatarUploading: false })
@@ -160,21 +171,26 @@ Page({
wx.showToast({ title: '请填写昵称', icon: 'none' })
return
}
if (form.avatarChanged && !form.avatarFileId) {
wx.showToast({ title: '头像上传未完成,请重新选择', icon: 'none', duration: 3000 })
return
}
this.setData({ saving: true })
try {
await userApi.updateInfo({
const payload = {
nickname,
avatar: form.avatar || '',
wechatId: String(form.wechatId || '').trim(),
signature: String(form.signature || '').trim()
})
}
if (form.avatarChanged) payload.avatarFileId = form.avatarFileId || undefined
await userApi.updateInfo(payload)
profileCache.invalidate()
const profile = await profileCache.getProfile({ force: true })
this.syncProfileToSession(profile)
wx.showToast({ title: '已保存', icon: 'success' })
wx.showToast({ title: '已保存', icon: 'success', duration: 3000 })
setTimeout(() => wx.navigateBack(), 350)
} catch (error) {
wx.showToast({ title: error.message || '保存失败', icon: 'none' })
wx.showToast({ title: error.message || '保存失败', icon: 'none', duration: 3000 })
} finally {
this.setData({ saving: false })
}
@@ -0,0 +1,55 @@
const assert = require('assert')
let definition
let toast
let savedPayload
global.Page = value => { definition = value }
global.wx = {
showToast: options => { toast = options },
navigateBack: () => {}
}
global.getApp = () => ({ globalData: { userInfo: { id: 7 } }, setSession: () => {} })
global.setTimeout = callback => { callback(); return 1 }
const auth = require('../../utils/auth')
auth.getSession = () => ({ userInfo: { id: 7 } })
const profileCache = require('../../utils/profile-cache')
profileCache.invalidate = () => {}
profileCache.getProfile = async () => ({ id: 7, nickname: '员工', avatar: 'profile/7/avatar.png' })
const userApi = require('../../api/user')
userApi.updateInfo = async payload => { savedPayload = payload }
require('./index')
function createPage(form) {
return {
...definition,
data: { ...definition.data, form: { ...definition.data.form, ...form } },
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 }
})
}
}
}
async function run() {
const missingFilePage = createPage({ nickname: '員工', avatarChanged: true, avatarFileId: '' })
await missingFilePage.save()
assert.strictEqual(toast.title, '头像上传未完成,请重新选择')
assert.strictEqual(toast.duration, 3000)
assert.strictEqual(savedPayload, undefined)
const validPage = createPage({ nickname: '员工', avatarChanged: true, avatarFileId: '90071992547409931' })
await validPage.save()
assert.strictEqual(savedPayload.avatarFileId, '90071992547409931')
assert.strictEqual(toast.title, '已保存')
assert.strictEqual(toast.duration, 3000)
}
run().catch(error => {
console.error(error)
process.exitCode = 1
})
+14
View File
@@ -3,6 +3,7 @@ const auth = require('../../utils/auth')
const planningApi = require('../../api/planning')
const { buildProfileCard } = require('../../utils/profile-card')
const profileCache = require('../../utils/profile-cache')
const authApi = require('../../api/auth')
function resolveRoleText(type) {
const role = Number(type)
@@ -90,6 +91,19 @@ Page({
wx.navigateTo({ url: event.currentTarget.dataset.url })
},
async logout() {
const confirmed = await new Promise(resolve => wx.showModal({
title: '退出登录',
content: '退出后将关闭自动登录,并清除本机提醒设置。',
success: result => resolve(result.confirm),
fail: () => resolve(false)
}))
if (!confirmed) return
try { await authApi.logout() } catch (error) {}
getApp().logoutDevice()
wx.reLaunch({ url: '/pages/login/index' })
},
onProfileAvatarError() {
this.setData({ 'profileCard.avatar': '' })
},
+1
View File
@@ -54,5 +54,6 @@
<text class="arrow">›</text>
</view>
</view>
<button class="profile-logout" bindtap="logout">退出登录</button>
</view>
+1
View File
@@ -177,3 +177,4 @@
color: #b0a79e;
font-size: 44rpx;
}
.profile-logout { margin:48rpx 8rpx 24rpx; background:transparent; color:#a24f42; font-size:25rpx; }
+29 -2
View File
@@ -4,7 +4,7 @@ Page({
data: {
step: 1,
role: 'manager',
form: { shopName: '', shopAddress: '', shopId: '', applicantNickname: '', applicantAvatarFileId: '', applicantAvatarUrl: '' },
form: { shopName: '', shopAddress: '', shopId: '', shopLongitude: '', shopLatitude: '', applicantNickname: '', applicantAvatarFileId: '', applicantAvatarUrl: '' },
registrationTicket: '',
applicationId: '',
shopOptions: [],
@@ -53,7 +53,32 @@ Page({
}
},
onInput(event) { this.setData({ [`form.${event.currentTarget.dataset.field}`]: event.detail.value }) },
onInput(event) {
const field = event.currentTarget.dataset.field
const value = event.detail.value
const next = { [`form.${field}`]: value }
if (field === 'shopAddress') {
next['form.shopLongitude'] = ''
next['form.shopLatitude'] = ''
}
this.setData(next)
},
chooseShopLocation() {
wx.chooseLocation({
success: result => {
if (!result || (!result.address && !result.name)) return
this.setData({
'form.shopAddress': result.address || result.name || '',
'form.shopLongitude': result.longitude || '',
'form.shopLatitude': result.latitude || ''
})
},
fail: error => {
if (!String(error && error.errMsg || '').includes('cancel')) wx.showToast({ title: '地图选点失败,可继续手动填写地址', icon: 'none' })
}
})
},
async chooseApplicantAvatar(event) {
try {
@@ -141,6 +166,8 @@ Page({
applicationId: this.data.applicationId || undefined,
shopName: String(form.shopName || '').trim(),
shopAddress: String(form.shopAddress || '').trim(),
shopLongitude: form.shopLongitude ? Number(form.shopLongitude) : undefined,
shopLatitude: form.shopLatitude ? Number(form.shopLatitude) : undefined,
shopId: form.shopId || undefined,
roleType: this.data.role === 'manager' ? 'MANAGER' : 'STAFF',
applicantNickname: this.data.role === 'staff' ? String(form.applicantNickname || '').trim() || undefined : undefined,
+33 -1
View File
@@ -4,7 +4,11 @@ const authApi = require('../../api/auth')
let definition
let toast
global.Page = value => { definition = value }
global.wx = { showToast: options => { toast = options.title } }
let chooseLocationOptions
global.wx = {
showToast: options => { toast = options.title },
chooseLocation(options) { chooseLocationOptions = options }
}
require('./index')
function createPage() {
@@ -23,6 +27,17 @@ function createPage() {
}
async function run() {
const locationPage = createPage()
locationPage.chooseShopLocation()
chooseLocationOptions.success({ address: '杭州市西湖区某路', longitude: 120.12, latitude: 30.28 })
assert.strictEqual(locationPage.data.form.shopAddress, '杭州市西湖区某路')
assert.strictEqual(locationPage.data.form.shopLongitude, 120.12)
assert.strictEqual(locationPage.data.form.shopLatitude, 30.28)
locationPage.onInput({ currentTarget: { dataset: { field: 'shopAddress' } }, detail: { value: '手动修正地址' } })
assert.strictEqual(locationPage.data.form.shopAddress, '手动修正地址')
assert.strictEqual(locationPage.data.form.shopLongitude, '')
assert.strictEqual(locationPage.data.form.shopLatitude, '')
const page = createPage()
page.data.registrationTicket = 'valid-ticket'
page.data.role = 'staff'
@@ -40,6 +55,23 @@ async function run() {
assert.strictEqual(page.data.contentStatusReason, '图片审核仍在处理')
assert.strictEqual(page.data.step, 3)
const managerPage = createPage()
managerPage.data.registrationTicket = 'manager-ticket'
managerPage.data.role = 'manager'
managerPage.data.form.shopName = '店铺'
managerPage.data.form.shopAddress = '已选地址'
managerPage.data.form.shopLongitude = 120.12
managerPage.data.form.shopLatitude = 30.28
let registrationPayload
authApi.register = async payload => { registrationPayload = payload; return { status: 'PENDING_ADMIN' } }
await managerPage.submit()
assert.strictEqual(registrationPayload.shopLongitude, 120.12)
assert.strictEqual(registrationPayload.shopLatitude, 30.28)
const appConfig = require('../../app.json')
assert.deepStrictEqual(appConfig.requiredPrivateInfos, ['chooseLocation'])
assert.ok(appConfig.permission['scope.userLocation'].desc)
const expired = createPage()
expired.data.registrationTicket = 'spent-ticket'
expired.data.role = 'staff'
+1 -1
View File
@@ -3,7 +3,7 @@
<view class="progress-row"><view class="progress-step {{step >= 1 ? 'active' : ''}}"><text>1</text><label>选择身份</label></view><view class="progress-line {{step >= 2 ? 'active' : ''}}"></view><view class="progress-step {{step >= 2 ? 'active' : ''}}"><text>2</text><label>门店资料</label></view><view class="progress-line {{step >= 3 ? 'active' : ''}}"></view><view class="progress-step {{step >= 3 ? 'active' : ''}}"><text>3</text><label>申请状态</label></view></view>
<view wx:if="{{ticketInvalid}}" class="card result-card"><view class="result-icon">!</view><view class="section-title">申请入口已失效</view><view class="section-desc">这次注册凭证已过期或已使用,请返回登录页重新点击微信快捷登录获取新凭证。</view><button class="primary-btn" bindtap="back">重新快捷登录</button></view>
<view wx:elif="{{step === 1}}" class="card form-card"><view class="section-title">选择工作身份</view><view class="section-desc">无需手机号和密码,审核人会根据你的身份处理申请</view><view class="role-list"><view class="role-option {{role === 'manager' ? 'selected' : ''}}" data-role="manager" bindtap="selectRole"><view class="role-icon">店</view><view class="role-copy"><text class="role-title">店长</text><text class="role-desc">创建并负责一家 Salon 门店</text></view><text class="role-mark">{{role === 'manager' ? '✓' : '○'}}</text></view><view class="role-option {{role === 'staff' ? 'selected' : ''}}" data-role="staff" bindtap="selectRole"><view class="role-icon">员</view><view class="role-copy"><text class="role-title">店员</text><text class="role-desc">加入已有门店协同工作</text></view><text class="role-mark">{{role === 'staff' ? '✓' : '○'}}</text></view></view><button class="primary-btn" bindtap="continueFromRole">继续</button></view>
<view wx:elif="{{step === 2}}" class="card form-card"><view class="section-title">{{role === 'manager' ? '完善店铺资料' : '选择要加入的店铺'}}</view><view class="section-desc">{{role === 'manager' ? '提交后由平台管理员审核' : '提交后由对应店长审核,昵称和头像均为可选资料'}}</view><view wx:if="{{role === 'manager'}}" class="field"><text class="field-label">店铺名称</text><input value="{{form.shopName}}" data-field="shopName" bindinput="onInput" placeholder="请输入店铺名称" /></view><view wx:if="{{role === 'manager'}}" class="field"><text class="field-label">店铺地址</text><input value="{{form.shopAddress}}" data-field="shopAddress" bindinput="onInput" placeholder="请输入门店地址" /></view><view wx:if="{{role === 'staff'}}" class="field"><text class="field-label">选择店铺</text><view class="picker-value {{selectedShopName ? 'filled' : ''}}" bindtap="openShopSheet"><text>{{selectedShopName || '请选择要加入的店铺'}}</text><text class="picker-arrow">›</text></view></view><view wx:if="{{role === 'staff'}}" class="field"><text class="field-label">申请昵称(选填)</text><input type="nickname" value="{{form.applicantNickname}}" data-field="applicantNickname" bindinput="onInput" placeholder="可填写希望展示的昵称" /></view><view wx:if="{{role === 'staff'}}" class="field avatar-pick-field"><text class="field-label">申请头像(选填)</text><button class="avatar-pick" open-type="chooseAvatar" bindchooseavatar="chooseApplicantAvatar"><image src="{{form.applicantAvatarUrl || '/assets/images/default-user-avatar.png'}}" mode="aspectFill"></image><text>{{avatarUploading ? '上传中...' : '主动选择头像'}}</text></button></view><view wx:if="{{role === 'staff'}}" class="notice">审核通过前不会获得门店业务权限</view><button class="primary-btn" loading="{{loading}}" disabled="{{avatarUploading}}" bindtap="submit">提交审核</button><view class="back-entry" bindtap="goBackStep">返回上一步</view></view>
<view wx:elif="{{step === 2}}" class="card form-card"><view class="section-title">{{role === 'manager' ? '完善店铺资料' : '选择要加入的店铺'}}</view><view class="section-desc">{{role === 'manager' ? '提交后由平台管理员审核' : '提交后由对应店长审核,昵称和头像均为可选资料'}}</view><view wx:if="{{role === 'manager'}}" class="field"><text class="field-label">店铺名称</text><input value="{{form.shopName}}" data-field="shopName" bindinput="onInput" placeholder="请输入店铺名称" /></view><view wx:if="{{role === 'manager'}}" class="field"><text class="field-label">店铺地址</text><view class="address-entry"><input value="{{form.shopAddress}}" data-field="shopAddress" bindinput="onInput" placeholder="可手动填写门店地址" /><button class="map-pick-btn" bindtap="chooseShopLocation">地图选点</button></view><text class="field-hint">地图选点为可选项,仅用于门店展示和预约导航,不会在后台静默获取位置。</text></view><view wx:if="{{role === 'staff'}}" class="field"><text class="field-label">选择店铺</text><view class="picker-value {{selectedShopName ? 'filled' : ''}}" bindtap="openShopSheet"><text>{{selectedShopName || '请选择要加入的店铺'}}</text><text class="picker-arrow">›</text></view></view><view wx:if="{{role === 'staff'}}" class="field"><text class="field-label">申请昵称(选填)</text><input type="nickname" value="{{form.applicantNickname}}" data-field="applicantNickname" bindinput="onInput" placeholder="可填写希望展示的昵称" /></view><view wx:if="{{role === 'staff'}}" class="field avatar-pick-field"><text class="field-label">申请头像(选填)</text><button class="avatar-pick" open-type="chooseAvatar" bindchooseavatar="chooseApplicantAvatar"><image src="{{form.applicantAvatarUrl || '/assets/images/default-user-avatar.png'}}" mode="aspectFill"></image><text>{{avatarUploading ? '上传中...' : '主动选择头像'}}</text></button></view><view wx:if="{{role === 'staff'}}" class="notice">审核通过前不会获得门店业务权限</view><button class="primary-btn" loading="{{loading}}" disabled="{{avatarUploading}}" bindtap="submit">提交审核</button><view class="back-entry" bindtap="goBackStep">返回上一步</view></view>
<view wx:elif="{{step === 3}}" class="card result-card"><view class="result-icon {{registrationStatusText === '已驳回' ? 'rejected' : registrationStatusText === '已通过' ? 'approved' : ''}}">{{registrationStatusText === '已驳回' ? '!' : registrationStatusText === '已通过' ? '✓' : '…'}}</view><view class="section-title">{{registrationStatusText === '已通过' ? '申请已通过' : registrationStatusText === '已驳回' ? '申请未通过' : '申请已提交'}}</view><view class="section-desc">{{registrationStatusText === '已通过' ? '现在可以返回登录页,使用微信快捷登录。' : registrationStatusText === '已驳回' ? (registrationStatus.rejectReason || '请联系对应审核人了解原因。') : (role === 'manager' ? '申请由平台管理员处理,通过后即可使用快捷登录。' : '申请由门店店长处理,通过后即可使用快捷登录。')}}</view><view class="result-status">当前状态:<text>{{registrationStatusText}}</text></view><view wx:if="{{contentStatusText}}" class="content-review-status"><text>{{contentStatusText}}</text><text wx:if="{{contentStatusReason}}" class="content-review-reason">{{contentStatusReason}}</text></view><button class="primary-btn" bindtap="back">返回登录</button></view>
<entity-selector-sheet visible="{{shopSheetVisible}}" title="选择门店" keyword="{{shopKeyword}}" placeholder="搜索门店名称或地址" items="{{shopSelectorItems}}" selected-id="{{form.shopId}}" loading="{{shopLoading}}" error-text="{{shopError}}" empty-text="暂无匹配门店" bind:search="onShopSearch" bind:select="selectShop" bind:retry="loadShops" bind:close="closeShopSheet" />
<view class="safe-note">OpenID 仅用于识别你的微信身份,不会在页面中展示。</view>
@@ -276,3 +276,7 @@
}
.avatar-pick::after { border: 0; }
.avatar-pick image { width: 72rpx; height: 72rpx; margin-right: 20rpx; border-radius: 50%; background: #e5f4ed; }
.address-entry { display:flex; align-items:center; gap:12rpx; }
.address-entry input { min-width:0; flex:1; }
.map-pick-btn { flex:none; width:132rpx; height:64rpx; margin:0; padding:0; border-radius:10rpx; background:#e5f4ed; color:#247b63; font-size:21rpx; line-height:64rpx; }
.field-hint { display:block; margin-top:10rpx; color:#819087; font-size:20rpx; line-height:1.5; }
+47 -15
View File
@@ -26,6 +26,27 @@ function resolveBusinessHours(value) {
return { start, end }
}
const WEEKDAYS = ['周一', '周二', '周三', '周四', '周五', '周六', '周日']
function normalizeWeeklyHours(weeklyHours, legacyHours) {
const legacy = resolveBusinessHours(legacyHours) || { start: '10:00', end: '22:00' }
const source = Array.isArray(weeklyHours) && weeklyHours.length === 7
? weeklyHours
: WEEKDAYS.map((_, index) => ({ dayOfWeek: index + 1, open: true, startTime: legacy.start, endTime: legacy.end }))
const byDay = new Map(source.map(item => [Number(item.dayOfWeek), item]))
return WEEKDAYS.map((dayName, index) => {
const day = byDay.get(index + 1) || {}
const open = day.open !== false
return {
dayOfWeek: index + 1,
dayName,
open,
startTime: resolveBusinessHours(`${day.startTime || legacy.start}-${day.endTime || legacy.end}`)?.start || legacy.start,
endTime: resolveBusinessHours(`${day.startTime || legacy.start}-${day.endTime || legacy.end}`)?.end || legacy.end
}
})
}
Page({
data: {
profile: {},
@@ -37,7 +58,7 @@ Page({
businessHoursConfigured: false,
nameSaving: false,
settingsError: '',
form: { shopName: BRAND_CONFIG.defaultShopName, pendingShopName: '', startTime: '', endTime: '', defaultDuration: 60 }
form: { shopName: BRAND_CONFIG.defaultShopName, pendingShopName: '', weeklyHours: normalizeWeeklyHours(), defaultDuration: 60 }
},
onShow() { this.loadProfileAndSettings() },
@@ -57,10 +78,10 @@ Page({
: hasRemainingDays
? `剩余 ${remainingDays} 天`
: '有效期未设置'
const businessHours = resolveBusinessHours(settings.businessHours)
const weeklyHours = normalizeWeeklyHours(settings.weeklyHours, settings.businessHours)
this.setData({
profile,
businessHoursConfigured: Boolean(businessHours),
businessHoursConfigured: weeklyHours.some(day => day.open),
businessExpireDateText,
businessExpiryStatusText,
nameModerationText: resolveNameStatus(settings.shopNameModerationStatus),
@@ -68,8 +89,7 @@ Page({
...this.data.form,
shopName: settings.pendingShopName || settings.shopName || profile.shopName || BRAND_CONFIG.defaultShopName,
pendingShopName: settings.pendingShopName || '',
startTime: businessHours ? businessHours.start : '',
endTime: businessHours ? businessHours.end : '',
weeklyHours,
defaultDuration: Number(settings.defaultAppointmentDurationMinutes) || 60
}
})
@@ -77,8 +97,7 @@ Page({
this.setData({
settingsError: error.message || '设置加载失败',
businessHoursConfigured: false,
'form.startTime': '',
'form.endTime': ''
'form.weeklyHours': []
})
} finally {
this.setData({ settingsLoading: false })
@@ -86,15 +105,25 @@ Page({
},
onInput(event) { this.setData({ [`form.${event.currentTarget.dataset.field}`]: event.detail.value }) },
onStartChange(event) { this.setData({ 'form.startTime': event.detail.value }) },
onEndChange(event) { this.setData({ 'form.endTime': event.detail.value }) },
toggleBusinessDay(event) {
const index = Number(event.currentTarget.dataset.index)
const weeklyHours = (this.data.form.weeklyHours || []).map((item, itemIndex) => itemIndex === index ? { ...item, open: Boolean(event.detail.value) } : item)
this.setData({ 'form.weeklyHours': weeklyHours })
},
changeBusinessTime(event) {
const index = Number(event.currentTarget.dataset.index)
const field = event.currentTarget.dataset.field
const weeklyHours = (this.data.form.weeklyHours || []).map((item, itemIndex) => itemIndex === index ? { ...item, [field]: event.detail.value } : item)
this.setData({ 'form.weeklyHours': weeklyHours })
},
async saveAppointmentSettings() {
const { startTime, endTime, defaultDuration } = this.data.form
const { weeklyHours, defaultDuration } = this.data.form
const duration = Number(defaultDuration)
const businessHours = resolveBusinessHours(`${startTime}-${endTime}`)
if (!businessHours) {
wx.showToast({ title: '请设置完整有效的营业时间', icon: 'none' })
const normalizedHours = normalizeWeeklyHours(weeklyHours)
if (normalizedHours.some(day => day.open && !resolveBusinessHours(`${day.startTime}-${day.endTime}`))) {
wx.showToast({ title: '请检查营业日的开始和结束时间', icon: 'none' })
return
}
if (!Number.isInteger(duration) || duration < 15 || duration > 720) {
@@ -103,8 +132,11 @@ Page({
}
this.setData({ settingsSaving: true })
try {
await shopApi.saveAppointmentSettings({ businessHours: `${businessHours.start}-${businessHours.end}`, defaultAppointmentDurationMinutes: duration })
this.setData({ businessHoursConfigured: true })
await shopApi.saveAppointmentSettings({
weeklyHours: normalizedHours.map(({ dayOfWeek, open, startTime, endTime }) => ({ dayOfWeek, open, startTime: open ? startTime : null, endTime: open ? endTime : null })),
defaultAppointmentDurationMinutes: duration
})
this.setData({ businessHoursConfigured: normalizedHours.some(day => day.open) })
wx.showToast({ title: '预约设置已生效', icon: 'success' })
} catch (error) {
wx.showToast({ title: error.message || '保存失败,请重试', icon: 'none' })
@@ -38,6 +38,7 @@ async function run() {
currentSettings = {
shopName: '薄荷美甲',
businessHours: '09:30-21:30',
weeklyHours: Array.from({ length: 7 }, (_, index) => ({ dayOfWeek: index + 1, open: true, startTime: '09:30', endTime: '21:30' })),
defaultAppointmentDurationMinutes: 75,
shopNameModerationStatus: 'PENDING',
pendingShopName: '薄荷指尖'
@@ -67,8 +68,9 @@ async function run() {
shopBusinessRemainingDays: 0
})
assert.strictEqual(expired.businessExpiryStatusText, '已过期,暂不能新增预约')
assert.strictEqual(expired.form.startTime, '09:30')
assert.strictEqual(expired.form.endTime, '21:30')
assert.strictEqual(expired.form.weeklyHours.length, 7)
assert.strictEqual(expired.form.weeklyHours[0].startTime, '09:30')
assert.strictEqual(expired.form.weeklyHours[6].endTime, '21:30')
assert.strictEqual(expired.businessHoursConfigured, true)
assert.strictEqual(expired.form.defaultDuration, 75)
assert.strictEqual(expired.nameModerationText, '名称审核中')
@@ -76,7 +78,7 @@ async function run() {
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('默认预约时长'))
assert(shopSettingsWxml.includes('catchtap="explainDefaultDuration"'))
@@ -85,17 +87,25 @@ async function run() {
assert(!shopSettingsWxml.includes('预约规则'))
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)
assert.strictEqual(unconfigured.form.weeklyHours.length, 7)
assert.strictEqual(unconfigured.form.weeklyHours[0].startTime, '10:00')
assert.strictEqual(unconfigured.form.weeklyHours[6].endTime, '22:00')
assert.strictEqual(unconfigured.businessHoursConfigured, true)
currentSettings = {
weeklyHours: Array.from({ length: 7 }, (_, index) => ({ dayOfWeek: index + 1, open: false, startTime: null, endTime: null })),
defaultAppointmentDurationMinutes: 60
}
const allClosed = await loadProfile({ type: 2 })
assert.strictEqual(allClosed.businessHoursConfigured, false)
assert.strictEqual(allClosed.form.weeklyHours.every(day => !day.open), true)
const savePage = {
data: { ...pageDefinition.data, businessHoursConfigured: false, form: { ...pageDefinition.data.form, startTime: '', endTime: '' } },
data: { ...pageDefinition.data, businessHoursConfigured: true, form: { ...pageDefinition.data.form, weeklyHours: pageDefinition.data.form.weeklyHours.map(day => ({ ...day })) } },
setData(values) {
Object.entries(values).forEach(([key, value]) => {
const parts = key.split('.')
@@ -106,14 +116,20 @@ async function run() {
}
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'
assert.strictEqual(savedSettings.weeklyHours.length, 7)
assert.deepStrictEqual(savedSettings.weeklyHours[0], { dayOfWeek: 1, open: true, startTime: '10:00', endTime: '22:00' })
savePage.data.form.weeklyHours[0].startTime = '09:00'
savePage.data.form.weeklyHours[0].endTime = '21:30'
await pageDefinition.saveAppointmentSettings.call(savePage)
assert.deepStrictEqual(savedSettings, { businessHours: '09:00-21:30', defaultAppointmentDurationMinutes: 60 })
assert.strictEqual(savedSettings.weeklyHours.length, 7)
assert.deepStrictEqual(savedSettings.weeklyHours[0], { dayOfWeek: 1, open: true, startTime: '09:00', endTime: '21:30' })
assert.strictEqual(savedSettings.defaultAppointmentDurationMinutes, 60)
assert.strictEqual(savePage.data.businessHoursConfigured, true)
savePage.data.form.weeklyHours = savePage.data.form.weeklyHours.map(day => ({ ...day, open: false }))
await pageDefinition.saveAppointmentSettings.call(savePage)
assert.strictEqual(savePage.data.businessHoursConfigured, false)
assert.strictEqual(savedSettings.weeklyHours.every(day => !day.open && day.startTime === null && day.endTime === null), true)
}
run().catch(error => {
@@ -12,9 +12,9 @@
<button class="settings-action secondary" loading="{{nameSaving}}" disabled="{{nameSaving}}" bindtap="submitShopName">提交名称审核</button>
<view class="settings-divider"></view>
<view class="settings-section-head"><view><text class="section-title">预约运营设置</text><text class="settings-section-note">保存后立即生效,不需要门店资料审核</text></view></view>
<view class="settings-field-row"><text class="settings-label">营业时间</text><view class="time-range"><picker mode="time" value="{{form.startTime}}" bindchange="onStartChange"><view class="time-value {{!form.startTime ? 'unconfigured' : ''}}">{{form.startTime || '设置开始时间'}}</view></picker><text>至</text><picker mode="time" value="{{form.endTime}}" bindchange="onEndChange"><view class="time-value {{!form.endTime ? 'unconfigured' : ''}}">{{form.endTime || '设置结束时间'}}</view></picker></view></view>
<text wx:if="{{!businessHoursConfigured}}" class="appointment-hours-note">营业时间尚未设置,保存后才能创建普通预约。</text>
<view class="settings-section-head"><view><text class="section-title">营业时间</text><text class="settings-section-note">按星期设置营业日和休息日,保存后立即生效</text></view></view>
<view class="weekly-hours-list"><view wx:for="{{form.weeklyHours}}" wx:key="dayOfWeek" class="weekly-hours-row"><view class="weekly-day-copy"><text class="settings-label">{{item.dayName}}</text><text class="weekly-day-status">{{item.open ? '营业' : '休息'}}</text></view><switch checked="{{item.open}}" data-index="{{index}}" bindchange="toggleBusinessDay" color="#247B63"/><view wx:if="{{item.open}}" class="time-range"><picker mode="time" value="{{item.startTime}}" data-index="{{index}}" data-field="startTime" bindchange="changeBusinessTime"><view class="time-value">{{item.startTime}}</view></picker><text>至</text><picker mode="time" value="{{item.endTime}}" data-index="{{index}}" data-field="endTime" bindchange="changeBusinessTime"><view class="time-value">{{item.endTime}}</view></picker></view></view></view>
<text wx:if="{{!businessHoursConfigured}}" class="appointment-hours-note">当前每周都设置为休息,不能创建普通预约。</text>
<view class="settings-field-row duration-row"><view class="label-with-help"><text class="settings-label">默认预约时长</text><text class="help-badge" catchtap="explainDefaultDuration">?</text></view><view class="duration-input"><input type="number" value="{{form.defaultDuration}}" data-field="defaultDuration" bindinput="onInput" /><text>分钟</text></view></view>
<button class="settings-action" loading="{{settingsSaving}}" disabled="{{settingsSaving}}" bindtap="saveAppointmentSettings">保存预约设置</button>
</view>
@@ -13,6 +13,13 @@
.settings-action.secondary { background: #e9f3ed; color: #397055; }
.settings-divider { height: 1rpx; margin: 32rpx 0 28rpx; background: #e4ebe6; }
.settings-field-row { display: flex; min-height: 90rpx; align-items: center; justify-content: space-between; gap: 20rpx; border-bottom: 1rpx solid #e8eee9; }
.weekly-hours-list { margin-top: 12rpx; border-top: 1rpx solid #e8eee9; }
.weekly-hours-row { display:flex; min-height:86rpx; align-items:center; gap:12rpx; border-bottom:1rpx solid #e8eee9; }
.weekly-day-copy { display:flex; width:100rpx; flex:none; flex-direction:column; gap:4rpx; }
.weekly-day-status { color:#819087; font-size:19rpx; }
.weekly-hours-row switch { flex:none; transform:scale(.78); transform-origin:center; }
.weekly-hours-row .time-range { flex:1; justify-content:flex-end; gap:8rpx; }
.weekly-hours-row .time-value { min-width:86rpx; padding:10rpx 8rpx; font-size:22rpx; }
.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; }
@@ -0,0 +1,15 @@
# Salon 小程序地图选点配置说明
## 小程序代码配置
- `JC-Salon-WeChat/app.json` 声明了 `chooseLocation` 隐私接口。
- 店长注册页仅在用户点击“地图选点”后调用微信地图选点;取消选点不会阻止注册,门店地址仍可手动输入。
- 用户确认选点后,提交门店地址、经度和纬度;手动修改地址时清除此前坐标,避免地址与坐标不一致。
## 微信公众平台发布前检查
1. 在小程序后台的用户隐私保护指引中,如实说明门店注册时由用户主动选择位置,供门店展示和预约导航使用。
2. 核对小程序隐私接口声明包含 `chooseLocation`,并按微信后台提示完成隐私保护指引审核/更新。
3. 上传体验版后,在真机上分别验证允许选点、取消选点和手动填写地址;没有选择位置时仍可继续注册。
本功能不会在后台静默读取设备位置,也不会因用户取消选点而拦截注册。微信公众平台配置需由具备小程序管理权限的人员完成。
+11
View File
@@ -1,5 +1,16 @@
# 项目变更记录
## 2026-11-03 Salon 小程序登录、门店排班与资料页修正
- 登录成功后才主动申请三个订阅模板;选店登录也会申请,自动登录跳过,用户拒绝或 API 不可用不阻断登录。
- 店长注册支持主动地图选点,保存门店地址及可选经纬度;手动修改地址会清除旧坐标,页面说明位置用途,不做静默定位。
- 门店按周一至周日配置营业/休息和时段;新门店默认每天 10:00–22:00,旧门店迁移回填既有营业时段,缺失时使用默认时段。日历按门店营业与员工排班显示状态,普通预约受营业时间约束,闭店日不显示新建入口。
- 个人头像上传现在先写入对象存储文件登记并返回文件 ID,个人资料更新限制引用本人上传的图片;缺少上传文件 ID 时阻止保存,成功/失败提示延长至 3 秒。
- 退出登录入口移至“我的”页面底部;周视图保持七日同屏,并压缩卡片占用。
- 新增 Flyway `V13__门店每周营业排班_20261103.sql`,不修改已发布迁移、不连接实际数据库。小程序地图选点使用 `chooseLocation`,微信公众平台隐私 API/指引需按配置说明完成登记。
- 问题与处理:日历顶层时段仍从旧单一营业时段读取,导致每周全部休息时前端可能误判仍有营业时间;改为仅从每周排班的有效营业日推导,全周关闭时返回空时段,并补充全闭与部分营业测试。新增日视图/闭店用例时重复声明测试变量,已拆分命名并重新运行全部测试。
- 验证:Salon Core `mvn clean test` 通过;小程序 30 个测试脚本和 77 个 JavaScript 语法检查通过;V13 迁移静态检查及 `git diff --check` 通过。GitNexus 索引更新后变更检查为低风险。
## 2026-11-03 Salon 微信审核回调支持 JSON
- 原因:微信消息推送选择安全模式和 JSON 时,SIT 回调入口只接收 XML 外层密文,导致 JSON 请求无法进入回调处理。