diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/config/WebMvcConfig.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/config/WebMvcConfig.java index 174cf00c..f2cd1642 100644 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/config/WebMvcConfig.java +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/config/WebMvcConfig.java @@ -49,6 +49,7 @@ public class WebMvcConfig implements WebMvcConfigurer { "/user/wechat-mini/confirm-login", "/user/wechat-mini/status", "/user/wechat-mini/quick-login", + "/integration/wechat/content-moderation/callback", "/user/workbench/register/**", "/user/workbench/shops/available", "/user/reset-password-by-phone", diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/artist/controller/admin/AdminNailArtistController.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/artist/controller/admin/AdminNailArtistController.java index cadd683f..552d4aa3 100644 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/artist/controller/admin/AdminNailArtistController.java +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/artist/controller/admin/AdminNailArtistController.java @@ -136,7 +136,7 @@ public class AdminNailArtistController { } } - NailArtistInfoDTO saved = nailArtistInfoService.saveOrUpdateNailArtistInfo(nailArtistInfoDTO); + NailArtistInfoDTO saved = nailArtistInfoService.submitNailArtistInfo(nailArtistInfoDTO, currentUser.getId()); return Result.success(saved); } } diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/artist/controller/front/NailArtistController.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/artist/controller/front/NailArtistController.java index 7ec61a67..985cd848 100644 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/artist/controller/front/NailArtistController.java +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/artist/controller/front/NailArtistController.java @@ -39,7 +39,7 @@ public class NailArtistController { @GetMapping("/list/shop/{shopId}") public Result> listByShopId(@PathVariable Long shopId) { - return Result.success(nailArtistInfoService.getByShopId(shopId)); + return Result.success(nailArtistInfoService.listPublicByShopId(shopId)); } /** @@ -47,7 +47,7 @@ public class NailArtistController { */ @GetMapping("/get/{userId}") public Result getNailArtistInfo(@PathVariable Long userId) { - NailArtistInfoDTO nailArtistInfoDTO = nailArtistInfoService.getByUserId(userId); + NailArtistInfoDTO nailArtistInfoDTO = nailArtistInfoService.getPublicByUserId(userId); return Result.success(nailArtistInfoDTO); } diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/artist/dto/NailArtistInfoDTO.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/artist/dto/NailArtistInfoDTO.java index ce46e421..1c5ceafb 100644 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/artist/dto/NailArtistInfoDTO.java +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/artist/dto/NailArtistInfoDTO.java @@ -79,6 +79,11 @@ public class NailArtistInfoDTO { */ private String portfolio; + /** + * 对外资料审核状态,仅用于后台展示当前发布版本状态。 + */ + private String moderationStatus; + /** * 美甲师姓名(从用户表获取) */ diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/artist/entity/NailArtistInfoDO.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/artist/entity/NailArtistInfoDO.java index 039eadee..0e4e63f7 100644 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/artist/entity/NailArtistInfoDO.java +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/artist/entity/NailArtistInfoDO.java @@ -70,6 +70,12 @@ public class NailArtistInfoDO extends BaseEntity { */ private String portfolio; + /** + * 对外资料审核状态:PENDING/APPROVED/REJECTED/RETRY。 + */ + @TableField("moderation_status") + private String moderationStatus; + /** * 逻辑删除:0-未删,1-已删 */ diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/artist/service/NailArtistInfoService.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/artist/service/NailArtistInfoService.java index 4b5fc1a7..d89b45f7 100644 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/artist/service/NailArtistInfoService.java +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/artist/service/NailArtistInfoService.java @@ -33,6 +33,11 @@ public interface NailArtistInfoService extends IService { */ List getByShopId(Long shopId); + /** + * 获取对外展示的指定门店美甲师,只返回个人资料和门店审核通过的记录。 + */ + List listPublicByShopId(Long shopId); + /** * 保存或更新美甲师信息 * @param nailArtistInfoDTO 美甲师信息DTO @@ -40,12 +45,20 @@ public interface NailArtistInfoService extends IService { */ NailArtistInfoDTO saveOrUpdateNailArtistInfo(NailArtistInfoDTO nailArtistInfoDTO); + /** 保存运营字段,并将美甲师对外展示资料提交审核。 */ + NailArtistInfoDTO submitNailArtistInfo(NailArtistInfoDTO nailArtistInfoDTO, Long authorUserId); + /** * 获取所有可用的美甲师信息(前台使用) * @return 美甲师信息列表 */ List getAllAvailableNailArtists(); + /** + * 获取对外展示的指定美甲师资料。 + */ + NailArtistInfoDTO getPublicByUserId(Long userId); + NailArtistProfileVO getPublicProfile(Long artistId); List getAvailability(Long artistId); diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/artist/service/impl/NailArtistInfoServiceImpl.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/artist/service/impl/NailArtistInfoServiceImpl.java index e0aa81a4..bebc69c0 100644 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/artist/service/impl/NailArtistInfoServiceImpl.java +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/artist/service/impl/NailArtistInfoServiceImpl.java @@ -10,6 +10,8 @@ import com.xiaowang.jayucloud.salon.core.modules.order.entity.OrderArtistReviewD import com.xiaowang.jayucloud.salon.core.modules.order.entity.OrderDO; import com.xiaowang.jayucloud.salon.core.modules.order.entity.OrderItemDO; import com.xiaowang.jayucloud.salon.core.modules.product.entity.ProductDO; +import com.xiaowang.jayucloud.salon.core.modules.product.entity.TagDO; +import com.xiaowang.jayucloud.salon.core.modules.product.mapper.TagMapper; import com.xiaowang.jayucloud.salon.core.modules.shop.entity.ShopDO; import com.xiaowang.jayucloud.salon.core.modules.user.entity.UserDO; import com.xiaowang.jayucloud.salon.core.modules.artist.mapper.NailArtistInfoMapper; @@ -31,7 +33,11 @@ import com.xiaowang.jayucloud.salon.core.modules.artist.vo.NailArtistProfileVO; import com.xiaowang.jayucloud.salon.core.modules.artist.vo.NailArtistReviewVO; import com.xiaowang.jayucloud.salon.core.modules.artist.vo.NailArtistWorkVO; import com.xiaowang.jayucloud.salon.core.modules.file.vo.ObjectStorageFileVO; +import com.xiaowang.jayucloud.salon.core.modules.privacy.service.ContentModerationService; +import com.xiaowang.jayucloud.salon.core.modules.privacy.vo.ContentModerationResultVO; import com.xiaowang.jayucloud.salon.core.modules.shop.vo.ShopSimpleVO; +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.ObjectMapper; import org.springframework.beans.BeanUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; @@ -51,6 +57,7 @@ import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.Set; +import java.util.LinkedHashMap; import java.util.stream.Collectors; @Service @@ -109,6 +116,15 @@ public class NailArtistInfoServiceImpl extends ServiceImpl listPublicByShopId(Long shopId) { + if (!isPublicShop(shopId)) { + return new ArrayList<>(); + } + List serviceUserIds = userShopBindingSupport.listUserIdsByShopId(shopId, true); + if (serviceUserIds.isEmpty()) { + return new ArrayList<>(); + } + List users = userMapper.selectList(new LambdaQueryWrapper() + .in(UserDO::getId, serviceUserIds) + .eq(UserDO::getType, 3) + .eq(UserDO::getStatus, 1) + .eq(UserDO::getIsDelete, 0) + .eq(UserDO::getProfileModerationStatus, "APPROVED") + .orderByAsc(UserDO::getCreateTime) + .orderByAsc(UserDO::getId)); + List result = new ArrayList<>(); + ShopDO shop = shopMapper.selectById(shopId); + for (UserDO user : users) { + NailArtistInfoDTO dto = getByUserId(user.getId()); + if (dto == null) { + dto = buildFallbackArtistInfo(user); + } + if (!isVisibleServiceUser(dto) || !"APPROVED".equals(dto.getModerationStatus())) { + continue; + } + dto.setShopId(shopId); + dto.setShopName(shop == null ? null : shop.getShopName()); + result.add(dto); + } + enrichScheduleSummaries(result, shopId); + return result; + } + @Override /** * Save submitted data. @@ -196,16 +247,50 @@ public class NailArtistInfoServiceImpl extends ServiceImpl() .eq(NailArtistInfoDO::getUserId, dto.getUserId()) .eq(NailArtistInfoDO::getIsDelete, 0) .last("LIMIT 1")); - if (existing != null) { - entity.setId(existing.getId()); + if (existing == null && moderatePublicProfile) { + UserDO user = userMapper.selectById(dto.getUserId()); + if (user == null || isDeleted(user.getIsDelete())) { + throw new IllegalArgumentException("美甲师信息不存在"); + } + existing = new NailArtistInfoDO(); + existing.setUserId(dto.getUserId()); + existing.setIdentity(""); + existing.setExperience(0); + existing.setSkills(""); + existing.setPortfolio(""); + existing.setStatus(1); + existing.setParticipateProduction(Integer.valueOf(3).equals(user.getType()) ? 1 : 0); + existing.setModerationStatus("APPROVED"); + saveOrUpdate(existing); } + + NailArtistInfoDO entity = new NailArtistInfoDO(); + if (existing != null) { + // 后台编辑可能只提交部分资料。以已保存实体为基线,避免缺失字段被 BeanUtils 覆盖成 null。 + BeanUtils.copyProperties(existing, entity); + mergeSubmittedFields(dto, entity); + } else { + BeanUtils.copyProperties(dto, entity); + } + entity.setModerationStatus(existing == null || !StringUtils.hasText(existing.getModerationStatus()) + ? "APPROVED" : existing.getModerationStatus()); if (entity.getStatus() == null) { entity.setStatus(1); } @@ -214,12 +299,17 @@ public class NailArtistInfoServiceImpl extends ServiceImpl values = new ArrayList<>(); + if (StringUtils.hasText(profile.getIdentity())) values.add(profile.getIdentity().trim()); + if (profile.getExperience() != null) values.add(profile.getExperience() + "年从业经验"); + List tagIds = parseLongTokens(profile.getSkills()); + if (!tagIds.isEmpty()) { + tagMapper.selectBatchIds(tagIds).stream() + .filter(tag -> !isDeleted(tag.getIsDelete())) + .map(TagDO::getTagName) + .filter(StringUtils::hasText) + .forEach(values::add); + } + return String.join("\n", values); + } + + private String submitPublicProfileModeration(NailArtistInfoDO current, NailArtistInfoDO candidate, Long authorUserId) { + LinkedHashMap payload = new LinkedHashMap<>(); + payload.put("identity", candidate.getIdentity()); + payload.put("experience", candidate.getExperience()); + payload.put("skills", candidate.getSkills()); + payload.put("portfolio", candidate.getPortfolio()); + String text = buildArtistProfileModerationText(candidate); + try { + ContentModerationResultVO result = contentModerationService.assessVersion( + "NAIL_ARTIST_PROFILE", current.getId(), authorUserId, text, + objectMapper.writeValueAsString(payload), java.util.Collections.emptyList()); + return result == null || !StringUtils.hasText(result.getStatus()) ? "PENDING" : result.getStatus(); + } catch (JsonProcessingException exception) { + throw new IllegalStateException("美甲师公开资料审核任务创建失败", exception); + } } @Override @@ -242,14 +397,25 @@ public class NailArtistInfoServiceImpl extends ServiceImpl(); } + NailArtistInfoDTO artistInfo = loadPublicArtistInfo(artistId); + if (artistInfo == null || !isPublicShop(artistInfo.getShopId())) { + return new ArrayList<>(); + } List reviews = orderArtistReviewMapper.selectList(new LambdaQueryWrapper() .eq(OrderArtistReviewDO::getArtistId, artistId) + .eq(OrderArtistReviewDO::getShopId, artistInfo.getShopId()) .eq(OrderArtistReviewDO::getStatus, REVIEW_STATUS_SUBMITTED) .eq(OrderArtistReviewDO::getIsDelete, 0) + .eq(OrderArtistReviewDO::getModerationStatus, "APPROVED") .orderByDesc(OrderArtistReviewDO::getSubmittedAt) .orderByDesc(OrderArtistReviewDO::getId)); if (reviews == null || reviews.isEmpty()) { @@ -386,6 +558,12 @@ public class NailArtistInfoServiceImpl extends ServiceImpl productMap = loadProducts(limitedReviews.stream() .map(OrderArtistReviewDO::getProductId) .collect(Collectors.toCollection(LinkedHashSet::new))); + limitedReviews = limitedReviews.stream() + .filter(review -> { + ProductDO product = productMap.get(review.getProductId()); + return product != null && isFrontVisible(product) && "APPROVED".equals(product.getModerationStatus()); + }) + .collect(Collectors.toList()); Set imageIds = new LinkedHashSet<>(); for (OrderArtistReviewDO review : limitedReviews) { imageIds.addAll(parseLongTokens(review.getImageFileIds())); @@ -447,6 +625,7 @@ public class NailArtistInfoServiceImpl extends ServiceImpl shopOptions = userShopBindingSupport.listShopOptionsByUserId(user.getId(), true, true); if (!shopOptions.isEmpty()) { @@ -567,22 +746,67 @@ public class NailArtistInfoServiceImpl extends ServiceImpl reviews = orderArtistReviewMapper.selectList(new LambdaQueryWrapper() + .eq(OrderArtistReviewDO::getArtistId, artistId) + .eq(OrderArtistReviewDO::getShopId, artistInfo.getShopId()) + .eq(OrderArtistReviewDO::getStatus, REVIEW_STATUS_SUBMITTED) + .eq(OrderArtistReviewDO::getIsDelete, 0) + .eq(OrderArtistReviewDO::getModerationStatus, "APPROVED") + .isNotNull(OrderArtistReviewDO::getRatingScore)); + Map products = loadProducts(reviews.stream() + .map(OrderArtistReviewDO::getProductId) + .collect(Collectors.toCollection(LinkedHashSet::new))); + BigDecimal averageRating = reviews.stream() + .filter(review -> products.containsKey(review.getProductId())) + .map(OrderArtistReviewDO::getRatingScore) + .filter(java.util.Objects::nonNull) + .reduce(BigDecimal.ZERO, BigDecimal::add); + long ratingCount = reviews.stream() + .filter(review -> products.containsKey(review.getProductId())) + .map(OrderArtistReviewDO::getRatingScore) + .filter(java.util.Objects::nonNull) + .count(); + if (ratingCount > 0) { + averageRating = averageRating.divide(BigDecimal.valueOf(ratingCount), 1, RoundingMode.HALF_UP); + } else { + averageRating = null; + } BigDecimal rating = averageRating == null ? artistInfo.getRating() : averageRating; if (rating == null) { return BigDecimal.ZERO.setScale(1, RoundingMode.HALF_UP); @@ -822,7 +1046,8 @@ public class NailArtistInfoServiceImpl extends ServiceImpl { + @Select("SELECT COUNT(1) FROM t_comment c " + + "LEFT JOIN t_product p ON p.id = NULLIF(c.product_id, 0) " + + "LEFT JOIN t_shop s ON s.id = COALESCE(NULLIF(c.shop_id, 0), p.shop_id) " + + "WHERE c.is_delete = 0 AND c.moderation_status = 'APPROVED' " + + "AND (NULLIF(c.product_id, 0) IS NULL OR (p.is_delete = 0 AND p.front_visible = 1 AND p.moderation_status = 'APPROVED')) " + + "AND (COALESCE(NULLIF(c.shop_id, 0), p.shop_id) IS NULL OR (s.is_delete = 0 AND s.status = 1 AND s.moderation_status = 'APPROVED')) " + + "AND FIND_IN_SET(#{fileId}, REPLACE(COALESCE(c.image_file_ids, ''), ' ', '')) > 0") + Long countPublicImageReference(@Param("fileId") Long fileId); } diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/content/service/impl/CommentServiceImpl.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/content/service/impl/CommentServiceImpl.java index 17643eec..7ee77356 100644 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/content/service/impl/CommentServiceImpl.java +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/content/service/impl/CommentServiceImpl.java @@ -180,12 +180,8 @@ public class CommentServiceImpl extends ServiceImpl im if (commentDO == null) { return false; } - commentDO.setCommentContent(sanitizeContent(commentDTO.getCommentContent())); - commentDO.setModerationStatus("PENDING"); - commentDO.setUpdateTime(LocalDateTime.now()); - boolean updated = commentMapper.updateById(commentDO) > 0; - if (updated) moderateComment(commentDO, commentDO.getUserId()); - return updated; + moderateComment(commentDO, commentDO.getUserId(), sanitizeContent(commentDTO.getCommentContent()), commentDO.getImageFileIds()); + return true; } @Override @@ -215,7 +211,8 @@ public class CommentServiceImpl extends ServiceImpl im */ public boolean updateComment(Long id, Long currentUserId, CommentDTO commentDTO) { CommentDO commentDO = commentMapper.selectById(id); - if (commentDO == null || Integer.valueOf(1).equals(commentDO.getIsDelete())) { + if (commentDO == null || Integer.valueOf(1).equals(commentDO.getIsDelete()) + || !"APPROVED".equals(commentDO.getModerationStatus())) { return false; } if (currentUserId == null || !currentUserId.equals(commentDO.getUserId())) { @@ -226,12 +223,10 @@ public class CommentServiceImpl extends ServiceImpl im */ throw new RuntimeException("只能修改自己的评论"); } - commentDO.setCommentContent(sanitizeContent(commentDTO.getCommentContent())); - commentDO.setModerationStatus("PENDING"); - commentDO.setUpdateTime(LocalDateTime.now()); - boolean updated = commentMapper.updateById(commentDO) > 0; - if (updated) moderateComment(commentDO, currentUserId); - return updated; + String nextContent = sanitizeContent(commentDTO.getCommentContent()); + String nextImages = joinImageFileIds(commentDTO.getImageFileIds()); + moderateComment(commentDO, currentUserId, nextContent, nextImages); + return true; } @Override @@ -270,7 +265,8 @@ public class CommentServiceImpl extends ServiceImpl im */ public boolean adminDeleteComment(Long id, Long managedShopId) { CommentDO commentDO = commentMapper.selectById(id); - if (commentDO == null || Integer.valueOf(1).equals(commentDO.getIsDelete())) { + if (commentDO == null || Integer.valueOf(1).equals(commentDO.getIsDelete()) + || !"APPROVED".equals(commentDO.getModerationStatus())) { return false; } if (managedShopId != null && !managedShopId.equals(commentDO.getShopId())) { @@ -330,6 +326,7 @@ public class CommentServiceImpl extends ServiceImpl im .eq(CommentDO::getUserId, userId) .eq(CommentDO::getIsDelete, 0) .eq(CommentDO::getModerationStatus, "APPROVED") + .apply(publicVisibilitySql()) .orderByDesc(CommentDO::getCreateTime) ); return commentDOs.stream() @@ -350,6 +347,7 @@ public class CommentServiceImpl extends ServiceImpl im .eq(CommentDO::getShopId, shopId) .eq(CommentDO::getIsDelete, 0) .eq(CommentDO::getModerationStatus, "APPROVED") + .apply(publicVisibilitySql()) .orderByDesc(CommentDO::getCreateTime) ); return commentDOs.stream() @@ -370,6 +368,7 @@ public class CommentServiceImpl extends ServiceImpl im .eq(CommentDO::getProductId, productId) .eq(CommentDO::getIsDelete, 0) .eq(CommentDO::getModerationStatus, "APPROVED") + .apply(publicVisibilitySql()) .orderByDesc(CommentDO::getCreateTime) ); /** @@ -394,6 +393,7 @@ public class CommentServiceImpl extends ServiceImpl im .eq(CommentDO::getParentCommentId, parentCommentId) .eq(CommentDO::getIsDelete, 0) .eq(CommentDO::getModerationStatus, "APPROVED") + .apply(publicVisibilitySql()) .orderByAsc(CommentDO::getCreateTime) ); return commentDOs.stream() @@ -559,8 +559,8 @@ public class CommentServiceImpl extends ServiceImpl im if (id > 0) { result.add(id); } - } catch (NumberFormatException ignored) { - // Ignore malformed legacy tokens. + } catch (NumberFormatException exception) { + throw new IllegalArgumentException("评论图片必须引用已上传文件", exception); } } return new ArrayList<>(new LinkedHashSet<>(result)); @@ -589,19 +589,37 @@ public class CommentServiceImpl extends ServiceImpl im */ private com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper activeQuery() { return Wrappers.lambdaQuery(CommentDO.class).eq(CommentDO::getIsDelete, 0) - .eq(CommentDO::getModerationStatus, "APPROVED"); + .eq(CommentDO::getModerationStatus, "APPROVED") + .apply(publicVisibilitySql()); + } + + private String publicVisibilitySql() { + return "(t_comment.shop_id IS NULL OR t_comment.shop_id = 0 OR EXISTS " + + "(SELECT 1 FROM t_shop visible_shop WHERE visible_shop.id = t_comment.shop_id " + + "AND visible_shop.is_delete = 0 AND visible_shop.status = 1 " + + "AND visible_shop.moderation_status = 'APPROVED')) " + + "AND (t_comment.product_id IS NULL OR t_comment.product_id = 0 OR EXISTS " + + "(SELECT 1 FROM t_product visible_product " + + "JOIN t_shop product_shop ON product_shop.id = visible_product.shop_id " + + "AND product_shop.is_delete = 0 AND product_shop.status = 1 " + + "AND product_shop.moderation_status = 'APPROVED' " + + "WHERE visible_product.id = t_comment.product_id " + + "AND visible_product.is_delete = 0 AND visible_product.front_visible = 1 " + + "AND visible_product.moderation_status = 'APPROVED'))"; } private void moderateComment(CommentDO comment, Long userId) { + moderateComment(comment, userId, comment.getCommentContent(), comment.getImageFileIds()); + } + + private void moderateComment(CommentDO comment, Long userId, String content, String imageFileIds) { try { - ContentModerationResultVO result = contentModerationService.assess("COMMENT", comment.getId(), userId, - comment.getCommentContent() + "\n" + String.valueOf(comment.getImageFileIds()), - objectMapper.writeValueAsString(java.util.Map.of( - "commentContent", comment.getCommentContent(), - "imageFileIds", comment.getImageFileIds() == null ? "" : comment.getImageFileIds()))); - comment.setModerationStatus(result.getStatus()); - comment.setUpdateTime(LocalDateTime.now()); - commentMapper.updateById(comment); + java.util.Map payload = new java.util.LinkedHashMap<>(); + payload.put("commentContent", content); + payload.put("imageFileIds", imageFileIds); + List imageIds = parseImageFileIds(imageFileIds); + contentModerationService.assessVersion("COMMENT", comment.getId(), userId, content, + objectMapper.writeValueAsString(payload), imageIds); } catch (JsonProcessingException exception) { throw new IllegalStateException("评论审核内容序列化失败", exception); } diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/file/controller/front/FrontendFileController.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/file/controller/front/FrontendFileController.java index 7d9bbfc5..621a0622 100644 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/file/controller/front/FrontendFileController.java +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/file/controller/front/FrontendFileController.java @@ -4,6 +4,11 @@ import com.xiaowang.jayucloud.salon.core.common.Result; import com.xiaowang.jayucloud.salon.core.modules.product.mapper.EffectDiagramMapper; 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.content.mapper.CommentMapper; +import com.xiaowang.jayucloud.salon.core.modules.order.mapper.OrderArtistReviewMapper; +import com.xiaowang.jayucloud.salon.core.modules.message.mapper.AnnouncementMapper; +import com.xiaowang.jayucloud.salon.core.modules.message.mapper.SystemMessageMapper; +import com.xiaowang.jayucloud.salon.core.modules.user.mapper.UserMapper; import com.xiaowang.jayucloud.salon.core.modules.file.service.ObjectStorageFileService; import com.xiaowang.jayucloud.salon.core.modules.file.support.ObjectStorageUrlSupport; import com.xiaowang.jayucloud.salon.core.modules.file.vo.ObjectStorageFileVO; @@ -28,6 +33,11 @@ public class FrontendFileController { private final ProductMapper productMapper; private final ShopMapper shopMapper; private final EffectDiagramMapper effectDiagramMapper; + private final CommentMapper commentMapper; + private final OrderArtistReviewMapper orderArtistReviewMapper; + private final AnnouncementMapper announcementMapper; + private final SystemMessageMapper systemMessageMapper; + private final UserMapper userMapper; /** * Purpose: getSignedUrl returns a short-lived URL for public image references, or the original external URL when it is already public. @@ -71,7 +81,12 @@ public class FrontendFileController { } return positive(productMapper.countPublicImageReference(fileId)) || positive(shopMapper.countPublicImageReference(fileId)) - || positive(effectDiagramMapper.countPublicImageReference(fileId)); + || positive(effectDiagramMapper.countPublicImageReference(fileId)) + || positive(commentMapper.countPublicImageReference(fileId)) + || positive(orderArtistReviewMapper.countPublicImageReference(fileId)) + || positive(announcementMapper.countPublicImageReference(fileId)) + || positive(systemMessageMapper.countPublicImageReference(fileId)) + || positive(userMapper.countPublicImageReference(fileId)); } /** diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/file/service/ObjectStorageFileService.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/file/service/ObjectStorageFileService.java index 3112446a..da393bc2 100644 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/file/service/ObjectStorageFileService.java +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/file/service/ObjectStorageFileService.java @@ -75,4 +75,8 @@ public interface ObjectStorageFileService extends IService List listObjectStorageFilesByStatus(Integer status); void evictObjectStorageFileCache(Long id); + + Long findFileIdByReference(String reference); + + String createTemporaryModerationUrl(Long fileId, Integer expiryMinutes); } diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/file/service/impl/ObjectStorageFileServiceImpl.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/file/service/impl/ObjectStorageFileServiceImpl.java index 33243a25..e1e845c3 100644 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/file/service/impl/ObjectStorageFileServiceImpl.java +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/file/service/impl/ObjectStorageFileServiceImpl.java @@ -11,6 +11,7 @@ import com.xiaowang.jayucloud.salon.core.modules.file.mapper.ObjectStorageFileMa import com.xiaowang.jayucloud.salon.core.modules.file.mq.ObjectStorageBackupMessagePublisher; import com.xiaowang.jayucloud.salon.core.modules.file.service.ObjectStorageFileService; import com.xiaowang.jayucloud.salon.core.modules.file.service.ObjectStorageReplicaService; +import com.xiaowang.jayucloud.salon.core.modules.file.support.ObjectStorageUrlSupport; import com.xiaowang.jayucloud.salon.core.support.cache.MultiLevelCacheService; import com.xiaowang.jayucloud.salon.core.modules.file.vo.ObjectStorageFileVO; import lombok.RequiredArgsConstructor; @@ -59,6 +60,7 @@ public class ObjectStorageFileServiceImpl extends ServiceImpl query.eq(ObjectStorageFileDO::getFileUrl, reference) + .or().eq(ObjectStorageFileDO::getPrimaryUrl, reference) + .or().eq(StringUtils.hasText(objectName), ObjectStorageFileDO::getObjectName, objectName)) + .last("LIMIT 1")); + return file == null ? null : file.getId(); + } + + @Override + public String createTemporaryModerationUrl(Long fileId, Integer expiryMinutes) { + ObjectStorageFileVO file = getObjectStorageFileById(fileId); + if (file == null || !Integer.valueOf(1).equals(file.getStatus())) { + throw new IllegalStateException("审核图片不存在或不可用"); + } + String url = objectStorageUrlSupport.getSignedUrlOrThrow(file, expiryMinutes); + if (!StringUtils.hasText(url) || !url.startsWith("https://")) { + throw new IllegalStateException("审核图片必须通过 HTTPS 访问"); + } + return url; + } + /** * 将 DO 转换为 VO * diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/integration/service/WechatMiniClientService.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/integration/service/WechatMiniClientService.java index ba9e7435..ad65ed78 100644 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/integration/service/WechatMiniClientService.java +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/integration/service/WechatMiniClientService.java @@ -29,6 +29,8 @@ public interface WechatMiniClientService { */ String getConfiguredAppId(); + String getAccessTokenForContentModeration(); + /** * Run business method `SessionInfo`. * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/integration/service/impl/WechatMiniClientServiceImpl.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/integration/service/impl/WechatMiniClientServiceImpl.java index 0733d6ac..eb9e572b 100644 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/integration/service/impl/WechatMiniClientServiceImpl.java +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/integration/service/impl/WechatMiniClientServiceImpl.java @@ -201,6 +201,11 @@ public class WechatMiniClientServiceImpl implements WechatMiniClientService { return properties.getAppId(); } + @Override + public String getAccessTokenForContentModeration() { + return getAccessToken(); + } + /** * Load data by the supplied parameter. * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/manager/controller/admin/AdminManagerController.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/manager/controller/admin/AdminManagerController.java index 308f420a..e5bd310d 100644 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/manager/controller/admin/AdminManagerController.java +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/manager/controller/admin/AdminManagerController.java @@ -200,7 +200,7 @@ public class AdminManagerController { if (!adminScopeHelper.isPlatformAdmin(currentUser)) { adminScopeHelper.ensureUserAccessibleInCurrentShop(currentUser, dto.getUserId(), "无权编辑其他店铺员工"); } - return Result.success(nailArtistInfoService.saveOrUpdateNailArtistInfo(dto)); + return Result.success(nailArtistInfoService.submitNailArtistInfo(dto, currentUser.getId())); } @PostMapping("/employees/users") diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/message/dto/AnnouncementCreateDTO.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/message/dto/AnnouncementCreateDTO.java index dbe4fe58..f73e22e3 100644 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/message/dto/AnnouncementCreateDTO.java +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/message/dto/AnnouncementCreateDTO.java @@ -27,6 +27,9 @@ public class AnnouncementCreateDTO { */ private String content; + /** 公告图片文件ID集合,多个ID以逗号分隔。 */ + private String imageFileIds; + @NotBlank(message = "公告范围不能为空") /** * Field `targetType` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/message/entity/AnnouncementDO.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/message/entity/AnnouncementDO.java index 833bca6b..3075823e 100644 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/message/entity/AnnouncementDO.java +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/message/entity/AnnouncementDO.java @@ -30,6 +30,9 @@ public class AnnouncementDO extends BaseEntity { */ private String content; + @TableField("image_file_ids") + private String imageFileIds; + @TableField("publisher_id") /** * Field `publisherId` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. @@ -66,6 +69,9 @@ public class AnnouncementDO extends BaseEntity { */ private Integer status; + @TableField("moderation_status") + private String moderationStatus; + @TableField("sort_order") /** * Field `sortOrder` (Integer): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/message/entity/SystemMessageDO.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/message/entity/SystemMessageDO.java index d0667a59..76ec67cd 100644 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/message/entity/SystemMessageDO.java +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/message/entity/SystemMessageDO.java @@ -106,6 +106,9 @@ public class SystemMessageDO extends BaseEntity { */ private Integer status; + @TableField("moderation_status") + private String moderationStatus; + @TableField("publish_time") /** * Field `publishTime` (LocalDateTime): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/message/mapper/AnnouncementMapper.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/message/mapper/AnnouncementMapper.java index 8e71d620..ca978c9f 100644 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/message/mapper/AnnouncementMapper.java +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/message/mapper/AnnouncementMapper.java @@ -2,10 +2,14 @@ package com.xiaowang.jayucloud.salon.core.modules.message.mapper; import com.baomidou.mybatisplus.core.mapper.BaseMapper; import com.xiaowang.jayucloud.salon.core.modules.message.entity.AnnouncementDO; +import org.apache.ibatis.annotations.Param; +import org.apache.ibatis.annotations.Select; /** * AnnouncementMapper is a MyBatis mapper interface. ServiceImpl classes call it to read or write database rows. * Field and parameter names are kept consistent with the frontend/API payload to make tracing easier. */ public interface AnnouncementMapper extends BaseMapper { + @Select("SELECT COUNT(1) FROM t_announcement WHERE is_delete = 0 AND status = 1 AND moderation_status = 'APPROVED' AND FIND_IN_SET(#{fileId}, REPLACE(COALESCE(image_file_ids, ''), ' ', '')) > 0") + Long countPublicImageReference(@Param("fileId") Long fileId); } diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/message/mapper/SystemMessageMapper.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/message/mapper/SystemMessageMapper.java index 43a7b814..6c5caebf 100644 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/message/mapper/SystemMessageMapper.java +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/message/mapper/SystemMessageMapper.java @@ -3,6 +3,8 @@ package com.xiaowang.jayucloud.salon.core.modules.message.mapper; import com.baomidou.mybatisplus.core.mapper.BaseMapper; import com.xiaowang.jayucloud.salon.core.modules.message.entity.SystemMessageDO; import org.apache.ibatis.annotations.Mapper; +import org.apache.ibatis.annotations.Param; +import org.apache.ibatis.annotations.Select; @Mapper /** @@ -10,4 +12,6 @@ import org.apache.ibatis.annotations.Mapper; * Field and parameter names are kept consistent with the frontend/API payload to make tracing easier. */ public interface SystemMessageMapper extends BaseMapper { + @Select("SELECT COUNT(1) FROM t_system_message WHERE is_delete = 0 AND status = 1 AND moderation_status = 'APPROVED' AND image_file_id = #{fileId}") + Long countPublicImageReference(@Param("fileId") Long fileId); } diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/message/service/impl/AnnouncementServiceImpl.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/message/service/impl/AnnouncementServiceImpl.java index a5244d02..360e2998 100644 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/message/service/impl/AnnouncementServiceImpl.java +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/message/service/impl/AnnouncementServiceImpl.java @@ -13,6 +13,8 @@ import com.xiaowang.jayucloud.salon.core.modules.user.mapper.UserMapper; import com.xiaowang.jayucloud.salon.core.modules.shop.mapper.UserShopBindingMapper; import com.xiaowang.jayucloud.salon.core.modules.message.service.AnnouncementService; import com.xiaowang.jayucloud.salon.core.modules.security.support.AdminScopeHelper; +import com.xiaowang.jayucloud.salon.core.modules.privacy.service.ContentModerationService; +import com.fasterxml.jackson.databind.ObjectMapper; import com.xiaowang.jayucloud.salon.core.modules.message.vo.AnnouncementVO; import com.xiaowang.jayucloud.salon.core.modules.message.vo.MessageTargetOptionsVO; import com.xiaowang.jayucloud.salon.core.support.privacy.PhoneCrypto; @@ -85,6 +87,8 @@ public class AnnouncementServiceImpl extends ServiceImpl payload = new java.util.LinkedHashMap<>(); + payload.put("title", announcement.getTitle()); payload.put("content", announcement.getContent()); + payload.put("imageFileIds", announcement.getImageFileIds()); payload.put("status", 1); + contentModerationService.assessVersion("ANNOUNCEMENT", announcement.getId(), currentUser.getId(), + announcement.getTitle() + "\n" + announcement.getContent(), objectMapper.writeValueAsString(payload), + parseImageFileIds(announcement.getImageFileIds())); + } catch (Exception exception) { + throw new IllegalStateException("公告审核任务创建失败", exception); + } return announcement.getId(); } @@ -235,6 +251,7 @@ public class AnnouncementServiceImpl extends ServiceImpl() .eq(AnnouncementDO::getIsDelete, 0) .eq(AnnouncementDO::getStatus, 1) + .eq(AnnouncementDO::getModerationStatus, "APPROVED") .orderByDesc(AnnouncementDO::getSortOrder) .orderByDesc(AnnouncementDO::getPublishTime)) .stream() @@ -375,6 +392,7 @@ public class AnnouncementServiceImpl extends ServiceImpl parseImageFileIdsStrict(String value) { + if (!StringUtils.hasText(value)) return List.of(); + return java.util.Arrays.stream(value.split(",")) + .map(String::trim) + .filter(StringUtils::hasText) + .map(token -> { + try { + long id = Long.parseLong(token); + if (id <= 0) throw new NumberFormatException("file id must be positive"); + return id; + } catch (NumberFormatException exception) { + throw new IllegalArgumentException("公告图片必须引用已上传文件", exception); + } + }) + .distinct() + .collect(Collectors.toList()); + } + + private List parseImageFileIds(String value) { + if (!StringUtils.hasText(value)) return List.of(); + return java.util.Arrays.stream(value.split(",")) + .map(String::trim).filter(StringUtils::hasText) + .map(token -> { try { return Long.valueOf(token); } catch (NumberFormatException ignored) { return null; } }) + .filter(id -> id != null && id > 0).distinct().collect(Collectors.toList()); + } + /** * Run business method `targetTypeName`. * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/message/service/impl/SystemMessageServiceImpl.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/message/service/impl/SystemMessageServiceImpl.java index ddc23fca..2e966913 100644 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/message/service/impl/SystemMessageServiceImpl.java +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/message/service/impl/SystemMessageServiceImpl.java @@ -16,6 +16,8 @@ import com.xiaowang.jayucloud.salon.core.modules.shop.mapper.UserShopBindingMapp import com.xiaowang.jayucloud.salon.core.modules.file.service.ObjectStorageFileService; import com.xiaowang.jayucloud.salon.core.modules.message.service.SystemMessageService; import com.xiaowang.jayucloud.salon.core.modules.security.support.AdminScopeHelper; +import com.xiaowang.jayucloud.salon.core.modules.privacy.service.ContentModerationService; +import com.fasterxml.jackson.databind.ObjectMapper; import com.xiaowang.jayucloud.salon.core.modules.file.support.ObjectStorageUrlSupport; import com.xiaowang.jayucloud.salon.core.modules.message.vo.MessageTargetOptionsVO; import com.xiaowang.jayucloud.salon.core.modules.file.vo.ObjectStorageFileVO; @@ -103,6 +105,8 @@ public class SystemMessageServiceImpl extends ServiceImpl payload = new java.util.LinkedHashMap<>(); + payload.put("title", title); payload.put("content", content); payload.put("imageFileId", dto.getImageFileId()); payload.put("status", 1); + List imageIds = dto.getImageFileId() == null ? List.of() : List.of(dto.getImageFileId()); + contentModerationService.assessVersion("SYSTEM_MESSAGE", message.getId(), currentUser.getId(), + title + "\n" + content, objectMapper.writeValueAsString(payload), imageIds); + } catch (Exception exception) { + throw new IllegalStateException("站内消息审核任务创建失败", exception); + } return message.getId(); } @@ -429,6 +445,7 @@ public class SystemMessageServiceImpl extends ServiceImpl() .eq(SystemMessageDO::getIsDelete, 0) .eq(SystemMessageDO::getStatus, 1) + .eq(SystemMessageDO::getModerationStatus, "APPROVED") .orderByDesc(SystemMessageDO::getPublishTime)) .stream() .filter(message -> isMessageVisibleToUser(message, user)) diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/message/vo/AnnouncementVO.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/message/vo/AnnouncementVO.java index d068d8a7..11ec1597 100644 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/message/vo/AnnouncementVO.java +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/message/vo/AnnouncementVO.java @@ -23,6 +23,7 @@ public class AnnouncementVO { * Field `content` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. */ private String content; + private List imageFileIds; /** * Field `publisherId` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled. */ diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/order/entity/OrderArtistReviewDO.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/order/entity/OrderArtistReviewDO.java index a64c727d..f48299e7 100644 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/order/entity/OrderArtistReviewDO.java +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/order/entity/OrderArtistReviewDO.java @@ -67,6 +67,9 @@ public class OrderArtistReviewDO extends BaseEntity { */ private Integer status; + @TableField("moderation_status") + private String moderationStatus; + @TableField("rating_score") /** * Purpose: ratingScore supports OrderArtistReviewDO.java by holding or executing the rating score business role. diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/order/mapper/OrderArtistReviewMapper.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/order/mapper/OrderArtistReviewMapper.java index 63e2fef3..4a9e6eed 100644 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/order/mapper/OrderArtistReviewMapper.java +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/order/mapper/OrderArtistReviewMapper.java @@ -25,6 +25,24 @@ public interface OrderArtistReviewMapper extends BaseMapper @Select("SELECT * FROM t_order_artist_review WHERE order_item_id = #{orderItemId} AND is_delete = 0 LIMIT 1") OrderArtistReviewDO selectByOrderItemId(@Param("orderItemId") Long orderItemId); - @Select("SELECT AVG(rating_score) FROM t_order_artist_review WHERE artist_id = #{artistId} AND status = 1 AND is_delete = 0") + @Select("SELECT AVG(rating_score) FROM t_order_artist_review WHERE artist_id = #{artistId} AND status = 1 AND is_delete = 0 AND moderation_status = 'APPROVED'") BigDecimal selectAverageSubmittedRatingByArtistId(@Param("artistId") Long artistId); + + @Select("SELECT COUNT(1) FROM t_order_artist_review r " + + "LEFT JOIN t_product p ON p.id = r.product_id " + + "LEFT JOIN t_shop s ON s.id = COALESCE(r.shop_id, p.shop_id) " + + "WHERE r.id = #{reviewId} AND r.is_delete = 0 AND r.status = 1 AND r.moderation_status = 'APPROVED' " + + "AND p.is_delete = 0 AND p.front_visible = 1 AND p.moderation_status = 'APPROVED' " + + "AND s.is_delete = 0 AND s.status = 1 AND s.moderation_status = 'APPROVED' " + + "AND FIND_IN_SET(#{fileId}, REPLACE(COALESCE(r.image_file_ids, ''), ' ', '')) > 0") + Long countPublicImageReference(@Param("reviewId") Long reviewId, @Param("fileId") Long fileId); + + @Select("SELECT COUNT(1) FROM t_order_artist_review r " + + "LEFT JOIN t_product p ON p.id = r.product_id " + + "LEFT JOIN t_shop s ON s.id = COALESCE(r.shop_id, p.shop_id) " + + "WHERE r.is_delete = 0 AND r.status = 1 AND r.moderation_status = 'APPROVED' " + + "AND p.is_delete = 0 AND p.front_visible = 1 AND p.moderation_status = 'APPROVED' " + + "AND s.is_delete = 0 AND s.status = 1 AND s.moderation_status = 'APPROVED' " + + "AND FIND_IN_SET(#{fileId}, REPLACE(COALESCE(r.image_file_ids, ''), ' ', '')) > 0") + Long countPublicImageReference(@Param("fileId") Long fileId); } diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/order/service/impl/AfterSaleServiceImpl.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/order/service/impl/AfterSaleServiceImpl.java index d5f6f88e..175759af 100644 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/order/service/impl/AfterSaleServiceImpl.java +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/order/service/impl/AfterSaleServiceImpl.java @@ -145,6 +145,7 @@ public class AfterSaleServiceImpl implements AfterSaleService { message.setActionPath("/after-sales?afterSaleId=" + afterSale.getId()); message.setPopupEnabled(1); message.setStatus(1); + message.setModerationStatus("APPROVED"); message.setPublishTime(LocalDateTime.now()); message.setIsDelete(0); systemMessageMapper.insert(message); diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/order/service/impl/OrderServiceImpl.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/order/service/impl/OrderServiceImpl.java index 64c6f469..83a6a7e0 100644 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/order/service/impl/OrderServiceImpl.java +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/order/service/impl/OrderServiceImpl.java @@ -46,6 +46,10 @@ import com.xiaowang.jayucloud.salon.core.modules.order.service.OrderService; import com.xiaowang.jayucloud.salon.core.modules.product.service.TagService; import com.xiaowang.jayucloud.salon.core.modules.artist.support.BookableArtistSupport; 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.privacy.service.ContentModerationService; +import com.xiaowang.jayucloud.salon.core.modules.privacy.vo.ContentModerationResultVO; +import com.fasterxml.jackson.databind.ObjectMapper; import com.xiaowang.jayucloud.salon.core.modules.order.support.OrderStateMachine; import com.xiaowang.jayucloud.salon.core.modules.order.support.OrderStatus; import com.xiaowang.jayucloud.salon.core.support.id.TimeOrderedSnowflakeIdGenerator; @@ -284,6 +288,15 @@ public class OrderServiceImpl implements OrderService { */ private OrderArtistReviewMapper orderArtistReviewMapper; + @Resource + private ContentModerationService contentModerationService; + + @Resource + private ObjectStorageFileService objectStorageFileService; + + @Resource + private ObjectMapper objectMapper; + @Resource /** * Purpose: orderArtistChangeRequestMapper supports OrderServiceImpl.java by holding or executing the order artist change request mapper business role. @@ -1791,9 +1804,25 @@ public class OrderServiceImpl implements OrderService { review.setRatingScore(rating); review.setContent(trimToNull(dto == null ? null : dto.getContent())); review.setImageFileIds(joinLongIds(dto == null ? null : dto.getImageFileIds())); + review.setModerationStatus("PENDING"); review.setStatus(REVIEW_STATUS_SUBMITTED); review.setSubmittedAt(LocalDateTime.now()); orderArtistReviewMapper.updateById(review); + try { + java.util.Map payload = new java.util.LinkedHashMap<>(); + payload.put("content", review.getContent()); + payload.put("imageFileIds", review.getImageFileIds()); + List imageIds = parseIdSet(review.getImageFileIds()).stream().toList(); + ContentModerationResultVO moderation = contentModerationService.assessVersion( + "ORDER_ARTIST_REVIEW", review.getId(), userId, review.getContent(), + objectMapper.writeValueAsString(payload), imageIds); + if (moderation != null && "APPROVED".equals(moderation.getStatus())) { + review.setModerationStatus("APPROVED"); + orderArtistReviewMapper.updateById(review); + } + } catch (Exception exception) { + throw new IllegalStateException("评价审核任务创建失败", exception); + } refreshArtistRating(review.getArtistId()); return buildArtistReviewVO(review); } @@ -2144,6 +2173,7 @@ public class OrderServiceImpl implements OrderService { review.setArtistId(item.getArtistId()); review.setCustomerId(order.getUserId()); review.setStatus(REVIEW_STATUS_PENDING); + review.setModerationStatus("APPROVED"); review.setIsDelete(0); review = insertPendingArtistReview(review); if (review == null || review.getId() == null) { @@ -2220,8 +2250,11 @@ public class OrderServiceImpl implements OrderService { vo.setCustomerId(review.getCustomerId()); vo.setRating(review.getRatingScore()); vo.setRatingScore(review.getRatingScore()); - vo.setContent(review.getContent()); - vo.setImageFileIds(new ArrayList<>(parseIdSet(review.getImageFileIds()))); + boolean moderationApproved = "APPROVED".equals(review.getModerationStatus()); + vo.setContent(moderationApproved ? review.getContent() : null); + vo.setImageFileIds(moderationApproved + ? new ArrayList<>(parseIdSet(review.getImageFileIds())) + : new ArrayList<>()); vo.setStatus(review.getStatus()); vo.setStatusText(Integer.valueOf(REVIEW_STATUS_SUBMITTED).equals(review.getStatus()) ? "已评价" : "待评价"); vo.setReminderMessageId(review.getReminderMessageId()); @@ -3063,6 +3096,7 @@ public class OrderServiceImpl implements OrderService { message.setActionPath(actionPath); message.setPopupEnabled(1); message.setStatus(1); + message.setModerationStatus("APPROVED"); message.setPublishTime(LocalDateTime.now()); message.setIsDelete(0); systemMessageMapper.insert(message); @@ -3102,6 +3136,7 @@ public class OrderServiceImpl implements OrderService { message.setIdempotencyKey(idempotencyKey); message.setPopupEnabled(1); message.setStatus(1); + message.setModerationStatus("APPROVED"); message.setPublishTime(LocalDateTime.now()); message.setIsDelete(0); try { diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/privacy/config/ContentModerationProperties.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/privacy/config/ContentModerationProperties.java new file mode 100644 index 00000000..d4d8a8fd --- /dev/null +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/privacy/config/ContentModerationProperties.java @@ -0,0 +1,20 @@ +package com.xiaowang.jayucloud.salon.core.modules.privacy.config; + +import lombok.Data; +import org.springframework.boot.context.properties.ConfigurationProperties; +import org.springframework.stereotype.Component; + +@Data +@Component +@ConfigurationProperties(prefix = "jayucloud-salon.privacy.content-moderation") +public class ContentModerationProperties { + private String provider = "disabled"; + private String callbackUrl; + private String callbackToken; + private String encodingAesKey; + private Integer scene = 2; + private Integer imageUrlExpireMinutes = 5; + private Integer requestTimeoutMillis = 8000; + private Integer maxRetries = 3; + private String retryCron = "0 */2 * * * *"; +} diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/privacy/config/WechatContentModerationHttpConfig.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/privacy/config/WechatContentModerationHttpConfig.java new file mode 100644 index 00000000..4a2b3395 --- /dev/null +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/privacy/config/WechatContentModerationHttpConfig.java @@ -0,0 +1,21 @@ +package com.xiaowang.jayucloud.salon.core.modules.privacy.config; + +import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.http.client.SimpleClientHttpRequestFactory; +import org.springframework.web.client.RestTemplate; + +@Configuration +@ConditionalOnProperty(prefix = "jayucloud-salon.privacy.content-moderation", name = "provider", havingValue = "wechat") +public class WechatContentModerationHttpConfig { + @Bean("wechatContentModerationRestTemplate") + public RestTemplate wechatContentModerationRestTemplate(ContentModerationProperties properties) { + int timeoutMillis = properties.getRequestTimeoutMillis() == null + ? 8000 : Math.max(1000, properties.getRequestTimeoutMillis()); + SimpleClientHttpRequestFactory requestFactory = new SimpleClientHttpRequestFactory(); + requestFactory.setConnectTimeout(timeoutMillis); + requestFactory.setReadTimeout(timeoutMillis); + return new RestTemplate(requestFactory); + } +} diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/privacy/controller/admin/AdminContentModerationController.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/privacy/controller/admin/AdminContentModerationController.java index 6afb7473..e8facf1a 100644 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/privacy/controller/admin/AdminContentModerationController.java +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/privacy/controller/admin/AdminContentModerationController.java @@ -3,8 +3,8 @@ package com.xiaowang.jayucloud.salon.core.modules.privacy.controller.admin; import com.xiaowang.jayucloud.salon.core.annotation.OperationGuard; import com.xiaowang.jayucloud.salon.core.common.Result; import com.xiaowang.jayucloud.salon.core.modules.privacy.dto.ContentModerationReviewDTO; -import com.xiaowang.jayucloud.salon.core.modules.privacy.entity.ContentModerationRecordDO; import com.xiaowang.jayucloud.salon.core.modules.privacy.service.ContentModerationService; +import com.xiaowang.jayucloud.salon.core.modules.privacy.vo.ContentModerationRecordVO; import com.xiaowang.jayucloud.salon.core.modules.user.entity.UserDO; import com.xiaowang.jayucloud.salon.core.modules.user.mapper.UserMapper; import lombok.RequiredArgsConstructor; @@ -29,7 +29,7 @@ public class AdminContentModerationController { private final UserMapper userMapper; @GetMapping("/pending") - public Result> pending(HttpServletRequest request) { + public Result> pending(HttpServletRequest request) { requirePlatformAdmin(request); return Result.success(contentModerationService.listPending()); } 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 new file mode 100644 index 00000000..02f46850 --- /dev/null +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/privacy/controller/front/WechatContentModerationCallbackController.java @@ -0,0 +1,99 @@ +package com.xiaowang.jayucloud.salon.core.modules.privacy.controller.front; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.xiaowang.jayucloud.salon.core.config.WechatMiniProperties; +import com.xiaowang.jayucloud.salon.core.modules.privacy.config.ContentModerationProperties; +import com.xiaowang.jayucloud.salon.core.modules.privacy.service.ContentModerationService; +import com.xiaowang.jayucloud.salon.core.modules.privacy.support.WechatCallbackCrypto; +import lombok.RequiredArgsConstructor; +import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; +import org.springframework.http.MediaType; +import org.springframework.util.StringUtils; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.RestController; + +import javax.servlet.http.HttpServletRequest; +import java.nio.charset.StandardCharsets; + +@RestController +@RequiredArgsConstructor +@RequestMapping("/integration/wechat/content-moderation") +@ConditionalOnProperty(prefix = "jayucloud-salon.privacy.content-moderation", name = "provider", havingValue = "wechat") +public class WechatContentModerationCallbackController { + private final ContentModerationProperties properties; + private final WechatMiniProperties wechatProperties; + private final WechatCallbackCrypto crypto; + private final ContentModerationService contentModerationService; + private final ObjectMapper objectMapper; + + @GetMapping("/callback") + public String verifyEndpoint(@RequestParam("timestamp") String timestamp, + @RequestParam("nonce") String nonce, + @RequestParam(value = "msg_signature", required = false) String messageSignature, + @RequestParam(value = "signature", required = false) String signature, + @RequestParam(value = "encrypt_type", required = false) String encryptType, + @RequestParam("echostr") String echoString) { + if ("aes".equalsIgnoreCase(encryptType)) { + if (!StringUtils.hasText(properties.getEncodingAesKey()) + || !crypto.verify(properties.getCallbackToken(), timestamp, nonce, echoString, messageSignature)) { + throw new IllegalArgumentException("微信审核回调 AES 握手校验失败"); + } + return crypto.decrypt(echoString, properties.getEncodingAesKey(), wechatProperties.getAppId()); + } + if (!crypto.verifyPlain(properties.getCallbackToken(), timestamp, nonce, signature)) { + throw new IllegalArgumentException("微信审核回调明文握手校验失败"); + } + return echoString; + } + + @PostMapping(value = "/callback", consumes = {MediaType.APPLICATION_XML_VALUE, MediaType.TEXT_XML_VALUE}) + public String callback(HttpServletRequest request, @RequestParam("timestamp") String timestamp, + @RequestParam("nonce") String nonce, + @RequestParam(value = "msg_signature", required = false) String messageSignature, + @RequestParam(value = "signature", required = false) String signature, + @RequestParam(value = "encrypt_type", required = false) String encryptType, + @org.springframework.web.bind.annotation.RequestBody String body) throws Exception { + String encrypted = crypto.encryptedValue(body); + String expectedSignature = "aes".equalsIgnoreCase(encryptType) ? messageSignature : signature; + if (!crypto.verify(properties.getCallbackToken(), timestamp, nonce, + "aes".equalsIgnoreCase(encryptType) ? encrypted : "", expectedSignature)) { + throw new IllegalArgumentException("微信审核回调签名校验失败"); + } + if (!"aes".equalsIgnoreCase(encryptType) || !StringUtils.hasText(properties.getEncodingAesKey())) { + throw new IllegalArgumentException("微信审核回调仅接受 AES 加密消息"); + } + String decoded = crypto.decrypt(encrypted, properties.getEncodingAesKey(), wechatProperties.getAppId()); + String taskId; + String suggest; + String reason; + 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"), "微信异步图片审核回调"); + } else { + JsonNode root = objectMapper.readTree(decoded); + taskId = firstText(root, "trace_id", "traceId", "task_id"); + suggest = firstText(root.path("result"), "suggest", "Suggest"); + if (!StringUtils.hasText(suggest)) suggest = "review"; + reason = firstText(root, "errmsg", "reason"); + if (!StringUtils.hasText(reason)) reason = "微信异步图片审核回调"; + } + if (!StringUtils.hasText(taskId)) throw new IllegalArgumentException("微信审核回调缺少任务标识"); + contentModerationService.handleWechatImageResult(taskId, suggest, reason); + return "success"; + } + + private String firstText(JsonNode node, String... keys) { + for (String key : keys) if (node != null && node.hasNonNull(key)) return node.path(key).asText(); + return null; + } + + private String firstNonBlank(String... values) { + for (String value : values) if (StringUtils.hasText(value)) return value; + return null; + } +} 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 new file mode 100644 index 00000000..ec535536 --- /dev/null +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/privacy/entity/ContentModerationImageTaskDO.java @@ -0,0 +1,26 @@ +package com.xiaowang.jayucloud.salon.core.modules.privacy.entity; + +import com.baomidou.mybatisplus.annotation.IdType; +import com.baomidou.mybatisplus.annotation.TableId; +import com.baomidou.mybatisplus.annotation.TableName; +import com.xiaowang.jayucloud.salon.core.common.entity.BaseEntity; +import lombok.Getter; +import lombok.Setter; + +import java.time.LocalDateTime; + +@Getter +@Setter +@TableName("t_content_moderation_image_task") +public class ContentModerationImageTaskDO extends BaseEntity { + @TableId(type = IdType.ASSIGN_ID) + private Long id; + private Long recordId; + private Long fileId; + private String providerTaskId; + private String status; + private String resultCode; + private String reason; + private Integer attemptCount; + private LocalDateTime nextRetryAt; +} diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/privacy/entity/ContentModerationRecordDO.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/privacy/entity/ContentModerationRecordDO.java index f3cf46b2..0d6f093b 100644 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/privacy/entity/ContentModerationRecordDO.java +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/privacy/entity/ContentModerationRecordDO.java @@ -18,6 +18,10 @@ public class ContentModerationRecordDO extends BaseEntity { private String contentType; private Long businessId; private Long userId; + private Integer versionNo; + private Integer imageCount; + private String textStatus; + private String textContent; private String status; private String provider; private String resultCode; @@ -26,4 +30,5 @@ public class ContentModerationRecordDO extends BaseEntity { private Long reviewedBy; private LocalDateTime reviewedAt; private Integer attemptCount; + private LocalDateTime nextRetryAt; } diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/privacy/mapper/ContentModerationImageTaskMapper.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/privacy/mapper/ContentModerationImageTaskMapper.java new file mode 100644 index 00000000..f4d8e8bc --- /dev/null +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/privacy/mapper/ContentModerationImageTaskMapper.java @@ -0,0 +1,7 @@ +package com.xiaowang.jayucloud.salon.core.modules.privacy.mapper; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import com.xiaowang.jayucloud.salon.core.modules.privacy.entity.ContentModerationImageTaskDO; + +public interface ContentModerationImageTaskMapper extends BaseMapper { +} 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 36e27688..4b92f09d 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 @@ -3,5 +3,7 @@ package com.xiaowang.jayucloud.salon.core.modules.privacy.moderation; public interface ContentModerationProvider { String providerName(); - ModerationOutcome review(String contentType, String content); + ModerationOutcome reviewText(String contentType, String content, String openId); + + ModerationOutcome submitImage(String contentType, String imageUrl, String openId); } diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/privacy/moderation/LocalMockContentModerationProvider.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/privacy/moderation/LocalMockContentModerationProvider.java index fbc0a02d..33af9ad6 100644 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/privacy/moderation/LocalMockContentModerationProvider.java +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/privacy/moderation/LocalMockContentModerationProvider.java @@ -16,7 +16,16 @@ public class LocalMockContentModerationProvider implements ContentModerationProv } @Override - public ModerationOutcome review(String contentType, String content) { + public ModerationOutcome reviewText(String contentType, String content, String openId) { + return result(content); + } + + @Override + public ModerationOutcome submitImage(String contentType, String imageUrl, String openId) { + return result(imageUrl); + } + + private ModerationOutcome result(String content) { String value = content == null ? "" : content; if (value.contains("[[MOCK:FAIL]]")) throw new IllegalStateException("本地模拟审核故障"); if (value.contains("[[MOCK:REJECT]]")) { diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/privacy/moderation/ModerationOutcome.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/privacy/moderation/ModerationOutcome.java index 95f47858..b4ea0e4b 100644 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/privacy/moderation/ModerationOutcome.java +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/privacy/moderation/ModerationOutcome.java @@ -1,5 +1,9 @@ package com.xiaowang.jayucloud.salon.core.modules.privacy.moderation; -public record ModerationOutcome(Status status, String code, String reason) { +public record ModerationOutcome(Status status, String code, String reason, String remoteTaskId) { + public ModerationOutcome(Status status, String code, String reason) { + this(status, code, reason, null); + } + public enum Status { APPROVED, PENDING, REJECTED, RETRY } } diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/privacy/moderation/UnconfiguredContentModerationProvider.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/privacy/moderation/UnconfiguredContentModerationProvider.java index 4a7dd301..b54ee9be 100644 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/privacy/moderation/UnconfiguredContentModerationProvider.java +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/privacy/moderation/UnconfiguredContentModerationProvider.java @@ -17,11 +17,16 @@ public class UnconfiguredContentModerationProvider implements ContentModerationP } @Override - public ModerationOutcome review(String contentType, String content) { + public ModerationOutcome reviewText(String contentType, String content, String openId) { return new ModerationOutcome( ModerationOutcome.Status.RETRY, "PROVIDER_NOT_CONFIGURED", "内容审核平台尚未接入,内容已隔离等待人工复核" ); } + + @Override + public ModerationOutcome submitImage(String contentType, String imageUrl, String openId) { + return reviewText(contentType, imageUrl, openId); + } } 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 new file mode 100644 index 00000000..ae2c8c09 --- /dev/null +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/privacy/moderation/WechatContentModerationProvider.java @@ -0,0 +1,120 @@ +package com.xiaowang.jayucloud.salon.core.modules.privacy.moderation; + +import com.fasterxml.jackson.core.type.TypeReference; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.xiaowang.jayucloud.salon.core.modules.integration.service.WechatMiniClientService; +import com.xiaowang.jayucloud.salon.core.modules.privacy.config.ContentModerationProperties; +import org.springframework.beans.factory.annotation.Qualifier; +import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; +import org.springframework.http.HttpEntity; +import org.springframework.http.HttpHeaders; +import org.springframework.http.MediaType; +import org.springframework.stereotype.Component; +import org.springframework.util.StringUtils; +import org.springframework.web.client.RestClientException; +import org.springframework.web.client.RestTemplate; +import org.springframework.web.util.UriComponentsBuilder; + +import java.util.LinkedHashMap; +import java.util.Map; + +@Component +@ConditionalOnProperty(prefix = "jayucloud-salon.privacy.content-moderation", name = "provider", havingValue = "wechat") +public class WechatContentModerationProvider implements ContentModerationProvider { + private static final String TEXT_CHECK_URL = "https://api.weixin.qq.com/wxa/msg_sec_check"; + private static final String IMAGE_CHECK_URL = "https://api.weixin.qq.com/wxa/media_check_async"; + + private final RestTemplate restTemplate; + private final ObjectMapper objectMapper; + private final WechatMiniClientService wechatMiniClientService; + private final ContentModerationProperties properties; + + public WechatContentModerationProvider( + @Qualifier("wechatContentModerationRestTemplate") RestTemplate restTemplate, + ObjectMapper objectMapper, + WechatMiniClientService wechatMiniClientService, + ContentModerationProperties properties) { + this.restTemplate = restTemplate; + this.objectMapper = objectMapper; + this.wechatMiniClientService = wechatMiniClientService; + this.properties = properties; + } + + @Override + public String providerName() { + return "WECHAT"; + } + + @Override + public ModerationOutcome reviewText(String contentType, String content, String openId) { + if (!StringUtils.hasText(openId)) return pending("OPENID_REQUIRED", "缺少微信作者身份,转人工复核"); + if (!StringUtils.hasText(content)) return approved("EMPTY_TEXT"); + Map payload = new LinkedHashMap<>(); + payload.put("content", content); + payload.put("version", 2); + payload.put("scene", properties.getScene()); + payload.put("openid", openId); + return parseResult(post(TEXT_CHECK_URL, payload), false); + } + + @Override + public ModerationOutcome submitImage(String contentType, String imageUrl, String openId) { + if (!StringUtils.hasText(openId)) return pending("OPENID_REQUIRED", "缺少微信作者身份,转人工复核"); + if (!StringUtils.hasText(imageUrl) || !imageUrl.startsWith("https://")) { + return retry("IMAGE_URL_INVALID", "审核图片需要短期有效的 HTTPS 地址"); + } + Map payload = new LinkedHashMap<>(); + payload.put("media_url", imageUrl); + payload.put("media_type", 2); + payload.put("version", 2); + payload.put("scene", properties.getScene()); + payload.put("openid", openId); + return parseResult(post(IMAGE_CHECK_URL, payload), true); + } + + private Map post(String endpoint, Map payload) { + String url = UriComponentsBuilder.fromHttpUrl(endpoint) + .queryParam("access_token", wechatMiniClientService.getAccessTokenForContentModeration()) + .toUriString(); + HttpHeaders headers = new HttpHeaders(); + headers.setContentType(MediaType.APPLICATION_JSON); + try { + String response = restTemplate.postForObject(url, new HttpEntity<>(payload, headers), String.class); + if (!StringUtils.hasText(response)) throw new IllegalStateException("微信审核服务返回空响应"); + return objectMapper.readValue(response, new TypeReference>() {}); + } catch (RestClientException | java.io.IOException exception) { + throw new IllegalStateException("微信内容审核请求失败", exception); + } + } + + private ModerationOutcome parseResult(Map response, boolean asynchronous) { + int errorCode = number(response.get("errcode")); + if (errorCode != 0) return errorCode == 87014 + ? new ModerationOutcome(ModerationOutcome.Status.REJECTED, String.valueOf(errorCode), "微信内容安全接口判定内容违规") + : retry(String.valueOf(errorCode), "微信内容安全接口暂不可用"); + if (asynchronous) { + String taskId = text(response.get("trace_id")); + return StringUtils.hasText(taskId) + ? new ModerationOutcome(ModerationOutcome.Status.PENDING, "WECHAT_ASYNC", "等待微信图片审核回调", taskId) + : retry("TRACE_ID_MISSING", "微信图片审核未返回任务标识"); + } + Object resultRaw = response.get("result"); + if (resultRaw instanceof Map) { + Object suggest = ((Map) resultRaw).get("suggest"); + if ("pass".equalsIgnoreCase(text(suggest))) return approved("WECHAT_PASS"); + if ("review".equalsIgnoreCase(text(suggest))) return pending("WECHAT_REVIEW", "微信要求人工复核"); + if ("risky".equalsIgnoreCase(text(suggest))) return new ModerationOutcome(ModerationOutcome.Status.REJECTED, "WECHAT_RISKY", "微信内容安全接口判定内容违规"); + } + return retry("RESULT_MISSING", "微信内容安全接口未返回明确审核结论"); + } + + private int number(Object value) { + try { return value == null ? -1 : Integer.parseInt(String.valueOf(value)); } + catch (NumberFormatException ignored) { return -1; } + } + + private String text(Object value) { return value == null ? null : String.valueOf(value); } + private ModerationOutcome approved(String code) { return new ModerationOutcome(ModerationOutcome.Status.APPROVED, code, "审核通过"); } + private ModerationOutcome pending(String code, String reason) { return new ModerationOutcome(ModerationOutcome.Status.PENDING, code, reason); } + private ModerationOutcome retry(String code, String reason) { return new ModerationOutcome(ModerationOutcome.Status.RETRY, code, reason); } +} diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/privacy/scheduler/ContentModerationRetryScheduler.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/privacy/scheduler/ContentModerationRetryScheduler.java new file mode 100644 index 00000000..fd0f650a --- /dev/null +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/privacy/scheduler/ContentModerationRetryScheduler.java @@ -0,0 +1,20 @@ +package com.xiaowang.jayucloud.salon.core.modules.privacy.scheduler; + +import com.xiaowang.jayucloud.salon.core.modules.privacy.service.ContentModerationService; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.scheduling.annotation.Scheduled; +import org.springframework.stereotype.Component; + +@Slf4j +@Component +@RequiredArgsConstructor +public class ContentModerationRetryScheduler { + private final ContentModerationService contentModerationService; + + @Scheduled(cron = "${jayucloud-salon.privacy.content-moderation.retry-cron:0 */2 * * * *}") + public void retryFailedImageTasks() { + int count = contentModerationService.retryFailedImageTasks(); + if (count > 0) log.info("内容审核图片重试任务完成, count={}", count); + } +} 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 3258b039..8b5360c0 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 @@ -2,11 +2,16 @@ package com.xiaowang.jayucloud.salon.core.modules.privacy.service; import com.xiaowang.jayucloud.salon.core.modules.privacy.entity.ContentModerationRecordDO; import com.xiaowang.jayucloud.salon.core.modules.privacy.vo.ContentModerationResultVO; +import com.xiaowang.jayucloud.salon.core.modules.privacy.vo.ContentModerationRecordVO; import java.util.List; public interface ContentModerationService { ContentModerationResultVO assess(String contentType, Long businessId, Long userId, String content, String payloadJson); - List listPending(); + ContentModerationResultVO assessVersion(String contentType, Long businessId, Long userId, String text, + String payloadJson, List imageFileIds); + List listPending(); boolean review(Long reviewerId, Long recordId, boolean approved, String reason); + boolean handleWechatImageResult(String providerTaskId, String suggest, String reason); + 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 feb7e451..886f5094 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 @@ -3,121 +3,538 @@ package com.xiaowang.jayucloud.salon.core.modules.privacy.service.impl; import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; -import com.xiaowang.jayucloud.salon.core.modules.product.entity.ProductDO; -import com.xiaowang.jayucloud.salon.core.modules.product.mapper.ProductMapper; import com.xiaowang.jayucloud.salon.core.modules.content.entity.CommentDO; import com.xiaowang.jayucloud.salon.core.modules.content.mapper.CommentMapper; +import com.xiaowang.jayucloud.salon.core.modules.file.service.ObjectStorageFileService; +import com.xiaowang.jayucloud.salon.core.modules.file.vo.ObjectStorageFileVO; +import com.xiaowang.jayucloud.salon.core.modules.integration.entity.WechatMiniBindingDO; +import com.xiaowang.jayucloud.salon.core.modules.integration.mapper.WechatMiniBindingMapper; +import com.xiaowang.jayucloud.salon.core.modules.integration.service.WechatMiniClientService; +import com.xiaowang.jayucloud.salon.core.modules.message.entity.AnnouncementDO; +import com.xiaowang.jayucloud.salon.core.modules.message.entity.SystemMessageDO; +import com.xiaowang.jayucloud.salon.core.modules.message.mapper.AnnouncementMapper; +import com.xiaowang.jayucloud.salon.core.modules.message.mapper.SystemMessageMapper; +import com.xiaowang.jayucloud.salon.core.modules.privacy.config.ContentModerationProperties; +import com.xiaowang.jayucloud.salon.core.modules.privacy.entity.ContentModerationImageTaskDO; import com.xiaowang.jayucloud.salon.core.modules.privacy.entity.ContentModerationRecordDO; +import com.xiaowang.jayucloud.salon.core.modules.privacy.mapper.ContentModerationImageTaskMapper; import com.xiaowang.jayucloud.salon.core.modules.privacy.mapper.ContentModerationRecordMapper; import com.xiaowang.jayucloud.salon.core.modules.privacy.moderation.ContentModerationProvider; import com.xiaowang.jayucloud.salon.core.modules.privacy.moderation.ModerationOutcome; import com.xiaowang.jayucloud.salon.core.modules.privacy.service.ContentModerationService; +import com.xiaowang.jayucloud.salon.core.modules.privacy.vo.ContentModerationRecordVO; import com.xiaowang.jayucloud.salon.core.modules.privacy.vo.ContentModerationResultVO; +import com.xiaowang.jayucloud.salon.core.modules.product.entity.ProductDO; +import com.xiaowang.jayucloud.salon.core.modules.product.mapper.ProductMapper; +import com.xiaowang.jayucloud.salon.core.modules.product.entity.EffectDiagramDO; +import com.xiaowang.jayucloud.salon.core.modules.product.mapper.EffectDiagramMapper; +import com.xiaowang.jayucloud.salon.core.modules.artist.entity.NailArtistInfoDO; +import com.xiaowang.jayucloud.salon.core.modules.artist.mapper.NailArtistInfoMapper; +import com.xiaowang.jayucloud.salon.core.modules.order.entity.OrderArtistReviewDO; +import com.xiaowang.jayucloud.salon.core.modules.order.mapper.OrderArtistReviewMapper; +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.user.entity.UserDO; import com.xiaowang.jayucloud.salon.core.modules.user.mapper.UserMapper; import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; import org.springframework.stereotype.Service; -import org.springframework.transaction.annotation.Transactional; import org.springframework.transaction.annotation.Propagation; +import org.springframework.transaction.annotation.Transactional; import org.springframework.util.StringUtils; import java.time.LocalDateTime; +import java.util.ArrayList; +import java.util.Collections; +import java.util.LinkedHashSet; import java.util.List; +import java.util.Set; +import java.util.Comparator; +@Slf4j @Service @RequiredArgsConstructor public class ContentModerationServiceImpl implements ContentModerationService { private final ContentModerationProvider provider; private final ContentModerationRecordMapper recordMapper; + private final ContentModerationImageTaskMapper imageTaskMapper; private final ProductMapper productMapper; + private final EffectDiagramMapper effectDiagramMapper; + private final NailArtistInfoMapper nailArtistInfoMapper; + private final OrderArtistReviewMapper orderArtistReviewMapper; private final CommentMapper commentMapper; + private final ShopMapper shopMapper; + private final AnnouncementMapper announcementMapper; + private final SystemMessageMapper systemMessageMapper; private final UserMapper userMapper; + private final WechatMiniBindingMapper bindingMapper; + private final WechatMiniClientService wechatMiniClientService; + private final ObjectStorageFileService objectStorageFileService; + private final ContentModerationProperties properties; private final ObjectMapper objectMapper; @Override - @Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRES_NEW) + @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class) public ContentModerationResultVO assess(String contentType, Long businessId, Long userId, String content, String payloadJson) { - ModerationOutcome outcome; - try { - outcome = provider.review(contentType, content); - } catch (RuntimeException exception) { - outcome = new ModerationOutcome(ModerationOutcome.Status.RETRY, "PROVIDER_FAILURE", "内容审核服务暂不可用,内容已隔离等待重试"); - } + return assessVersion(contentType, businessId, userId, content, payloadJson, Collections.emptyList()); + } + + @Override + @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class) + public ContentModerationResultVO assessVersion(String contentType, Long businessId, Long userId, String text, + String payloadJson, List imageFileIds) { + List normalizedImageIds = imageFileIds == null ? Collections.emptyList() : imageFileIds.stream() + .filter(fileId -> fileId != null && fileId > 0) + .collect(java.util.stream.Collectors.collectingAndThen( + java.util.stream.Collectors.toCollection(LinkedHashSet::new), ArrayList::new)); ContentModerationRecordDO record = new ContentModerationRecordDO(); record.setContentType(contentType); record.setBusinessId(businessId); record.setUserId(userId); - record.setStatus(outcome.status().name()); + record.setVersionNo(nextVersion(contentType, businessId, userId)); + record.setTextContent(text); + record.setImageCount(normalizedImageIds.size()); record.setProvider(provider.providerName()); - record.setResultCode(outcome.code()); - record.setReason(outcome.reason()); - record.setPayloadJson(outcome.status() == ModerationOutcome.Status.APPROVED ? null : payloadJson); + record.setPayloadJson(payloadJson); record.setAttemptCount(1); + int maxRetries = Math.max(0, properties.getMaxRetries() == null ? 3 : properties.getMaxRetries()); + + String openId = resolveOpenId(userId); + ModerationOutcome textOutcome = StringUtils.hasText(openId) + ? safeTextReview(contentType, text, openId) + : outcome(ModerationOutcome.Status.PENDING, "OPENID_REQUIRED", "发布者未绑定可核验的微信身份,转人工复核"); + boolean textRetryExhausted = exhausted(textOutcome, 1, maxRetries); + record.setTextStatus(textRetryExhausted ? "PENDING" : textOutcome.status().name()); + record.setResultCode(textOutcome.code()); + record.setReason(textRetryExhausted ? "自动重试已关闭,转人工复核" : textOutcome.reason()); + record.setStatus(textRetryExhausted ? "PENDING" : textOutcome.status().name()); + record.setNextRetryAt(textOutcome.status() == ModerationOutcome.Status.RETRY && !textRetryExhausted ? LocalDateTime.now().plusMinutes(2) : null); recordMapper.insert(record); - ContentModerationResultVO result = new ContentModerationResultVO(); - result.setRecordId(record.getId()); - result.setStatus(outcome.status().name()); - result.setReason(outcome.reason()); - return result; + if (!normalizedImageIds.isEmpty()) { + for (Long fileId : normalizedImageIds) { + ContentModerationImageTaskDO task = new ContentModerationImageTaskDO(); + task.setRecordId(record.getId()); + task.setFileId(fileId); + task.setAttemptCount(1); + ModerationOutcome imageOutcome = StringUtils.hasText(openId) + ? safeImageReview(contentType, fileId, openId) + : outcome(ModerationOutcome.Status.PENDING, "OPENID_REQUIRED", "发布者未绑定可核验的微信身份,转人工复核"); + boolean imageRetryExhausted = exhausted(imageOutcome, 1, maxRetries); + task.setStatus(imageRetryExhausted ? "PENDING" : imageOutcome.status().name()); + task.setResultCode(imageOutcome.code()); + task.setReason(imageRetryExhausted ? "自动重试已关闭,转人工复核" : imageOutcome.reason()); + task.setProviderTaskId(imageOutcome.remoteTaskId()); + task.setNextRetryAt(imageOutcome.status() == ModerationOutcome.Status.RETRY && !imageRetryExhausted ? LocalDateTime.now().plusMinutes(2) : null); + imageTaskMapper.insert(task); + } + } + refreshAggregate(record); + return result(record); } @Override - public List listPending() { - return recordMapper.selectList(new LambdaQueryWrapper() + public List listPending() { + List records = recordMapper.selectList(new LambdaQueryWrapper() .in(ContentModerationRecordDO::getStatus, "PENDING", "RETRY") .orderByAsc(ContentModerationRecordDO::getCreateTime)); + List result = new ArrayList<>(); + for (ContentModerationRecordDO record : records) { + ContentModerationRecordVO vo = new ContentModerationRecordVO(); + vo.setId(record.getId()); + vo.setContentType(record.getContentType()); + vo.setBusinessId(record.getBusinessId()); + vo.setStatus(record.getStatus()); + vo.setResultCode(record.getResultCode()); + vo.setReason(record.getReason()); + vo.setTextPreview(record.getTextContent()); + vo.setAttemptCount(record.getAttemptCount()); + vo.setCreateTime(record.getCreateTime()); + UserDO author = record.getUserId() == null ? null : userMapper.selectById(record.getUserId()); + vo.setAuthorName(author == null ? "后台/未知发布者" : author.getNickname()); + vo.setImages(loadImagePreviews(record)); + result.add(vo); + } + return result; } @Override @Transactional(rollbackFor = Exception.class) public boolean review(Long reviewerId, Long recordId, boolean approved, String reason) { if (!StringUtils.hasText(reason)) throw new IllegalArgumentException("复核说明不能为空"); - ContentModerationRecordDO record = recordMapper.selectById(recordId); - if (record == null || !("PENDING".equals(record.getStatus()) || "RETRY".equals(record.getStatus()))) { - throw new IllegalStateException("该内容已复核或不存在"); + ContentModerationRecordDO record = lockVersionRecord(recordId); + if (record == null || !isReviewable(record.getStatus())) throw new IllegalStateException("该内容已复核或不存在"); + List tasks = imageTaskMapper.selectList(new LambdaQueryWrapper() + .eq(ContentModerationImageTaskDO::getRecordId, recordId) + .orderByAsc(ContentModerationImageTaskDO::getId) + .last("FOR UPDATE")); + if (approved && tasks.size() != (record.getImageCount() == null ? 0 : record.getImageCount())) { + throw new IllegalStateException("图片审核任务不完整,不能通过复核"); } - if (approved) applyApprovedPayload(record); - if ("COMMENT".equals(record.getContentType()) && record.getBusinessId() != null) { - CommentDO comment = commentMapper.selectById(record.getBusinessId()); - if (comment != null && !Integer.valueOf(1).equals(comment.getIsDelete())) { - comment.setModerationStatus(approved ? "APPROVED" : "REJECTED"); - comment.setUpdateTime(LocalDateTime.now()); - commentMapper.updateById(comment); + if (approved) { + for (ContentModerationImageTaskDO task : tasks) { + try { + objectStorageFileService.createTemporaryModerationUrl(task.getFileId(), properties.getImageUrlExpireMinutes()); + } catch (RuntimeException exception) { + throw new IllegalStateException("存在无法安全预览的图片,不能通过复核"); + } } } + for (ContentModerationImageTaskDO task : tasks) { + task.setStatus(approved ? "APPROVED" : "REJECTED"); + task.setReason("由管理员人工复核"); + task.setProviderTaskId(null); + task.setNextRetryAt(null); + imageTaskMapper.updateById(task); + } + record.setTextStatus(approved ? "APPROVED" : "REJECTED"); record.setStatus(approved ? "APPROVED" : "REJECTED"); record.setReviewedBy(reviewerId); record.setReviewedAt(LocalDateTime.now()); record.setReason(reason.trim()); + record.setNextRetryAt(null); + if (approved && isCurrentVersionLocked(record)) applyApprovedPayload(record); record.setPayloadJson(null); return recordMapper.updateById(record) > 0; } + @Override + @Transactional(rollbackFor = Exception.class) + public boolean handleWechatImageResult(String providerTaskId, String suggest, String reason) { + if (!StringUtils.hasText(providerTaskId)) return false; + ContentModerationImageTaskDO candidate = imageTaskMapper.selectOne(new LambdaQueryWrapper() + .eq(ContentModerationImageTaskDO::getProviderTaskId, providerTaskId).last("LIMIT 1")); + if (candidate == null) return false; + if (!isReviewable(candidate.getStatus())) return true; + + ContentModerationRecordDO record = lockVersionRecord(candidate.getRecordId()); + if (record == null || !isReviewable(record.getStatus())) return true; + + ContentModerationImageTaskDO task = imageTaskMapper.selectOne(new LambdaQueryWrapper() + .eq(ContentModerationImageTaskDO::getId, candidate.getId()) + .eq(ContentModerationImageTaskDO::getProviderTaskId, providerTaskId) + .last("FOR UPDATE")); + if (task == null || !isReviewable(task.getStatus())) return task != null; + if ("pass".equalsIgnoreCase(suggest)) task.setStatus("APPROVED"); + else if ("risky".equalsIgnoreCase(suggest)) task.setStatus("REJECTED"); + else task.setStatus("PENDING"); + task.setResultCode("WECHAT_CALLBACK_" + (suggest == null ? "UNKNOWN" : suggest.toUpperCase())); + task.setReason(reason); + task.setNextRetryAt(null); + imageTaskMapper.updateById(task); + refreshAggregate(record); + return true; + } + + @Override + @Transactional(rollbackFor = Exception.class) + public int retryFailedImageTasks() { + int maxRetries = properties.getMaxRetries() == null ? 3 : properties.getMaxRetries(); + List tasks = imageTaskMapper.selectList(new LambdaQueryWrapper() + .eq(ContentModerationImageTaskDO::getStatus, "RETRY") + .le(ContentModerationImageTaskDO::getAttemptCount, maxRetries) + .and(query -> query.isNull(ContentModerationImageTaskDO::getNextRetryAt) + .or().le(ContentModerationImageTaskDO::getNextRetryAt, LocalDateTime.now())) + .orderByAsc(ContentModerationImageTaskDO::getRecordId) + .orderByAsc(ContentModerationImageTaskDO::getId) + .last("LIMIT 100")); + int attempted = 0; + for (ContentModerationImageTaskDO candidate : tasks) { + ContentModerationRecordDO record = lockVersionRecord(candidate.getRecordId()); + String openId = record == null ? null : resolveOpenId(record.getUserId()); + if (record == null || !isReviewable(record.getStatus()) || !StringUtils.hasText(openId)) continue; + ContentModerationImageTaskDO task = imageTaskMapper.selectOne(new LambdaQueryWrapper() + .eq(ContentModerationImageTaskDO::getId, candidate.getId()) + .eq(ContentModerationImageTaskDO::getStatus, "RETRY") + .le(ContentModerationImageTaskDO::getAttemptCount, maxRetries) + .and(query -> query.isNull(ContentModerationImageTaskDO::getNextRetryAt) + .or().le(ContentModerationImageTaskDO::getNextRetryAt, LocalDateTime.now())) + .last("FOR UPDATE")); + if (task == null) continue; + attempted++; + task.setProviderTaskId(null); + ModerationOutcome outcome = safeImageReview(record.getContentType(), task.getFileId(), openId); + task.setAttemptCount((task.getAttemptCount() == null ? 0 : task.getAttemptCount()) + 1); + task.setStatus(exhausted(outcome, task.getAttemptCount(), maxRetries) ? "PENDING" : outcome.status().name()); + task.setResultCode(outcome.code()); + task.setReason(exhausted(outcome, task.getAttemptCount(), maxRetries) ? "自动重试次数已耗尽,转人工复核" : outcome.reason()); + task.setProviderTaskId(outcome.remoteTaskId()); + task.setNextRetryAt(outcome.status() == ModerationOutcome.Status.RETRY && !exhausted(outcome, task.getAttemptCount(), maxRetries) ? LocalDateTime.now().plusMinutes(2) : null); + imageTaskMapper.updateById(task); + refreshAggregate(record); + } + List records = recordMapper.selectList(new LambdaQueryWrapper() + .eq(ContentModerationRecordDO::getTextStatus, "RETRY") + .le(ContentModerationRecordDO::getAttemptCount, maxRetries) + .and(query -> query.isNull(ContentModerationRecordDO::getNextRetryAt) + .or().le(ContentModerationRecordDO::getNextRetryAt, LocalDateTime.now())) + .orderByAsc(ContentModerationRecordDO::getId) + .last("LIMIT 100")); + for (ContentModerationRecordDO candidate : records) { + ContentModerationRecordDO record = lockVersionRecord(candidate.getId()); + if (record == null || !"RETRY".equals(record.getTextStatus()) + || (record.getNextRetryAt() != null && record.getNextRetryAt().isAfter(LocalDateTime.now()))) continue; + String openId = resolveOpenId(record.getUserId()); + if (!isReviewable(record.getStatus()) || !StringUtils.hasText(openId)) continue; + attempted++; + ModerationOutcome outcome = safeTextReview(record.getContentType(), record.getTextContent(), openId); + record.setAttemptCount((record.getAttemptCount() == null ? 0 : record.getAttemptCount()) + 1); + boolean exhausted = exhausted(outcome, record.getAttemptCount(), maxRetries); + record.setTextStatus(exhausted ? "PENDING" : outcome.status().name()); + record.setStatus(exhausted ? "PENDING" : outcome.status().name()); + record.setResultCode(outcome.code()); + record.setReason(exhausted ? "自动重试次数已耗尽,转人工复核" : outcome.reason()); + record.setNextRetryAt(outcome.status() == ModerationOutcome.Status.RETRY && !exhausted ? LocalDateTime.now().plusMinutes(2) : null); + recordMapper.updateById(record); + refreshAggregate(record); + } + return attempted; + } + + private void refreshAggregate(ContentModerationRecordDO record) { + List tasks = imageTaskMapper.selectList(new LambdaQueryWrapper() + .eq(ContentModerationImageTaskDO::getRecordId, record.getId())); + boolean rejected = "REJECTED".equals(record.getTextStatus()) || tasks.stream().anyMatch(task -> "REJECTED".equals(task.getStatus())); + boolean retry = "RETRY".equals(record.getTextStatus()) || tasks.stream().anyMatch(task -> "RETRY".equals(task.getStatus())); + boolean allImagesApproved = tasks.stream().allMatch(task -> "APPROVED".equals(task.getStatus())); + boolean pending = "PENDING".equals(record.getTextStatus()) || tasks.stream().anyMatch(task -> "PENDING".equals(task.getStatus())); + int expectedImageCount = record.getImageCount() == null ? 0 : record.getImageCount(); + if (tasks.size() != expectedImageCount) pending = true; + if (rejected) record.setStatus("REJECTED"); + else if (retry) record.setStatus("RETRY"); + else if (pending) record.setStatus("PENDING"); + else if (allImagesApproved && "APPROVED".equals(record.getTextStatus())) { + if (isCurrentVersionLocked(record)) { + applyApprovedPayload(record); + } + record.setStatus("APPROVED"); + record.setPayloadJson(null); + record.setReason("文字及全部图片审核通过"); + record.setNextRetryAt(null); + } + recordMapper.updateById(record); + } + + private boolean isCurrentVersionLocked(ContentModerationRecordDO record) { + ContentModerationRecordDO latest = currentVersion(record, true); + return latest != null && record.getId().equals(latest.getId()); + } + + private ContentModerationRecordDO currentVersion(ContentModerationRecordDO record, boolean lock) { + return latestVersion(versionScope(record, lock)); + } + + private ContentModerationRecordDO lockVersionRecord(Long recordId) { + if (recordId == null) return null; + ContentModerationRecordDO snapshot = recordMapper.selectById(recordId); + if (snapshot == null) return null; + return versionScope(snapshot, true).stream() + .filter(record -> recordId.equals(record.getId())) + .findFirst() + .orElse(null); + } + + private List versionScope(ContentModerationRecordDO record, boolean lock) { + LambdaQueryWrapper query = new LambdaQueryWrapper() + .eq(ContentModerationRecordDO::getContentType, record.getContentType()); + if (record.getBusinessId() != null) { + query.eq(ContentModerationRecordDO::getBusinessId, record.getBusinessId()); + } else if (record.getUserId() != null) { + query.isNull(ContentModerationRecordDO::getBusinessId).eq(ContentModerationRecordDO::getUserId, record.getUserId()); + } else { + query.isNull(ContentModerationRecordDO::getBusinessId).isNull(ContentModerationRecordDO::getUserId); + } + query.orderByAsc(ContentModerationRecordDO::getId); + if (lock) query.last("FOR UPDATE"); + return recordMapper.selectList(query); + } + + private ContentModerationRecordDO latestVersion(List records) { + if (records == null || records.isEmpty()) return null; + return records.stream() + .max(Comparator.comparing(ContentModerationRecordDO::getVersionNo, + Comparator.nullsFirst(Comparator.naturalOrder()))) + .orElse(null); + } + private void applyApprovedPayload(ContentModerationRecordDO record) { if (!StringUtils.hasText(record.getPayloadJson())) return; try { JsonNode payload = objectMapper.readTree(record.getPayloadJson()); - if ("PRODUCT".equals(record.getContentType()) && record.getBusinessId() != null) { - ProductDO product = productMapper.selectById(record.getBusinessId()); - if (product != null && !Integer.valueOf(1).equals(product.getIsDelete())) { - product.setFrontVisible(payload.path("frontVisible").asInt(1)); - product.setUpdateTime(LocalDateTime.now()); - productMapper.updateById(product); - } - } else if (("USER_PROFILE".equals(record.getContentType()) || "USER_AVATAR".equals(record.getContentType())) - && record.getUserId() != null) { - UserDO user = userMapper.selectById(record.getUserId()); - if (user != null && !Integer.valueOf(1).equals(user.getIsDelete())) { - if (payload.hasNonNull("nickname")) user.setNickname(payload.path("nickname").asText()); - if (payload.hasNonNull("signature")) user.setSignature(payload.path("signature").asText()); - if (payload.hasNonNull("avatar")) user.setAvatar(payload.path("avatar").asText()); - user.setUpdateTime(LocalDateTime.now()); - userMapper.updateById(user); - } + switch (record.getContentType()) { + case "PRODUCT": applyProduct(record.getBusinessId(), payload); break; + case "EFFECT_DIAGRAM": applyEffectDiagram(record.getBusinessId(), payload); break; + case "COMMENT": applyComment(record.getBusinessId(), payload); break; + case "ORDER_ARTIST_REVIEW": applyOrderArtistReview(record.getBusinessId(), payload); break; + case "USER_PROFILE": case "USER_AVATAR": applyUser(record.getBusinessId() == null ? record.getUserId() : record.getBusinessId(), payload); break; + case "NAIL_ARTIST_PROFILE": applyNailArtistProfile(record.getBusinessId(), payload); break; + case "SHOP": applyShop(record.getBusinessId(), payload); break; + case "ANNOUNCEMENT": applyAnnouncement(record.getBusinessId(), payload); break; + case "SYSTEM_MESSAGE": applySystemMessage(record.getBusinessId(), payload); break; + default: throw new IllegalStateException("不支持的审核内容类型: " + record.getContentType()); } } catch (Exception exception) { - throw new IllegalStateException("隔离内容载荷无法解析,未应用复核结果", exception); + throw new IllegalStateException("隔离内容快照无法应用", exception); } } + + private void applyProduct(Long id, JsonNode p) { + ProductDO row = productMapper.selectById(id); if (row == null) return; + if (p.has("shopId")) row.setShopId(p.path("shopId").asLong()); + if (p.has("title")) row.setTitle(p.path("title").asText()); + if (p.has("description")) row.setDescription(p.path("description").asText(null)); + if (p.has("targetAudience")) row.setTargetAudience(p.path("targetAudience").asText(null)); + if (p.has("precautions")) row.setPrecautions(p.path("precautions").asText(null)); + if (p.has("imageFileIds")) row.setImageFileIds(p.path("imageFileIds").asText(null)); + if (p.has("price")) row.setPrice(p.path("price").decimalValue()); + if (p.has("tags")) row.setTags(p.path("tags").asText(null)); + if (p.has("approximateDuration")) row.setApproximateDuration(p.path("approximateDuration").asText(null)); + if (p.has("bookableArtists")) row.setBookableArtists(p.path("bookableArtists").asText(null)); + if (p.has("availableCoupons")) row.setAvailableCoupons(p.path("availableCoupons").asText(null)); + row.setFrontVisible(p.path("frontVisible").asInt(1)); + row.setModerationStatus("APPROVED"); + row.setUpdateTime(LocalDateTime.now()); productMapper.updateById(row); + } + + private void applyEffectDiagram(Long id, JsonNode p) { + EffectDiagramDO row = effectDiagramMapper.selectById(id); + if (row == null || Integer.valueOf(1).equals(row.getIsDelete())) return; + if (p.has("productId")) row.setProductId(p.path("productId").asLong()); + if (p.has("category")) row.setCategory(p.path("category").asText(null)); + if (p.has("imageFileIds")) row.setImageFileIds(p.path("imageFileIds").asText(null)); + if (p.has("description")) row.setDescription(p.path("description").asText(null)); + if (p.has("price")) row.setPrice(p.path("price").isNull() ? null : p.path("price").decimalValue()); + if (p.has("duration")) row.setDuration(p.path("duration").asText(null)); + if (p.has("tag")) row.setTag(p.path("tag").asText(null)); + row.setModerationStatus("APPROVED"); + row.setUpdateTime(LocalDateTime.now()); + effectDiagramMapper.updateById(row); + } + + private void applyComment(Long id, JsonNode p) { + CommentDO row = commentMapper.selectById(id); if (row == null) return; + row.setCommentContent(p.path("commentContent").asText(row.getCommentContent())); + if (p.has("imageFileIds")) row.setImageFileIds(p.path("imageFileIds").asText(null)); + row.setModerationStatus("APPROVED"); row.setUpdateTime(LocalDateTime.now()); commentMapper.updateById(row); + } + + private void applyOrderArtistReview(Long id, JsonNode p) { + OrderArtistReviewDO row = orderArtistReviewMapper.selectById(id); + if (row == null || Integer.valueOf(1).equals(row.getIsDelete())) return; + if (p.has("content")) row.setContent(p.path("content").asText(null)); + if (p.has("imageFileIds")) row.setImageFileIds(p.path("imageFileIds").asText(null)); + row.setModerationStatus("APPROVED"); + row.setUpdateTime(LocalDateTime.now()); + orderArtistReviewMapper.updateById(row); + } + + private void applyUser(Long id, JsonNode p) { + UserDO row = userMapper.selectById(id); if (row == null) return; + if (p.hasNonNull("nickname")) row.setNickname(p.path("nickname").asText()); + if (p.has("signature")) row.setSignature(p.path("signature").asText(null)); + if (p.has("avatar")) row.setAvatar(p.path("avatar").asText(null)); + if (p.has("wechatQrCode")) row.setWechatQrCode(p.path("wechatQrCode").asText(null)); + row.setProfileModerationStatus("APPROVED"); + row.setUpdateTime(LocalDateTime.now()); userMapper.updateById(row); + } + + private void applyNailArtistProfile(Long id, JsonNode p) { + NailArtistInfoDO row = nailArtistInfoMapper.selectById(id); + if (row == null || Integer.valueOf(1).equals(row.getIsDelete())) return; + if (p.has("identity")) row.setIdentity(p.path("identity").asText(null)); + if (p.has("experience")) row.setExperience(p.path("experience").isNull() ? null : p.path("experience").asInt()); + if (p.has("skills")) row.setSkills(p.path("skills").asText(null)); + if (p.has("portfolio")) row.setPortfolio(p.path("portfolio").asText(null)); + row.setModerationStatus("APPROVED"); + row.setUpdateTime(LocalDateTime.now()); + nailArtistInfoMapper.updateById(row); + } + + private void applyShop(Long id, JsonNode p) { + ShopDO row = shopMapper.selectById(id); if (row == null) return; + if (p.has("shopName")) row.setShopName(p.path("shopName").asText()); + if (p.has("description")) row.setDescription(p.path("description").asText(null)); + if (p.has("address")) row.setAddress(p.path("address").asText()); + if (p.has("mapProvider")) row.setMapProvider(p.path("mapProvider").asText(null)); + if (p.has("longitude")) row.setLongitude(p.path("longitude").isNull() ? null : p.path("longitude").decimalValue()); + if (p.has("latitude")) row.setLatitude(p.path("latitude").isNull() ? null : p.path("latitude").decimalValue()); + if (p.has("businessHours")) row.setBusinessHours(p.path("businessHours").asText(null)); + if (p.has("coverImageFileId")) row.setCoverImageFileId(p.path("coverImageFileId").asText(null)); + if (p.has("imageFileIds")) row.setImageFileIds(p.path("imageFileIds").asText(null)); + if (p.has("themeBackgroundImageFileId")) row.setThemeBackgroundImageFileId(p.path("themeBackgroundImageFileId").asText(null)); + if (p.has("themePrimaryColor")) row.setThemePrimaryColor(p.path("themePrimaryColor").asText(null)); + if (p.has("themeSecondaryColor")) row.setThemeSecondaryColor(p.path("themeSecondaryColor").asText(null)); + if (p.has("themeAccentColor")) row.setThemeAccentColor(p.path("themeAccentColor").asText(null)); + if (p.has("themePageBgColor")) row.setThemePageBgColor(p.path("themePageBgColor").asText(null)); + if (p.has("themeCardBgColor")) row.setThemeCardBgColor(p.path("themeCardBgColor").asText(null)); + row.setModerationStatus("APPROVED"); row.setUpdateTime(LocalDateTime.now()); shopMapper.updateById(row); + } + + private void applyAnnouncement(Long id, JsonNode p) { + AnnouncementDO row = announcementMapper.selectById(id); if (row == null) return; + row.setTitle(p.path("title").asText(row.getTitle())); row.setContent(p.path("content").asText(row.getContent())); + if (p.has("imageFileIds")) row.setImageFileIds(p.path("imageFileIds").asText(null)); + row.setStatus(p.path("status").asInt(1)); row.setModerationStatus("APPROVED"); row.setUpdateTime(LocalDateTime.now()); announcementMapper.updateById(row); + } + + private void applySystemMessage(Long id, JsonNode p) { + SystemMessageDO row = systemMessageMapper.selectById(id); if (row == null) return; + row.setTitle(p.path("title").asText(row.getTitle())); row.setContent(p.path("content").asText(row.getContent())); + if (p.has("imageFileId")) row.setImageFileId(p.path("imageFileId").isNull() ? null : p.path("imageFileId").asLong()); + row.setStatus(p.path("status").asInt(1)); row.setModerationStatus("APPROVED"); row.setUpdateTime(LocalDateTime.now()); systemMessageMapper.updateById(row); + } + + private List loadImagePreviews(ContentModerationRecordDO record) { + List previews = new ArrayList<>(); + for (ContentModerationImageTaskDO task : imageTaskMapper.selectList(new LambdaQueryWrapper().eq(ContentModerationImageTaskDO::getRecordId, record.getId()))) { + ContentModerationRecordVO.ImagePreview image = new ContentModerationRecordVO.ImagePreview(); image.setFileId(task.getFileId()); image.setStatus(task.getStatus()); + try { image.setUrl(objectStorageFileService.createTemporaryModerationUrl(task.getFileId(), properties.getImageUrlExpireMinutes())); } + catch (RuntimeException exception) { log.warn("审核图片安全预览生成失败, taskId={}", task.getId()); } + previews.add(image); + } + return previews; + } + + private ModerationOutcome safeTextReview(String type, String text, String openId) { + try { return provider.reviewText(type, text, openId); } + catch (RuntimeException exception) { return outcome(ModerationOutcome.Status.RETRY, "PROVIDER_FAILURE", "内容审核服务暂不可用,内容已隔离等待重试"); } + } + + private ModerationOutcome safeImageReview(String type, Long fileId, String openId) { + try { + String url = objectStorageFileService.createTemporaryModerationUrl(fileId, properties.getImageUrlExpireMinutes()); + return provider.submitImage(type, url, openId); + } catch (RuntimeException exception) { + return outcome(ModerationOutcome.Status.RETRY, "IMAGE_REVIEW_FAILURE", "图片审核暂不可用,内容已隔离等待重试"); + } + } + + private String resolveOpenId(Long userId) { + if (userId == null) return null; + try { + String appId = wechatMiniClientService.getConfiguredAppId(); + WechatMiniBindingDO binding = bindingMapper.selectOne(new LambdaQueryWrapper() + .eq(WechatMiniBindingDO::getUserId, userId).eq(WechatMiniBindingDO::getAppId, appId) + .eq(WechatMiniBindingDO::getStatus, 1).last("LIMIT 1")); + return binding == null ? null : binding.getOpenId(); + } catch (RuntimeException exception) { return null; } + } + + private int nextVersion(String type, Long businessId, Long userId) { + ContentModerationRecordDO scope = new ContentModerationRecordDO(); + scope.setContentType(type); + scope.setBusinessId(businessId); + scope.setUserId(userId); + ContentModerationRecordDO latest = latestVersion(versionScope(scope, true)); + return latest == null || latest.getVersionNo() == null ? 1 : latest.getVersionNo() + 1; + } + + private ContentModerationResultVO result(ContentModerationRecordDO record) { + ContentModerationResultVO vo = new ContentModerationResultVO(); vo.setRecordId(record.getId()); vo.setStatus(record.getStatus()); vo.setReason(record.getReason()); return vo; + } + private boolean isReviewable(String status) { return "PENDING".equals(status) || "RETRY".equals(status); } + private boolean exhausted(ModerationOutcome outcome, int attempts, int maxRetries) { + return outcome.status() == ModerationOutcome.Status.RETRY && attempts > Math.max(0, maxRetries); + } + private ModerationOutcome outcome(ModerationOutcome.Status status, String code, String reason) { return new ModerationOutcome(status, code, reason); } } diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/privacy/support/WechatCallbackCrypto.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/privacy/support/WechatCallbackCrypto.java new file mode 100644 index 00000000..0fa13211 --- /dev/null +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/privacy/support/WechatCallbackCrypto.java @@ -0,0 +1,82 @@ +package com.xiaowang.jayucloud.salon.core.modules.privacy.support; + +import org.springframework.stereotype.Component; +import org.springframework.util.StringUtils; +import org.w3c.dom.Document; +import org.xml.sax.InputSource; + +import javax.crypto.Cipher; +import javax.crypto.spec.IvParameterSpec; +import javax.crypto.spec.SecretKeySpec; +import javax.xml.parsers.DocumentBuilderFactory; +import java.io.ByteArrayInputStream; +import java.io.StringReader; +import java.nio.ByteBuffer; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.util.Arrays; +import java.util.Base64; +import java.util.HexFormat; +import java.util.List; +import java.util.stream.Collectors; + +@Component +public class WechatCallbackCrypto { + public boolean verifyPlain(String token, String timestamp, String nonce, String signature) { + if (!StringUtils.hasText(token) || !StringUtils.hasText(timestamp) + || !StringUtils.hasText(nonce) || !StringUtils.hasText(signature)) return false; + return sha1Equals(Arrays.asList(token, timestamp, nonce), signature); + } + + public boolean verify(String token, String timestamp, String nonce, String encrypted, String signature) { + if (!StringUtils.hasText(token) || !StringUtils.hasText(timestamp) || !StringUtils.hasText(nonce) + || !StringUtils.hasText(encrypted) || !StringUtils.hasText(signature)) return false; + return sha1Equals(Arrays.asList(token, timestamp, nonce, encrypted), signature); + } + + private boolean sha1Equals(List values, String signature) { + try { + String source = values.stream().sorted().collect(Collectors.joining()); + byte[] digest = MessageDigest.getInstance("SHA-1").digest(source.getBytes(StandardCharsets.UTF_8)); + return MessageDigest.isEqual(HexFormat.of().formatHex(digest).getBytes(StandardCharsets.US_ASCII), signature.getBytes(StandardCharsets.US_ASCII)); + } catch (Exception exception) { return false; } + } + + public String encryptedValue(String xml) { + return element(xml, "Encrypt"); + } + + public String decrypt(String encrypted, String encodingAesKey, String expectedAppId) { + try { + byte[] aesKey = Base64.getDecoder().decode(encodingAesKey + "="); + byte[] cipherText = Base64.getDecoder().decode(encrypted); + Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding"); + cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(aesKey, "AES"), new IvParameterSpec(Arrays.copyOf(aesKey, 16))); + byte[] padded = cipher.doFinal(cipherText); + int messageLength = ByteBuffer.wrap(padded, 16, 4).getInt(); + if (messageLength < 0 || messageLength > padded.length - 20) throw new IllegalArgumentException("微信回调密文长度无效"); + String appId = new String(padded, 20 + messageLength, padded.length - 20 - messageLength, StandardCharsets.UTF_8).trim(); + if (!expectedAppId.equals(appId)) throw new IllegalArgumentException("微信回调 AppID 不匹配"); + return new String(padded, 20, messageLength, StandardCharsets.UTF_8); + } catch (Exception exception) { + throw new IllegalArgumentException("微信审核回调解密失败", exception); + } + } + + public String value(String xml, String key) { + return element(xml, key); + } + + public String element(String xml, String key) { + try { + DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); + factory.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true); + factory.setFeature("http://xml.org/sax/features/external-general-entities", false); + factory.setFeature("http://xml.org/sax/features/external-parameter-entities", false); + factory.setXIncludeAware(false); + factory.setExpandEntityReferences(false); + Document document = factory.newDocumentBuilder().parse(new InputSource(new StringReader(xml))); + return document.getElementsByTagName(key).item(0) == null ? null : document.getElementsByTagName(key).item(0).getTextContent(); + } catch (Exception exception) { throw new IllegalArgumentException("微信审核回调 XML 无效", exception); } + } +} diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/privacy/vo/ContentModerationRecordVO.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/privacy/vo/ContentModerationRecordVO.java new file mode 100644 index 00000000..edea2ff7 --- /dev/null +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/privacy/vo/ContentModerationRecordVO.java @@ -0,0 +1,28 @@ +package com.xiaowang.jayucloud.salon.core.modules.privacy.vo; + +import lombok.Data; + +import java.time.LocalDateTime; +import java.util.List; + +@Data +public class ContentModerationRecordVO { + private Long id; + private String contentType; + private Long businessId; + private String authorName; + private String status; + private String resultCode; + private String reason; + private String textPreview; + private List images; + private Integer attemptCount; + private LocalDateTime createTime; + + @Data + public static class ImagePreview { + private Long fileId; + private String url; + private String status; + } +} diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/product/controller/admin/AdminProductController.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/product/controller/admin/AdminProductController.java index cf634963..3e764305 100644 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/product/controller/admin/AdminProductController.java +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/product/controller/admin/AdminProductController.java @@ -64,6 +64,7 @@ public class AdminProductController { */ public Result createProduct(HttpServletRequest request, @RequestBody ProductDTO productDTO) { UserDO currentUser = adminScopeHelper.getCurrentUser(request); + productDTO.setPublisherUserId(currentUser.getId()); productDTO.setShopId(adminScopeHelper.resolveShopScope(currentUser, productDTO.getShopId())); Long id = productService.createProduct(productDTO); return Result.success(id); @@ -82,6 +83,7 @@ public class AdminProductController { */ public Result updateProduct(HttpServletRequest request, @PathVariable Long id, @RequestBody ProductDTO productDTO) { UserDO currentUser = adminScopeHelper.getCurrentUser(request); + productDTO.setPublisherUserId(currentUser.getId()); ProductVO productVO = productService.getProductById(id); if (productVO == null) { return Result.success(false); diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/product/controller/front/ProductController.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/product/controller/front/ProductController.java index cc04a7f4..3bdea3e0 100644 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/product/controller/front/ProductController.java +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/product/controller/front/ProductController.java @@ -72,6 +72,7 @@ public class ProductController { */ public Result createProduct(HttpServletRequest request, @RequestBody ProductDTO productDTO) { UserDO currentUser = adminScopeHelper.getCurrentUser(request); + productDTO.setPublisherUserId(currentUser.getId()); productDTO.setShopId(adminScopeHelper.resolveShopScope(currentUser, productDTO.getShopId())); Long id = productService.createProduct(productDTO); return Result.success(id); @@ -89,6 +90,7 @@ public class ProductController { */ public Result updateProduct(HttpServletRequest request, @PathVariable Long id, @RequestBody ProductDTO productDTO) { UserDO currentUser = adminScopeHelper.getCurrentUser(request); + productDTO.setPublisherUserId(currentUser.getId()); ProductVO productVO = productService.getProductById(id); if (productVO == null) { return Result.success(false); diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/product/dto/ProductDTO.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/product/dto/ProductDTO.java index bbd80343..38e66360 100644 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/product/dto/ProductDTO.java +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/product/dto/ProductDTO.java @@ -88,4 +88,7 @@ public class ProductDTO { * 来源类型 */ private String sourceType; + + /** Server-populated author id; never trust a client-supplied value. */ + private Long publisherUserId; } diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/product/entity/EffectDiagramDO.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/product/entity/EffectDiagramDO.java index ccb2a9b1..7cb2b926 100644 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/product/entity/EffectDiagramDO.java +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/product/entity/EffectDiagramDO.java @@ -62,6 +62,9 @@ public class EffectDiagramDO extends BaseEntity { @TableField("tag") private String tag; + @TableField("moderation_status") + private String moderationStatus; + /** * 效果图点赞数 */ diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/product/entity/ProductDO.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/product/entity/ProductDO.java index 738d62dd..5739e23b 100644 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/product/entity/ProductDO.java +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/product/entity/ProductDO.java @@ -105,6 +105,9 @@ public class ProductDO extends BaseEntity { @TableField("front_visible") private Integer frontVisible; + @TableField("moderation_status") + private String moderationStatus; + /** * 来源类型:BACKEND-后台维护,MANAGER_APPOINTMENT-管理师端手动预约 */ diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/product/mapper/EffectDiagramMapper.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/product/mapper/EffectDiagramMapper.java index 4a238076..bfe5f63a 100644 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/product/mapper/EffectDiagramMapper.java +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/product/mapper/EffectDiagramMapper.java @@ -14,6 +14,6 @@ import org.apache.ibatis.annotations.Select; */ public interface EffectDiagramMapper extends BaseMapper { - @Select("SELECT COUNT(1) FROM t_effect_diagram e INNER JOIN t_product p ON p.id = e.product_id AND p.is_delete = 0 INNER JOIN t_shop s ON s.id = p.shop_id AND s.is_delete = 0 AND s.status = 1 WHERE e.is_delete = 0 AND FIND_IN_SET(#{fileId}, REPLACE(e.image_file_ids, ' ', '')) > 0") + @Select("SELECT COUNT(1) FROM t_effect_diagram e INNER JOIN t_product p ON p.id = e.product_id AND p.is_delete = 0 AND p.front_visible = 1 AND p.moderation_status = 'APPROVED' INNER JOIN t_shop s ON s.id = p.shop_id AND s.is_delete = 0 AND s.status = 1 AND s.moderation_status = 'APPROVED' WHERE e.is_delete = 0 AND e.moderation_status = 'APPROVED' AND FIND_IN_SET(#{fileId}, REPLACE(e.image_file_ids, ' ', '')) > 0") Long countPublicImageReference(@Param("fileId") Long fileId); } diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/product/mapper/ProductMapper.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/product/mapper/ProductMapper.java index 40115dab..bfe1e148 100644 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/product/mapper/ProductMapper.java +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/product/mapper/ProductMapper.java @@ -51,6 +51,6 @@ public interface ProductMapper extends BaseMapper { @Update("UPDATE t_product SET like_count = CASE WHEN like_count > 0 THEN like_count - 1 ELSE 0 END WHERE id = #{productId}") int decrementLikeCount(@Param("productId") Long productId); - @Select("SELECT COUNT(1) FROM t_product p INNER JOIN t_shop s ON s.id = p.shop_id AND s.is_delete = 0 AND s.status = 1 WHERE p.is_delete = 0 AND FIND_IN_SET(#{fileId}, REPLACE(p.image_file_ids, ' ', '')) > 0") + @Select("SELECT COUNT(1) FROM t_product p INNER JOIN t_shop s ON s.id = p.shop_id AND s.is_delete = 0 AND s.status = 1 AND s.moderation_status = 'APPROVED' WHERE p.is_delete = 0 AND p.front_visible = 1 AND p.moderation_status = 'APPROVED' AND FIND_IN_SET(#{fileId}, REPLACE(p.image_file_ids, ' ', '')) > 0") Long countPublicImageReference(@Param("fileId") Long fileId); } diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/product/service/impl/EffectDiagramServiceImpl.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/product/service/impl/EffectDiagramServiceImpl.java index 46ab151c..cd7dcbee 100644 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/product/service/impl/EffectDiagramServiceImpl.java +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/product/service/impl/EffectDiagramServiceImpl.java @@ -7,10 +7,26 @@ import com.xiaowang.jayucloud.salon.core.modules.product.entity.EffectDiagramDO; import com.xiaowang.jayucloud.salon.core.modules.product.mapper.EffectDiagramMapper; import com.xiaowang.jayucloud.salon.core.modules.product.service.EffectDiagramService; import com.xiaowang.jayucloud.salon.core.modules.product.vo.EffectDiagramVO; +import com.xiaowang.jayucloud.salon.core.modules.product.mapper.ProductMapper; +import com.xiaowang.jayucloud.salon.core.modules.product.entity.ProductDO; +import com.xiaowang.jayucloud.salon.core.modules.shop.entity.ShopDO; +import com.xiaowang.jayucloud.salon.core.modules.shop.mapper.ShopMapper; +import com.xiaowang.jayucloud.salon.core.modules.privacy.service.ContentModerationService; +import com.xiaowang.jayucloud.salon.core.modules.privacy.vo.ContentModerationResultVO; +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.ObjectMapper; +import org.springframework.util.StringUtils; import lombok.RequiredArgsConstructor; import org.springframework.stereotype.Service; import java.util.List; +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.Collections; +import java.util.Arrays; +import org.springframework.web.context.request.RequestContextHolder; +import org.springframework.web.context.request.ServletRequestAttributes; import java.util.stream.Collectors; /** @@ -27,6 +43,10 @@ public class EffectDiagramServiceImpl extends ServiceImpl 0; + EffectDiagramDO candidate = copy(source); + candidate.setProductId(effectDiagramDTO.getProductId()); + candidate.setCategory(effectDiagramDTO.getCategory()); + candidate.setImageFileIds(effectDiagramDTO.getImageFileIds()); + candidate.setDescription(effectDiagramDTO.getDescription()); + candidate.setPrice(effectDiagramDTO.getPrice()); + candidate.setDuration(effectDiagramDTO.getDuration()); + candidate.setTag(effectDiagramDTO.getTag()); + candidate.setModerationStatus("PENDING"); + ContentModerationResultVO moderation = assess(candidate); + return "APPROVED".equals(moderation.getStatus()) && effectDiagramMapper.updateById(candidate) > 0; } @Override @@ -81,7 +110,7 @@ public class EffectDiagramServiceImpl extends ServiceImpl result consumed by the caller or returned to the frontend */ public List listAllEffectDiagrams() { - List effectDiagramDOs = effectDiagramMapper.selectList(null); + List effectDiagramDOs = effectDiagramMapper.selectList( + Wrappers.lambdaQuery(EffectDiagramDO.class).eq(EffectDiagramDO::getIsDelete, 0) + .eq(EffectDiagramDO::getModerationStatus, "APPROVED")); return effectDiagramDOs.stream() + .filter(this::isPublic) .map(this::convertToVO) .collect(Collectors.toList()); } @@ -133,8 +166,10 @@ public class EffectDiagramServiceImpl extends ServiceImpl effectDiagramDOs = effectDiagramMapper.selectList( Wrappers.lambdaQuery(EffectDiagramDO.class) .eq(EffectDiagramDO::getProductId, productId) + .eq(EffectDiagramDO::getIsDelete, 0) + .eq(EffectDiagramDO::getModerationStatus, "APPROVED") ); - return effectDiagramDOs.stream() + return effectDiagramDOs.stream().filter(this::isPublic) .map(this::convertToVO) .collect(Collectors.toList()); } @@ -150,8 +185,10 @@ public class EffectDiagramServiceImpl extends ServiceImpl effectDiagramDOs = effectDiagramMapper.selectList( Wrappers.lambdaQuery(EffectDiagramDO.class) .eq(EffectDiagramDO::getCategory, category) + .eq(EffectDiagramDO::getIsDelete, 0) + .eq(EffectDiagramDO::getModerationStatus, "APPROVED") ); - return effectDiagramDOs.stream() + return effectDiagramDOs.stream().filter(this::isPublic) .map(this::convertToVO) .collect(Collectors.toList()); } @@ -177,4 +214,66 @@ public class EffectDiagramServiceImpl extends ServiceImpl payload = new LinkedHashMap<>(); + payload.put("productId", effect.getProductId()); payload.put("category", effect.getCategory()); + payload.put("imageFileIds", effect.getImageFileIds()); payload.put("description", effect.getDescription()); + payload.put("price", effect.getPrice()); payload.put("duration", effect.getDuration()); payload.put("tag", effect.getTag()); + String text = String.join("\n", safe(effect.getCategory()), safe(effect.getDescription()), safe(effect.getTag())); + return contentModerationService.assessVersion("EFFECT_DIAGRAM", effect.getId(), currentUserId(), text, + objectMapper.writeValueAsString(payload), parseImageFileIds(effect.getImageFileIds())); + } catch (JsonProcessingException exception) { + throw new IllegalStateException("效果图审核内容序列化失败", exception); + } + } + + private EffectDiagramDO copy(EffectDiagramDO source) { + EffectDiagramDO target = new EffectDiagramDO(); + target.setId(source.getId()); target.setProductId(source.getProductId()); target.setCategory(source.getCategory()); + target.setImageFileIds(source.getImageFileIds()); target.setDescription(source.getDescription()); target.setPrice(source.getPrice()); + target.setDuration(source.getDuration()); target.setTag(source.getTag()); target.setLikeCount(source.getLikeCount()); + target.setModerationStatus(source.getModerationStatus()); target.setIsDelete(source.getIsDelete()); + target.setCreateTime(source.getCreateTime()); target.setUpdateTime(source.getUpdateTime()); + return target; + } + + private boolean isPublic(EffectDiagramDO effect) { + ProductDO product = effect.getProductId() == null ? null : productMapper.selectById(effect.getProductId()); + ShopDO shop = product == null || product.getShopId() == null ? null : shopMapper.selectById(product.getShopId()); + return product != null && shop != null + && Integer.valueOf(0).equals(product.getIsDelete()) + && Integer.valueOf(1).equals(product.getFrontVisible()) + && "APPROVED".equals(product.getModerationStatus()) + && Integer.valueOf(0).equals(shop.getIsDelete()) + && Integer.valueOf(1).equals(shop.getStatus()) + && "APPROVED".equals(shop.getModerationStatus()); + } + + private List parseImageFileIds(String value) { + if (!StringUtils.hasText(value)) return Collections.emptyList(); + List imageIds = new ArrayList<>(); + for (String valuePart : value.split(",")) { + String token = valuePart.trim(); + if (!StringUtils.hasText(token)) continue; + try { + long fileId = Long.parseLong(token); + if (fileId <= 0) throw new NumberFormatException("file id must be positive"); + imageIds.add(fileId); + } catch (NumberFormatException exception) { + throw new IllegalArgumentException("效果图必须引用已上传文件", exception); + } + } + return imageIds.stream().distinct().collect(java.util.stream.Collectors.toList()); + } + + private String safe(String value) { return value == null ? "" : value; } + + private Long currentUserId() { + ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes(); + if (attributes == null) return null; + Object value = attributes.getRequest().getAttribute("userId"); + return value instanceof Long ? (Long) value : null; + } } diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/product/service/impl/ProductServiceImpl.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/product/service/impl/ProductServiceImpl.java index ac2a9078..6f990bc3 100644 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/product/service/impl/ProductServiceImpl.java +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/product/service/impl/ProductServiceImpl.java @@ -150,10 +150,14 @@ public class ProductServiceImpl extends ServiceImpl im productDO.setFrontVisible(0); productDO.setSourceType(resolveSourceType(productDTO.getSourceType())); productDO.setIsDelete(0); + productDO.setModerationStatus("PENDING"); productMapper.insert(productDO); - ContentModerationResultVO moderation = assessProduct(productDO, requestedFrontVisible); - productDO.setFrontVisible("APPROVED".equals(moderation.getStatus()) ? requestedFrontVisible : 0); - productMapper.updateById(productDO); + ContentModerationResultVO moderation = assessProduct(productDO, requestedFrontVisible, productDTO.getPublisherUserId()); + if ("APPROVED".equals(moderation.getStatus())) { + productDO.setFrontVisible(requestedFrontVisible); + productDO.setModerationStatus("APPROVED"); + productMapper.updateById(productDO); + } evictPublicProductCaches(productDO.getId()); return productDO.getId(); } @@ -174,31 +178,36 @@ public class ProductServiceImpl extends ServiceImpl im } validateBookableArtists(productDTO.getShopId(), productDTO.getBookableArtists()); validateAvailableCoupons(productDTO.getShopId(), productDTO.getAvailableCoupons()); - productDO.setShopId(productDTO.getShopId()); - productDO.setTitle(productDTO.getTitle()); - productDO.setDescription(productDTO.getDescription()); - productDO.setTargetAudience(productDTO.getTargetAudience()); - productDO.setPrecautions(productDTO.getPrecautions()); - productDO.setImageFileIds(productDTO.getImageFileIds()); - productDO.setPrice(productDTO.getPrice()); - productDO.setTags(productDTO.getTags()); + ProductDO candidate = copyProduct(productDO); + candidate.setShopId(productDTO.getShopId()); + candidate.setTitle(productDTO.getTitle()); + candidate.setDescription(productDTO.getDescription()); + candidate.setTargetAudience(productDTO.getTargetAudience()); + candidate.setPrecautions(productDTO.getPrecautions()); + candidate.setImageFileIds(productDTO.getImageFileIds()); + candidate.setPrice(productDTO.getPrice()); + candidate.setTags(productDTO.getTags()); if (productDTO.getLikeCount() != null) { - productDO.setLikeCount(normalizeInteractionCount(productDTO.getLikeCount())); + candidate.setLikeCount(normalizeInteractionCount(productDTO.getLikeCount())); } if (productDTO.getCollectCount() != null) { - productDO.setCollectCount(normalizeInteractionCount(productDTO.getCollectCount())); + candidate.setCollectCount(normalizeInteractionCount(productDTO.getCollectCount())); } - productDO.setApproximateDuration(productDTO.getApproximateDuration()); - productDO.setBookableArtists(bookableArtistSupport.filterValidBookableArtists(productDTO.getShopId(), productDTO.getBookableArtists())); - productDO.setAvailableCoupons(productDTO.getAvailableCoupons()); + candidate.setApproximateDuration(productDTO.getApproximateDuration()); + candidate.setBookableArtists(bookableArtistSupport.filterValidBookableArtists(productDTO.getShopId(), productDTO.getBookableArtists())); + candidate.setAvailableCoupons(productDTO.getAvailableCoupons()); Integer requestedFrontVisible = resolveUpdateFrontVisible(productDO.getFrontVisible(), productDTO.getFrontVisible()); - productDO.setFrontVisible(0); - productDO.setSourceType(resolveUpdateSourceType(productDO.getSourceType(), productDTO.getSourceType())); - boolean updated = productMapper.updateById(productDO) > 0; + candidate.setFrontVisible(productDO.getFrontVisible()); + candidate.setModerationStatus("PENDING"); + candidate.setSourceType(resolveUpdateSourceType(productDO.getSourceType(), productDTO.getSourceType())); + ContentModerationResultVO moderation = assessProduct(candidate, requestedFrontVisible, productDTO.getPublisherUserId()); + boolean updated = true; + if ("APPROVED".equals(moderation.getStatus())) { + candidate.setFrontVisible(requestedFrontVisible); + candidate.setModerationStatus("APPROVED"); + updated = productMapper.updateById(candidate) > 0; + } if (updated) { - ContentModerationResultVO moderation = assessProduct(productDO, requestedFrontVisible); - productDO.setFrontVisible("APPROVED".equals(moderation.getStatus()) ? requestedFrontVisible : 0); - productMapper.updateById(productDO); /** * Run business method `evictPublicProductCaches`. * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. @@ -210,18 +219,55 @@ public class ProductServiceImpl extends ServiceImpl im return updated; } - private ContentModerationResultVO assessProduct(ProductDO product, Integer requestedFrontVisible) { - String content = String.join("\n", List.of( - safe(product.getTitle()), safe(product.getDescription()), safe(product.getTargetAudience()), - safe(product.getPrecautions()), safe(product.getTags()), safe(product.getImageFileIds()))); + private ContentModerationResultVO assessProduct(ProductDO product, Integer requestedFrontVisible, Long publisherUserId) { try { - String payload = objectMapper.writeValueAsString(java.util.Map.of("frontVisible", requestedFrontVisible == null ? 1 : requestedFrontVisible)); - return contentModerationService.assess("PRODUCT", product.getId(), null, content, payload); + Map snapshot = new LinkedHashMap<>(); + snapshot.put("shopId", product.getShopId()); snapshot.put("title", product.getTitle()); + snapshot.put("description", product.getDescription()); snapshot.put("targetAudience", product.getTargetAudience()); + snapshot.put("precautions", product.getPrecautions()); snapshot.put("imageFileIds", product.getImageFileIds()); + snapshot.put("price", product.getPrice()); snapshot.put("tags", product.getTags()); + snapshot.put("approximateDuration", product.getApproximateDuration()); snapshot.put("bookableArtists", product.getBookableArtists()); + snapshot.put("availableCoupons", product.getAvailableCoupons()); snapshot.put("frontVisible", requestedFrontVisible == null ? 1 : requestedFrontVisible); + String content = String.join("\n", List.of(safe(product.getTitle()), safe(product.getDescription()), + safe(product.getTargetAudience()), safe(product.getPrecautions()), safe(product.getTags()))); + return contentModerationService.assessVersion("PRODUCT", product.getId(), publisherUserId, + content, objectMapper.writeValueAsString(snapshot), parseImageFileIds(product.getImageFileIds())); } catch (JsonProcessingException exception) { throw new IllegalStateException("作品审核内容序列化失败", exception); } } + private ProductDO copyProduct(ProductDO source) { + ProductDO target = new ProductDO(); + target.setId(source.getId()); target.setShopId(source.getShopId()); target.setTitle(source.getTitle()); + target.setDescription(source.getDescription()); target.setTargetAudience(source.getTargetAudience()); + target.setPrecautions(source.getPrecautions()); target.setImageFileIds(source.getImageFileIds()); + target.setPrice(source.getPrice()); target.setTags(source.getTags()); target.setLikeCount(source.getLikeCount()); + target.setCollectCount(source.getCollectCount()); target.setApproximateDuration(source.getApproximateDuration()); + target.setBookableArtists(source.getBookableArtists()); target.setAvailableCoupons(source.getAvailableCoupons()); + target.setFrontVisible(source.getFrontVisible()); target.setSourceType(source.getSourceType()); + target.setModerationStatus(source.getModerationStatus()); target.setIsDelete(source.getIsDelete()); + target.setCreateTime(source.getCreateTime()); target.setUpdateTime(source.getUpdateTime()); + return target; + } + + private List parseImageFileIds(String value) { + if (!StringUtils.hasText(value)) return Collections.emptyList(); + List imageIds = new ArrayList<>(); + for (String valuePart : value.split(",")) { + String token = valuePart.trim(); + if (!StringUtils.hasText(token)) continue; + try { + long fileId = Long.parseLong(token); + if (fileId <= 0) throw new NumberFormatException("file id must be positive"); + imageIds.add(fileId); + } catch (NumberFormatException exception) { + throw new IllegalArgumentException("作品图片必须引用已上传文件", exception); + } + } + return imageIds.stream().distinct().collect(Collectors.toList()); + } + private String safe(String value) { return value == null ? "" : value; } @@ -338,7 +384,9 @@ public class ProductServiceImpl extends ServiceImpl im ProductDO productDO = productMapper.selectById(id); if (productDO == null || Integer.valueOf(1).equals(productDO.getIsDelete()) - || !Integer.valueOf(FRONT_VISIBLE).equals(productDO.getFrontVisible())) { + || !Integer.valueOf(FRONT_VISIBLE).equals(productDO.getFrontVisible()) + || !"APPROVED".equals(productDO.getModerationStatus()) + || !isPublicShop(productDO.getShopId())) { return null; } return convertToVO(productDO); @@ -920,6 +968,7 @@ public class ProductServiceImpl extends ServiceImpl im LambdaQueryWrapper wrapper = Wrappers.lambdaQuery(ProductDO.class) .eq(ProductDO::getIsDelete, 0) .eq(ProductDO::getFrontVisible, FRONT_VISIBLE) + .eq(ProductDO::getModerationStatus, "APPROVED") .orderByDesc(ProductDO::getCreateTime); if (shopId != null) { wrapper.eq(ProductDO::getShopId, shopId); @@ -1017,7 +1066,11 @@ public class ProductServiceImpl extends ServiceImpl im private LambdaQueryWrapper buildFrontQuery(String keyword, String tag, Set exactTagIds, Set selectedTagIds, Long shopId) { LambdaQueryWrapper wrapper = Wrappers.lambdaQuery(ProductDO.class) .eq(ProductDO::getIsDelete, 0) - .eq(ProductDO::getFrontVisible, FRONT_VISIBLE); + .eq(ProductDO::getFrontVisible, FRONT_VISIBLE) + .eq(ProductDO::getModerationStatus, "APPROVED"); + wrapper.apply("EXISTS (SELECT 1 FROM t_shop public_product_shop WHERE public_product_shop.id = t_product.shop_id " + + "AND public_product_shop.is_delete = 0 AND public_product_shop.status = 1 " + + "AND public_product_shop.moderation_status = 'APPROVED')"); if (shopId != null) { wrapper.eq(ProductDO::getShopId, shopId); } @@ -1039,12 +1092,22 @@ public class ProductServiceImpl extends ServiceImpl im return wrapper; } + private boolean isPublicShop(Long shopId) { + if (shopId == null || shopId <= 0) return false; + ShopDO shop = shopMapper.selectById(shopId); + return shop != null && !Integer.valueOf(1).equals(shop.getIsDelete()) + && Integer.valueOf(1).equals(shop.getStatus()) + && "APPROVED".equals(shop.getModerationStatus()); + } + private Integer resolveFrontVisible(Integer frontVisible) { return Integer.valueOf(0).equals(frontVisible) ? 0 : FRONT_VISIBLE; } private String resolveSourceType(String sourceType) { - return StringUtils.hasText(sourceType) ? sourceType.trim() : SOURCE_TYPE_BACKEND; + // MANAGER_APPOINTMENT products are created only by the planning domain. A public + // product endpoint must never trust a client-provided source to bypass moderation. + return SOURCE_TYPE_BACKEND; } private Integer resolveUpdateFrontVisible(Integer currentFrontVisible, Integer nextFrontVisible) { @@ -1055,10 +1118,8 @@ public class ProductServiceImpl extends ServiceImpl im } private String resolveUpdateSourceType(String currentSourceType, String nextSourceType) { - if (StringUtils.hasText(nextSourceType)) { - return resolveSourceType(nextSourceType); - } - return StringUtils.hasText(currentSourceType) ? currentSourceType : SOURCE_TYPE_BACKEND; + return "MANAGER_APPOINTMENT".equals(currentSourceType) + ? currentSourceType : SOURCE_TYPE_BACKEND; } /** diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/shop/controller/front/ShopController.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/shop/controller/front/ShopController.java index 5753348e..ab8cd7fe 100644 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/shop/controller/front/ShopController.java +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/shop/controller/front/ShopController.java @@ -115,7 +115,7 @@ public class ShopController { * @return Result result consumed by the caller or returned to the frontend */ public Result getShopById(@PathVariable Long id) { - ShopVO shopVO = shopService.getShopById(id); + ShopVO shopVO = shopService.getPublicShopById(id); return Result.success(shopVO); } diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/shop/entity/ShopDO.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/shop/entity/ShopDO.java index 67535d1e..3ef2779c 100644 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/shop/entity/ShopDO.java +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/shop/entity/ShopDO.java @@ -136,6 +136,9 @@ public class ShopDO extends BaseEntity { @TableField("status") private Integer status; + @TableField("moderation_status") + private String moderationStatus; + @TableField("authorization_start_date") /** * Purpose: authorizationStartDate supports ShopDO.java by holding or executing the authorization start date business role. diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/shop/mapper/ShopMapper.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/shop/mapper/ShopMapper.java index 1b5792dc..5cec65eb 100644 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/shop/mapper/ShopMapper.java +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/shop/mapper/ShopMapper.java @@ -14,6 +14,6 @@ import org.apache.ibatis.annotations.Select; */ public interface ShopMapper extends BaseMapper { - @Select("SELECT COUNT(1) FROM t_shop WHERE is_delete = 0 AND status = 1 AND (FIND_IN_SET(#{fileId}, REPLACE(COALESCE(cover_image_file_id, ''), ' ', '')) > 0 OR FIND_IN_SET(#{fileId}, REPLACE(COALESCE(image_file_ids, ''), ' ', '')) > 0 OR FIND_IN_SET(#{fileId}, REPLACE(COALESCE(theme_background_image_file_id, ''), ' ', '')) > 0)") + @Select("SELECT COUNT(1) FROM t_shop WHERE is_delete = 0 AND status = 1 AND moderation_status = 'APPROVED' AND (FIND_IN_SET(#{fileId}, REPLACE(COALESCE(cover_image_file_id, ''), ' ', '')) > 0 OR FIND_IN_SET(#{fileId}, REPLACE(COALESCE(image_file_ids, ''), ' ', '')) > 0 OR FIND_IN_SET(#{fileId}, REPLACE(COALESCE(theme_background_image_file_id, ''), ' ', '')) > 0)") Long countPublicImageReference(@Param("fileId") Long fileId); } diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/shop/service/ShopService.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/shop/service/ShopService.java index 1006a133..75ee4706 100644 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/shop/service/ShopService.java +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/shop/service/ShopService.java @@ -51,6 +51,9 @@ public interface ShopService extends IService { */ ShopVO getShopById(Long id); + /** Public shop detail with the approved-content visibility gate applied. */ + ShopVO getPublicShopById(Long id); + /** * Purpose: getShopTrustProfile aggregates public shop confidence signals. * Usage: call it from the public shop detail endpoint; phone data stays behind explicit contact APIs. 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 2778fc8f..307dc8fa 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,8 @@ import com.xiaowang.jayucloud.salon.core.modules.shop.service.ShopService; 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; +import com.xiaowang.jayucloud.salon.core.modules.privacy.service.ContentModerationService; +import com.fasterxml.jackson.databind.ObjectMapper; import com.xiaowang.jayucloud.salon.core.support.cache.MultiLevelCacheService; import com.xiaowang.jayucloud.salon.core.modules.file.vo.ObjectStorageFileVO; import com.xiaowang.jayucloud.salon.core.common.vo.PageResultVO; @@ -139,6 +141,8 @@ public class ShopServiceImpl extends ServiceImpl implements * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. */ private final MapService mapService; + private final ContentModerationService contentModerationService; + private final ObjectMapper objectMapper; @Override @Transactional(rollbackFor = Exception.class) @@ -150,20 +154,22 @@ public class ShopServiceImpl extends ServiceImpl implements */ public Long createShop(ShopDTO shopDTO) { ShopDO shopDO = new ShopDO(); - shopDO.setShopName(shopDTO.getShopName()); - shopDO.setDescription(shopDTO.getDescription()); - shopDO.setAddress(shopDTO.getAddress()); + shopDO.setShopName(""); + shopDO.setDescription(null); + shopDO.setAddress(""); shopDO.setMapProvider(mapService.normalizeProvider(shopDTO.getMapProvider())); shopDO.setLongitude(shopDTO.getLongitude()); shopDO.setLatitude(shopDTO.getLatitude()); - shopDO.setBusinessHours(shopDTO.getBusinessHours()); - shopDO.setCoverImageFileId(shopDTO.getCoverImageFileId()); - shopDO.setImageFileIds(shopDTO.getImageFileIds()); + shopDO.setBusinessHours(null); + shopDO.setCoverImageFileId(null); + shopDO.setImageFileIds(null); + shopDO.setModerationStatus("PENDING"); applyTheme(shopDO, shopDTO); applyAuthorization(shopDO, shopDTO); shopDO.setStatus(normalizeStatus(shopDTO.getStatus())); shopDO.setIsDelete(0); shopMapper.insert(shopDO); + submitShopSnapshot(shopDO, shopDTO); couponService.initializeDefaultVipAutoCoupons(shopDO.getId()); evictShopCaches(shopDO.getId()); return shopDO.getId(); @@ -185,21 +191,8 @@ public class ShopServiceImpl extends ServiceImpl implements if (Integer.valueOf(0).equals(normalizeStatus(shopDO.getStatus()))) { throw new RuntimeException(DISABLED_SHOP_ARCHIVED_MESSAGE); } - shopDO.setShopName(shopDTO.getShopName()); - shopDO.setDescription(shopDTO.getDescription()); - shopDO.setAddress(shopDTO.getAddress()); - shopDO.setMapProvider(mapService.normalizeProvider(shopDTO.getMapProvider())); - shopDO.setLongitude(shopDTO.getLongitude()); - shopDO.setLatitude(shopDTO.getLatitude()); - shopDO.setBusinessHours(shopDTO.getBusinessHours()); - shopDO.setCoverImageFileId(shopDTO.getCoverImageFileId()); - shopDO.setImageFileIds(shopDTO.getImageFileIds()); - applyTheme(shopDO, shopDTO); - applyAuthorization(shopDO, shopDTO); - if (shopDTO.getStatus() != null) { - shopDO.setStatus(normalizeStatus(shopDTO.getStatus())); - } - boolean updated = shopMapper.updateById(shopDO) > 0; + boolean updated = updateShopOperationalFields(shopDO, shopDTO); + submitShopSnapshot(shopDO, shopDTO); if (updated) { /** * Run business method `evictShopCaches`. @@ -212,6 +205,75 @@ public class ShopServiceImpl extends ServiceImpl implements return updated; } + private boolean updateShopOperationalFields(ShopDO current, ShopDTO dto) { + boolean changed = false; + if (dto.getStatus() != null) { + current.setStatus(normalizeStatus(dto.getStatus())); + changed = true; + } + if (dto.getAuthorizationStartDate() != null || dto.getAuthorizationDays() != null || dto.getAuthorizationExpireTime() != null) { + applyAuthorization(current, dto); + changed = true; + } + return !changed || shopMapper.updateById(current) > 0; + } + + private ShopDO copyShop(ShopDO source) { + ShopDO target = new ShopDO(); + target.setId(source.getId()); target.setShopName(source.getShopName()); target.setDescription(source.getDescription()); + target.setAddress(source.getAddress()); target.setMapProvider(source.getMapProvider()); target.setLongitude(source.getLongitude()); + target.setLatitude(source.getLatitude()); target.setBusinessHours(source.getBusinessHours()); target.setCoverImageFileId(source.getCoverImageFileId()); + target.setImageFileIds(source.getImageFileIds()); target.setThemePrimaryColor(source.getThemePrimaryColor()); + target.setThemeSecondaryColor(source.getThemeSecondaryColor()); target.setThemeAccentColor(source.getThemeAccentColor()); + target.setThemePageBgColor(source.getThemePageBgColor()); target.setThemeCardBgColor(source.getThemeCardBgColor()); + target.setThemeBackgroundImageFileId(source.getThemeBackgroundImageFileId()); target.setStatus(source.getStatus()); + target.setAuthorizationStartDate(source.getAuthorizationStartDate()); target.setAuthorizationDays(source.getAuthorizationDays()); + target.setAuthorizationExpireTime(source.getAuthorizationExpireTime()); target.setIsDelete(source.getIsDelete()); + target.setModerationStatus(source.getModerationStatus()); target.setCreateTime(source.getCreateTime()); target.setUpdateTime(source.getUpdateTime()); + return target; + } + + private void submitShopSnapshot(ShopDO current, ShopDTO dto) { + try { + ShopDO candidate = copyShop(current); + candidate.setShopName(dto.getShopName()); candidate.setDescription(dto.getDescription()); candidate.setAddress(dto.getAddress()); + candidate.setMapProvider(mapService.normalizeProvider(dto.getMapProvider())); + candidate.setLongitude(dto.getLongitude()); candidate.setLatitude(dto.getLatitude()); + candidate.setBusinessHours(dto.getBusinessHours()); candidate.setCoverImageFileId(dto.getCoverImageFileId()); + candidate.setImageFileIds(dto.getImageFileIds()); applyTheme(candidate, dto); + java.util.Map payload = new java.util.LinkedHashMap<>(); + payload.put("shopName", candidate.getShopName()); payload.put("description", candidate.getDescription()); + payload.put("address", candidate.getAddress()); payload.put("businessHours", candidate.getBusinessHours()); + payload.put("mapProvider", candidate.getMapProvider()); payload.put("longitude", candidate.getLongitude()); + payload.put("latitude", candidate.getLatitude()); + payload.put("coverImageFileId", candidate.getCoverImageFileId()); payload.put("imageFileIds", candidate.getImageFileIds()); + payload.put("themePrimaryColor", candidate.getThemePrimaryColor()); + payload.put("themeSecondaryColor", candidate.getThemeSecondaryColor()); + payload.put("themeAccentColor", candidate.getThemeAccentColor()); + payload.put("themePageBgColor", candidate.getThemePageBgColor()); + payload.put("themeCardBgColor", candidate.getThemeCardBgColor()); + payload.put("themeBackgroundImageFileId", candidate.getThemeBackgroundImageFileId()); + String text = String.join("\n", java.util.Arrays.asList(candidate.getShopName(), candidate.getDescription(), candidate.getAddress(), candidate.getBusinessHours())); + java.util.List images = new java.util.ArrayList<>(); + addImageIds(images, candidate.getCoverImageFileId()); addImageIds(images, candidate.getImageFileIds()); addImageIds(images, candidate.getThemeBackgroundImageFileId()); + contentModerationService.assessVersion("SHOP", current.getId(), null, text, objectMapper.writeValueAsString(payload), images); + } catch (Exception exception) { + throw new IllegalStateException("门店展示资料审核任务创建失败", exception); + } + } + + private void addImageIds(java.util.List ids, String value) { + if (!StringUtils.hasText(value)) return; + for (String token : value.split(",")) { + if (!StringUtils.hasText(token)) continue; + Long fileId = objectStorageFileService.findFileIdByReference(token.trim()); + if (fileId == null || fileId <= 0) { + throw new IllegalArgumentException("门店图片必须引用已上传文件"); + } + if (!ids.contains(fileId)) ids.add(fileId); + } + } + @Override @Transactional(rollbackFor = Exception.class) /** @@ -282,6 +344,18 @@ public class ShopServiceImpl extends ServiceImpl implements ); } + @Override + public ShopVO getPublicShopById(Long id) { + ShopDO shop = id == null ? null : shopMapper.selectById(id); + if (shop == null || Integer.valueOf(1).equals(shop.getIsDelete()) + || !Integer.valueOf(1).equals(normalizeStatus(shop.getStatus())) + || !"APPROVED".equals(shop.getModerationStatus()) + || !isAuthorizationValid(shop)) { + return null; + } + return convertToVO(shop); + } + @Override /** * Purpose: getShopTrustProfile aggregates public shop confidence signals for detail pages. @@ -292,7 +366,8 @@ public class ShopServiceImpl extends ServiceImpl implements return null; } ShopDO shopDO = shopMapper.selectById(id); - if (shopDO == null || Integer.valueOf(1).equals(shopDO.getIsDelete()) || !isAuthorizationValid(shopDO)) { + if (shopDO == null || Integer.valueOf(1).equals(shopDO.getIsDelete()) + || !"APPROVED".equals(shopDO.getModerationStatus()) || !isAuthorizationValid(shopDO)) { return null; } @@ -358,6 +433,7 @@ public class ShopServiceImpl extends ServiceImpl implements Wrappers.lambdaQuery(ShopDO.class) .eq(ShopDO::getIsDelete, 0) .eq(ShopDO::getStatus, 1) + .eq(ShopDO::getModerationStatus, "APPROVED") .orderByDesc(ShopDO::getCreateTime) ).stream() .filter(this::isAuthorizationValid) @@ -404,6 +480,7 @@ public class ShopServiceImpl extends ServiceImpl implements Wrappers.lambdaQuery(ShopDO.class) .eq(ShopDO::getIsDelete, 0) .eq(ShopDO::getStatus, 1) + .eq(ShopDO::getModerationStatus, "APPROVED") .like(ShopDO::getShopName, normalizedShopName) ).stream().filter(this::isAuthorizationValid).collect(Collectors.toList()); return shopDOs.stream() @@ -456,7 +533,8 @@ public class ShopServiceImpl extends ServiceImpl implements private long countActiveProducts(Long shopId) { Long count = productMapper.selectCount(Wrappers.lambdaQuery(ProductDO.class) .eq(ProductDO::getShopId, shopId) - .eq(ProductDO::getIsDelete, 0)); + .eq(ProductDO::getIsDelete, 0) + .eq(ProductDO::getModerationStatus, "APPROVED")); return count == null ? 0L : count; } @@ -476,6 +554,7 @@ public class ShopServiceImpl extends ServiceImpl implements return productMapper.selectList(Wrappers.lambdaQuery(ProductDO.class) .eq(ProductDO::getShopId, shopId) .eq(ProductDO::getIsDelete, 0) + .eq(ProductDO::getModerationStatus, "APPROVED") .and(wrapper -> applyProductTagTokenConditions(wrapper, featuredTagTokens)) .orderByDesc(ProductDO::getCollectCount) .orderByDesc(ProductDO::getLikeCount) @@ -530,14 +609,24 @@ public class ShopServiceImpl extends ServiceImpl implements * Usage: only status=1 reviews should feed public trust display. */ private List listSubmittedReviews(Long shopId, int limit) { - return orderArtistReviewMapper.selectList(Wrappers.lambdaQuery(OrderArtistReviewDO.class) + if (!isPublicShop(shopId)) { + return Collections.emptyList(); + } + List reviews = orderArtistReviewMapper.selectList(Wrappers.lambdaQuery(OrderArtistReviewDO.class) .eq(OrderArtistReviewDO::getShopId, shopId) .eq(OrderArtistReviewDO::getStatus, 1) .eq(OrderArtistReviewDO::getIsDelete, 0) + .eq(OrderArtistReviewDO::getModerationStatus, "APPROVED") .orderByDesc(OrderArtistReviewDO::getSubmittedAt) - .orderByDesc(OrderArtistReviewDO::getCreateTime) - .last("LIMIT " + Math.max(1, limit))) - .stream() + .orderByDesc(OrderArtistReviewDO::getCreateTime)); + Set productIds = reviews.stream() + .map(OrderArtistReviewDO::getProductId) + .filter(Objects::nonNull) + .collect(Collectors.toCollection(LinkedHashSet::new)); + Set approvedProductIds = listApprovedProductIds(productIds); + return reviews.stream() + .filter(review -> approvedProductIds.contains(review.getProductId())) + .limit(Math.max(1, limit)) .filter(Objects::nonNull) .collect(Collectors.toList()); } @@ -547,11 +636,20 @@ public class ShopServiceImpl extends ServiceImpl implements * Usage: render it beside average rating so customers can judge sample size. */ private long countSubmittedReviews(Long shopId) { - Long count = orderArtistReviewMapper.selectCount(Wrappers.lambdaQuery(OrderArtistReviewDO.class) + if (!isPublicShop(shopId)) { + return 0L; + } + List reviews = orderArtistReviewMapper.selectList(Wrappers.lambdaQuery(OrderArtistReviewDO.class) .eq(OrderArtistReviewDO::getShopId, shopId) .eq(OrderArtistReviewDO::getStatus, 1) - .eq(OrderArtistReviewDO::getIsDelete, 0)); - return count == null ? 0L : count; + .eq(OrderArtistReviewDO::getIsDelete, 0) + .eq(OrderArtistReviewDO::getModerationStatus, "APPROVED")); + Set productIds = reviews.stream() + .map(OrderArtistReviewDO::getProductId) + .filter(Objects::nonNull) + .collect(Collectors.toCollection(LinkedHashSet::new)); + Set approvedProductIds = listApprovedProductIds(productIds); + return reviews.stream().filter(review -> approvedProductIds.contains(review.getProductId())).count(); } /** @@ -559,11 +657,23 @@ public class ShopServiceImpl extends ServiceImpl implements * Usage: use submitted reviews only and return zero when no rating exists. */ private BigDecimal calculateAverageRating(Long shopId) { + if (!isPublicShop(shopId)) { + return BigDecimal.ZERO; + } List reviews = orderArtistReviewMapper.selectList(Wrappers.lambdaQuery(OrderArtistReviewDO.class) .eq(OrderArtistReviewDO::getShopId, shopId) .eq(OrderArtistReviewDO::getStatus, 1) .eq(OrderArtistReviewDO::getIsDelete, 0) + .eq(OrderArtistReviewDO::getModerationStatus, "APPROVED") .isNotNull(OrderArtistReviewDO::getRatingScore)); + Set productIds = reviews.stream() + .map(OrderArtistReviewDO::getProductId) + .filter(Objects::nonNull) + .collect(Collectors.toCollection(LinkedHashSet::new)); + Set approvedProductIds = listApprovedProductIds(productIds); + reviews = reviews.stream() + .filter(review -> approvedProductIds.contains(review.getProductId())) + .collect(Collectors.toList()); if (reviews == null || reviews.isEmpty()) { return BigDecimal.ZERO; } @@ -578,6 +688,32 @@ public class ShopServiceImpl extends ServiceImpl implements return total.divide(BigDecimal.valueOf(count), 1, RoundingMode.HALF_UP); } + private boolean isPublicShop(Long shopId) { + if (shopId == null) { + return false; + } + ShopDO shop = shopMapper.selectById(shopId); + return shop != null + && !Integer.valueOf(1).equals(shop.getIsDelete()) + && Integer.valueOf(1).equals(normalizeStatus(shop.getStatus())) + && "APPROVED".equals(shop.getModerationStatus()) + && isAuthorizationValid(shop); + } + + private Set listApprovedProductIds(Set productIds) { + if (productIds == null || productIds.isEmpty()) { + return Collections.emptySet(); + } + return productMapper.selectBatchIds(productIds).stream() + .filter(Objects::nonNull) + .filter(product -> !Integer.valueOf(1).equals(product.getIsDelete())) + .filter(product -> Integer.valueOf(1).equals(product.getFrontVisible())) + .filter(product -> "APPROVED".equals(product.getModerationStatus())) + .map(ProductDO::getId) + .filter(Objects::nonNull) + .collect(Collectors.toCollection(LinkedHashSet::new)); + } + /** * Purpose: buildFeaturedProduct converts a product row into a compact trust card. * Usage: keep this card small and do not include unpublished product internals. diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/user/entity/UserDO.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/user/entity/UserDO.java index 2471e98c..c5cf1466 100644 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/user/entity/UserDO.java +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/user/entity/UserDO.java @@ -127,6 +127,9 @@ public class UserDO extends BaseEntity { @TableField("signature") private String signature; + @TableField("profile_moderation_status") + private String profileModerationStatus; + /** * 用户等级 */ diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/user/mapper/UserMapper.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/user/mapper/UserMapper.java index 06a3e902..02e9bd57 100644 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/user/mapper/UserMapper.java +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/user/mapper/UserMapper.java @@ -16,6 +16,9 @@ import java.util.List; */ public interface UserMapper extends BaseMapper { + @Select("SELECT COUNT(1) FROM t_user WHERE is_delete = 0 AND status = 1 AND profile_moderation_status = 'APPROVED' AND (avatar = (SELECT file_url FROM t_object_storage_file WHERE id = #{fileId}) OR avatar = (SELECT primary_url FROM t_object_storage_file WHERE id = #{fileId}) OR avatar = (SELECT object_name FROM t_object_storage_file WHERE id = #{fileId}) OR wechat_qr_code = (SELECT file_url FROM t_object_storage_file WHERE id = #{fileId}) OR wechat_qr_code = (SELECT primary_url FROM t_object_storage_file WHERE id = #{fileId}) OR wechat_qr_code = (SELECT object_name FROM t_object_storage_file WHERE id = #{fileId}))") + Long countPublicImageReference(@Param("fileId") Long fileId); + @Select("SELECT id FROM t_user WHERE account = #{account} AND account_hash IS NULL AND is_delete = 0 LIMIT 1") Long findLegacyIdByAccount(@Param("account") String account); 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 8abbd489..ffe5a56d 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 @@ -35,6 +35,7 @@ import com.xiaowang.jayucloud.salon.core.modules.registration.entity.WorkbenchRe import com.xiaowang.jayucloud.salon.core.modules.registration.mapper.WorkbenchRegistrationApplicationMapper; 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.security.support.PermissionCatalog; import com.xiaowang.jayucloud.salon.core.support.security.UserSessionService; import com.xiaowang.jayucloud.salon.core.support.id.TimeOrderedSnowflakeIdGenerator; @@ -191,6 +192,7 @@ public class UserServiceImpl extends ServiceImpl implements * Variable `objectStorageUrlSupport`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. */ private final ObjectStorageUrlSupport objectStorageUrlSupport; + private final ObjectStorageFileService objectStorageFileService; /** * Variable `redisTemplate`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. */ @@ -423,6 +425,9 @@ public class UserServiceImpl extends ServiceImpl implements userDO.setVipId(userDTO.getVipId()); userDO.setIsDelete(0); userDO.setStatus(1); + if (!Integer.valueOf(0).equals(userType)) { + userDO.setProfileModerationStatus("PENDING"); + } if (StringUtils.hasText(userDTO.getAvatar())) { userDO.setAvatar(normalizeStoredAvatar(userDTO.getAvatar())); } else { @@ -454,6 +459,20 @@ public class UserServiceImpl extends ServiceImpl implements throw e; } + if (!Integer.valueOf(0).equals(userType)) { + Map profile = new java.util.LinkedHashMap<>(); + profile.put("nickname", userDO.getNickname()); + profile.put("signature", userDO.getSignature()); + profile.put("avatar", userDO.getAvatar()); + profile.put("wechatQrCode", userDO.getWechatQrCode()); + List profileImages = new ArrayList<>(); + addImageFileId(profileImages, userDO.getAvatar()); + addImageFileId(profileImages, userDO.getWechatQrCode()); + contentModerationService.assessVersion("USER_PROFILE", userDO.getId(), userDO.getId(), + profile.values().stream().filter(Objects::nonNull).collect(Collectors.joining("\n")), + serializeModerationPayload(profile), profileImages); + } + // 分配默认权限 assignDefaultPermissions(userDO.getId(), userDO.getType()); userShopBindingSupport.syncUserShopBindings(userDO.getId(), validatedShopIds); @@ -593,6 +612,10 @@ public class UserServiceImpl extends ServiceImpl implements if (userDO == null) { return false; } + String originalNickname = userDO.getNickname(); + String originalAvatar = userDO.getAvatar(); + String originalSignature = userDO.getSignature(); + String originalWechatQrCode = userDO.getWechatQrCode(); // 更新账号(如果提供且变更) String normalizedAccount = AccountValidationUtils.validateOptionalAccount(userDTO.getAccount()); @@ -655,6 +678,33 @@ public class UserServiceImpl extends ServiceImpl implements if (userDTO.getVipId() != null) { userDO.setVipId(userDTO.getVipId()); } + boolean publicProfileChanged = !Objects.equals(originalNickname, userDO.getNickname()) + || !Objects.equals(originalAvatar, userDO.getAvatar()) + || !Objects.equals(originalSignature, userDO.getSignature()) + || !Objects.equals(originalWechatQrCode, userDO.getWechatQrCode()); + if (publicProfileChanged) { + Map profile = new java.util.LinkedHashMap<>(); + profile.put("nickname", userDO.getNickname()); + profile.put("signature", userDO.getSignature()); + profile.put("avatar", userDO.getAvatar()); + profile.put("wechatQrCode", userDO.getWechatQrCode()); + List profileImages = new ArrayList<>(); + if (userDTO.getAvatar() != null && !userDTO.getAvatar().isEmpty()) { + addImageFileId(profileImages, userDO.getAvatar()); + } + if (userDTO.getWechatQrCode() != null) { + addImageFileId(profileImages, userDO.getWechatQrCode()); + } + ContentModerationResultVO moderation = contentModerationService.assessVersion("USER_PROFILE", id, id, + profile.values().stream().filter(Objects::nonNull).collect(Collectors.joining("\n")), + serializeModerationPayload(profile), profileImages); + if (!moderationApproved(moderation)) { + userDO.setNickname(originalNickname); + userDO.setAvatar(originalAvatar); + userDO.setSignature(originalSignature); + userDO.setWechatQrCode(originalWechatQrCode); + } + } Integer targetUserType = userDO.getType(); UserProfileFieldSupport.requireWechatIdForServiceUser(targetUserType, userDO.getWechatId()); List validatedShopIds = null; @@ -799,6 +849,7 @@ public class UserServiceImpl extends ServiceImpl implements Wrappers.lambdaQuery(UserDO.class) .eq(UserDO::getIsDelete, 0) .eq(UserDO::getType, type) + .eq(UserDO::getProfileModerationStatus, "APPROVED") ); return userDOs.stream() .map(this::convertToVO) @@ -1740,30 +1791,38 @@ public class UserServiceImpl extends ServiceImpl implements */ assertUserAvailable(userDO); + boolean profileApproved = true; if (userDTO.getNickname() != null || userDTO.getSignature() != null - || (userDTO.getAvatar() != null && !userDTO.getAvatar().isEmpty())) { + || (userDTO.getAvatar() != null && !userDTO.getAvatar().isEmpty()) || userDTO.getWechatQrCode() != null) { Map content = new java.util.LinkedHashMap<>(); - content.put("nickname", userDTO.getNickname()); - content.put("signature", userDTO.getSignature()); - content.put("avatar", userDTO.getAvatar() == null || userDTO.getAvatar().isEmpty() - ? null : normalizeStoredAvatar(userDTO.getAvatar())); + 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 + ? userDO.getAvatar() + : (userDTO.getAvatar().isEmpty() ? null : normalizeStoredAvatar(userDTO.getAvatar()))); + content.put("wechatQrCode", userDTO.getWechatQrCode() == null + ? userDO.getWechatQrCode() : normalizeStoredProfileImage(userDTO.getWechatQrCode())); String serialized = serializeModerationPayload(content); - ContentModerationResultVO moderation = contentModerationService.assess("USER_PROFILE", userId, userId, - String.join("\n", content.values().stream().filter(Objects::nonNull).toList()), serialized); - requireApprovedContent(moderation); + List profileImages = new ArrayList<>(); + addImageFileId(profileImages, content.get("avatar")); + addImageFileId(profileImages, content.get("wechatQrCode")); + ContentModerationResultVO moderation = contentModerationService.assessVersion("USER_PROFILE", userId, userId, + String.join("\n", content.values().stream().filter(Objects::nonNull).toList()), serialized, profileImages); + profileApproved = moderation != null && "APPROVED".equals(moderation.getStatus()); + if (profileApproved) userDO = userMapper.selectById(userId); } - if (userDTO.getNickname() != null) { + if (profileApproved && userDTO.getNickname() != null) { userDO.setNickname(userDTO.getNickname()); } - if (userDTO.getAvatar() != null) { + if (profileApproved && userDTO.getAvatar() != null) { if (userDTO.getAvatar().isEmpty()) { userDO.setAvatar(null); } else { userDO.setAvatar(normalizeStoredAvatar(userDTO.getAvatar())); } } - if (userDTO.getSignature() != null) { + if (profileApproved && userDTO.getSignature() != null) { userDO.setSignature(userDTO.getSignature()); } if (userDTO.getContactPhone() != null) { @@ -1775,7 +1834,7 @@ public class UserServiceImpl extends ServiceImpl implements if (userDTO.getWechatId() != null) { userDO.setWechatId(UserProfileFieldSupport.normalizeOptionalText(userDTO.getWechatId())); } - if (userDTO.getWechatQrCode() != null) { + if (profileApproved && userDTO.getWechatQrCode() != null) { userDO.setWechatQrCode(normalizeStoredProfileImage(userDTO.getWechatQrCode())); } UserProfileFieldSupport.requireWechatIdForServiceUser(userDO.getType(), userDO.getWechatId()); @@ -2231,12 +2290,21 @@ public class UserServiceImpl extends ServiceImpl implements */ assertUserAvailable(userDO); String storedAvatar = normalizeStoredAvatar(avatarUrl); - ContentModerationResultVO moderation = contentModerationService.assess("USER_AVATAR", userId, userId, - avatarUrl, serializeModerationPayload(java.util.Map.of("avatar", storedAvatar))); - requireApprovedContent(moderation); - userDO.setAvatar(storedAvatar); - userDO.setUpdateTime(LocalDateTime.now()); - return userMapper.updateById(userDO) > 0; + List imageIds = new ArrayList<>(); + addImageFileId(imageIds, storedAvatar); + ContentModerationResultVO moderation = contentModerationService.assessVersion("USER_AVATAR", userId, userId, + "", serializeModerationPayload(java.util.Map.of("avatar", storedAvatar)), imageIds); + return moderation != null && ("APPROVED".equals(moderation.getStatus()) || "PENDING".equals(moderation.getStatus()) || "RETRY".equals(moderation.getStatus())); + } + + private void addImageFileId(List imageIds, String reference) { + if (!StringUtils.hasText(reference)) return; + if (DEFAULT_AVATAR_URL.equals(reference)) return; + Long fileId = objectStorageFileService.findFileIdByReference(reference); + if (fileId == null || fileId <= 0) { + throw new IllegalArgumentException("个人资料图片必须引用已上传文件"); + } + if (!imageIds.contains(fileId)) imageIds.add(fileId); } private String serializeModerationPayload(Object payload) { @@ -2254,6 +2322,10 @@ public class UserServiceImpl extends ServiceImpl implements } } + private boolean moderationApproved(ContentModerationResultVO result) { + return result != null && "APPROVED".equals(result.getStatus()); + } + @Override /** * Update an existing record. diff --git a/JC-Salon-Core/src/main/resources/db/migration/V2__Salon对外内容审核_20261024.sql b/JC-Salon-Core/src/main/resources/db/migration/V2__Salon对外内容审核_20261024.sql new file mode 100644 index 00000000..ea123a57 --- /dev/null +++ b/JC-Salon-Core/src/main/resources/db/migration/V2__Salon对外内容审核_20261024.sql @@ -0,0 +1,216 @@ +ALTER TABLE t_content_moderation_record + ADD COLUMN version_no int NOT NULL DEFAULT 1 COMMENT '业务内容版本号', + ADD COLUMN image_count int NOT NULL DEFAULT 0 COMMENT '该版本图片总数', + ADD COLUMN text_status varchar(20) NOT NULL DEFAULT 'PENDING' COMMENT '文字审核状态', + ADD COLUMN text_content mediumtext NULL COMMENT '待审文字内容', + ADD COLUMN next_retry_at datetime NULL COMMENT '下次自动重试时间'; + +ALTER TABLE t_product + ADD COLUMN moderation_status varchar(20) NOT NULL DEFAULT 'PENDING' COMMENT '公开审核状态'; +ALTER TABLE t_comment + ADD COLUMN moderation_version int NOT NULL DEFAULT 1 COMMENT '评论审核版本号'; +ALTER TABLE t_shop + ADD COLUMN moderation_status varchar(20) NOT NULL DEFAULT 'PENDING' COMMENT '门店展示资料审核状态'; +ALTER TABLE t_announcement + ADD COLUMN moderation_status varchar(20) NOT NULL DEFAULT 'PENDING' COMMENT '公告审核状态', + ADD COLUMN image_file_ids text NULL COMMENT '公告图片文件ID集合,多个ID以逗号分隔'; +ALTER TABLE t_system_message + ADD COLUMN moderation_status varchar(20) NOT NULL DEFAULT 'APPROVED' COMMENT '人工消息审核状态;自动事务消息默认通过'; +ALTER TABLE t_user + ADD COLUMN profile_moderation_status varchar(20) NOT NULL DEFAULT 'APPROVED' COMMENT '公开个人资料审核状态'; +ALTER TABLE t_order_artist_review + ADD COLUMN moderation_status varchar(20) NOT NULL DEFAULT 'APPROVED' COMMENT '评价审核状态:PENDING/APPROVED/REJECTED/RETRY'; +ALTER TABLE t_effect_diagram + ADD COLUMN moderation_status varchar(20) NOT NULL DEFAULT 'PENDING' COMMENT '效果图审核状态:PENDING/APPROVED/REJECTED/RETRY'; + +CREATE TEMPORARY TABLE tmp_content_moderation_sequence ( + seq int NOT NULL PRIMARY KEY +); +INSERT INTO tmp_content_moderation_sequence (seq) +SELECT ones.n + tens.n * 10 + hundreds.n * 100 + 1 +FROM (SELECT 0 n UNION ALL SELECT 1 UNION ALL SELECT 2 UNION ALL SELECT 3 UNION ALL SELECT 4 UNION ALL SELECT 5 UNION ALL SELECT 6 UNION ALL SELECT 7 UNION ALL SELECT 8 UNION ALL SELECT 9) ones +CROSS JOIN (SELECT 0 n UNION ALL SELECT 1 UNION ALL SELECT 2 UNION ALL SELECT 3 UNION ALL SELECT 4 UNION ALL SELECT 5 UNION ALL SELECT 6 UNION ALL SELECT 7 UNION ALL SELECT 8 UNION ALL SELECT 9) tens +CROSS JOIN (SELECT 0 n UNION ALL SELECT 1 UNION ALL SELECT 2 UNION ALL SELECT 3 UNION ALL SELECT 4 UNION ALL SELECT 5 UNION ALL SELECT 6 UNION ALL SELECT 7 UNION ALL SELECT 8 UNION ALL SELECT 9) hundreds; + +CREATE TABLE t_content_moderation_image_task ( + id bigint unsigned NOT NULL COMMENT '审核图片任务ID', + record_id bigint unsigned NOT NULL COMMENT '内容审核版本ID', + file_id bigint unsigned NOT NULL COMMENT '对象存储文件ID', + provider_task_id varchar(100) NULL COMMENT '微信异步审核任务标识', + status varchar(20) NOT NULL COMMENT '图片审核状态:PENDING/APPROVED/REJECTED/RETRY', + result_code varchar(80) NULL COMMENT '图片审核结果代码', + reason varchar(500) NULL COMMENT '图片审核说明', + attempt_count int NOT NULL DEFAULT 0 COMMENT '提交尝试次数', + next_retry_at datetime 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 (id), + UNIQUE KEY uk_content_moderation_image_provider_task (provider_task_id), + KEY idx_content_moderation_image_record (record_id, status), + KEY idx_content_moderation_image_file (file_id), + KEY idx_content_moderation_image_retry (status, next_retry_at), + CONSTRAINT fk_content_moderation_image_record FOREIGN KEY (record_id) REFERENCES t_content_moderation_record (id) +) COMMENT='内容版本逐图审核与微信异步任务'; + +CREATE INDEX idx_product_moderation_public ON t_product (shop_id, moderation_status, front_visible, is_delete); +CREATE INDEX idx_shop_moderation_public ON t_shop (moderation_status, status, is_delete); +CREATE INDEX idx_announcement_moderation_public ON t_announcement (moderation_status, status, publish_time); +CREATE INDEX idx_system_message_moderation_public ON t_system_message (moderation_status, status, publish_time); +CREATE INDEX idx_order_artist_review_moderation_public ON t_order_artist_review (moderation_status, status, is_delete); +CREATE INDEX idx_effect_diagram_moderation_public ON t_effect_diagram (product_id, moderation_status, is_delete); + +INSERT INTO t_content_moderation_record + (id, content_type, business_id, user_id, version_no, image_count, text_status, text_content, status, provider, result_code, reason, payload_json, attempt_count, create_time, update_time) +SELECT CAST(CONV(SUBSTR(SHA2(CONCAT('LEGACY:RECORD:PRODUCT:', p.id), 256), 1, 15), 16, 10) AS UNSIGNED), 'PRODUCT', p.id, NULL, 1, + (LENGTH(REPLACE(COALESCE(p.image_file_ids, ''), ' ', '')) - LENGTH(REPLACE(REPLACE(COALESCE(p.image_file_ids, ''), ' ', ''), ',', '')) + IF(COALESCE(p.image_file_ids, '') = '', 0, 1)), + 'PENDING', CONCAT_WS(CHAR(10), p.title, p.description, p.target_audience, p.precautions, p.tags), 'PENDING', 'LEGACY_REVIEW', 'LEGACY_PUBLIC_CONTENT', '存量公开作品等待审核', + JSON_OBJECT('shopId', p.shop_id, 'title', p.title, 'description', p.description, 'targetAudience', p.target_audience, 'precautions', p.precautions, 'imageFileIds', p.image_file_ids, 'price', p.price, 'tags', p.tags, 'approximateDuration', p.approximate_duration, 'bookableArtists', p.bookable_artists, 'availableCoupons', p.available_coupons, 'frontVisible', p.front_visible), 0, NOW(), NOW() +FROM t_product p WHERE p.is_delete = 0 AND p.front_visible = 1 AND COALESCE(p.source_type, '') <> 'MANAGER_APPOINTMENT'; + +INSERT INTO t_content_moderation_image_task (id, record_id, file_id, status, result_code, reason, attempt_count, create_time, update_time) +SELECT CAST(CONV(SUBSTR(SHA2(CONCAT('PRODUCT:', p.id, ':', seq.seq), 256), 1, 15), 16, 10) AS UNSIGNED), + CAST(CONV(SUBSTR(SHA2(CONCAT('LEGACY:RECORD:PRODUCT:', p.id), 256), 1, 15), 16, 10) AS UNSIGNED), + CAST(SUBSTRING_INDEX(SUBSTRING_INDEX(REPLACE(COALESCE(p.image_file_ids, ''), ' ', ''), ',', seq.seq), ',', -1) AS UNSIGNED), + 'PENDING', 'LEGACY_REVIEW', '存量公开作品图片等待审核', 0, NOW(), NOW() +FROM t_product p +JOIN tmp_content_moderation_sequence seq + ON seq.seq <= (LENGTH(REPLACE(COALESCE(p.image_file_ids, ''), ' ', '')) - LENGTH(REPLACE(REPLACE(COALESCE(p.image_file_ids, ''), ' ', ''), ',', '')) + IF(COALESCE(p.image_file_ids, '') = '', 0, 1)) +WHERE p.is_delete = 0 AND p.front_visible = 1 AND COALESCE(p.source_type, '') <> 'MANAGER_APPOINTMENT' + AND CAST(SUBSTRING_INDEX(SUBSTRING_INDEX(REPLACE(p.image_file_ids, ' ', ''), ',', seq.seq), ',', -1) AS UNSIGNED) > 0; + +UPDATE t_product p JOIN t_content_moderation_record r ON r.content_type = 'PRODUCT' AND r.business_id = p.id SET p.moderation_status = 'PENDING', p.front_visible = 0; + +INSERT INTO t_content_moderation_record + (id, content_type, business_id, user_id, version_no, image_count, text_status, text_content, status, provider, result_code, reason, payload_json, attempt_count, create_time, update_time) +SELECT CAST(CONV(SUBSTR(SHA2(CONCAT('LEGACY:RECORD:SHOP:', s.id), 256), 1, 15), 16, 10) AS UNSIGNED), 'SHOP', s.id, NULL, 1, + (LENGTH(CONCAT_WS(',', NULLIF(s.cover_image_file_id, ''), NULLIF(s.image_file_ids, ''), NULLIF(s.theme_background_image_file_id, ''))) - LENGTH(REPLACE(CONCAT_WS(',', NULLIF(s.cover_image_file_id, ''), NULLIF(s.image_file_ids, ''), NULLIF(s.theme_background_image_file_id, '')), ',', '')) + IF(CONCAT_WS(',', NULLIF(s.cover_image_file_id, ''), NULLIF(s.image_file_ids, ''), NULLIF(s.theme_background_image_file_id, '')) = '', 0, 1)), + 'PENDING', CONCAT_WS(CHAR(10), s.shop_name, s.description, s.address, s.business_hours), 'PENDING', 'LEGACY_REVIEW', 'LEGACY_PUBLIC_CONTENT', '存量门店展示资料等待审核', + JSON_OBJECT('shopName', s.shop_name, 'description', s.description, 'address', s.address, 'businessHours', s.business_hours, 'coverImageFileId', s.cover_image_file_id, 'imageFileIds', s.image_file_ids, 'themeBackgroundImageFileId', s.theme_background_image_file_id), 0, NOW(), NOW() +FROM t_shop s WHERE s.is_delete = 0 AND s.status = 1; + +INSERT INTO t_content_moderation_image_task (id, record_id, file_id, status, result_code, reason, attempt_count, create_time, update_time) +SELECT CAST(CONV(SUBSTR(SHA2(CONCAT('LEGACY:IMAGE:SHOP:', s.id, ':', seq.seq), 256), 1, 15), 16, 10) AS UNSIGNED), CAST(CONV(SUBSTR(SHA2(CONCAT('LEGACY:RECORD:SHOP:', s.id), 256), 1, 15), 16, 10) AS UNSIGNED), + CAST(SUBSTRING_INDEX(SUBSTRING_INDEX(REPLACE(CONCAT_WS(',', NULLIF(s.cover_image_file_id, ''), NULLIF(s.image_file_ids, ''), NULLIF(s.theme_background_image_file_id, '')), ' ', ''), ',', seq.seq), ',', -1) AS UNSIGNED), + 'PENDING', 'LEGACY_REVIEW', '存量门店图片等待审核', 0, NOW(), NOW() +FROM t_shop s +JOIN tmp_content_moderation_sequence seq + ON seq.seq <= (LENGTH(CONCAT_WS(',', NULLIF(s.cover_image_file_id, ''), NULLIF(s.image_file_ids, ''), NULLIF(s.theme_background_image_file_id, ''))) - LENGTH(REPLACE(CONCAT_WS(',', NULLIF(s.cover_image_file_id, ''), NULLIF(s.image_file_ids, ''), NULLIF(s.theme_background_image_file_id, '')), ',', '')) + IF(CONCAT_WS(',', NULLIF(s.cover_image_file_id, ''), NULLIF(s.image_file_ids, ''), NULLIF(s.theme_background_image_file_id, '')) = '', 0, 1)) +WHERE s.is_delete = 0 AND s.status = 1 AND CAST(SUBSTRING_INDEX(SUBSTRING_INDEX(REPLACE(CONCAT_WS(',', NULLIF(s.cover_image_file_id, ''), NULLIF(s.image_file_ids, ''), NULLIF(s.theme_background_image_file_id, '')), ' ', ''), ',', seq.seq), ',', -1) AS UNSIGNED) > 0; + +UPDATE t_shop s JOIN t_content_moderation_record r ON r.content_type = 'SHOP' AND r.business_id = s.id SET s.moderation_status = 'PENDING'; + +INSERT INTO t_content_moderation_record + (id, content_type, business_id, user_id, version_no, image_count, text_status, text_content, status, provider, result_code, reason, payload_json, attempt_count, create_time, update_time) +SELECT CAST(CONV(SUBSTR(SHA2(CONCAT('LEGACY:RECORD:COMMENT:', c.id), 256), 1, 15), 16, 10) AS UNSIGNED), 'COMMENT', c.id, c.user_id, 1, + (LENGTH(REPLACE(COALESCE(c.image_file_ids, ''), ' ', '')) - LENGTH(REPLACE(REPLACE(COALESCE(c.image_file_ids, ''), ' ', ''), ',', '')) + IF(COALESCE(c.image_file_ids, '') = '', 0, 1)), + 'PENDING', c.comment_content, 'PENDING', 'LEGACY_REVIEW', 'LEGACY_PUBLIC_CONTENT', '存量公开评论等待审核', + JSON_OBJECT('commentContent', c.comment_content, 'imageFileIds', c.image_file_ids), 0, NOW(), NOW() +FROM t_comment c WHERE c.is_delete = 0 AND c.moderation_status = 'APPROVED'; + +INSERT INTO t_content_moderation_image_task (id, record_id, file_id, status, result_code, reason, attempt_count, create_time, update_time) +SELECT CAST(CONV(SUBSTR(SHA2(CONCAT('LEGACY:IMAGE:COMMENT:', c.id, ':', seq.seq), 256), 1, 15), 16, 10) AS UNSIGNED), CAST(CONV(SUBSTR(SHA2(CONCAT('LEGACY:RECORD:COMMENT:', c.id), 256), 1, 15), 16, 10) AS UNSIGNED), + CAST(SUBSTRING_INDEX(SUBSTRING_INDEX(REPLACE(COALESCE(c.image_file_ids, ''), ' ', ''), ',', seq.seq), ',', -1) AS UNSIGNED), + 'PENDING', 'LEGACY_REVIEW', '存量评论图片等待审核', 0, NOW(), NOW() +FROM t_comment c +JOIN tmp_content_moderation_sequence seq + ON seq.seq <= (LENGTH(REPLACE(COALESCE(c.image_file_ids, ''), ' ', '')) - LENGTH(REPLACE(REPLACE(COALESCE(c.image_file_ids, ''), ' ', ''), ',', '')) + IF(COALESCE(c.image_file_ids, '') = '', 0, 1)) +WHERE c.is_delete = 0 AND c.moderation_status = 'APPROVED' AND CAST(SUBSTRING_INDEX(SUBSTRING_INDEX(REPLACE(c.image_file_ids, ' ', ''), ',', seq.seq), ',', -1) AS UNSIGNED) > 0; + +UPDATE t_comment c JOIN t_content_moderation_record r ON r.content_type = 'COMMENT' AND r.business_id = c.id SET c.moderation_status = 'PENDING'; + +INSERT INTO t_content_moderation_record + (id, content_type, business_id, user_id, version_no, image_count, text_status, text_content, status, provider, result_code, reason, payload_json, attempt_count, create_time, update_time) +SELECT CAST(CONV(SUBSTR(SHA2(CONCAT('LEGACY:RECORD:ANNOUNCEMENT:', a.id), 256), 1, 15), 16, 10) AS UNSIGNED), 'ANNOUNCEMENT', a.id, a.publisher_id, 1, + (CASE WHEN TRIM(REPLACE(COALESCE(a.image_file_ids, ''), ' ', '')) REGEXP '^[0-9]+(,[0-9]+)*$' THEN (LENGTH(REPLACE(a.image_file_ids, ' ', '')) - LENGTH(REPLACE(REPLACE(a.image_file_ids, ' ', ''), ',', '')) + 1) ELSE 0 END), + 'PENDING', CONCAT_WS(CHAR(10), a.title, a.content), 'PENDING', 'LEGACY_REVIEW', 'LEGACY_PUBLIC_CONTENT', '存量公开公告等待审核', + JSON_OBJECT('title', a.title, 'content', a.content, 'imageFileIds', a.image_file_ids, 'status', a.status), 0, NOW(), NOW() +FROM t_announcement a WHERE a.is_delete = 0 AND a.status = 1; +UPDATE t_announcement a JOIN t_content_moderation_record r ON r.content_type = 'ANNOUNCEMENT' AND r.business_id = a.id SET a.moderation_status = 'PENDING'; + +INSERT INTO t_content_moderation_image_task (id, record_id, file_id, status, result_code, reason, attempt_count, create_time, update_time) +SELECT CAST(CONV(SUBSTR(SHA2(CONCAT('LEGACY:IMAGE:ANNOUNCEMENT:', a.id, ':', seq.seq), 256), 1, 15), 16, 10) AS UNSIGNED), CAST(CONV(SUBSTR(SHA2(CONCAT('LEGACY:RECORD:ANNOUNCEMENT:', a.id), 256), 1, 15), 16, 10) AS UNSIGNED), + CAST(SUBSTRING_INDEX(SUBSTRING_INDEX(REPLACE(COALESCE(a.image_file_ids, ''), ' ', ''), ',', seq.seq), ',', -1) AS UNSIGNED), + 'PENDING', 'LEGACY_REVIEW', '存量公告图片等待审核', 0, NOW(), NOW() +FROM t_announcement a +JOIN tmp_content_moderation_sequence seq + ON seq.seq <= (LENGTH(REPLACE(COALESCE(a.image_file_ids, ''), ' ', '')) - LENGTH(REPLACE(REPLACE(COALESCE(a.image_file_ids, ''), ' ', ''), ',', '')) + IF(COALESCE(a.image_file_ids, '') = '', 0, 1)) +WHERE a.is_delete = 0 AND a.status = 1 AND CAST(SUBSTRING_INDEX(SUBSTRING_INDEX(REPLACE(a.image_file_ids, ' ', ''), ',', seq.seq), ',', -1) AS UNSIGNED) > 0; + +INSERT INTO t_content_moderation_record + (id, content_type, business_id, user_id, version_no, image_count, text_status, text_content, status, provider, result_code, reason, payload_json, attempt_count, create_time, update_time) +SELECT CAST(CONV(SUBSTR(SHA2(CONCAT('LEGACY:RECORD:SYSTEM_MESSAGE:', m.id), 256), 1, 15), 16, 10) AS UNSIGNED), 'SYSTEM_MESSAGE', m.id, m.publisher_id, 1, + IF(m.image_file_id IS NULL, 0, 1), 'PENDING', CONCAT_WS(CHAR(10), m.title, m.content), 'PENDING', 'LEGACY_REVIEW', 'LEGACY_PUBLIC_CONTENT', '存量人工发布消息等待审核', + JSON_OBJECT('title', m.title, 'content', m.content, 'imageFileId', m.image_file_id, 'status', m.status), 0, NOW(), NOW() +FROM t_system_message m WHERE m.is_delete = 0 AND m.status = 1 AND m.business_type IS NULL; +INSERT INTO t_content_moderation_image_task (id, record_id, file_id, status, result_code, reason, attempt_count, create_time, update_time) +SELECT CAST(CONV(SUBSTR(SHA2(CONCAT('LEGACY:IMAGE:SYSTEM_MESSAGE:', m.id, ':1'), 256), 1, 15), 16, 10) AS UNSIGNED), CAST(CONV(SUBSTR(SHA2(CONCAT('LEGACY:RECORD:SYSTEM_MESSAGE:', m.id), 256), 1, 15), 16, 10) AS UNSIGNED), m.image_file_id, 'PENDING', 'LEGACY_REVIEW', '存量人工消息图片等待审核', 0, NOW(), NOW() +FROM t_system_message m WHERE m.is_delete = 0 AND m.status = 1 AND m.business_type IS NULL AND m.image_file_id IS NOT NULL; +UPDATE t_system_message m JOIN t_content_moderation_record r ON r.content_type = 'SYSTEM_MESSAGE' AND r.business_id = m.id SET m.moderation_status = 'PENDING'; + +INSERT INTO t_content_moderation_record + (id, content_type, business_id, user_id, version_no, image_count, text_status, text_content, status, provider, result_code, reason, payload_json, attempt_count, create_time, update_time) +SELECT CAST(CONV(SUBSTR(SHA2(CONCAT('LEGACY:RECORD:USER_PROFILE:', u.id), 256), 1, 15), 16, 10) AS UNSIGNED), 'USER_PROFILE', u.id, u.id, 1, + (SELECT COUNT(DISTINCT profile_file.id) FROM t_object_storage_file profile_file + WHERE profile_file.file_url IN (u.avatar, u.wechat_qr_code) + OR profile_file.primary_url IN (u.avatar, u.wechat_qr_code) + OR profile_file.object_name IN (u.avatar, u.wechat_qr_code)), 'PENDING', CONCAT_WS(CHAR(10), u.nickname, u.signature), 'PENDING', 'LEGACY_REVIEW', 'LEGACY_PUBLIC_CONTENT', '存量个人资料等待审核', + JSON_OBJECT( + 'nickname', u.nickname, + 'signature', u.signature, + 'avatar', CASE WHEN EXISTS (SELECT 1 FROM t_object_storage_file avatar_file WHERE avatar_file.file_url = u.avatar OR avatar_file.primary_url = u.avatar OR avatar_file.object_name = u.avatar) THEN u.avatar ELSE NULL END, + 'wechatQrCode', CASE WHEN EXISTS (SELECT 1 FROM t_object_storage_file qr_file WHERE qr_file.file_url = u.wechat_qr_code OR qr_file.primary_url = u.wechat_qr_code OR qr_file.object_name = u.wechat_qr_code) THEN u.wechat_qr_code ELSE NULL END + ), 0, NOW(), NOW() +FROM t_user u WHERE u.is_delete = 0 AND u.status = 1 + AND (u.nickname IS NOT NULL OR u.signature IS NOT NULL OR u.avatar IS NOT NULL OR u.wechat_qr_code IS NOT NULL); +INSERT INTO t_content_moderation_image_task (id, record_id, file_id, status, result_code, reason, attempt_count, create_time, update_time) +SELECT CAST(CONV(SUBSTR(SHA2(CONCAT('LEGACY:IMAGE:USER_PROFILE:', u.id, ':', f.id), 256), 1, 15), 16, 10) AS UNSIGNED), + CAST(CONV(SUBSTR(SHA2(CONCAT('LEGACY:RECORD:USER_PROFILE:', u.id), 256), 1, 15), 16, 10) AS UNSIGNED), f.id, 'PENDING', 'LEGACY_REVIEW', '存量个人资料图片等待审核', 0, NOW(), NOW() +FROM t_user u JOIN t_object_storage_file f + ON f.file_url IN (u.avatar, u.wechat_qr_code) + OR f.primary_url IN (u.avatar, u.wechat_qr_code) + OR f.object_name IN (u.avatar, u.wechat_qr_code) +WHERE u.is_delete = 0 AND u.status = 1 AND (u.avatar IS NOT NULL OR u.wechat_qr_code IS NOT NULL) +GROUP BY u.id, f.id; +UPDATE t_user u JOIN t_content_moderation_record r ON r.content_type = 'USER_PROFILE' AND r.business_id = u.id SET u.profile_moderation_status = 'PENDING'; + +INSERT INTO t_content_moderation_record + (id, content_type, business_id, user_id, version_no, image_count, text_status, text_content, status, provider, result_code, reason, payload_json, attempt_count, create_time, update_time) +SELECT CAST(CONV(SUBSTR(SHA2(CONCAT('LEGACY:RECORD:AUTO_SYSTEM_MESSAGE:', m.id), 256), 1, 15), 16, 10) AS UNSIGNED), 'SYSTEM_MESSAGE', m.id, m.publisher_id, 1, 0, + 'APPROVED', '', 'APPROVED', 'LEGACY_SYSTEM', 'AUTO_TRANSACTION_MESSAGE', '自动事务消息不送审', NULL, 0, NOW(), NOW() +FROM t_system_message m WHERE m.is_delete = 0 AND m.status = 1 AND m.business_type IS NOT NULL; + +INSERT INTO t_content_moderation_record + (id, content_type, business_id, user_id, version_no, image_count, text_status, text_content, status, provider, result_code, reason, payload_json, attempt_count, create_time, update_time) +SELECT CAST(CONV(SUBSTR(SHA2(CONCAT('LEGACY:RECORD:ORDER_ARTIST_REVIEW:', r.id), 256), 1, 15), 16, 10) AS UNSIGNED), 'ORDER_ARTIST_REVIEW', r.id, r.customer_id, 1, + (LENGTH(REPLACE(COALESCE(r.image_file_ids, ''), ' ', '')) - LENGTH(REPLACE(REPLACE(COALESCE(r.image_file_ids, ''), ' ', ''), ',', '')) + IF(COALESCE(r.image_file_ids, '') = '', 0, 1)), + 'PENDING', r.content, 'PENDING', 'LEGACY_REVIEW', 'LEGACY_PUBLIC_CONTENT', '存量订单评价等待审核', + JSON_OBJECT('content', r.content, 'imageFileIds', r.image_file_ids), 0, NOW(), NOW() +FROM t_order_artist_review r WHERE r.is_delete = 0 AND r.status = 1 AND r.moderation_status = 'APPROVED'; +INSERT INTO t_content_moderation_image_task (id, record_id, file_id, status, result_code, reason, attempt_count, create_time, update_time) +SELECT CAST(CONV(SUBSTR(SHA2(CONCAT('LEGACY:IMAGE:ORDER_ARTIST_REVIEW:', r.id, ':', seq.seq), 256), 1, 15), 16, 10) AS UNSIGNED), CAST(CONV(SUBSTR(SHA2(CONCAT('LEGACY:RECORD:ORDER_ARTIST_REVIEW:', r.id), 256), 1, 15), 16, 10) AS UNSIGNED), + CAST(SUBSTRING_INDEX(SUBSTRING_INDEX(REPLACE(COALESCE(r.image_file_ids, ''), ' ', ''), ',', seq.seq), ',', -1) AS UNSIGNED), + 'PENDING', 'LEGACY_REVIEW', '存量订单评价图片等待审核', 0, NOW(), NOW() +FROM t_order_artist_review r +JOIN tmp_content_moderation_sequence seq + ON seq.seq <= (LENGTH(REPLACE(COALESCE(r.image_file_ids, ''), ' ', '')) - LENGTH(REPLACE(REPLACE(COALESCE(r.image_file_ids, ''), ' ', ''), ',', '')) + IF(COALESCE(r.image_file_ids, '') = '', 0, 1)) +WHERE r.is_delete = 0 AND r.status = 1 AND r.moderation_status = 'APPROVED' AND CAST(SUBSTRING_INDEX(SUBSTRING_INDEX(REPLACE(r.image_file_ids, ' ', ''), ',', seq.seq), ',', -1) AS UNSIGNED) > 0; +UPDATE t_order_artist_review r JOIN t_content_moderation_record m ON m.content_type = 'ORDER_ARTIST_REVIEW' AND m.business_id = r.id SET r.moderation_status = 'PENDING'; + +INSERT INTO t_content_moderation_record + (id, content_type, business_id, user_id, version_no, image_count, text_status, text_content, status, provider, result_code, reason, payload_json, attempt_count, create_time, update_time) +SELECT CAST(CONV(SUBSTR(SHA2(CONCAT('LEGACY:RECORD:EFFECT_DIAGRAM:', e.id), 256), 1, 15), 16, 10) AS UNSIGNED), 'EFFECT_DIAGRAM', e.id, NULL, 1, + (CASE WHEN TRIM(REPLACE(COALESCE(e.image_file_ids, ''), ' ', '')) REGEXP '^[0-9]+(,[0-9]+)*$' THEN (LENGTH(REPLACE(e.image_file_ids, ' ', '')) - LENGTH(REPLACE(REPLACE(e.image_file_ids, ' ', ''), ',', '')) + 1) ELSE 0 END), + 'PENDING', CONCAT_WS(CHAR(10), e.category, e.description, e.tag), 'PENDING', 'LEGACY_REVIEW', 'LEGACY_PUBLIC_CONTENT', '存量效果图等待审核', + JSON_OBJECT('productId', e.product_id, 'category', e.category, 'imageFileIds', e.image_file_ids, 'description', e.description, 'price', e.price, 'duration', e.duration, 'tag', e.tag), 0, NOW(), NOW() +FROM t_effect_diagram e WHERE e.is_delete = 0; +INSERT INTO t_content_moderation_image_task (id, record_id, file_id, status, result_code, reason, attempt_count, create_time, update_time) +SELECT CAST(CONV(SUBSTR(SHA2(CONCAT('LEGACY:IMAGE:EFFECT_DIAGRAM:', e.id, ':', seq.seq), 256), 1, 15), 16, 10) AS UNSIGNED), CAST(CONV(SUBSTR(SHA2(CONCAT('LEGACY:RECORD:EFFECT_DIAGRAM:', e.id), 256), 1, 15), 16, 10) AS UNSIGNED), + CAST(SUBSTRING_INDEX(SUBSTRING_INDEX(REPLACE(COALESCE(e.image_file_ids, ''), ' ', ''), ',', seq.seq), ',', -1) AS UNSIGNED), + 'PENDING', 'LEGACY_REVIEW', '存量效果图图片等待审核', 0, NOW(), NOW() +FROM t_effect_diagram e +JOIN tmp_content_moderation_sequence seq + ON seq.seq <= (LENGTH(REPLACE(COALESCE(e.image_file_ids, ''), ' ', '')) - LENGTH(REPLACE(REPLACE(COALESCE(e.image_file_ids, ''), ' ', ''), ',', '')) + IF(COALESCE(e.image_file_ids, '') = '', 0, 1)) +WHERE e.is_delete = 0 AND CAST(SUBSTRING_INDEX(SUBSTRING_INDEX(REPLACE(e.image_file_ids, ' ', ''), ',', seq.seq), ',', -1) AS UNSIGNED) > 0; +UPDATE t_effect_diagram e JOIN t_content_moderation_record m ON m.content_type = 'EFFECT_DIAGRAM' AND m.business_id = e.id SET e.moderation_status = 'PENDING'; + +DROP TEMPORARY TABLE tmp_content_moderation_sequence; diff --git a/JC-Salon-Core/src/main/resources/db/migration/V3__Salon内容审核存量数据和协议版本修正_20261025.sql b/JC-Salon-Core/src/main/resources/db/migration/V3__Salon内容审核存量数据和协议版本修正_20261025.sql new file mode 100644 index 00000000..b9073f52 --- /dev/null +++ b/JC-Salon-Core/src/main/resources/db/migration/V3__Salon内容审核存量数据和协议版本修正_20261025.sql @@ -0,0 +1,176 @@ +ALTER TABLE t_comment + MODIFY COLUMN moderation_status varchar(20) NOT NULL DEFAULT 'APPROVED' + COMMENT '内容审核状态:PENDING/APPROVED/REJECTED/RETRY'; + +CREATE TEMPORARY TABLE tmp_content_moderation_invalid_legacy_record ( + record_id bigint unsigned NOT NULL PRIMARY KEY +); + +INSERT IGNORE INTO tmp_content_moderation_invalid_legacy_record (record_id) +SELECT r.id +FROM t_content_moderation_record r +JOIN t_product p ON r.content_type = 'PRODUCT' AND r.business_id = p.id +WHERE r.provider = 'LEGACY_REVIEW' + AND COALESCE(TRIM(REPLACE(COALESCE(p.image_file_ids, ''), ' ', '')), '') <> '' + AND ( + TRIM(REPLACE(COALESCE(p.image_file_ids, ''), ' ', '')) NOT REGEXP '^[0-9]+(,[0-9]+)*$' + OR LENGTH(TRIM(REPLACE(COALESCE(p.image_file_ids, ''), ' ', ''))) + - LENGTH(REPLACE(TRIM(REPLACE(COALESCE(p.image_file_ids, ''), ' ', '')), ',', '')) + 1 > 1000 + ); + +INSERT IGNORE INTO tmp_content_moderation_invalid_legacy_record (record_id) +SELECT r.id +FROM t_content_moderation_record r +JOIN t_comment c ON r.content_type = 'COMMENT' AND r.business_id = c.id +WHERE r.provider = 'LEGACY_REVIEW' + AND COALESCE(TRIM(REPLACE(COALESCE(c.image_file_ids, ''), ' ', '')), '') <> '' + AND ( + TRIM(REPLACE(COALESCE(c.image_file_ids, ''), ' ', '')) NOT REGEXP '^[0-9]+(,[0-9]+)*$' + OR LENGTH(TRIM(REPLACE(COALESCE(c.image_file_ids, ''), ' ', ''))) + - LENGTH(REPLACE(TRIM(REPLACE(COALESCE(c.image_file_ids, ''), ' ', '')), ',', '')) + 1 > 1000 + ); + +INSERT IGNORE INTO tmp_content_moderation_invalid_legacy_record (record_id) +SELECT r.id +FROM t_content_moderation_record r +JOIN t_order_artist_review business_review ON r.content_type = 'ORDER_ARTIST_REVIEW' AND r.business_id = business_review.id +WHERE r.provider = 'LEGACY_REVIEW' + AND COALESCE(TRIM(REPLACE(COALESCE(business_review.image_file_ids, ''), ' ', '')), '') <> '' + AND ( + TRIM(REPLACE(COALESCE(business_review.image_file_ids, ''), ' ', '')) NOT REGEXP '^[0-9]+(,[0-9]+)*$' + OR LENGTH(TRIM(REPLACE(COALESCE(business_review.image_file_ids, ''), ' ', ''))) + - LENGTH(REPLACE(TRIM(REPLACE(COALESCE(business_review.image_file_ids, ''), ' ', '')), ',', '')) + 1 > 1000 + ); + +INSERT IGNORE INTO tmp_content_moderation_invalid_legacy_record (record_id) +SELECT r.id +FROM t_content_moderation_record r +JOIN t_announcement a ON r.content_type = 'ANNOUNCEMENT' AND r.business_id = a.id +WHERE r.provider = 'LEGACY_REVIEW' + AND COALESCE(TRIM(REPLACE(COALESCE(a.image_file_ids, ''), ' ', '')), '') <> '' + AND ( + TRIM(REPLACE(COALESCE(a.image_file_ids, ''), ' ', '')) NOT REGEXP '^[0-9]+(,[0-9]+)*$' + OR LENGTH(TRIM(REPLACE(COALESCE(a.image_file_ids, ''), ' ', ''))) + - LENGTH(REPLACE(TRIM(REPLACE(COALESCE(a.image_file_ids, ''), ' ', '')), ',', '')) + 1 > 1000 + ); + +INSERT IGNORE INTO tmp_content_moderation_invalid_legacy_record (record_id) +SELECT r.id +FROM t_content_moderation_record r +JOIN t_effect_diagram e ON r.content_type = 'EFFECT_DIAGRAM' AND r.business_id = e.id +WHERE r.provider = 'LEGACY_REVIEW' + AND COALESCE(TRIM(REPLACE(COALESCE(e.image_file_ids, ''), ' ', '')), '') <> '' + AND ( + TRIM(REPLACE(COALESCE(e.image_file_ids, ''), ' ', '')) NOT REGEXP '^[0-9]+(,[0-9]+)*$' + OR LENGTH(TRIM(REPLACE(COALESCE(e.image_file_ids, ''), ' ', ''))) + - LENGTH(REPLACE(TRIM(REPLACE(COALESCE(e.image_file_ids, ''), ' ', '')), ',', '')) + 1 > 1000 + ); + +INSERT IGNORE INTO tmp_content_moderation_invalid_legacy_record (record_id) +SELECT r.id +FROM t_content_moderation_record r +JOIN t_shop s ON r.content_type = 'SHOP' AND r.business_id = s.id +WHERE r.provider = 'LEGACY_REVIEW' + AND ( + (COALESCE(TRIM(s.cover_image_file_id), '') <> '' AND TRIM(s.cover_image_file_id) NOT REGEXP '^[0-9]+$') + OR (COALESCE(TRIM(s.theme_background_image_file_id), '') <> '' AND TRIM(s.theme_background_image_file_id) NOT REGEXP '^[0-9]+$') + OR (COALESCE(TRIM(REPLACE(COALESCE(s.image_file_ids, ''), ' ', '')), '') <> '' AND ( + TRIM(REPLACE(COALESCE(s.image_file_ids, ''), ' ', '')) NOT REGEXP '^[0-9]+(,[0-9]+)*$' + OR LENGTH(TRIM(REPLACE(COALESCE(s.image_file_ids, ''), ' ', ''))) + - LENGTH(REPLACE(TRIM(REPLACE(COALESCE(s.image_file_ids, ''), ' ', '')), ',', '')) + 1 > 1000 + )) + ); + +INSERT IGNORE INTO tmp_content_moderation_invalid_legacy_record (record_id) +SELECT r.id +FROM t_content_moderation_record r +JOIN t_system_message m ON r.content_type = 'SYSTEM_MESSAGE' AND r.business_id = m.id +LEFT JOIN t_object_storage_file f ON f.id = m.image_file_id AND f.status = 1 +WHERE r.provider = 'LEGACY_REVIEW' AND m.image_file_id IS NOT NULL AND f.id IS NULL; + +INSERT IGNORE INTO tmp_content_moderation_invalid_legacy_record (record_id) +SELECT DISTINCT r.id +FROM t_content_moderation_record r +JOIN t_content_moderation_image_task task ON task.record_id = r.id +LEFT JOIN t_object_storage_file f ON f.id = task.file_id AND f.status = 1 +WHERE r.provider = 'LEGACY_REVIEW' AND f.id IS NULL; + +UPDATE t_content_moderation_image_task task +JOIN tmp_content_moderation_invalid_legacy_record invalid ON invalid.record_id = task.record_id +SET task.status = 'REJECTED', + task.provider_task_id = NULL, + task.result_code = 'LEGACY_IMAGE_REFERENCE_INVALID', + task.reason = '历史图片引用无法安全核验,内容保持隐藏', + task.next_retry_at = NULL; + +UPDATE t_content_moderation_record r +JOIN tmp_content_moderation_invalid_legacy_record invalid ON invalid.record_id = r.id +SET r.status = 'REJECTED', + r.text_status = 'REJECTED', + r.result_code = 'LEGACY_IMAGE_REFERENCE_INVALID', + r.reason = '历史图片引用格式无效、超出迁移范围或文件不可用,内容保持隐藏', + r.payload_json = CASE r.content_type + WHEN 'SHOP' THEN JSON_SET(r.payload_json, '$.coverImageFileId', NULL, '$.imageFileIds', NULL, '$.themeBackgroundImageFileId', NULL) + WHEN 'USER_PROFILE' THEN JSON_SET(r.payload_json, '$.avatar', NULL, '$.wechatQrCode', NULL) + WHEN 'SYSTEM_MESSAGE' THEN JSON_SET(r.payload_json, '$.imageFileId', NULL) + ELSE JSON_SET(r.payload_json, '$.imageFileIds', NULL) + END; + +UPDATE t_product p +JOIN t_content_moderation_record r ON r.content_type = 'PRODUCT' AND r.business_id = p.id AND r.provider = 'LEGACY_REVIEW' +JOIN tmp_content_moderation_invalid_legacy_record invalid ON invalid.record_id = r.id +SET p.moderation_status = 'REJECTED', p.front_visible = 0; + +UPDATE t_comment c +JOIN t_content_moderation_record r ON r.content_type = 'COMMENT' AND r.business_id = c.id AND r.provider = 'LEGACY_REVIEW' +JOIN tmp_content_moderation_invalid_legacy_record invalid ON invalid.record_id = r.id +SET c.moderation_status = 'REJECTED'; + +UPDATE t_order_artist_review business_review +JOIN t_content_moderation_record r ON r.content_type = 'ORDER_ARTIST_REVIEW' AND r.business_id = business_review.id AND r.provider = 'LEGACY_REVIEW' +JOIN tmp_content_moderation_invalid_legacy_record invalid ON invalid.record_id = r.id +SET business_review.moderation_status = 'REJECTED'; + +UPDATE t_announcement a +JOIN t_content_moderation_record r ON r.content_type = 'ANNOUNCEMENT' AND r.business_id = a.id AND r.provider = 'LEGACY_REVIEW' +JOIN tmp_content_moderation_invalid_legacy_record invalid ON invalid.record_id = r.id +SET a.moderation_status = 'REJECTED', a.status = 0; + +UPDATE t_effect_diagram e +JOIN t_content_moderation_record r ON r.content_type = 'EFFECT_DIAGRAM' AND r.business_id = e.id AND r.provider = 'LEGACY_REVIEW' +JOIN tmp_content_moderation_invalid_legacy_record invalid ON invalid.record_id = r.id +SET e.moderation_status = 'REJECTED'; + +UPDATE t_shop s +JOIN t_content_moderation_record r ON r.content_type = 'SHOP' AND r.business_id = s.id AND r.provider = 'LEGACY_REVIEW' +JOIN tmp_content_moderation_invalid_legacy_record invalid ON invalid.record_id = r.id +SET s.moderation_status = 'REJECTED'; + +UPDATE t_system_message m +JOIN t_content_moderation_record r ON r.content_type = 'SYSTEM_MESSAGE' AND r.business_id = m.id AND r.provider = 'LEGACY_REVIEW' +JOIN tmp_content_moderation_invalid_legacy_record invalid ON invalid.record_id = r.id +SET m.moderation_status = 'REJECTED', m.status = 0; + +UPDATE t_user u +JOIN t_content_moderation_record r ON r.content_type = 'USER_PROFILE' AND r.business_id = u.id AND r.provider = 'LEGACY_REVIEW' +JOIN tmp_content_moderation_invalid_legacy_record invalid ON invalid.record_id = r.id +SET u.profile_moderation_status = 'REJECTED'; + +UPDATE t_content_moderation_record r +SET r.image_count = (SELECT COUNT(1) FROM t_content_moderation_image_task task WHERE task.record_id = r.id) +WHERE r.provider = 'LEGACY_REVIEW'; + +UPDATE t_legal_agreement SET status = 0, update_time = NOW() +WHERE agreement_type IN ('USER_TERMS', 'PRIVACY_POLICY') AND is_delete = 0 AND status = 1; + +INSERT INTO t_legal_agreement + (id, agreement_type, title, version, content, status, effective_time, create_time, update_time, is_delete) +VALUES + (313931273555140001, 'USER_TERMS', '用户协议', '2026.10.25', + '欢迎使用甲屿手纪 Salon 门店工作台。本服务供经门店授权的店长和员工管理门店日程、预约、员工和经营记录使用。登录前须阅读并明确同意本协议与隐私政策;不同意时不会交换微信登录凭证,也不能继续使用。微信 OpenID 用于识别账号,昵称和头像为可选资料,手机号绑定为可选,不绑定不影响基础工作台使用。头像、作品、评论、店铺展示资料、公告和人工发布的消息在公开前进行内容安全审核。DEV 使用本地模拟服务;其他环境未启用审核平台时保持隔离或进入人工复核;只有完成审核资质、回调域名、隐私指引和环境配置后启用微信审核服务时,必要文本、作者 OpenID 与图片短期授权地址才会提交给微信。拒绝、待复核、无法核验作者身份或服务异常的内容不会公开。客户业务资料及自动事务通知不纳入对外内容审核。页面中的预约金额仅为门店经营记录,不代表本平台已经收款;当前不提供充值、订阅或平台虚拟权益购买。请仅提交有权处理的业务信息并确保上传内容来源合法。可在账号设置申请注销;门店移交或归档后清理个人账号资料。必要订单、预约和经营记录按产品目标去身份化保留五年。', + 1, NOW(), NOW(), NOW(), 0), + (313931273555140002, 'PRIVACY_POLICY', '隐私政策', '2026.10.25', + '我们处理信息仅用于提供门店工作台:用户主动同意后使用微信 OpenID 识别账号;昵称和头像仅在用户主动补充或更新时处理;手机号仅在用户主动绑定或更换时获取,用于账号找回和必要业务联系,不用于营销。店长和员工可能录入客户姓名、可选联系电话、预约和订单信息,这些是门店业务资料,不是客户的小程序账号。头像、作品文字和图片、评论文字和图片、店铺展示资料、公告及人工发布的系统消息在对外展示前进行内容安全审核;开发环境使用本地模拟服务,其他环境以实际启用的审核 Provider 为准,未配置、待复核、拒绝、缺少作者 OpenID 或服务异常时内容保持隔离。仅在已完成微信资质、回调域名和隐私指引配置并于目标环境启用微信审核服务时,必要的待审文字、作者微信 OpenID 和图片短时授权地址会提交给微信内容安全接口。客户姓名和联系电话、预约与补单资料、备注、凭证、员工申请资料、内部审核说明和自动生成的事务通知不纳入对外审核。我们不主动采集设备标识、IMEI、MAC、定位或麦克风信息。手机号使用 AES-GCM 加密并以独立 HMAC 索引支持查重,常规页面、日志和导出脱敏。用户可在账号设置申请注销或解绑手机号;注销完成后目标十五个工作日内删除或匿名化个人资料,必要订单、预约和经营记录去除账号身份关联后按产品目标保留五年。隐私内容上线前由运营方核实实际服务商、微信后台指引和适用要求。', + 1, NOW(), NOW(), NOW(), 0); + +DROP TEMPORARY TABLE tmp_content_moderation_invalid_legacy_record; diff --git a/JC-Salon-Core/src/main/resources/db/migration/V4__Salon门店存量图片审核任务完整性校验_20261025.sql b/JC-Salon-Core/src/main/resources/db/migration/V4__Salon门店存量图片审核任务完整性校验_20261025.sql new file mode 100644 index 00000000..bb4bd81c --- /dev/null +++ b/JC-Salon-Core/src/main/resources/db/migration/V4__Salon门店存量图片审核任务完整性校验_20261025.sql @@ -0,0 +1,46 @@ +-- Legacy shop media can span three columns. V2 expands at most 1000 files per record; +-- reject snapshots whose source references do not have an exact matching task set. +UPDATE t_content_moderation_record r +JOIN t_shop s + ON r.content_type = 'SHOP' + AND r.business_id = s.id +LEFT JOIN ( + SELECT record_id, COUNT(1) AS task_count + FROM t_content_moderation_image_task + GROUP BY record_id +) image_tasks + ON image_tasks.record_id = r.id +SET r.status = 'REJECTED', + r.text_status = 'REJECTED', + r.result_code = 'LEGACY_IMAGE_TASKS_INCOMPLETE', + r.reason = '门店存量图片审核任务不完整,内容保持隐藏,请重新提交资料', + r.next_retry_at = NULL +WHERE r.provider = 'LEGACY_REVIEW' + AND r.status IN ('PENDING', 'RETRY') + AND ( + CASE WHEN NULLIF(TRIM(s.cover_image_file_id), '') IS NULL THEN 0 ELSE 1 END + + CASE WHEN NULLIF(TRIM(s.theme_background_image_file_id), '') IS NULL THEN 0 ELSE 1 END + + CASE + WHEN NULLIF(TRIM(REPLACE(COALESCE(s.image_file_ids, ''), ' ', '')), '') IS NULL THEN 0 + ELSE LENGTH(TRIM(REPLACE(COALESCE(s.image_file_ids, ''), ' ', ''))) + - LENGTH(REPLACE(TRIM(REPLACE(COALESCE(s.image_file_ids, ''), ' ', '')), ',', '')) + 1 + END + ) <> COALESCE(image_tasks.task_count, 0); + +UPDATE t_content_moderation_image_task task +JOIN t_content_moderation_record r ON r.id = task.record_id +SET task.status = 'REJECTED', + task.provider_task_id = NULL, + task.result_code = 'LEGACY_IMAGE_TASKS_INCOMPLETE', + task.reason = '门店存量图片审核任务不完整,内容保持隐藏', + task.next_retry_at = NULL +WHERE r.provider = 'LEGACY_REVIEW' + AND r.result_code = 'LEGACY_IMAGE_TASKS_INCOMPLETE'; + +UPDATE t_shop s +JOIN t_content_moderation_record r + ON r.content_type = 'SHOP' + AND r.business_id = s.id + AND r.provider = 'LEGACY_REVIEW' + AND r.result_code = 'LEGACY_IMAGE_TASKS_INCOMPLETE' +SET s.moderation_status = 'REJECTED'; diff --git a/JC-Salon-Core/src/main/resources/db/migration/V5__Salon美甲师资料审核状态_20261025.sql b/JC-Salon-Core/src/main/resources/db/migration/V5__Salon美甲师资料审核状态_20261025.sql new file mode 100644 index 00000000..d9b188fd --- /dev/null +++ b/JC-Salon-Core/src/main/resources/db/migration/V5__Salon美甲师资料审核状态_20261025.sql @@ -0,0 +1,63 @@ +ALTER TABLE t_nail_artist_info + ADD COLUMN moderation_status varchar(20) NOT NULL DEFAULT 'PENDING' + COMMENT '美甲师对外资料审核状态:PENDING/APPROVED/REJECTED/RETRY' AFTER portfolio; + +CREATE INDEX idx_nail_artist_moderation_public + ON t_nail_artist_info (moderation_status, status, is_delete); + +CREATE TEMPORARY TABLE tmp_legacy_artist_profile_moderation ( + artist_info_id bigint unsigned NOT NULL PRIMARY KEY, + user_id bigint unsigned NOT NULL, + has_public_content tinyint unsigned NOT NULL, + text_content mediumtext NULL, + identity varchar(50) NULL, + experience int NULL, + skills text NULL, + portfolio text NULL +); + +INSERT INTO tmp_legacy_artist_profile_moderation + (artist_info_id, user_id, has_public_content, text_content, identity, experience, skills, portfolio) +SELECT ai.id, + ai.user_id, + CASE WHEN NULLIF(TRIM(ai.identity), '') IS NOT NULL + OR COALESCE(ai.experience, 0) > 0 + OR NULLIF(TRIM(ai.skills), '') IS NOT NULL + OR NULLIF(TRIM(ai.portfolio), '') IS NOT NULL THEN 1 ELSE 0 END, + CONCAT_WS(CHAR(10), NULLIF(TRIM(ai.identity), ''), + CASE WHEN COALESCE(ai.experience, 0) > 0 THEN CONCAT(ai.experience, '年从业经验') END, + (SELECT GROUP_CONCAT(COALESCE(NULLIF(t.display_name, ''), t.tag_name) ORDER BY t.id SEPARATOR ',') + FROM t_tag t + WHERE t.is_delete = 0 AND t.front_visible = 1 + AND FIND_IN_SET(CAST(t.id AS CHAR), REPLACE(COALESCE(ai.skills, ''), ' ', '')) > 0)), + ai.identity, ai.experience, ai.skills, ai.portfolio +FROM t_nail_artist_info ai +JOIN t_user u ON u.id = ai.user_id +WHERE ai.is_delete = 0 AND u.is_delete = 0 AND u.status = 1 AND u.type IN (2, 3); + +UPDATE t_nail_artist_info ai +JOIN tmp_legacy_artist_profile_moderation legacy ON legacy.artist_info_id = ai.id +SET ai.moderation_status = CASE WHEN legacy.has_public_content = 1 THEN 'PENDING' ELSE 'APPROVED' END; + +INSERT INTO t_content_moderation_record + (id, content_type, business_id, user_id, version_no, image_count, text_status, text_content, status, + provider, result_code, reason, payload_json, attempt_count, create_time, update_time) +SELECT CAST(CONV(SUBSTR(SHA2(CONCAT('LEGACY:RECORD:NAIL_ARTIST_PROFILE:', legacy.artist_info_id), 256), 1, 15), 16, 10) AS UNSIGNED), + 'NAIL_ARTIST_PROFILE', legacy.artist_info_id, NULL, 1, 0, + CASE WHEN legacy.has_public_content = 1 THEN 'PENDING' ELSE 'APPROVED' END, + legacy.text_content, + CASE WHEN legacy.has_public_content = 1 THEN 'PENDING' ELSE 'APPROVED' END, + CASE WHEN legacy.has_public_content = 1 THEN 'LEGACY_REVIEW' ELSE 'LEGACY_SYSTEM' END, + CASE WHEN legacy.has_public_content = 1 THEN 'LEGACY_PUBLIC_CONTENT' ELSE 'EMPTY_PROFILE_BASELINE' END, + CASE WHEN legacy.has_public_content = 1 THEN '存量美甲师公开资料等待审核' ELSE '系统默认美甲师资料无需审核' END, + JSON_OBJECT('identity', legacy.identity, 'experience', legacy.experience, + 'skills', legacy.skills, 'portfolio', legacy.portfolio), + 0, NOW(), NOW() +FROM tmp_legacy_artist_profile_moderation legacy +WHERE NOT EXISTS ( + SELECT 1 FROM t_content_moderation_record current_record + WHERE current_record.content_type = 'NAIL_ARTIST_PROFILE' + AND current_record.business_id = legacy.artist_info_id +); + +DROP TEMPORARY TABLE tmp_legacy_artist_profile_moderation; diff --git a/JC-Salon-Frontend/public/legal/privacy-policy.html b/JC-Salon-Frontend/public/legal/privacy-policy.html index 7a47fa3e..73b53a31 100644 --- a/JC-Salon-Frontend/public/legal/privacy-policy.html +++ b/JC-Salon-Frontend/public/legal/privacy-policy.html @@ -28,7 +28,8 @@

四、第三方服务

服务依赖微信小程序登录与用户主动触发的微信能力;验证码由部署环境启用的短信服务商发送;通知由配置的消息通道处理;头像、作品等文件存储于部署环境配置的对象存储服务。运营方上线前应在微信后台列明实际服务商,并确认其处理范围和协议。

五、内容审核

-

当前代码仅使用本地模拟审核 Provider,不调用微信内容安全接口。模拟结果只用于开发验证,不代表真实审核能力。接入正式审核前将完成单独评估、隐私指引更新和数据流说明。

+

头像、作品文字和图片、评论文字和图片、店铺展示资料、公告及人工发布的系统消息在面向用户或门店成员展示前进行内容安全审核。开发环境使用本地模拟服务;配置启用微信审核服务的环境会将必要的文字、微信 OpenID 和图片的短时授权地址提交给微信内容安全接口,图片审核结果通过加密回调更新。审核未通过、待复核、超时或服务故障时内容保持隔离,不会公开。

+

客户姓名和联系电话、预约及补单资料、备注、凭证、员工申请资料、内部审核说明和自动生成的事务通知不纳入对外内容审核。审核记录、任务状态和人工复核操作会按安全审计要求保存。

六、保留、注销和解绑

用户可在小程序“我的-账号设置”申请注销或解绑手机号。解绑通过当前号码验证码核验后立即清除手机号密文和索引。注销申请经管理员完成门店移交或归档后撤销会话,并在目标15个工作日内删除或匿名化 OpenID、昵称、头像、手机号等个人资料。必要订单、预约和经营记录在去除账号身份关联后按产品目标保留五年;该期限及范围由运营方上线前核实。

七、政策更新与联系

diff --git a/JC-Salon-Frontend/public/legal/user-terms.html b/JC-Salon-Frontend/public/legal/user-terms.html index 389f4763..e265071b 100644 --- a/JC-Salon-Frontend/public/legal/user-terms.html +++ b/JC-Salon-Frontend/public/legal/user-terms.html @@ -19,7 +19,7 @@

微信 OpenID 用于关联工作台账号。账号仅供本人使用,不得转借。昵称和头像可选;手机号可选绑定,不绑定不影响基础功能。离职或不再获授权时,门店管理员可以调整账号权限。

三、业务资料与内容

使用者仅可录入履行门店业务所需且有权处理的客户、预约、作品和员工资料,并应确保上传文字和图片来源合法,不得上传违法、侵权、欺诈或侵害他人权益的内容。用户可随时更正自己提交的非业务资料。

-

头像、作品、评论等内容当前使用本地模拟审核流程,仅用于开发验证,不代表已接入微信内容安全审核。正式上线前,平台将依据实际审核服务更新隐私指引和本协议说明。

+

头像、作品、评论、店铺展示资料、公告和人工发布的消息会在公开前经过内容安全审核。开发环境使用本地模拟服务进行验证;正式环境启用微信内容安全服务后,文字和图片会按审核平台要求处理,未通过、待复核或服务异常的内容不会公开。

四、业务记录与金额

订单及预约页面展示的金额用于门店经营记录,不构成平台收款、支付或退款承诺。当前平台不提供充值或订阅交易。不得将工作台用于未经授权的资金收取或虚拟权益交易。

五、账号注销

diff --git a/JC-Salon-Frontend/src/api/admin.ts b/JC-Salon-Frontend/src/api/admin.ts index 6c53d1a6..513a1297 100644 --- a/JC-Salon-Frontend/src/api/admin.ts +++ b/JC-Salon-Frontend/src/api/admin.ts @@ -1560,6 +1560,7 @@ export interface NailArtistInfoVO { rating: number status: number portfolio: string + moderationStatus?: string nickname: string shopId: IdType shopName: string @@ -1694,6 +1695,7 @@ export interface AnnouncementVO { id: IdType title: string content: string + imageFileIds?: IdType[] publisherId?: IdType publisherName?: string publisherType?: number @@ -1713,6 +1715,7 @@ export interface AnnouncementVO { export interface AnnouncementCreateRequest { title: string content: string + imageFileIds?: string targetType: string shopIds?: IdType[] userIds?: IdType[] @@ -2025,12 +2028,12 @@ export interface ContentModerationRecordVO { id: IdType contentType: string businessId?: IdType - userId?: IdType + authorName?: string status: string - provider: string resultCode?: string reason?: string - payloadJson?: string + textPreview?: string + images?: Array<{ fileId: IdType; url?: string; status?: string }> attemptCount?: number createTime?: string } diff --git a/JC-Salon-Frontend/src/views/admin/AnnouncementsView.vue b/JC-Salon-Frontend/src/views/admin/AnnouncementsView.vue index 45cf77d4..125b4484 100644 --- a/JC-Salon-Frontend/src/views/admin/AnnouncementsView.vue +++ b/JC-Salon-Frontend/src/views/admin/AnnouncementsView.vue @@ -40,6 +40,15 @@ + + + 添加图片 + + + 图片 {{ fileId }} + +
图片会和标题、正文一起进入内容审核,审核通过后才会对外展示。
+
@@ -68,7 +77,7 @@ import { message, Modal } from 'ant-design-vue' * Purpose: AnnouncementVO supports AnnouncementsView.vue by holding or executing the announcement vo page or API role. * Usage: import, call, read, or update this type from the owning page/module while preserving the surrounding loading and permission flow. */ -import { adminAnnouncementApi, type AnnouncementVO, type MessageTargetOptionsVO } from '@/api/admin' +import { adminAnnouncementApi, adminFileApi, type AnnouncementVO, type MessageTargetOptionsVO } from '@/api/admin' import { extractRichText, renderRichContent } from '@/utils/rich-content' /** loading is a reactive state variable used by the template and event handlers. */ @@ -91,7 +100,8 @@ const options = ref({ shops: [], users: [] }) * Purpose: form supports AnnouncementsView.vue by holding or executing the form page or API role. * Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow. */ -const form = reactive({ title: '', content: '', targetType: 'PLATFORM_ALL', shopIds: [], userIds: [], sortOrder: 0 }) +const form = reactive({ title: '', content: '', imageFileIds: [], targetType: 'PLATFORM_ALL', shopIds: [], userIds: [], sortOrder: 0 }) +const imageUploading = ref(false) /** * Purpose: columns supports AnnouncementsView.vue by holding or executing the columns page or API role. @@ -143,10 +153,24 @@ const load = async () => { /** openCreate is a local helper used by this page script. */ const openCreate = () => { - Object.assign(form, { title: '', content: '', targetType: 'PLATFORM_ALL', shopIds: [], userIds: [], sortOrder: 0 }) + Object.assign(form, { title: '', content: '', imageFileIds: [], targetType: 'PLATFORM_ALL', shopIds: [], userIds: [], sortOrder: 0 }) formOpen.value = true } +const uploadAnnouncementImage = async (file: File) => { + imageUploading.value = true + try { + const uploaded = await adminFileApi.uploadFile(file) + if (uploaded?.id) form.imageFileIds.push(uploaded.id) + message.success('图片已上传,提交后会进入审核') + } catch (error) { + message.error(error instanceof Error ? error.message : '图片上传失败') + } finally { + imageUploading.value = false + } + return false +} + /** submit is an async page action. Trigger it from the template or lifecycle hook, then await the result. */ const submit = async () => { if (!form.title || !form.content) { @@ -155,7 +179,7 @@ const submit = async () => { } saving.value = true try { - await adminAnnouncementApi.createAnnouncement(form) + await adminAnnouncementApi.createAnnouncement({ ...form, imageFileIds: form.imageFileIds.join(',') }) message.success('公告已发布') formOpen.value = false await load() @@ -188,6 +212,8 @@ onMounted(load)