Merge pull request '合并sit1.0版本' (#93) from dev into sit
自动发布测试环境 Nacos 配置 / publish (push) Successful in 20s

Reviewed-on: http://wcsrv.top:3000/xiaowang/JayuCloud/pulls/93
This commit was merged in pull request #93.
This commit is contained in:
2026-11-03 18:27:08 +08:00
70 changed files with 1654 additions and 244 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);
@@ -9,6 +9,7 @@ import com.xiaowang.jayucloud.salon.core.modules.file.entity.ObjectStorageReplic
import com.xiaowang.jayucloud.salon.core.modules.file.service.ObjectStorageOrchestrationService;
import com.xiaowang.jayucloud.salon.core.modules.file.service.ObjectStorageProvider;
import com.xiaowang.jayucloud.salon.core.modules.file.service.ObjectStorageReplicaService;
import com.xiaowang.jayucloud.salon.core.modules.system.service.SystemParameterConfigService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
@@ -23,6 +24,9 @@ import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Arrays;
import java.util.Collections;
import java.util.Set;
import java.util.stream.Collectors;
@Slf4j
@@ -35,6 +39,12 @@ public class ObjectStorageOrchestrationServiceImpl implements ObjectStorageOrche
private final List<ObjectStorageProvider> providers;
private final ObjectStorageProperties objectStorageProperties;
private final ObjectStorageReplicaService objectStorageReplicaService;
private final SystemParameterConfigService systemParameterConfigService;
private volatile ProviderOrderCache providerOrderCache;
private static final long PROVIDER_ORDER_CACHE_MILLIS = 30_000L;
private static final String PROVIDER_ORDER_GROUP = "FILE";
private static final String PROVIDER_ORDER_KEY = "IMAGE_READ_PROVIDER_ORDER";
private static final Set<String> SUPPORTED_PROVIDERS = Set.of("MINIO", "QINIU_KODO", "ALIYUN_OSS");
@Override
public ObjectStorageUploadOutcome uploadPrimary(InputStream inputStream, long fileSize, String contentType, String objectName) throws Exception {
@@ -110,7 +120,7 @@ public class ObjectStorageOrchestrationServiceImpl implements ObjectStorageOrche
Map<String, ObjectStorageReplicaDO> replicaMap = replicas.stream()
.collect(Collectors.toMap(ObjectStorageReplicaDO::getProvider, replica -> replica, (left, right) -> left, LinkedHashMap::new));
Exception lastFailure = null;
for (String providerCode : objectStorageProperties.getProviderOrder()) {
for (String providerCode : readProviderOrder()) {
ObjectStorageReplicaDO replica = replicaMap.get(providerCode);
if (replica == null
|| !Integer.valueOf(ObjectStorageBackupServiceImpl.UPLOAD_STATUS_SUCCEEDED).equals(replica.getUploadStatus())) {
@@ -129,7 +139,7 @@ public class ObjectStorageOrchestrationServiceImpl implements ObjectStorageOrche
@Override
public String getPresignedUrl(String objectName, Integer expiryTimeInMinutes) {
Exception lastFailure = null;
for (String providerCode : objectStorageProperties.getProviderOrder()) {
for (String providerCode : readProviderOrder()) {
try {
ObjectStorageProvider provider = requireProvider(providerCode);
ensureEnabled(provider);
@@ -142,6 +152,52 @@ public class ObjectStorageOrchestrationServiceImpl implements ObjectStorageOrche
throw new IllegalStateException("No available object storage signed URL for objectName=" + objectName, lastFailure);
}
private List<String> readProviderOrder() {
long now = System.currentTimeMillis();
ProviderOrderCache cache = providerOrderCache;
if (cache != null && now < cache.expiresAt) return cache.providers;
synchronized (this) {
cache = providerOrderCache;
now = System.currentTimeMillis();
if (cache != null && now < cache.expiresAt) return cache.providers;
List<String> providers;
try {
providers = parseProviderOrder(systemParameterConfigService.getEnabledValue(PROVIDER_ORDER_GROUP, PROVIDER_ORDER_KEY));
} catch (RuntimeException exception) {
log.warn("读取对象存储签名访问顺序失败,回退到当前环境默认配置", exception);
providers = Collections.emptyList();
}
if (providers.isEmpty()) providers = validateFallbackOrder(objectStorageProperties.getProviderOrder());
providerOrderCache = new ProviderOrderCache(providers, now + PROVIDER_ORDER_CACHE_MILLIS);
return providers;
}
}
private List<String> parseProviderOrder(String value) {
if (!StringUtils.hasText(value)) return Collections.emptyList();
return validateFallbackOrder(Arrays.asList(value.split(",")));
}
private List<String> validateFallbackOrder(List<String> configured) {
if (configured == null) return Collections.emptyList();
List<String> providers = configured.stream().filter(StringUtils::hasText)
.map(value -> value.trim().toUpperCase(java.util.Locale.ROOT)).collect(Collectors.toList());
if (providers.size() != SUPPORTED_PROVIDERS.size() || !SUPPORTED_PROVIDERS.equals(new java.util.HashSet<>(providers))) {
return Collections.emptyList();
}
return Collections.unmodifiableList(providers);
}
private static final class ProviderOrderCache {
private final List<String> providers;
private final long expiresAt;
private ProviderOrderCache(List<String> providers, long expiresAt) {
this.providers = providers;
this.expiresAt = expiresAt;
}
}
private boolean uploadReplica(ObjectStorageFileDO file, String providerCode, Map<String, ObjectStorageReplicaDO> replicaMap) {
ObjectStorageReplicaDTO replicaDTO = new ObjectStorageReplicaDTO();
replicaDTO.setProvider(providerCode);
@@ -23,6 +23,8 @@ import com.xiaowang.jayucloud.salon.core.modules.order.mapper.OrderMapper;
import com.xiaowang.jayucloud.salon.core.modules.product.mapper.ProductMapper;
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.user.mapper.UserMapper;
import com.xiaowang.jayucloud.salon.core.modules.user.service.UserService;
import com.xiaowang.jayucloud.salon.core.modules.planning.service.AppointmentCapacityService;
@@ -95,6 +97,7 @@ public class PlanningServiceImpl implements PlanningService {
private final ProductMapper productMapper;
private final ShopMapper shopMapper;
private final ShopBusinessExpiryService shopBusinessExpiryService;
private final ShopBusinessScheduleService shopBusinessScheduleService;
private final AppointmentCapacityService appointmentCapacityService;
private final OrderService orderService;
private final WechatSubscribeMessageService wechatSubscribeMessageService;
@@ -114,9 +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())
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);
@@ -146,7 +156,7 @@ public class PlanningServiceImpl implements PlanningService {
vo.setArtists(artists);
vo.setSchedules(scheduleVos);
vo.setAppointments(appointments);
vo.setDaySummaries(buildDaySummaries(start, end, artists, schedules, appointments));
vo.setDaySummaries(buildDaySummaries(start, end, artists, schedules, appointments, weeklyHours));
return vo;
}
@@ -641,7 +651,8 @@ public class PlanningServiceImpl implements PlanningService {
}
private List<PlanningDaySummaryVO> buildDaySummaries(LocalDate start, LocalDate end, List<PlanningArtistVO> artists,
List<ArtistScheduleDO> schedules, List<PlanningAppointmentVO> appointments) {
List<ArtistScheduleDO> schedules, List<PlanningAppointmentVO> appointments,
Map<Integer, ShopBusinessHoursDayVO> weeklyHours) {
Map<String, List<PlanningAppointmentVO>> appointmentsByDate = appointments.stream()
.filter(appointment -> appointment.getDate() != null)
.collect(Collectors.groupingBy(PlanningAppointmentVO::getDate));
@@ -699,7 +710,12 @@ public class PlanningServiceImpl implements PlanningService {
summary.setTotalCount(total);
summary.setUnassignedCount(unassignedCount);
summary.setArtistCounts(artistCounts);
summary.setDayStatus(PlanningCalendarSupport.resolveDayStatus(total, hasWorkingSchedule, allFull));
ShopBusinessHoursDayVO shopDay = weeklyHours == null ? null : weeklyHours.get(cursor.getDayOfWeek().getValue());
boolean shopOpen = shopDay == null || Boolean.TRUE.equals(shopDay.getOpen());
summary.setShopOpen(shopOpen);
summary.setShopStartTime(shopDay == null ? null : shopDay.getStartTime());
summary.setShopEndTime(shopDay == null ? null : shopDay.getEndTime());
summary.setDayStatus(!shopOpen ? "rest" : PlanningCalendarSupport.resolveDayStatus(total, hasWorkingSchedule, allFull));
summaries.add(summary);
cursor = cursor.plusDays(1);
}
@@ -884,12 +900,11 @@ 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 = parseConfiguredBusinessHours(configuredHours);
if (hours == null) {
throw new RuntimeException(StringUtils.hasText(configuredHours)
? "门店营业时间格式无效,请先完成设置"
: "门店营业时间未设置,请先完成设置");
}
ShopBusinessHoursDayVO shopDay = shopBusinessScheduleService.forDate(shopId, startTime.toLocalDate(), configuredHours);
if (shopDay == null || !Boolean.TRUE.equals(shopDay.getOpen())) throw new RuntimeException("预约日期门店休息,暂不可新建普通预约");
PlanningCalendarSupport.BusinessHours hours = parseConfiguredBusinessHours(
shopDay.getStartTime() + "-" + shopDay.getEndTime());
if (hours == null) throw new RuntimeException("门店营业时间未设置,请先完成设置");
LocalTime start = startTime.toLocalTime();
LocalTime end = endTime.toLocalTime();
if (start.isBefore(hours.start()) || end.isAfter(hours.end()) || !startTime.toLocalDate().equals(endTime.toLocalDate())) {
@@ -66,9 +66,6 @@ public final class PlanningCalendarSupport {
}
public static String resolveDayStatus(int totalCount, boolean hasWorkingSchedule, boolean allWorkingArtistsBusy) {
if (!hasWorkingSchedule) {
return "rest";
}
if (allWorkingArtistsBusy) {
return "full";
}
@@ -11,4 +11,7 @@ public class PlanningDaySummaryVO {
private Integer unassignedCount;
private List<PlanningArtistCountVO> artistCounts;
private String dayStatus;
private Boolean shopOpen;
private String shopStartTime;
private String shopEndTime;
}
@@ -72,10 +72,12 @@ public class WechatContentModerationCallbackController {
String taskId;
String suggest;
String reason;
String extra;
if (decoded.trim().startsWith("<")) {
taskId = firstNonBlank(crypto.value(decoded, "trace_id"), crypto.value(decoded, "TraceId"), crypto.value(decoded, "task_id"));
suggest = firstNonBlank(crypto.value(decoded, "suggest"), crypto.value(decoded, "Suggest"), "review");
reason = firstNonBlank(crypto.value(decoded, "errmsg"), crypto.value(decoded, "label"), "微信异步图片审核回调");
extra = firstNonBlank(crypto.value(decoded, "extra"), crypto.value(decoded, "Extra"));
} else {
JsonNode root = objectMapper.readTree(decoded);
taskId = firstText(root, "trace_id", "traceId", "task_id");
@@ -83,12 +85,23 @@ public class WechatContentModerationCallbackController {
if (!StringUtils.hasText(suggest)) suggest = "review";
reason = firstText(root, "errmsg", "reason");
if (!StringUtils.hasText(reason)) reason = "微信异步图片审核回调";
extra = firstText(root, "extra", "Extra");
}
if (!StringUtils.hasText(taskId)) throw new IllegalArgumentException("微信审核回调缺少任务标识");
contentModerationService.handleWechatImageResult(taskId, suggest, reason);
contentModerationService.handleWechatImageResult(taskId, suggest, reason, decodeSourceEnvVersion(extra));
return "success";
}
private String decodeSourceEnvVersion(String extra) {
if (!StringUtils.hasText(extra)) return null;
try {
JsonNode payload = objectMapper.readTree(extra);
return firstText(payload, "envVersion", "env_version");
} catch (Exception ignored) {
return null;
}
}
private String extractEncryptedPayload(String body) throws Exception {
if (!StringUtils.hasText(body)) {
throw new IllegalArgumentException("微信审核回调消息体为空");
@@ -17,6 +17,7 @@ public class ContentModerationImageTaskDO extends BaseEntity {
private Long id;
private Long recordId;
private Long fileId;
private String sourceEnvVersion;
private String providerTaskId;
private String status;
private String resultCode;
@@ -6,4 +6,8 @@ public interface ContentModerationProvider {
ModerationOutcome reviewText(String contentType, String content, String openId);
ModerationOutcome submitImage(String contentType, String imageUrl, String openId);
default ModerationOutcome submitImage(String contentType, String imageUrl, String openId, String sourceEnvVersion) {
return submitImage(contentType, imageUrl, openId);
}
}
@@ -32,6 +32,11 @@ public class RoutingContentModerationProvider implements ContentModerationProvid
return resolveProvider().submitImage(contentType, imageUrl, openId);
}
@Override
public ModerationOutcome submitImage(String contentType, String imageUrl, String openId, String sourceEnvVersion) {
return resolveProvider().submitImage(contentType, imageUrl, openId, sourceEnvVersion);
}
private ContentModerationProvider resolveProvider() {
try {
ModerationRuntimeConfig config = secureIntegrationConfigService.getModerationRuntimeConfig();
@@ -57,6 +57,11 @@ public class WechatContentModerationProvider implements ContentModerationProvide
@Override
public ModerationOutcome submitImage(String contentType, String imageUrl, String openId) {
return submitImage(contentType, imageUrl, openId, "UNKNOWN");
}
@Override
public ModerationOutcome submitImage(String contentType, String imageUrl, String openId, String sourceEnvVersion) {
if (!StringUtils.hasText(openId)) return pending("OPENID_REQUIRED", "缺少微信作者身份,转人工复核");
if (!StringUtils.hasText(imageUrl) || !imageUrl.startsWith("https://")) {
return retry("IMAGE_URL_INVALID", "审核图片需要短期有效的 HTTPS 地址");
@@ -67,9 +72,22 @@ public class WechatContentModerationProvider implements ContentModerationProvide
payload.put("version", 2);
payload.put("scene", properties.getScene());
payload.put("openid", openId);
payload.put("extra", encodeSourceEnvVersion(sourceEnvVersion));
return parseResult(post(IMAGE_CHECK_URL, payload), true);
}
private String encodeSourceEnvVersion(String sourceEnvVersion) {
String envVersion = sourceEnvVersion;
if (!"develop".equals(envVersion) && !"trial".equals(envVersion) && !"release".equals(envVersion)) {
envVersion = "UNKNOWN";
}
try {
return objectMapper.writeValueAsString(Map.of("envVersion", envVersion));
} catch (java.io.IOException exception) {
throw new IllegalStateException("无法编码微信审核来源版本", exception);
}
}
private Map<String, Object> post(String endpoint, Map<String, Object> payload) {
String url = UriComponentsBuilder.fromHttpUrl(endpoint)
.queryParam("access_token", wechatMiniClientService.getAccessTokenForContentModeration())
@@ -12,6 +12,10 @@ public interface ContentModerationService {
String payloadJson, List<Long> imageFileIds);
List<ContentModerationRecordVO> listPending();
boolean review(Long reviewerId, Long recordId, boolean approved, String reason);
boolean handleWechatImageResult(String providerTaskId, String suggest, String reason);
boolean handleWechatImageResult(String providerTaskId, String suggest, String reason, String sourceEnvVersion);
default boolean handleWechatImageResult(String providerTaskId, String suggest, String reason) {
return handleWechatImageResult(providerTaskId, suggest, reason, null);
}
int retryFailedImageTasks();
}
@@ -42,6 +42,8 @@ import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import java.time.LocalDateTime;
import java.util.ArrayList;
@@ -116,9 +118,11 @@ public class ContentModerationServiceImpl implements ContentModerationService {
ContentModerationImageTaskDO task = new ContentModerationImageTaskDO();
task.setRecordId(record.getId());
task.setFileId(fileId);
String sourceEnvVersion = currentMiniProgramEnvVersion();
task.setSourceEnvVersion(sourceEnvVersion);
task.setAttemptCount(1);
ModerationOutcome imageOutcome = StringUtils.hasText(openId)
? safeImageReview(contentType, fileId, openId)
? safeImageReview(contentType, fileId, openId, sourceEnvVersion)
: outcome(ModerationOutcome.Status.PENDING, "OPENID_REQUIRED", "发布者未绑定可核验的微信身份,转人工复核");
boolean imageRetryExhausted = exhausted(imageOutcome, 1, maxRetries);
task.setStatus(imageRetryExhausted ? "PENDING" : imageOutcome.status().name());
@@ -201,6 +205,12 @@ public class ContentModerationServiceImpl implements ContentModerationService {
@Override
@Transactional(rollbackFor = Exception.class)
public boolean handleWechatImageResult(String providerTaskId, String suggest, String reason) {
return handleWechatImageResult(providerTaskId, suggest, reason, null);
}
@Override
@Transactional(rollbackFor = Exception.class)
public boolean handleWechatImageResult(String providerTaskId, String suggest, String reason, String sourceEnvVersion) {
if (!StringUtils.hasText(providerTaskId)) return false;
ContentModerationImageTaskDO candidate = imageTaskMapper.selectOne(new LambdaQueryWrapper<ContentModerationImageTaskDO>()
.eq(ContentModerationImageTaskDO::getProviderTaskId, providerTaskId).last("LIMIT 1"));
@@ -215,6 +225,13 @@ public class ContentModerationServiceImpl implements ContentModerationService {
.eq(ContentModerationImageTaskDO::getProviderTaskId, providerTaskId)
.last("FOR UPDATE"));
if (task == null || !isReviewable(task.getStatus())) return task != null;
String expectedEnvVersion = normalizeTaskEnvVersion(task.getSourceEnvVersion());
if (!StringUtils.hasText(sourceEnvVersion) && !"LEGACY".equals(expectedEnvVersion)) return true;
String callbackEnvVersion = normalizeEnvVersion(sourceEnvVersion);
if ("LEGACY".equals(expectedEnvVersion) && !StringUtils.hasText(sourceEnvVersion)) {
callbackEnvVersion = "LEGACY";
}
if (!expectedEnvVersion.equals(callbackEnvVersion)) return true;
if ("pass".equalsIgnoreCase(suggest)) task.setStatus("APPROVED");
else if ("risky".equalsIgnoreCase(suggest)) task.setStatus("REJECTED");
else task.setStatus("PENDING");
@@ -253,7 +270,10 @@ public class ContentModerationServiceImpl implements ContentModerationService {
if (task == null) continue;
attempted++;
task.setProviderTaskId(null);
ModerationOutcome outcome = safeImageReview(record.getContentType(), task.getFileId(), openId);
String sourceEnvVersion = normalizeTaskEnvVersion(task.getSourceEnvVersion());
if ("LEGACY".equals(sourceEnvVersion)) sourceEnvVersion = "UNKNOWN";
task.setSourceEnvVersion(sourceEnvVersion);
ModerationOutcome outcome = safeImageReview(record.getContentType(), task.getFileId(), openId, sourceEnvVersion);
task.setAttemptCount((task.getAttemptCount() == null ? 0 : task.getAttemptCount()) + 1);
task.setStatus(exhausted(outcome, task.getAttemptCount(), maxRetries) ? "PENDING" : outcome.status().name());
task.setResultCode(outcome.code());
@@ -500,15 +520,32 @@ public class ContentModerationServiceImpl implements ContentModerationService {
catch (RuntimeException exception) { return outcome(ModerationOutcome.Status.RETRY, "PROVIDER_FAILURE", "内容审核服务暂不可用,内容已隔离等待重试"); }
}
private ModerationOutcome safeImageReview(String type, Long fileId, String openId) {
private ModerationOutcome safeImageReview(String type, Long fileId, String openId, String sourceEnvVersion) {
try {
String url = objectStorageFileService.createTemporaryModerationUrl(fileId, properties.getImageUrlExpireMinutes());
return provider.submitImage(type, url, openId);
return provider.submitImage(type, url, openId, normalizeEnvVersion(sourceEnvVersion));
} catch (RuntimeException exception) {
return outcome(ModerationOutcome.Status.RETRY, "IMAGE_REVIEW_FAILURE", "图片审核暂不可用,内容已隔离等待重试");
}
}
private String currentMiniProgramEnvVersion() {
Object attributes = RequestContextHolder.getRequestAttributes();
if (!(attributes instanceof ServletRequestAttributes)) return "UNKNOWN";
String envVersion = ((ServletRequestAttributes) attributes).getRequest().getHeader("X-Mini-Program-Env-Version");
return normalizeEnvVersion(envVersion);
}
private String normalizeEnvVersion(String value) {
if ("develop".equals(value) || "trial".equals(value) || "release".equals(value)) return value;
if ("LEGACY".equals(value)) return "LEGACY";
return "UNKNOWN";
}
private String normalizeTaskEnvVersion(String value) {
return StringUtils.hasText(value) ? normalizeEnvVersion(value) : "LEGACY";
}
private String resolveOpenId(Long userId) {
if (userId == null) return null;
try {
@@ -3,6 +3,8 @@ package com.xiaowang.jayucloud.salon.core.modules.registration.dto;
import lombok.Getter;
import lombok.Setter;
import java.math.BigDecimal;
@Getter
@Setter
public class WorkbenchRegistrationRequestDTO {
@@ -12,6 +14,8 @@ public class WorkbenchRegistrationRequestDTO {
private Long shopId;
private String shopName;
private String shopAddress;
private BigDecimal shopLongitude;
private BigDecimal shopLatitude;
private Boolean agreementAccepted;
private String applicantNickname;
private Long applicantAvatarFileId;
@@ -22,6 +22,7 @@ import com.xiaowang.jayucloud.salon.core.modules.shop.support.UserShopBindingSup
import com.xiaowang.jayucloud.salon.core.modules.shop.entity.UserShopBindingDO;
import com.xiaowang.jayucloud.salon.core.modules.shop.mapper.UserShopBindingMapper;
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.privacy.entity.ContentModerationRecordDO;
import com.xiaowang.jayucloud.salon.core.modules.privacy.mapper.ContentModerationRecordMapper;
import com.xiaowang.jayucloud.salon.core.modules.privacy.service.ContentModerationService;
@@ -62,6 +63,7 @@ public class WorkbenchRegistrationServiceImpl implements WorkbenchRegistrationSe
private final ContentModerationService contentModerationService;
private final ContentModerationRecordMapper contentModerationRecordMapper;
private final ShopBusinessExpiryService shopBusinessExpiryService;
private final ShopBusinessScheduleService shopBusinessScheduleService;
private final TransactionTemplate transactionTemplate;
private final WechatMiniBindingMapper wechatMiniBindingMapper;
private final ObjectStorageFileService objectStorageFileService;
@@ -79,6 +81,7 @@ public class WorkbenchRegistrationServiceImpl implements WorkbenchRegistrationSe
ContentModerationService contentModerationService,
ContentModerationRecordMapper contentModerationRecordMapper,
ShopBusinessExpiryService shopBusinessExpiryService,
ShopBusinessScheduleService shopBusinessScheduleService,
PlatformTransactionManager transactionManager,
WechatMiniBindingMapper wechatMiniBindingMapper,
ObjectStorageFileService objectStorageFileService,
@@ -95,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;
@@ -111,6 +115,13 @@ public class WorkbenchRegistrationServiceImpl implements WorkbenchRegistrationSe
String managerShopName = WorkbenchRegistrationRole.MANAGER.equals(roleType)
? requireText(request.getShopName(), "店铺名称不能为空") : null;
if ((request.getShopLongitude() == null) != (request.getShopLatitude() == null)) {
throw new IllegalArgumentException("地图坐标信息不完整,请重新选点");
}
if (request.getShopLongitude() != null && (request.getShopLongitude().abs().compareTo(java.math.BigDecimal.valueOf(180)) > 0
|| request.getShopLatitude().abs().compareTo(java.math.BigDecimal.valueOf(90)) > 0)) {
throw new IllegalArgumentException("地图坐标超出有效范围");
}
ShopDO selectedStaffShop = null;
if (WorkbenchRegistrationRole.STAFF.equals(roleType)) {
require(request.getShopId() != null, "请选择要加入的店铺");
@@ -144,6 +155,8 @@ public class WorkbenchRegistrationServiceImpl implements WorkbenchRegistrationSe
}
shop.setShopName(managerShopName);
shop.setAddress(request.getShopAddress());
shop.setLongitude(request.getShopLongitude());
shop.setLatitude(request.getShopLatitude());
shop.setDescription("Salon店务工作台注册申请");
shop.setBusinessHours("10:00-22:00");
shop.setStatus(0);
@@ -154,6 +167,7 @@ public class WorkbenchRegistrationServiceImpl implements WorkbenchRegistrationSe
} else {
shopMapper.updateById(shop);
}
shopBusinessScheduleService.initializeDefault(shop.getId(), "10:00-22:00");
} else {
shop = selectedStaffShop;
}
@@ -1,9 +1,11 @@
package com.xiaowang.jayucloud.salon.core.modules.shop.dto;
import lombok.Data;
import java.util.List;
@Data
public class ShopAppointmentSettingsDTO {
private String businessHours;
private Integer defaultAppointmentDurationMinutes;
private List<ShopBusinessHoursDayDTO> weeklyHours;
}
@@ -0,0 +1,11 @@
package com.xiaowang.jayucloud.salon.core.modules.shop.dto;
import lombok.Data;
@Data
public class ShopBusinessHoursDayDTO {
private Integer dayOfWeek;
private Boolean open;
private String startTime;
private String endTime;
}
@@ -0,0 +1,158 @@
package com.xiaowang.jayucloud.salon.core.modules.shop.service;
import com.xiaowang.jayucloud.salon.core.modules.shop.dto.ShopBusinessHoursDayDTO;
import com.xiaowang.jayucloud.salon.core.modules.shop.vo.ShopBusinessHoursDayVO;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import java.sql.Time;
import java.time.LocalDate;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@Service
public class ShopBusinessScheduleService {
private static final LocalTime DEFAULT_START = LocalTime.of(10, 0);
private static final LocalTime DEFAULT_END = LocalTime.of(22, 0);
private static final DateTimeFormatter TIME_FORMAT = DateTimeFormatter.ofPattern("HH:mm");
private final JdbcTemplate jdbcTemplate;
public ShopBusinessScheduleService(JdbcTemplate jdbcTemplate) {
this.jdbcTemplate = jdbcTemplate;
}
public List<ShopBusinessHoursDayVO> list(Long shopId, String legacyHours) {
ensureDefaultSchedule(shopId, legacyHours);
return jdbcTemplate.query(
"SELECT day_of_week, is_open, start_time, end_time FROM t_shop_weekly_schedule WHERE shop_id = ? ORDER BY day_of_week",
(rs, rowNum) -> {
ShopBusinessHoursDayVO day = new ShopBusinessHoursDayVO();
day.setDayOfWeek(rs.getInt("day_of_week"));
day.setOpen(rs.getInt("is_open") == 1);
Time start = rs.getTime("start_time");
Time end = rs.getTime("end_time");
day.setStartTime(start == null ? null : start.toLocalTime().format(TIME_FORMAT));
day.setEndTime(end == null ? null : end.toLocalTime().format(TIME_FORMAT));
return day;
}, shopId
);
}
public Map<Integer, ShopBusinessHoursDayVO> mapByDay(Long shopId, String legacyHours) {
Map<Integer, ShopBusinessHoursDayVO> result = new HashMap<>();
list(shopId, legacyHours).forEach(day -> result.put(day.getDayOfWeek(), day));
return result;
}
public ShopBusinessHoursDayVO forDate(Long shopId, LocalDate date, String legacyHours) {
if (date == null) return null;
return mapByDay(shopId, legacyHours).get(date.getDayOfWeek().getValue());
}
@Transactional
public void initializeDefault(Long shopId, String legacyHours) {
ensureDefaultSchedule(shopId, legacyHours);
}
@Transactional
public void save(Long shopId, List<ShopBusinessHoursDayDTO> requested, String legacyHours) {
List<ShopBusinessHoursDayDTO> days = requested;
if (days == null || days.isEmpty()) {
days = legacySchedule(legacyHours);
}
if (days.size() != 7) throw new IllegalArgumentException("请设置周一至周日的营业状态");
Map<Integer, ShopBusinessHoursDayDTO> byDay = new HashMap<>();
for (ShopBusinessHoursDayDTO day : days) {
if (day == null || day.getDayOfWeek() == null || day.getDayOfWeek() < 1 || day.getDayOfWeek() > 7
|| byDay.putIfAbsent(day.getDayOfWeek(), day) != null) {
throw new IllegalArgumentException("每周营业设置必须包含周一至周日且不能重复");
}
if (!Boolean.TRUE.equals(day.getOpen())) {
day.setOpen(false);
day.setStartTime(null);
day.setEndTime(null);
continue;
}
LocalTime start = parseTime(day.getStartTime(), "营业开始时间");
LocalTime end = parseTime(day.getEndTime(), "营业结束时间");
if (!start.isBefore(end)) throw new IllegalArgumentException("营业开始时间必须早于结束时间");
day.setStartTime(start.format(TIME_FORMAT));
day.setEndTime(end.format(TIME_FORMAT));
}
if (byDay.size() != 7) throw new IllegalArgumentException("请完整设置周一至周日");
ensureDefaultSchedule(shopId, legacyHours);
for (int dayOfWeek = 1; dayOfWeek <= 7; dayOfWeek++) {
ShopBusinessHoursDayDTO day = byDay.get(dayOfWeek);
jdbcTemplate.update(
"UPDATE t_shop_weekly_schedule SET is_open = ?, start_time = ?, end_time = ?, update_time = CURRENT_TIMESTAMP WHERE shop_id = ? AND day_of_week = ?",
Boolean.TRUE.equals(day.getOpen()) ? 1 : 0,
day.getStartTime() == null ? null : Time.valueOf(day.getStartTime() + ":00"),
day.getEndTime() == null ? null : Time.valueOf(day.getEndTime() + ":00"),
shopId,
dayOfWeek
);
}
}
private void ensureDefaultSchedule(Long shopId, String legacyHours) {
if (shopId == null) throw new IllegalArgumentException("门店不能为空");
LocalTime[] parsed = parseLegacyHours(legacyHours);
LocalTime start = parsed == null ? DEFAULT_START : parsed[0];
LocalTime end = parsed == null ? DEFAULT_END : parsed[1];
for (int day = 1; day <= 7; day++) {
jdbcTemplate.update(
"INSERT IGNORE INTO t_shop_weekly_schedule (shop_id, day_of_week, is_open, start_time, end_time, create_time, update_time) VALUES (?, ?, 1, ?, ?, CURRENT_TIMESTAMP, CURRENT_TIMESTAMP)",
shopId, day, Time.valueOf(start), Time.valueOf(end)
);
}
}
private List<ShopBusinessHoursDayDTO> legacySchedule(String legacyHours) {
LocalTime[] times = parseLegacyHours(legacyHours);
LocalTime start = times == null ? DEFAULT_START : times[0];
LocalTime end = times == null ? DEFAULT_END : times[1];
List<ShopBusinessHoursDayDTO> result = new ArrayList<>();
for (int day = 1; day <= 7; day++) {
ShopBusinessHoursDayDTO item = new ShopBusinessHoursDayDTO();
item.setDayOfWeek(day);
item.setOpen(true);
item.setStartTime(start.format(TIME_FORMAT));
item.setEndTime(end.format(TIME_FORMAT));
result.add(item);
}
return result;
}
private LocalTime[] parseLegacyHours(String value) {
if (!StringUtils.hasText(value)) return null;
String[] parts = value.trim().split("-");
if (parts.length != 2) return null;
try {
LocalTime start = parseTime(parts[0], "营业开始时间");
LocalTime end = parseTime(parts[1], "营业结束时间");
return start.isBefore(end) ? new LocalTime[]{start, end} : null;
} catch (IllegalArgumentException ignored) {
return null;
}
}
private LocalTime parseTime(String value, String label) {
if (!StringUtils.hasText(value)) throw new IllegalArgumentException(label + "不能为空");
try {
String normalized = value.trim();
return LocalTime.parse(normalized.length() == 5 ? normalized : normalized.substring(0, 5), TIME_FORMAT);
} catch (DateTimeParseException | IndexOutOfBoundsException e) {
throw new IllegalArgumentException(label + "格式不正确");
}
}
}
@@ -26,6 +26,7 @@ import com.xiaowang.jayucloud.salon.core.modules.artist.service.NailArtistInfoSe
import com.xiaowang.jayucloud.salon.core.modules.file.service.ObjectStorageFileService;
import com.xiaowang.jayucloud.salon.core.modules.shop.service.ShopService;
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.file.support.ObjectStorageUrlSupport;
import com.xiaowang.jayucloud.salon.core.modules.shop.support.ShopThemeSupport;
import com.xiaowang.jayucloud.salon.core.modules.shop.support.UserShopBindingSupport;
@@ -97,6 +98,7 @@ public class ShopServiceImpl extends ServiceImpl<ShopMapper, ShopDO> implements
private final ShopMapper shopMapper;
private final ContentModerationRecordMapper contentModerationRecordMapper;
private final ShopBusinessExpiryService shopBusinessExpiryService;
private final ShopBusinessScheduleService shopBusinessScheduleService;
/**
* Variable `couponService`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls.
*/
@@ -180,6 +182,7 @@ public class ShopServiceImpl extends ServiceImpl<ShopMapper, ShopDO> implements
shopDO.setStatus(normalizeStatus(shopDTO.getStatus()));
shopDO.setIsDelete(0);
shopMapper.insert(shopDO);
shopBusinessScheduleService.initializeDefault(shopDO.getId(), "10:00-22:00");
submitShopSnapshot(shopDO, shopDTO);
couponService.initializeDefaultVipAutoCoupons(shopDO.getId());
evictShopCaches(shopDO.getId());
@@ -239,6 +242,7 @@ public class ShopServiceImpl extends ServiceImpl<ShopMapper, ShopDO> implements
}
result.setBusinessHours(StringUtils.hasText(shop.getAppointmentBusinessHours())
? shop.getAppointmentBusinessHours() : shop.getBusinessHours());
result.setWeeklyHours(shopBusinessScheduleService.list(id, result.getBusinessHours()));
result.setDefaultAppointmentDurationMinutes(shop.getDefaultAppointmentDurationMinutes() == null
|| shop.getDefaultAppointmentDurationMinutes() <= 0 ? 60 : shop.getDefaultAppointmentDurationMinutes());
return result;
@@ -252,12 +256,17 @@ public class ShopServiceImpl extends ServiceImpl<ShopMapper, ShopDO> implements
if (shop == null || Integer.valueOf(1).equals(shop.getIsDelete())) {
throw new IllegalArgumentException("门店不存在");
}
String businessHours = normalizeAppointmentBusinessHours(settings.getBusinessHours());
Integer duration = settings.getDefaultAppointmentDurationMinutes();
if (duration == null || duration < 15 || duration > 720) {
throw new IllegalArgumentException("默认预约时长需在15至720分钟之间");
}
shop.setAppointmentBusinessHours(businessHours);
shopBusinessScheduleService.save(id, settings.getWeeklyHours(), settings.getBusinessHours());
List<com.xiaowang.jayucloud.salon.core.modules.shop.vo.ShopBusinessHoursDayVO> weeklyHours = shopBusinessScheduleService.list(
id, StringUtils.hasText(settings.getBusinessHours()) ? settings.getBusinessHours() : shop.getBusinessHours());
String firstOpenHours = weeklyHours.stream().filter(day -> Boolean.TRUE.equals(day.getOpen()))
.sorted(java.util.Comparator.comparing(com.xiaowang.jayucloud.salon.core.modules.shop.vo.ShopBusinessHoursDayVO::getDayOfWeek))
.map(day -> day.getStartTime() + "-" + day.getEndTime()).findFirst().orElse(null);
shop.setAppointmentBusinessHours(firstOpenHours);
shop.setDefaultAppointmentDurationMinutes(duration);
return shopMapper.updateById(shop) > 0;
}
@@ -1,6 +1,7 @@
package com.xiaowang.jayucloud.salon.core.modules.shop.vo;
import lombok.Data;
import java.util.List;
@Data
public class ShopAppointmentSettingsVO {
@@ -9,4 +10,5 @@ public class ShopAppointmentSettingsVO {
private String pendingShopName;
private String businessHours;
private Integer defaultAppointmentDurationMinutes;
private List<ShopBusinessHoursDayVO> weeklyHours;
}
@@ -0,0 +1,11 @@
package com.xiaowang.jayucloud.salon.core.modules.shop.vo;
import lombok.Data;
@Data
public class ShopBusinessHoursDayVO {
private Integer dayOfWeek;
private Boolean open;
private String startTime;
private String endTime;
}
@@ -26,6 +26,9 @@ import java.util.stream.Collectors;
* Usage: reference this class from the owning layer and pass validated inputs before reading or updating related state.
*/
public class SystemParameterConfigServiceImpl implements SystemParameterConfigService {
private static final String STORAGE_READ_ORDER_GROUP = "FILE";
private static final String STORAGE_READ_ORDER_KEY = "IMAGE_READ_PROVIDER_ORDER";
private static final java.util.Set<String> STORAGE_PROVIDERS = java.util.Set.of("MINIO", "QINIU_KODO", "ALIYUN_OSS");
/**
* Purpose: configMapper supports SystemParameterConfigServiceImpl.java by holding or executing the config mapper business role.
@@ -69,6 +72,12 @@ public class SystemParameterConfigServiceImpl implements SystemParameterConfigSe
if ("MAP".equals(group)) {
throw new IllegalArgumentException("地图密钥已迁移至安全接入配置,不允许通过通用参数接口读写");
}
if (STORAGE_READ_ORDER_KEY.equals(key)) {
if (!STORAGE_READ_ORDER_GROUP.equals(group)) {
throw new IllegalArgumentException("对象存储读取顺序只能保存在 FILE 配置分组");
}
validateStorageReadOrder(dto.getConfigValue());
}
if (AdminDefaultPasswordSupport.isDefaultPasswordConfig(group, key)) {
AdminDefaultPasswordSupport.validateDefaultPassword(dto.getConfigValue());
}
@@ -135,6 +144,14 @@ public class SystemParameterConfigServiceImpl implements SystemParameterConfigSe
return value.trim().toUpperCase(Locale.ROOT);
}
private void validateStorageReadOrder(String value) {
List<String> providers = value == null ? Collections.emptyList() : java.util.Arrays.stream(value.split(","))
.map(String::trim).map(item -> item.toUpperCase(Locale.ROOT)).collect(Collectors.toList());
if (providers.size() != STORAGE_PROVIDERS.size() || !STORAGE_PROVIDERS.equals(new java.util.HashSet<>(providers))) {
throw new IllegalArgumentException("对象存储读取顺序必须且仅能包含 MinIO、七牛云、阿里云 OSS 各一次");
}
}
/**
* Purpose: toVO supports SystemParameterConfigServiceImpl.java by holding or executing the to vo business role.
* Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state.
@@ -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;
/**
* 用户签名
*/
@@ -27,6 +27,7 @@ import com.xiaowang.jayucloud.salon.core.modules.integration.mapper.WechatMiniBi
import com.xiaowang.jayucloud.salon.core.modules.artist.service.NailArtistInfoService;
import com.xiaowang.jayucloud.salon.core.modules.shop.service.ShopService;
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.system.service.SystemParameterConfigService;
import com.xiaowang.jayucloud.salon.core.modules.user.service.UserService;
import com.xiaowang.jayucloud.salon.core.modules.auth.service.VerificationCodeService;
@@ -38,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;
@@ -157,6 +159,7 @@ public class UserServiceImpl extends ServiceImpl<UserMapper, UserDO> implements
*/
private final ShopService shopService;
private final ShopBusinessExpiryService shopBusinessExpiryService;
private final ShopBusinessScheduleService shopBusinessScheduleService;
/**
* Variable `userPermissionMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls.
*/
@@ -1795,6 +1798,7 @@ public class UserServiceImpl extends ServiceImpl<UserMapper, UserDO> implements
shop.setBusinessExpireTime(shopBusinessExpiryService.defaultExpireTime(LocalDate.now()));
shop.setIsDelete(0);
shopMapper.insert(shop);
shopBusinessScheduleService.initializeDefault(shop.getId(), shop.getBusinessHours());
UserDO manager = new UserDO();
manager.setShopId(shop.getId());
@@ -1947,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"));
@@ -1971,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) {
@@ -1991,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());
@@ -2445,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,
@@ -2463,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;
}
@@ -0,0 +1,53 @@
-- 门店逐周营业安排,旧营业区间完整回填到周一至周日。
CREATE TABLE IF NOT EXISTS t_shop_weekly_schedule
(
shop_id bigint unsigned NOT NULL COMMENT '门店ID',
day_of_week tinyint unsigned NOT NULL COMMENT '星期:1周一至7周日',
is_open tinyint NOT NULL DEFAULT 1 COMMENT '营业状态:1营业,0休息',
start_time time NULL COMMENT '营业开始时间',
end_time time NULL COMMENT '营业结束时间',
create_time datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
update_time datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
PRIMARY KEY (shop_id, day_of_week),
KEY idx_shop_weekly_schedule_open (shop_id, is_open)
) ENGINE = InnoDB DEFAULT CHARSET = utf8mb4 COMMENT = '门店每周营业安排';
DROP TEMPORARY TABLE IF EXISTS tmp_salon_weekly_hours;
CREATE TEMPORARY TABLE tmp_salon_weekly_hours
(
shop_id bigint unsigned NOT NULL PRIMARY KEY,
start_time time NOT NULL,
end_time time NOT NULL
) ENGINE = MEMORY;
INSERT INTO tmp_salon_weekly_hours (shop_id, start_time, end_time)
SELECT source.id,
CASE
WHEN source.legacy_hours REGEXP '^([01][0-9]|2[0-3]):[0-5][0-9]-([01][0-9]|2[0-3]):[0-5][0-9]$'
AND STR_TO_DATE(SUBSTRING_INDEX(source.legacy_hours, '-', 1), '%H:%i')
< STR_TO_DATE(SUBSTRING_INDEX(source.legacy_hours, '-', -1), '%H:%i')
THEN STR_TO_DATE(SUBSTRING_INDEX(source.legacy_hours, '-', 1), '%H:%i')
ELSE '10:00:00'
END,
CASE
WHEN source.legacy_hours REGEXP '^([01][0-9]|2[0-3]):[0-5][0-9]-([01][0-9]|2[0-3]):[0-5][0-9]$'
AND STR_TO_DATE(SUBSTRING_INDEX(source.legacy_hours, '-', 1), '%H:%i')
< STR_TO_DATE(SUBSTRING_INDEX(source.legacy_hours, '-', -1), '%H:%i')
THEN STR_TO_DATE(SUBSTRING_INDEX(source.legacy_hours, '-', -1), '%H:%i')
ELSE '22:00:00'
END
FROM (
SELECT id, COALESCE(NULLIF(appointment_business_hours, ''), NULLIF(business_hours, ''), '10:00-22:00') AS legacy_hours
FROM t_shop
WHERE is_delete = 0
) source;
INSERT IGNORE INTO t_shop_weekly_schedule (shop_id, day_of_week, is_open, start_time, end_time)
SELECT legacy.shop_id, days.day_of_week, 1, legacy.start_time, legacy.end_time
FROM tmp_salon_weekly_hours legacy
CROSS JOIN (
SELECT 1 AS day_of_week UNION ALL SELECT 2 UNION ALL SELECT 3 UNION ALL
SELECT 4 UNION ALL SELECT 5 UNION ALL SELECT 6 UNION ALL SELECT 7
) days;
DROP TEMPORARY TABLE IF EXISTS tmp_salon_weekly_hours;
@@ -0,0 +1,31 @@
SET @column_exists = (
SELECT COUNT(1)
FROM information_schema.columns
WHERE table_schema = DATABASE()
AND table_name = 't_content_moderation_image_task'
AND column_name = 'source_env_version'
);
SET @migration_sql = IF(
@column_exists = 0,
'ALTER TABLE t_content_moderation_image_task ADD COLUMN source_env_version VARCHAR(20) NOT NULL DEFAULT ''LEGACY'' COMMENT ''小程序来源环境:develop/trial/release/UNKNOWN;历史任务为LEGACY'' AFTER file_id',
'SELECT 1'
);
PREPARE migration_statement FROM @migration_sql;
EXECUTE migration_statement;
DEALLOCATE PREPARE migration_statement;
INSERT INTO t_system_parameter_config (
id, config_group, config_key, config_name, config_value, enabled, remark,
create_time, update_time, is_delete
)
VALUES (
313931273555139021, 'FILE', 'IMAGE_READ_PROVIDER_ORDER', '对象存储图片读取优先级',
'MINIO,QINIU_KODO,ALIYUN_OSS', 1,
'仅作用于签名访问 URL 生成和可用副本回退;不影响上传和副本修复顺序',
NOW(), NOW(), 0
)
ON DUPLICATE KEY UPDATE
config_name = VALUES(config_name),
remark = VALUES(remark),
is_delete = 0,
update_time = NOW();
@@ -0,0 +1,126 @@
package com.xiaowang.jayucloud.salon.core.modules.file.service.impl;
import com.xiaowang.jayucloud.salon.core.config.ObjectStorageProperties;
import com.xiaowang.jayucloud.salon.core.modules.file.entity.ObjectStorageFileDO;
import com.xiaowang.jayucloud.salon.core.modules.file.entity.ObjectStorageReplicaDO;
import com.xiaowang.jayucloud.salon.core.modules.file.service.ObjectStorageProvider;
import com.xiaowang.jayucloud.salon.core.modules.file.service.ObjectStorageReplicaService;
import com.xiaowang.jayucloud.salon.core.modules.system.service.SystemParameterConfigService;
import org.junit.jupiter.api.Test;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.util.List;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyLong;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.inOrder;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
class ObjectStorageOrchestrationServiceImplTest {
@Test
void savedOrderControlsSignedUrlsButNotUploadPreference() throws Exception {
ObjectStorageProvider minio = provider("MINIO", "minio");
ObjectStorageProvider qiniu = provider("QINIU_KODO", "qiniu");
ObjectStorageProvider oss = provider("ALIYUN_OSS", "oss");
ObjectStorageProperties properties = new ObjectStorageProperties();
properties.setProviderOrder(List.of("MINIO", "QINIU_KODO", "ALIYUN_OSS"));
properties.setReplicaRequiredProviders(List.of("MINIO", "QINIU_KODO", "ALIYUN_OSS"));
ObjectStorageReplicaService replicaService = mock(ObjectStorageReplicaService.class);
ObjectStorageReplicaDO minioReplica = replica("MINIO");
ObjectStorageReplicaDO qiniuReplica = replica("QINIU_KODO");
ObjectStorageReplicaDO ossReplica = replica("ALIYUN_OSS");
when(replicaService.listByFileId(7L)).thenReturn(List.of(minioReplica, qiniuReplica, ossReplica));
SystemParameterConfigService configService = mock(SystemParameterConfigService.class);
when(configService.getEnabledValue("FILE", "IMAGE_READ_PROVIDER_ORDER"))
.thenReturn("ALIYUN_OSS,QINIU_KODO,MINIO");
ObjectStorageOrchestrationServiceImpl service = new ObjectStorageOrchestrationServiceImpl(
List.of(minio, qiniu, oss), properties, replicaService, configService);
assertEquals("oss:signed", service.getPresignedUrl(7L, "object", 5));
service.uploadPrimary(new ByteArrayInputStream(new byte[] {1}), 1, "image/png", "object");
verify(oss).getPresignedUrl("oss-object", 5);
verify(minio, never()).getPresignedUrl(any(), any());
verify(minio).uploadStream(any(InputStream.class), eq(1L), eq("image/png"), eq("object"));
verify(configService).getEnabledValue("FILE", "IMAGE_READ_PROVIDER_ORDER");
}
@Test
void signedUrlFallsBackToNextConfiguredReadableReplica() throws Exception {
ObjectStorageProvider minio = provider("MINIO", "minio");
ObjectStorageProvider qiniu = provider("QINIU_KODO", "qiniu");
ObjectStorageProvider oss = provider("ALIYUN_OSS", "oss");
when(oss.getPresignedUrl("oss-object", 5)).thenThrow(new IllegalStateException("OSS unavailable"));
when(qiniu.getPresignedUrl("qiniu_kodo-object", 5)).thenReturn("qiniu:signed");
ObjectStorageProperties properties = new ObjectStorageProperties();
properties.setProviderOrder(List.of("MINIO", "QINIU_KODO", "ALIYUN_OSS"));
ObjectStorageReplicaService replicaService = mock(ObjectStorageReplicaService.class);
when(replicaService.listByFileId(8L)).thenReturn(List.of(
replica("MINIO"), replica("QINIU_KODO"), replica("ALIYUN_OSS")));
SystemParameterConfigService configService = mock(SystemParameterConfigService.class);
when(configService.getEnabledValue("FILE", "IMAGE_READ_PROVIDER_ORDER"))
.thenReturn("ALIYUN_OSS,QINIU_KODO,MINIO");
ObjectStorageOrchestrationServiceImpl service = new ObjectStorageOrchestrationServiceImpl(
List.of(minio, qiniu, oss), properties, replicaService, configService);
assertEquals("qiniu:signed", service.getPresignedUrl(8L, "object", 5));
org.mockito.InOrder providerOrder = inOrder(oss, qiniu);
providerOrder.verify(oss).getPresignedUrl("oss-object", 5);
providerOrder.verify(qiniu).getPresignedUrl("qiniu_kodo-object", 5);
verify(minio, never()).getPresignedUrl(any(), any());
}
@Test
void replicaRepairKeepsEnvironmentSourceReadOrder() throws Exception {
ObjectStorageProvider minio = provider("MINIO", "minio");
ObjectStorageProvider qiniu = provider("QINIU_KODO", "qiniu");
ObjectStorageProvider oss = provider("ALIYUN_OSS", "oss");
when(minio.downloadFile("minio-object")).thenReturn(new ByteArrayInputStream(new byte[] {1}));
ObjectStorageProperties properties = new ObjectStorageProperties();
properties.setProviderOrder(List.of("MINIO", "QINIU_KODO", "ALIYUN_OSS"));
properties.setReplicaRequiredProviders(List.of("MINIO", "QINIU_KODO", "ALIYUN_OSS"));
ObjectStorageReplicaService replicaService = mock(ObjectStorageReplicaService.class);
when(replicaService.listByFileId(9L)).thenReturn(List.of(replica("MINIO"), replica("QINIU_KODO")));
SystemParameterConfigService configService = mock(SystemParameterConfigService.class);
when(configService.getEnabledValue("FILE", "IMAGE_READ_PROVIDER_ORDER"))
.thenReturn("ALIYUN_OSS,QINIU_KODO,MINIO");
ObjectStorageOrchestrationServiceImpl service = new ObjectStorageOrchestrationServiceImpl(
List.of(minio, qiniu, oss), properties, replicaService, configService);
ObjectStorageFileDO file = new ObjectStorageFileDO();
file.setId(9L);
file.setObjectName("object");
file.setFileSize(1L);
file.setContentType("image/png");
service.completeReplicas(file);
verify(minio).downloadFile("minio-object");
verify(qiniu, never()).downloadFile(any());
verify(oss).uploadStream(any(InputStream.class), eq(1L), eq("image/png"), eq("object"));
verify(configService, never()).getEnabledValue("FILE", "IMAGE_READ_PROVIDER_ORDER");
}
private ObjectStorageProvider provider(String code, String name) throws Exception {
ObjectStorageProvider provider = mock(ObjectStorageProvider.class);
when(provider.providerCode()).thenReturn(code);
when(provider.isEnabled()).thenReturn(true);
when(provider.getPresignedUrl("oss-object", 5)).thenReturn("oss:signed");
when(provider.uploadStream(any(InputStream.class), anyLong(), any(), any())).thenReturn(name + ":uploaded");
return provider;
}
private ObjectStorageReplicaDO replica(String code) {
ObjectStorageReplicaDO replica = new ObjectStorageReplicaDO();
replica.setProvider(code);
replica.setObjectName(code.equals("ALIYUN_OSS") ? "oss-object" : code.toLowerCase() + "-object");
replica.setUploadStatus(ObjectStorageBackupServiceImpl.UPLOAD_STATUS_SUCCEEDED);
return replica;
}
}
@@ -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());
}
}
@@ -72,7 +72,7 @@ class WechatContentModerationCallbackControllerTest {
when(crypto.verify("callback-token", "1000", "nonce", "encrypted-json", "message-signature"))
.thenReturn(true);
when(crypto.decrypt("encrypted-json", "encoding-aes-key", "mini-app-id"))
.thenReturn("{\"trace_id\":\"task-json\",\"result\":{\"suggest\":\"pass\"}}");
.thenReturn("{\"trace_id\":\"task-json\",\"result\":{\"suggest\":\"pass\"},\"extra\":\"{\\\"envVersion\\\":\\\"trial\\\"}\"}");
MockMvc mvc = MockMvcBuilders.standaloneSetup(controller(secureConfig, crypto, moderationService)).build();
mvc.perform(post("/integration/wechat/content-moderation/callback")
@@ -86,7 +86,7 @@ class WechatContentModerationCallbackControllerTest {
.andExpect(content().string("success"));
verify(crypto).verify("callback-token", "1000", "nonce", "encrypted-json", "message-signature");
verify(moderationService).handleWechatImageResult("task-json", "pass", "微信异步图片审核回调");
verify(moderationService).handleWechatImageResult("task-json", "pass", "微信异步图片审核回调", "trial");
}
@Test
@@ -98,8 +98,11 @@ class WechatContentModerationCallbackControllerTest {
when(crypto.encryptedValue(xml)).thenReturn("encrypted-xml");
when(crypto.verify("callback-token", "1000", "nonce", "encrypted-xml", "message-signature"))
.thenReturn(true);
when(crypto.decrypt("encrypted-xml", "encoding-aes-key", "mini-app-id"))
.thenReturn("{\"trace_id\":\"task-xml\",\"result\":{\"suggest\":\"review\"}}");
String decodedXml = "<xml><trace_id>task-xml</trace_id><suggest>review</suggest><extra>{&quot;envVersion&quot;:&quot;release&quot;}</extra></xml>";
when(crypto.decrypt("encrypted-xml", "encoding-aes-key", "mini-app-id")).thenReturn(decodedXml);
when(crypto.value(decodedXml, "trace_id")).thenReturn("task-xml");
when(crypto.value(decodedXml, "suggest")).thenReturn("review");
when(crypto.value(decodedXml, "extra")).thenReturn("{\"envVersion\":\"release\"}");
MockMvc mvc = MockMvcBuilders.standaloneSetup(controller(secureConfig, crypto, moderationService)).build();
mvc.perform(post("/integration/wechat/content-moderation/callback")
@@ -113,7 +116,7 @@ class WechatContentModerationCallbackControllerTest {
.andExpect(content().string("success"));
verify(crypto).verify("callback-token", "1000", "nonce", "encrypted-xml", "message-signature");
verify(moderationService).handleWechatImageResult("task-xml", "review", "微信异步图片审核回调");
verify(moderationService).handleWechatImageResult("task-xml", "review", "微信异步图片审核回调", "release");
}
private SecureIntegrationConfigService readyWechatConfig() {
@@ -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;
}
}
@@ -0,0 +1,56 @@
package com.xiaowang.jayucloud.salon.core.modules.system.service.impl;
import com.xiaowang.jayucloud.salon.core.modules.integration.service.MessageHubPushConfigService;
import com.xiaowang.jayucloud.salon.core.modules.system.dto.SystemParameterConfigDTO;
import com.xiaowang.jayucloud.salon.core.modules.system.mapper.SystemParameterConfigMapper;
import com.xiaowang.jayucloud.salon.core.modules.user.entity.UserDO;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
class SystemParameterConfigServiceImplTest {
@Test
void objectStorageReadOrderMustContainEachProviderExactlyOnce() {
SystemParameterConfigMapper mapper = mock(SystemParameterConfigMapper.class);
SystemParameterConfigServiceImpl service = new SystemParameterConfigServiceImpl(
mapper, mock(MessageHubPushConfigService.class));
UserDO admin = new UserDO();
admin.setType(4);
SystemParameterConfigDTO config = new SystemParameterConfigDTO();
config.setConfigGroup("FILE");
config.setConfigKey("IMAGE_READ_PROVIDER_ORDER");
config.setConfigName("对象存储图片读取优先级");
config.setConfigValue("MINIO,MINIO,ALIYUN_OSS");
assertThrows(IllegalArgumentException.class, () -> service.saveConfig(admin, config));
verify(mapper, never()).selectOne(any());
verify(mapper, never()).insert(any());
}
@Test
void validObjectStorageReadOrderIsSavedAsProvided() {
SystemParameterConfigMapper mapper = mock(SystemParameterConfigMapper.class);
when(mapper.selectOne(any())).thenReturn(null);
SystemParameterConfigServiceImpl service = new SystemParameterConfigServiceImpl(
mapper, mock(MessageHubPushConfigService.class));
UserDO admin = new UserDO();
admin.setType(4);
SystemParameterConfigDTO config = new SystemParameterConfigDTO();
config.setConfigGroup("FILE");
config.setConfigKey("IMAGE_READ_PROVIDER_ORDER");
config.setConfigName("对象存储图片读取优先级");
config.setConfigValue("ALIYUN_OSS,QINIU_KODO,MINIO");
service.saveConfig(admin, config);
org.mockito.ArgumentCaptor<com.xiaowang.jayucloud.salon.core.modules.system.entity.SystemParameterConfigDO> captor =
org.mockito.ArgumentCaptor.forClass(com.xiaowang.jayucloud.salon.core.modules.system.entity.SystemParameterConfigDO.class);
verify(mapper).insert(captor.capture());
org.junit.jupiter.api.Assertions.assertEquals("ALIYUN_OSS,QINIU_KODO,MINIO", captor.getValue().getConfigValue());
}
}
@@ -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),
@@ -108,7 +108,7 @@
</div>
<div class="setting-group">
<div class="setting-group__head setting-group__head--with-action"><strong>地图服务</strong><span>安全接入</span><a-button size="small" type="primary" :loading="savingMap" @click="saveMapConfig">保存地图设置</a-button></div>
<div class="setting-group__head setting-group__head--with-action"><strong>地图服务</strong><span>安全接入</span><a-button size="small" type="primary" :loading="savingMap || confirmingMap" @click="saveMapConfig">保存地图设置</a-button></div>
<div class="setting-row">
<div class="setting-copy"><strong>默认地图渠道</strong><span>店铺选点和后台地图展示使用的默认渠道。</span></div>
<div class="setting-control"><a-select v-model:value="mapProvider" :options="mapProviderOptions" /></div>
@@ -132,8 +132,8 @@
<span>{{ item.description }}</span>
</div>
<div class="setting-control setting-control--password">
<a-input-password v-model:value="mapSecrets[item.key]" :placeholder="item.placeholder" autocomplete="new-password" />
<a-button v-if="mapConfigured(item.key)" size="small" type="text" danger @click="toggleMapSecretClear(item.key)">{{ clearMapSecrets[item.key] ? '撤销清除' : '清除' }}</a-button>
<a-input-password v-model:value="mapSecrets[item.key]" :placeholder="mapKeyPlaceholder(item.key, item.placeholder)" autocomplete="new-password" @update:value="clearMapSecrets[item.key] = false" />
<a-button v-if="mapKeyStoredConfigured(item.key)" size="small" type="text" danger @click="toggleMapSecretClear(item.key)">{{ clearMapSecrets[item.key] ? '撤销清除' : '清除' }}</a-button>
</div>
<span class="status-pill" :class="{ 'is-muted': !mapConfigured(item.key) || clearMapSecrets[item.key] }">{{ clearMapSecrets[item.key] ? '保存后清除' : mapConfigured(item.key) ? '已配置' : '待配置' }}</span>
</div>
@@ -146,7 +146,7 @@
</div>
<div class="setting-group">
<div class="setting-group__head setting-group__head--with-action"><strong>微信内容审核</strong><span>安全回调</span><a-button size="small" type="primary" :loading="savingModeration" @click="saveModerationConfig">保存审核设置</a-button></div>
<div class="setting-group__head setting-group__head--with-action"><strong>微信内容审核</strong><span>安全回调</span><a-button size="small" type="primary" :loading="savingModeration || confirmingModeration" @click="saveModerationConfig">保存审核设置</a-button></div>
<div class="setting-row">
<div class="setting-copy"><strong>审核渠道</strong><span>未启用或配置不完整时,内容保持隔离,不会自动放行。</span></div>
<div class="setting-control"><a-select v-model:value="moderationProvider" :options="moderationProviderOptions" /></div>
@@ -168,7 +168,7 @@
<div class="setting-row">
<div class="setting-copy"><strong>回调 Token</strong><span>3-32 位英文字母或数字;留空表示不修改已保存值。</span></div>
<div class="setting-control setting-control--password">
<a-input-password v-model:value="moderationSecrets.callbackToken" autocomplete="new-password" :placeholder="secureStatus?.moderationCallbackTokenConfigured && !clearModerationSecrets.callbackToken ? '••••••••' : '填写新的 Token,留空保持原值'" />
<a-input-password v-model:value="moderationSecrets.callbackToken" autocomplete="new-password" :placeholder="secureStatus?.moderationCallbackTokenConfigured && !clearModerationSecrets.callbackToken ? '••••••••' : '填写新的 Token,留空保持原值'" @update:value="clearModerationSecrets.callbackToken = false" />
<a-button v-if="secureStatus?.moderationCallbackTokenConfigured" size="small" type="text" danger @click="toggleModerationSecretClear('callbackToken')">{{ clearModerationSecrets.callbackToken ? '撤销清除' : '清除' }}</a-button>
</div>
<span class="status-pill" :class="{ 'is-muted': !secureStatus?.moderationCallbackTokenConfigured || clearModerationSecrets.callbackToken }">{{ clearModerationSecrets.callbackToken ? '保存后清除' : secureStatus?.moderationCallbackTokenConfigured ? '已配置' : '待配置' }}</span>
@@ -176,7 +176,7 @@
<div class="setting-row setting-row--last">
<div class="setting-copy"><strong>EncodingAESKey</strong><span>微信平台生成的 43 位密钥;消息加密方式必须选择「安全模式」。</span></div>
<div class="setting-control setting-control--password">
<a-input-password v-model:value="moderationSecrets.encodingAesKey" autocomplete="new-password" :placeholder="secureStatus?.moderationEncodingAesKeyConfigured && !clearModerationSecrets.encodingAesKey ? '••••••••' : '填写 43 位 EncodingAESKey,留空保持原值'" />
<a-input-password v-model:value="moderationSecrets.encodingAesKey" autocomplete="new-password" :placeholder="secureStatus?.moderationEncodingAesKeyConfigured && !clearModerationSecrets.encodingAesKey ? '••••••••' : '填写 43 位 EncodingAESKey,留空保持原值'" @update:value="clearModerationSecrets.encodingAesKey = false" />
<a-button v-if="secureStatus?.moderationEncodingAesKeyConfigured" size="small" type="text" danger @click="toggleModerationSecretClear('encodingAesKey')">{{ clearModerationSecrets.encodingAesKey ? '撤销清除' : '清除' }}</a-button>
</div>
<span class="status-pill" :class="{ 'is-muted': !secureStatus?.moderationEncodingAesKeyConfigured || clearModerationSecrets.encodingAesKey }">{{ clearModerationSecrets.encodingAesKey ? '保存后清除' : secureStatus?.moderationEncodingAesKeyConfigured ? '已配置' : '待配置' }}</span>
@@ -199,14 +199,32 @@
</div>
</div>
<div class="setting-group">
<div class="setting-group__head setting-group__head--with-action"><strong>短信服务</strong><span>SMS</span><a-button size="small" type="primary" :loading="savingSmsProvider" @click="saveSmsProvider">保存短信设置</a-button></div>
<div class="setting-row setting-row--last">
<div class="setting-copy"><strong>短信供应商</strong><span>统一控制登录、绑定和找回密码的验证码通道。</span></div>
<div class="setting-control"><a-select v-model:value="smsProviderForm.configValue" :options="smsProviderOptions" /></div>
<span class="warning-note">切换会影响全部验证码</span>
<div class="setting-group">
<div class="setting-group__head setting-group__head--with-action"><strong>对象存储读取顺序</strong><span>FILE</span><a-button size="small" type="primary" :loading="savingStorageReadOrder" @click="saveStorageReadOrder">保存读取顺序</a-button></div>
<div class="setting-row setting-row--last storage-order-row">
<div class="setting-copy"><strong>MinIO、七牛云、阿里云 OSS</strong><span>头像、作品等资源都按此顺序生成签名访问地址并回退可用副本;不改变上传首选、三副本要求和副本修复顺序。</span></div>
<div class="storage-order-list" aria-label="对象存储读取优先级">
<div v-for="(provider, index) in storageReadOrder" :key="provider.code" class="storage-order-item">
<span class="storage-order-index">{{ index + 1 }}</span>
<strong>{{ provider.label }}</strong>
<div class="storage-order-actions">
<a-button size="small" type="text" :disabled="index === 0" :aria-label="`上移${provider.label}`" @click="moveStorageProvider(index, -1)"><ArrowUpOutlined /></a-button>
<a-button size="small" type="text" :disabled="index === storageReadOrder.length - 1" :aria-label="`下移${provider.label}`" @click="moveStorageProvider(index, 1)"><ArrowDownOutlined /></a-button>
</div>
</div>
</div>
<span class="control-note">最多 30 秒同步至其他服务实例</span>
</div>
</div>
<div class="setting-group">
<div class="setting-group__head setting-group__head--with-action"><strong>短信服务</strong><span>SMS</span><a-button size="small" type="primary" :loading="savingSmsProvider" @click="saveSmsProvider">保存短信设置</a-button></div>
<div class="setting-row setting-row--last">
<div class="setting-copy"><strong>短信供应商</strong><span>统一控制登录、绑定和找回密码的验证码通道。</span></div>
<div class="setting-control"><a-select v-model:value="smsProviderForm.configValue" :options="smsProviderOptions" /></div>
<span class="warning-note">切换会影响全部验证码</span>
</div>
</div>
</div>
</section>
<section v-else class="settings-section-panel">
@@ -245,8 +263,8 @@
<script setup lang="ts">
import { computed, onMounted, reactive, ref } from 'vue'
import { useRoute } from 'vue-router'
import { message } from 'ant-design-vue'
import { ApiOutlined, CopyOutlined, ExportOutlined, SettingOutlined, UserOutlined } from '@ant-design/icons-vue'
import { message, Modal } from 'ant-design-vue'
import { ApiOutlined, ArrowDownOutlined, ArrowUpOutlined, CopyOutlined, ExportOutlined, SettingOutlined, UserOutlined } from '@ant-design/icons-vue'
import { adminSecureIntegrationConfigApi, adminSystemParameterConfigApi, type SecureIntegrationConfigVO, type SystemParameterConfigVO } from '@/api/admin'
import { ADMIN_API_BASE_URL } from '@/config/api'
import { loadCachedAdminUserInfo } from '@/utils/admin-session'
@@ -263,7 +281,15 @@ const savingManagerReviewMode = ref(false)
const savingShopValidity = ref(false)
const savingMap = ref(false)
const savingModeration = ref(false)
const confirmingMap = ref(false)
const confirmingModeration = ref(false)
const savingSmsProvider = ref(false)
const savingStorageReadOrder = ref(false)
const storageReadOrder = ref([
{ code: 'MINIO', label: 'MinIO' },
{ code: 'QINIU_KODO', label: '七牛云' },
{ code: 'ALIYUN_OSS', label: '阿里云 OSS' }
])
const defaultPasswordEnabled = ref(true)
const reviewNoticeEnabled = ref(true)
const managerAutoApproveEnabled = ref(false)
@@ -356,20 +382,36 @@ const defaultCallbackUrl = () => {
const mapConfigured = (key: MapKey) => {
if (clearMapSecrets[key]) return false
if (mapSecrets[key]) return true
return mapKeyStoredConfigured(key)
}
const mapKeyStoredConfigured = (key: MapKey) => {
if (!secureStatus.value) return false
return key === 'tencentWeb' ? secureStatus.value.tencentWebKeyConfigured
: key === 'amapWeb' ? secureStatus.value.amapWebKeyConfigured
: secureStatus.value.amapMiniKeyConfigured
}
const mapKeyPlaceholder = (key: MapKey, fallback: string) =>
mapKeyStoredConfigured(key) && !clearMapSecrets[key] ? '••••••••' : fallback
const confirmSecureKeyChanges = (title: string, changes: string[]) => new Promise<boolean>(resolve => {
Modal.confirm({
title,
content: `${changes.join(';')}。确认后将立即应用到当前环境。`,
okText: '确认保存',
cancelText: '取消',
onOk: () => resolve(true),
onCancel: () => resolve(false)
})
})
const load = async () => {
loading.value = true
try {
const [userConfigs, smsConfigs, workbenchConfigs, shopConfigs, secureConfig] = await Promise.all([
const [userConfigs, smsConfigs, workbenchConfigs, shopConfigs, fileConfigs, secureConfig] = await Promise.all([
adminSystemParameterConfigApi.listConfigs('USER'),
adminSystemParameterConfigApi.listConfigs('SMS'),
adminSystemParameterConfigApi.listConfigs('WORKBENCH'),
adminSystemParameterConfigApi.listConfigs('SHOP'),
adminSystemParameterConfigApi.listConfigs('FILE'),
adminSecureIntegrationConfigApi.getConfig()
])
const defaultPassword = userConfigs.find(item => item.configKey === 'DEFAULT_PASSWORD')
@@ -394,6 +436,17 @@ const load = async () => {
Object.assign(shopValidityForm, shopValidity)
shopDefaultValidDays.value = String(shopValidity.configValue || '30')
}
const storageOrder = fileConfigs.find(item => item.configKey === 'IMAGE_READ_PROVIDER_ORDER')
if (storageOrder?.configValue) {
const labels = { MINIO: 'MinIO', QINIU_KODO: '七牛云', ALIYUN_OSS: '阿里云 OSS' } as const
const order = storageOrder.configValue.split(',').map(code => code.trim().toUpperCase())
const providers = order.flatMap(code => code in labels
? [{ code: code as keyof typeof labels, label: labels[code as keyof typeof labels] }]
: [])
if (order.length === 3 && new Set(order).size === 3 && providers.length === 3) {
storageReadOrder.value = providers
}
}
secureStatus.value = secureConfig
mapProvider.value = secureConfig.mapProvider === 'AMAP' ? 'AMAP' : 'TENCENT'
mapEnabled.value = Boolean(secureConfig.mapEnabled)
@@ -490,6 +543,21 @@ const saveMapConfig = async () => {
message.warning('当前默认渠道的 Key 已标记清除,请同时停用地图服务后再保存')
return
}
const secretChanges = mapKeyRows.flatMap(item => {
if (clearMapSecrets[item.key]) return [`${item.label}将被清除`]
if (!mapSecrets[item.key].trim()) return []
return [`${item.label}将${mapKeyStoredConfigured(item.key) ? '替换当前配置' : '保存新配置'}`]
})
if (secretChanges.length) {
confirmingMap.value = true
let confirmed = false
try {
confirmed = await confirmSecureKeyChanges('确认保存地图 Key', secretChanges)
} finally {
confirmingMap.value = false
}
if (!confirmed) return
}
savingMap.value = true
try {
const result = await adminSecureIntegrationConfigApi.saveMapConfig({
@@ -534,6 +602,20 @@ const saveModerationConfig = async () => {
message.warning('EncodingAESKey 需要为 43 位字符')
return
}
const moderationSecretChanges = [
clearModerationSecrets.callbackToken ? '回调 Token 将被清除' : moderationSecrets.callbackToken.trim() ? `回调 Token 将${secureStatus.value?.moderationCallbackTokenConfigured ? '替换当前配置' : '保存新配置'}` : '',
clearModerationSecrets.encodingAesKey ? 'EncodingAESKey 将被清除' : moderationSecrets.encodingAesKey.trim() ? `EncodingAESKey 将${secureStatus.value?.moderationEncodingAesKeyConfigured ? '替换当前配置' : '保存新配置'}` : ''
].filter(Boolean)
if (moderationSecretChanges.length) {
confirmingModeration.value = true
let confirmed = false
try {
confirmed = await confirmSecureKeyChanges('确认保存微信审核密钥', moderationSecretChanges)
} finally {
confirmingModeration.value = false
}
if (!confirmed) return
}
savingModeration.value = true
try {
secureStatus.value = await adminSecureIntegrationConfigApi.saveModerationConfig({
@@ -582,6 +664,37 @@ const saveSmsProvider = async () => {
}
}
const moveStorageProvider = (index: number, offset: number) => {
const targetIndex = index + offset
if (targetIndex < 0 || targetIndex >= storageReadOrder.value.length) return
const next = [...storageReadOrder.value]
const currentProvider = next[index]
const targetProvider = next[targetIndex]
if (!currentProvider || !targetProvider) return
next[index] = targetProvider
next[targetIndex] = currentProvider
storageReadOrder.value = next
}
const saveStorageReadOrder = async () => {
savingStorageReadOrder.value = true
try {
await adminSystemParameterConfigApi.saveConfig({
configGroup: 'FILE',
configKey: 'IMAGE_READ_PROVIDER_ORDER',
configName: '对象存储图片读取优先级',
configValue: storageReadOrder.value.map(provider => provider.code).join(','),
enabled: 1,
remark: '仅作用于签名访问 URL 生成和可用副本回退;不影响上传和副本修复顺序'
})
message.success('图片读取顺序已保存,其他服务实例将在 30 秒内同步')
} catch (error) {
message.error(error instanceof Error ? error.message : '图片读取顺序保存失败')
} finally {
savingStorageReadOrder.value = false
}
}
onMounted(() => {
void load()
})
@@ -629,6 +742,13 @@ onMounted(() => {
.setting-control--joined > :deep(.ant-input) { flex: 1; min-width: 0; }
.setting-control--joined > :deep(.ant-btn) { flex: 0 0 auto; }
.setting-control--number { width: min(220px, 100%); }
.storage-order-row { grid-template-columns: minmax(170px, 1fr) minmax(220px, 1.35fr) auto; }
.storage-order-list { display: grid; gap: 5px; min-width: 0; }
.storage-order-item { display: flex; align-items: center; gap: 9px; min-height: 34px; padding: 3px 7px; border: 1px solid var(--admin-mobile-border); border-radius: 7px; background: var(--theme-card-bg); }
.storage-order-index { display: inline-flex; width: 20px; height: 20px; align-items: center; justify-content: center; border-radius: 50%; background: var(--admin-mobile-accent-soft); color: var(--theme-primary-action); font-size: 11px; font-weight: 750; }
.storage-order-item strong { flex: 1; color: var(--admin-mobile-ink); font-size: 12px; }
.storage-order-actions { display: flex; }
.storage-order-actions :deep(.ant-btn) { width: 26px; height: 26px; padding: 0; }
.control-note { color: var(--admin-mobile-muted); font-size: 11px; white-space: nowrap; }
.setting-row > .control-note { max-width: 100%; white-space: normal; overflow-wrap: anywhere; }
.setting-value { min-width: 0; color: var(--admin-mobile-ink); font-size: 13px; font-weight: 650; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
@@ -662,6 +782,7 @@ onMounted(() => {
.setting-group__head--with-action .ant-btn { width: 100%; margin-left: 0; }
.setting-row { grid-template-columns: 1fr; gap: 9px; padding: 13px 12px; }
.setting-control { width: 100%; }
.storage-order-row { grid-template-columns: 1fr; }
.status-pill, .warning-note, .control-note { justify-self: start; }
}
</style>
+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
}
@@ -924,7 +924,8 @@ button.full{
display: grid;
min-width: 0;
flex: 1;
grid-template-columns: minmax(0, 1.15fr) minmax(0, 1fr) minmax(0, 1.1fr);
/* grid-template-columns: minmax(0, 1.15fr) minmax(0, 1fr) minmax(0, 1.1fr); */
grid-template-columns: repeat(2, minmax(0, 1fr));
gap: 12rpx;
}
@@ -1,4 +1,6 @@
const assert = require('assert')
const fs = require('fs')
const path = require('path')
const modalChoices = []
const toasts = []
@@ -37,6 +39,11 @@ function createPage() {
}
async function run() {
const styles = fs.readFileSync(path.join(__dirname, 'index.wxss'), 'utf8')
assert(styles.includes('min-width: 0;'))
assert(styles.includes('flex-wrap: wrap;'))
assert(styles.includes('@media (max-width: 390px)'))
assert(styles.includes('text-overflow: ellipsis;'))
const employeesApi = require('../../api/employees')
const planningApi = require('../../api/planning')
const application = {
@@ -98,6 +98,8 @@
.review-item {
gap: 14rpx;
min-width: 0;
flex-wrap: wrap;
padding: 18rpx;
border-radius: 20rpx;
background: #fff;
@@ -115,6 +117,7 @@
.review-info {
min-width: 0;
flex: 1;
overflow: hidden;
}
.review-name {
@@ -141,6 +144,7 @@
.review-actions {
flex: 0 0 auto;
gap: 8rpx;
margin-left: auto;
}
.review-action {
@@ -178,6 +182,23 @@
color: #a8554e;
}
@media (max-width: 390px) {
.review-item {
align-items: flex-start;
}
.review-info {
max-width: calc(100% - 100rpx);
}
.review-actions {
width: 100%;
justify-content: flex-end;
padding-left: 86rpx;
box-sizing: border-box;
}
}
.review-retry {
width: 150rpx;
min-width: 150rpx;
+4 -4
View File
@@ -148,7 +148,6 @@ Page({
if (this.data.loading || !(await this.ensureCanLogin())) return
this._presentedLoginState = ''
// 订阅授权是可选的,拒绝时仍继续登录;调用必须发生在用户点击登录链路中。
await requestSubscribeMessages()
const rememberMe = await this.chooseRememberMode()
if (rememberMe === null) return
this.setData({ rememberMe, loading: true })
@@ -166,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)
@@ -231,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 {
@@ -239,7 +238,7 @@ Page({
}
},
finishLogin(result) {
async finishLogin(result, requestSubscription = true) {
this._presentedLoginState = ''
getApp().setSession(result, true)
auth.setLoginPreference(this.data.rememberMe ? {
@@ -247,6 +246,7 @@ Page({
preferredShopId: result.userInfo && result.userInfo.shopId,
agreementVersions: this.agreementPayload().agreementVersions
} : { rememberMe: false })
if (requestSubscription) await requestSubscribeMessages()
wx.reLaunch({ url: '/pages/planning/index' })
}
})
+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,
+38 -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,28 @@ async function run() {
assert.strictEqual(page.data.contentStatusReason, '图片审核仍在处理')
assert.strictEqual(page.data.step, 3)
const registerMarkup = require('fs').readFileSync(require('path').join(__dirname, 'index.wxml'), 'utf8')
assert(registerMarkup.includes('可从微信昵称中选择'))
assert(registerMarkup.includes('点击主动选择微信头像'))
assert(registerMarkup.includes('头像会先上传并完成资料登记'))
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="可填写希望展示的昵称" /><text class="field-hint">点击输入框可从微信昵称中选择,也可以手动填写。</text></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><text class="field-hint">头像会先上传并完成资料登记,提交时只引用已上传的文件。</text></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; }
+3 -2
View File
@@ -1,4 +1,4 @@
const { API_DOMAIN, REQUEST_TIMEOUT, ENABLE_REQUEST_SIGNING } = require('./config')
const { API_DOMAIN, REQUEST_TIMEOUT, ENABLE_REQUEST_SIGNING, ENV_VERSION } = require('./config')
const auth = require('./auth')
const { sha256Hex, hmacSha256Hex, buildCanonicalParams, buildJsonPayload, randomNonce } = require('./crypto')
@@ -156,7 +156,8 @@ function request(options) {
header: {
'Content-Type': 'application/json',
...signatureHeaders,
...(options.header || {})
...(options.header || {}),
'X-Mini-Program-Env-Version': ENV_VERSION
},
success(response) {
if (response.statusCode === 401) {
+1
View File
@@ -49,6 +49,7 @@ async function run() {
auth.setSession({ accessToken: 'expired-token' }, true)
await rejectWithUnauthorized({ url: '/user/wechat-mini/quick-login' })
assert.strictEqual(requests[requests.length - 1].header['X-Mini-Program-Env-Version'], 'develop')
assert.strictEqual(clearedSessions, 0)
assert.deepStrictEqual(navigations, [])
+2 -2
View File
@@ -1,4 +1,4 @@
const { API_DOMAIN, REQUEST_TIMEOUT } = require('./config')
const { API_DOMAIN, REQUEST_TIMEOUT, ENV_VERSION } = require('./config')
const request = require('./request')
function normalizeUploadResponse(response, fallbackMessage, url) {
@@ -56,7 +56,7 @@ function uploadFile(options) {
name: options.name,
timeout: options.timeout || REQUEST_TIMEOUT,
formData: options.formData || {},
header: signatureHeaders,
header: { ...signatureHeaders, 'X-Mini-Program-Env-Version': ENV_VERSION },
success(response) {
try {
let parsedData = {}
+1
View File
@@ -41,6 +41,7 @@ async function run() {
})
assert.strictEqual(uploadOptions.url, 'http://127.0.0.1:80/api/user/workbench/register/avatar')
assert.strictEqual(uploadOptions.header['X-Mini-Program-Env-Version'], 'develop')
assert.strictEqual(result.fileId, '9223372036854775001')
assert.strictEqual(result.id, '9223372036854775002')
@@ -0,0 +1,20 @@
# Salon 图片读取渠道优先级配置说明
更新时间:2026-11-03
## 配置入口
平台管理员进入后台「系统设置 → 服务接入 → 图片读取渠道」,可调整 MinIO、七牛云、阿里云 OSS 的读取顺序并保存。保存值使用 `FILE/IMAGE_READ_PROVIDER_ORDER` 系统参数,三个渠道必须各出现一次。
## 生效范围
- 顺序仅控制对象存储签名访问 URL 的首选渠道和副本不可用时的回退顺序。
- 上传首选、三副本要求和补副本时的源文件读取顺序仍由当前环境配置管理,不受后台排序影响。
- Core 实例缓存最长 30 秒,其他实例会在 30 秒内从当前环境数据库同步新顺序;未配置或值校验失败时回退到当前环境对象存储 `provider-order`。
- 数据库初始化由 Salon Core 启动时的 Flyway V14 迁移完成,部署流水线不直接连接数据库执行 SQL。
## 微信审核来源版本
小程序请求会携带微信运行时 `develop`、`trial` 或 `release` 环境标识。异步图片审核将环境标识编码在微信 `extra` 字段并保存在逐图任务中,重试复用原版本。回调只有在返回的 `extra` 与任务环境一致时才更新审核任务;缺失或不匹配不会改变审核结论。该值只用于来源识别,不参与身份鉴权或内容审核决策。旧版迁移前创建的任务标记为 `LEGACY`,兼容未携带 `extra` 的旧回调。
非小程序请求或无法识别的版本使用 `UNKNOWN`。不要将该字段作为安全边界。
@@ -0,0 +1,15 @@
# Salon 小程序地图选点配置说明
## 小程序代码配置
- `JC-Salon-WeChat/app.json` 声明了 `chooseLocation` 隐私接口。
- 店长注册页仅在用户点击“地图选点”后调用微信地图选点;取消选点不会阻止注册,门店地址仍可手动输入。
- 用户确认选点后,提交门店地址、经度和纬度;手动修改地址时清除此前坐标,避免地址与坐标不一致。
## 微信公众平台发布前检查
1. 在小程序后台的用户隐私保护指引中,如实说明门店注册时由用户主动选择位置,供门店展示和预约导航使用。
2. 核对小程序隐私接口声明包含 `chooseLocation`,并按微信后台提示完成隐私保护指引审核/更新。
3. 上传体验版后,在真机上分别验证允许选点、取消选点和手动填写地址;没有选择位置时仍可继续注册。
本功能不会在后台静默读取设备位置,也不会因用户取消选点而拦截注册。微信公众平台配置需由具备小程序管理权限的人员完成。
@@ -95,6 +95,7 @@ MessageHub 的地址、交换机、路由和来源系统放在对应环境 `core
- Flyway V10 增加门店预约运营营业时间和默认预约时长字段;老门店时长初始化为60分钟,迁移可重复执行,不修改冻结初始化 SQL。店长通过独立预约运营设置接口保存营业时间和时长,不触发门店公开资料审核;门店名称仍通过内容审核流程提交。普通预约时长优先使用明确选择值、再使用款式时长、最后使用门店默认值;历史日期和已过时间由小程序与 Core 双重拒绝,需转历史补单。
- 预约选择客户使用门店范围专用接口返回完整联系电话,普通客户列表仍脱敏;客户预约建档与客户页保持姓名/微信号/手机号三字段完全一致才判重。预约日历以门店运营营业时间生成可选时段;接口无有效营业时间时不生成默认时段,页面明确提示先到店铺设置完成配置。
- 微信订阅消息使用三个固定小程序模板:新建/分配预约发送“预约提醒”,取消发送“预约取消通知”,开始前30分钟发送“服务开始提醒”;只通知当前承接美甲师,未分配不发送。DEV 使用 Mock,SIT/PROD 使用微信 Provider;用户拒绝订阅不影响登录或预约。配置、字段映射和上线检查见 `docs/scripts/Salon微信订阅消息配置说明_20261102.md`,数据库发送日志由 V12 迁移创建。
- Flyway V14 增加微信图片审核任务来源环境版本,并种入 `FILE/IMAGE_READ_PROVIDER_ORDER` 对象存储读取优先级。后台「系统设置 → 服务接入 → 图片读取渠道」仅调整签名访问 URL 和可用副本回退顺序,不改变上传、三副本要求或副本修复读取顺序;Core 最多缓存 30 秒,缺失或非法值回退当前环境 `object-storage.provider-order`。微信异步图片审核将小程序 `develop/trial/release` 写入微信 `extra` 并保存在任务中,重试保持原版本;回调版本缺失或不匹配不改变任务结果。说明见 `docs/scripts/Salon图片读取渠道优先级配置说明_20261103.md`。
## 8. 操作前检查
+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 请求无法进入回调处理。