diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/file/service/ObjectStorageDirectUploadService.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/file/service/ObjectStorageDirectUploadService.java index 17381419..6facdae0 100644 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/file/service/ObjectStorageDirectUploadService.java +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/file/service/ObjectStorageDirectUploadService.java @@ -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); diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/file/service/impl/ObjectStorageOrchestrationServiceImpl.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/file/service/impl/ObjectStorageOrchestrationServiceImpl.java index c02c7455..ad7f4f8b 100644 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/file/service/impl/ObjectStorageOrchestrationServiceImpl.java +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/file/service/impl/ObjectStorageOrchestrationServiceImpl.java @@ -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 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 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 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 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 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 parseProviderOrder(String value) { + if (!StringUtils.hasText(value)) return Collections.emptyList(); + return validateFallbackOrder(Arrays.asList(value.split(","))); + } + + private List validateFallbackOrder(List configured) { + if (configured == null) return Collections.emptyList(); + List 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 providers; + private final long expiresAt; + + private ProviderOrderCache(List providers, long expiresAt) { + this.providers = providers; + this.expiresAt = expiresAt; + } + } + private boolean uploadReplica(ObjectStorageFileDO file, String providerCode, Map replicaMap) { ObjectStorageReplicaDTO replicaDTO = new ObjectStorageReplicaDTO(); replicaDTO.setProvider(providerCode); diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/planning/service/impl/PlanningServiceImpl.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/planning/service/impl/PlanningServiceImpl.java index e00062b8..d1102b3e 100644 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/planning/service/impl/PlanningServiceImpl.java +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/planning/service/impl/PlanningServiceImpl.java @@ -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 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 artists = listArtists(shopId, artistId); List 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 buildDaySummaries(LocalDate start, LocalDate end, List artists, - List schedules, List appointments) { + List schedules, List appointments, + Map weeklyHours) { Map> 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())) { diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/planning/support/PlanningCalendarSupport.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/planning/support/PlanningCalendarSupport.java index daa086e3..d2f579a4 100644 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/planning/support/PlanningCalendarSupport.java +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/planning/support/PlanningCalendarSupport.java @@ -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"; } diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/planning/vo/PlanningDaySummaryVO.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/planning/vo/PlanningDaySummaryVO.java index 8b00cb88..e8c64a3d 100644 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/planning/vo/PlanningDaySummaryVO.java +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/planning/vo/PlanningDaySummaryVO.java @@ -11,4 +11,7 @@ public class PlanningDaySummaryVO { private Integer unassignedCount; private List artistCounts; private String dayStatus; + private Boolean shopOpen; + private String shopStartTime; + private String shopEndTime; } diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/privacy/controller/front/WechatContentModerationCallbackController.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/privacy/controller/front/WechatContentModerationCallbackController.java index 19041638..81d2e1fd 100644 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/privacy/controller/front/WechatContentModerationCallbackController.java +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/privacy/controller/front/WechatContentModerationCallbackController.java @@ -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("微信审核回调消息体为空"); diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/privacy/entity/ContentModerationImageTaskDO.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/privacy/entity/ContentModerationImageTaskDO.java index ec535536..0836c121 100644 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/privacy/entity/ContentModerationImageTaskDO.java +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/privacy/entity/ContentModerationImageTaskDO.java @@ -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; diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/privacy/moderation/ContentModerationProvider.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/privacy/moderation/ContentModerationProvider.java index 4b92f09d..b6d3fe15 100644 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/privacy/moderation/ContentModerationProvider.java +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/privacy/moderation/ContentModerationProvider.java @@ -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); + } } diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/privacy/moderation/RoutingContentModerationProvider.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/privacy/moderation/RoutingContentModerationProvider.java index 549e254b..7a30daf8 100644 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/privacy/moderation/RoutingContentModerationProvider.java +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/privacy/moderation/RoutingContentModerationProvider.java @@ -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(); diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/privacy/moderation/WechatContentModerationProvider.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/privacy/moderation/WechatContentModerationProvider.java index a3d1da87..20fb1caa 100644 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/privacy/moderation/WechatContentModerationProvider.java +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/privacy/moderation/WechatContentModerationProvider.java @@ -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 post(String endpoint, Map payload) { String url = UriComponentsBuilder.fromHttpUrl(endpoint) .queryParam("access_token", wechatMiniClientService.getAccessTokenForContentModeration()) diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/privacy/service/ContentModerationService.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/privacy/service/ContentModerationService.java index 8b5360c0..29ffda2b 100644 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/privacy/service/ContentModerationService.java +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/privacy/service/ContentModerationService.java @@ -12,6 +12,10 @@ public interface ContentModerationService { String payloadJson, List imageFileIds); List 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(); } diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/privacy/service/impl/ContentModerationServiceImpl.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/privacy/service/impl/ContentModerationServiceImpl.java index 886f5094..8b30929e 100644 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/privacy/service/impl/ContentModerationServiceImpl.java +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/privacy/service/impl/ContentModerationServiceImpl.java @@ -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() .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 { diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/registration/dto/WorkbenchRegistrationRequestDTO.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/registration/dto/WorkbenchRegistrationRequestDTO.java index b64ec349..2afe55be 100644 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/registration/dto/WorkbenchRegistrationRequestDTO.java +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/registration/dto/WorkbenchRegistrationRequestDTO.java @@ -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; diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/registration/service/impl/WorkbenchRegistrationServiceImpl.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/registration/service/impl/WorkbenchRegistrationServiceImpl.java index 87b7e038..2c1526bf 100644 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/registration/service/impl/WorkbenchRegistrationServiceImpl.java +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/registration/service/impl/WorkbenchRegistrationServiceImpl.java @@ -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; } diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/shop/dto/ShopAppointmentSettingsDTO.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/shop/dto/ShopAppointmentSettingsDTO.java index 8ea218ea..07e951df 100644 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/shop/dto/ShopAppointmentSettingsDTO.java +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/shop/dto/ShopAppointmentSettingsDTO.java @@ -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 weeklyHours; } diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/shop/dto/ShopBusinessHoursDayDTO.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/shop/dto/ShopBusinessHoursDayDTO.java new file mode 100644 index 00000000..bdedcbe3 --- /dev/null +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/shop/dto/ShopBusinessHoursDayDTO.java @@ -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; +} diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/shop/service/ShopBusinessScheduleService.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/shop/service/ShopBusinessScheduleService.java new file mode 100644 index 00000000..634eaee2 --- /dev/null +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/shop/service/ShopBusinessScheduleService.java @@ -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 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 mapByDay(Long shopId, String legacyHours) { + Map 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 requested, String legacyHours) { + List days = requested; + if (days == null || days.isEmpty()) { + days = legacySchedule(legacyHours); + } + if (days.size() != 7) throw new IllegalArgumentException("请设置周一至周日的营业状态"); + Map 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 legacySchedule(String legacyHours) { + LocalTime[] times = parseLegacyHours(legacyHours); + LocalTime start = times == null ? DEFAULT_START : times[0]; + LocalTime end = times == null ? DEFAULT_END : times[1]; + List 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 + "格式不正确"); + } + } +} diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/shop/service/impl/ShopServiceImpl.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/shop/service/impl/ShopServiceImpl.java index 99f8e165..48cc1278 100644 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/shop/service/impl/ShopServiceImpl.java +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/shop/service/impl/ShopServiceImpl.java @@ -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 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 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 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 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 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; } diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/shop/vo/ShopAppointmentSettingsVO.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/shop/vo/ShopAppointmentSettingsVO.java index 2a039666..0511175c 100644 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/shop/vo/ShopAppointmentSettingsVO.java +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/shop/vo/ShopAppointmentSettingsVO.java @@ -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 weeklyHours; } diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/shop/vo/ShopBusinessHoursDayVO.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/shop/vo/ShopBusinessHoursDayVO.java new file mode 100644 index 00000000..05e73436 --- /dev/null +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/shop/vo/ShopBusinessHoursDayVO.java @@ -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; +} diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/system/service/impl/SystemParameterConfigServiceImpl.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/system/service/impl/SystemParameterConfigServiceImpl.java index ea6ec63a..0c7c4a43 100644 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/system/service/impl/SystemParameterConfigServiceImpl.java +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/system/service/impl/SystemParameterConfigServiceImpl.java @@ -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 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 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. diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/user/controller/front/UserController.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/user/controller/front/UserController.java index 975cb151..f7c3d46a 100644 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/user/controller/front/UserController.java +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/user/controller/front/UserController.java @@ -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 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 completeProfileImageUpload(HttpServletRequest request, @Valid @RequestBody ChunkUploadCompleteRequestDTO requestDTO) { + public Result 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 uploadProfileImage(HttpServletRequest request, @RequestParam("file") MultipartFile file) { + public Result 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; + } + /** * 重置用户密码。 */ diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/user/dto/UserDTO.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/user/dto/UserDTO.java index 3c5d7349..be38754f 100644 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/user/dto/UserDTO.java +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/user/dto/UserDTO.java @@ -48,6 +48,9 @@ public class UserDTO { */ private String avatar; + /** 当前用户本人上传的头像文件 ID。 */ + private Long avatarFileId; + /** * 用户签名 */ diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/user/service/impl/UserServiceImpl.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/user/service/impl/UserServiceImpl.java index f0d91a77..158af818 100644 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/user/service/impl/UserServiceImpl.java +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/user/service/impl/UserServiceImpl.java @@ -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 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 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 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 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 profileImages = new ArrayList<>(); addImageFileId(profileImages, content.get("avatar")); @@ -1971,11 +1987,11 @@ public class UserServiceImpl extends ServiceImpl 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 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 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 imageIds = new ArrayList<>(); addImageFileId(imageIds, storedAvatar); ContentModerationResultVO moderation = contentModerationService.assessVersion("USER_AVATAR", userId, userId, @@ -2463,6 +2479,45 @@ public class UserServiceImpl extends ServiceImpl 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); diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/user/vo/ProfileImageUploadVO.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/user/vo/ProfileImageUploadVO.java new file mode 100644 index 00000000..0e8bb136 --- /dev/null +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/user/vo/ProfileImageUploadVO.java @@ -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; +} diff --git a/JC-Salon-Core/src/main/resources/db/migration/V13__门店每周营业排班_20261103.sql b/JC-Salon-Core/src/main/resources/db/migration/V13__门店每周营业排班_20261103.sql new file mode 100644 index 00000000..754885c1 --- /dev/null +++ b/JC-Salon-Core/src/main/resources/db/migration/V13__门店每周营业排班_20261103.sql @@ -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; diff --git a/JC-Salon-Core/src/main/resources/db/migration/V14__图片读取渠道优先级和审核环境版本_20261103.sql b/JC-Salon-Core/src/main/resources/db/migration/V14__图片读取渠道优先级和审核环境版本_20261103.sql new file mode 100644 index 00000000..67b15356 --- /dev/null +++ b/JC-Salon-Core/src/main/resources/db/migration/V14__图片读取渠道优先级和审核环境版本_20261103.sql @@ -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(); diff --git a/JC-Salon-Core/src/test/java/com/xiaowang/jayucloud/salon/core/modules/file/service/impl/ObjectStorageOrchestrationServiceImplTest.java b/JC-Salon-Core/src/test/java/com/xiaowang/jayucloud/salon/core/modules/file/service/impl/ObjectStorageOrchestrationServiceImplTest.java new file mode 100644 index 00000000..1527c677 --- /dev/null +++ b/JC-Salon-Core/src/test/java/com/xiaowang/jayucloud/salon/core/modules/file/service/impl/ObjectStorageOrchestrationServiceImplTest.java @@ -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; + } +} diff --git a/JC-Salon-Core/src/test/java/com/xiaowang/jayucloud/salon/core/modules/planning/service/impl/PlanningServiceImplTest.java b/JC-Salon-Core/src/test/java/com/xiaowang/jayucloud/salon/core/modules/planning/service/impl/PlanningServiceImplTest.java index 806d1098..392b4627 100644 --- a/JC-Salon-Core/src/test/java/com/xiaowang/jayucloud/salon/core/modules/planning/service/impl/PlanningServiceImplTest.java +++ b/JC-Salon-Core/src/test/java/com/xiaowang/jayucloud/salon/core/modules/planning/service/impl/PlanningServiceImplTest.java @@ -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 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 closedWeeklySchedule() { + java.util.Map 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()); + } } diff --git a/JC-Salon-Core/src/test/java/com/xiaowang/jayucloud/salon/core/modules/privacy/controller/front/WechatContentModerationCallbackControllerTest.java b/JC-Salon-Core/src/test/java/com/xiaowang/jayucloud/salon/core/modules/privacy/controller/front/WechatContentModerationCallbackControllerTest.java index 34e592e5..f7b50956 100644 --- a/JC-Salon-Core/src/test/java/com/xiaowang/jayucloud/salon/core/modules/privacy/controller/front/WechatContentModerationCallbackControllerTest.java +++ b/JC-Salon-Core/src/test/java/com/xiaowang/jayucloud/salon/core/modules/privacy/controller/front/WechatContentModerationCallbackControllerTest.java @@ -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 = "task-xmlreview{"envVersion":"release"}"; + 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() { diff --git a/JC-Salon-Core/src/test/java/com/xiaowang/jayucloud/salon/core/modules/registration/service/impl/WorkbenchRegistrationServiceImplTest.java b/JC-Salon-Core/src/test/java/com/xiaowang/jayucloud/salon/core/modules/registration/service/impl/WorkbenchRegistrationServiceImplTest.java index 616bf0f7..c756d1a6 100644 --- a/JC-Salon-Core/src/test/java/com/xiaowang/jayucloud/salon/core/modules/registration/service/impl/WorkbenchRegistrationServiceImplTest.java +++ b/JC-Salon-Core/src/test/java/com/xiaowang/jayucloud/salon/core/modules/registration/service/impl/WorkbenchRegistrationServiceImplTest.java @@ -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); } diff --git a/JC-Salon-Core/src/test/java/com/xiaowang/jayucloud/salon/core/modules/shop/service/impl/ShopAppointmentSettingsTest.java b/JC-Salon-Core/src/test/java/com/xiaowang/jayucloud/salon/core/modules/shop/service/impl/ShopAppointmentSettingsTest.java index f1a639a1..22d4df10 100644 --- a/JC-Salon-Core/src/test/java/com/xiaowang/jayucloud/salon/core/modules/shop/service/impl/ShopAppointmentSettingsTest.java +++ b/JC-Salon-Core/src/test/java/com/xiaowang/jayucloud/salon/core/modules/shop/service/impl/ShopAppointmentSettingsTest.java @@ -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 weeklyHours(String start, String end) { + java.util.List 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 weeklyHoursVO(String start, String end) { + java.util.List 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; + } } diff --git a/JC-Salon-Core/src/test/java/com/xiaowang/jayucloud/salon/core/modules/system/service/impl/SystemParameterConfigServiceImplTest.java b/JC-Salon-Core/src/test/java/com/xiaowang/jayucloud/salon/core/modules/system/service/impl/SystemParameterConfigServiceImplTest.java new file mode 100644 index 00000000..fa284c37 --- /dev/null +++ b/JC-Salon-Core/src/test/java/com/xiaowang/jayucloud/salon/core/modules/system/service/impl/SystemParameterConfigServiceImplTest.java @@ -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 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()); + } +} diff --git a/JC-Salon-Core/src/test/java/com/xiaowang/jayucloud/salon/core/modules/user/controller/front/UserControllerPhonePrivacyTest.java b/JC-Salon-Core/src/test/java/com/xiaowang/jayucloud/salon/core/modules/user/controller/front/UserControllerPhonePrivacyTest.java index 56ec4f1a..ebfe3620 100644 --- a/JC-Salon-Core/src/test/java/com/xiaowang/jayucloud/salon/core/modules/user/controller/front/UserControllerPhonePrivacyTest.java +++ b/JC-Salon-Core/src/test/java/com/xiaowang/jayucloud/salon/core/modules/user/controller/front/UserControllerPhonePrivacyTest.java @@ -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), diff --git a/JC-Salon-Frontend/src/views/admin/SystemSettingsView.vue b/JC-Salon-Frontend/src/views/admin/SystemSettingsView.vue index 52bbe6b3..cb4c52c5 100644 --- a/JC-Salon-Frontend/src/views/admin/SystemSettingsView.vue +++ b/JC-Salon-Frontend/src/views/admin/SystemSettingsView.vue @@ -108,7 +108,7 @@
-
地图服务安全接入保存地图设置
+
地图服务安全接入保存地图设置
默认地图渠道店铺选点和后台地图展示使用的默认渠道。
@@ -132,8 +132,8 @@ {{ item.description }}
- - {{ clearMapSecrets[item.key] ? '撤销清除' : '清除' }} + + {{ clearMapSecrets[item.key] ? '撤销清除' : '清除' }}
{{ clearMapSecrets[item.key] ? '保存后清除' : mapConfigured(item.key) ? '已配置' : '待配置' }}
@@ -146,7 +146,7 @@
-
微信内容审核安全回调保存审核设置
+
微信内容审核安全回调保存审核设置
审核渠道未启用或配置不完整时,内容保持隔离,不会自动放行。
@@ -168,7 +168,7 @@
回调 Token3-32 位英文字母或数字;留空表示不修改已保存值。
- + {{ clearModerationSecrets.callbackToken ? '撤销清除' : '清除' }}
{{ clearModerationSecrets.callbackToken ? '保存后清除' : secureStatus?.moderationCallbackTokenConfigured ? '已配置' : '待配置' }} @@ -176,7 +176,7 @@
EncodingAESKey微信平台生成的 43 位密钥;消息加密方式必须选择「安全模式」。
- + {{ clearModerationSecrets.encodingAesKey ? '撤销清除' : '清除' }}
{{ clearModerationSecrets.encodingAesKey ? '保存后清除' : secureStatus?.moderationEncodingAesKeyConfigured ? '已配置' : '待配置' }} @@ -199,14 +199,32 @@
-
-
短信服务SMS保存短信设置
-
-
短信供应商统一控制登录、绑定和找回密码的验证码通道。
-
- 切换会影响全部验证码 +
+
对象存储读取顺序FILE保存读取顺序
+
+
MinIO、七牛云、阿里云 OSS头像、作品等资源都按此顺序生成签名访问地址并回退可用副本;不改变上传首选、三副本要求和副本修复顺序。
+
+
+ {{ index + 1 }} + {{ provider.label }} +
+ + +
+
+
+ 最多 30 秒同步至其他服务实例 +
+
+ +
+
短信服务SMS保存短信设置
+
+
短信供应商统一控制登录、绑定和找回密码的验证码通道。
+
+ 切换会影响全部验证码 +
-
@@ -245,8 +263,8 @@