diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/config/DialProperties.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/config/DialProperties.java new file mode 100644 index 00000000..03d6ad88 --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/config/DialProperties.java @@ -0,0 +1,19 @@ +package com.xiaowang.jayucloud.artlist.core.config; + +import lombok.Data; +import org.springframework.boot.context.properties.ConfigurationProperties; +import org.springframework.context.annotation.Configuration; + +/** + * 拨号取号配置。 + */ +@Data +@Configuration +@ConfigurationProperties(prefix = "jayucloud-artlist.dial") +public class DialProperties { + + /** + * 拨号提供方:direct(直拨真实号码)或 privacy-number(隐私号,未对接时明确报错)。 + */ + private String provider = "direct"; +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/config/MyMetaObjectHandler.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/config/MyMetaObjectHandler.java index b0745ddf..4e65a0e4 100644 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/config/MyMetaObjectHandler.java +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/config/MyMetaObjectHandler.java @@ -1,6 +1,7 @@ package com.xiaowang.jayucloud.artlist.core.config; import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler; +import com.xiaowang.jayucloud.artlist.core.support.privacy.PhoneCrypto; import lombok.extern.slf4j.Slf4j; import org.apache.ibatis.reflection.MetaObject; import org.springframework.stereotype.Component; @@ -27,6 +28,7 @@ public class MyMetaObjectHandler implements MetaObjectHandler { log.info("start insert fill ...."); this.strictInsertFill(metaObject, "createTime", LocalDateTime.class, LocalDateTime.now()); this.strictInsertFill(metaObject, "updateTime", LocalDateTime.class, LocalDateTime.now()); + fillPhoneHashes(metaObject); } @Override @@ -37,5 +39,31 @@ public class MyMetaObjectHandler implements MetaObjectHandler { public void updateFill(MetaObject metaObject) { log.info("start update fill ...."); this.strictUpdateFill(metaObject, "updateTime", LocalDateTime.class, LocalDateTime.now()); + fillPhoneHashes(metaObject); + } + + /** + * 实体写入时按明文手机号刷新哈希列。 + * 注意:QueryWrapper/UpdateWrapper 的 set 不会经过这里,删除等场景需显式置空哈希。 + */ + private void fillPhoneHashes(MetaObject metaObject) { + if (metaObject.hasSetter("accountHash")) { + Object account = getFieldValByName("account", metaObject); + if (account != null) { + setFieldValByName("accountHash", PhoneCrypto.current().index(String.valueOf(account)), metaObject); + } + } + if (metaObject.hasSetter("phoneHash")) { + Object phone = getFieldValByName("phone", metaObject); + if (phone != null) { + setFieldValByName("phoneHash", PhoneCrypto.current().index(String.valueOf(phone)), metaObject); + } + } + if (metaObject.hasSetter("contactPhoneHash")) { + Object contactPhone = getFieldValByName("contactPhone", metaObject); + if (contactPhone != null) { + setFieldValByName("contactPhoneHash", PhoneCrypto.current().index(String.valueOf(contactPhone)), metaObject); + } + } } } diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/config/PhoneCryptoProperties.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/config/PhoneCryptoProperties.java new file mode 100644 index 00000000..bcb36c6a --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/config/PhoneCryptoProperties.java @@ -0,0 +1,17 @@ +package com.xiaowang.jayucloud.artlist.core.config; + +import lombok.Data; +import org.springframework.boot.context.properties.ConfigurationProperties; +import org.springframework.context.annotation.Configuration; + +/** + * 手机号加密配置。密钥口径与 JC-Salon-Core 完全一致,保证两条业务线的 phone_hash 可比对。 + * 配置位置:Nacos jayucloud-artlist / DEFAULT_GROUP / secret.yaml。 + */ +@Data +@Configuration +@ConfigurationProperties(prefix = "jayucloud-artlist.privacy.phone-crypto") +public class PhoneCryptoProperties { + private String encryptionKey; + private String indexKey; +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/config/RateLimitProperties.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/config/RateLimitProperties.java index 1eaaef16..ca29dc27 100644 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/config/RateLimitProperties.java +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/config/RateLimitProperties.java @@ -28,6 +28,16 @@ public class RateLimitProperties { private LimitRule orderCreate = new LimitRule(10, 60); + /** + * 联系方式查询:按登录用户维度。 + */ + private LimitRule contactInfoRead = new LimitRule(30, 60); + + /** + * 单次拨号取号:按登录用户维度。 + */ + private LimitRule contactDial = new LimitRule(10, 60); + @Data /** * Purpose: LimitRule supports RateLimitProperties.java by holding or executing the limit rule business role. diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/auth/service/impl/VerificationCodeServiceImpl.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/auth/service/impl/VerificationCodeServiceImpl.java index 9a95ec9f..dff3dffe 100644 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/auth/service/impl/VerificationCodeServiceImpl.java +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/auth/service/impl/VerificationCodeServiceImpl.java @@ -2,6 +2,7 @@ package com.xiaowang.jayucloud.artlist.core.modules.auth.service.impl; import com.xiaowang.jayucloud.artlist.core.modules.integration.service.MessageHubClientService; import com.xiaowang.jayucloud.artlist.core.modules.auth.service.VerificationCodeService; +import com.xiaowang.jayucloud.artlist.core.support.privacy.PhoneCrypto; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.springframework.data.redis.core.StringRedisTemplate; @@ -51,6 +52,7 @@ public class VerificationCodeServiceImpl implements VerificationCodeService { * Variable `messageHubClientService`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. */ private final MessageHubClientService messageHubClientService; + private final PhoneCrypto phoneCrypto; @Override /** @@ -94,15 +96,16 @@ public class VerificationCodeServiceImpl implements VerificationCodeService { public void sendVerificationCode(String phone, String sceneCode) { String code = generateVerificationCode(); - String codeKey = CODE_PREFIX + phone; - String sendTimeKey = SEND_TIME_PREFIX + phone; + String phoneKey = phoneCrypto.index(phone); + String codeKey = CODE_PREFIX + phoneKey; + String sendTimeKey = SEND_TIME_PREFIX + phoneKey; redisTemplate.opsForValue().set(codeKey, code, Duration.ofMinutes(CODE_EXPIRE_MINUTES)); redisTemplate.opsForValue().set(sendTimeKey, String.valueOf(System.currentTimeMillis()), Duration.ofSeconds(RESEND_INTERVAL_SECONDS)); messageHubClientService.sendSmsVerificationCode(sceneCode, phone, code); - log.info("验证码已发送,手机号: {}, sceneCode: {}", phone, sceneCode); + log.info("验证码已发送,手机号: {}, sceneCode: {}", phoneCrypto.mask(phone), sceneCode); } @Override @@ -114,21 +117,21 @@ public class VerificationCodeServiceImpl implements VerificationCodeService { * @return boolean result consumed by the caller or returned to the frontend */ public boolean verifyCode(String phone, String code) { - String codeKey = CODE_PREFIX + phone; + String codeKey = CODE_PREFIX + phoneCrypto.index(phone); String storedCode = redisTemplate.opsForValue().get(codeKey); if (storedCode == null) { - log.warn("验证码不存在或已过期,手机号: {}", phone); + log.warn("验证码不存在或已过期,手机号: {}", phoneCrypto.mask(phone)); return false; } if (!storedCode.equals(code)) { - log.warn("验证码错误,手机号: {}", phone); + log.warn("验证码错误,手机号: {}", phoneCrypto.mask(phone)); return false; } redisTemplate.delete(codeKey); - log.info("验证码验证成功,手机号: {}", phone); + log.info("验证码验证成功,手机号: {}", phoneCrypto.mask(phone)); return true; } @@ -140,7 +143,7 @@ public class VerificationCodeServiceImpl implements VerificationCodeService { * @return boolean result consumed by the caller or returned to the frontend */ public boolean canResend(String phone) { - String sendTimeKey = SEND_TIME_PREFIX + phone; + String sendTimeKey = SEND_TIME_PREFIX + phoneCrypto.index(phone); String sendTime = redisTemplate.opsForValue().get(sendTimeKey); return sendTime == null; } diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/content/service/impl/CommentServiceImpl.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/content/service/impl/CommentServiceImpl.java index ed42aed6..8f17d3c3 100644 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/content/service/impl/CommentServiceImpl.java +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/content/service/impl/CommentServiceImpl.java @@ -1,4 +1,4 @@ -package com.xiaowang.jayucloud.artlist.core.modules.content.service.impl; +import com.xiaowang.jayucloud.artlist.core.support.privacy.SensitiveFieldPolicy; import com.baomidou.mybatisplus.core.toolkit.Wrappers; import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; @@ -489,7 +489,8 @@ public class CommentServiceImpl extends ServiceImpl im private void fillDisplayFields(CommentVO commentVO, CommentDO commentDO) { UserDO user = commentDO.getUserId() == null ? null : userMapper.selectById(commentDO.getUserId()); if (user != null) { - commentVO.setUserNickname(StringUtils.hasText(user.getNickname()) ? user.getNickname() : user.getAccount()); + commentVO.setUserNickname(StringUtils.hasText(user.getNickname()) ? user.getNickname() + : SensitiveFieldPolicy.account(user.getAccount(), SensitiveFieldPolicy.Scenario.THIRD_PARTY)); } ShopDO shop = commentDO.getShopId() == null ? null : shopMapper.selectById(commentDO.getShopId()); if (shop != null) { diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/integration/service/impl/MessageHubClientServiceImpl.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/integration/service/impl/MessageHubClientServiceImpl.java index 9e4ab43d..14c7467c 100644 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/integration/service/impl/MessageHubClientServiceImpl.java +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/integration/service/impl/MessageHubClientServiceImpl.java @@ -6,6 +6,7 @@ import com.xiaowang.jayucloud.artlist.core.modules.integration.entity.MessageHub import com.xiaowang.jayucloud.artlist.core.modules.integration.service.MessageHubClientService; import com.xiaowang.jayucloud.artlist.core.modules.integration.service.MessageHubPushConfigService; import com.xiaowang.jayucloud.artlist.core.support.id.TimeOrderedSnowflakeIdGenerator; +import com.xiaowang.jayucloud.artlist.core.support.privacy.PhoneCrypto; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.springframework.amqp.core.Message; @@ -51,6 +52,7 @@ public class MessageHubClientServiceImpl implements MessageHubClientService { * 平台品牌文案配置。 */ private final BrandProperties brandProperties; + private final PhoneCrypto phoneCrypto; @Value("${messagehub.client.sms-queue:smsQueue}") /** @@ -123,7 +125,7 @@ public class MessageHubClientServiceImpl implements MessageHubClientService { String queueName = config == null ? smsQueue : config.getQueueName(); rabbitTemplate.convertAndSend(queueName, message); log.info("短信验证码消息已投递到 MessageHub,sceneCode: {}, phone: {}, queue: {}, sourceSystem: {}, templateCode: {}", - sceneCode, phone, queueName, messageBody.get("sourceSystem"), messageBody.get("templateCode")); + sceneCode, phoneCrypto.mask(phone), queueName, messageBody.get("sourceSystem"), messageBody.get("templateCode")); } catch (Exception exception) { log.error("发送短信验证码失败", exception); throw new RuntimeException("发送短信验证码失败: " + exception.getMessage(), exception); diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/integration/service/impl/WechatMiniAuthServiceImpl.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/integration/service/impl/WechatMiniAuthServiceImpl.java index e854db38..3ecaf046 100644 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/integration/service/impl/WechatMiniAuthServiceImpl.java +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/integration/service/impl/WechatMiniAuthServiceImpl.java @@ -24,6 +24,7 @@ import com.xiaowang.jayucloud.artlist.core.modules.integration.vo.WechatMiniLogi import lombok.Data; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; +import com.xiaowang.jayucloud.artlist.core.support.privacy.PhoneCrypto; import org.springframework.data.redis.core.StringRedisTemplate; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; @@ -87,6 +88,7 @@ public class WechatMiniAuthServiceImpl implements WechatMiniAuthService { * Variable `snowflakeIdGenerator`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. */ private final TimeOrderedSnowflakeIdGenerator snowflakeIdGenerator; + private final PhoneCrypto phoneCrypto; @Override /** @@ -350,7 +352,7 @@ public class WechatMiniAuthServiceImpl implements WechatMiniAuthService { } return userMapper.selectOne( new LambdaQueryWrapper() - .eq(UserDO::getPhone, phone) + .eq(UserDO::getPhoneHash, phoneCrypto.index(phone)) .eq(UserDO::getIsDelete, 0) .last("limit 1") ); diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/message/service/impl/AnnouncementServiceImpl.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/message/service/impl/AnnouncementServiceImpl.java index a994fa33..a692e919 100644 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/message/service/impl/AnnouncementServiceImpl.java +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/message/service/impl/AnnouncementServiceImpl.java @@ -1,4 +1,4 @@ -package com.xiaowang.jayucloud.artlist.core.modules.message.service.impl; +import com.xiaowang.jayucloud.artlist.core.support.privacy.SensitiveFieldPolicy; import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; @@ -212,7 +212,7 @@ public class AnnouncementServiceImpl extends ServiceImpl result consumed by the caller or returned to the frontend */ public Result shopManager(HttpServletRequest request, @PathVariable Long shopId) { - Long userId = (Long) request.getAttribute("userId"); + Long userId = requireLogin(request); + requestThrottleService.checkContactInfoRead(request, userId); return Result.success(contactInfoService.getShopManagerContact(userId, shopId)); } @@ -44,7 +64,8 @@ public class ContactInfoController { * @return Result result consumed by the caller or returned to the frontend */ public Result productArtist(HttpServletRequest request, @PathVariable Long productId, @PathVariable Long artistId) { - Long userId = (Long) request.getAttribute("userId"); + Long userId = requireLogin(request); + requestThrottleService.checkContactInfoRead(request, userId); return Result.success(contactInfoService.getProductArtistContact(userId, productId, artistId)); } @@ -54,7 +75,8 @@ public class ContactInfoController { * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. */ public Result orderArtist(HttpServletRequest request, @PathVariable Long orderId, @RequestParam(required = false) Long artistId) { - Long userId = (Long) request.getAttribute("userId"); + Long userId = requireLogin(request); + requestThrottleService.checkContactInfoRead(request, userId); return Result.success(contactInfoService.getOrderArtistContact(userId, orderId, artistId)); } @@ -62,9 +84,50 @@ public class ContactInfoController { /** * Run business method `platform`. * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. + * @param request parameter `request` supplied by the caller * @return Result result consumed by the caller or returned to the frontend */ - public Result platform() { + public Result platform(HttpServletRequest request) { + Long userId = requireLogin(request); + requestThrottleService.checkContactInfoRead(request, userId); return Result.success(contactInfoService.getPlatformContact()); } + + @PostMapping("/dial") + /** + * 单次拨号取号:按场景校验可见范围后返回一次可用号码,号码不落库、不进日志、不进缓存。 + */ + public Result dial(HttpServletRequest request, @RequestBody DialRequestDTO dialRequestDTO) { + Long userId = requireLogin(request); + String account = (String) request.getAttribute("account"); + requestThrottleService.checkContactDial(request, userId); + String action = "CONTACT_DIAL_" + safeSceneCode(dialRequestDTO); + try { + DialResponseVO response = contactDialService.dial(userId, dialRequestDTO); + securityAuditLogService.record(userId, account, action, "SUCCESS", null, request); + return Result.success(response); + } catch (BusinessException exception) { + securityAuditLogService.record(userId, account, action, "FAIL", "code=" + exception.getCode(), request); + throw exception; + } + } + + private Long requireLogin(HttpServletRequest request) { + Long userId = (Long) request.getAttribute("userId"); + if (userId == null) { + throw new BusinessException(403, "请先登录后再获取联系方式"); + } + return userId; + } + + private String safeSceneCode(DialRequestDTO dialRequestDTO) { + if (dialRequestDTO == null || dialRequestDTO.getScene() == null) { + return "UNKNOWN"; + } + try { + return DialScene.fromCode(dialRequestDTO.getScene()).name(); + } catch (BusinessException exception) { + return "UNKNOWN"; + } + } } diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/shop/dto/DialRequestDTO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/shop/dto/DialRequestDTO.java new file mode 100644 index 00000000..03a8c533 --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/shop/dto/DialRequestDTO.java @@ -0,0 +1,25 @@ +package com.xiaowang.jayucloud.artlist.core.modules.shop.dto; + +import lombok.Data; + +/** + * 单次拨号取号请求。 + */ +@Data +public class DialRequestDTO { + + /** + * 拨号场景:SHOP_MANAGER / ORDER_ARTIST / PRODUCT_ARTIST / PLATFORM。 + */ + private String scene; + + /** + * 目标标识:SHOP_MANAGER=店铺ID,ORDER_ARTIST=订单ID,PRODUCT_ARTIST=作品ID,PLATFORM 忽略。 + */ + private Long targetId; + + /** + * 可选的美甲师ID,仅 PRODUCT_ARTIST 场景使用;不传时取作品可预约美甲师的第一位。 + */ + private Long artistId; +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/shop/service/ContactDialService.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/shop/service/ContactDialService.java new file mode 100644 index 00000000..33cb95f2 --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/shop/service/ContactDialService.java @@ -0,0 +1,15 @@ +package com.xiaowang.jayucloud.artlist.core.modules.shop.service; + +import com.xiaowang.jayucloud.artlist.core.modules.shop.dto.DialRequestDTO; +import com.xiaowang.jayucloud.artlist.core.modules.shop.vo.DialResponseVO; + +/** + * 单次拨号取号服务:按场景校验可见范围后返回一次可用的拨号号码。 + */ +public interface ContactDialService { + + /** + * 按场景解析并返回拨号号码;号码不落库、不进日志、不进缓存。 + */ + DialResponseVO dial(Long userId, DialRequestDTO request); +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/shop/service/impl/ContactDialServiceImpl.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/shop/service/impl/ContactDialServiceImpl.java new file mode 100644 index 00000000..91802edd --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/shop/service/impl/ContactDialServiceImpl.java @@ -0,0 +1,200 @@ +package com.xiaowang.jayucloud.artlist.core.modules.shop.service.impl; + +import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; +import com.xiaowang.jayucloud.artlist.core.common.BusinessException; +import com.xiaowang.jayucloud.artlist.core.config.DialProperties; +import com.xiaowang.jayucloud.artlist.core.modules.order.entity.OrderDO; +import com.xiaowang.jayucloud.artlist.core.modules.order.entity.OrderItemDO; +import com.xiaowang.jayucloud.artlist.core.modules.order.mapper.OrderItemMapper; +import com.xiaowang.jayucloud.artlist.core.modules.order.mapper.OrderMapper; +import com.xiaowang.jayucloud.artlist.core.modules.product.entity.ProductDO; +import com.xiaowang.jayucloud.artlist.core.modules.product.mapper.ProductMapper; +import com.xiaowang.jayucloud.artlist.core.modules.shop.dto.DialRequestDTO; +import com.xiaowang.jayucloud.artlist.core.modules.shop.entity.ShopDO; +import com.xiaowang.jayucloud.artlist.core.modules.shop.mapper.ShopMapper; +import com.xiaowang.jayucloud.artlist.core.modules.shop.service.ContactDialService; +import com.xiaowang.jayucloud.artlist.core.modules.shop.support.UserShopBindingSupport; +import com.xiaowang.jayucloud.artlist.core.modules.shop.support.dial.DialScene; +import com.xiaowang.jayucloud.artlist.core.modules.shop.support.dial.DialTargetProvider; +import com.xiaowang.jayucloud.artlist.core.modules.shop.vo.DialResponseVO; +import com.xiaowang.jayucloud.artlist.core.modules.user.entity.UserDO; +import com.xiaowang.jayucloud.artlist.core.modules.user.mapper.UserMapper; +import lombok.RequiredArgsConstructor; +import org.springframework.stereotype.Service; +import org.springframework.util.StringUtils; + +import java.util.Arrays; +import java.util.List; + +@Service +@RequiredArgsConstructor +/** + * 单次拨号取号实现:先按场景校验可见范围,再由配置的提供方生成拨号号码。 + */ +public class ContactDialServiceImpl implements ContactDialService { + + private static final int FORBIDDEN = 403; + + private final UserMapper userMapper; + private final ShopMapper shopMapper; + private final ProductMapper productMapper; + private final OrderMapper orderMapper; + private final OrderItemMapper orderItemMapper; + private final UserShopBindingSupport userShopBindingSupport; + private final DialProperties dialProperties; + private final List dialTargetProviders; + + @Override + public DialResponseVO dial(Long userId, DialRequestDTO request) { + if (userId == null) { + throw new BusinessException(FORBIDDEN, "请先登录后再获取联系方式"); + } + DialScene scene = DialScene.fromCode(request == null ? null : request.getScene()); + UserDO caller = userMapper.selectById(userId); + if (caller == null || Integer.valueOf(1).equals(caller.getIsDelete())) { + throw new BusinessException(FORBIDDEN, "用户不存在或已失效"); + } + + String rawPhone = switch (scene) { + case SHOP_MANAGER -> resolveShopManagerPhone(caller, request.getTargetId()); + case ORDER_ARTIST -> resolveOrderArtistPhone(caller, request.getTargetId()); + case PRODUCT_ARTIST -> resolveProductArtistPhone(request.getTargetId(), request.getArtistId()); + case PLATFORM -> resolvePlatformPhone(); + }; + if (!StringUtils.hasText(rawPhone)) { + throw new BusinessException(404, "该联系人暂未配置可拨打电话"); + } + + DialTargetProvider provider = selectProvider(); + return provider.resolve(rawPhone); + } + + private String resolveShopManagerPhone(UserDO caller, Long shopId) { + if (shopId == null || shopId <= 0) { + throw new BusinessException(400, "店铺ID不能为空"); + } + ensureShopVisible(caller, shopId); + UserDO manager = userMapper.selectOne(new LambdaQueryWrapper() + .eq(UserDO::getType, 2) + .eq(UserDO::getShopId, shopId) + .eq(UserDO::getIsDelete, 0) + .eq(UserDO::getStatus, 1) + .last("LIMIT 1")); + return resolveContactPhone(manager); + } + + private String resolveOrderArtistPhone(UserDO caller, Long orderId) { + if (orderId == null || orderId <= 0) { + throw new BusinessException(400, "订单ID不能为空"); + } + OrderDO order = orderMapper.selectById(orderId); + if (order == null + || Integer.valueOf(1).equals(order.getIsDelete()) + || !caller.getId().equals(order.getUserId())) { + throw new BusinessException(FORBIDDEN, "订单不存在或无权查看"); + } + OrderItemDO item = orderItemMapper.selectList(new LambdaQueryWrapper() + .eq(OrderItemDO::getOrderId, orderId) + .eq(OrderItemDO::getIsDelete, 0) + .isNotNull(OrderItemDO::getArtistId) + .last("LIMIT 1")) + .stream() + .findFirst() + .orElseThrow(() -> new BusinessException(404, "订单暂无可联系美甲师")); + return resolveContactPhone(userMapper.selectById(item.getArtistId())); + } + + private String resolveProductArtistPhone(Long productId, Long artistId) { + if (productId == null || productId <= 0) { + throw new BusinessException(400, "作品ID不能为空"); + } + ProductDO product = productMapper.selectById(productId); + if (product == null || Integer.valueOf(1).equals(product.getIsDelete())) { + throw new BusinessException(FORBIDDEN, "作品不存在或不可见"); + } + Long targetArtistId = artistId; + if (targetArtistId == null || targetArtistId <= 0) { + targetArtistId = firstBookableArtistId(product.getBookableArtists()); + } + if (targetArtistId == null) { + throw new BusinessException(404, "该作品暂未配置可联系美甲师"); + } + ensureArtistAllowed(product.getBookableArtists(), targetArtistId); + return resolveContactPhone(userMapper.selectById(targetArtistId)); + } + + private String resolvePlatformPhone() { + UserDO admin = userMapper.selectOne(new LambdaQueryWrapper() + .eq(UserDO::getType, 4) + .eq(UserDO::getIsDelete, 0) + .eq(UserDO::getStatus, 1) + .isNotNull(UserDO::getPhone) + .last("LIMIT 1")); + return resolveContactPhone(admin); + } + + /** + * 校验当前用户是否可拨打该店铺店长:平台管理员、本店用户、有绑定关系或门店公开可见。 + */ + private void ensureShopVisible(UserDO caller, Long shopId) { + if (Integer.valueOf(4).equals(caller.getType())) { + return; + } + if (shopId.equals(caller.getShopId()) || userShopBindingSupport.hasActiveBinding(caller.getId(), shopId)) { + return; + } + ShopDO shop = shopMapper.selectById(shopId); + if (shop == null || Integer.valueOf(1).equals(shop.getIsDelete())) { + throw new BusinessException(FORBIDDEN, "店铺不存在或不可见"); + } + } + + private void ensureArtistAllowed(String rawBookableArtists, Long artistId) { + if (!StringUtils.hasText(rawBookableArtists)) { + return; + } + boolean allowed = Arrays.stream(rawBookableArtists.split(",")) + .map(String::trim) + .filter(StringUtils::hasText) + .anyMatch(id -> id.equals(String.valueOf(artistId))); + if (!allowed) { + throw new BusinessException(FORBIDDEN, "该美甲师不可联系当前作品"); + } + } + + private Long firstBookableArtistId(String rawBookableArtists) { + if (!StringUtils.hasText(rawBookableArtists)) { + return null; + } + return Arrays.stream(rawBookableArtists.split(",")) + .map(String::trim) + .filter(StringUtils::hasText) + .map(value -> { + try { + return Long.valueOf(value); + } catch (NumberFormatException exception) { + return null; + } + }) + .filter(java.util.Objects::nonNull) + .findFirst() + .orElse(null); + } + + private String resolveContactPhone(UserDO contact) { + if (contact == null || Integer.valueOf(1).equals(contact.getIsDelete())) { + return null; + } + return StringUtils.hasText(contact.getContactPhone()) ? contact.getContactPhone() : contact.getPhone(); + } + + private DialTargetProvider selectProvider() { + String configured = StringUtils.hasText(dialProperties.getProvider()) + ? dialProperties.getProvider().trim() + : "direct"; + return dialTargetProviders.stream() + .filter(provider -> provider.name().equalsIgnoreCase(configured)) + .findFirst() + .orElseThrow(() -> new BusinessException(9002, "拨号号码提供方配置无效")); + } +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/shop/service/impl/ContactInfoServiceImpl.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/shop/service/impl/ContactInfoServiceImpl.java index 43ac284e..7ae696c7 100644 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/shop/service/impl/ContactInfoServiceImpl.java +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/shop/service/impl/ContactInfoServiceImpl.java @@ -1,6 +1,7 @@ package com.xiaowang.jayucloud.artlist.core.modules.shop.service.impl; import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; +import com.xiaowang.jayucloud.artlist.core.common.BusinessException; import com.xiaowang.jayucloud.artlist.core.modules.order.entity.OrderDO; import com.xiaowang.jayucloud.artlist.core.modules.order.entity.OrderItemDO; import com.xiaowang.jayucloud.artlist.core.modules.product.entity.ProductDO; @@ -8,11 +9,13 @@ import com.xiaowang.jayucloud.artlist.core.modules.user.entity.UserDO; import com.xiaowang.jayucloud.artlist.core.modules.order.mapper.OrderItemMapper; import com.xiaowang.jayucloud.artlist.core.modules.order.mapper.OrderMapper; import com.xiaowang.jayucloud.artlist.core.modules.product.mapper.ProductMapper; +import com.xiaowang.jayucloud.artlist.core.modules.shop.entity.ShopDO; import com.xiaowang.jayucloud.artlist.core.modules.user.mapper.UserMapper; import com.xiaowang.jayucloud.artlist.core.modules.shop.service.ContactInfoService; import com.xiaowang.jayucloud.artlist.core.modules.file.support.ObjectStorageUrlSupport; import com.xiaowang.jayucloud.artlist.core.modules.shop.support.UserShopBindingSupport; import com.xiaowang.jayucloud.artlist.core.modules.shop.vo.ContactInfoVO; +import com.xiaowang.jayucloud.artlist.core.support.privacy.SensitiveFieldPolicy; import lombok.RequiredArgsConstructor; import org.springframework.stereotype.Service; import org.springframework.util.StringUtils; @@ -40,6 +43,10 @@ public class ContactInfoServiceImpl implements ContactInfoService { * Variable `orderItemMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. */ private final OrderItemMapper orderItemMapper; + /** + * Variable `shopMapper`: used to verify the target shop is visible before exposing contact actions. + */ + private final com.xiaowang.jayucloud.artlist.core.modules.shop.mapper.ShopMapper shopMapper; /** * Variable `userShopBindingSupport`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. */ @@ -160,11 +167,23 @@ public class ContactInfoServiceImpl implements ContactInfoService { * @return private void result consumed by the caller or returned to the frontend */ private void ensureUserCanSeeShop(Long userId, Long shopId) { - if (userId == null) return; + if (userId == null) { + throw new BusinessException(403, "请先登录后再获取联系方式"); + } UserDO user = userMapper.selectById(userId); - if (user != null && shopId.equals(user.getShopId())) return; - if (!userShopBindingSupport.hasActiveBinding(userId, shopId)) { - // 店铺详情是公开入口,未绑定用户仍允许看联系方式。 + if (user == null || Integer.valueOf(1).equals(user.getIsDelete())) { + throw new BusinessException(403, "用户不存在或已失效"); + } + if (Integer.valueOf(4).equals(user.getType())) { + return; + } + if (shopId.equals(user.getShopId()) || userShopBindingSupport.hasActiveBinding(userId, shopId)) { + return; + } + // 普通用户仅可查看未删除的门店,与公开店铺详情可见范围一致。 + ShopDO shop = shopMapper.selectById(shopId); + if (shop == null || Integer.valueOf(1).equals(shop.getIsDelete())) { + throw new BusinessException(403, "店铺不存在或不可见"); } } @@ -202,9 +221,11 @@ public class ContactInfoServiceImpl implements ContactInfoService { return vo; } vo.setContactUserId(user.getId()); - vo.setContactName(StringUtils.hasText(user.getNickname()) ? user.getNickname() : user.getAccount()); + vo.setContactName(StringUtils.hasText(user.getNickname()) ? user.getNickname() + : SensitiveFieldPolicy.account(user.getAccount(), SensitiveFieldPolicy.Scenario.THIRD_PARTY)); String contactPhone = StringUtils.hasText(user.getContactPhone()) ? user.getContactPhone() : user.getPhone(); - vo.setPhone(contactPhone); + // 全场景脱敏:联系信息接口不再返回号码,真实号码只通过 /contact-info/dial 单次取号。 + vo.setPhone(null); vo.setPhoneAvailable(StringUtils.hasText(contactPhone)); vo.setWechatId(user.getWechatId()); vo.setWechatAvailable(StringUtils.hasText(user.getWechatId())); diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/shop/support/dial/DialScene.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/shop/support/dial/DialScene.java new file mode 100644 index 00000000..62b21a7f --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/shop/support/dial/DialScene.java @@ -0,0 +1,41 @@ +package com.xiaowang.jayucloud.artlist.core.modules.shop.support.dial; + +import com.xiaowang.jayucloud.artlist.core.common.BusinessException; +import org.springframework.util.StringUtils; + +/** + * 拨号场景及其入参含义。 + */ +public enum DialScene { + + /** + * 店铺店长:targetId 为店铺ID。 + */ + SHOP_MANAGER, + /** + * 订单美甲师:targetId 为订单ID。 + */ + ORDER_ARTIST, + /** + * 作品美甲师:targetId 为作品ID,可选 artistId 指定美甲师。 + */ + PRODUCT_ARTIST, + /** + * 平台客服:targetId 忽略。 + */ + PLATFORM; + + /** + * 解析前端传入的场景值。 + */ + public static DialScene fromCode(String code) { + if (!StringUtils.hasText(code)) { + throw new BusinessException(400, "拨号场景不能为空"); + } + try { + return DialScene.valueOf(code.trim().toUpperCase()); + } catch (IllegalArgumentException exception) { + throw new BusinessException(400, "不支持的拨号场景"); + } + } +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/shop/support/dial/DialTargetProvider.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/shop/support/dial/DialTargetProvider.java new file mode 100644 index 00000000..48d5137c --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/shop/support/dial/DialTargetProvider.java @@ -0,0 +1,19 @@ +package com.xiaowang.jayucloud.artlist.core.modules.shop.support.dial; + +import com.xiaowang.jayucloud.artlist.core.modules.shop.vo.DialResponseVO; + +/** + * 拨号号码提供方:直拨真实号码或隐私号。 + */ +public interface DialTargetProvider { + + /** + * 配置值标识,与 jayucloud-artlist.dial.provider 对应。 + */ + String name(); + + /** + * 将已通过授权校验的真实号码转换为拨号响应。 + */ + DialResponseVO resolve(String rawPhone); +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/shop/support/dial/DirectDialTargetProvider.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/shop/support/dial/DirectDialTargetProvider.java new file mode 100644 index 00000000..527ff2df --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/shop/support/dial/DirectDialTargetProvider.java @@ -0,0 +1,30 @@ +package com.xiaowang.jayucloud.artlist.core.modules.shop.support.dial; + +import com.xiaowang.jayucloud.artlist.core.modules.shop.vo.DialResponseVO; +import org.springframework.stereotype.Component; + +/** + * 直拨真实号码的提供方。 + */ +@Component +public class DirectDialTargetProvider implements DialTargetProvider { + + /** + * 直拨号码的有效提示时长,仅用于前端控制展示,不做服务端缓存。 + */ + private static final int EXPIRES_IN_SECONDS = 300; + + @Override + public String name() { + return "direct"; + } + + @Override + public DialResponseVO resolve(String rawPhone) { + DialResponseVO vo = new DialResponseVO(); + vo.setMode("DIRECT"); + vo.setDialNumber(rawPhone); + vo.setExpiresInSeconds(EXPIRES_IN_SECONDS); + return vo; + } +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/shop/support/dial/PlaceholderPrivacyNumberProvider.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/shop/support/dial/PlaceholderPrivacyNumberProvider.java new file mode 100644 index 00000000..3a0b5a8f --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/shop/support/dial/PlaceholderPrivacyNumberProvider.java @@ -0,0 +1,27 @@ +package com.xiaowang.jayucloud.artlist.core.modules.shop.support.dial; + +import com.xiaowang.jayucloud.artlist.core.common.BusinessException; +import com.xiaowang.jayucloud.artlist.core.modules.shop.vo.DialResponseVO; +import org.springframework.stereotype.Component; + +/** + * 隐私号提供方占位实现:未对接隐私号平台时明确报错,绝不回退成真实号码。 + */ +@Component +public class PlaceholderPrivacyNumberProvider implements DialTargetProvider { + + /** + * 隐私号未配置的业务码。 + */ + public static final int NOT_CONFIGURED_CODE = 9001; + + @Override + public String name() { + return "privacy-number"; + } + + @Override + public DialResponseVO resolve(String rawPhone) { + throw new BusinessException(NOT_CONFIGURED_CODE, "隐私号码服务未配置,暂时无法拨号"); + } +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/shop/vo/DialResponseVO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/shop/vo/DialResponseVO.java new file mode 100644 index 00000000..7124e526 --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/shop/vo/DialResponseVO.java @@ -0,0 +1,25 @@ +package com.xiaowang.jayucloud.artlist.core.modules.shop.vo; + +import lombok.Data; + +/** + * 单次拨号取号响应。号码本身不进审计、日志与缓存。 + */ +@Data +public class DialResponseVO { + + /** + * 拨号模式:DIRECT=直拨真实号码,PRIVACY_NUMBER=隐私号码。 + */ + private String mode; + + /** + * 拨号号码;PRIVACY_NUMBER 未对接时不会返回真实号码。 + */ + private String dialNumber; + + /** + * 本次号码的有效时长(秒),供前端控制缓存时间。 + */ + private Integer expiresInSeconds; +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/user/controller/front/UserController.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/user/controller/front/UserController.java index 1c5cbacf..52a50ccc 100644 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/user/controller/front/UserController.java +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/user/controller/front/UserController.java @@ -38,6 +38,7 @@ import com.xiaowang.jayucloud.artlist.core.modules.user.service.UserService; import com.xiaowang.jayucloud.artlist.core.modules.security.service.ShopRoleService; import com.xiaowang.jayucloud.artlist.core.modules.auth.service.VerificationCodeService; import com.xiaowang.jayucloud.artlist.core.modules.integration.service.WechatMiniAuthService; +import com.xiaowang.jayucloud.artlist.core.support.privacy.PhoneCrypto; import com.xiaowang.jayucloud.artlist.core.modules.system.service.LegalAgreementService; import com.xiaowang.jayucloud.artlist.core.modules.security.service.SecurityAuditLogService; import com.xiaowang.jayucloud.artlist.core.support.id.TimeOrderedSnowflakeIdGenerator; @@ -89,6 +90,7 @@ public class UserController { * Variable `userService`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. */ private final UserService userService; + private final PhoneCrypto phoneCrypto; /** * Variable `userAssetService`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. */ @@ -138,6 +140,10 @@ public class UserController { * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. */ private final LegalAgreementService legalAgreementService; + /** + * Variable `jwtUtil`: resolves the optional logged-in user on endpoints excluded from authentication. + */ + private final com.xiaowang.jayucloud.artlist.core.utils.JwtUtil jwtUtil; /** * Purpose: securityAuditLogService supports UserController.java by holding or executing the security audit log service business role. * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. @@ -359,7 +365,7 @@ public class UserController { String normalizedAccount = AccountValidationUtils.requireValidAccount(account); UserDO userDO = userMapper.selectOne( com.baomidou.mybatisplus.core.toolkit.Wrappers.lambdaQuery(UserDO.class) - .eq(UserDO::getAccount, normalizedAccount) + .eq(UserDO::getAccountHash, phoneCrypto.index(normalizedAccount)) ); boolean available = userDO == null || Integer.valueOf(1).equals(userDO.getIsDelete()); String message = available ? "账号可用" : "账号已被注册"; @@ -377,7 +383,7 @@ public class UserController { String normalizedAccount = AccountValidationUtils.requireValidAccount(account); UserDO userDO = userMapper.selectOne( com.baomidou.mybatisplus.core.toolkit.Wrappers.lambdaQuery(UserDO.class) - .eq(UserDO::getAccount, normalizedAccount) + .eq(UserDO::getAccountHash, phoneCrypto.index(normalizedAccount)) .eq(UserDO::getIsDelete, 0) .last("limit 1") ); @@ -421,7 +427,7 @@ public class UserController { public Result checkPhoneAvailability(@PathVariable String phone) { UserDO userDO = userMapper.selectOne( com.baomidou.mybatisplus.core.toolkit.Wrappers.lambdaQuery(UserDO.class) - .eq(UserDO::getPhone, phone) + .eq(UserDO::getPhoneHash, phoneCrypto.index(phone)) .eq(UserDO::getIsDelete, 0) ); boolean available = userDO == null; @@ -550,7 +556,7 @@ public class UserController { boolean success = userService.register(registerRequestDTO); UserDO userDO = userMapper.selectOne( com.baomidou.mybatisplus.core.toolkit.Wrappers.lambdaQuery(UserDO.class) - .eq(UserDO::getAccount, AccountValidationUtils.requireValidAccount(registerRequestDTO.getAccount())) + .eq(UserDO::getAccountHash, phoneCrypto.index(AccountValidationUtils.requireValidAccount(registerRequestDTO.getAccount()))) .eq(UserDO::getIsDelete, 0) .last("limit 1") ); @@ -597,8 +603,9 @@ public class UserController { @PostMapping("/send-verification-code") @OperationGuard(action = "send-verification-code", ttlSeconds = 8, message = "验证码发送处理中,请稍后再试") public Result sendVerificationCode(HttpServletRequest request, @RequestBody SendVerificationCodeRequestDTO sendVerificationCodeRequestDTO) { - requestThrottleService.checkSendCode(request, sendVerificationCodeRequestDTO.getPhone()); - if (!verificationCodeService.canResend(sendVerificationCodeRequestDTO.getPhone())) { + String phone = resolveSendCodePhone(request, sendVerificationCodeRequestDTO); + requestThrottleService.checkSendCode(request, phone); + if (!verificationCodeService.canResend(phone)) { /** * Run business method `RuntimeException`. * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. @@ -607,10 +614,41 @@ public class UserController { */ throw new RuntimeException("验证码发送过于频繁,请1分钟后再试"); } - verificationCodeService.sendVerificationCode(sendVerificationCodeRequestDTO.getPhone(), sendVerificationCodeRequestDTO.getSceneCode()); + verificationCodeService.sendVerificationCode(phone, sendVerificationCodeRequestDTO.getSceneCode()); return Result.success(true); } + /** + * 修改密码等"发给自己"的验证码场景:号码由服务端按当前登录用户取,客户端传参忽略。 + */ + private String resolveSendCodePhone(HttpServletRequest request, SendVerificationCodeRequestDTO dto) { + String sceneCode = dto.getSceneCode(); + if (!"USER_CHANGE_PASSWORD_SMS_CODE".equals(sceneCode)) { + return dto.getPhone(); + } + Long userId = resolveOptionalUserId(request); + if (userId == null) { + return dto.getPhone(); + } + return userService.getBoundPhone(userId); + } + + private Long resolveOptionalUserId(HttpServletRequest request) { + Long userId = (Long) request.getAttribute("userId"); + if (userId != null) { + return userId; + } + String authorization = request.getHeader("Authorization"); + if (authorization == null || !authorization.startsWith("Bearer ")) { + return null; + } + String token = authorization.substring("Bearer ".length()).trim(); + if (!jwtUtil.validateToken(token) || !jwtUtil.isAccessToken(token)) { + return null; + } + return jwtUtil.getUserIdFromToken(token); + } + /** * 通过手机号验证码重置密码 * diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/user/entity/UserDO.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/user/entity/UserDO.java index cc7940bb..166dbadd 100644 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/user/entity/UserDO.java +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/user/entity/UserDO.java @@ -12,6 +12,8 @@ import lombok.EqualsAndHashCode; import java.time.LocalDate; import com.xiaowang.jayucloud.artlist.core.common.entity.BaseEntity; +import com.xiaowang.jayucloud.artlist.core.support.privacy.AccountPhoneTypeHandler; +import com.xiaowang.jayucloud.artlist.core.support.privacy.PhoneEncryptionTypeHandler; /** * 系统用户信息表 DO * 对应数据库表 t_user @@ -22,7 +24,7 @@ import com.xiaowang.jayucloud.artlist.core.common.entity.BaseEntity; @Getter @Setter @EqualsAndHashCode(callSuper = true) -@TableName("t_user") +@TableName(value = "t_user", autoResultMap = true) public class UserDO extends BaseEntity { /** @@ -44,23 +46,41 @@ public class UserDO extends BaseEntity { private String nickname; /** - * 用户账号(登录用) + * 用户账号(登录用,AES-GCM 密文,落库列 account;实体中保持明文,便于业务使用) */ - @TableField("account") + @TableField(value = "account", typeHandler = AccountPhoneTypeHandler.class) private String account; /** - * 手机号 + * 账号哈希(HMAC-SHA256,十六进制小写),所有账号等值查询统一使用 */ - @TableField("phone") + @TableField("account_hash") + private String accountHash; + + /** + * 手机号(AES-GCM 密文,落库列 phone_cipher;实体中保持明文,便于业务使用) + */ + @TableField(value = "phone_cipher", typeHandler = PhoneEncryptionTypeHandler.class) private String phone; /** - * 联系电话 + * 手机号哈希(HMAC-SHA256,十六进制小写),用于等值查询与唯一去重 */ - @TableField("contact_phone") + @TableField("phone_hash") + private String phoneHash; + + /** + * 联系电话(AES-GCM 密文,落库列 contact_phone_cipher;实体中保持明文) + */ + @TableField(value = "contact_phone_cipher", typeHandler = PhoneEncryptionTypeHandler.class) private String contactPhone; + /** + * 联系电话哈希(HMAC-SHA256,十六进制小写),用于等值查询 + */ + @TableField("contact_phone_hash") + private String contactPhoneHash; + /** * 生日 */ diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/user/service/UserService.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/user/service/UserService.java index 950a1ad0..88ac5275 100644 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/user/service/UserService.java +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/user/service/UserService.java @@ -394,4 +394,9 @@ public interface UserService extends IService { * @return boolean result consumed by the caller or returned to the frontend */ boolean updatePhone(Long userId, UpdatePhoneRequestDTO updatePhoneDTO); + + /** + * 获取当前登录用户已绑定的手机号(明文,仅用于服务端发码,不返回前端)。 + */ + String getBoundPhone(Long userId); } diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/user/service/impl/UserServiceImpl.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/user/service/impl/UserServiceImpl.java index 52695f45..996ac58f 100644 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/user/service/impl/UserServiceImpl.java +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/modules/user/service/impl/UserServiceImpl.java @@ -6,6 +6,7 @@ import com.baomidou.mybatisplus.core.toolkit.Wrappers; import com.baomidou.mybatisplus.extension.plugins.pagination.Page; import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import com.xiaowang.jayucloud.artlist.core.config.BrandProperties; +import com.xiaowang.jayucloud.artlist.core.common.BusinessException; import com.xiaowang.jayucloud.artlist.core.common.dto.*; import com.xiaowang.jayucloud.artlist.core.modules.artist.dto.*; import com.xiaowang.jayucloud.artlist.core.modules.auth.dto.*; @@ -48,6 +49,8 @@ import com.xiaowang.jayucloud.artlist.core.modules.system.support.AdminDefaultPa import com.xiaowang.jayucloud.artlist.core.modules.file.support.ObjectStorageUrlSupport; import com.xiaowang.jayucloud.artlist.core.modules.security.support.PermissionCatalog; import com.xiaowang.jayucloud.artlist.core.support.security.UserSessionService; +import com.xiaowang.jayucloud.artlist.core.support.privacy.PhoneCrypto; +import com.xiaowang.jayucloud.artlist.core.support.privacy.SensitiveFieldPolicy; import com.xiaowang.jayucloud.artlist.core.support.id.TimeOrderedSnowflakeIdGenerator; import com.xiaowang.jayucloud.artlist.core.modules.security.support.PermissionPolicy; import com.xiaowang.jayucloud.artlist.core.support.RequestShopContext; @@ -118,10 +121,10 @@ public class UserServiceImpl extends ServiceImpl implements private static final String DEFAULT_AVATAR_URL = "https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png"; private static final BigDecimal DEFAULT_NAIL_ARTIST_RATING = BigDecimal.valueOf(4.5); /** - * Purpose: DELETED_PHONE_MARKER supports UserServiceImpl.java by holding or executing the deleted phone marker business role. + * Purpose: DELETED_ACCOUNT_MARKER supports UserServiceImpl.java by holding or executing the deleted account marker business role. * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. */ - private static final String DELETED_PHONE_MARKER = "_deleted_"; + private static final String DELETED_ACCOUNT_MARKER = "_deleted_"; /** * Purpose: LOGIN_FAIL_KEY_PREFIX supports UserServiceImpl.java by holding or executing the login fail key prefix business role. * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. @@ -170,6 +173,7 @@ public class UserServiceImpl extends ServiceImpl implements */ private final UserInviteCodeMapper userInviteCodeMapper; private final BrandProperties brandProperties; + private final PhoneCrypto phoneCrypto; /** * Variable `userShopRoleMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls. */ @@ -369,7 +373,7 @@ public class UserServiceImpl extends ServiceImpl implements // 检查账号是否已存在 UserDO existingUser = userMapper.selectOne( Wrappers.lambdaQuery(UserDO.class) - .eq(UserDO::getAccount, validatedAccount) + .eq(UserDO::getAccountHash, phoneCrypto.index(validatedAccount)) .eq(UserDO::getIsDelete, 0) ); if (existingUser != null) { @@ -534,7 +538,7 @@ public class UserServiceImpl extends ServiceImpl implements if (normalizedAccount != null && !normalizedAccount.equals(userDO.getAccount())) { UserDO existingUser = userMapper.selectOne( Wrappers.lambdaQuery(UserDO.class) - .eq(UserDO::getAccount, normalizedAccount) + .eq(UserDO::getAccountHash, phoneCrypto.index(normalizedAccount)) .eq(UserDO::getIsDelete, 0) ); if (existingUser != null) { @@ -653,19 +657,34 @@ public class UserServiceImpl extends ServiceImpl implements .set(WechatMiniBindingDO::getUpdateTime, LocalDateTime.now()) ); LocalDateTime now = LocalDateTime.now(); + String deletedAccount = buildDeletedAccount(userDO); return userMapper.update( null, - new LambdaUpdateWrapper() - .eq(UserDO::getId, id) - .eq(UserDO::getIsDelete, 0) - .set(UserDO::getAccount, buildDeletedAccount(userDO)) - .set(UserDO::getPhone, buildDeletedPhone(userDO)) - .set(UserDO::getStatus, 0) - .set(UserDO::getIsDelete, 1) - .set(UserDO::getUpdateTime, now) + buildSoftDeleteUpdate(id, + phoneCrypto.encryptAccount(deletedAccount), + phoneCrypto.index(deletedAccount), + now) ) > 0; } + /** + * 构造账号注销更新条件:账号改为占位值,手机号/联系电话的密文与哈希一并清空,避免数据残留。 + */ + static LambdaUpdateWrapper buildSoftDeleteUpdate(Long id, String encryptedAccount, String accountHash, LocalDateTime now) { + return new LambdaUpdateWrapper() + .eq(UserDO::getId, id) + .eq(UserDO::getIsDelete, 0) + .set(UserDO::getAccount, encryptedAccount) + .set(UserDO::getAccountHash, accountHash) + .set(UserDO::getPhone, null) + .set(UserDO::getPhoneHash, null) + .set(UserDO::getContactPhone, null) + .set(UserDO::getContactPhoneHash, null) + .set(UserDO::getStatus, 0) + .set(UserDO::getIsDelete, 1) + .set(UserDO::getUpdateTime, now); + } + /** * 根据ID获取用户信息 * @param id 用户ID @@ -683,7 +702,7 @@ public class UserServiceImpl extends ServiceImpl implements * @param userDO parameter `userDO` supplied by the caller * @return return result consumed by the caller or returned to the frontend */ - return convertToVO(userDO); + return convertToVO(userDO, SensitiveFieldPolicy.Scenario.SELF_PROFILE); } /** @@ -697,7 +716,7 @@ public class UserServiceImpl extends ServiceImpl implements .eq(UserDO::getIsDelete, 0) ); return userDOs.stream() - .map(this::convertToVO) + .map(user -> convertToVO(user, SensitiveFieldPolicy.Scenario.ADMIN_LIST)) .collect(Collectors.toList()); } @@ -718,7 +737,7 @@ public class UserServiceImpl extends ServiceImpl implements .in(UserDO::getId, userIds) ); return userDOs.stream() - .map(this::convertToVO) + .map(user -> convertToVO(user, SensitiveFieldPolicy.Scenario.ADMIN_LIST)) .collect(Collectors.toList()); } @@ -735,7 +754,7 @@ public class UserServiceImpl extends ServiceImpl implements .eq(UserDO::getType, type) ); return userDOs.stream() - .map(this::convertToVO) + .map(user -> convertToVO(user, SensitiveFieldPolicy.Scenario.ADMIN_LIST)) .collect(Collectors.toList()); } @@ -749,7 +768,7 @@ public class UserServiceImpl extends ServiceImpl implements String normalizedAccount = AccountValidationUtils.requireValidAccount(account); UserDO userDO = userMapper.selectOne( Wrappers.lambdaQuery(UserDO.class) - .eq(UserDO::getAccount, normalizedAccount) + .eq(UserDO::getAccountHash, phoneCrypto.index(normalizedAccount)) .eq(UserDO::getIsDelete, 0) ); if (userDO == null || Integer.valueOf(1).equals(userDO.getIsDelete())) { @@ -761,7 +780,7 @@ public class UserServiceImpl extends ServiceImpl implements * @param userDO parameter `userDO` supplied by the caller * @return return result consumed by the caller or returned to the frontend */ - return convertToVO(userDO); + return convertToVO(userDO, SensitiveFieldPolicy.Scenario.SELF_PROFILE); } /** @@ -770,7 +789,7 @@ public class UserServiceImpl extends ServiceImpl implements * @param userDO 用户DO * @return 用户VO */ - private UserVO convertToVO(UserDO userDO) { + private UserVO convertToVO(UserDO userDO, SensitiveFieldPolicy.Scenario scenario) { UserVO userVO = new UserVO(); userVO.setId(userDO.getId()); List shopOptions = resolveShopOptions(userDO, true, false); @@ -791,9 +810,9 @@ public class UserServiceImpl extends ServiceImpl implements userVO.setShopIds(shopOptions.stream().map(ShopSimpleVO::getId).collect(Collectors.toList())); userVO.setShopNames(shopOptions.stream().map(ShopSimpleVO::getShopName).collect(Collectors.toList())); userVO.setNickname(userDO.getNickname()); - userVO.setAccount(userDO.getAccount()); - userVO.setPhone(userDO.getPhone()); - userVO.setContactPhone(userDO.getContactPhone()); + userVO.setAccount(SensitiveFieldPolicy.account(userDO.getAccount(), scenario)); + userVO.setPhone(SensitiveFieldPolicy.phone(userDO.getPhone(), scenario)); + userVO.setContactPhone(SensitiveFieldPolicy.phone(userDO.getContactPhone(), scenario)); userVO.setBirthday(userDO.getBirthday()); userVO.setWechatId(userDO.getWechatId()); userVO.setWechatQrCode(resolveAccessibleProfileImage(userDO.getWechatQrCode())); @@ -869,7 +888,7 @@ public class UserServiceImpl extends ServiceImpl implements UserDO userDO = userMapper.selectOne( Wrappers.lambdaQuery(UserDO.class) - .eq(UserDO::getAccount, normalizedAccount) + .eq(UserDO::getAccountHash, phoneCrypto.index(normalizedAccount)) .eq(UserDO::getIsDelete, 0) .last("limit 1") ); @@ -919,7 +938,7 @@ public class UserServiceImpl extends ServiceImpl implements UserDO userDO = userMapper.selectOne( Wrappers.lambdaQuery(UserDO.class) - .eq(UserDO::getPhone, normalizedPhone) + .eq(UserDO::getPhoneHash, phoneCrypto.index(normalizedPhone)) .eq(UserDO::getIsDelete, 0) .last("limit 1") ); @@ -974,7 +993,7 @@ public class UserServiceImpl extends ServiceImpl implements UserDO userDO = userMapper.selectOne( Wrappers.lambdaQuery(UserDO.class) - .eq(UserDO::getAccount, normalizedAccount) + .eq(UserDO::getAccountHash, phoneCrypto.index(normalizedAccount)) .eq(UserDO::getIsDelete, 0) .last("limit 1") ); @@ -1022,7 +1041,7 @@ public class UserServiceImpl extends ServiceImpl implements String normalizedAccount = AccountValidationUtils.requireValidAccount(loginRequestDTO.getAccount()); UserDO userDO = userMapper.selectOne( Wrappers.lambdaQuery(UserDO.class) - .eq(UserDO::getAccount, normalizedAccount) + .eq(UserDO::getAccountHash, phoneCrypto.index(normalizedAccount)) ); /** @@ -1085,7 +1104,7 @@ public class UserServiceImpl extends ServiceImpl implements UserDO userDO = userMapper.selectOne( Wrappers.lambdaQuery(UserDO.class) - .eq(UserDO::getPhone, phoneLoginRequestDTO.getPhone()) + .eq(UserDO::getPhoneHash, phoneCrypto.index(phoneLoginRequestDTO.getPhone())) .eq(UserDO::getIsDelete, 0) ); @@ -1126,7 +1145,7 @@ public class UserServiceImpl extends ServiceImpl implements public LoginResponseVO loginByVerifiedPhone(String phone, Long shopId) { UserDO userDO = userMapper.selectOne( Wrappers.lambdaQuery(UserDO.class) - .eq(UserDO::getPhone, phone) + .eq(UserDO::getPhoneHash, phoneCrypto.index(phone)) .eq(UserDO::getIsDelete, 0) .last("limit 1") ); @@ -1239,7 +1258,7 @@ public class UserServiceImpl extends ServiceImpl implements String normalizedAccount = AccountValidationUtils.requireValidAccount(loginRequestDTO.getAccount()); UserDO userDO = userMapper.selectOne( Wrappers.lambdaQuery(UserDO.class) - .eq(UserDO::getAccount, normalizedAccount) + .eq(UserDO::getAccountHash, phoneCrypto.index(normalizedAccount)) ); /** @@ -1448,7 +1467,7 @@ public class UserServiceImpl extends ServiceImpl implements UserDO existingUser = userMapper.selectOne( Wrappers.lambdaQuery(UserDO.class) - .eq(UserDO::getAccount, validatedAccount) + .eq(UserDO::getAccountHash, phoneCrypto.index(validatedAccount)) ); if (existingUser != null) { @@ -1471,7 +1490,7 @@ public class UserServiceImpl extends ServiceImpl implements UserDO existingPhoneUser = userMapper.selectOne( Wrappers.lambdaQuery(UserDO.class) - .eq(UserDO::getPhone, registerRequestDTO.getPhone()) + .eq(UserDO::getPhoneHash, phoneCrypto.index(registerRequestDTO.getPhone())) .eq(UserDO::getIsDelete, 0) ); @@ -1541,7 +1560,7 @@ public class UserServiceImpl extends ServiceImpl implements UserDO existingUser = userMapper.selectOne( Wrappers.lambdaQuery(UserDO.class) - .eq(UserDO::getAccount, phone) + .eq(UserDO::getAccountHash, phoneCrypto.index(phone)) .eq(UserDO::getIsDelete, 0) .last("limit 1") ); @@ -1896,10 +1915,17 @@ public class UserServiceImpl extends ServiceImpl implements wrapper.eq(UserDO::getIsDelete, 0); // 不再过滤普通用户,由前端根据用户角色进行过滤 if (StringUtils.hasText(keyword)) { - wrapper.and(w -> w.like(UserDO::getAccount, keyword) - .or().like(UserDO::getNickname, keyword) - .or().like(UserDO::getPhone, keyword) - .or().like(UserDO::getContactPhone, keyword)); + String keywordPhoneHash = phoneCrypto.isMobilePhone(keyword) ? phoneCrypto.index(keyword) : null; + String keywordAccountHash = phoneCrypto.index(keyword); + wrapper.and(w -> { + // 账号落库为密文,不能模糊检索,统一走 account_hash 精确匹配 + w.eq(UserDO::getAccountHash, keywordAccountHash).or().like(UserDO::getNickname, keyword); + // 手机号只做精确匹配:密文不可模糊检索,统一走 phone_hash + if (keywordPhoneHash != null) { + w.or().eq(UserDO::getPhoneHash, keywordPhoneHash) + .or().eq(UserDO::getContactPhoneHash, keywordPhoneHash); + } + }); } if (shopId != null && shopId > 0) { List userIds = userShopBindingSupport.listUserIdsByShopId(shopId, true); @@ -1951,7 +1977,7 @@ public class UserServiceImpl extends ServiceImpl implements Page userPage = userMapper.selectPage(pageParam, wrapper); PageResultVO result = new PageResultVO<>(); - result.setList(userPage.getRecords().stream().map(this::convertToVO).collect(Collectors.toList())); + result.setList(userPage.getRecords().stream().map(user -> convertToVO(user, SensitiveFieldPolicy.Scenario.ADMIN_LIST)).collect(Collectors.toList())); result.setTotal(userPage.getTotal()); result.setPage(page); result.setSize(size); @@ -2211,7 +2237,7 @@ public class UserServiceImpl extends ServiceImpl implements * @return boolean result consumed by the caller or returned to the frontend */ public boolean updatePhone(Long userId, UpdatePhoneRequestDTO updatePhoneDTO) { - String oldPhone = updatePhoneDTO.getOldPhone(); + // 原手机号由服务端按当前登录用户读取,客户端传入的 oldPhone 仅为兼容旧协议,不参与校验。 String newPhone = updatePhoneDTO.getNewPhone(); String verificationCode = updatePhoneDTO.getVerificationCode(); @@ -2231,14 +2257,6 @@ public class UserServiceImpl extends ServiceImpl implements */ throw new RuntimeException("当前账号未绑定手机号"); } - if (!userDO.getPhone().equals(oldPhone)) { - /** - * Run business method `RuntimeException`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @return throw new result consumed by the caller or returned to the frontend - */ - throw new RuntimeException("原手机号不匹配"); - } /** * Run business method `validateVerificationCode`. @@ -2263,6 +2281,19 @@ public class UserServiceImpl extends ServiceImpl implements return userMapper.updateById(userDO) > 0; } + @Override + /** + * 获取当前登录用户已绑定手机号的明文,仅用于服务端发码。 + */ + public String getBoundPhone(Long userId) { + UserDO userDO = userMapper.selectById(userId); + assertUserAvailable(userDO); + if (!StringUtils.hasText(userDO.getPhone())) { + throw new BusinessException(400, "当前账号未绑定手机号"); + } + return userDO.getPhone(); + } + @Override /** * Run business method `resetPasswordByPhone`. @@ -2284,9 +2315,9 @@ public class UserServiceImpl extends ServiceImpl implements */ validateVerificationCode(phone, verificationCode); - // 根据手机号查找用户 + // 根据手机号哈希查找用户 LambdaQueryWrapper wrapper = Wrappers.lambdaQuery(UserDO.class); - wrapper.eq(UserDO::getPhone, phone); + wrapper.eq(UserDO::getPhoneHash, phoneCrypto.index(phone)); wrapper.eq(UserDO::getIsDelete, 0); UserDO userDO = userMapper.selectOne(wrapper); @@ -2334,26 +2365,7 @@ public class UserServiceImpl extends ServiceImpl implements * @param 50 parameter `50` supplied by the caller * @return return result consumed by the caller or returned to the frontend */ - return trimDeletedPlaceholder(base + DELETED_PHONE_MARKER + suffix, 50); - } - - /** - * Run business method `buildDeletedPhone`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param userDO parameter `userDO` supplied by the caller - * @return private String result consumed by the caller or returned to the frontend - */ - private String buildDeletedPhone(UserDO userDO) { - String suffix = userDO.getId() + "_" + snowflakeIdGenerator.nextIdString(); - String base = StringUtils.hasText(userDO.getPhone()) ? userDO.getPhone() : "deleted_phone"; - /** - * Run business method `trimDeletedPlaceholder`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param suffix parameter `suffix` supplied by the caller - * @param 50 parameter `50` supplied by the caller - * @return return result consumed by the caller or returned to the frontend - */ - return trimDeletedPlaceholder(base + DELETED_PHONE_MARKER + suffix, 50); + return trimDeletedPlaceholder(base + DELETED_ACCOUNT_MARKER + suffix, 50); } /** @@ -2499,7 +2511,8 @@ public class UserServiceImpl extends ServiceImpl implements * @return private String result consumed by the caller or returned to the frontend */ private String buildLoginFailKey(String account) { - return LOGIN_FAIL_KEY_PREFIX + account.trim(); + String indexedAccount = StringUtils.hasText(account) ? phoneCrypto.index(account) : null; + return LOGIN_FAIL_KEY_PREFIX + (indexedAccount == null ? "anonymous" : indexedAccount); } /** @@ -2969,9 +2982,6 @@ public class UserServiceImpl extends ServiceImpl implements } return null; } - if (isDeletedPlaceholderPhone(normalizedPhone)) { - return normalizedPhone; - } if (!normalizedPhone.matches(PHONE_REGEX)) { /** * Run business method `RuntimeException`. @@ -2991,16 +3001,6 @@ public class UserServiceImpl extends ServiceImpl implements return normalizedPhone; } - /** - * Run business method `isDeletedPlaceholderPhone`. - * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. - * @param phone parameter `phone` supplied by the caller - * @return private boolean result consumed by the caller or returned to the frontend - */ - private boolean isDeletedPlaceholderPhone(String phone) { - return StringUtils.hasText(phone) && phone.contains(DELETED_PHONE_MARKER); - } - /** * Run business method `ensurePhoneNotUsed`. * Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result. @@ -3010,7 +3010,7 @@ public class UserServiceImpl extends ServiceImpl implements */ private void ensurePhoneNotUsed(String phone, Long currentUserId) { LambdaQueryWrapper wrapper = Wrappers.lambdaQuery(UserDO.class) - .eq(UserDO::getPhone, phone) + .eq(UserDO::getPhoneHash, phoneCrypto.index(phone)) .eq(UserDO::getIsDelete, 0); if (currentUserId != null) { wrapper.ne(UserDO::getId, currentUserId); diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/support/privacy/AccountHashBackfillRunner.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/support/privacy/AccountHashBackfillRunner.java new file mode 100644 index 00000000..a6a57e7a --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/support/privacy/AccountHashBackfillRunner.java @@ -0,0 +1,52 @@ +package com.xiaowang.jayucloud.artlist.core.support.privacy; + +import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper; +import com.baomidou.mybatisplus.core.toolkit.Wrappers; +import com.xiaowang.jayucloud.artlist.core.modules.user.entity.UserDO; +import com.xiaowang.jayucloud.artlist.core.modules.user.mapper.UserMapper; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.boot.ApplicationArguments; +import org.springframework.boot.ApplicationRunner; +import org.springframework.stereotype.Component; +import org.springframework.util.StringUtils; + +import java.util.List; + +/** + * V5 迁移之后的账号补写:把 account_hash 为空的历史行(如 V1 种子账号 xiaowang) + * 加密 account 并回填 account_hash,之后所有账号查询可统一走哈希等值条件。 + * + *

只处理无哈希的行,幂等;已处理行不会重复更新。

+ */ +@Slf4j +@Component +@RequiredArgsConstructor +public class AccountHashBackfillRunner implements ApplicationRunner { + + private final UserMapper userMapper; + private final PhoneCrypto phoneCrypto; + + @Override + public void run(ApplicationArguments args) { + List candidates = userMapper.selectList(Wrappers.lambdaQuery() + .isNull(UserDO::getAccountHash) + .isNotNull(UserDO::getAccount)); + if (candidates.isEmpty()) { + return; + } + int updated = 0; + for (UserDO user : candidates) { + String plainAccount = user.getAccount(); + if (!StringUtils.hasText(plainAccount)) { + continue; + } + userMapper.update(null, new LambdaUpdateWrapper() + .eq(UserDO::getId, user.getId()) + .set(UserDO::getAccount, phoneCrypto.encryptAccount(plainAccount)) + .set(UserDO::getAccountHash, phoneCrypto.index(plainAccount))); + updated++; + } + log.info("账号加密回填完成,共处理 {} 条", updated); + } +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/support/privacy/AccountPhoneTypeHandler.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/support/privacy/AccountPhoneTypeHandler.java new file mode 100644 index 00000000..b511b47b --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/support/privacy/AccountPhoneTypeHandler.java @@ -0,0 +1,35 @@ +package com.xiaowang.jayucloud.artlist.core.support.privacy; + +import org.apache.ibatis.type.BaseTypeHandler; +import org.apache.ibatis.type.JdbcType; + +import java.sql.CallableStatement; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; + +/** + * 账号 TypeHandler:写库时一律 AES-GCM 加密,读库时仅解密 enc:v1: 前缀的密文。 + * 与 JC-Salon-Core 的 AccountPhoneTypeHandler 同名同结构。 + */ +public class AccountPhoneTypeHandler extends BaseTypeHandler { + @Override + public void setNonNullParameter(PreparedStatement ps, int index, String parameter, JdbcType jdbcType) throws SQLException { + ps.setString(index, PhoneCrypto.current().encryptAccount(parameter)); + } + + @Override + public String getNullableResult(ResultSet rs, String columnName) throws SQLException { + return PhoneCrypto.current().decryptAccount(rs.getString(columnName)); + } + + @Override + public String getNullableResult(ResultSet rs, int columnIndex) throws SQLException { + return PhoneCrypto.current().decryptAccount(rs.getString(columnIndex)); + } + + @Override + public String getNullableResult(CallableStatement cs, int columnIndex) throws SQLException { + return PhoneCrypto.current().decryptAccount(cs.getString(columnIndex)); + } +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/support/privacy/PhoneCrypto.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/support/privacy/PhoneCrypto.java new file mode 100644 index 00000000..3d28e1be --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/support/privacy/PhoneCrypto.java @@ -0,0 +1,141 @@ +package com.xiaowang.jayucloud.artlist.core.support.privacy; + +import com.xiaowang.jayucloud.artlist.core.config.PhoneCryptoProperties; +import org.springframework.stereotype.Component; +import org.springframework.util.StringUtils; + +import javax.annotation.PostConstruct; +import javax.crypto.Cipher; +import javax.crypto.Mac; +import javax.crypto.spec.GCMParameterSpec; +import javax.crypto.spec.SecretKeySpec; +import java.nio.charset.StandardCharsets; +import java.security.GeneralSecurityException; +import java.security.SecureRandom; +import java.util.Arrays; +import java.util.Base64; +import java.util.HexFormat; + +/** + * 手机号加密与索引组件,算法与 JC-Salon-Core 的 PhoneCrypto 逐字对齐: + *
    + *
  • 加密:AES/GCM/NoPadding,12 字节随机 IV,128 位 tag,前缀 {@code enc:v1:},载荷为 Base64(IV||密文);
  • + *
  • 索引:HMAC-SHA256,输入为 {@code value.trim()},输出十六进制小写;
  • + *
  • 手机号识别:{@code 1[3-9]\d{9}}。
  • + *
+ * 两条线使用同一把 index-key,phone_hash 才可跨线比对;密文因随机 IV 各自独立,不要求可比。 + */ +@Component +public class PhoneCrypto { + private static final String CIPHER_PREFIX = "enc:v1:"; + private static final SecureRandom RANDOM = new SecureRandom(); + private static volatile PhoneCrypto current; + + private final PhoneCryptoProperties properties; + private byte[] encryptionKey; + private byte[] indexKey; + + public PhoneCrypto(PhoneCryptoProperties properties) { + this.properties = properties; + } + + @PostConstruct + public void initialize() { + encryptionKey = decodeKey(properties.getEncryptionKey(), "phone-crypto.encryption-key"); + indexKey = decodeKey(properties.getIndexKey(), "phone-crypto.index-key"); + if (encryptionKey.length != 32 || indexKey.length < 32) { + throw new IllegalStateException("手机号加密与索引密钥必须分别配置为至少32字节的Base64密钥"); + } + if (Arrays.equals(encryptionKey, indexKey)) { + throw new IllegalStateException("手机号加密密钥与索引密钥必须独立"); + } + current = this; + } + + public String encrypt(String value) { + if (!StringUtils.hasText(value) || value.startsWith(CIPHER_PREFIX)) return value; + try { + byte[] iv = new byte[12]; + RANDOM.nextBytes(iv); + Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding"); + cipher.init(Cipher.ENCRYPT_MODE, new SecretKeySpec(encryptionKey, "AES"), new GCMParameterSpec(128, iv)); + byte[] encrypted = cipher.doFinal(value.getBytes(StandardCharsets.UTF_8)); + byte[] payload = new byte[iv.length + encrypted.length]; + System.arraycopy(iv, 0, payload, 0, iv.length); + System.arraycopy(encrypted, 0, payload, iv.length, encrypted.length); + return CIPHER_PREFIX + Base64.getEncoder().encodeToString(payload); + } catch (GeneralSecurityException exception) { + throw new IllegalStateException("手机号加密失败", exception); + } + } + + public String decrypt(String value) { + if (!StringUtils.hasText(value) || !value.startsWith(CIPHER_PREFIX)) return value; + try { + byte[] payload = Base64.getDecoder().decode(value.substring(CIPHER_PREFIX.length())); + if (payload.length < 29) throw new IllegalArgumentException("手机号密文格式无效"); + byte[] iv = Arrays.copyOfRange(payload, 0, 12); + byte[] encrypted = Arrays.copyOfRange(payload, 12, payload.length); + Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding"); + cipher.init(Cipher.DECRYPT_MODE, new SecretKeySpec(encryptionKey, "AES"), new GCMParameterSpec(128, iv)); + return new String(cipher.doFinal(encrypted), StandardCharsets.UTF_8); + } catch (GeneralSecurityException | IllegalArgumentException exception) { + throw new IllegalStateException("手机号解密失败,请检查密钥或数据完整性", exception); + } + } + + /** + * 账号加密:ArtList 允许字母数字自定义账号,因此非空账号一律加密。 + */ + public String encryptAccount(String value) { + return encrypt(value); + } + + /** + * 账号解密:仅对 {@code enc:v1:} 前缀的密文解密,历史明文账号原样返回。 + */ + public String decryptAccount(String value) { + return decrypt(value); + } + + public boolean isEncrypted(String value) { + return value != null && value.startsWith(CIPHER_PREFIX); + } + + public boolean isMobilePhone(String value) { + return value != null && value.trim().matches("1[3-9]\\d{9}"); + } + + public String mask(String value) { + if (!StringUtils.hasText(value)) return value; + String plain = isEncrypted(value) ? decrypt(value) : value; + return isMobilePhone(plain) ? plain.substring(0, 3) + "****" + plain.substring(7) : plain; + } + + public String index(String value) { + if (!StringUtils.hasText(value)) return null; + try { + Mac mac = Mac.getInstance("HmacSHA256"); + mac.init(new SecretKeySpec(indexKey, "HmacSHA256")); + byte[] digest = mac.doFinal(value.trim().getBytes(StandardCharsets.UTF_8)); + return HexFormat.of().formatHex(digest); + } catch (GeneralSecurityException exception) { + throw new IllegalStateException("敏感字段索引生成失败", exception); + } + } + + public static PhoneCrypto current() { + PhoneCrypto instance = current; + if (instance == null) throw new IllegalStateException("手机号加密组件尚未初始化"); + return instance; + } + + private byte[] decodeKey(String value, String name) { + if (!StringUtils.hasText(value)) throw new IllegalStateException("缺少Nacos配置: jayucloud-artlist.privacy." + name); + try { + return Base64.getDecoder().decode(value.trim()); + } catch (IllegalArgumentException exception) { + throw new IllegalStateException("Nacos配置必须使用Base64编码: " + name, exception); + } + } +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/support/privacy/PhoneEncryptionTypeHandler.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/support/privacy/PhoneEncryptionTypeHandler.java new file mode 100644 index 00000000..e90d750d --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/support/privacy/PhoneEncryptionTypeHandler.java @@ -0,0 +1,35 @@ +package com.xiaowang.jayucloud.artlist.core.support.privacy; + +import org.apache.ibatis.type.BaseTypeHandler; +import org.apache.ibatis.type.JdbcType; + +import java.sql.CallableStatement; +import java.sql.PreparedStatement; +import java.sql.ResultSet; +import java.sql.SQLException; + +/** + * 手机号密文列的类型处理器,与 JC-Salon-Core 的 PhoneEncryptionTypeHandler 一致。 + * 仅作用于实体读写;QueryWrapper 条件不会经过类型处理器,按手机号查询必须使用 phone_hash。 + */ +public class PhoneEncryptionTypeHandler extends BaseTypeHandler { + @Override + public void setNonNullParameter(PreparedStatement ps, int index, String parameter, JdbcType jdbcType) throws SQLException { + ps.setString(index, PhoneCrypto.current().encrypt(parameter)); + } + + @Override + public String getNullableResult(ResultSet rs, String columnName) throws SQLException { + return PhoneCrypto.current().decrypt(rs.getString(columnName)); + } + + @Override + public String getNullableResult(ResultSet rs, int columnIndex) throws SQLException { + return PhoneCrypto.current().decrypt(rs.getString(columnIndex)); + } + + @Override + public String getNullableResult(CallableStatement cs, int columnIndex) throws SQLException { + return PhoneCrypto.current().decrypt(cs.getString(columnIndex)); + } +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/support/privacy/SensitiveFieldPolicy.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/support/privacy/SensitiveFieldPolicy.java new file mode 100644 index 00000000..e472aa15 --- /dev/null +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/support/privacy/SensitiveFieldPolicy.java @@ -0,0 +1,51 @@ +package com.xiaowang.jayucloud.artlist.core.support.privacy; + +import org.springframework.util.StringUtils; + +/** + * 手机号 / 账号的集中脱敏策略。 + * + *

后端始终完整保存明文语义(落库为 AES-GCM 密文),但返回前端、写日志、写审计时一律脱敏: + * 不再存在任何"返回完整号码"的场景。需要真实号码时只走 {@code POST /contact-info/dial} 单次取号。

+ */ +public final class SensitiveFieldPolicy { + + /** + * 调用场景,仅用于表达调用方语义;所有场景的输出均为脱敏值。 + */ + public enum Scenario { + SELF_PROFILE, + ADMIN_LIST, + THIRD_PARTY, + DIAL, + LOG + } + + private SensitiveFieldPolicy() { + } + + /** + * 手机号按场景返回脱敏值(138****0000)。 + */ + public static String phone(String value, Scenario scenario) { + if (!StringUtils.hasText(value)) { + return value; + } + String plain = PhoneCrypto.current().isEncrypted(value) ? PhoneCrypto.current().decrypt(value) : value; + return PhoneCrypto.current().mask(plain); + } + + /** + * 账号按场景返回脱敏值;手机号形态账号按手机号规则脱敏,其余保留前两位。 + */ + public static String account(String value, Scenario scenario) { + if (!StringUtils.hasText(value)) { + return value; + } + String plain = PhoneCrypto.current().isEncrypted(value) ? PhoneCrypto.current().decryptAccount(value) : value; + if (PhoneCrypto.current().isMobilePhone(plain)) { + return PhoneCrypto.current().mask(plain); + } + return plain.length() <= 2 ? "***" : plain.substring(0, 2) + "***"; + } +} diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/support/security/OperationGuardService.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/support/security/OperationGuardService.java index 89239fff..da20c366 100644 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/support/security/OperationGuardService.java +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/support/security/OperationGuardService.java @@ -3,6 +3,7 @@ package com.xiaowang.jayucloud.artlist.core.support.security; import com.fasterxml.jackson.core.type.TypeReference; import com.fasterxml.jackson.databind.ObjectMapper; import com.xiaowang.jayucloud.artlist.core.support.RequestShopContext; +import com.xiaowang.jayucloud.artlist.core.support.privacy.PhoneCrypto; import lombok.RequiredArgsConstructor; import org.springframework.data.redis.core.StringRedisTemplate; import org.springframework.data.redis.core.script.DefaultRedisScript; @@ -55,6 +56,10 @@ public class OperationGuardService { * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. */ private final ObjectMapper objectMapper; + /** + * Purpose: phoneCrypto supports OperationGuardService.java by hashing phone numbers before they become Redis key segments. + */ + private final PhoneCrypto phoneCrypto; /** * Purpose: tryAcquire supports OperationGuardService.java by holding or executing the try acquire business role. @@ -186,7 +191,8 @@ public class OperationGuardService { readBodyField(request, key) ); if (StringUtils.hasText(value)) { - return sanitize(value); + // 手机号/账号不落 Redis 键:统一替换为哈希 + return ("phone".equals(key) || "account".equals(key)) ? phoneCrypto.index(value) : sanitize(value); } } return buildRequestFingerprint(request, request == null ? "-" : request.getRequestURI()); diff --git a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/support/security/RequestThrottleService.java b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/support/security/RequestThrottleService.java index c6d0b117..4861910f 100644 --- a/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/support/security/RequestThrottleService.java +++ b/JC-ArtList-Core/src/main/java/com/xiaowang/jayucloud/artlist/core/support/security/RequestThrottleService.java @@ -107,6 +107,22 @@ public class RequestThrottleService { assertAllowed(category, request, userId == null ? "" : String.valueOf(userId), rule, message); } + /** + * 联系方式查询限流:按登录用户维度。 + */ + public void checkContactInfoRead(HttpServletRequest request, Long userId) { + assertAllowed("contact-info-read", request, userId == null ? "" : String.valueOf(userId), + rateLimitProperties.getContactInfoRead(), "联系方式查询过于频繁,请稍后再试"); + } + + /** + * 单次拨号取号限流:按登录用户维度,避免批量撞取号码。 + */ + public void checkContactDial(HttpServletRequest request, Long userId) { + assertAllowed("contact-dial", request, userId == null ? "" : String.valueOf(userId), + rateLimitProperties.getContactDial(), "拨号取号过于频繁,请稍后再试"); + } + /** * Purpose: recordLoginFailure supports RequestThrottleService.java by holding or executing the record login failure business role. * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. diff --git a/JC-ArtList-Core/src/main/resources/db/migration/V2__手机号加密与手机号哈希_20261104.sql b/JC-ArtList-Core/src/main/resources/db/migration/V2__手机号加密与手机号哈希_20261104.sql new file mode 100644 index 00000000..6cde0091 --- /dev/null +++ b/JC-ArtList-Core/src/main/resources/db/migration/V2__手机号加密与手机号哈希_20261104.sql @@ -0,0 +1,123 @@ +-- ============================================================================= +-- V2 手机号加密与手机号哈希(ArtList) +-- 日期:2026-11-04 +-- 口径:不做数据迁移,空库初始化。本迁移只调整结构,不回填历史数据。 +-- 说明: +-- - t_user.phone / t_user.contact_phone 改为密文列 phone_cipher / contact_phone_cipher; +-- - 新增 phone_hash / contact_phone_hash,用于等值查询与去重; +-- - 哈希算法与 Salon 一致:HMAC-SHA256(规范化手机号),规范化为 trim; +-- - 加密算法与 Salon 一致:AES/GCM/NoPadding,12 字节随机 IV,128 位 tag。 +-- 可重复执行:所有 DDL 均先查 information_schema 再执行。 +-- ============================================================================= + +DROP PROCEDURE IF EXISTS sp_v2_add_column_if_not_exists; +DROP PROCEDURE IF EXISTS sp_v2_drop_column_if_exists; +DROP PROCEDURE IF EXISTS sp_v2_drop_index_if_exists; +DROP PROCEDURE IF EXISTS sp_v2_add_index_if_not_exists; +DROP PROCEDURE IF EXISTS sp_v2_add_unique_index_if_not_exists; + +DELIMITER $$ + +CREATE PROCEDURE sp_v2_add_column_if_not_exists( + IN p_table VARCHAR(64), + IN p_column VARCHAR(64), + IN p_definition VARCHAR(500) +) +BEGIN + IF NOT EXISTS ( + SELECT 1 FROM information_schema.columns + WHERE table_schema = DATABASE() AND table_name = p_table AND column_name = p_column + ) THEN + SET @ddl = CONCAT('ALTER TABLE `', p_table, '` ADD COLUMN `', p_column, '` ', p_definition); + PREPARE stmt FROM @ddl; + EXECUTE stmt; + DEALLOCATE PREPARE stmt; + END IF; +END $$ + +CREATE PROCEDURE sp_v2_drop_column_if_exists( + IN p_table VARCHAR(64), + IN p_column VARCHAR(64) +) +BEGIN + IF EXISTS ( + SELECT 1 FROM information_schema.columns + WHERE table_schema = DATABASE() AND table_name = p_table AND column_name = p_column + ) THEN + SET @ddl = CONCAT('ALTER TABLE `', p_table, '` DROP COLUMN `', p_column, '`'); + PREPARE stmt FROM @ddl; + EXECUTE stmt; + DEALLOCATE PREPARE stmt; + END IF; +END $$ + +CREATE PROCEDURE sp_v2_drop_index_if_exists( + IN p_table VARCHAR(64), + IN p_index VARCHAR(64) +) +BEGIN + IF EXISTS ( + SELECT 1 FROM information_schema.statistics + WHERE table_schema = DATABASE() AND table_name = p_table AND index_name = p_index + ) THEN + SET @ddl = CONCAT('ALTER TABLE `', p_table, '` DROP INDEX `', p_index, '`'); + PREPARE stmt FROM @ddl; + EXECUTE stmt; + DEALLOCATE PREPARE stmt; + END IF; +END $$ + +CREATE PROCEDURE sp_v2_add_index_if_not_exists( + IN p_table VARCHAR(64), + IN p_index VARCHAR(64), + IN p_columns VARCHAR(255) +) +BEGIN + IF NOT EXISTS ( + SELECT 1 FROM information_schema.statistics + WHERE table_schema = DATABASE() AND table_name = p_table AND index_name = p_index + ) THEN + SET @ddl = CONCAT('CREATE INDEX `', p_index, '` ON `', p_table, '` ', p_columns); + PREPARE stmt FROM @ddl; + EXECUTE stmt; + DEALLOCATE PREPARE stmt; + END IF; +END $$ + +CREATE PROCEDURE sp_v2_add_unique_index_if_not_exists( + IN p_table VARCHAR(64), + IN p_index VARCHAR(64), + IN p_columns VARCHAR(255) +) +BEGIN + IF NOT EXISTS ( + SELECT 1 FROM information_schema.statistics + WHERE table_schema = DATABASE() AND table_name = p_table AND index_name = p_index + ) THEN + SET @ddl = CONCAT('CREATE UNIQUE INDEX `', p_index, '` ON `', p_table, '` ', p_columns); + PREPARE stmt FROM @ddl; + EXECUTE stmt; + DEALLOCATE PREPARE stmt; + END IF; +END $$ + +DELIMITER ; + +CALL sp_v2_add_column_if_not_exists('t_user', 'phone_cipher', 'varchar(255) NULL COMMENT ''手机号密文(AES-GCM)'''); +CALL sp_v2_add_column_if_not_exists('t_user', 'phone_hash', 'char(64) NULL COMMENT ''手机号哈希(HMAC-SHA256,十六进制小写)'''); +CALL sp_v2_add_column_if_not_exists('t_user', 'contact_phone_cipher', 'varchar(255) NULL COMMENT ''联系电话密文(AES-GCM)'''); +CALL sp_v2_add_column_if_not_exists('t_user', 'contact_phone_hash', 'char(64) NULL COMMENT ''联系电话哈希(HMAC-SHA256,十六进制小写)'''); + +CALL sp_v2_drop_index_if_exists('t_user', 'idx_phone'); +CALL sp_v2_drop_column_if_exists('t_user', 'phone'); +CALL sp_v2_drop_column_if_exists('t_user', 'contact_phone'); + +-- MySQL 唯一索引允许多行 NULL,因此未绑定手机号的用户不受影响。 +CALL sp_v2_add_unique_index_if_not_exists('t_user', 'uk_user_phone_hash', '(phone_hash)'); +CALL sp_v2_add_index_if_not_exists('t_user', 'idx_user_contact_phone_hash', '(contact_phone_hash)'); + +DROP PROCEDURE IF EXISTS sp_v2_add_column_if_not_exists; +DROP PROCEDURE IF EXISTS sp_v2_drop_column_if_exists; +DROP PROCEDURE IF EXISTS sp_v2_drop_index_if_exists; +DROP PROCEDURE IF EXISTS sp_v2_add_index_if_not_exists; +DROP PROCEDURE IF EXISTS sp_v2_add_unique_index_if_not_exists; diff --git a/JC-ArtList-Core/src/main/resources/db/migration/V4__隐私政策与用户协议加密脱敏条款修订_20261104.sql b/JC-ArtList-Core/src/main/resources/db/migration/V4__隐私政策与用户协议加密脱敏条款修订_20261104.sql new file mode 100644 index 00000000..8dfb4456 --- /dev/null +++ b/JC-ArtList-Core/src/main/resources/db/migration/V4__隐私政策与用户协议加密脱敏条款修订_20261104.sql @@ -0,0 +1,110 @@ +-- 隐私政策与用户协议条款修订:对齐手机号/账号 AES-GCM 加密存储、HMAC 不可逆索引与按场景脱敏展示 +-- 版本:2026.11.04 +-- 说明:仅停用旧版本并新增协议版本,不修改已在任一环境执行的 V1 协议正文。 +-- 版本号说明:并行改造已占用 V3(账号加密与账号哈希),本次协议修订顺延为 V4。 + +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 + (313931273555138003, 'USER_TERMS', '用户协议', '2026.11.04', + '欢迎使用 JayuCloud ArtList。请在使用账号、预约、订单、会员、消息等功能前仔细阅读本协议。继续登录或注册即表示你已理解并同意平台基础服务规则、账号安全要求、订单预约规则和依法合规使用要求。本协议与《隐私政策》共同构成你使用本服务的基础规则。 + +一、协议接受与版本 +你在登录或注册前应完整阅读本协议和《隐私政策》并主动选择同意;不同意时不能完成注册或继续使用。本协议版本为 2026.11.04,自 2026 年 11 月 4 日起生效;协议发生重要变更时,我们会通过小程序提示并重新征得同意。 + +二、账号与安全 +1. 你应使用本人手机号注册和登录,手机号用于身份识别、验证码校验、订单联系和账号找回。 +2. 手机号与账号按《隐私政策》所述采用 AES-GCM 加密存储,并以 phone_hash/account_hash 不可逆索引支持登录与去重;客户端页面按场景展示脱敏或完整号码,完整号码仅限权限校验通过的必要业务场景。 +3. 你应妥善保管账号、验证码和登录设备,不得转借、出租、出售账号,不得绕过权限校验访问他人信息。 +4. 发现账号异常、手机号被冒用或验证码泄露时,应及时修改资料、解绑手机号并联系客服。 + +三、预约、订单与会员 +1. 预约与订单信息应真实、准确;你应确保填写的联系人手机号已获得联系人授权。 +2. 订单金额、会员余额、优惠券和售后规则以页面展示和门店确认为准;本平台当前不发起在线支付,充值档位仅作展示,实际充值、退款和余额变动由门店按线下流程处理。 +3. 不得利用订单、优惠券、会员权益进行虚假交易、套现、刷单或欺诈。 + +四、用户内容 +你上传的头像、作品图片、评价等内容应来源合法,不得包含违法、侵权、暴力、色情、欺诈或侵害他人权益的信息。你授予平台为提供服务所必需的展示、存储和处理权限;平台可对违规内容采取删除、屏蔽或限制功能等措施。 + +五、个人信息与保密 +1. 你不得收集、导出、转卖或向无关第三方提供通过平台获取的他人手机号、订单或会员信息。 +2. 完整手机号仅在本人资料维护、管理端编辑、门店或客服拨号等必要业务场景,且权限校验通过时由服务端使用,任何客户端页面不得作为批量获取完整号码的工具。 + +六、账号注销与数据留存 +1. 你可在小程序设置中申请注销;注销后账号不可登录,系统清除账号手机号密文和 phone_hash 索引,将账号标识替换为注销占位,并更新 account_hash。 +2. 订单、预约、会员余额、售后和交易记录在去除账号身份关联后,于实现目的所必需的最短期限内保存,当前产品目标为五年【待法务/业务确认】。 +3. 法律法规另有强制留存要求的,按法定期限保存。 + +七、未成年人 +不满 14 周岁的未成年人应在监护人同意和陪同下阅读并使用本服务;未取得监护人同意,不得注册或下单。 + +八、服务调整、责任与联系 +1. 我们会在合理范围内维护服务,并可能因升级、维护或合规要求调整功能;重要调整将提前告知。 +2. 因你违反本协议、法律法规或侵害他人权益造成的损失,由你依法承担;因不可抗力、网络故障或第三方服务异常造成的服务中断,我们将在合理范围内协助恢复。 +3. 隐私相关申请可从设置发起或联系在线客服;其他问题请联系运营方公布的客服渠道【待业务确认】。 + +本协议为产品说明文本,正式发布前应由运营方根据实际主体、业务和适用法律完成审核。', + 1, NOW(), NOW(), NOW(), 0), + (313931273555138004, 'PRIVACY_POLICY', '隐私政策', '2026.11.04', + 'JayuCloud ArtList 会在提供登录注册、预约下单、会员余额、消息通知和客户服务时处理必要的手机号、昵称、门店归属、订单与设备信息。本政策说明我们如何处理这些个人信息。 + +一、处理的信息及用途 +1. 登录与账号:你通过微信登录授权获取 OpenID 与 UnionID,用于识别和绑定账号;你主动授权手机号或输入手机号完成注册登录,手机号用于注册登录、验证码校验、订单联系、售后处理和账号找回,不用于营销。 +2. 账号标识:账号用于身份识别、权限校验和操作归属记录;账号与手机号均使用 AES-GCM 加密存储。 +3. 资料:昵称、头像仅在你主动补充或更新时处理。 +4. 业务信息:预约、订单、会员余额与余额变动、优惠券、售后、消息和客服记录,用于履行交易和服务。 +5. 安全运行:服务端处理网络地址、登录会话、客户端本地生成的随机设备标识和操作审计信息,用于登录安全、风险控制和审计;不采集 IMEI、MAC、通讯录、麦克风或持续定位。 +6. 内容与图片:你主动上传的头像、作品图片等文件存储于对象存储,用于资料展示和服务履约;本服务当前不接入第三方内容安全审核平台和地图服务,如后续启用将更新本政策并另行告知。 + +二、加密存储与检索索引 +1. 手机号与账号使用 AES-GCM 加密后落库,不以明文存入数据库;密文带版本标识。 +2. 加密密钥由服务端按环境独立管理,仅授权服务进程读取,不通过接口、日志或客户端对外提供。 +3. 为支持登录、去重和查询匹配,系统以 HMAC-SHA256 生成 phone_hash/account_hash 不可逆索引;该索引不能反推手机号或账号原文,不对外展示。 +4. 备份、导出和迁移沿用同等加密要求。 + +三、按场景脱敏展示 +1. 订单、预约、售后、消息、客户服务和后台列表等常规场景展示脱敏号码。 +2. 本人资料维护、管理端编辑、门店或客服拨号等必要业务联系场景,在登录态、门店或订单可见范围和权限校验通过时展示完整号码;完整号码不向无权限页面批量返回。 +3. 脱敏由服务端集中策略执行;客户端不得缓存、截屏传播或向无关第三方提供完整号码。 + +四、第三方共享 +我们仅在实现功能所必需时与以下第三方共享必要信息,不将其用于其他目的: +1. 微信:微信登录、手机号授权和订阅消息。 +2. 短信服务商:通过部署环境配置的 MessageHub 短信通道发送验证码、绑定/解绑和必要业务通知。 +3. 消息通道:通过 MessageHub 等已配置通道推送站内或订阅消息。 +4. 对象存储与 CDN:存储和分发头像、作品图片等文件,具体服务商按部署环境配置(七牛云、MinIO 或阿里云 OSS)。 +我们不会出售个人信息,也不会向无关第三方提供完整手机号。上线前,运营方应在微信后台隐私指引中逐项列明实际服务商名称、处理目的和字段范围【待法务/业务确认】。 + +五、保存期限与删除 +1. 账号注销:可在小程序设置中提交注销申请;注销后账号不可登录,系统清除账号手机号密文和 phone_hash 索引,将账号标识替换为注销占位,并更新 account_hash。 +2. 订单、预约、会员余额、售后和交易记录:在去除账号身份关联后,于实现目的所必需的最短期限内保存;当前产品目标为五年【待法务/业务确认】。 +3. 安全审计日志:按安全审计要求保存,具体期限【待法务/业务确认】。 +4. 法律法规另有强制留存要求的,按法定期限保存,并在期限届满后删除或匿名化。 + +六、你的权利 +1. 查询与更正:可在个人资料页查看和修改昵称、头像等资料;手机号可在设置中更换。 +2. 删除与注销:可在设置中申请注销;也可请求删除非交易必需的资料。 +3. 撤回同意:可在设置或联系客服撤回授权;撤回后不影响撤回前已进行的处理。 +4. 投诉与咨询:可联系在线客服或运营方公布的客服渠道【待业务确认】;我们将在收到请求后按适用法律规定的期限响应。 +5. 请注意:为保障交易安全,订单、余额和售后记录在法定或约定留存期内可能无法立即删除。 + +七、未成年人保护 +不满 14 周岁的未成年人应在监护人同意和陪同下阅读并使用本服务;未取得监护人同意,我们不会处理其个人信息。如发现误收集,将停止处理并删除。 + +八、安全措施与安全事件响应 +我们采取加密存储、访问控制、最小权限、会话撤销、操作审计等措施保护个人信息。发生或可能发生个人信息泄露、篡改、丢失时,我们将立即采取补救措施,并按适用法律要求向你和监管部门告知事件情况、可能影响、已采取措施和自主防范建议;通知方式包括小程序公告、短信或电话【待业务确认】。 + +九、跨境传输 +目前我们不涉及向境外提供个人信息。如未来发生跨境传输,将另行告知处理目的、接收方和联系方式,并依法取得单独同意或完成安全评估、备案等程序。 + +十、政策更新与联系 +本政策版本为 2026.11.04,自 2026 年 11 月 4 日起生效。处理目的、信息类别或第三方范围发生重要变化时,我们会更新版本并通过小程序提示、公告或重新征得同意等方式告知。你可在设置中查看当前版本;其他问题请联系在线客服或运营方公布的客服渠道【待业务确认】。 + +本文件是产品说明,不构成法律意见;上线前应由运营方或专业顾问结合实际处理活动审阅。', + 1, NOW(), NOW(), NOW(), 0); diff --git a/JC-ArtList-Core/src/main/resources/db/migration/V5__账号加密与账号哈希_20261104.sql b/JC-ArtList-Core/src/main/resources/db/migration/V5__账号加密与账号哈希_20261104.sql new file mode 100644 index 00000000..aca85eaf --- /dev/null +++ b/JC-ArtList-Core/src/main/resources/db/migration/V5__账号加密与账号哈希_20261104.sql @@ -0,0 +1,118 @@ +-- ============================================================ +-- ArtList V5:账号加密与账号哈希 +-- 日期:2026-11-04 +-- +-- 版本号说明:V3 从未在任何环境执行过;并行分支已先占用 V4 +-- (V4__隐私政策与用户协议加密脱敏条款修订_20261104.sql), +-- 在 out-of-order:false 前提下本文件使用 V5,保证 V1→V2→V4→V5 顺序天然正确。 +-- +-- 语义: +-- 1. t_user.account 列改为存放 AES-GCM 密文(enc:v1: 前缀),列名与 Salon 保持一致; +-- 2. 新增 account_hash(HMAC-SHA256 十六进制),并建立唯一索引 uk_user_account_hash, +-- 所有账号等值查询统一走 account_hash; +-- 3. 删除依赖明文 account 的唯一索引 uk_account; +-- 4. 不做 SQL 数据迁移:历史/种子账号(如 xiaowang)由应用启动时 +-- AccountHashBackfillRunner 加密并回填 hash。 +-- +-- 幂等:information_schema 判存在 + 存储过程,沿用 V2 风格;可安全重放。 +-- ============================================================ + +DROP PROCEDURE IF EXISTS sp_v5_add_column_if_not_exists; +DROP PROCEDURE IF EXISTS sp_v5_drop_index_if_exists; +DROP PROCEDURE IF EXISTS sp_v5_add_unique_index_if_not_exists; + +DELIMITER $$ + +CREATE PROCEDURE sp_v5_add_column_if_not_exists( + IN p_table_name VARCHAR(64), + IN p_column_name VARCHAR(64), + IN p_definition TEXT +) +BEGIN + IF NOT EXISTS ( + SELECT 1 + FROM information_schema.COLUMNS + WHERE TABLE_SCHEMA = DATABASE() + AND TABLE_NAME = p_table_name + AND COLUMN_NAME = p_column_name + ) THEN + SET @sql = CONCAT( + 'ALTER TABLE `', p_table_name, '` ADD COLUMN `', p_column_name, '` ', + p_definition + ); + PREPARE stmt FROM @sql; + EXECUTE stmt; + DEALLOCATE PREPARE stmt; + END IF; +END$$ + +CREATE PROCEDURE sp_v5_drop_index_if_exists( + IN p_table_name VARCHAR(64), + IN p_index_name VARCHAR(64) +) +BEGIN + IF EXISTS ( + SELECT 1 + FROM information_schema.STATISTICS + WHERE TABLE_SCHEMA = DATABASE() + AND TABLE_NAME = p_table_name + AND INDEX_NAME = p_index_name + ) THEN + SET @sql = CONCAT( + 'ALTER TABLE `', p_table_name, '` DROP INDEX `', p_index_name, '`' + ); + PREPARE stmt FROM @sql; + EXECUTE stmt; + DEALLOCATE PREPARE stmt; + END IF; +END$$ + +CREATE PROCEDURE sp_v5_add_unique_index_if_not_exists( + IN p_table_name VARCHAR(64), + IN p_index_name VARCHAR(64), + IN p_columns TEXT +) +BEGIN + IF NOT EXISTS ( + SELECT 1 + FROM information_schema.STATISTICS + WHERE TABLE_SCHEMA = DATABASE() + AND TABLE_NAME = p_table_name + AND INDEX_NAME = p_index_name + ) THEN + SET @sql = CONCAT( + 'ALTER TABLE `', p_table_name, '` ADD UNIQUE INDEX `', p_index_name, '` ', + p_columns + ); + PREPARE stmt FROM @sql; + EXECUTE stmt; + DEALLOCATE PREPARE stmt; + END IF; +END$$ + +DELIMITER ; + +-- 1. 账号列改为密文容器(与 Salon 对齐:varchar(128) NULL) +ALTER TABLE t_user + MODIFY COLUMN account varchar(128) NULL COMMENT '账号AES-GCM密文(enc:v1: 前缀)'; + +-- 2. 新增账号 HMAC 索引列 +CALL sp_v5_add_column_if_not_exists( + 't_user', + 'account_hash', + "char(64) NULL COMMENT '账号HMAC-SHA256索引'" +); + +-- 3. 删除依赖明文账号的唯一索引 +CALL sp_v5_drop_index_if_exists('t_user', 'uk_account'); + +-- 4. 新增账号哈希唯一索引(MySQL 唯一索引允许多行 NULL) +CALL sp_v5_add_unique_index_if_not_exists( + 't_user', + 'uk_user_account_hash', + '(account_hash)' +); + +DROP PROCEDURE IF EXISTS sp_v5_add_column_if_not_exists; +DROP PROCEDURE IF EXISTS sp_v5_drop_index_if_exists; +DROP PROCEDURE IF EXISTS sp_v5_add_unique_index_if_not_exists; diff --git a/JC-ArtList-Core/src/main/resources/db/migration/V6__协议文本改为全场景脱敏与单次拨号取号_20261104.sql b/JC-ArtList-Core/src/main/resources/db/migration/V6__协议文本改为全场景脱敏与单次拨号取号_20261104.sql new file mode 100644 index 00000000..b568cffd --- /dev/null +++ b/JC-ArtList-Core/src/main/resources/db/migration/V6__协议文本改为全场景脱敏与单次拨号取号_20261104.sql @@ -0,0 +1,119 @@ +-- V6:协议文本改为全场景脱敏与单次拨号取号 +-- 版本:2026.11.04-R2 +-- 说明:V4 已发布 2026.11.04 版本协议文本;本次仅新增修订版本并停用旧版本,不修改 V1/V2/V4 文件内容。 +-- 变更点:所有推送前端的号码一律脱敏;电话联系改为按需单次拨号取号,可对接隐私号码且未配置时明确不可用。 + +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 + (313931273555138005, 'USER_TERMS', '用户协议', '2026.11.04-R2', + '欢迎使用 JayuCloud ArtList。请在使用账号、预约、订单、会员、消息等功能前仔细阅读本协议。继续登录或注册即表示你已理解并同意平台基础服务规则、账号安全要求、订单预约规则和依法合规使用要求。本协议与《隐私政策》共同构成你使用本服务的基础规则。 + +一、协议接受与版本 +你在登录或注册前应完整阅读本协议和《隐私政策》并主动选择同意;不同意时不能完成注册或继续使用。本协议版本为 2026.11.04-R2,自 2026 年 11 月 4 日起生效;协议发生重要变更时,我们会通过小程序提示并重新征得同意。 + +二、账号与安全 +1. 你应使用本人手机号注册和登录,手机号用于身份识别、验证码校验、订单联系和账号找回。 +2. 手机号与账号按《隐私政策》所述采用 AES-GCM 加密存储,并以 phone_hash/account_hash 不可逆索引支持登录与去重;客户端页面一律展示脱敏号码,需要电话联系时通过单次拨号取号接口按需获取当次可拨号码,该接口可对接隐私号码且不会回退为真实号码。 +3. 你应妥善保管账号、验证码和登录设备,不得转借、出租、出售账号,不得绕过权限校验访问他人信息。 +4. 发现账号异常、手机号被冒用或验证码泄露时,应及时修改资料、解绑手机号并联系客服。 + +三、预约、订单与会员 +1. 预约与订单信息应真实、准确;你应确保填写的联系人手机号已获得联系人授权。 +2. 订单金额、会员余额、优惠券和售后规则以页面展示和门店确认为准;本平台当前不发起在线支付,充值档位仅作展示,实际充值、退款和余额变动由门店按线下流程处理。 +3. 不得利用订单、优惠券、会员权益进行虚假交易、套现、刷单或欺诈。 + +四、用户内容 +你上传的头像、作品图片、评价等内容应来源合法,不得包含违法、侵权、暴力、色情、欺诈或侵害他人权益的信息。你授予平台为提供服务所必需的展示、存储和处理权限;平台可对违规内容采取删除、屏蔽或限制功能等措施。 + +五、个人信息与保密 +1. 你不得收集、导出、转卖或向无关第三方提供通过平台获取的他人手机号、订单或会员信息。 +2. 任何客户端页面均不展示完整手机号;需要电话联系时,仅在登录态与可见范围、权限校验通过后通过单次拨号取号接口获取当次可拨号码,平台不向客户端批量返回、缓存或提供长期有效的号码。 + +六、账号注销与数据留存 +1. 你可在小程序设置中申请注销;注销后账号不可登录,系统清除账号手机号密文、联系电话密文及相关哈希索引,将账号标识替换为注销占位,并更新 account_hash。 +2. 订单、预约、会员余额、售后和交易记录在去除账号身份关联后,于实现目的所必需的最短期限内保存,当前产品目标为五年【待法务/业务确认】。 +3. 法律法规另有强制留存要求的,按法定期限保存。 + +七、未成年人 +不满 14 周岁的未成年人应在监护人同意和陪同下阅读并使用本服务;未取得监护人同意,不得注册或下单。 + +八、服务调整、责任与联系 +1. 我们会在合理范围内维护服务,并可能因升级、维护或合规要求调整功能;重要调整将提前告知。 +2. 因你违反本协议、法律法规或侵害他人权益造成的损失,由你依法承担;因不可抗力、网络故障或第三方服务异常造成的服务中断,我们将在合理范围内协助恢复。 +3. 隐私相关申请可从设置发起或联系在线客服;其他问题请联系运营方公布的客服渠道【待业务确认】。 + +本协议为产品说明文本,正式发布前应由运营方根据实际主体、业务和适用法律完成审核。', + 1, NOW(), NOW(), NOW(), 0), + (313931273555138006, 'PRIVACY_POLICY', '隐私政策', '2026.11.04-R2', + 'JayuCloud ArtList 会在提供登录注册、预约下单、会员余额、消息通知和客户服务时处理必要的手机号、昵称、门店归属、订单与设备信息。本政策说明我们如何处理这些个人信息。 + +一、处理的信息及用途 +1. 登录与账号:你通过微信登录授权获取 OpenID 与 UnionID,用于识别和绑定账号;你主动授权手机号或输入手机号完成注册登录,手机号用于注册登录、验证码校验、订单联系、售后处理和账号找回,不用于营销。 +2. 账号标识:账号用于身份识别、权限校验和操作归属记录;账号与手机号均使用 AES-GCM 加密存储。 +3. 资料:昵称、头像仅在你主动补充或更新时处理。 +4. 业务信息:预约、订单、会员余额与余额变动、优惠券、售后、消息和客服记录,用于履行交易和服务。 +5. 安全运行:服务端处理网络地址、登录会话、客户端本地生成的随机设备标识和操作审计信息,用于登录安全、风险控制和审计;不采集 IMEI、MAC、通讯录、麦克风或持续定位。 +6. 内容与图片:你主动上传的头像、作品图片等文件存储于对象存储,用于资料展示和服务履约;本服务当前不接入第三方内容安全审核平台和地图服务,如后续启用将更新本政策并另行告知。 + +二、加密存储与检索索引 +1. 手机号与账号使用 AES-GCM 加密后落库,不以明文存入数据库;密文带版本标识。 +2. 加密密钥由服务端按环境独立管理,仅授权服务进程读取,不通过接口、日志或客户端对外提供。 +3. 为支持登录、去重和查询匹配,系统以 HMAC-SHA256 生成 phone_hash/account_hash 不可逆索引;该索引不能反推手机号或账号原文,不对外展示。 +4. 备份、导出和迁移沿用同等加密要求。 + +三、全场景脱敏与单次拨号取号 +1. 本人资料、管理端列表与编辑、订单、预约、售后、消息、客户服务和后台列表等所有返回客户端的场景,一律展示脱敏号码与脱敏账号;服务端不对客户端返回完整手机号。 +2. 需要电话联系时,客户端在点击联系入口后调用单次拨号取号接口;服务端按场景校验登录态、订单归属、门店可见范围与权限后,返回当次可拨号码或隐私号码,响应带有效期标识,前端不缓存、不落库、不写入日志。 +3. 平台可对接隐私号码服务;未配置隐私号码时接口明确返回不可用错误,不会回退为真实号码。 +4. 日志、审计、消息记录与缓存不得保存完整手机号或完整账号;审计仅记录操作人、时间、场景与结果。 + +四、第三方共享 +我们仅在实现功能所必需时与以下第三方共享必要信息,不将其用于其他目的: +1. 微信:微信登录、手机号授权和订阅消息。 +2. 短信服务商:通过部署环境配置的 MessageHub 短信通道发送验证码、绑定/解绑和必要业务通知。 +3. 消息通道:通过 MessageHub 等已配置通道推送站内或订阅消息。 +4. 对象存储与 CDN:存储和分发头像、作品图片等文件,具体服务商按部署环境配置(七牛云、MinIO 或阿里云 OSS)。 +我们不会出售个人信息,也不会向无关第三方提供完整手机号。上线前,运营方应在微信后台隐私指引中逐项列明实际服务商名称、处理目的和字段范围【待法务/业务确认】。 + +五、保存期限与删除 +1. 账号注销:可在小程序设置中提交注销申请;注销后账号不可登录,系统清除账号手机号密文、联系电话密文及相关哈希索引,将账号标识替换为注销占位,并更新 account_hash。 +2. 订单、预约、会员余额、售后和交易记录:在去除账号身份关联后,于实现目的所必需的最短期限内保存;当前产品目标为五年【待法务/业务确认】。 +3. 安全审计日志:按安全审计要求保存,具体期限【待法务/业务确认】。 +4. 法律法规另有强制留存要求的,按法定期限保存,并在期限届满后删除或匿名化。 + +六、你的权利 +1. 查询与更正:可在个人资料页查看和修改昵称、头像等资料;手机号可在设置中更换,展示值为脱敏值。 +2. 删除与注销:可在设置中申请注销;也可请求删除非交易必需的资料。 +3. 撤回同意:可在设置或联系客服撤回授权;撤回后不影响撤回前已进行的处理。 +4. 投诉与咨询:可联系在线客服或运营方公布的客服渠道【待业务确认】;我们将在收到请求后按适用法律规定的期限响应。 +5. 请注意:为保障交易安全,订单、余额和售后记录在法定或约定留存期内可能无法立即删除。 + +七、未成年人保护 +不满 14 周岁的未成年人应在监护人同意和陪同下阅读并使用本服务;未取得监护人同意,我们不会处理其个人信息。如发现误收集,将停止处理并删除。 + +八、安全措施与安全事件响应 +我们采取加密存储、访问控制、最小权限、会话撤销、操作审计等措施保护个人信息。发生或可能发生个人信息泄露、篡改、丢失时,我们将立即采取补救措施,并按适用法律要求向你和监管部门告知事件情况、可能影响、已采取措施和自主防范建议;通知方式包括小程序公告、短信或电话【待业务确认】。 + +九、跨境传输 +目前我们不涉及向境外提供个人信息。如未来发生跨境传输,将另行告知处理目的、接收方和联系方式,并依法取得单独同意或完成安全评估、备案等程序。 + +十、政策更新与联系 +本政策版本为 2026.11.04-R2,自 2026 年 11 月 4 日起生效。处理目的、信息类别或第三方范围发生重要变化时,我们会更新版本并通过小程序提示、公告或重新征得同意等方式告知。你可在设置中查看当前版本;其他问题请联系在线客服或运营方公布的客服渠道【待业务确认】。 + +本文件是产品说明,不构成法律意见;上线前应由运营方或专业顾问结合实际处理活动审阅。', + 1, NOW(), NOW(), NOW(), 0) +ON DUPLICATE KEY UPDATE + title = VALUES(title), + content = VALUES(content), + status = VALUES(status), + effective_time = VALUES(effective_time), + is_delete = 0, + update_time = NOW(); diff --git a/JC-ArtList-Core/src/test/java/com/xiaowang/jayucloud/artlist/core/modules/shop/controller/front/ContactDialControllerTest.java b/JC-ArtList-Core/src/test/java/com/xiaowang/jayucloud/artlist/core/modules/shop/controller/front/ContactDialControllerTest.java new file mode 100644 index 00000000..dd039d27 --- /dev/null +++ b/JC-ArtList-Core/src/test/java/com/xiaowang/jayucloud/artlist/core/modules/shop/controller/front/ContactDialControllerTest.java @@ -0,0 +1,92 @@ +package com.xiaowang.jayucloud.artlist.core.modules.shop.controller.front; + +import com.xiaowang.jayucloud.artlist.core.common.BusinessException; +import com.xiaowang.jayucloud.artlist.core.modules.security.service.SecurityAuditLogService; +import com.xiaowang.jayucloud.artlist.core.modules.shop.dto.DialRequestDTO; +import com.xiaowang.jayucloud.artlist.core.modules.shop.service.ContactDialService; +import com.xiaowang.jayucloud.artlist.core.modules.shop.service.ContactInfoService; +import com.xiaowang.jayucloud.artlist.core.modules.shop.vo.DialResponseVO; +import com.xiaowang.jayucloud.artlist.core.support.security.RequestThrottleService; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; +import org.springframework.mock.web.MockHttpServletRequest; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +@ExtendWith(MockitoExtension.class) +class ContactDialControllerTest { + @Mock + private ContactInfoService contactInfoService; + @Mock + private ContactDialService contactDialService; + @Mock + private RequestThrottleService requestThrottleService; + @Mock + private SecurityAuditLogService securityAuditLogService; + + private ContactInfoController controller; + private MockHttpServletRequest request; + + @BeforeEach + void setUp() { + controller = new ContactInfoController(contactInfoService, contactDialService, requestThrottleService, + securityAuditLogService); + request = new MockHttpServletRequest(); + } + + @Test + void rejectsAnonymousCallerWith403() { + DialRequestDTO dialRequestDTO = new DialRequestDTO(); + dialRequestDTO.setScene("PLATFORM"); + + BusinessException exception = assertThrows(BusinessException.class, () -> + controller.dial(request, dialRequestDTO)); + + assertEquals(403, exception.getCode()); + verify(contactDialService, never()).dial(any(), any()); + } + + @Test + void successRecordsAuditWithoutNumber() { + request.setAttribute("userId", 1L); + request.setAttribute("account", "xiaowang"); + DialRequestDTO dialRequestDTO = new DialRequestDTO(); + dialRequestDTO.setScene("SHOP_MANAGER"); + dialRequestDTO.setTargetId(88L); + DialResponseVO response = new DialResponseVO(); + response.setMode("DIRECT"); + response.setDialNumber("13800000000"); + response.setExpiresInSeconds(300); + when(contactDialService.dial(eq(1L), any())).thenReturn(response); + + controller.dial(request, dialRequestDTO); + + verify(requestThrottleService).checkContactDial(request, 1L); + verify(securityAuditLogService).record(eq(1L), eq("xiaowang"), eq("CONTACT_DIAL_SHOP_MANAGER"), + eq("SUCCESS"), eq(null), eq(request)); + } + + @Test + void throttledRequestDoesNotReachDialService() { + request.setAttribute("userId", 1L); + DialRequestDTO dialRequestDTO = new DialRequestDTO(); + dialRequestDTO.setScene("PLATFORM"); + org.mockito.Mockito.doThrow(new RuntimeException("拨号取号过于频繁,请稍后再试")) + .when(requestThrottleService).checkContactDial(request, 1L); + + RuntimeException exception = assertThrows(RuntimeException.class, () -> + controller.dial(request, dialRequestDTO)); + + assertEquals("拨号取号过于频繁,请稍后再试", exception.getMessage()); + verify(contactDialService, never()).dial(any(), any()); + } +} diff --git a/JC-ArtList-Core/src/test/java/com/xiaowang/jayucloud/artlist/core/modules/shop/service/impl/ContactDialServiceTest.java b/JC-ArtList-Core/src/test/java/com/xiaowang/jayucloud/artlist/core/modules/shop/service/impl/ContactDialServiceTest.java new file mode 100644 index 00000000..25ae3f82 --- /dev/null +++ b/JC-ArtList-Core/src/test/java/com/xiaowang/jayucloud/artlist/core/modules/shop/service/impl/ContactDialServiceTest.java @@ -0,0 +1,131 @@ +package com.xiaowang.jayucloud.artlist.core.modules.shop.service.impl; + +import com.xiaowang.jayucloud.artlist.core.common.BusinessException; +import com.xiaowang.jayucloud.artlist.core.config.DialProperties; +import com.xiaowang.jayucloud.artlist.core.modules.order.entity.OrderDO; +import com.xiaowang.jayucloud.artlist.core.modules.order.mapper.OrderItemMapper; +import com.xiaowang.jayucloud.artlist.core.modules.order.mapper.OrderMapper; +import com.xiaowang.jayucloud.artlist.core.modules.product.mapper.ProductMapper; +import com.xiaowang.jayucloud.artlist.core.modules.shop.dto.DialRequestDTO; +import com.xiaowang.jayucloud.artlist.core.modules.shop.mapper.ShopMapper; +import com.xiaowang.jayucloud.artlist.core.modules.shop.support.UserShopBindingSupport; +import com.xiaowang.jayucloud.artlist.core.modules.shop.support.dial.DialTargetProvider; +import com.xiaowang.jayucloud.artlist.core.modules.shop.support.dial.DirectDialTargetProvider; +import com.xiaowang.jayucloud.artlist.core.modules.shop.support.dial.PlaceholderPrivacyNumberProvider; +import com.xiaowang.jayucloud.artlist.core.modules.shop.vo.DialResponseVO; +import com.xiaowang.jayucloud.artlist.core.modules.user.entity.UserDO; +import com.xiaowang.jayucloud.artlist.core.modules.user.mapper.UserMapper; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; + +import java.util.Arrays; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.when; + +@ExtendWith(MockitoExtension.class) +class ContactDialServiceTest { + + @Mock + private UserMapper userMapper; + @Mock + private ShopMapper shopMapper; + @Mock + private ProductMapper productMapper; + @Mock + private OrderMapper orderMapper; + @Mock + private OrderItemMapper orderItemMapper; + @Mock + private UserShopBindingSupport userShopBindingSupport; + + private DialProperties dialProperties; + private ContactDialServiceImpl contactDialService; + + @BeforeEach + void setUp() { + dialProperties = new DialProperties(); + dialProperties.setProvider("direct"); + DialTargetProvider[] providers = { + new DirectDialTargetProvider(), + new PlaceholderPrivacyNumberProvider() + }; + contactDialService = new ContactDialServiceImpl(userMapper, shopMapper, productMapper, orderMapper, + orderItemMapper, userShopBindingSupport, dialProperties, Arrays.asList(providers)); + } + + @Test + void rejectsAnonymousCallerWith403() { + BusinessException exception = assertThrows(BusinessException.class, () -> + contactDialService.dial(null, platformRequest())); + assertEquals(403, exception.getCode()); + } + + @Test + void platformSceneReturnsDirectNumber() { + UserDO caller = user(1L, 1); + UserDO admin = user(9L, 4); + admin.setPhone("13800000000"); + when(userMapper.selectById(1L)).thenReturn(caller); + when(userMapper.selectOne(any())).thenReturn(admin); + + DialResponseVO response = contactDialService.dial(1L, platformRequest()); + + assertEquals("DIRECT", response.getMode()); + assertEquals("13800000000", response.getDialNumber()); + } + + @Test + void orderArtistRejectsOrderOfOtherUser() { + UserDO caller = user(1L, 1); + OrderDO order = new OrderDO(); + order.setId(100L); + order.setUserId(2L); + order.setIsDelete(0); + when(userMapper.selectById(1L)).thenReturn(caller); + when(orderMapper.selectById(100L)).thenReturn(order); + + DialRequestDTO request = new DialRequestDTO(); + request.setScene("ORDER_ARTIST"); + request.setTargetId(100L); + + BusinessException exception = assertThrows(BusinessException.class, () -> + contactDialService.dial(1L, request)); + assertEquals(403, exception.getCode()); + } + + @Test + void privacyNumberProviderNeverFallsBackToRealNumber() { + dialProperties.setProvider("privacy-number"); + UserDO caller = user(1L, 1); + UserDO admin = user(9L, 4); + admin.setPhone("13800000000"); + when(userMapper.selectById(1L)).thenReturn(caller); + when(userMapper.selectOne(any())).thenReturn(admin); + + BusinessException exception = assertThrows(BusinessException.class, () -> + contactDialService.dial(1L, platformRequest())); + + assertEquals(PlaceholderPrivacyNumberProvider.NOT_CONFIGURED_CODE, exception.getCode()); + } + + private DialRequestDTO platformRequest() { + DialRequestDTO request = new DialRequestDTO(); + request.setScene("PLATFORM"); + return request; + } + + private UserDO user(Long id, Integer type) { + UserDO user = new UserDO(); + user.setId(id); + user.setType(type); + user.setIsDelete(0); + user.setStatus(1); + return user; + } +} diff --git a/JC-ArtList-Core/src/test/java/com/xiaowang/jayucloud/artlist/core/support/privacy/PhoneCryptoTest.java b/JC-ArtList-Core/src/test/java/com/xiaowang/jayucloud/artlist/core/support/privacy/PhoneCryptoTest.java new file mode 100644 index 00000000..51221fda --- /dev/null +++ b/JC-ArtList-Core/src/test/java/com/xiaowang/jayucloud/artlist/core/support/privacy/PhoneCryptoTest.java @@ -0,0 +1,88 @@ +package com.xiaowang.jayucloud.artlist.core.support.privacy; + +import com.xiaowang.jayucloud.artlist.core.config.PhoneCryptoProperties; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNotEquals; +import static org.junit.jupiter.api.Assertions.assertTrue; + +class PhoneCryptoTest { + + private static final String ENCRYPTION_KEY = "Y+Y5vAG/yUVDEvEQ3L5IQOO1ZFsbJp6l4wvrNR69mKM="; + private static final String INDEX_KEY = "4/wLgcudBE8XNVBjnUle1A2H1L0ePV0rKUbX3VFeAzU="; + + private PhoneCrypto phoneCrypto; + + @BeforeEach + void setUp() { + PhoneCryptoProperties properties = new PhoneCryptoProperties(); + properties.setEncryptionKey(ENCRYPTION_KEY); + properties.setIndexKey(INDEX_KEY); + phoneCrypto = new PhoneCrypto(properties); + phoneCrypto.initialize(); + } + + @Test + void encryptAndDecryptRoundTrip() { + String phone = "13800000000"; + String cipher = phoneCrypto.encrypt(phone); + assertTrue(cipher.startsWith("enc:v1:")); + assertEquals(phone, phoneCrypto.decrypt(cipher)); + assertNotEquals(cipher, phoneCrypto.encrypt(phone), "随机IV使同一明文的密文不同"); + } + + @Test + void hashIsStableForSamePhone() { + String phone = "13800000000"; + String first = phoneCrypto.index(phone); + String second = phoneCrypto.index(phone); + assertEquals(first, second); + assertEquals(64, first.length()); + assertEquals(first, first.toLowerCase()); + } + + @Test + void normalizationOnlyTrimsToMatchSalon() { + assertEquals(phoneCrypto.index("13800000000"), phoneCrypto.index(" 13800000000 ")); + assertNotEquals(phoneCrypto.index("13800000000"), phoneCrypto.index("+8613800000000")); + assertNotEquals(phoneCrypto.index("13800000000"), phoneCrypto.index("138-0000-0000")); + assertFalse(phoneCrypto.isMobilePhone("+8613800000000")); + assertFalse(phoneCrypto.isMobilePhone("138-0000-0000")); + assertTrue(phoneCrypto.isMobilePhone("13800000000")); + } + + @Test + void hashOfUnknownPhoneDoesNotMatchRegisteredPhone() { + assertNotEquals(phoneCrypto.index("13900000000"), phoneCrypto.index("13800000000")); + } + + @Test + void maskKeepsPrefixAndSuffix() { + assertEquals("138****0000", phoneCrypto.mask("13800000000")); + assertEquals("138****0000", phoneCrypto.mask(phoneCrypto.encrypt("13800000000"))); + assertEquals("zhangsan", phoneCrypto.mask("zhangsan")); + } + + @Test + void accountIsAlwaysEncryptedAndDecryptsBack() { + String account = "xiaowang"; + String cipher = phoneCrypto.encryptAccount(account); + assertTrue(cipher.startsWith("enc:v1:")); + assertEquals(account, phoneCrypto.decryptAccount(cipher)); + // 数值型自定义账号同样加密,不采用 Salon 的"仅手机号形态加密"条件 + String digitAccount = "20261104"; + assertTrue(phoneCrypto.encryptAccount(digitAccount).startsWith("enc:v1:")); + assertEquals(digitAccount, phoneCrypto.decryptAccount(phoneCrypto.encryptAccount(digitAccount))); + } + + @Test + void legacyPlainAccountIsReadableAndHashIsStable() { + // V1 种子账号历史上是明文,无 enc:v1: 前缀时原样返回 + assertEquals("xiaowang", phoneCrypto.decryptAccount("xiaowang")); + assertEquals(phoneCrypto.index("xiaowang"), phoneCrypto.index(" xiaowang ")); + assertEquals(64, phoneCrypto.index("xiaowang").length()); + } +} diff --git a/JC-ArtList-Core/src/test/java/com/xiaowang/jayucloud/artlist/core/support/privacy/SensitiveFieldPolicyTest.java b/JC-ArtList-Core/src/test/java/com/xiaowang/jayucloud/artlist/core/support/privacy/SensitiveFieldPolicyTest.java new file mode 100644 index 00000000..521b76de --- /dev/null +++ b/JC-ArtList-Core/src/test/java/com/xiaowang/jayucloud/artlist/core/support/privacy/SensitiveFieldPolicyTest.java @@ -0,0 +1,55 @@ +package com.xiaowang.jayucloud.artlist.core.support.privacy; + +import com.xiaowang.jayucloud.artlist.core.config.PhoneCryptoProperties; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; + +import static org.junit.jupiter.api.Assertions.assertEquals; + +class SensitiveFieldPolicyTest { + + private static final String ENCRYPTION_KEY = "Y+Y5vAG/yUVDEvEQ3L5IQOO1ZFsbJp6l4wvrNR69mKM="; + private static final String INDEX_KEY = "4/wLgcudBE8XNVBjnUle1A2H1L0ePV0rKUbX3VFeAzU="; + private static final String PHONE = "13800000000"; + + @BeforeEach + void setUp() { + PhoneCryptoProperties properties = new PhoneCryptoProperties(); + properties.setEncryptionKey(ENCRYPTION_KEY); + properties.setIndexKey(INDEX_KEY); + PhoneCrypto crypto = new PhoneCrypto(properties); + crypto.initialize(); + } + + @Test + void phoneIsMaskedInEveryScenario() { + assertEquals("138****0000", SensitiveFieldPolicy.phone(PHONE, SensitiveFieldPolicy.Scenario.SELF_PROFILE)); + assertEquals("138****0000", SensitiveFieldPolicy.phone(PHONE, SensitiveFieldPolicy.Scenario.ADMIN_LIST)); + assertEquals("138****0000", SensitiveFieldPolicy.phone(PHONE, SensitiveFieldPolicy.Scenario.THIRD_PARTY)); + assertEquals("138****0000", SensitiveFieldPolicy.phone(PHONE, SensitiveFieldPolicy.Scenario.DIAL)); + assertEquals("138****0000", SensitiveFieldPolicy.phone(PHONE, SensitiveFieldPolicy.Scenario.LOG)); + assertEquals("138****0000", SensitiveFieldPolicy.phone(PhoneCrypto.current().encrypt(PHONE), SensitiveFieldPolicy.Scenario.DIAL)); + } + + @Test + void accountIsMaskedInEveryScenario() { + assertEquals("xi***", SensitiveFieldPolicy.account("xiaowang", SensitiveFieldPolicy.Scenario.SELF_PROFILE)); + assertEquals("xi***", SensitiveFieldPolicy.account("xiaowang", SensitiveFieldPolicy.Scenario.ADMIN_LIST)); + assertEquals("xi***", SensitiveFieldPolicy.account("xiaowang", SensitiveFieldPolicy.Scenario.THIRD_PARTY)); + assertEquals("xi***", SensitiveFieldPolicy.account("xiaowang", SensitiveFieldPolicy.Scenario.DIAL)); + assertEquals("xi***", SensitiveFieldPolicy.account("xiaowang", SensitiveFieldPolicy.Scenario.LOG)); + assertEquals("138****0000", SensitiveFieldPolicy.account(PHONE, SensitiveFieldPolicy.Scenario.ADMIN_LIST)); + assertEquals("***", SensitiveFieldPolicy.account("ab", SensitiveFieldPolicy.Scenario.LOG)); + } + + @Test + void encryptedAccountIsMaskedAfterDecrypt() { + assertEquals("xi***", SensitiveFieldPolicy.account(PhoneCrypto.current().encryptAccount("xiaowang"), SensitiveFieldPolicy.Scenario.SELF_PROFILE)); + } + + @Test + void nullAndBlankValuesStayUnchanged() { + assertEquals(null, SensitiveFieldPolicy.phone(null, SensitiveFieldPolicy.Scenario.LOG)); + assertEquals("", SensitiveFieldPolicy.account("", SensitiveFieldPolicy.Scenario.ADMIN_LIST)); + } +} diff --git a/JC-ArtList-Frontend/src/api/user.ts b/JC-ArtList-Frontend/src/api/user.ts index 4c6fc5df..d7de3af3 100644 --- a/JC-ArtList-Frontend/src/api/user.ts +++ b/JC-ArtList-Frontend/src/api/user.ts @@ -202,7 +202,8 @@ export interface InviteCodeVO { * Usage: import, call, read, or update this interface from the owning page/module while preserving the surrounding loading and permission flow. */ export interface UpdatePhoneRequest { - oldPhone: string + /** 兼容旧协议保留;服务端按当前登录用户取原手机号,不再使用该字段。 */ + oldPhone?: string newPhone: string verificationCode: string } @@ -319,6 +320,20 @@ export interface ContactInfoVO { platformContactText?: string } +/** + * 拨号场景:与后端 /contact-info/dial 的 scene 取值一致。 + */ +export type ContactDialScene = 'SHOP_MANAGER' | 'ORDER_ARTIST' | 'PRODUCT_ARTIST' | 'PLATFORM' + +/** + * 单次拨号取号结果;DIRECT 为直拨真实号码,PRIVACY_NUMBER 为隐私号码。 + */ +export interface DialContactResult { + mode: 'DIRECT' | 'PRIVACY_NUMBER' + dialNumber: string + expiresInSeconds: number +} + /** * userApi groups all API calls for this page domain. * Call guide: pass the typed payload or identifier into the method below, and use the returned Promise in the page script. @@ -385,7 +400,7 @@ export const userApi = { * Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller. * @param data: { phone: string; sceneCode?: string } caller-supplied value for `data: { phone: string; sceneCode?: string }` */ - sendVerificationCode: (data: { phone: string; sceneCode?: string }) => { + sendVerificationCode: (data: { phone?: string; sceneCode?: string }) => { return api.post('/user/send-verification-code', data) }, /** @@ -459,6 +474,10 @@ export const userApi = { getPlatformContact: async (): Promise => { return await api.get('/contact-info/platform') as unknown as ContactInfoVO }, + // 单次拨号取号:号码不缓存到本地,拨号完成后即丢弃。 + dialContact: async (scene: ContactDialScene, targetId?: IdType, artistId?: IdType): Promise => { + return await api.post('/contact-info/dial', { scene, targetId, artistId }) as unknown as DialContactResult + }, /** * `deactivateAccount` API call. Use this method from the page script to invoke the backend endpoint tied to this feature. * Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller. diff --git a/JC-ArtList-Frontend/src/views/AccountSettingsView.vue b/JC-ArtList-Frontend/src/views/AccountSettingsView.vue index 712fb84c..6fa473f1 100644 --- a/JC-ArtList-Frontend/src/views/AccountSettingsView.vue +++ b/JC-ArtList-Frontend/src/views/AccountSettingsView.vue @@ -625,8 +625,8 @@ const handleChangePhoneSubmit = async () => { changePhoneLoading.value = true try { await runWithGlobalLoading(async () => { + // 原手机号由服务端按当前登录用户读取,前端不再回传可能已脱敏的号码。 await userApi.updatePhone({ - oldPhone: userInfo.value.phone!, newPhone: changePhoneForm.newPhone, verificationCode: changePhoneForm.verificationCode }) diff --git a/JC-ArtList-Frontend/src/views/HelpView.vue b/JC-ArtList-Frontend/src/views/HelpView.vue index 3e503e01..e19c4656 100644 --- a/JC-ArtList-Frontend/src/views/HelpView.vue +++ b/JC-ArtList-Frontend/src/views/HelpView.vue @@ -9,6 +9,20 @@ import { BRAND_CONFIG } from '@/config/brand' const router = useRouter() const loading = ref(false) const contact = ref(null) +const dialing = ref(false) + +/** 平台客服拨号:点击后才单次取号,号码不落页面状态。 */ +const dialPlatform = async () => { + dialing.value = true + try { + const result = await userApi.dialContact('PLATFORM') + window.location.href = `tel:${result.dialNumber}` + } catch (error: any) { + message.error(error?.message || '获取客服号码失败') + } finally { + dialing.value = false + } +} const loadContact = async () => { loading.value = true @@ -46,7 +60,9 @@ onMounted(loadContact)

平台联系信息

{{ contact.contactName }} {{ contact.roleLabel || '' }}

-

电话:{{ contact.phone }}

+

+ 拨打客服电话 +

微信:{{ contact.wechatId }}

{{ contact.platformContactText }}

暂无可展示的客服信息,请稍后重试或通过订单详情联系服务人员。

diff --git a/JC-ArtList-Frontend/src/views/OrderDetailView.vue b/JC-ArtList-Frontend/src/views/OrderDetailView.vue index 5531b08e..6b9fb014 100644 --- a/JC-ArtList-Frontend/src/views/OrderDetailView.vue +++ b/JC-ArtList-Frontend/src/views/OrderDetailView.vue @@ -19,6 +19,7 @@ const reviews = ref([]) const changeRequests = ref([]) const afterSales = ref([]) const contact = ref(null) +const dialing = ref(false) const quoteReply = ref('') const quoteSubmitting = ref(false) const quoteConfirming = ref(false) @@ -130,6 +131,20 @@ const loadRelated = async () => { contact.value = contactInfo } +/** 单次取号后立即拨号:不缓存号码,仅使用本次返回的 dialNumber。 */ +const dialArtist = async () => { + if (!orderId.value) return + dialing.value = true + try { + const result = await userApi.dialContact('ORDER_ARTIST', orderId.value) + window.location.href = `tel:${result.dialNumber}` + } catch (error: any) { + message.error(error?.message || '获取拨号号码失败') + } finally { + dialing.value = false + } +} + const loadOrder = async () => { if (!orderId.value) { order.value = null @@ -334,7 +349,9 @@ onMounted(loadOrder)

联系信息

{{ contact.contactName || contact.roleLabel || '服务联系人' }}

-

电话:{{ contact.phone }}

+

+ 拨打美甲师电话 +

微信:{{ contact.wechatId }}

{{ contact.platformContactText }}

diff --git a/JC-ArtList-Frontend/src/views/PasswordSettingsView.vue b/JC-ArtList-Frontend/src/views/PasswordSettingsView.vue index 82d3c055..65819edd 100644 --- a/JC-ArtList-Frontend/src/views/PasswordSettingsView.vue +++ b/JC-ArtList-Frontend/src/views/PasswordSettingsView.vue @@ -238,7 +238,7 @@ const handleSendVerificationCode = async () => { try { await runWithGlobalLoading(() => userApi.sendVerificationCode({ - phone: userPhone.value, + // 号码由服务端按当前登录用户读取,前端只传场景,避免回传已脱敏的展示值。 sceneCode: 'USER_CHANGE_PASSWORD_SMS_CODE' })) message.success('验证码发送成功') diff --git a/JC-ArtList-Frontend/src/views/ProfileView.vue b/JC-ArtList-Frontend/src/views/ProfileView.vue index 37eb972e..8f2277d2 100644 --- a/JC-ArtList-Frontend/src/views/ProfileView.vue +++ b/JC-ArtList-Frontend/src/views/ProfileView.vue @@ -373,6 +373,9 @@ const editForm = reactive({ wechatQrCode: '' }) +/** 打开编辑弹窗时的联系电话原值,用于判断用户是否真实修改过(未修改则不提交该字段)。 */ +const originalContactPhone = ref('') + /** getDraftKey is a local helper used by this page script. */ const getDraftKey = () => buildDraftStorageKey('profile-edit') @@ -596,6 +599,7 @@ const handleEditProfile = () => { editForm.avatar = userInfo.value.avatar || '' editForm.signature = userInfo.value.signature || '' editForm.contactPhone = userInfo.value.contactPhone || '' + originalContactPhone.value = editForm.contactPhone editForm.birthday = userInfo.value.birthday || '' editForm.wechatId = userInfo.value.wechatId || '' editForm.wechatQrCode = userInfo.value.wechatQrCode || '' @@ -742,15 +746,17 @@ const handleSaveProfile = async () => { saving.value = true try { await runWithGlobalLoading(async () => { - await userApi.updateUserInfo({ + const payload = { nickname: editForm.nickname, avatar: editForm.avatar, signature: editForm.signature, - contactPhone: editForm.contactPhone, birthday: editForm.birthday || undefined, wechatId: editForm.wechatId, - wechatQrCode: editForm.wechatQrCode - }) + wechatQrCode: editForm.wechatQrCode, + // 只有联系电话真实变更时才提交,避免把接口回填值(可能已脱敏)原样写回 + ...(editForm.contactPhone !== originalContactPhone.value ? { contactPhone: editForm.contactPhone } : {}) + } + await userApi.updateUserInfo(payload) await fetchUserInfo() }) message.success('资料更新成功') diff --git a/JC-ArtList-Frontend/src/views/ShopDetailView.vue b/JC-ArtList-Frontend/src/views/ShopDetailView.vue index afa5215c..739f5999 100644 --- a/JC-ArtList-Frontend/src/views/ShopDetailView.vue +++ b/JC-ArtList-Frontend/src/views/ShopDetailView.vue @@ -226,16 +226,12 @@

{{ contactInfo.contactName || contactInfo.roleLabel || '联系人' }}

联系电话 - {{ contactInfo.phoneAvailable ? contactInfo.phone : '暂无电话' }} + {{ contactInfo.phoneAvailable ? '点击下方按钮获取当次号码' : '暂无电话' }}
- + - 拨号 - - - - 复制电话 + 拨打店长电话
@@ -372,6 +368,7 @@ const contactOpen = ref(false) * Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow. */ const contactInfo = ref({}) +const dialing = ref(false) /** * Purpose: mapOpen supports ShopDetailView.vue by holding or executing the map open 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. @@ -617,11 +614,24 @@ const openWechatContact = async () => { window.location.href = 'weixin://' } -/** copyContactInfo copies all available contact channels in one action. */ +/** 单次取号后立即拨号:页面不缓存号码,仅使用本次返回的 dialNumber。 */ +const dialManager = async () => { + if (!shopInfo.value.id) return + dialing.value = true + try { + const result = await userApi.dialContact('SHOP_MANAGER', shopInfo.value.id) + window.location.href = `tel:${result.dialNumber}` + } catch (error: any) { + message.error(error?.message || '获取拨号号码失败') + } finally { + dialing.value = false + } +} + +/** copyContactInfo copies the WeChat channel only; phone numbers are no longer rendered or cached. */ const copyContactInfo = async () => { const lines = [ contactInfo.value.contactName || contactInfo.value.roleLabel || '联系人', - contactInfo.value.phoneAvailable && contactInfo.value.phone ? `电话:${contactInfo.value.phone}` : '', contactInfo.value.wechatAvailable && contactInfo.value.wechatId ? `微信:${contactInfo.value.wechatId}` : '' ].filter(Boolean) await copyToClipboard(lines.join('\n'), '联系方式') diff --git a/JC-ArtList-WeChat/api/user.js b/JC-ArtList-WeChat/api/user.js index f7662e43..d186dae7 100644 --- a/JC-ArtList-WeChat/api/user.js +++ b/JC-ArtList-WeChat/api/user.js @@ -144,6 +144,18 @@ module.exports = { }) }, + /** + * 单次拨号取号:号码不缓存,仅用于本次拨号。 + * scene: SHOP_MANAGER / ORDER_ARTIST / PRODUCT_ARTIST / PLATFORM + */ + dialContact(scene, targetId, artistId) { + return request({ + url: '/contact-info/dial', + method: 'POST', + data: { scene, targetId, artistId } + }) + }, + /** * Purpose: getShopManagerContact supports user.js by holding or executing the get shop manager contact page or API role. * Usage: import, call, read, or update this method from the owning page/module while preserving the surrounding loading and permission flow. diff --git a/JC-ArtList-WeChat/pages/help/index.js b/JC-ArtList-WeChat/pages/help/index.js index c266d5dd..bf2d8a53 100644 --- a/JC-ArtList-WeChat/pages/help/index.js +++ b/JC-ArtList-WeChat/pages/help/index.js @@ -30,6 +30,18 @@ Page({ } }, + /** + * 平台客服拨号:点击后才单次取号,号码不保存。 + */ + async handleDialPlatform() { + try { + const dial = await userApi.dialContact('PLATFORM') + wx.makePhoneCall({ phoneNumber: dial.dialNumber }) + } catch (error) { + wx.showToast({ title: error.message || '获取客服号码失败', icon: 'none' }) + } + }, + openRoute(event) { const route = event.currentTarget.dataset.route const pureRoute = String(route || '').split('?')[0] diff --git a/JC-ArtList-WeChat/pages/help/index.wxml b/JC-ArtList-WeChat/pages/help/index.wxml index 457dfa80..18b8da83 100644 --- a/JC-ArtList-WeChat/pages/help/index.wxml +++ b/JC-ArtList-WeChat/pages/help/index.wxml @@ -12,7 +12,9 @@ 平台联系信息 {{contact.contactName}} {{contact.roleLabel || ''}} - 电话:{{contact.phone}} + + 拨打客服电话 + 微信:{{contact.wechatId}} {{contact.platformContactText}} diff --git a/JC-ArtList-WeChat/pages/order-detail/index.js b/JC-ArtList-WeChat/pages/order-detail/index.js index e30653cb..9c397660 100644 --- a/JC-ArtList-WeChat/pages/order-detail/index.js +++ b/JC-ArtList-WeChat/pages/order-detail/index.js @@ -131,6 +131,21 @@ Page({ navigation.navigate('/pages/after-sales/index', { orderId: this.data.id }) }, + /** + * 点击后才单次取号并拨号,页面不保存号码。 + */ + async handleDialArtist() { + if (!this.data.id) { + return + } + try { + const dial = await userApi.dialContact('ORDER_ARTIST', this.data.id) + wx.makePhoneCall({ phoneNumber: dial.dialNumber }) + } catch (error) { + wx.showToast({ title: error.message || '获取拨号号码失败', icon: 'none' }) + } + }, + async handleCancelOrder() { const confirmed = await new Promise(resolve => { wx.showModal({ diff --git a/JC-ArtList-WeChat/pages/order-detail/index.wxml b/JC-ArtList-WeChat/pages/order-detail/index.wxml index ae54d8fd..bad7d21b 100644 --- a/JC-ArtList-WeChat/pages/order-detail/index.wxml +++ b/JC-ArtList-WeChat/pages/order-detail/index.wxml @@ -51,7 +51,9 @@ 联系信息 {{contact.contactName || contact.roleLabel || '服务联系人'}} - 电话:{{contact.phone}} + + 拨打美甲师电话 + 微信:{{contact.wechatId}} {{contact.platformContactText}} diff --git a/JC-ArtList-WeChat/pages/settings/index.js b/JC-ArtList-WeChat/pages/settings/index.js index 882b0571..fb749df4 100644 --- a/JC-ArtList-WeChat/pages/settings/index.js +++ b/JC-ArtList-WeChat/pages/settings/index.js @@ -739,22 +739,9 @@ Page({ }, async handleChangePhoneSubmit() { - const userInfo = this.data.userInfo || {} - const oldPhone = String(userInfo.phone || '').trim() const newPhone = String(this.data.changePhoneForm.newPhone || '').trim() const verificationCode = String(this.data.changePhoneForm.verificationCode || '').trim() - - /** - * `if` page method. Use this from WXML event bindings or lifecycle hooks. - * Call guide: read or update page data with `this.setData(...)` inside the method when state changes. - */ - if (!oldPhone) { - wx.showToast({ - title: '请先绑定手机号', - icon: 'none' - }) - return - } + // 原手机号由服务端按当前登录用户取,页面展示的是脱敏值,不再回传。 if (!phoneRegex.test(newPhone)) { wx.showToast({ @@ -782,7 +769,6 @@ Page({ try { await runWithLoading(() => userApi.updatePhone({ - oldPhone, newPhone, verificationCode })) @@ -829,8 +815,8 @@ Page({ } try { + // 号码由服务端按当前登录用户读取,前端只传场景。 await runWithLoading(() => authApi.sendVerificationCode({ - phone, sceneCode: 'USER_CHANGE_PASSWORD_SMS_CODE' })) wx.showToast({ diff --git a/JC-ArtList-WeChat/pages/shop-detail/index.js b/JC-ArtList-WeChat/pages/shop-detail/index.js index fb89de0e..ec368046 100644 --- a/JC-ArtList-WeChat/pages/shop-detail/index.js +++ b/JC-ArtList-WeChat/pages/shop-detail/index.js @@ -180,8 +180,8 @@ Page({ }, /** - * Purpose: handleContactManager retrieves and shows the current shop manager contact. - * Usage: bind it to the contact button and require login before exposing phone data. + * Purpose: handleContactManager 点击后才单次取号并拨号,页面不再保存或展示号码。 + * Usage: 绑定到联系按钮,要求登录后由服务端按场景鉴权。 */ async handleContactManager() { const shopInfo = this.data.shopInfo @@ -191,20 +191,9 @@ Page({ try { const contact = await userApi.getShopManagerContact(shopInfo.id) this.setData({ managerContact: contact }) - if (contact && contact.phoneAvailable && contact.phone) { - wx.showModal({ - title: contact.contactName || '店长联系方式', - content: `${contact.roleLabel || '店长'}:${contact.phone}`, - confirmText: '拨打', - cancelText: '复制', - success: res => { - if (res.confirm) { - wx.makePhoneCall({ phoneNumber: contact.phone }) - } else { - wx.setClipboardData({ data: contact.phone }) - } - } - }) + if (contact && contact.phoneAvailable) { + const dial = await userApi.dialContact('SHOP_MANAGER', shopInfo.id) + wx.makePhoneCall({ phoneNumber: dial.dialNumber }) return } wx.showToast({ diff --git a/JC-ArtList-WeChat/pages/shop-detail/index.wxml b/JC-ArtList-WeChat/pages/shop-detail/index.wxml index 3f740ca1..d72805f2 100644 --- a/JC-ArtList-WeChat/pages/shop-detail/index.wxml +++ b/JC-ArtList-WeChat/pages/shop-detail/index.wxml @@ -67,7 +67,7 @@ 联系店长 - {{managerContact.contactName || '店长'}} · {{managerContact.phoneAvailable ? managerContact.phone : (managerContact.platformContactText || '暂无电话')}} + {{managerContact.contactName || '店长'}} · {{managerContact.phoneAvailable ? '点击“联系店长”获取当次号码' : (managerContact.platformContactText || '暂无电话')}} diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/config/AgreementAcceptanceInterceptor.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/config/AgreementAcceptanceInterceptor.java new file mode 100644 index 00000000..36fd8f17 --- /dev/null +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/config/AgreementAcceptanceInterceptor.java @@ -0,0 +1,83 @@ +package com.xiaowang.jayucloud.salon.core.config; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.xiaowang.jayucloud.salon.core.common.Result; +import com.xiaowang.jayucloud.salon.core.modules.system.support.AgreementVersionCacheService; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.stereotype.Component; +import org.springframework.web.servlet.HandlerInterceptor; + +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.stream.Collectors; + +/** + * 协议同意校验拦截器:在身份解析之后、业务方法之前阻断未同意当前协议版本的已登录用户。 + * 未登录请求不在此校验;判定组件故障时放行并告警,避免协议缓存/数据库异常导致全站不可用。 + */ +@Slf4j +@Component +@RequiredArgsConstructor +public class AgreementAcceptanceInterceptor implements HandlerInterceptor { + + public static final int AGREEMENT_VERSION_REQUIRED_CODE = 4510; + + public static final String AGREEMENT_VERSION_REQUIRED_BUSINESS_CODE = "AGREEMENT_VERSION_REQUIRED"; + + private final AgreementVersionCacheService agreementVersionCacheService; + + private final ObjectMapper objectMapper; + + @Override + public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { + Object userIdAttribute = request.getAttribute("userId"); + if (!(userIdAttribute instanceof Number)) { + return true; + } + Long userId = ((Number) userIdAttribute).longValue(); + try { + Map currentVersions = agreementVersionCacheService.currentVersions(); + Map acceptedVersions = agreementVersionCacheService.acceptedVersions(userId); + List pendingTypes = new ArrayList<>(); + for (Map.Entry entry : currentVersions.entrySet()) { + if (!Objects.equals(entry.getValue(), acceptedVersions.get(entry.getKey()))) { + pendingTypes.add(entry.getKey()); + } + } + if (pendingTypes.isEmpty()) { + return true; + } + writeAgreementRequired(response, currentVersions, pendingTypes); + return false; + } catch (Exception exception) { + // 可用性优先:协议校验只是附加门禁,Redis/DB 故障时放行主业务,记录告警供监控排查。 + log.warn("协议同意校验失败,已放行请求 path={} userId={}", request.getRequestURI(), userId, exception); + return true; + } + } + + private void writeAgreementRequired(HttpServletResponse response, + Map currentVersions, + List pendingTypes) throws Exception { + String versionText = currentVersions.values().stream() + .filter(Objects::nonNull) + .distinct() + .collect(Collectors.joining("/")); + String message = "用户协议与隐私政策已更新(当前版本 " + versionText + "),请阅读并同意后继续使用"; + Map data = new LinkedHashMap<>(); + data.put("businessCode", AGREEMENT_VERSION_REQUIRED_BUSINESS_CODE); + data.put("currentVersions", currentVersions); + data.put("pendingTypes", pendingTypes); + Result> result = new Result<>(AGREEMENT_VERSION_REQUIRED_CODE, message, data); + response.setStatus(HttpServletResponse.SC_OK); + response.setContentType("application/json;charset=UTF-8"); + response.setHeader("Cache-Control", "no-store"); + response.getWriter().write(objectMapper.writeValueAsString(result)); + } +} diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/config/RateLimitProperties.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/config/RateLimitProperties.java index 2784dc7c..30ce8c5f 100644 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/config/RateLimitProperties.java +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/config/RateLimitProperties.java @@ -28,6 +28,8 @@ public class RateLimitProperties { private LimitRule orderCreate = new LimitRule(10, 60); + private LimitRule customerDial = new LimitRule(10, 60); + @Data /** * Purpose: LimitRule supports RateLimitProperties.java by holding or executing the limit rule business role. diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/config/SalonDeployProperties.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/config/SalonDeployProperties.java new file mode 100644 index 00000000..757f6b77 --- /dev/null +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/config/SalonDeployProperties.java @@ -0,0 +1,24 @@ +package com.xiaowang.jayucloud.salon.core.config; + +import lombok.Data; +import org.springframework.boot.context.properties.ConfigurationProperties; +import org.springframework.stereotype.Component; +import org.springframework.validation.annotation.Validated; + +import javax.validation.constraints.NotBlank; +import javax.validation.constraints.Pattern; + +/** + * 部署环境标识。 + * 用于微信内容审核回调的跨环境路由,必须由各环境 Nacos 显式配置,缺失时启动失败。 + */ +@Data +@Component +@Validated +@ConfigurationProperties(prefix = "jayucloud-salon.deploy") +public class SalonDeployProperties { + + @NotBlank + @Pattern(regexp = "dev|sit|prod", message = "部署环境标识必须是 dev、sit 或 prod") + private String env; +} 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 64d4bb98..0daf8535 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 @@ -13,6 +13,86 @@ import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; */ public class WebMvcConfig implements WebMvcConfigurer { + private static final String[] AUTH_FREE_PATHS = { + "/user/login", + "/user/register", + "/user/check/**", + "/user/refresh-token", + "/user/send-verification-code", + "/user/phone-login", + "/user/wechat-mini/auto-login", + "/user/wechat-mini/phone-login", + "/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", + "/legal-agreement/current", + "/legal-agreement/current/**", + "/legal-agreement/pending", + "/api/legal-agreement/current", + "/api/legal-agreement/current/**", + "/api/legal-agreement/pending", + "/product/get/**", + "/product/list/**", + "/comment/list/product/**", + "/api/comment/list/product/**", + "/nail-artist/profile/**", + "/nail-artist/*/availability", + "/nail-artist/*/reviews", + "/shop/get/**", + "/shop/trust-profile/**", + "/shop/list", + "/shop/list/public", + "/shop/list/simple", + "/tag/list/all", + "/tag/list/filter-options", + "/file/get-signed-url/**", + "/admin/auth/login", + "/admin/auth/refresh", + "/error", + "/health/**" + }; + + /** + * 协议同意门禁额外放行:同意接口、协议阅读页、账号认证类操作、外部回调与健康检查。 + * 这些路径不校验协议版本,避免版本发布后把已登录用户或外部回调锁在门外。 + */ + private static final String[] AGREEMENT_EXTRA_FREE_PATHS = { + "/legal-agreement/accept", + "/api/legal-agreement/accept", + "/legal-agreement/admin/**", + "/api/legal-agreement/admin/**", + "/user/logout", + "/user/info", + "/user/agreement-consent/**", + "/user/switch-shop", + "/user/relation/me", + "/user/invite-code/resolve", + "/user/bind-phone", + "/user/unbind-phone", + "/user/unbind-phone/**", + "/user/wechat-mini/bind-phone", + "/user/bind-email", + "/user/password", + "/user/phone", + "/user/send-current-password-code", + "/user/reset-password/**", + "/user/upload-avatar/**", + "/user/upload-profile-image/**", + "/user/deactivate", + "/legal/**", + "/integration/**", + "/api/integration/**", + "/actuator/**", + "/static/**", + "/assets/**", + "/index.html", + "/favicon.ico" + }; + /** * Purpose: authInterceptor supports WebMvcConfig.java by holding or executing the auth interceptor business role. * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. @@ -23,6 +103,10 @@ public class WebMvcConfig implements WebMvcConfigurer { * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. */ private final SlowRequestLoggingInterceptor slowRequestLoggingInterceptor; + /** + * Purpose: agreementAcceptanceInterceptor 在鉴权之后校验协议同意状态。 + */ + private final AgreementAcceptanceInterceptor agreementAcceptanceInterceptor; @Override /** @@ -37,45 +121,12 @@ public class WebMvcConfig implements WebMvcConfigurer { registry.addInterceptor(authInterceptor) .addPathPatterns("/**") .order(0) - .excludePathPatterns( - "/user/login", - "/user/register", - "/user/check/**", - "/user/refresh-token", - "/user/send-verification-code", - "/user/phone-login", - "/user/wechat-mini/auto-login", - "/user/wechat-mini/phone-login", - "/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", - "/legal-agreement/current", - "/legal-agreement/current/**", - "/api/legal-agreement/current", - "/api/legal-agreement/current/**", - "/product/get/**", - "/product/list/**", - "/comment/list/product/**", - "/api/comment/list/product/**", - "/nail-artist/profile/**", - "/nail-artist/*/availability", - "/nail-artist/*/reviews", - "/shop/get/**", - "/shop/trust-profile/**", - "/shop/list", - "/shop/list/public", - "/shop/list/simple", - "/tag/list/all", - "/tag/list/filter-options", - "/file/get-signed-url/**", - "/admin/auth/login", - "/admin/auth/refresh", - "/error", - "/health/**" - ); + .excludePathPatterns(AUTH_FREE_PATHS); + + registry.addInterceptor(agreementAcceptanceInterceptor) + .addPathPatterns("/**") + .order(1) + .excludePathPatterns(AUTH_FREE_PATHS) + .excludePathPatterns(AGREEMENT_EXTRA_FREE_PATHS); } } 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 81194408..422210bf 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 @@ -33,6 +33,8 @@ import com.xiaowang.jayucloud.salon.core.modules.shop.service.ShopService; import com.xiaowang.jayucloud.salon.core.modules.shop.vo.ShopVO; import com.xiaowang.jayucloud.salon.core.modules.shop.vo.ShopAppointmentSettingsVO; import com.xiaowang.jayucloud.salon.core.modules.manager.vo.AppointmentCustomerOptionVO; +import com.xiaowang.jayucloud.salon.core.modules.privacy.service.CustomerDialService; +import com.xiaowang.jayucloud.salon.core.modules.privacy.vo.CustomerDialVO; import com.xiaowang.jayucloud.salon.core.modules.user.dto.UserDTO; import com.xiaowang.jayucloud.salon.core.modules.user.entity.UserDO; import com.xiaowang.jayucloud.salon.core.modules.user.service.UserService; @@ -49,6 +51,7 @@ import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; import javax.validation.Valid; import java.time.LocalDate; import java.util.List; @@ -65,6 +68,7 @@ public class AdminManagerController { private final ProductService productService; private final ShopService shopService; private final AdminScopeHelper adminScopeHelper; + private final CustomerDialService customerDialService; @GetMapping("/planning/calendar") @RequirePermission("schedule:view") @@ -179,6 +183,30 @@ public class AdminManagerController { return Result.success(userService.listCustomersForAppointment(page, size, keyword, shopId)); } + @PostMapping("/customers/{customerId}/dial") + @RequirePermission("user:view") + public Result dialCustomer(HttpServletRequest request, + HttpServletResponse response, + @PathVariable Long customerId, + @RequestParam(required = false) Long appointmentId, + @RequestParam(required = false) Long orderId) { + UserDO currentUser = adminScopeHelper.getCurrentUser(request); + response.setHeader("Cache-Control", "no-store"); + return Result.success(customerDialService.dial(currentUser, customerId, appointmentId, orderId, request)); + } + + @PostMapping("/customers/dial") + @RequirePermission("user:view") + public Result dialCustomerForGuest(HttpServletRequest request, + HttpServletResponse response, + @RequestParam(required = false) Long customerId, + @RequestParam(required = false) Long appointmentId, + @RequestParam(required = false) Long orderId) { + UserDO currentUser = adminScopeHelper.getCurrentUser(request); + response.setHeader("Cache-Control", "no-store"); + return Result.success(customerDialService.dial(currentUser, customerId, appointmentId, orderId, request)); + } + @GetMapping("/customers/{id}") @RequirePermission("user:view") public Result customer(HttpServletRequest request, @PathVariable Long id) { diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/manager/vo/AppointmentCustomerOptionVO.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/manager/vo/AppointmentCustomerOptionVO.java index 3831ab2f..2bf1f36b 100644 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/manager/vo/AppointmentCustomerOptionVO.java +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/manager/vo/AppointmentCustomerOptionVO.java @@ -11,7 +11,10 @@ public class AppointmentCustomerOptionVO { @JsonSerialize(using = ToStringSerializer.class) private Long id; private String name; + /** 脱敏后的手机号,永不返回完整号码 */ private String phone; + /** 是否存在可拨打的手机号,呼叫按钮据此展示 */ + private Boolean phoneAvailable; private String avatar; private LocalDateTime createdAt; } diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/planning/service/impl/PlanningServiceImpl.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/planning/service/impl/PlanningServiceImpl.java index 7a77525e..d5120bdd 100644 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/planning/service/impl/PlanningServiceImpl.java +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/planning/service/impl/PlanningServiceImpl.java @@ -37,6 +37,7 @@ import com.xiaowang.jayucloud.salon.core.modules.file.support.ObjectStorageUrlSu import com.xiaowang.jayucloud.salon.core.modules.planning.support.PlanningCalendarSupport; import com.xiaowang.jayucloud.salon.core.modules.planning.support.PlanningTodayOverviewSupport; import com.xiaowang.jayucloud.salon.core.support.id.TimeOrderedSnowflakeIdGenerator; +import com.xiaowang.jayucloud.salon.core.support.privacy.PhoneCrypto; import com.xiaowang.jayucloud.salon.core.modules.planning.vo.PlanningAppointmentVO; import com.xiaowang.jayucloud.salon.core.modules.planning.vo.PlanningArtistCountVO; import com.xiaowang.jayucloud.salon.core.modules.planning.vo.PlanningArtistVO; @@ -103,6 +104,7 @@ public class PlanningServiceImpl implements PlanningService { private final WechatSubscribeMessageService wechatSubscribeMessageService; private final TimeOrderedSnowflakeIdGenerator snowflakeIdGenerator; private final ObjectStorageUrlSupport objectStorageUrlSupport; + private final PhoneCrypto phoneCrypto; @Override public PlanningCalendarVO getCalendar(UserDO currentUser, LocalDate startDate, LocalDate endDate, Long artistId) { @@ -621,7 +623,11 @@ public class PlanningServiceImpl implements PlanningService { vo.setOrderItemId(item == null ? reservation == null ? null : reservation.getOrderItemId() : item.getId()); vo.setCustomerId(customer == null ? order == null ? null : order.getUserId() : customer.getId()); vo.setCustomerName(customer == null ? firstNonBlank(order == null ? null : order.getCustomerNameSnapshot(), "散客") : firstNonBlank(customer.getNickname(), customer.getAccount(), "到店客户")); - vo.setCustomerPhone(customer == null ? order == null ? null : order.getCustomerPhoneSnapshot() : firstNonBlank(customer.getContactPhone(), customer.getPhone(), "")); + String plainPhone = customer == null + ? (order == null ? null : order.getCustomerPhoneSnapshot()) + : firstNonBlank(customer.getContactPhone(), customer.getPhone(), ""); + vo.setCustomerPhone(phoneCrypto.mask(plainPhone)); + vo.setCustomerPhoneAvailable(StringUtils.hasText(plainPhone) && !plainPhone.contains("*")); vo.setProductId(product == null ? item == null ? null : item.getProductId() : product.getId()); vo.setProductTitle(reservation != null && hasText(reservation.getProductTitle()) ? reservation.getProductTitle() diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/planning/vo/PlanningAppointmentVO.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/planning/vo/PlanningAppointmentVO.java index edd3899a..b7f2ebdd 100644 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/planning/vo/PlanningAppointmentVO.java +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/planning/vo/PlanningAppointmentVO.java @@ -11,7 +11,10 @@ public class PlanningAppointmentVO { private Long orderItemId; private Long customerId; private String customerName; + /** 脱敏后的客户手机号,完整号码仅通过拨号取号端点单次获取 */ private String customerPhone; + /** 是否存在可拨打的手机号,呼叫按钮据此展示 */ + private Boolean customerPhoneAvailable; private Long productId; private String productTitle; private Long artistId; diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/privacy/config/DialProperties.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/privacy/config/DialProperties.java new file mode 100644 index 00000000..04e21159 --- /dev/null +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/privacy/config/DialProperties.java @@ -0,0 +1,17 @@ +package com.xiaowang.jayucloud.salon.core.modules.privacy.config; + +import lombok.Data; +import org.springframework.boot.context.properties.ConfigurationProperties; +import org.springframework.context.annotation.Configuration; + +/** + * 拨号取号配置。 + * provider 取值:direct(直拨真实号码)或 privacy-number(隐私号码,暂未对接)。 + */ +@Data +@Configuration +@ConfigurationProperties(prefix = "jayucloud-salon.dial") +public class DialProperties { + + private String provider = "direct"; +} diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/privacy/controller/front/WechatContentModerationCallbackController.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/privacy/controller/front/WechatContentModerationCallbackController.java index fa0e972b..6aac43d2 100644 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/privacy/controller/front/WechatContentModerationCallbackController.java +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/privacy/controller/front/WechatContentModerationCallbackController.java @@ -2,30 +2,46 @@ package com.xiaowang.jayucloud.salon.core.modules.privacy.controller.front; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.node.ObjectNode; +import com.xiaowang.jayucloud.salon.core.config.SalonDeployProperties; import com.xiaowang.jayucloud.salon.core.config.WechatMiniProperties; +import com.xiaowang.jayucloud.salon.core.modules.privacy.service.ContentModerationForwardService; import com.xiaowang.jayucloud.salon.core.modules.privacy.service.ContentModerationService; import com.xiaowang.jayucloud.salon.core.modules.privacy.support.WechatCallbackCrypto; +import com.xiaowang.jayucloud.salon.core.modules.system.secure.ModerationForwardConfig; import com.xiaowang.jayucloud.salon.core.modules.system.secure.ModerationRuntimeConfig; import com.xiaowang.jayucloud.salon.core.modules.system.service.SecureIntegrationConfigService; import com.xiaowang.jayucloud.salon.core.modules.system.service.IntegrationProbeService; import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; 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.RequestBody; +import org.springframework.web.bind.annotation.RequestHeader; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; +import java.util.Arrays; +import java.util.Locale; + +@Slf4j @RestController @RequiredArgsConstructor @RequestMapping("/integration/wechat/content-moderation") public class WechatContentModerationCallbackController { + private static final String FORWARD_BY_HEADER = "X-Moderation-Forward-By"; + private static final String FORWARD_HOP_HEADER = "X-Moderation-Forward-Hop"; + private final SecureIntegrationConfigService secureIntegrationConfigService; private final WechatMiniProperties wechatProperties; private final WechatCallbackCrypto crypto; private final ContentModerationService contentModerationService; private final IntegrationProbeService integrationProbeService; + private final ContentModerationForwardService contentModerationForwardService; + private final SalonDeployProperties deployProperties; private final ObjectMapper objectMapper; @GetMapping("/callback") @@ -54,12 +70,23 @@ public class WechatContentModerationCallbackController { MediaType.APPLICATION_XML_VALUE, MediaType.TEXT_XML_VALUE }) - public String callback(@RequestParam("timestamp") String timestamp, - @RequestParam("nonce") String nonce, + public String callback(@RequestParam(value = "timestamp", required = false) String timestamp, + @RequestParam(value = "nonce", required = false) 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 { + @RequestHeader(value = "X-Moderation-Forward-By", required = false) String forwardBy, + @RequestHeader(value = "X-Moderation-Forward-Hop", required = false) String forwardHop, + @RequestHeader(value = "X-Timestamp", required = false) String forwardTimestamp, + @RequestHeader(value = "X-Nonce", required = false) String forwardNonce, + @RequestHeader(value = "X-Signature", required = false) String forwardSignature, + @RequestBody String body) throws Exception { + if (StringUtils.hasText(forwardBy) || StringUtils.hasText(forwardHop)) { + return handleForwardedCallback(forwardBy, forwardHop, forwardTimestamp, forwardNonce, forwardSignature, body); + } + if (!StringUtils.hasText(timestamp) || !StringUtils.hasText(nonce)) { + throw new IllegalArgumentException("微信审核回调缺少时间戳或随机串"); + } ModerationRuntimeConfig config = requireWechatConfig(); String encrypted = extractEncryptedPayload(body); String expectedSignature = "aes".equalsIgnoreCase(encryptType) ? messageSignature : signature; @@ -90,12 +117,119 @@ public class WechatContentModerationCallbackController { extra = firstText(root, "extra", "Extra"); } if (!StringUtils.hasText(taskId)) throw new IllegalArgumentException("微信审核回调缺少任务标识"); - if (!integrationProbeService.handleImageCallback(taskId, suggest, decodeProbeId(extra))) { - contentModerationService.handleWechatImageResult(taskId, suggest, reason, decodeSourceEnvVersion(extra)); + if (claimLocally(taskId, suggest, reason, extra)) { + return "success"; + } + + String taskEnv = normalizeEnv(decodeTaskEnv(extra)); + String localEnv = deployProperties.getEnv(); + String forwardPayload = buildForwardPayload(taskId, suggest, reason, extra); + if (!StringUtils.hasText(taskEnv)) { + contentModerationForwardService.recordUnclaimed(taskId, extra, forwardPayload, "回调 extra 缺少部署环境标识"); + log.warn("微信审核回调无法认领:extra 缺少环境标识,traceId={}, sourceEnv={}, targetEnv={}, hop=0", + taskId, localEnv, null); + return "success"; + } + if (taskEnv.equals(localEnv)) { + contentModerationForwardService.recordUnclaimed(taskId, extra, forwardPayload, "本环境未匹配到审核任务"); + log.warn("微信审核回调无法认领:本环境未匹配任务,traceId={}, sourceEnv={}, targetEnv={}, hop=0", + taskId, localEnv, taskEnv); + return "success"; + } + ModerationForwardConfig forwardConfig = contentModerationForwardService.runtimeConfig(); + if (!StringUtils.hasText(forwardConfig.targetFor(taskEnv))) { + contentModerationForwardService.recordTargetMissing(taskId, localEnv, taskEnv, extra, forwardPayload); + log.warn("微信审核回调目标环境未配置转发地址,traceId={}, sourceEnv={}, targetEnv={}, hop=0", + taskId, localEnv, taskEnv); + return "success"; + } + contentModerationForwardService.enqueue(taskId, localEnv, taskEnv, extra, forwardPayload); + return "success"; + } + + /** + * 处理转发进来的回调:只允许一跳,验签通过后仅在本地处理,不再二次转发。 + */ + private String handleForwardedCallback(String forwardBy, String forwardHop, String timestamp, + String nonce, String signature, String body) { + if (!contentModerationForwardService.verifySignature(timestamp, nonce, signature, body)) { + throw new IllegalArgumentException("跨环境转发签名校验失败"); + } + String taskId; + String suggest; + String reason; + String extra; + try { + JsonNode root = objectMapper.readTree(body == null ? "" : body); + taskId = firstText(root, "trace_id", "traceId", "task_id"); + suggest = firstText(root, "suggest", "Suggest"); + if (!StringUtils.hasText(suggest)) suggest = "review"; + reason = firstText(root, "reason", "errmsg"); + if (!StringUtils.hasText(reason)) reason = "微信异步图片审核回调"; + extra = firstText(root, "extra", "Extra"); + } catch (Exception exception) { + throw new IllegalArgumentException("跨环境转发报文无法解析"); + } + if (!StringUtils.hasText(taskId)) throw new IllegalArgumentException("跨环境转发报文缺少任务标识"); + + String hopText = forwardHop == null ? "1" : forwardHop.trim(); + int hop; + try { + hop = Integer.parseInt(hopText); + } catch (NumberFormatException exception) { + hop = 2; + } + String localEnv = deployProperties.getEnv(); + String sourceEnv = normalizeEnv(forwardBy); + if (hop > 1 || (StringUtils.hasText(sourceEnv) && sourceEnv.equals(localEnv))) { + contentModerationForwardService.recordUnclaimed(taskId, extra, body, + "检测到转发环路或超过一跳,已丢弃"); + log.warn("微信审核回调转发被丢弃:环路或超过一跳,traceId={}, sourceEnv={}, targetEnv={}, hop={}", + taskId, sourceEnv, localEnv, hop); + return "success"; + } + log.info("收到跨环境转发的微信审核回调,traceId={}, sourceEnv={}, targetEnv={}, hop={}", + taskId, sourceEnv, localEnv, hop); + if (!claimLocally(taskId, suggest, reason, extra)) { + contentModerationForwardService.recordUnclaimed(taskId, extra, body, "转发目标环境仍未匹配到审核任务"); + log.warn("跨环境转发的微信审核回调未匹配到本地任务,traceId={}, sourceEnv={}, targetEnv={}, hop={}", + taskId, sourceEnv, localEnv, hop); } return "success"; } + private boolean claimLocally(String taskId, String suggest, String reason, String extra) { + if (integrationProbeService.handleImageCallback(taskId, suggest, decodeProbeId(extra))) { + return true; + } + return contentModerationService.handleWechatImageResult(taskId, suggest, reason, decodeSourceEnvVersion(extra)); + } + + private String buildForwardPayload(String taskId, String suggest, String reason, String extra) { + ObjectNode payload = objectMapper.createObjectNode(); + payload.put("trace_id", taskId); + payload.put("suggest", suggest); + payload.put("reason", reason); + if (StringUtils.hasText(extra)) payload.put("extra", extra); + return payload.toString(); + } + + private String decodeTaskEnv(String extra) { + if (!StringUtils.hasText(extra)) return null; + try { + JsonNode payload = objectMapper.readTree(extra); + return firstText(payload, "env"); + } catch (Exception ignored) { + return null; + } + } + + private String normalizeEnv(String value) { + if (!StringUtils.hasText(value)) return null; + String normalized = value.trim().toLowerCase(Locale.ROOT); + return Arrays.asList("dev", "sit", "prod").contains(normalized) ? normalized : null; + } + private String decodeSourceEnvVersion(String extra) { if (!StringUtils.hasText(extra)) return null; try { diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/privacy/dial/DialMode.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/privacy/dial/DialMode.java new file mode 100644 index 00000000..8d80a3e8 --- /dev/null +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/privacy/dial/DialMode.java @@ -0,0 +1,14 @@ +package com.xiaowang.jayucloud.salon.core.modules.privacy.dial; + +/** + * 拨号返回模式。 + */ +public final class DialMode { + + public static final String DIRECT = "DIRECT"; + + public static final String PRIVACY_NUMBER = "PRIVACY_NUMBER"; + + private DialMode() { + } +} diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/privacy/dial/DialTarget.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/privacy/dial/DialTarget.java new file mode 100644 index 00000000..c85f9bd0 --- /dev/null +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/privacy/dial/DialTarget.java @@ -0,0 +1,29 @@ +package com.xiaowang.jayucloud.salon.core.modules.privacy.dial; + +/** + * 单次取号结果,仅在本次响应中返回,不落库、不写日志、不缓存。 + */ +public class DialTarget { + + private final String mode; + private final String dialNumber; + private final int expiresInSeconds; + + public DialTarget(String mode, String dialNumber, int expiresInSeconds) { + this.mode = mode; + this.dialNumber = dialNumber; + this.expiresInSeconds = expiresInSeconds; + } + + public String getMode() { + return mode; + } + + public String getDialNumber() { + return dialNumber; + } + + public int getExpiresInSeconds() { + return expiresInSeconds; + } +} diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/privacy/dial/DialTargetProvider.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/privacy/dial/DialTargetProvider.java new file mode 100644 index 00000000..9732b4f3 --- /dev/null +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/privacy/dial/DialTargetProvider.java @@ -0,0 +1,20 @@ +package com.xiaowang.jayucloud.salon.core.modules.privacy.dial; + +import com.xiaowang.jayucloud.salon.core.modules.order.entity.OrderDO; +import com.xiaowang.jayucloud.salon.core.modules.user.entity.UserDO; + +/** + * 拨号目标渠道。不同渠道返回不同的号码类型,调用方不得自行降级为真实号码。 + */ +public interface DialTargetProvider { + + /** + * 配置项中使用的渠道标识,例如 direct、privacy-number。 + */ + String providerKey(); + + /** + * 解析本次拨号目标。 + */ + DialTarget resolve(UserDO customer, OrderDO order); +} diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/privacy/dial/DirectDialTargetProvider.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/privacy/dial/DirectDialTargetProvider.java new file mode 100644 index 00000000..56e57e9b --- /dev/null +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/privacy/dial/DirectDialTargetProvider.java @@ -0,0 +1,65 @@ +package com.xiaowang.jayucloud.salon.core.modules.privacy.dial; + +import com.xiaowang.jayucloud.salon.core.common.BusinessException; +import com.xiaowang.jayucloud.salon.core.modules.order.entity.OrderDO; +import com.xiaowang.jayucloud.salon.core.modules.user.entity.UserDO; +import com.xiaowang.jayucloud.salon.core.support.privacy.PhoneCrypto; +import lombok.RequiredArgsConstructor; +import org.springframework.stereotype.Component; +import org.springframework.util.StringUtils; + +/** + * 直拨渠道:实时读取客户档案中的号码,仅在本次响应返回。 + */ +@Component +@RequiredArgsConstructor +public class DirectDialTargetProvider implements DialTargetProvider { + + public static final int NUMBER_UNAVAILABLE_CODE = 422; + + public static final String NUMBER_UNAVAILABLE_BUSINESS_CODE = "DIAL_NUMBER_UNAVAILABLE"; + + private final PhoneCrypto phoneCrypto; + + @Override + public String providerKey() { + return "direct"; + } + + @Override + public DialTarget resolve(UserDO customer, OrderDO order) { + String plainPhone = resolvePlainPhone(customer, order); + if (!StringUtils.hasText(plainPhone) || plainPhone.contains("*")) { + throw new BusinessException(NUMBER_UNAVAILABLE_CODE, + "该预约/订单未登记可拨打的手机号(" + NUMBER_UNAVAILABLE_BUSINESS_CODE + ")"); + } + return new DialTarget(DialMode.DIRECT, plainPhone.trim(), 0); + } + + /** + * 号码来源优先级:订单/预约上的客户手机号快照优先,其次客户档案。 + */ + private String resolvePlainPhone(UserDO customer, OrderDO order) { + if (order != null && StringUtils.hasText(order.getCustomerPhoneSnapshot())) { + String snapshot = phoneCrypto.decrypt(order.getCustomerPhoneSnapshot()); + if (StringUtils.hasText(snapshot)) { + return snapshot; + } + } + if (customer != null) { + if (StringUtils.hasText(customer.getContactPhone())) { + String contactPhone = phoneCrypto.decrypt(customer.getContactPhone()); + if (StringUtils.hasText(contactPhone)) { + return contactPhone; + } + } + if (StringUtils.hasText(customer.getPhone())) { + String phone = phoneCrypto.decrypt(customer.getPhone()); + if (StringUtils.hasText(phone)) { + return phone; + } + } + } + return null; + } +} diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/privacy/dial/PlaceholderPrivacyNumberProvider.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/privacy/dial/PlaceholderPrivacyNumberProvider.java new file mode 100644 index 00000000..ff689af5 --- /dev/null +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/privacy/dial/PlaceholderPrivacyNumberProvider.java @@ -0,0 +1,28 @@ +package com.xiaowang.jayucloud.salon.core.modules.privacy.dial; + +import com.xiaowang.jayucloud.salon.core.common.BusinessException; +import com.xiaowang.jayucloud.salon.core.modules.order.entity.OrderDO; +import com.xiaowang.jayucloud.salon.core.modules.user.entity.UserDO; +import org.springframework.stereotype.Component; + +/** + * 隐私号码占位渠道:未对接时明确报错,绝不静默回退为真实号码。 + */ +@Component +public class PlaceholderPrivacyNumberProvider implements DialTargetProvider { + + public static final int NOT_CONFIGURED_CODE = 4250; + + public static final String NOT_CONFIGURED_BUSINESS_CODE = "DIAL_PRIVACY_NUMBER_NOT_CONFIGURED"; + + @Override + public String providerKey() { + return "privacy-number"; + } + + @Override + public DialTarget resolve(UserDO customer, OrderDO order) { + throw new BusinessException(NOT_CONFIGURED_CODE, + "隐私号码服务未配置(" + NOT_CONFIGURED_BUSINESS_CODE + "),请联系平台开通"); + } +} diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/privacy/moderation/WechatContentModerationProvider.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/privacy/moderation/WechatContentModerationProvider.java index fed6376b..929a101a 100644 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/privacy/moderation/WechatContentModerationProvider.java +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/privacy/moderation/WechatContentModerationProvider.java @@ -2,6 +2,7 @@ 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.config.SalonDeployProperties; 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; @@ -26,16 +27,19 @@ public class WechatContentModerationProvider implements ContentModerationProvide private final ObjectMapper objectMapper; private final WechatMiniClientService wechatMiniClientService; private final ContentModerationProperties properties; + private final SalonDeployProperties deployProperties; public WechatContentModerationProvider( @Qualifier("wechatContentModerationRestTemplate") RestTemplate restTemplate, ObjectMapper objectMapper, WechatMiniClientService wechatMiniClientService, - ContentModerationProperties properties) { + ContentModerationProperties properties, + SalonDeployProperties deployProperties) { this.restTemplate = restTemplate; this.objectMapper = objectMapper; this.wechatMiniClientService = wechatMiniClientService; this.properties = properties; + this.deployProperties = deployProperties; } @Override @@ -67,6 +71,7 @@ public class WechatContentModerationProvider implements ContentModerationProvide public ModerationOutcome submitTestImage(String imageUrl, String openId, String probeId, String sourceEnvVersion) { Map extra = new LinkedHashMap<>(); + extra.put("env", deployProperties.getEnv()); extra.put("envVersion", normalizeEnvVersion(sourceEnvVersion)); extra.put("probeId", probeId); try { @@ -103,8 +108,11 @@ public class WechatContentModerationProvider implements ContentModerationProvide if (!"develop".equals(envVersion) && !"trial".equals(envVersion) && !"release".equals(envVersion)) { envVersion = "UNKNOWN"; } + Map extra = new LinkedHashMap<>(); + extra.put("env", deployProperties.getEnv()); + extra.put("envVersion", envVersion); try { - return objectMapper.writeValueAsString(Map.of("envVersion", envVersion)); + return objectMapper.writeValueAsString(extra); } catch (java.io.IOException exception) { throw new IllegalStateException("无法编码微信审核来源版本", exception); } diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/privacy/service/ContentModerationForwardService.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/privacy/service/ContentModerationForwardService.java new file mode 100644 index 00000000..65d8527a --- /dev/null +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/privacy/service/ContentModerationForwardService.java @@ -0,0 +1,46 @@ +package com.xiaowang.jayucloud.salon.core.modules.privacy.service; + +import com.xiaowang.jayucloud.salon.core.modules.system.secure.ModerationForwardConfig; +import com.xiaowang.jayucloud.salon.core.modules.system.vo.ModerationForwardRecordVO; + +import java.util.List; + +/** + * 微信异步图片审核回调的跨环境转发。 + */ +public interface ContentModerationForwardService { + + ModerationForwardConfig runtimeConfig(); + + List listRecent(int limit); + + /** + * 记录无法认领的回调(extra 缺失或指向本环境但本地没有任务),不自动重试。 + */ + void recordUnclaimed(String traceId, String extraJson, String payload, String note); + + /** + * 记录目标环境未配置的回调,不自动重试,配置补齐后可由补偿任务重放。 + */ + void recordTargetMissing(String traceId, String sourceEnv, String targetEnv, String extraJson, String payload); + + /** + * 落库为 PENDING 并异步转发,确保微信回调在 5 秒内拿到 success。 + */ + void enqueue(String traceId, String sourceEnv, String targetEnv, String extraJson, String payload); + + /** + * 重放到期的 RETRY 记录,最多 5 次,指数退避。 + */ + int retryPending(); + + /** + * 转发配置补齐后,把对应目标环境下的 TARGET_MISSING 记录重新排队。 + */ + int requeueConfiguredTargets(); + + /** + * 校验转发请求的 HMAC 签名、时间窗与 nonce 防重放。 + */ + boolean verifySignature(String timestamp, String nonce, String signature, String body); +} diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/privacy/service/CustomerDialService.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/privacy/service/CustomerDialService.java new file mode 100644 index 00000000..16a840cb --- /dev/null +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/privacy/service/CustomerDialService.java @@ -0,0 +1,14 @@ +package com.xiaowang.jayucloud.salon.core.modules.privacy.service; + +import com.xiaowang.jayucloud.salon.core.modules.privacy.vo.CustomerDialVO; +import com.xiaowang.jayucloud.salon.core.modules.user.entity.UserDO; + +import javax.servlet.http.HttpServletRequest; + +/** + * 客户拨号取号服务:按门店范围与订单上下文单次授权,号码不落库、不写日志、不缓存。 + */ +public interface CustomerDialService { + + CustomerDialVO dial(UserDO currentUser, Long customerId, Long appointmentId, Long orderId, HttpServletRequest request); +} diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/privacy/service/impl/ContentModerationForwardServiceImpl.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/privacy/service/impl/ContentModerationForwardServiceImpl.java new file mode 100644 index 00000000..f7076718 --- /dev/null +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/privacy/service/impl/ContentModerationForwardServiceImpl.java @@ -0,0 +1,341 @@ +package com.xiaowang.jayucloud.salon.core.modules.privacy.service.impl; + +import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; +import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper; +import com.xiaowang.jayucloud.salon.core.config.SalonDeployProperties; +import com.xiaowang.jayucloud.salon.core.modules.privacy.service.ContentModerationForwardService; +import com.xiaowang.jayucloud.salon.core.modules.privacy.support.ModerationForwardHttpClient; +import com.xiaowang.jayucloud.salon.core.modules.system.entity.ModerationCallbackForwardDO; +import com.xiaowang.jayucloud.salon.core.modules.system.mapper.ModerationCallbackForwardMapper; +import com.xiaowang.jayucloud.salon.core.modules.system.secure.ModerationForwardConfig; +import com.xiaowang.jayucloud.salon.core.modules.system.service.SecureIntegrationConfigService; +import com.xiaowang.jayucloud.salon.core.modules.system.vo.ModerationForwardRecordVO; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.dao.DuplicateKeyException; +import org.springframework.data.redis.core.RedisTemplate; +import org.springframework.scheduling.annotation.Scheduled; +import org.springframework.stereotype.Service; +import org.springframework.util.StringUtils; + +import javax.annotation.PreDestroy; +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.time.Duration; +import java.time.LocalDateTime; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.concurrent.ThreadFactory; +import java.util.concurrent.atomic.AtomicInteger; + +@Slf4j +@Service +@RequiredArgsConstructor +public class ContentModerationForwardServiceImpl implements ContentModerationForwardService { + private static final String STATUS_PENDING = "PENDING"; + private static final String STATUS_SUCCESS = "SUCCESS"; + private static final String STATUS_RETRY = "RETRY"; + private static final String STATUS_FAILED = "FAILED"; + private static final String STATUS_NO_ENV = "NO_ENV"; + private static final String STATUS_TARGET_MISSING = "TARGET_MISSING"; + + private static final int MAX_RETRY = 5; + private static final long SIGNATURE_WINDOW_SECONDS = 300; + private static final long NONCE_TTL_SECONDS = 600; + private static final String NONCE_KEY_PREFIX = "salon:content-moderation:forward:nonce:"; + private static final String FORWARD_BY_HEADER = "X-Moderation-Forward-By"; + private static final String FORWARD_HOP_HEADER = "X-Moderation-Forward-Hop"; + + private static final AtomicInteger THREAD_INDEX = new AtomicInteger(1); + private static final ExecutorService FORWARD_EXECUTOR = Executors.newFixedThreadPool(2, new ThreadFactory() { + @Override + public Thread newThread(Runnable runnable) { + Thread thread = new Thread(runnable, "moderation-forward-" + THREAD_INDEX.getAndIncrement()); + thread.setDaemon(true); + return thread; + } + }); + + private final ModerationCallbackForwardMapper forwardMapper; + private final SecureIntegrationConfigService secureIntegrationConfigService; + private final SalonDeployProperties deployProperties; + private final RedisTemplate redisTemplate; + private final ModerationForwardHttpClient forwardHttpClient; + + @Override + public ModerationForwardConfig runtimeConfig() { + return secureIntegrationConfigService.getModerationForwardConfig(); + } + + @Override + public List listRecent(int limit) { + int size = limit <= 0 ? 10 : Math.min(limit, 50); + List rows = forwardMapper.selectList(new LambdaQueryWrapper() + .orderByDesc(ModerationCallbackForwardDO::getCreatedAt) + .last("LIMIT " + size)); + return rows.stream().map(this::toVO).toList(); + } + + @Override + public void recordUnclaimed(String traceId, String extraJson, String payload, String note) { + if (!StringUtils.hasText(traceId)) { + log.warn("微信审核回调无法认领且缺少任务标识,note={}", note); + return; + } + log.warn("微信审核回调无法认领,traceId={}, sourceEnv={}, targetEnv={}, hop=0, note={}", + traceId, deployProperties.getEnv(), null, note); + ModerationCallbackForwardDO row = build(traceId, deployProperties.getEnv(), null, extraJson, payload, STATUS_NO_ENV, note); + saveQuietly(row); + } + + @Override + public void recordTargetMissing(String traceId, String sourceEnv, String targetEnv, String extraJson, String payload) { + log.warn("微信审核回调目标环境未配置转发地址,traceId={}, sourceEnv={}, targetEnv={}, hop=0", + traceId, sourceEnv, targetEnv); + ModerationCallbackForwardDO row = build(traceId, sourceEnv, targetEnv, extraJson, payload, + STATUS_TARGET_MISSING, "目标环境未配置转发地址"); + saveQuietly(row); + } + + @Override + public void enqueue(String traceId, String sourceEnv, String targetEnv, String extraJson, String payload) { + ModerationCallbackForwardDO existing = findByTrace(traceId); + if (existing != null) { + log.info("微信审核回调转发已存在记录,traceId={}, sourceEnv={}, targetEnv={}, status={}", + traceId, sourceEnv, targetEnv, existing.getStatus()); + return; + } + ModerationCallbackForwardDO row = build(traceId, sourceEnv, targetEnv, extraJson, payload, STATUS_PENDING, null); + if (!saveQuietly(row)) return; + log.info("微信审核回调进入跨环境转发,traceId={}, sourceEnv={}, targetEnv={}, hop=1", + traceId, sourceEnv, targetEnv); + FORWARD_EXECUTOR.execute(() -> dispatchById(row.getId())); + } + + @Override + @Scheduled(fixedDelay = 60000) + public int retryPending() { + List rows = forwardMapper.selectList(new LambdaQueryWrapper() + .eq(ModerationCallbackForwardDO::getStatus, STATUS_RETRY) + .lt(ModerationCallbackForwardDO::getRetryCount, MAX_RETRY) + .orderByAsc(ModerationCallbackForwardDO::getId) + .last("LIMIT 50")); + LocalDateTime now = LocalDateTime.now(); + int attempted = 0; + for (ModerationCallbackForwardDO row : rows) { + if (!backoffElapsed(row, now)) continue; + attempted++; + dispatchById(row.getId()); + } + return attempted; + } + + @Override + public int requeueConfiguredTargets() { + ModerationForwardConfig config = runtimeConfig(); + if (!config.ready() || config.getTargets() == null || config.getTargets().isEmpty()) return 0; + List configuredEnvs = config.getTargets().entrySet().stream() + .filter(entry -> StringUtils.hasText(entry.getValue())) + .map(Map.Entry::getKey) + .toList(); + if (configuredEnvs.isEmpty()) return 0; + return forwardMapper.update(null, new UpdateWrapper() + .eq("status", STATUS_TARGET_MISSING) + .in("target_env", configuredEnvs) + .set("status", STATUS_RETRY) + .set("retry_count", 0) + .set("last_error", null) + .set("updated_at", LocalDateTime.now())); + } + + @Override + public boolean verifySignature(String timestamp, String nonce, String signature, String body) { + if (!StringUtils.hasText(timestamp) || !StringUtils.hasText(nonce) || !StringUtils.hasText(signature)) return false; + ModerationForwardConfig config = runtimeConfig(); + if (!config.ready()) return false; + long epochSeconds; + try { + epochSeconds = Long.parseLong(timestamp.trim()); + } catch (NumberFormatException exception) { + return false; + } + if (Math.abs(System.currentTimeMillis() / 1000 - epochSeconds) > SIGNATURE_WINDOW_SECONDS) return false; + if (!reserveNonce(nonce.trim())) return false; + String expected = sign(config.getSecret(), timestamp.trim(), nonce.trim(), body == null ? "" : body); + return MessageDigest.isEqual(expected.getBytes(StandardCharsets.UTF_8), + signature.trim().toLowerCase(java.util.Locale.ROOT).getBytes(StandardCharsets.UTF_8)); + } + + private void dispatchById(Long id) { + ModerationCallbackForwardDO row = forwardMapper.selectById(id); + if (row == null || STATUS_SUCCESS.equals(row.getStatus())) return; + ModerationForwardConfig config = runtimeConfig(); + if (!config.ready()) { + markFailed(row, "跨环境转发未启用或共享密钥缺失", false); + return; + } + String target = config.targetFor(row.getTargetEnv()); + if (!StringUtils.hasText(target)) { + row.setStatus(STATUS_TARGET_MISSING); + row.setLastError("目标环境未配置转发地址"); + row.setUpdatedAt(LocalDateTime.now()); + forwardMapper.updateById(row); + log.warn("微信审核回调转发目标缺失,traceId={}, sourceEnv={}, targetEnv={}, hop=1", + row.getTraceId(), row.getSourceEnv(), row.getTargetEnv()); + return; + } + try { + String timestamp = String.valueOf(System.currentTimeMillis() / 1000); + String nonce = UUID.randomUUID().toString().replace("-", ""); + String signature = sign(config.getSecret(), timestamp, nonce, row.getPayload() == null ? "" : row.getPayload()); + Map headers = new java.util.HashMap<>(); + headers.put(FORWARD_BY_HEADER, deployProperties.getEnv()); + headers.put(FORWARD_HOP_HEADER, "1"); + headers.put("X-Timestamp", timestamp); + headers.put("X-Nonce", nonce); + headers.put("X-Signature", signature); + boolean accepted = forwardHttpClient.post(target, row.getPayload(), headers); + if (accepted) { + row.setStatus(STATUS_SUCCESS); + row.setLastError(null); + row.setUpdatedAt(LocalDateTime.now()); + forwardMapper.updateById(row); + log.info("微信审核回调跨环境转发成功,traceId={}, sourceEnv={}, targetEnv={}, hop=1", + row.getTraceId(), row.getSourceEnv(), row.getTargetEnv()); + } else { + markRetry(row, "目标环境返回异常状态"); + } + } catch (RuntimeException exception) { + markRetry(row, "目标环境不可达或请求失败"); + } + } + + private void markRetry(ModerationCallbackForwardDO row, String error) { + int retries = (row.getRetryCount() == null ? 0 : row.getRetryCount()) + 1; + row.setRetryCount(retries); + row.setLastError(clip(error, 500)); + row.setStatus(retries >= MAX_RETRY ? STATUS_FAILED : STATUS_RETRY); + row.setUpdatedAt(LocalDateTime.now()); + forwardMapper.updateById(row); + log.warn("微信审核回调转发失败,traceId={}, sourceEnv={}, targetEnv={}, hop=1, retryCount={}, status={}", + row.getTraceId(), row.getSourceEnv(), row.getTargetEnv(), retries, row.getStatus()); + } + + private void markFailed(ModerationCallbackForwardDO row, String error, boolean retry) { + if (retry) { + markRetry(row, error); + return; + } + row.setStatus(STATUS_FAILED); + row.setLastError(clip(error, 500)); + row.setUpdatedAt(LocalDateTime.now()); + forwardMapper.updateById(row); + log.warn("微信审核回调转发失败,traceId={}, sourceEnv={}, targetEnv={}, hop=1, status=FAILED", + row.getTraceId(), row.getSourceEnv(), row.getTargetEnv()); + } + + private boolean backoffElapsed(ModerationCallbackForwardDO row, LocalDateTime now) { + if (row.getUpdatedAt() == null) return true; + long minutes = 1L << Math.min(Math.max(row.getRetryCount() == null ? 0 : row.getRetryCount(), 0), 5); + return !row.getUpdatedAt().plusMinutes(minutes).isAfter(now); + } + + private boolean reserveNonce(String nonce) { + try { + Boolean fresh = redisTemplate.opsForValue().setIfAbsent(NONCE_KEY_PREFIX + nonce, "1", + Duration.ofSeconds(NONCE_TTL_SECONDS)); + return Boolean.TRUE.equals(fresh); + } catch (RuntimeException exception) { + log.warn("转发 nonce 防重放写入失败,按拒绝处理"); + return false; + } + } + + private String sign(String secret, String timestamp, String nonce, String body) { + try { + javax.crypto.Mac mac = javax.crypto.Mac.getInstance("HmacSHA256"); + mac.init(new javax.crypto.spec.SecretKeySpec(secret.getBytes(StandardCharsets.UTF_8), "HmacSHA256")); + String canonical = timestamp + "\n" + nonce + "\n" + sha256Hex(body); + return hex(mac.doFinal(canonical.getBytes(StandardCharsets.UTF_8))); + } catch (java.security.GeneralSecurityException exception) { + throw new IllegalStateException("转发签名计算失败", exception); + } + } + + private String sha256Hex(String value) { + try { + MessageDigest digest = MessageDigest.getInstance("SHA-256"); + return hex(digest.digest(value.getBytes(StandardCharsets.UTF_8))); + } catch (java.security.NoSuchAlgorithmException exception) { + throw new IllegalStateException("无法计算报文摘要", exception); + } + } + + private String hex(byte[] bytes) { + StringBuilder builder = new StringBuilder(bytes.length * 2); + for (byte item : bytes) builder.append(String.format("%02x", item)); + return builder.toString(); + } + + private ModerationCallbackForwardDO build(String traceId, String sourceEnv, String targetEnv, + String extraJson, String payload, String status, String error) { + LocalDateTime now = LocalDateTime.now(); + ModerationCallbackForwardDO row = new ModerationCallbackForwardDO(); + row.setTraceId(clip(traceId, 128)); + row.setSourceEnv(clip(sourceEnv, 16)); + row.setTargetEnv(StringUtils.hasText(targetEnv) ? clip(targetEnv, 16) : null); + row.setExtraJson(clip(extraJson, 256)); + row.setPayload(payload); + row.setStatus(status); + row.setRetryCount(0); + row.setLastError(clip(error, 500)); + row.setCreatedAt(now); + row.setUpdatedAt(now); + return row; + } + + private boolean saveQuietly(ModerationCallbackForwardDO row) { + try { + forwardMapper.insert(row); + return true; + } catch (DuplicateKeyException exception) { + log.info("微信审核回调转发记录已存在,traceId={}", row.getTraceId()); + return false; + } + } + + private ModerationCallbackForwardDO findByTrace(String traceId) { + if (!StringUtils.hasText(traceId)) return null; + return forwardMapper.selectOne(new LambdaQueryWrapper() + .eq(ModerationCallbackForwardDO::getTraceId, traceId) + .last("LIMIT 1")); + } + + private ModerationForwardRecordVO toVO(ModerationCallbackForwardDO row) { + ModerationForwardRecordVO vo = new ModerationForwardRecordVO(); + vo.setId(row.getId()); + vo.setTraceId(row.getTraceId()); + vo.setSourceEnv(row.getSourceEnv()); + vo.setTargetEnv(row.getTargetEnv()); + vo.setStatus(row.getStatus()); + vo.setRetryCount(row.getRetryCount()); + vo.setLastError(row.getLastError()); + vo.setCreatedAt(row.getCreatedAt()); + vo.setUpdatedAt(row.getUpdatedAt()); + return vo; + } + + private String clip(String value, int max) { + if (!StringUtils.hasText(value)) return null; + String trimmed = value.trim(); + return trimmed.length() <= max ? trimmed : trimmed.substring(0, max); + } + + @PreDestroy + public void shutdown() { + FORWARD_EXECUTOR.shutdownNow(); + } +} diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/privacy/service/impl/CustomerDialServiceImpl.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/privacy/service/impl/CustomerDialServiceImpl.java new file mode 100644 index 00000000..f70423a6 --- /dev/null +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/privacy/service/impl/CustomerDialServiceImpl.java @@ -0,0 +1,141 @@ +package com.xiaowang.jayucloud.salon.core.modules.privacy.service.impl; + +import com.xiaowang.jayucloud.salon.core.common.BusinessException; +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.order.mapper.OrderItemMapper; +import com.xiaowang.jayucloud.salon.core.modules.order.mapper.OrderMapper; +import com.xiaowang.jayucloud.salon.core.modules.privacy.config.DialProperties; +import com.xiaowang.jayucloud.salon.core.modules.privacy.dial.DialTarget; +import com.xiaowang.jayucloud.salon.core.modules.privacy.dial.DialTargetProvider; +import com.xiaowang.jayucloud.salon.core.modules.privacy.service.CustomerDialService; +import com.xiaowang.jayucloud.salon.core.modules.privacy.vo.CustomerDialVO; +import com.xiaowang.jayucloud.salon.core.modules.security.support.AdminScopeHelper; +import com.xiaowang.jayucloud.salon.core.modules.security.support.SecurityAuditActions; +import com.xiaowang.jayucloud.salon.core.modules.security.support.SecurityAuditSupport; +import com.xiaowang.jayucloud.salon.core.modules.user.entity.UserDO; +import com.xiaowang.jayucloud.salon.core.modules.user.service.UserService; +import com.xiaowang.jayucloud.salon.core.support.security.RequestThrottleService; +import lombok.RequiredArgsConstructor; +import org.springframework.stereotype.Service; +import org.springframework.util.StringUtils; + +import javax.servlet.http.HttpServletRequest; +import java.util.List; +import java.util.Objects; + +/** + * 客户拨号取号实现:先校验门店范围与订单归属,再按配置渠道单次取号并记录审计。 + */ +@Service +@RequiredArgsConstructor +public class CustomerDialServiceImpl implements CustomerDialService { + + private static final String AUDIT_ACTION = SecurityAuditActions.CUSTOMER_DIAL; + + private final AdminScopeHelper adminScopeHelper; + private final UserService userService; + private final OrderMapper orderMapper; + private final OrderItemMapper orderItemMapper; + private final RequestThrottleService requestThrottleService; + private final SecurityAuditSupport securityAuditSupport; + private final DialProperties dialProperties; + private final List providers; + + @Override + public CustomerDialVO dial(UserDO currentUser, Long customerId, Long appointmentId, Long orderId, HttpServletRequest request) { + adminScopeHelper.requireShopContext(currentUser, "请先选择店铺后再拨号"); + Long currentShopId = currentUser.getShopId(); + requestThrottleService.checkCustomerDial(request, currentUser.getId()); + + if (customerId == null && appointmentId == null && orderId == null) { + throw new BusinessException(400, "请提供预约或订单信息后再拨号(DIAL_TARGET_REQUIRED)"); + } + + OrderDO order = null; + if (appointmentId != null) { + OrderItemDO item = orderItemMapper.selectById(appointmentId); + if (item == null || Objects.equals(1, item.getIsDelete())) { + throw new BusinessException(404, "预约不存在"); + } + order = orderMapper.selectById(item.getOrderId()); + if (order == null || Objects.equals(1, order.getIsDelete())) { + throw new BusinessException(404, "预约关联订单不存在"); + } + } + if (orderId != null) { + if (order != null && !Objects.equals(orderId, order.getId())) { + throw new BusinessException(403, "预约与订单不匹配,或无权拨打"); + } + if (order == null) { + order = orderMapper.selectById(orderId); + if (order == null || Objects.equals(1, order.getIsDelete())) { + throw new BusinessException(404, "订单不存在"); + } + } + } + if (order != null && !Objects.equals(currentShopId, order.getShopId())) { + throw new BusinessException(403, "无权拨打其他店铺预约/订单客户"); + } + + UserDO customer = resolveCustomer(currentUser, customerId, order); + Long auditCustomerId = customer == null ? null : customer.getId(); + + DialTargetProvider provider = resolveProvider(); + String reason = "customerId=" + auditCustomerId + + ";appointmentId=" + appointmentId + + ";orderId=" + (order == null ? null : order.getId()) + + ";provider=" + provider.providerKey(); + try { + DialTarget target = provider.resolve(customer, order); + securityAuditSupport.success(request, AUDIT_ACTION, reason + ";mode=" + target.getMode() + ";result=SUCCESS"); + CustomerDialVO vo = new CustomerDialVO(); + vo.setMode(target.getMode()); + vo.setDialNumber(target.getDialNumber()); + vo.setExpiresInSeconds(target.getExpiresInSeconds()); + return vo; + } catch (BusinessException exception) { + securityAuditSupport.fail(request, AUDIT_ACTION, + reason + ";result=FAIL;errorCode=" + exception.getCode()); + throw exception; + } catch (RuntimeException exception) { + securityAuditSupport.fail(request, AUDIT_ACTION, + reason + ";result=FAIL;errorType=" + exception.getClass().getSimpleName()); + throw exception; + } + } + + /** + * 解析目标客户:优先使用显式 customerId,其次订单关联客户;散客预约返回 null,不要求客户有账号。 + */ + private UserDO resolveCustomer(UserDO currentUser, Long customerId, OrderDO order) { + Long targetCustomerId = customerId; + if (targetCustomerId == null && order != null) { + targetCustomerId = order.getUserId(); + } + if (targetCustomerId == null) { + return null; + } + if (order != null && !Objects.equals(targetCustomerId, order.getUserId())) { + throw new BusinessException(403, "该客户与预约/订单不匹配,或无权拨打"); + } + UserDO customer = userService.getById(targetCustomerId); + if (customer == null || Objects.equals(1, customer.getIsDelete()) || !Objects.equals(0, customer.getType())) { + throw new BusinessException(404, "客户不存在"); + } + adminScopeHelper.ensureUserAccessibleInCurrentShop(currentUser, targetCustomerId, "无权拨打其他店铺客户"); + return customer; + } + + private DialTargetProvider resolveProvider() { + String configured = StringUtils.hasText(dialProperties.getProvider()) + ? dialProperties.getProvider().trim() + : "direct"; + for (DialTargetProvider provider : providers) { + if (configured.equalsIgnoreCase(provider.providerKey())) { + return provider; + } + } + throw new BusinessException(500, "拨号渠道配置无效(jayucloud-salon.dial.provider=" + configured + ")"); + } +} diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/privacy/support/ModerationForwardHttpClient.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/privacy/support/ModerationForwardHttpClient.java new file mode 100644 index 00000000..6bd9dfd1 --- /dev/null +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/privacy/support/ModerationForwardHttpClient.java @@ -0,0 +1,35 @@ +package com.xiaowang.jayucloud.salon.core.modules.privacy.support; + +import org.springframework.http.HttpEntity; +import org.springframework.http.HttpHeaders; +import org.springframework.http.MediaType; +import org.springframework.http.ResponseEntity; +import org.springframework.http.client.SimpleClientHttpRequestFactory; +import org.springframework.stereotype.Component; +import org.springframework.web.client.RestTemplate; + +import java.util.Map; + +/** + * 跨环境审核回调转发客户端,固定 3 秒超时,失败以异常抛出由上层登记重试。 + */ +@Component +public class ModerationForwardHttpClient { + + private final RestTemplate restTemplate; + + public ModerationForwardHttpClient() { + SimpleClientHttpRequestFactory factory = new SimpleClientHttpRequestFactory(); + factory.setConnectTimeout(3000); + factory.setReadTimeout(3000); + this.restTemplate = new RestTemplate(factory); + } + + public boolean post(String url, String body, Map headers) { + HttpHeaders httpHeaders = new HttpHeaders(); + httpHeaders.setContentType(MediaType.APPLICATION_JSON); + headers.forEach(httpHeaders::set); + ResponseEntity response = restTemplate.postForEntity(url, new HttpEntity<>(body, httpHeaders), String.class); + return response.getStatusCode().is2xxSuccessful(); + } +} diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/privacy/vo/CustomerDialVO.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/privacy/vo/CustomerDialVO.java new file mode 100644 index 00000000..a62bc030 --- /dev/null +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/privacy/vo/CustomerDialVO.java @@ -0,0 +1,19 @@ +package com.xiaowang.jayucloud.salon.core.modules.privacy.vo; + +import lombok.Data; + +/** + * 单次拨号取号响应。 + */ +@Data +public class CustomerDialVO { + + /** DIRECT:真实号码;PRIVACY_NUMBER:隐私号码 */ + private String mode; + + /** 本次可拨打的号码,仅用于当前客户端一次性拨号 */ + private String dialNumber; + + /** 号码有效秒数,DIRECT 为 0 表示不设时效 */ + private Integer expiresInSeconds; +} diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/security/support/SecurityAuditActions.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/security/support/SecurityAuditActions.java index a581544f..83ed716f 100644 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/security/support/SecurityAuditActions.java +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/security/support/SecurityAuditActions.java @@ -108,6 +108,7 @@ public final class SecurityAuditActions { public static final String ANALYTICS_VIEW = "ANALYTICS_VIEW"; public static final String PERFORMANCE_VIEW = "PERFORMANCE_VIEW"; public static final String SECURE_CONFIG_UPDATE = "SECURE_CONFIG_UPDATE"; + public static final String CUSTOMER_DIAL = "CUSTOMER_DIAL"; private SecurityAuditActions() { } diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/system/controller/admin/AdminSecureIntegrationConfigController.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/system/controller/admin/AdminSecureIntegrationConfigController.java index f40efc2f..21c851fc 100644 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/system/controller/admin/AdminSecureIntegrationConfigController.java +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/system/controller/admin/AdminSecureIntegrationConfigController.java @@ -6,6 +6,7 @@ import com.xiaowang.jayucloud.salon.core.common.Result; import com.xiaowang.jayucloud.salon.core.modules.security.support.AdminScopeHelper; import com.xiaowang.jayucloud.salon.core.modules.security.support.SecurityAuditActions; import com.xiaowang.jayucloud.salon.core.modules.security.support.SecurityAuditSupport; +import com.xiaowang.jayucloud.salon.core.modules.privacy.service.ContentModerationForwardService; import com.xiaowang.jayucloud.salon.core.modules.system.dto.SecureIntegrationConfigDTO; import com.xiaowang.jayucloud.salon.core.modules.system.dto.IntegrationProbeRequestDTO; import com.xiaowang.jayucloud.salon.core.modules.system.service.IntegrationProbeService; @@ -31,6 +32,7 @@ import java.util.List; public class AdminSecureIntegrationConfigController { private final SecureIntegrationConfigService secureIntegrationConfigService; private final IntegrationProbeService integrationProbeService; + private final ContentModerationForwardService contentModerationForwardService; private final AdminScopeHelper adminScopeHelper; private final SecurityAuditSupport securityAuditSupport; @@ -40,6 +42,7 @@ public class AdminSecureIntegrationConfigController { UserDO currentUser = adminScopeHelper.getCurrentUser(request); SecureIntegrationConfigVO config = secureIntegrationConfigService.getAdminConfig(currentUser); config.setProbeResults(integrationProbeService.listLatest(currentUser)); + config.setModerationForwardRecent(contentModerationForwardService.listRecent(10)); return Result.success(config); } @@ -82,6 +85,31 @@ public class AdminSecureIntegrationConfigController { } } + @PostMapping("/content-moderation-forward") + @RequirePermission("messagehub:config:manage") + @OperationGuard(action = "secure-moderation-forward-config-save", ttlSeconds = 5, message = "跨环境转发设置正在保存,请勿重复提交") + public Result saveModerationForwardConfig(HttpServletRequest request, + @Valid @RequestBody SecureIntegrationConfigDTO dto) { + UserDO currentUser = adminScopeHelper.getCurrentUser(request); + try { + secureIntegrationConfigService.saveModerationForwardConfig(currentUser, dto); + int requeued = contentModerationForwardService.requeueConfiguredTargets(); + if (requeued > 0) { + securityAuditSupport.success(request, SecurityAuditActions.SECURE_CONFIG_UPDATE, + "section=CONTENT_MODERATION_FORWARD,requeued=" + requeued); + } else { + securityAuditSupport.success(request, SecurityAuditActions.SECURE_CONFIG_UPDATE, + "section=CONTENT_MODERATION_FORWARD"); + } + SecureIntegrationConfigVO config = secureIntegrationConfigService.getAdminConfig(currentUser); + config.setModerationForwardRecent(contentModerationForwardService.listRecent(10)); + return Result.success(config); + } catch (RuntimeException exception) { + securityAuditSupport.fail(request, SecurityAuditActions.SECURE_CONFIG_UPDATE, "section=CONTENT_MODERATION_FORWARD"); + throw exception; + } + } + @GetMapping("/probe-results") @RequirePermission("messagehub:config:manage") public Result> listProbeResults(HttpServletRequest request) { diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/system/controller/front/LegalAgreementController.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/system/controller/front/LegalAgreementController.java index 1c189feb..0597bfd7 100644 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/system/controller/front/LegalAgreementController.java +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/system/controller/front/LegalAgreementController.java @@ -6,9 +6,11 @@ import com.xiaowang.jayucloud.salon.core.common.Result; import com.xiaowang.jayucloud.salon.core.modules.system.dto.LegalAgreementDTO; import com.xiaowang.jayucloud.salon.core.modules.user.entity.UserDO; import com.xiaowang.jayucloud.salon.core.modules.system.service.LegalAgreementService; +import com.xiaowang.jayucloud.salon.core.modules.system.support.AgreementVersionCacheService; import com.xiaowang.jayucloud.salon.core.modules.security.service.SecurityAuditLogService; import com.xiaowang.jayucloud.salon.core.modules.security.support.AdminScopeHelper; import com.xiaowang.jayucloud.salon.core.support.security.RequestThrottleService; +import com.xiaowang.jayucloud.salon.core.modules.system.vo.AgreementPendingVO; import com.xiaowang.jayucloud.salon.core.modules.system.vo.LegalAgreementVO; import com.xiaowang.jayucloud.salon.core.modules.user.vo.UserAgreementConsentVO; import lombok.RequiredArgsConstructor; @@ -47,6 +49,10 @@ public class LegalAgreementController { * Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state. */ private final RequestThrottleService requestThrottleService; + /** + * Purpose: agreementVersionCacheService 在同意成功后清除该用户的协议缓存。 + */ + private final AgreementVersionCacheService agreementVersionCacheService; @GetMapping("/current") /** @@ -68,6 +74,28 @@ public class LegalAgreementController { return Result.success(legalAgreementService.getCurrentAgreement(type)); } + @GetMapping("/pending") + /** + * Purpose: pending 返回当前协议版本;登录用户额外返回是否已同意新版本。免登录只返回当前版本。 + */ + public Result pending(HttpServletRequest request) { + requestThrottleService.checkAgreementRead(request, "PENDING"); + Long userId = (Long) request.getAttribute("userId"); + return Result.success(legalAgreementService.getPendingAgreements(userId)); + } + + @PostMapping("/accept") + /** + * Purpose: accept 记录登录用户对当前发布协议版本的同意。 + */ + public Result accept(HttpServletRequest request, + @RequestParam(required = false) String clientType) { + Long userId = (Long) request.getAttribute("userId"); + legalAgreementService.acceptCurrentAgreements(userId, clientType, request); + agreementVersionCacheService.evictUser(userId); + return Result.success(legalAgreementService.getPendingAgreements(userId)); + } + @GetMapping("/admin/list") @RequirePermission("legal_agreement:manage") /** diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/system/dto/SecureIntegrationConfigDTO.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/system/dto/SecureIntegrationConfigDTO.java index 23c58956..4b162450 100644 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/system/dto/SecureIntegrationConfigDTO.java +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/system/dto/SecureIntegrationConfigDTO.java @@ -2,6 +2,8 @@ package com.xiaowang.jayucloud.salon.core.modules.system.dto; import lombok.Data; +import java.util.Map; + @Data public class SecureIntegrationConfigDTO { private String mapProvider; @@ -19,4 +21,9 @@ public class SecureIntegrationConfigDTO { private String moderationEncodingAesKey; private Boolean clearModerationCallbackToken; private Boolean clearModerationEncodingAesKey; + + private Boolean moderationForwardEnabled; + private Map moderationForwardTargets; + private String moderationForwardSecret; + private Boolean clearModerationForwardSecret; } diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/system/entity/ModerationCallbackForwardDO.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/system/entity/ModerationCallbackForwardDO.java new file mode 100644 index 00000000..5fb504a3 --- /dev/null +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/system/entity/ModerationCallbackForwardDO.java @@ -0,0 +1,46 @@ +package com.xiaowang.jayucloud.salon.core.modules.system.entity; + +import com.baomidou.mybatisplus.annotation.IdType; +import com.baomidou.mybatisplus.annotation.TableField; +import com.baomidou.mybatisplus.annotation.TableId; +import com.baomidou.mybatisplus.annotation.TableName; +import lombok.Data; + +import java.time.LocalDateTime; + +@Data +@TableName("t_moderation_callback_forward") +public class ModerationCallbackForwardDO { + @TableId(type = IdType.ASSIGN_ID) + private Long id; + + @TableField("trace_id") + private String traceId; + + @TableField("source_env") + private String sourceEnv; + + @TableField("target_env") + private String targetEnv; + + @TableField("extra_json") + private String extraJson; + + @TableField("payload") + private String payload; + + @TableField("status") + private String status; + + @TableField("retry_count") + private Integer retryCount; + + @TableField("last_error") + private String lastError; + + @TableField("created_at") + private LocalDateTime createdAt; + + @TableField("updated_at") + private LocalDateTime updatedAt; +} diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/system/mapper/ModerationCallbackForwardMapper.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/system/mapper/ModerationCallbackForwardMapper.java new file mode 100644 index 00000000..04d42c24 --- /dev/null +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/system/mapper/ModerationCallbackForwardMapper.java @@ -0,0 +1,9 @@ +package com.xiaowang.jayucloud.salon.core.modules.system.mapper; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import com.xiaowang.jayucloud.salon.core.modules.system.entity.ModerationCallbackForwardDO; +import org.apache.ibatis.annotations.Mapper; + +@Mapper +public interface ModerationCallbackForwardMapper extends BaseMapper { +} diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/system/secure/ModerationForwardConfig.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/system/secure/ModerationForwardConfig.java new file mode 100644 index 00000000..47ecd003 --- /dev/null +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/system/secure/ModerationForwardConfig.java @@ -0,0 +1,30 @@ +package com.xiaowang.jayucloud.salon.core.modules.system.secure; + +import lombok.AllArgsConstructor; +import lombok.Data; +import org.springframework.util.StringUtils; + +import java.util.Collections; +import java.util.Map; + +@Data +@AllArgsConstructor +public class ModerationForwardConfig { + private boolean enabled; + private Map targets; + private String secret; + + public static ModerationForwardConfig disabled() { + return new ModerationForwardConfig(false, Collections.emptyMap(), ""); + } + + public String targetFor(String env) { + if (!enabled || env == null || targets == null) return null; + String target = targets.get(env); + return StringUtils.hasText(target) ? target.trim() : null; + } + + public boolean ready() { + return enabled && StringUtils.hasText(secret); + } +} diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/system/service/LegalAgreementService.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/system/service/LegalAgreementService.java index 30a53df3..a2a4f857 100644 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/system/service/LegalAgreementService.java +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/system/service/LegalAgreementService.java @@ -3,6 +3,7 @@ package com.xiaowang.jayucloud.salon.core.modules.system.service; import com.xiaowang.jayucloud.salon.core.common.dto.AgreementAwareRequest; import com.xiaowang.jayucloud.salon.core.modules.system.dto.LegalAgreementDTO; import com.xiaowang.jayucloud.salon.core.modules.user.entity.UserDO; +import com.xiaowang.jayucloud.salon.core.modules.system.vo.AgreementPendingVO; import com.xiaowang.jayucloud.salon.core.modules.system.vo.LegalAgreementVO; import com.xiaowang.jayucloud.salon.core.modules.user.vo.UserAgreementConsentVO; @@ -31,6 +32,10 @@ public interface LegalAgreementService { UserAgreementConsentVO getMyConsent(Long userId); + AgreementPendingVO getPendingAgreements(Long userId); + + void acceptCurrentAgreements(Long userId, String clientType, HttpServletRequest httpRequest); + void requireAccepted(AgreementAwareRequest request); void recordConsent(Long userId, AgreementAwareRequest request, String entry, HttpServletRequest httpRequest); diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/system/service/SecureIntegrationConfigService.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/system/service/SecureIntegrationConfigService.java index 1fd7f59f..d574f5eb 100644 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/system/service/SecureIntegrationConfigService.java +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/system/service/SecureIntegrationConfigService.java @@ -1,6 +1,7 @@ package com.xiaowang.jayucloud.salon.core.modules.system.service; import com.xiaowang.jayucloud.salon.core.modules.system.dto.SecureIntegrationConfigDTO; +import com.xiaowang.jayucloud.salon.core.modules.system.secure.ModerationForwardConfig; import com.xiaowang.jayucloud.salon.core.modules.system.secure.ModerationRuntimeConfig; import com.xiaowang.jayucloud.salon.core.modules.system.vo.SecureIntegrationConfigVO; import com.xiaowang.jayucloud.salon.core.modules.user.entity.UserDO; @@ -14,6 +15,10 @@ public interface SecureIntegrationConfigService { void saveModerationConfig(UserDO currentUser, SecureIntegrationConfigDTO dto); + void saveModerationForwardConfig(UserDO currentUser, SecureIntegrationConfigDTO dto); + + ModerationForwardConfig getModerationForwardConfig(); + Map getMapRuntimeConfig(UserDO currentUser); ModerationRuntimeConfig getModerationRuntimeConfig(); diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/system/service/impl/LegalAgreementServiceImpl.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/system/service/impl/LegalAgreementServiceImpl.java index dff0a9ed..ba15b6cf 100644 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/system/service/impl/LegalAgreementServiceImpl.java +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/system/service/impl/LegalAgreementServiceImpl.java @@ -11,6 +11,7 @@ import com.xiaowang.jayucloud.salon.core.modules.system.mapper.LegalAgreementMap import com.xiaowang.jayucloud.salon.core.modules.user.mapper.UserAgreementConsentMapper; import com.xiaowang.jayucloud.salon.core.modules.system.service.LegalAgreementService; import com.xiaowang.jayucloud.salon.core.support.security.RequestThrottleService; +import com.xiaowang.jayucloud.salon.core.modules.system.vo.AgreementPendingVO; import com.xiaowang.jayucloud.salon.core.modules.system.vo.LegalAgreementVO; import com.xiaowang.jayucloud.salon.core.modules.user.vo.UserAgreementConsentVO; import lombok.RequiredArgsConstructor; @@ -20,6 +21,8 @@ import org.springframework.util.StringUtils; import javax.servlet.http.HttpServletRequest; import java.time.LocalDateTime; +import java.util.ArrayList; +import java.util.Collections; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; @@ -170,6 +173,57 @@ public class LegalAgreementServiceImpl implements LegalAgreementService { return new UserAgreementConsentVO(versions); } + @Override + /** + * Purpose: getPendingAgreements 返回当前协议版本与该用户的同意状态;未登录时只返回当前版本。 + */ + public AgreementPendingVO getPendingAgreements(Long userId) { + Map currentVersions = new LinkedHashMap<>(); + Map acceptedVersions = new LinkedHashMap<>(); + List pendingTypes = new ArrayList<>(); + Map accepted = userId == null + ? Collections.emptyMap() + : getMyConsent(userId).getConsentVersions(); + for (String type : List.of(USER_TERMS, PRIVACY_POLICY)) { + LegalAgreementDO current = findCurrentAgreement(type); + if (current == null) { + continue; + } + currentVersions.put(type, current.getVersion()); + String acceptedVersion = accepted == null ? null : accepted.get(type); + if (StringUtils.hasText(acceptedVersion)) { + acceptedVersions.put(type, acceptedVersion); + } + if (!StringUtils.hasText(acceptedVersion) || !current.getVersion().equals(acceptedVersion)) { + pendingTypes.add(type); + } + } + Boolean pending = userId == null ? null : !pendingTypes.isEmpty(); + return new AgreementPendingVO(pending, currentVersions, acceptedVersions, pendingTypes); + } + + @Override + @Transactional(rollbackFor = Exception.class) + /** + * Purpose: acceptCurrentAgreements 记录用户对当前发布版本的同意,不依赖客户端上报版本。 + */ + public void acceptCurrentAgreements(Long userId, String clientType, HttpServletRequest httpRequest) { + if (userId == null) { + throw new RuntimeException("请先登录后再同意协议"); + } + String normalizedClientType = StringUtils.hasText(clientType) + ? clientType.trim().toUpperCase() + : "WEB"; + String ip = resolveClientIp(httpRequest); + for (String type : List.of(USER_TERMS, PRIVACY_POLICY)) { + LegalAgreementDO current = findCurrentAgreement(type); + if (current == null) { + throw new RuntimeException("当前协议未配置,请联系管理员"); + } + upsertConsent(userId, type, current.getVersion(), "agreement-gate", normalizedClientType, ip); + } + } + @Override /** * Purpose: requireAccepted supports LegalAgreementServiceImpl.java by holding or executing the require accepted business role. diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/system/service/impl/SecureIntegrationConfigServiceImpl.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/system/service/impl/SecureIntegrationConfigServiceImpl.java index a1930a6b..bb17b8bd 100644 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/system/service/impl/SecureIntegrationConfigServiceImpl.java +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/system/service/impl/SecureIntegrationConfigServiceImpl.java @@ -1,6 +1,9 @@ package com.xiaowang.jayucloud.salon.core.modules.system.service.impl; import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.core.JsonProcessingException; 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.system.dto.SecureIntegrationConfigDTO; @@ -8,12 +11,14 @@ import com.xiaowang.jayucloud.salon.core.modules.system.entity.SecureIntegration import com.xiaowang.jayucloud.salon.core.modules.system.entity.SystemParameterConfigDO; import com.xiaowang.jayucloud.salon.core.modules.system.mapper.SecureIntegrationConfigMapper; import com.xiaowang.jayucloud.salon.core.modules.system.mapper.SystemParameterConfigMapper; +import com.xiaowang.jayucloud.salon.core.modules.system.secure.ModerationForwardConfig; import com.xiaowang.jayucloud.salon.core.modules.system.secure.ModerationRuntimeConfig; import com.xiaowang.jayucloud.salon.core.modules.system.secure.SecureConfigEncryptionService; import com.xiaowang.jayucloud.salon.core.modules.system.service.SecureIntegrationConfigService; import com.xiaowang.jayucloud.salon.core.modules.system.vo.SecureIntegrationConfigVO; import com.xiaowang.jayucloud.salon.core.modules.user.entity.UserDO; import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import org.springframework.util.StringUtils; @@ -22,15 +27,18 @@ import java.net.URI; import java.net.URISyntaxException; import java.util.Arrays; import java.util.HashMap; +import java.util.LinkedHashMap; import java.util.List; import java.util.Locale; import java.util.Map; +@Slf4j @Service @RequiredArgsConstructor public class SecureIntegrationConfigServiceImpl implements SecureIntegrationConfigService { private static final String MAP = "MAP"; private static final String MODERATION = "CONTENT_MODERATION"; + private static final String MODERATION_FORWARD = "CONTENT_MODERATION_FORWARD"; private static final String SYSTEM = "SYSTEM"; private static final String LEGACY_MAP_MIGRATED = "LEGACY_MAP_MIGRATED"; private static final String WECHAT_CALLBACK_PATH = "/api/integration/wechat/content-moderation/callback"; @@ -40,6 +48,7 @@ public class SecureIntegrationConfigServiceImpl implements SecureIntegrationConf private final SecureConfigEncryptionService encryptionService; private final ContentModerationProperties moderationProperties; private final WechatMiniProperties wechatMiniProperties; + private final ObjectMapper objectMapper; @Override @Transactional @@ -80,6 +89,12 @@ public class SecureIntegrationConfigServiceImpl implements SecureIntegrationConf result.setWechatMiniAppId(StringUtils.hasText(wechatMiniProperties.getAppId()) ? wechatMiniProperties.getAppId() : ""); result.setMockProviderAllowed(isMockAllowed()); + + ModerationForwardConfig forwardConfig = getModerationForwardConfig(); + result.setModerationForwardEnabled(forwardConfig.isEnabled()); + result.setModerationForwardTargets(forwardConfig.getTargets()); + result.setModerationForwardSecretConfigured(StringUtils.hasText(forwardConfig.getSecret())); + result.setUpdatedAt(latestUpdateTime()); return result; } @@ -163,6 +178,77 @@ public class SecureIntegrationConfigServiceImpl implements SecureIntegrationConf writeValue(MODERATION, "PROVIDER", provider, false, currentUser.getId()); } + @Override + @Transactional(rollbackFor = Exception.class) + public void saveModerationForwardConfig(UserDO currentUser, SecureIntegrationConfigDTO dto) { + requirePlatformAdmin(currentUser); + requireEncryptionKey(); + + boolean enabled = Boolean.TRUE.equals(dto.getModerationForwardEnabled()); + Map targets = normalizeForwardTargets(dto.getModerationForwardTargets()); + for (Map.Entry entry : targets.entrySet()) { + if (!isValidForwardTarget(entry.getValue())) { + throw new IllegalArgumentException("跨环境转发地址不合法(" + entry.getKey() + + "),必须精确指向 /api/integration/wechat/content-moderation/callback,且 HTTP 仅允许内网主机"); + } + } + + ModerationForwardConfig current = getModerationForwardConfig(); + String secret; + if (Boolean.TRUE.equals(dto.getClearModerationForwardSecret())) { + secret = ""; + } else if (StringUtils.hasText(dto.getModerationForwardSecret())) { + secret = dto.getModerationForwardSecret().trim(); + } else { + secret = current.getSecret(); + } + if (StringUtils.hasText(secret) && !secret.matches("[A-Za-z0-9+/=_\\-]{16,128}")) { + throw new IllegalArgumentException("跨环境转发共享密钥需要为 16-128 位字母、数字或常用符号"); + } + if (enabled) { + if (!StringUtils.hasText(secret)) { + throw new IllegalArgumentException("启用跨环境回调转发时必须配置共享密钥"); + } + if (targets.isEmpty()) { + throw new IllegalArgumentException("启用跨环境回调转发时至少需要配置一个目标环境地址"); + } + } + + Map payload = new LinkedHashMap<>(); + payload.put("enabled", enabled); + payload.put("targets", targets); + payload.put("secret", secret); + try { + writeValue(MODERATION_FORWARD, "CONFIG", objectMapper.writeValueAsString(payload), true, currentUser.getId()); + } catch (JsonProcessingException exception) { + throw new IllegalStateException("无法保存跨环境转发配置", exception); + } + } + + @Override + public ModerationForwardConfig getModerationForwardConfig() { + if (!encryptionService.isConfigured()) return ModerationForwardConfig.disabled(); + String json = readValue(MODERATION_FORWARD, "CONFIG", ""); + if (!StringUtils.hasText(json)) return ModerationForwardConfig.disabled(); + try { + JsonNode node = objectMapper.readTree(json); + boolean enabled = node.path("enabled").asBoolean(false); + Map targets = new LinkedHashMap<>(); + JsonNode targetsNode = node.path("targets"); + if (targetsNode.isObject()) { + targetsNode.fields().forEachRemaining(entry -> { + if (StringUtils.hasText(entry.getValue().asText(""))) { + targets.put(entry.getKey(), entry.getValue().asText("")); + } + }); + } + return new ModerationForwardConfig(enabled, targets, node.path("secret").asText("")); + } catch (JsonProcessingException exception) { + log.warn("跨环境转发配置解析失败,按未启用处理"); + return ModerationForwardConfig.disabled(); + } + } + @Override @Transactional public Map getMapRuntimeConfig(UserDO currentUser) { @@ -362,6 +448,62 @@ public class SecureIntegrationConfigServiceImpl implements SecureIntegrationConf } } + private Map normalizeForwardTargets(Map raw) { + Map result = new LinkedHashMap<>(); + if (raw == null) return result; + for (String env : Arrays.asList("dev", "sit", "prod")) { + String value = raw.get(env); + if (StringUtils.hasText(value)) result.put(env, value.trim()); + } + return result; + } + + /** + * 只允许指向内容审核回调路径:HTTPS 放行(各环境对外地址通常为 HTTPS 域名), + * HTTP 仅允许私网/本机主机,避免被配置为任意公网地址造成 SSRF。 + */ + private boolean isValidForwardTarget(String value) { + if (!StringUtils.hasText(value)) return false; + try { + URI uri = new URI(value.trim()); + String scheme = uri.getScheme() == null ? "" : uri.getScheme().toLowerCase(Locale.ROOT); + String host = uri.getHost(); + if (!"https".equals(scheme) && !"http".equals(scheme)) return false; + if (!StringUtils.hasText(host)) return false; + if (uri.getRawUserInfo() != null || uri.getRawQuery() != null || uri.getRawFragment() != null) return false; + if (!WECHAT_CALLBACK_PATH.equals(uri.getRawPath())) return false; + return !"http".equals(scheme) || isPrivateHost(host); + } catch (URISyntaxException exception) { + return false; + } + } + + private boolean isPrivateHost(String host) { + String normalized = host.toLowerCase(Locale.ROOT); + if (normalized.startsWith("[") && normalized.endsWith("]")) { + normalized = normalized.substring(1, normalized.length() - 1); + } + if ("localhost".equals(normalized) || normalized.endsWith(".localhost") + || normalized.endsWith(".local") || normalized.endsWith(".internal")) { + return true; + } + if (normalized.contains(":")) { + return normalized.startsWith("::1") || normalized.startsWith("fc") || normalized.startsWith("fd"); + } + String[] parts = normalized.split("\\."); + if (parts.length != 4) return false; + try { + int first = Integer.parseInt(parts[0]); + int second = Integer.parseInt(parts[1]); + if (first == 10 || first == 127) return true; + if (first == 192 && second == 168) return true; + if (first == 172 && second >= 16 && second <= 31) return true; + return first == 169 && second == 254; + } catch (NumberFormatException exception) { + return false; + } + } + private String normalizedProvider(String value) { return upper(value, "DISABLED"); } diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/system/support/AgreementVersionCacheService.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/system/support/AgreementVersionCacheService.java new file mode 100644 index 00000000..3166cd26 --- /dev/null +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/system/support/AgreementVersionCacheService.java @@ -0,0 +1,115 @@ +package com.xiaowang.jayucloud.salon.core.modules.system.support; + +import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; +import com.fasterxml.jackson.core.type.TypeReference; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.xiaowang.jayucloud.salon.core.modules.system.service.LegalAgreementService; +import com.xiaowang.jayucloud.salon.core.modules.user.entity.UserAgreementConsentDO; +import com.xiaowang.jayucloud.salon.core.modules.user.mapper.UserAgreementConsentMapper; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.data.redis.core.StringRedisTemplate; +import org.springframework.stereotype.Service; +import org.springframework.util.StringUtils; + +import java.time.Duration; +import java.util.Collections; +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.stream.Collectors; + +/** + * 协议版本缓存:当前发布版本缓存 4 分钟,用户已同意版本缓存 10 分钟。 + * 版本发布走 SQL 迁移,没有代码钩子,依赖短 TTL 自然收敛;accept 成功时主动清除该用户缓存。 + */ +@Slf4j +@Service +@RequiredArgsConstructor +public class AgreementVersionCacheService { + + private static final String CURRENT_VERSIONS_KEY = "jayucloud:agreement:current-versions:v1"; + + private static final String USER_VERSIONS_KEY_PREFIX = "jayucloud:agreement:user-versions:"; + + private static final Duration CURRENT_VERSIONS_TTL = Duration.ofMinutes(4); + + private static final Duration USER_VERSIONS_TTL = Duration.ofMinutes(10); + + private static final TypeReference> STRING_MAP_TYPE = new TypeReference>() { + }; + + private final LegalAgreementService legalAgreementService; + + private final UserAgreementConsentMapper consentMapper; + + private final ObjectMapper objectMapper; + + private final StringRedisTemplate stringRedisTemplate; + + public Map currentVersions() { + Map cached = readCache(CURRENT_VERSIONS_KEY); + if (cached != null) { + return cached; + } + Map loaded = legalAgreementService.getPendingAgreements(null).getCurrentVersions(); + writeCache(CURRENT_VERSIONS_KEY, loaded, CURRENT_VERSIONS_TTL); + return loaded == null ? Collections.emptyMap() : loaded; + } + + public Map acceptedVersions(Long userId) { + if (userId == null) { + return Collections.emptyMap(); + } + String key = userVersionsKey(userId); + Map cached = readCache(key); + if (cached != null) { + return cached; + } + Map loaded = consentMapper.selectList(new LambdaQueryWrapper() + .eq(UserAgreementConsentDO::getUserId, userId)) + .stream() + .collect(Collectors.toMap( + UserAgreementConsentDO::getAgreementType, + UserAgreementConsentDO::getVersion, + (left, right) -> right, + LinkedHashMap::new)); + writeCache(key, loaded, USER_VERSIONS_TTL); + return loaded; + } + + public void evictUser(Long userId) { + if (userId == null) { + return; + } + try { + stringRedisTemplate.delete(userVersionsKey(userId)); + } catch (Exception exception) { + log.warn("清除协议同意缓存失败 userId={}", userId, exception); + } + } + + private String userVersionsKey(Long userId) { + return USER_VERSIONS_KEY_PREFIX + userId; + } + + private Map readCache(String key) { + try { + String json = stringRedisTemplate.opsForValue().get(key); + if (!StringUtils.hasText(json)) { + return null; + } + return objectMapper.readValue(json, STRING_MAP_TYPE); + } catch (Exception exception) { + log.warn("读取协议版本缓存失败,回退数据库 key={}", key, exception); + return null; + } + } + + private void writeCache(String key, Map value, Duration ttl) { + try { + stringRedisTemplate.opsForValue().set(key, objectMapper.writeValueAsString(value), ttl); + } catch (Exception exception) { + log.warn("写入协议版本缓存失败 key={}", key, exception); + } + } +} diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/system/vo/AgreementPendingVO.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/system/vo/AgreementPendingVO.java new file mode 100644 index 00000000..df49a22a --- /dev/null +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/system/vo/AgreementPendingVO.java @@ -0,0 +1,25 @@ +package com.xiaowang.jayucloud.salon.core.modules.system.vo; + +import lombok.AllArgsConstructor; +import lombok.Data; +import lombok.NoArgsConstructor; + +import java.util.List; +import java.util.Map; + +/** + * 协议重新同意状态:未登录时只返回当前版本,登录后额外返回已同意版本与待同意类型。 + */ +@Data +@NoArgsConstructor +@AllArgsConstructor +public class AgreementPendingVO { + + private Boolean pending; + + private Map currentVersions; + + private Map acceptedVersions; + + private List pendingTypes; +} diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/system/vo/ModerationForwardRecordVO.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/system/vo/ModerationForwardRecordVO.java new file mode 100644 index 00000000..227be6bf --- /dev/null +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/system/vo/ModerationForwardRecordVO.java @@ -0,0 +1,18 @@ +package com.xiaowang.jayucloud.salon.core.modules.system.vo; + +import lombok.Data; + +import java.time.LocalDateTime; + +@Data +public class ModerationForwardRecordVO { + private Long id; + private String traceId; + private String sourceEnv; + private String targetEnv; + private String status; + private Integer retryCount; + private String lastError; + private LocalDateTime createdAt; + private LocalDateTime updatedAt; +} diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/system/vo/SecureIntegrationConfigVO.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/system/vo/SecureIntegrationConfigVO.java index d8c3d72d..2500683c 100644 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/system/vo/SecureIntegrationConfigVO.java +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/modules/system/vo/SecureIntegrationConfigVO.java @@ -4,6 +4,7 @@ import lombok.Data; import java.time.LocalDateTime; import java.util.List; +import java.util.Map; @Data public class SecureIntegrationConfigVO { @@ -24,6 +25,11 @@ public class SecureIntegrationConfigVO { private String wechatMiniAppId; private Boolean mockProviderAllowed; + private Boolean moderationForwardEnabled; + private Map moderationForwardTargets; + private Boolean moderationForwardSecretConfigured; + private List moderationForwardRecent; + private Boolean encryptionKeyConfigured; private LocalDateTime updatedAt; /** 最近一次各服务接入探测结果;仅返回脱敏摘要和检查项。 */ 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 158af818..ec8e200e 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 @@ -629,7 +629,9 @@ public class UserServiceImpl extends ServiceImpl implements AppointmentCustomerOptionVO customer = new AppointmentCustomerOptionVO(); customer.setId(user.getId()); customer.setName(user.getNickname()); - customer.setPhone(resolveCustomerPhone(user)); + String plainPhone = resolveCustomerPhone(user); + customer.setPhone(phoneCrypto.mask(plainPhone)); + customer.setPhoneAvailable(StringUtils.hasText(plainPhone)); customer.setAvatar(resolveAccessibleAvatar(user.getAvatar())); customer.setCreatedAt(user.getCreateTime()); return customer; @@ -658,7 +660,9 @@ public class UserServiceImpl extends ServiceImpl implements AppointmentCustomerOptionVO option = new AppointmentCustomerOptionVO(); option.setId(user.getId()); option.setName(user.getNickname()); - option.setPhone(resolveCustomerPhone(user)); + String plainPhone = resolveCustomerPhone(user); + option.setPhone(phoneCrypto.mask(plainPhone)); + option.setPhoneAvailable(StringUtils.hasText(plainPhone)); option.setAvatar(resolveAccessibleAvatar(user.getAvatar())); option.setCreatedAt(user.getCreateTime()); return option; diff --git a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/support/security/RequestThrottleService.java b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/support/security/RequestThrottleService.java index 59c2c8d1..2f895c52 100644 --- a/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/support/security/RequestThrottleService.java +++ b/JC-Salon-Core/src/main/java/com/xiaowang/jayucloud/salon/core/support/security/RequestThrottleService.java @@ -90,6 +90,14 @@ public class RequestThrottleService { assertAllowed("agreement-read", request, sanitize(agreementType), rateLimitProperties.getAgreementRead(), "协议读取过于频繁,请稍后再试"); } + /** + * 客户拨号取号按用户维度限流,避免管理员批量拉取完整号码。 + */ + public void checkCustomerDial(HttpServletRequest request, Long userId) { + assertAllowed("customer-dial", request, userId == null ? "" : String.valueOf(userId), + rateLimitProperties.getCustomerDial(), "拨号取号过于频繁,请稍后再试"); + } + /** * Purpose: checkAuthenticatedWrite supports RequestThrottleService.java by holding or executing the check authenticated write business role. * Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state. diff --git a/JC-Salon-Core/src/main/resources/db/migration/V17__隐私政策与用户协议加密脱敏条款修订_20261104.sql b/JC-Salon-Core/src/main/resources/db/migration/V17__隐私政策与用户协议加密脱敏条款修订_20261104.sql new file mode 100644 index 00000000..58bb334b --- /dev/null +++ b/JC-Salon-Core/src/main/resources/db/migration/V17__隐私政策与用户协议加密脱敏条款修订_20261104.sql @@ -0,0 +1,109 @@ +-- 隐私政策与用户协议条款修订:对齐手机号/账号 AES-GCM 加密存储、HMAC 不可逆索引与按场景脱敏展示 +-- 版本:2026.11.04 +-- 说明:仅停用旧版本并新增协议版本,不修改已在任一环境执行的 V1/V3 协议正文。 + +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 + (313931273555140003, 'USER_TERMS', '用户协议', '2026.11.04', + '欢迎使用甲屿手纪 Salon 门店工作台。本服务供经门店授权的店长和员工管理门店日程、预约、员工和经营记录使用。本协议与《隐私政策》共同构成你使用本服务的基础规则。 + +一、协议接受与版本 +你在登录前应完整阅读本协议和《隐私政策》,并主动选择同意。不同意时,我们不会交换微信登录凭证,你也不能继续使用。本协议版本为 2026.11.04,自 2026 年 11 月 4 日起生效;协议发生重要变更时,我们会通过小程序提示并重新征得同意。 + +二、账号与使用权限 +1. 微信 OpenID 用于识别和关联工作台账号;账号仅供本人使用,不得转借、出租或共享。 +2. 昵称和头像为可选资料;手机号可选绑定,不绑定不影响基础工作台功能。 +3. 你应妥善保管登录设备与账号,不得绕过权限校验访问他人数据。离职或不再获授权时,门店管理员可以调整或停用账号权限。 +4. 手机号及手机号形式的账号按《隐私政策》所述采用加密存储和不可逆索引;常规页面展示脱敏号码,完整号码仅在必要业务场景和权限校验通过时展示。你不得擅自收集、导出或向无关第三方提供完整号码。 + +三、业务资料与内容 +1. 你仅可录入履行门店业务所需且有权处理的客户、预约、作品、员工和经营资料,并确保上传文字、图片来源合法,不得上传违法、侵权、欺诈或侵害他人权益的内容。 +2. 头像、作品、评论、店铺展示资料、公告和人工发布的消息会在公开前经过内容安全审核;未通过、待复核或服务异常的内容不会公开。 +3. 客户姓名和联系电话、预约与补单资料、备注、凭证、员工申请资料、内部审核说明和自动事务通知不纳入对外内容审核,但仍受门店权限和保密要求约束。 + +四、业务记录与金额 +订单及预约页面展示的金额用于门店经营记录,不构成平台收款、支付或退款承诺。当前平台不提供充值、订阅或平台虚拟权益购买。不得将工作台用于未经授权的资金收取、代收或虚拟权益交易。 + +五、账号注销与数据处理 +1. 你可在小程序“我的-账号设置”提交注销申请,并在处理前撤回。 +2. 管理员完成必要的门店移交或归档后,系统撤销会话并清理或匿名化 OpenID、昵称、头像、手机号等个人资料,目标处理期限为 15 个工作日。 +3. 解绑手机号经当前号码验证码核验后立即生效,系统清除手机号密文和检索索引。 +4. 必要的订单、预约和经营记录去除账号身份关联后,于实现目的所必需的最短期限内保存,当前产品目标为五年【待法务/业务确认】。 + +六、未成年人 +不满 14 周岁的未成年人应在监护人同意和陪同下阅读并使用本服务。门店不得要求未成年人独立提交与其年龄不相适应的个人信息。 + +七、服务调整、责任与联系 +1. 我们会在合理范围内维护服务,并可能因升级、维护或合规要求调整功能;重要调整将提前告知。 +2. 因你违反本协议、法律法规或侵害他人权益造成的损失,由你依法承担;因不可抗力、网络故障或第三方服务异常造成的服务中断,我们将在合理范围内协助恢复。 +3. 隐私相关申请可从账号设置发起或联系所属门店管理员;其他问题请联系门店管理员或运营方公布的客服渠道【待业务确认】。 + +本协议为产品说明文本,正式发布前应由运营方根据实际主体、业务和适用法律完成审核。', + 1, NOW(), NOW(), NOW(), 0), + (313931273555140004, 'PRIVACY_POLICY', '隐私政策', '2026.11.04', + '欢迎使用甲屿手纪 Salon 门店工作台。本政策说明我们如何处理店长、员工账号及门店业务资料中的个人信息。本政策与《用户协议》共同构成你使用本服务的基础规则。 + +一、我们处理的信息及用途 +1. 登录与账号:经你主动同意后,通过微信登录获取 OpenID,用于识别和关联账号;如你使用手机号注册或绑定,手机号仅用于注册登录、验证码校验、账号找回、订单联系和售后处理,不用于营销。 +2. 账号标识:账号用于身份识别、权限校验和操作归属记录。当账号本身为手机号时,该账号按手机号同等强度加密存储;其他账号标识仅用于身份识别,并通过不可逆索引支持查询匹配。 +3. 可选资料:昵称、头像仅在你主动补充或更新时处理。 +4. 门店业务资料:店长和员工可能录入客户姓名、可选联系电话、预约、作品、订单和经营记录,用于履行门店服务管理;这些资料不构成客户的小程序登录账号。 +5. 安全运行:服务端处理请求所需的网络地址、登录会话和操作审计信息,用于安全防护、故障排查和审计。我们不主动采集 IMEI、MAC、麦克风或持续定位信息;仅当你主动使用地图选点功能时,才会调用微信地图能力获取你选择的地点。 +6. 内容审核:头像、作品、评论、店铺展示资料、公告和人工发布的消息在对外展示前进行内容安全审核。 + +二、加密存储与检索索引 +1. 手机号以及手机号形式的账号使用 AES-GCM 加密后落库,密文带版本标识,不以明文存入数据库。 +2. 加密密钥由服务端按环境独立管理,仅授权服务进程读取,不通过接口、日志或客户端对外提供;密钥访问受配置权限和审计约束。 +3. 为实现登录、去重和查询匹配,系统另以 HMAC-SHA256 生成 phone_hash/account_hash 不可逆索引。该索引不能反推出手机号或账号原文,且不用于对外展示。 +4. 数据导出、备份和迁移沿用同等加密要求;如发生密钥轮换,按版本标识兼容解密并逐步重加密。 + +三、按场景脱敏展示 +1. 常规客户列表、详情页、日志、导出文件、通知消息及面向第三方的展示,手机号一律脱敏。 +2. 仅在门店预约选择客户、需要与客户进行业务联系等必要场景,且请求通过门店数据权限校验时,才向授权人员展示完整号码。 +3. 脱敏规则由服务端统一执行,不依赖前端隐藏;客户端不得缓存、截屏传播或在无权限场景转述完整号码。 +4. 客户本人资料页、员工账号资料页默认展示脱敏号码;修改绑定手机号时通过短信验证码核验,不以页面明文号码作为身份凭证。 + +四、第三方共享 +我们仅在实现功能所必需时与以下第三方共享必要信息,不将其用于其他目的: +1. 微信:微信登录、手机号授权、地图选点和内容安全审核(图片与文本)。 +2. 短信服务商:通过部署环境配置的短信通道发送验证码、绑定/解绑通知和必要的业务通知。 +3. 消息通道:通过 MessageHub 等已配置通道发送站内或订阅消息。 +4. 对象存储与 CDN:存储和分发头像、作品图片等文件,具体服务商按部署环境配置(七牛云、MinIO 或阿里云 OSS)。 +5. 地图服务:仅在你主动地图选点时,由微信内置地图能力(腾讯位置服务)处理所选位置。 +我们不会出售个人信息,也不会向无关第三方提供完整手机号。上线前,运营方应在微信后台隐私指引中逐项列明实际服务商名称、处理目的和字段范围【待法务/业务确认】。 + +五、保存期限与删除 +1. 解绑手机号:通过当前号码验证码核验后,立即清除手机号密文及 phone_hash 索引。 +2. 账号注销:可在小程序“我的-账号设置”提交申请,处理前可撤回;管理员完成门店移交或归档后撤销会话,并在目标 15 个工作日内删除或匿名化 OpenID、昵称、头像和手机号等个人资料。 +3. 订单、预约和经营记录:在去除账号身份关联后,于实现目的所必需的最短期限内保存;当前产品目标为五年【待法务/业务确认】。 +4. 安全审计日志:按安全审计要求保存,具体期限【待法务/业务确认】。 +5. 法律法规另有强制留存要求的,按法定期限保存,并在期限届满后删除或匿名化。 + +六、你的权利 +1. 查询与更正:可在个人资料页查看和修改昵称、头像等资料;手机号可在账号设置中更换。 +2. 删除与注销:可在账号设置申请注销或解绑;也可请求删除非业务必需的资料。 +3. 撤回同意:可在账号设置或联系门店管理员撤回待处理的授权;撤回后不影响撤回前已进行的处理。 +4. 投诉与咨询:可联系所属门店管理员,或通过运营方公布的客服渠道提交隐私请求;具体客服渠道【待业务/法务确认】。 +5. 我们将在收到请求后按适用法律规定的期限响应;对于无法核验身份的请求,可能要求补充验证。 + +七、未成年人保护 +本服务主要面向门店经营人员。不满 14 周岁的未成年人应在监护人同意和陪同下阅读并使用本服务;我们不会在明知未取得监护人同意的情况下处理其个人信息。如发现误收集,将停止处理并删除。 + +八、安全措施与安全事件响应 +我们采取加密存储、访问控制、最小权限、会话撤销、操作审计等措施保护个人信息。发生或可能发生个人信息泄露、篡改、丢失时,我们将立即采取补救措施,并按适用法律要求向你和监管部门告知事件情况、可能影响、已采取措施和自主防范建议;通知方式包括小程序公告、短信或电话【待业务确认】。 + +九、跨境传输 +目前我们不涉及向境外提供个人信息。如未来因业务需要发生跨境传输,我们将另行告知处理目的、接收方和联系方式,并依法取得单独同意或完成安全评估、备案等程序。 + +十、政策更新与联系 +本政策版本为 2026.11.04,自 2026 年 11 月 4 日起生效。处理目的、信息类别或第三方范围发生重要变化时,我们会更新版本并通过小程序提示、公告或重新征得同意等方式告知。你可在账号设置查看当前版本;其他问题请联系所属门店管理员。 + +本文件是产品说明,不构成法律意见;上线前应由运营方或专业顾问结合实际处理活动审阅。', + 1, NOW(), NOW(), NOW(), 0); diff --git a/JC-Salon-Core/src/main/resources/db/migration/V18__隐私政策与用户协议全场景脱敏条款修订_20261104.sql b/JC-Salon-Core/src/main/resources/db/migration/V18__隐私政策与用户协议全场景脱敏条款修订_20261104.sql new file mode 100644 index 00000000..95a9601b --- /dev/null +++ b/JC-Salon-Core/src/main/resources/db/migration/V18__隐私政策与用户协议全场景脱敏条款修订_20261104.sql @@ -0,0 +1,51 @@ +-- 隐私政策与用户协议条款修订:对齐“全场景脱敏 + 拨号按需单次取号 + 可接隐私号码”口径 +-- 版本:2026.11.04(V18) +-- 说明:仅更新当前生效版本的条款正文,不新增协议版本、不触发重新同意;静态 HTML 正文由 public/legal 读库渲染,不再维护副本。 + +UPDATE t_legal_agreement +SET content = REPLACE( + content, + '常规页面展示脱敏号码,完整号码仅在必要业务场景和权限校验通过时展示。', + '所有页面统一脱敏展示;确需联系客户时,须通过门店数据权限与预约/订单上下文校验后按需单次取号拨号,不批量展示完整号码;接入隐私号码服务时返回临时隐私号码。' + ), + update_time = NOW() +WHERE agreement_type = 'USER_TERMS' + AND status = 1 + AND is_delete = 0 + AND content LIKE '%常规页面展示脱敏号码,完整号码仅在必要业务场景和权限校验通过时展示。%'; + +UPDATE t_legal_agreement +SET content = REPLACE( + content, + '常规客户列表、详情页、日志、导出文件、通知消息及面向第三方的展示,手机号一律脱敏。', + '全部客户列表、详情页、日志、导出文件、通知消息及面向第三方的展示,手机号一律脱敏。' + ), + update_time = NOW() +WHERE agreement_type = 'PRIVACY_POLICY' + AND status = 1 + AND is_delete = 0 + AND content LIKE '%常规客户列表、详情页、日志、导出文件、通知消息及面向第三方的展示,手机号一律脱敏。%'; + +UPDATE t_legal_agreement +SET content = REPLACE( + content, + '仅在门店预约选择客户、需要与客户进行业务联系等必要场景,且请求通过门店数据权限校验时,才向授权人员展示完整号码。', + '确需与客户进行业务联系时,由授权人员在门店数据权限和预约/订单上下文校验通过后按需单次取号:直拨模式仅返回本次拨号号码,隐私号码模式返回临时隐私号码;完整号码不下发列表、不落库、不写日志、不进入缓存,且隐私号码未开通时不会回退为真实号码。' + ), + update_time = NOW() +WHERE agreement_type = 'PRIVACY_POLICY' + AND status = 1 + AND is_delete = 0 + AND content LIKE '%仅在门店预约选择客户、需要与客户进行业务联系等必要场景,且请求通过门店数据权限校验时,才向授权人员展示完整号码。%'; + +UPDATE t_legal_agreement +SET content = REPLACE( + content, + '客户本人资料页、员工账号资料页默认展示脱敏号码;', + '客户本人资料页、员工账号资料页一律展示脱敏号码;' + ), + update_time = NOW() +WHERE agreement_type = 'PRIVACY_POLICY' + AND status = 1 + AND is_delete = 0 + AND content LIKE '%客户本人资料页、员工账号资料页默认展示脱敏号码;%'; diff --git a/JC-Salon-Core/src/main/resources/db/migration/V19__隐私政策与用户协议新版本发布_20261104.sql b/JC-Salon-Core/src/main/resources/db/migration/V19__隐私政策与用户协议新版本发布_20261104.sql new file mode 100644 index 00000000..9accd378 --- /dev/null +++ b/JC-Salon-Core/src/main/resources/db/migration/V19__隐私政策与用户协议新版本发布_20261104.sql @@ -0,0 +1,30 @@ +-- 隐私政策与用户协议新版本发布:停用当前生效版本,并从停用前正文复制新版本 +-- 版本:2026.11.04-R2 +-- 说明:正文通过 INSERT ... SELECT 复制 V18 已修订的当前生效文本,不在 SQL 中重复维护长文本; +-- V18 已在任一环境执行后不得修改,本文件仅新增版本。 + +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) +SELECT 313931273555140005, 'USER_TERMS', title, '2026.11.04-R2', content, 1, + '2026-11-04 00:00:00', NOW(), NOW(), 0 +FROM t_legal_agreement +WHERE agreement_type = 'USER_TERMS' + AND is_delete = 0 +ORDER BY effective_time DESC, create_time DESC +LIMIT 1; + +INSERT INTO t_legal_agreement + (id, agreement_type, title, version, content, status, effective_time, create_time, update_time, is_delete) +SELECT 313931273555140006, 'PRIVACY_POLICY', title, '2026.11.04-R2', content, 1, + '2026-11-04 00:00:00', NOW(), NOW(), 0 +FROM t_legal_agreement +WHERE agreement_type = 'PRIVACY_POLICY' + AND is_delete = 0 +ORDER BY effective_time DESC, create_time DESC +LIMIT 1; diff --git a/JC-Salon-Core/src/main/resources/db/migration/V20__微信审核回调跨环境转发_20261104.sql b/JC-Salon-Core/src/main/resources/db/migration/V20__微信审核回调跨环境转发_20261104.sql new file mode 100644 index 00000000..ee34e64c --- /dev/null +++ b/JC-Salon-Core/src/main/resources/db/migration/V20__微信审核回调跨环境转发_20261104.sql @@ -0,0 +1,16 @@ +CREATE TABLE IF NOT EXISTS t_moderation_callback_forward ( + id BIGINT NOT NULL COMMENT '主键ID', + trace_id VARCHAR(128) NOT NULL COMMENT '微信异步图片审核任务标识 trace_id', + source_env VARCHAR(16) NOT NULL COMMENT '实际收到微信回调的部署环境', + target_env VARCHAR(16) NULL COMMENT '应处理该回调的部署环境', + extra_json VARCHAR(256) NULL COMMENT '微信回调透传的 extra 原始内容', + payload LONGTEXT NULL COMMENT '回调解密后的完整报文,仅用于补偿重放', + status VARCHAR(16) NOT NULL COMMENT 'PENDING/SUCCESS/RETRY/FAILED/NO_ENV/TARGET_MISSING', + retry_count INT NOT NULL DEFAULT 0 COMMENT '已重试次数', + last_error VARCHAR(500) NULL COMMENT '最近一次失败原因(脱敏)', + created_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间', + updated_at DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间', + PRIMARY KEY (id), + UNIQUE KEY uk_moderation_callback_forward_trace (trace_id), + KEY idx_moderation_callback_forward_status (status, updated_at) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='微信审核回调跨环境转发记录'; diff --git a/JC-Salon-Core/src/test/java/com/xiaowang/jayucloud/salon/core/config/AgreementAcceptanceInterceptorTest.java b/JC-Salon-Core/src/test/java/com/xiaowang/jayucloud/salon/core/config/AgreementAcceptanceInterceptorTest.java new file mode 100644 index 00000000..9149ab16 --- /dev/null +++ b/JC-Salon-Core/src/test/java/com/xiaowang/jayucloud/salon/core/config/AgreementAcceptanceInterceptorTest.java @@ -0,0 +1,91 @@ +package com.xiaowang.jayucloud.salon.core.config; + +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.xiaowang.jayucloud.salon.core.modules.system.support.AgreementVersionCacheService; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; +import org.springframework.mock.web.MockHttpServletRequest; +import org.springframework.mock.web.MockHttpServletResponse; + +import java.util.LinkedHashMap; +import java.util.Map; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.Mockito.when; + +@ExtendWith(MockitoExtension.class) +class AgreementAcceptanceInterceptorTest { + + @Mock private AgreementVersionCacheService agreementVersionCacheService; + + private AgreementAcceptanceInterceptor interceptor; + private final ObjectMapper objectMapper = new ObjectMapper(); + + @BeforeEach + void setUp() { + interceptor = new AgreementAcceptanceInterceptor(agreementVersionCacheService, objectMapper); + } + + @Test + void allowsUnauthenticatedRequest() throws Exception { + MockHttpServletRequest request = new MockHttpServletRequest(); + MockHttpServletResponse response = new MockHttpServletResponse(); + + assertTrue(interceptor.preHandle(request, response, new Object())); + } + + @Test + void allowsWhenAcceptedVersionsMatchCurrent() throws Exception { + Map versions = currentVersions(); + when(agreementVersionCacheService.currentVersions()).thenReturn(versions); + when(agreementVersionCacheService.acceptedVersions(9L)).thenReturn(new LinkedHashMap<>(versions)); + + assertTrue(interceptor.preHandle(authenticatedRequest(9L), new MockHttpServletResponse(), new Object())); + } + + @Test + void rejectsWithBusinessCodeWhenVersionPending() throws Exception { + Map versions = currentVersions(); + Map accepted = new LinkedHashMap<>(); + accepted.put("USER_TERMS", "2026.11.04"); + when(agreementVersionCacheService.currentVersions()).thenReturn(versions); + when(agreementVersionCacheService.acceptedVersions(9L)).thenReturn(accepted); + + MockHttpServletResponse response = new MockHttpServletResponse(); + assertFalse(interceptor.preHandle(authenticatedRequest(9L), response, new Object())); + + assertEquals(200, response.getStatus()); + JsonNode body = objectMapper.readTree(response.getContentAsString()); + assertEquals(AgreementAcceptanceInterceptor.AGREEMENT_VERSION_REQUIRED_CODE, body.get("code").asInt()); + assertEquals("2026.11.04-R2", body.get("data").get("currentVersions").get("USER_TERMS").asText()); + assertEquals("USER_TERMS", body.get("data").get("pendingTypes").get(0).asText()); + assertEquals(AgreementAcceptanceInterceptor.AGREEMENT_VERSION_REQUIRED_BUSINESS_CODE, + body.get("data").get("businessCode").asText()); + } + + @Test + void failsOpenWhenGuardComponentThrows() throws Exception { + when(agreementVersionCacheService.currentVersions()).thenThrow(new IllegalStateException("redis down")); + + assertTrue(interceptor.preHandle(authenticatedRequest(9L), new MockHttpServletResponse(), new Object())); + } + + private MockHttpServletRequest authenticatedRequest(Long userId) { + MockHttpServletRequest request = new MockHttpServletRequest(); + request.setAttribute("userId", userId); + return request; + } + + private Map currentVersions() { + Map versions = new LinkedHashMap<>(); + versions.put("USER_TERMS", "2026.11.04-R2"); + versions.put("PRIVACY_POLICY", "2026.11.04-R2"); + return versions; + } +} diff --git a/JC-Salon-Core/src/test/java/com/xiaowang/jayucloud/salon/core/modules/planning/service/impl/PlanningServiceImplTest.java b/JC-Salon-Core/src/test/java/com/xiaowang/jayucloud/salon/core/modules/planning/service/impl/PlanningServiceImplTest.java index 46273f97..1c1c1121 100644 --- a/JC-Salon-Core/src/test/java/com/xiaowang/jayucloud/salon/core/modules/planning/service/impl/PlanningServiceImplTest.java +++ b/JC-Salon-Core/src/test/java/com/xiaowang/jayucloud/salon/core/modules/planning/service/impl/PlanningServiceImplTest.java @@ -29,6 +29,7 @@ import com.xiaowang.jayucloud.salon.core.modules.user.entity.UserDO; import com.xiaowang.jayucloud.salon.core.modules.user.mapper.UserMapper; import com.xiaowang.jayucloud.salon.core.modules.user.service.UserService; import com.xiaowang.jayucloud.salon.core.support.id.TimeOrderedSnowflakeIdGenerator; +import com.xiaowang.jayucloud.salon.core.support.privacy.PhoneCrypto; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; @@ -69,6 +70,7 @@ class PlanningServiceImplTest { @Mock private WechatSubscribeMessageService wechatSubscribeMessageService; @Mock private TimeOrderedSnowflakeIdGenerator snowflakeIdGenerator; @Mock private ObjectStorageUrlSupport objectStorageUrlSupport; + @Mock private PhoneCrypto phoneCrypto; private PlanningServiceImpl service; @@ -77,7 +79,7 @@ class PlanningServiceImplTest { service = new PlanningServiceImpl(adminScopeHelper, userMapper, userService, nailArtistInfoMapper, artistScheduleMapper, artistScheduleExceptionMapper, appointmentReservationMapper, orderMapper, orderItemMapper, productMapper, shopMapper, shopBusinessExpiryService, shopBusinessScheduleService, appointmentCapacityService, orderService, wechatSubscribeMessageService, snowflakeIdGenerator, - objectStorageUrlSupport); + objectStorageUrlSupport, phoneCrypto); ShopBusinessHoursDayVO defaultOpenDay = new ShopBusinessHoursDayVO(); defaultOpenDay.setOpen(true); defaultOpenDay.setStartTime("10:00"); @@ -514,13 +516,15 @@ class PlanningServiceImplTest { when(orderItemMapper.selectById(64L)).thenReturn(item); when(orderMapper.selectById(54L)).thenReturn(order); when(userMapper.selectList(any(Wrapper.class))).thenReturn(java.util.List.of()); + when(phoneCrypto.mask("13800138000")).thenReturn("138****8000"); com.xiaowang.jayucloud.salon.core.modules.planning.vo.PlanningAppointmentVO result = service.getAppointment(operator, 64L); assertNull(result.getCustomerId()); assertEquals("散客预约", result.getCustomerName()); - assertEquals("13800138000", result.getCustomerPhone()); + assertEquals("138****8000", result.getCustomerPhone()); + assertEquals(Boolean.TRUE, result.getCustomerPhoneAvailable()); assertEquals("门店临时闭店", result.getCancelReason()); verify(userMapper, never()).selectById(org.mockito.ArgumentMatchers.isNull()); } diff --git a/JC-Salon-Core/src/test/java/com/xiaowang/jayucloud/salon/core/modules/privacy/controller/front/WechatContentModerationCallbackControllerTest.java b/JC-Salon-Core/src/test/java/com/xiaowang/jayucloud/salon/core/modules/privacy/controller/front/WechatContentModerationCallbackControllerTest.java index 6b91d189..7e34bb01 100644 --- a/JC-Salon-Core/src/test/java/com/xiaowang/jayucloud/salon/core/modules/privacy/controller/front/WechatContentModerationCallbackControllerTest.java +++ b/JC-Salon-Core/src/test/java/com/xiaowang/jayucloud/salon/core/modules/privacy/controller/front/WechatContentModerationCallbackControllerTest.java @@ -1,45 +1,51 @@ package com.xiaowang.jayucloud.salon.core.modules.privacy.controller.front; import com.fasterxml.jackson.databind.ObjectMapper; +import com.xiaowang.jayucloud.salon.core.config.SalonDeployProperties; import com.xiaowang.jayucloud.salon.core.config.WechatMiniProperties; +import com.xiaowang.jayucloud.salon.core.modules.privacy.service.ContentModerationForwardService; import com.xiaowang.jayucloud.salon.core.modules.privacy.service.ContentModerationService; import com.xiaowang.jayucloud.salon.core.modules.privacy.support.WechatCallbackCrypto; +import com.xiaowang.jayucloud.salon.core.modules.system.secure.ModerationForwardConfig; import com.xiaowang.jayucloud.salon.core.modules.system.secure.ModerationRuntimeConfig; import com.xiaowang.jayucloud.salon.core.modules.system.service.SecureIntegrationConfigService; import com.xiaowang.jayucloud.salon.core.modules.system.service.IntegrationProbeService; +import org.junit.jupiter.api.Test; import org.springframework.http.MediaType; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.setup.MockMvcBuilders; -import org.junit.jupiter.api.Test; + +import java.util.Map; import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.never; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; class WechatContentModerationCallbackControllerTest { + private static final String CALLBACK_PATH = "/api/integration/wechat/content-moderation/callback"; + @Test void aesHandshakeVerifiesEncryptedEchoAndReturnsDecryptedValue() { SecureIntegrationConfigService secureConfig = mock(SecureIntegrationConfigService.class); when(secureConfig.getModerationCallbackConfig()).thenReturn( - new ModerationRuntimeConfig("WECHAT", "https://sit.example.test/api/integration/wechat/content-moderation/callback", "callback-token", "encoding-aes-key", true)); - WechatMiniProperties wechatProperties = new WechatMiniProperties(); - wechatProperties.setAppId("mini-app-id"); + new ModerationRuntimeConfig("WECHAT", "https://sit.example.test" + CALLBACK_PATH, "callback-token", "encoding-aes-key", true)); WechatCallbackCrypto crypto = mock(WechatCallbackCrypto.class); when(crypto.verify("callback-token", "1000", "nonce", "encrypted-echo", "message-signature")) .thenReturn(true); when(crypto.decrypt("encrypted-echo", "encoding-aes-key", "mini-app-id")) .thenReturn("verified-echo"); - WechatContentModerationCallbackController controller = new WechatContentModerationCallbackController( - secureConfig, - wechatProperties, - crypto, - mock(ContentModerationService.class), - mock(IntegrationProbeService.class), - new ObjectMapper()); + WechatContentModerationCallbackController controller = controller(secureConfig, crypto, + mock(ContentModerationService.class), mock(IntegrationProbeService.class), + mock(ContentModerationForwardService.class)); String result = controller.verifyEndpoint("1000", "nonce", "message-signature", null, "aes", "encrypted-echo"); @@ -52,31 +58,31 @@ class WechatContentModerationCallbackControllerTest { void plaintextHandshakeStillUsesPlainSignature() { SecureIntegrationConfigService secureConfig = mock(SecureIntegrationConfigService.class); when(secureConfig.getModerationCallbackConfig()).thenReturn( - new ModerationRuntimeConfig("WECHAT", "https://sit.example.test/api/integration/wechat/content-moderation/callback", "callback-token", "encoding-aes-key", true)); + new ModerationRuntimeConfig("WECHAT", "https://sit.example.test" + CALLBACK_PATH, "callback-token", "encoding-aes-key", true)); WechatCallbackCrypto crypto = mock(WechatCallbackCrypto.class); when(crypto.verifyPlain("callback-token", "1000", "nonce", "plain-signature")).thenReturn(true); - WechatContentModerationCallbackController controller = new WechatContentModerationCallbackController( - secureConfig, - new WechatMiniProperties(), - crypto, - mock(ContentModerationService.class), - mock(IntegrationProbeService.class), - new ObjectMapper()); + WechatMiniProperties wechatProperties = new WechatMiniProperties(); + wechatProperties.setAppId("mini-app-id"); + WechatContentModerationCallbackController controller = controller(secureConfig, crypto, + mock(ContentModerationService.class), mock(IntegrationProbeService.class), + mock(ContentModerationForwardService.class)); assertEquals("echo", controller.verifyEndpoint("1000", "nonce", null, "plain-signature", null, "echo")); verify(crypto).verifyPlain("callback-token", "1000", "nonce", "plain-signature"); } @Test - void acceptsJsonEnvelopeForAesEncryptedCallback() throws Exception { + void localHitDoesNotForward() throws Exception { SecureIntegrationConfigService secureConfig = readyWechatConfig(); WechatCallbackCrypto crypto = mock(WechatCallbackCrypto.class); ContentModerationService moderationService = mock(ContentModerationService.class); - when(crypto.verify("callback-token", "1000", "nonce", "encrypted-json", "message-signature")) - .thenReturn(true); + ContentModerationForwardService forwardService = mock(ContentModerationForwardService.class); + when(crypto.verify("callback-token", "1000", "nonce", "encrypted-json", "message-signature")).thenReturn(true); when(crypto.decrypt("encrypted-json", "encoding-aes-key", "mini-app-id")) - .thenReturn("{\"trace_id\":\"task-json\",\"result\":{\"suggest\":\"pass\"},\"extra\":\"{\\\"envVersion\\\":\\\"trial\\\"}\"}"); - MockMvc mvc = MockMvcBuilders.standaloneSetup(controller(secureConfig, crypto, moderationService)).build(); + .thenReturn("{\"trace_id\":\"task-json\",\"result\":{\"suggest\":\"pass\"},\"extra\":\"{\\\"env\\\":\\\"prod\\\",\\\"envVersion\\\":\\\"trial\\\"}\"}"); + when(moderationService.handleWechatImageResult("task-json", "pass", "微信异步图片审核回调", "trial")).thenReturn(true); + MockMvc mvc = MockMvcBuilders.standaloneSetup(controller(secureConfig, crypto, moderationService, + mock(IntegrationProbeService.class), forwardService)).build(); mvc.perform(post("/integration/wechat/content-moderation/callback") .param("timestamp", "1000") @@ -90,6 +96,8 @@ class WechatContentModerationCallbackControllerTest { verify(crypto).verify("callback-token", "1000", "nonce", "encrypted-json", "message-signature"); verify(moderationService).handleWechatImageResult("task-json", "pass", "微信异步图片审核回调", "trial"); + verify(forwardService, never()).enqueue(anyString(), anyString(), anyString(), any(), anyString()); + verify(forwardService, never()).recordUnclaimed(anyString(), any(), any(), anyString()); } @Test @@ -99,14 +107,15 @@ class WechatContentModerationCallbackControllerTest { ContentModerationService moderationService = mock(ContentModerationService.class); String xml = "encrypted-xml"; when(crypto.encryptedValue(xml)).thenReturn("encrypted-xml"); - when(crypto.verify("callback-token", "1000", "nonce", "encrypted-xml", "message-signature")) - .thenReturn(true); - String decodedXml = "task-xmlreview{"envVersion":"release"}"; + when(crypto.verify("callback-token", "1000", "nonce", "encrypted-xml", "message-signature")).thenReturn(true); + String decodedXml = "task-xmlreview{"env":"prod","envVersion":"release"}"; when(crypto.decrypt("encrypted-xml", "encoding-aes-key", "mini-app-id")).thenReturn(decodedXml); when(crypto.value(decodedXml, "trace_id")).thenReturn("task-xml"); when(crypto.value(decodedXml, "suggest")).thenReturn("review"); - when(crypto.value(decodedXml, "extra")).thenReturn("{\"envVersion\":\"release\"}"); - MockMvc mvc = MockMvcBuilders.standaloneSetup(controller(secureConfig, crypto, moderationService)).build(); + when(crypto.value(decodedXml, "extra")).thenReturn("{\"env\":\"prod\",\"envVersion\":\"release\"}"); + when(moderationService.handleWechatImageResult("task-xml", "review", "微信异步图片审核回调", "release")).thenReturn(true); + MockMvc mvc = MockMvcBuilders.standaloneSetup(controller(secureConfig, crypto, moderationService, + mock(IntegrationProbeService.class), mock(ContentModerationForwardService.class))).build(); mvc.perform(post("/integration/wechat/content-moderation/callback") .param("timestamp", "1000") @@ -122,19 +131,170 @@ class WechatContentModerationCallbackControllerTest { verify(moderationService).handleWechatImageResult("task-xml", "review", "微信异步图片审核回调", "release"); } + @Test + void probeHitSkipsModerationAndForwarding() throws Exception { + SecureIntegrationConfigService secureConfig = readyWechatConfig(); + WechatCallbackCrypto crypto = mock(WechatCallbackCrypto.class); + IntegrationProbeService probeService = mock(IntegrationProbeService.class); + ContentModerationForwardService forwardService = mock(ContentModerationForwardService.class); + when(crypto.verify("callback-token", "1000", "nonce", "encrypted-json", "message-signature")).thenReturn(true); + when(crypto.decrypt("encrypted-json", "encoding-aes-key", "mini-app-id")) + .thenReturn("{\"trace_id\":\"probe-1\",\"suggest\":\"review\",\"extra\":\"{\\\"env\\\":\\\"prod\\\",\\\"probeId\\\":\\\"probe-1\\\"}\"}"); + when(probeService.handleImageCallback("probe-1", "review", "probe-1")).thenReturn(true); + MockMvc mvc = MockMvcBuilders.standaloneSetup(controller(secureConfig, crypto, + mock(ContentModerationService.class), probeService, forwardService)).build(); + + mvc.perform(post("/integration/wechat/content-moderation/callback") + .param("timestamp", "1000") + .param("nonce", "nonce") + .param("msg_signature", "message-signature") + .param("encrypt_type", "aes") + .contentType(MediaType.APPLICATION_JSON) + .content("{\"Encrypt\":\"encrypted-json\"}")) + .andExpect(status().isOk()) + .andExpect(content().string("success")); + + verify(forwardService, never()).enqueue(anyString(), anyString(), anyString(), any(), anyString()); + } + + @Test + void otherEnvironmentCallbackIsEnqueuedAndReturnsSuccessImmediately() throws Exception { + SecureIntegrationConfigService secureConfig = readyWechatConfig(); + WechatCallbackCrypto crypto = mock(WechatCallbackCrypto.class); + ContentModerationService moderationService = mock(ContentModerationService.class); + ContentModerationForwardService forwardService = mock(ContentModerationForwardService.class); + when(crypto.verify(anyString(), anyString(), anyString(), anyString(), anyString())).thenReturn(true); + when(crypto.decrypt(anyString(), anyString(), anyString())) + .thenReturn("{\"trace_id\":\"task-prod\",\"suggest\":\"review\",\"extra\":\"{\\\"env\\\":\\\"prod\\\"}\"}"); + when(moderationService.handleWechatImageResult(anyString(), anyString(), anyString(), any())).thenReturn(false); + when(forwardService.runtimeConfig()).thenReturn(forwardConfig(Map.of("prod", "https://prod.example.test" + CALLBACK_PATH))); + MockMvc mvc = MockMvcBuilders.standaloneSetup(controller(secureConfig, crypto, moderationService, + mock(IntegrationProbeService.class), forwardService)).build(); + + mvc.perform(post("/integration/wechat/content-moderation/callback") + .param("timestamp", "1000") + .param("nonce", "nonce") + .param("msg_signature", "message-signature") + .param("encrypt_type", "aes") + .contentType(MediaType.APPLICATION_JSON) + .content("{\"Encrypt\":\"encrypted-json\"}")) + .andExpect(status().isOk()) + .andExpect(content().string("success")); + + verify(forwardService).enqueue(eq("task-prod"), eq("sit"), eq("prod"), anyString(), anyString()); + } + + @Test + void missingTargetReturnsSuccessAndRecordsTargetMissing() throws Exception { + SecureIntegrationConfigService secureConfig = readyWechatConfig(); + WechatCallbackCrypto crypto = mock(WechatCallbackCrypto.class); + ContentModerationService moderationService = mock(ContentModerationService.class); + ContentModerationForwardService forwardService = mock(ContentModerationForwardService.class); + when(crypto.verify(anyString(), anyString(), anyString(), anyString(), anyString())).thenReturn(true); + when(crypto.decrypt(anyString(), anyString(), anyString())) + .thenReturn("{\"trace_id\":\"task-prod\",\"suggest\":\"review\",\"extra\":\"{\\\"env\\\":\\\"prod\\\"}\"}"); + when(moderationService.handleWechatImageResult(anyString(), anyString(), anyString(), any())).thenReturn(false); + when(forwardService.runtimeConfig()).thenReturn(forwardConfig(Map.of())); + MockMvc mvc = MockMvcBuilders.standaloneSetup(controller(secureConfig, crypto, moderationService, + mock(IntegrationProbeService.class), forwardService)).build(); + + mvc.perform(post("/integration/wechat/content-moderation/callback") + .param("timestamp", "1000") + .param("nonce", "nonce") + .param("msg_signature", "message-signature") + .param("encrypt_type", "aes") + .contentType(MediaType.APPLICATION_JSON) + .content("{\"Encrypt\":\"encrypted-json\"}")) + .andExpect(status().isOk()) + .andExpect(content().string("success")); + + verify(forwardService).recordTargetMissing(eq("task-prod"), eq("sit"), eq("prod"), anyString(), anyString()); + } + + @Test + void extraWithoutEnvIsRecordedAsNoEnvAndNotForwarded() throws Exception { + SecureIntegrationConfigService secureConfig = readyWechatConfig(); + WechatCallbackCrypto crypto = mock(WechatCallbackCrypto.class); + ContentModerationService moderationService = mock(ContentModerationService.class); + ContentModerationForwardService forwardService = mock(ContentModerationForwardService.class); + when(crypto.verify(anyString(), anyString(), anyString(), anyString(), anyString())).thenReturn(true); + when(crypto.decrypt(anyString(), anyString(), anyString())) + .thenReturn("{\"trace_id\":\"task-unknown\",\"suggest\":\"review\",\"extra\":\"{\\\"envVersion\\\":\\\"trial\\\"}\"}"); + when(moderationService.handleWechatImageResult(anyString(), anyString(), anyString(), any())).thenReturn(false); + when(forwardService.runtimeConfig()).thenReturn(forwardConfig(Map.of("prod", "https://prod.example.test" + CALLBACK_PATH))); + MockMvc mvc = MockMvcBuilders.standaloneSetup(controller(secureConfig, crypto, moderationService, + mock(IntegrationProbeService.class), forwardService)).build(); + + mvc.perform(post("/integration/wechat/content-moderation/callback") + .param("timestamp", "1000") + .param("nonce", "nonce") + .param("msg_signature", "message-signature") + .param("encrypt_type", "aes") + .contentType(MediaType.APPLICATION_JSON) + .content("{\"Encrypt\":\"encrypted-json\"}")) + .andExpect(status().isOk()) + .andExpect(content().string("success")); + + verify(forwardService).recordUnclaimed(eq("task-unknown"), anyString(), anyString(), anyString()); + verify(forwardService, never()).enqueue(anyString(), anyString(), anyString(), any(), anyString()); + } + + @Test + void secondHopOrSelfForwardIsDroppedAndRecorded() throws Exception { + ContentModerationForwardService forwardService = mock(ContentModerationForwardService.class); + when(forwardService.verifySignature(anyString(), anyString(), anyString(), anyString())).thenReturn(true); + MockMvc mvc = MockMvcBuilders.standaloneSetup(controller(readyWechatConfig(), mock(WechatCallbackCrypto.class), + mock(ContentModerationService.class), mock(IntegrationProbeService.class), forwardService)).build(); + + mvc.perform(post("/integration/wechat/content-moderation/callback") + .header("X-Moderation-Forward-By", "sit") + .header("X-Moderation-Forward-Hop", "2") + .header("X-Timestamp", "1000") + .header("X-Nonce", "forward-nonce") + .header("X-Signature", "forward-signature") + .contentType(MediaType.APPLICATION_JSON) + .content("{\"trace_id\":\"loop-task\",\"suggest\":\"review\"}")) + .andExpect(status().isOk()) + .andExpect(content().string("success")); + + verify(forwardService).recordUnclaimed(eq("loop-task"), any(), anyString(), anyString()); + verify(forwardService, never()).enqueue(anyString(), anyString(), anyString(), any(), anyString()); + } + + @Test + void forwardedSignatureFailureIsRejected() { + ContentModerationForwardService forwardService = mock(ContentModerationForwardService.class); + when(forwardService.verifySignature(anyString(), anyString(), anyString(), anyString())).thenReturn(false); + WechatContentModerationCallbackController controller = controller(readyWechatConfig(), + mock(WechatCallbackCrypto.class), mock(ContentModerationService.class), + mock(IntegrationProbeService.class), forwardService); + + assertThrows(IllegalArgumentException.class, () -> controller.callback(null, null, null, null, null, + "prod", "1", "1000", "forward-nonce", "bad-signature", + "{\"trace_id\":\"task-1\"}")); + } + + private ModerationForwardConfig forwardConfig(Map targets) { + return new ModerationForwardConfig(true, targets, "forward-secret-key-01"); + } + private SecureIntegrationConfigService readyWechatConfig() { SecureIntegrationConfigService secureConfig = mock(SecureIntegrationConfigService.class); when(secureConfig.getModerationCallbackConfig()).thenReturn( - new ModerationRuntimeConfig("WECHAT", "https://sit.example.test/api/integration/wechat/content-moderation/callback", "callback-token", "encoding-aes-key", true)); + new ModerationRuntimeConfig("WECHAT", "https://sit.example.test" + CALLBACK_PATH, "callback-token", "encoding-aes-key", true)); return secureConfig; } private WechatContentModerationCallbackController controller(SecureIntegrationConfigService secureConfig, WechatCallbackCrypto crypto, - ContentModerationService moderationService) { + ContentModerationService moderationService, + IntegrationProbeService probeService, + ContentModerationForwardService forwardService) { WechatMiniProperties wechatProperties = new WechatMiniProperties(); wechatProperties.setAppId("mini-app-id"); - return new WechatContentModerationCallbackController( - secureConfig, wechatProperties, crypto, moderationService, mock(IntegrationProbeService.class), new ObjectMapper()); + SalonDeployProperties deployProperties = new SalonDeployProperties(); + deployProperties.setEnv("sit"); + return new WechatContentModerationCallbackController(secureConfig, wechatProperties, crypto, + moderationService, probeService, forwardService, deployProperties, new ObjectMapper()); } } diff --git a/JC-Salon-Core/src/test/java/com/xiaowang/jayucloud/salon/core/modules/privacy/service/impl/ContentModerationForwardServiceImplTest.java b/JC-Salon-Core/src/test/java/com/xiaowang/jayucloud/salon/core/modules/privacy/service/impl/ContentModerationForwardServiceImplTest.java new file mode 100644 index 00000000..4e0a40a1 --- /dev/null +++ b/JC-Salon-Core/src/test/java/com/xiaowang/jayucloud/salon/core/modules/privacy/service/impl/ContentModerationForwardServiceImplTest.java @@ -0,0 +1,172 @@ +package com.xiaowang.jayucloud.salon.core.modules.privacy.service.impl; + +import com.xiaowang.jayucloud.salon.core.config.SalonDeployProperties; +import com.xiaowang.jayucloud.salon.core.modules.privacy.support.ModerationForwardHttpClient; +import com.xiaowang.jayucloud.salon.core.modules.system.entity.ModerationCallbackForwardDO; +import com.xiaowang.jayucloud.salon.core.modules.system.mapper.ModerationCallbackForwardMapper; +import com.xiaowang.jayucloud.salon.core.modules.system.secure.ModerationForwardConfig; +import com.xiaowang.jayucloud.salon.core.modules.system.service.SecureIntegrationConfigService; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.mockito.ArgumentCaptor; +import org.springframework.data.redis.core.RedisTemplate; +import org.springframework.data.redis.core.ValueOperations; + +import java.nio.charset.StandardCharsets; +import java.security.MessageDigest; +import java.time.Duration; +import java.time.LocalDateTime; +import java.util.List; +import java.util.Map; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyString; + +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +class ContentModerationForwardServiceImplTest { + private static final String SECRET = "forward-secret-key-01"; + private static final String TARGET = "https://prod.example.test/api/integration/wechat/content-moderation/callback"; + + private ModerationCallbackForwardMapper forwardMapper; + private SecureIntegrationConfigService secureConfig; + private ModerationForwardHttpClient httpClient; + private RedisTemplate redisTemplate; + private ValueOperations valueOperations; + private ContentModerationForwardServiceImpl service; + + @BeforeEach + @SuppressWarnings("unchecked") + void setUp() { + forwardMapper = mock(ModerationCallbackForwardMapper.class); + secureConfig = mock(SecureIntegrationConfigService.class); + httpClient = mock(ModerationForwardHttpClient.class); + redisTemplate = mock(RedisTemplate.class); + valueOperations = mock(ValueOperations.class); + when(redisTemplate.opsForValue()).thenReturn(valueOperations); + when(valueOperations.setIfAbsent(anyString(), any(), any(Duration.class))).thenReturn(true); + when(secureConfig.getModerationForwardConfig()) + .thenReturn(new ModerationForwardConfig(true, Map.of("prod", TARGET), SECRET)); + SalonDeployProperties deployProperties = new SalonDeployProperties(); + deployProperties.setEnv("sit"); + service = new ContentModerationForwardServiceImpl(forwardMapper, secureConfig, deployProperties, + redisTemplate, httpClient); + } + + @Test + void acceptsValidHmacSignature() throws Exception { + String timestamp = String.valueOf(System.currentTimeMillis() / 1000); + String nonce = "nonce-valid"; + String body = "{\"trace_id\":\"task-1\"}"; + String signature = sign(SECRET, timestamp, nonce, body); + + assertTrue(service.verifySignature(timestamp, nonce, signature, body)); + } + + @Test + void rejectsInvalidHmacSignature() { + String timestamp = String.valueOf(System.currentTimeMillis() / 1000); + + assertFalse(service.verifySignature(timestamp, "nonce-bad", "deadbeef", "{\"trace_id\":\"task-1\"}")); + } + + @Test + void rejectsExpiredTimestamp() { + String timestamp = String.valueOf(System.currentTimeMillis() / 1000 - 600); + + assertFalse(service.verifySignature(timestamp, "nonce-expired", "deadbeef", "{}")); + } + + @Test + void retryPendingMarksSuccessWhenTargetAccepts() { + ModerationCallbackForwardDO row = new ModerationCallbackForwardDO(); + row.setId(11L); + row.setTraceId("task-retry"); + row.setSourceEnv("sit"); + row.setTargetEnv("prod"); + row.setStatus("RETRY"); + row.setRetryCount(1); + row.setUpdatedAt(LocalDateTime.now().minusMinutes(5)); + row.setPayload("{\"trace_id\":\"task-retry\"}"); + when(forwardMapper.selectList(any())).thenReturn(List.of(row)); + when(forwardMapper.selectById(11L)).thenReturn(row); + when(httpClient.post(anyString(), anyString(), any())).thenReturn(true); + + int attempted = service.retryPending(); + + assertEquals(1, attempted); + assertEquals("SUCCESS", row.getStatus()); + verify(forwardMapper).updateById(row); + } + + @Test + void retryFailureIncrementsCountAndKeepsRetry() { + ModerationCallbackForwardDO row = new ModerationCallbackForwardDO(); + row.setId(12L); + row.setTraceId("task-fail"); + row.setSourceEnv("sit"); + row.setTargetEnv("prod"); + row.setStatus("RETRY"); + row.setRetryCount(0); + row.setUpdatedAt(null); + row.setPayload("{\"trace_id\":\"task-fail\"}"); + when(forwardMapper.selectList(any())).thenReturn(List.of(row)); + when(forwardMapper.selectById(12L)).thenReturn(row); + when(httpClient.post(anyString(), anyString(), any())).thenThrow(new IllegalStateException("timeout")); + + service.retryPending(); + + assertEquals("RETRY", row.getStatus()); + assertEquals(1, row.getRetryCount()); + assertEquals("目标环境不可达或请求失败", row.getLastError()); + } + + @Test + void targetMissingIsRecordedWithoutRetryQueue() { + service.recordTargetMissing("task-missing", "sit", "prod", "{\"env\":\"prod\"}", "{}"); + + ArgumentCaptor captor = ArgumentCaptor.forClass(ModerationCallbackForwardDO.class); + verify(forwardMapper).insert(captor.capture()); + ModerationCallbackForwardDO saved = captor.getValue(); + assertEquals("TARGET_MISSING", saved.getStatus()); + assertEquals("prod", saved.getTargetEnv()); + assertEquals(0, saved.getRetryCount()); + } + + @Test + void missingExtraIsRecordedAsNoEnv() { + service.recordUnclaimed("task-noenv", "{\"envVersion\":\"trial\"}", "{}", "回调 extra 缺少部署环境标识"); + + ArgumentCaptor captor = ArgumentCaptor.forClass(ModerationCallbackForwardDO.class); + verify(forwardMapper).insert(captor.capture()); + assertEquals("NO_ENV", captor.getValue().getStatus()); + assertEquals("sit", captor.getValue().getSourceEnv()); + } + + @Test + void requeueMovesTargetMissingToRetryForConfiguredTargets() { + when(forwardMapper.update(any(), any())).thenReturn(2); + + int requeued = service.requeueConfiguredTargets(); + + assertEquals(2, requeued); + verify(forwardMapper).update(org.mockito.ArgumentMatchers.isNull(), any()); + } + + private String sign(String secret, String timestamp, String nonce, String body) throws Exception { + MessageDigest digest = MessageDigest.getInstance("SHA-256"); + StringBuilder bodyHash = new StringBuilder(); + for (byte item : digest.digest(body.getBytes(StandardCharsets.UTF_8))) bodyHash.append(String.format("%02x", item)); + String canonical = timestamp + "\n" + nonce + "\n" + bodyHash; + javax.crypto.Mac mac = javax.crypto.Mac.getInstance("HmacSHA256"); + mac.init(new javax.crypto.spec.SecretKeySpec(secret.getBytes(StandardCharsets.UTF_8), "HmacSHA256")); + StringBuilder result = new StringBuilder(); + for (byte item : mac.doFinal(canonical.getBytes(StandardCharsets.UTF_8))) result.append(String.format("%02x", item)); + return result.toString(); + } +} diff --git a/JC-Salon-Core/src/test/java/com/xiaowang/jayucloud/salon/core/modules/privacy/service/impl/CustomerDialServiceImplTest.java b/JC-Salon-Core/src/test/java/com/xiaowang/jayucloud/salon/core/modules/privacy/service/impl/CustomerDialServiceImplTest.java new file mode 100644 index 00000000..d9c89eb0 --- /dev/null +++ b/JC-Salon-Core/src/test/java/com/xiaowang/jayucloud/salon/core/modules/privacy/service/impl/CustomerDialServiceImplTest.java @@ -0,0 +1,221 @@ +package com.xiaowang.jayucloud.salon.core.modules.privacy.service.impl; + +import com.xiaowang.jayucloud.salon.core.common.BusinessException; +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.order.mapper.OrderItemMapper; +import com.xiaowang.jayucloud.salon.core.modules.order.mapper.OrderMapper; +import com.xiaowang.jayucloud.salon.core.modules.privacy.config.DialProperties; +import com.xiaowang.jayucloud.salon.core.modules.privacy.dial.DialMode; +import com.xiaowang.jayucloud.salon.core.modules.privacy.dial.DialTargetProvider; +import com.xiaowang.jayucloud.salon.core.modules.privacy.dial.DirectDialTargetProvider; +import com.xiaowang.jayucloud.salon.core.modules.privacy.dial.PlaceholderPrivacyNumberProvider; +import com.xiaowang.jayucloud.salon.core.modules.privacy.vo.CustomerDialVO; +import com.xiaowang.jayucloud.salon.core.modules.security.support.AdminScopeHelper; +import com.xiaowang.jayucloud.salon.core.modules.security.support.SecurityAuditSupport; +import com.xiaowang.jayucloud.salon.core.modules.user.entity.UserDO; +import com.xiaowang.jayucloud.salon.core.modules.user.service.UserService; +import com.xiaowang.jayucloud.salon.core.support.privacy.PhoneCrypto; +import com.xiaowang.jayucloud.salon.core.support.security.RequestThrottleService; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; + +import javax.servlet.http.HttpServletRequest; +import java.util.List; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.ArgumentMatchers.anyString; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +@ExtendWith(MockitoExtension.class) +class CustomerDialServiceImplTest { + + @Mock private AdminScopeHelper adminScopeHelper; + @Mock private UserService userService; + @Mock private OrderMapper orderMapper; + @Mock private OrderItemMapper orderItemMapper; + @Mock private RequestThrottleService requestThrottleService; + @Mock private SecurityAuditSupport securityAuditSupport; + @Mock private PhoneCrypto phoneCrypto; + @Mock private HttpServletRequest request; + + private CustomerDialServiceImpl service; + private UserDO currentUser; + private UserDO customer; + private OrderDO order; + + @BeforeEach + void setUp() { + DialProperties properties = new DialProperties(); + List providers = List.of( + new DirectDialTargetProvider(phoneCrypto), + new PlaceholderPrivacyNumberProvider()); + service = new CustomerDialServiceImpl(adminScopeHelper, userService, orderMapper, orderItemMapper, + requestThrottleService, securityAuditSupport, properties, providers); + + currentUser = new UserDO(); + currentUser.setId(9L); + currentUser.setType(2); + currentUser.setShopId(1L); + + customer = new UserDO(); + customer.setId(100L); + customer.setType(0); + customer.setIsDelete(0); + + order = new OrderDO(); + order.setId(10L); + order.setUserId(100L); + order.setShopId(1L); + order.setIsDelete(0); + } + + @Test + void directProviderReturnsFullNumberOnceAndWritesAudit() { + customer.setPhone("encrypted-phone"); + when(phoneCrypto.decrypt("encrypted-phone")).thenReturn("13800138000"); + when(userService.getById(100L)).thenReturn(customer); + when(orderMapper.selectById(10L)).thenReturn(order); + + CustomerDialVO result = service.dial(currentUser, 100L, null, 10L, request); + + assertEquals(DialMode.DIRECT, result.getMode()); + assertEquals("13800138000", result.getDialNumber()); + verify(requestThrottleService).checkCustomerDial(request, 9L); + verify(securityAuditSupport).success(eq(request), anyString(), anyString()); + } + + @Test + void guestOrderUsesSnapshotWithoutRequiringCustomerAccount() { + order.setUserId(null); + order.setCustomerPhoneSnapshot("encrypted-snapshot"); + when(phoneCrypto.decrypt("encrypted-snapshot")).thenReturn("13900139000"); + when(orderMapper.selectById(10L)).thenReturn(order); + + CustomerDialVO result = service.dial(currentUser, null, null, 10L, request); + + assertEquals("13900139000", result.getDialNumber()); + assertEquals(DialMode.DIRECT, result.getMode()); + verify(securityAuditSupport).success(eq(request), anyString(), anyString()); + } + + @Test + void orderSnapshotTakesPriorityOverCustomerProfile() { + order.setCustomerPhoneSnapshot("encrypted-snapshot"); + customer.setPhone("encrypted-customer-phone"); + when(phoneCrypto.decrypt("encrypted-snapshot")).thenReturn("13900139000"); + when(userService.getById(100L)).thenReturn(customer); + when(orderMapper.selectById(10L)).thenReturn(order); + + CustomerDialVO result = service.dial(currentUser, 100L, null, 10L, request); + + assertEquals("13900139000", result.getDialNumber()); + } + + @Test + void appointmentLocatorResolvesOrderItemThenOrder() { + OrderItemDO item = new OrderItemDO(); + item.setId(5L); + item.setOrderId(10L); + item.setIsDelete(0); + when(orderItemMapper.selectById(5L)).thenReturn(item); + when(orderMapper.selectById(10L)).thenReturn(order); + when(userService.getById(100L)).thenReturn(customer); + customer.setPhone("encrypted-phone"); + when(phoneCrypto.decrypt("encrypted-phone")).thenReturn("13800138000"); + + CustomerDialVO result = service.dial(currentUser, null, 5L, null, request); + + assertEquals("13800138000", result.getDialNumber()); + verify(securityAuditSupport).success(eq(request), anyString(), anyString()); + } + + @Test + void rejectsWhenAppointmentAndOrderDoNotMatch() { + OrderItemDO item = new OrderItemDO(); + item.setId(5L); + item.setOrderId(10L); + item.setIsDelete(0); + when(orderItemMapper.selectById(5L)).thenReturn(item); + when(orderMapper.selectById(10L)).thenReturn(order); + + BusinessException error = assertThrows(BusinessException.class, + () -> service.dial(currentUser, null, 5L, 11L, request)); + + assertEquals(403, error.getCode()); + } + + @Test + void guestOrderWithoutAnyPhoneReturnsExplicitBusinessCode() { + order.setUserId(null); + order.setCustomerPhoneSnapshot(null); + when(orderMapper.selectById(10L)).thenReturn(order); + + BusinessException error = assertThrows(BusinessException.class, + () -> service.dial(currentUser, null, null, 10L, request)); + + assertEquals(DirectDialTargetProvider.NUMBER_UNAVAILABLE_CODE, error.getCode()); + assertTrue(error.getMessage().contains(DirectDialTargetProvider.NUMBER_UNAVAILABLE_BUSINESS_CODE)); + verify(securityAuditSupport).fail(eq(request), anyString(), anyString()); + } + + @Test + void rejectsWhenNoLocatorProvided() { + BusinessException error = assertThrows(BusinessException.class, + () -> service.dial(currentUser, null, null, null, request)); + + assertEquals(400, error.getCode()); + } + + @Test + void rejectsOrderOfAnotherShop() { + order.setShopId(2L); + when(orderMapper.selectById(10L)).thenReturn(order); + + BusinessException error = assertThrows(BusinessException.class, + () -> service.dial(currentUser, 100L, null, 10L, request)); + + assertEquals(403, error.getCode()); + } + + @Test + void rejectsOrderThatDoesNotBelongToCustomer() { + order.setUserId(101L); + when(orderMapper.selectById(10L)).thenReturn(order); + + BusinessException error = assertThrows(BusinessException.class, + () -> service.dial(currentUser, 100L, null, 10L, request)); + + assertEquals(403, error.getCode()); + } + + @Test + void privacyNumberProviderReportsNotConfiguredWithoutFallingBackToRealNumber() { + service = new CustomerDialServiceImpl(adminScopeHelper, userService, orderMapper, orderItemMapper, + requestThrottleService, securityAuditSupport, privacyProperties(), List.of( + new DirectDialTargetProvider(phoneCrypto), + new PlaceholderPrivacyNumberProvider())); + customer.setPhone("encrypted-phone"); + when(userService.getById(100L)).thenReturn(customer); + when(orderMapper.selectById(10L)).thenReturn(order); + + BusinessException error = assertThrows(BusinessException.class, + () -> service.dial(currentUser, 100L, null, 10L, request)); + + assertEquals(PlaceholderPrivacyNumberProvider.NOT_CONFIGURED_CODE, error.getCode()); + verify(securityAuditSupport).fail(eq(request), anyString(), anyString()); + } + + private DialProperties privacyProperties() { + DialProperties properties = new DialProperties(); + properties.setProvider("privacy-number"); + return properties; + } +} diff --git a/JC-Salon-Core/src/test/java/com/xiaowang/jayucloud/salon/core/modules/system/secure/SecureIntegrationConfigServiceImplTest.java b/JC-Salon-Core/src/test/java/com/xiaowang/jayucloud/salon/core/modules/system/secure/SecureIntegrationConfigServiceImplTest.java index 2c0b7300..9fb0e17d 100644 --- a/JC-Salon-Core/src/test/java/com/xiaowang/jayucloud/salon/core/modules/system/secure/SecureIntegrationConfigServiceImplTest.java +++ b/JC-Salon-Core/src/test/java/com/xiaowang/jayucloud/salon/core/modules/system/secure/SecureIntegrationConfigServiceImplTest.java @@ -116,7 +116,7 @@ class SecureIntegrationConfigServiceImplTest { currentUser.setType(2); SecureIntegrationConfigServiceImpl service = new SecureIntegrationConfigServiceImpl( mapper, mock(SystemParameterConfigMapper.class), new SecureConfigEncryptionService(MASTER_KEY), - new ContentModerationProperties(), configuredWechat()); + new ContentModerationProperties(), configuredWechat(), new com.fasterxml.jackson.databind.ObjectMapper()); assertThrows(RuntimeException.class, () -> service.getMapRuntimeConfig(currentUser)); verify(mapper, never()).selectOne(any()); @@ -131,7 +131,7 @@ class SecureIntegrationConfigServiceImplTest { UserDO currentUser = adminUser(); SecureIntegrationConfigServiceImpl service = new SecureIntegrationConfigServiceImpl( mapper, mock(SystemParameterConfigMapper.class), new SecureConfigEncryptionService(MASTER_KEY), - new ContentModerationProperties(), configuredWechat()); + new ContentModerationProperties(), configuredWechat(), new com.fasterxml.jackson.databind.ObjectMapper()); assertEquals("false", service.getMapRuntimeConfig(currentUser).get("enabled")); verify(mapper, org.mockito.Mockito.atLeastOnce()).selectOne(any()); @@ -142,7 +142,7 @@ class SecureIntegrationConfigServiceImplTest { ContentModerationProperties moderationProperties, WechatMiniProperties wechatProperties) { return new SecureIntegrationConfigServiceImpl(mapper, mock(SystemParameterConfigMapper.class), encryption, - moderationProperties, wechatProperties); + moderationProperties, wechatProperties, new com.fasterxml.jackson.databind.ObjectMapper()); } private UserDO adminUser() { diff --git a/JC-Salon-Core/src/test/java/com/xiaowang/jayucloud/salon/core/modules/system/service/impl/IntegrationProbeServiceImplTest.java b/JC-Salon-Core/src/test/java/com/xiaowang/jayucloud/salon/core/modules/system/service/impl/IntegrationProbeServiceImplTest.java index 0cdf5079..faaefecf 100644 --- a/JC-Salon-Core/src/test/java/com/xiaowang/jayucloud/salon/core/modules/system/service/impl/IntegrationProbeServiceImplTest.java +++ b/JC-Salon-Core/src/test/java/com/xiaowang/jayucloud/salon/core/modules/system/service/impl/IntegrationProbeServiceImplTest.java @@ -132,7 +132,8 @@ class IntegrationProbeServiceImplTest { .thenReturn("{\"errcode\":0,\"trace_id\":\"probe-task\"}"); WechatContentModerationProvider provider = new WechatContentModerationProvider( restTemplate, new ObjectMapper(), wechatClient, - new com.xiaowang.jayucloud.salon.core.modules.privacy.config.ContentModerationProperties()); + new com.xiaowang.jayucloud.salon.core.modules.privacy.config.ContentModerationProperties(), + deployProperties()); provider.submitTestImage("https://storage.test/probe.png", "private-open-id", "probe-1", "trial"); @@ -149,7 +150,8 @@ class IntegrationProbeServiceImplTest { .thenReturn("{\"errcode\":47001}"); WechatContentModerationProvider provider = new WechatContentModerationProvider( restTemplate, new ObjectMapper(), wechatClient, - new com.xiaowang.jayucloud.salon.core.modules.privacy.config.ContentModerationProperties()); + new com.xiaowang.jayucloud.salon.core.modules.privacy.config.ContentModerationProperties(), + deployProperties()); var result = provider.submitTestImage("https://storage.test/probe.png", "private-open-id", "probe-1", "trial"); @@ -157,6 +159,13 @@ class IntegrationProbeServiceImplTest { assertEquals("微信审核请求参数格式无效,请核对接口字段", result.reason()); } + private com.xiaowang.jayucloud.salon.core.config.SalonDeployProperties deployProperties() { + com.xiaowang.jayucloud.salon.core.config.SalonDeployProperties properties = + new com.xiaowang.jayucloud.salon.core.config.SalonDeployProperties(); + properties.setEnv("sit"); + return properties; + } + private UserDO admin() { UserDO user = new UserDO(); user.setId(1L); diff --git a/JC-Salon-Core/src/test/java/com/xiaowang/jayucloud/salon/core/modules/system/service/impl/LegalAgreementServiceImplTest.java b/JC-Salon-Core/src/test/java/com/xiaowang/jayucloud/salon/core/modules/system/service/impl/LegalAgreementServiceImplTest.java new file mode 100644 index 00000000..c1f85ece --- /dev/null +++ b/JC-Salon-Core/src/test/java/com/xiaowang/jayucloud/salon/core/modules/system/service/impl/LegalAgreementServiceImplTest.java @@ -0,0 +1,130 @@ +package com.xiaowang.jayucloud.salon.core.modules.system.service.impl; + +import com.xiaowang.jayucloud.salon.core.modules.system.entity.LegalAgreementDO; +import com.xiaowang.jayucloud.salon.core.modules.system.mapper.LegalAgreementMapper; +import com.xiaowang.jayucloud.salon.core.modules.system.vo.AgreementPendingVO; +import com.xiaowang.jayucloud.salon.core.modules.user.entity.UserAgreementConsentDO; +import com.xiaowang.jayucloud.salon.core.modules.user.mapper.UserAgreementConsentMapper; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.api.extension.ExtendWith; +import org.mockito.ArgumentCaptor; +import org.mockito.Mock; +import org.mockito.junit.jupiter.MockitoExtension; + +import javax.servlet.http.HttpServletRequest; +import java.util.ArrayList; +import java.util.List; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.times; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +@ExtendWith(MockitoExtension.class) +class LegalAgreementServiceImplTest { + + private static final String CURRENT_VERSION = "2026.11.04-R2"; + + @Mock private LegalAgreementMapper agreementMapper; + @Mock private UserAgreementConsentMapper consentMapper; + @Mock private HttpServletRequest request; + + private LegalAgreementServiceImpl service; + private LegalAgreementDO userTerms; + private LegalAgreementDO privacyPolicy; + + @BeforeEach + void setUp() { + service = new LegalAgreementServiceImpl(agreementMapper, consentMapper); + userTerms = currentAgreement(LegalAgreementServiceImpl.USER_TERMS); + privacyPolicy = currentAgreement(LegalAgreementServiceImpl.PRIVACY_POLICY); + } + + @Test + void anonymousPendingReturnsCurrentVersionsOnly() { + when(agreementMapper.selectOne(any())).thenReturn(userTerms, privacyPolicy); + + AgreementPendingVO result = service.getPendingAgreements(null); + + assertEquals(CURRENT_VERSION, result.getCurrentVersions().get(LegalAgreementServiceImpl.USER_TERMS)); + assertEquals(CURRENT_VERSION, result.getCurrentVersions().get(LegalAgreementServiceImpl.PRIVACY_POLICY)); + assertTrue(result.getAcceptedVersions().isEmpty()); + assertNull(result.getPending()); + } + + @Test + void loggedInUserWithoutConsentIsPending() { + when(agreementMapper.selectOne(any())).thenReturn(userTerms, privacyPolicy); + when(consentMapper.selectList(any())).thenReturn(new ArrayList<>()); + + AgreementPendingVO result = service.getPendingAgreements(8L); + + assertEquals(Boolean.TRUE, result.getPending()); + assertEquals(List.of(LegalAgreementServiceImpl.USER_TERMS, LegalAgreementServiceImpl.PRIVACY_POLICY), + result.getPendingTypes()); + } + + @Test + void oldVersionConsentIsPending() { + when(agreementMapper.selectOne(any())).thenReturn(userTerms, privacyPolicy); + when(consentMapper.selectList(any())).thenReturn(List.of( + consent(LegalAgreementServiceImpl.USER_TERMS, "2026.11.04"), + consent(LegalAgreementServiceImpl.PRIVACY_POLICY, "2026.11.04"))); + + AgreementPendingVO result = service.getPendingAgreements(8L); + + assertEquals(Boolean.TRUE, result.getPending()); + assertEquals("2026.11.04", result.getAcceptedVersions().get(LegalAgreementServiceImpl.USER_TERMS)); + assertEquals(2, result.getPendingTypes().size()); + } + + @Test + void acceptedCurrentVersionsAreNotPending() { + when(agreementMapper.selectOne(any())).thenReturn(userTerms, privacyPolicy); + when(consentMapper.selectList(any())).thenReturn(List.of( + consent(LegalAgreementServiceImpl.USER_TERMS, CURRENT_VERSION), + consent(LegalAgreementServiceImpl.PRIVACY_POLICY, CURRENT_VERSION))); + + AgreementPendingVO result = service.getPendingAgreements(8L); + + assertEquals(Boolean.FALSE, result.getPending()); + assertTrue(result.getPendingTypes().isEmpty()); + } + + @Test + void acceptRecordsBothCurrentVersions() { + when(agreementMapper.selectOne(any())).thenReturn(userTerms, privacyPolicy); + when(consentMapper.selectOne(any())).thenReturn(null); + + service.acceptCurrentAgreements(8L, "WECHAT_MINI", request); + + ArgumentCaptor captor = ArgumentCaptor.forClass(UserAgreementConsentDO.class); + verify(consentMapper, times(2)).insert(captor.capture()); + assertEquals(8L, captor.getAllValues().get(0).getUserId()); + assertEquals(CURRENT_VERSION, captor.getAllValues().get(0).getVersion()); + assertEquals(CURRENT_VERSION, captor.getAllValues().get(1).getVersion()); + assertEquals("WECHAT_MINI", captor.getAllValues().get(0).getClientType()); + assertEquals("agreement-gate", captor.getAllValues().get(0).getEntry()); + } + + private LegalAgreementDO currentAgreement(String type) { + LegalAgreementDO agreement = new LegalAgreementDO(); + agreement.setAgreementType(type); + agreement.setVersion(CURRENT_VERSION); + agreement.setStatus(1); + agreement.setIsDelete(0); + return agreement; + } + + private UserAgreementConsentDO consent(String type, String version) { + UserAgreementConsentDO consent = new UserAgreementConsentDO(); + consent.setUserId(8L); + consent.setAgreementType(type); + consent.setVersion(version); + return consent; + } +} diff --git a/JC-Salon-Core/src/test/java/com/xiaowang/jayucloud/salon/core/modules/user/service/impl/UserServiceCustomerMatchingTest.java b/JC-Salon-Core/src/test/java/com/xiaowang/jayucloud/salon/core/modules/user/service/impl/UserServiceCustomerMatchingTest.java index f32bae0f..35d9b893 100644 --- a/JC-Salon-Core/src/test/java/com/xiaowang/jayucloud/salon/core/modules/user/service/impl/UserServiceCustomerMatchingTest.java +++ b/JC-Salon-Core/src/test/java/com/xiaowang/jayucloud/salon/core/modules/user/service/impl/UserServiceCustomerMatchingTest.java @@ -75,7 +75,7 @@ class UserServiceCustomerMatchingTest { } @Test - void appointmentIdentityLookupReturnsOnlyExactTupleAndFullPhone() { + void appointmentIdentityLookupReturnsOnlyExactTupleAndMaskedPhone() { UserDO existing = new UserDO(); existing.setId(92L); existing.setNickname("周女士"); @@ -85,6 +85,7 @@ class UserServiceCustomerMatchingTest { existing.setIsDelete(0); when(userMapper.selectList(any(Wrapper.class))).thenReturn(List.of(existing)); when(phoneCrypto.decrypt("encrypted-phone")).thenReturn("13800138000"); + when(phoneCrypto.mask("13800138000")).thenReturn("138****8000"); List matches = userService.findCustomerIdentityMatches("周女士", "wx-zhou", "13800138000", null); @@ -92,12 +93,13 @@ class UserServiceCustomerMatchingTest { userService.findCustomerIdentityMatches("周女士", "wx-another", "13800138000", null); assertEquals(1, matches.size()); - assertEquals("13800138000", matches.get(0).getPhone()); + assertEquals("138****8000", matches.get(0).getPhone()); + assertEquals(Boolean.TRUE, matches.get(0).getPhoneAvailable()); assertTrue(wrongWechat.isEmpty()); } @Test - void appointmentIdentityLookupFallsBackToLegacyContactPhone() { + void appointmentIdentityLookupFallsBackToLegacyContactPhoneWithMaskedPhone() { UserDO existing = new UserDO(); existing.setId(93L); existing.setNickname("周女士"); @@ -107,11 +109,13 @@ class UserServiceCustomerMatchingTest { existing.setIsDelete(0); when(userMapper.selectList(any(Wrapper.class))).thenReturn(List.of(existing)); when(phoneCrypto.decrypt("encrypted-contact-phone")).thenReturn("13800138000"); + when(phoneCrypto.mask("13800138000")).thenReturn("138****8000"); List matches = userService.findCustomerIdentityMatches("周女士", "wx-zhou", "13800138000", null); assertEquals(1, matches.size()); - assertEquals("13800138000", matches.get(0).getPhone()); + assertEquals("138****8000", matches.get(0).getPhone()); + assertEquals(Boolean.TRUE, matches.get(0).getPhoneAvailable()); } } diff --git a/JC-Salon-Frontend/public/legal/privacy-policy.html b/JC-Salon-Frontend/public/legal/privacy-policy.html index 73b53a31..6786b6c2 100644 --- a/JC-Salon-Frontend/public/legal/privacy-policy.html +++ b/JC-Salon-Frontend/public/legal/privacy-policy.html @@ -4,36 +4,256 @@ + 甲屿手纪 Salon 隐私政策 -

甲屿手纪 Salon 隐私政策

-

版本:2026.10.21 更新日期:2026年10月21日

-

本政策适用于 Salon 门店工作台的店长与员工账号。实际上线前,运营方应核实主体、短信服务商、消息通道、对象存储及微信后台隐私指引,并据实更新本政策。

-

一、处理的信息及用途

-
    -
  • 登录:在用户主动同意后,通过微信登录获取 OpenID,用于识别和关联账号。
  • -
  • 可选资料:用户主动选择时处理昵称和头像;未提供时使用系统默认展示。
  • -
  • 手机号:用户主动选择绑定或更换时处理,用于账号找回和必要业务联系,不用于营销;不绑定不影响基础工作台使用。
  • -
  • 门店业务资料:店长和员工可能录入客户姓名、可选联系电话、预约、作品和订单信息,以履行门店服务管理。客户业务资料不构成客户的小程序登录账号。
  • -
  • 安全运行:服务端会处理请求所需的网络地址、登录会话和操作审计信息,不读取设备标识、IMEI、MAC、麦克风或用户定位。
  • -
-

二、用户主动触发的权限

-

仅在用户主动选择头像、作品图片等操作后调用选图能力;仅在用户主动绑定手机号时调用微信手机号能力或发送短信验证码。短信只用于验证绑定、变更或解绑,不用于营销。手机号绑定和解绑前会显示用途说明。

-

三、存储与保护

-

账号、客户和订单快照中的手机号采用 AES-GCM 加密保存,另以独立 HMAC 索引支持查重。普通页面、日志和导出对手机号脱敏;完整号码仅在业务需要且权限允许时展示。账号密钥由各环境配置管理,运营方需限制配置访问并保留审计。

-

四、第三方服务

-

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

-

五、内容审核

-

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

-

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

-

六、保留、注销和解绑

-

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

-

七、政策更新与联系

-

处理目的、数据类别或服务商发生重要变化时,我们会更新本政策并在需要时重新征求同意。用户可以在账号设置查看注销申请状态、撤回待处理申请并提交隐私相关请求;也可联系所属门店管理员。

-

本文件是产品说明,不构成法律意见;上线前应由运营方或专业顾问结合实际处理活动审阅。

+
+

甲屿手纪 Salon 隐私政策

+ + + + +
+ + diff --git a/JC-Salon-Frontend/public/legal/user-terms.html b/JC-Salon-Frontend/public/legal/user-terms.html index e265071b..366c7318 100644 --- a/JC-Salon-Frontend/public/legal/user-terms.html +++ b/JC-Salon-Frontend/public/legal/user-terms.html @@ -4,28 +4,234 @@ + 甲屿手纪 Salon 用户协议 -

甲屿手纪 Salon 用户协议

-

版本:2026.10.21 更新日期:2026年10月21日

-

本服务面向经门店授权的店长和员工,提供门店日程、预约、客户业务资料和经营记录管理。预约金额是业务记录,不表示本平台已收款;当前不提供充值、订阅或平台虚拟权益购买。

-

一、接受协议

-

使用前请阅读本协议及《隐私政策》。登录时须主动选择同意;未同意时不会交换微信登录凭证,也不能继续使用。协议更新后需重新确认。

-

二、账号与使用权限

-

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

-

三、业务资料与内容

-

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

-

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

-

四、业务记录与金额

-

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

-

五、账号注销

-

用户可在小程序“我的-账号设置”提交注销申请并在处理前撤回。管理员完成必要的门店移交或归档后撤销会话并清理或匿名化个人账号资料。目标处理期限为15个工作日,具体取决于门店交接;必要的订单、预约和经营记录将去除身份关联后按产品目标保留五年。

-

六、服务调整与联系

-

平台会在合理范围内维护服务,并在功能或数据处理方式发生重要变化时更新说明。隐私相关申请可从账号设置发起;其他问题请联系所属门店管理员。

-

本协议为产品说明文本,正式发布前应由运营方根据实际主体、业务和适用法律完成审核。

+
+

甲屿手纪 Salon 用户协议

+ + + + +
+ + diff --git a/JC-Salon-Frontend/src/api/admin.ts b/JC-Salon-Frontend/src/api/admin.ts index 76b23ebe..f73b6e67 100644 --- a/JC-Salon-Frontend/src/api/admin.ts +++ b/JC-Salon-Frontend/src/api/admin.ts @@ -1594,11 +1594,27 @@ export interface SecureIntegrationConfigVO { wechatMiniAppConfigured: boolean wechatMiniAppId: string mockProviderAllowed: boolean + moderationForwardEnabled?: boolean + moderationForwardTargets?: Record + moderationForwardSecretConfigured?: boolean + moderationForwardRecent?: ModerationForwardRecordVO[] encryptionKeyConfigured: boolean updatedAt?: string probeResults?: IntegrationProbeResultVO[] } +export interface ModerationForwardRecordVO { + id: IdType + traceId: string + sourceEnv?: string + targetEnv?: string + status: 'PENDING' | 'SUCCESS' | 'RETRY' | 'FAILED' | 'NO_ENV' | 'TARGET_MISSING' | string + retryCount?: number + lastError?: string + createdAt?: string + updatedAt?: string +} + export interface IntegrationProbeCheckVO { name: string status: 'PASS' | 'WARN' | 'FAIL' | 'PENDING' @@ -1640,6 +1656,10 @@ export interface SecureIntegrationConfigUpdate { moderationEncodingAesKey?: string clearModerationCallbackToken?: boolean clearModerationEncodingAesKey?: boolean + moderationForwardEnabled?: boolean + moderationForwardTargets?: Record + moderationForwardSecret?: string + clearModerationForwardSecret?: boolean } /** @@ -1664,7 +1684,8 @@ export const adminSecureIntegrationConfigApi = { probe: (data: IntegrationProbeRequest) => adminApi.post('/system-settings/secure-integration/probe', data) as unknown as Promise, getMapRuntimeConfig: () => adminApi.get<{ provider: 'TENCENT' | 'AMAP'; enabled: string; key: string }>('/system-settings/secure-integration/map-runtime') as unknown as Promise<{ provider: 'TENCENT' | 'AMAP'; enabled: string; key: string }>, saveMapConfig: (data: SecureIntegrationConfigUpdate) => adminApi.post('/system-settings/secure-integration/map', data) as unknown as Promise, - saveModerationConfig: (data: SecureIntegrationConfigUpdate) => adminApi.post('/system-settings/secure-integration/content-moderation', data) as unknown as Promise + saveModerationConfig: (data: SecureIntegrationConfigUpdate) => adminApi.post('/system-settings/secure-integration/content-moderation', data) as unknown as Promise, + saveModerationForwardConfig: (data: SecureIntegrationConfigUpdate) => adminApi.post('/system-settings/secure-integration/content-moderation-forward', data) as unknown as Promise } export interface WorkbenchRegistrationApplication { diff --git a/JC-Salon-Frontend/src/api/auth.ts b/JC-Salon-Frontend/src/api/auth.ts index 9fe657a0..79c03be0 100644 --- a/JC-Salon-Frontend/src/api/auth.ts +++ b/JC-Salon-Frontend/src/api/auth.ts @@ -234,6 +234,13 @@ export const authApi = { } } +export interface AgreementPending { + pending: boolean | null + currentVersions: Record + acceptedVersions: Record + pendingTypes: string[] +} + /** * Purpose: legalAgreementApi supports auth.ts by holding or executing the legal agreement api 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. @@ -247,5 +254,13 @@ export const legalAgreementApi = { }, getMyConsent: () => { return api.get<{ consentVersions: Record }>('/user/agreement-consent/me') + }, + getPending: () => { + return api.get('/legal-agreement/pending') + }, + accept: (clientType = 'WEB') => { + return api.post('/legal-agreement/accept', null, { + params: { clientType } + }) } } diff --git a/JC-Salon-Frontend/src/api/index.ts b/JC-Salon-Frontend/src/api/index.ts index f4f0731a..c5ce0450 100644 --- a/JC-Salon-Frontend/src/api/index.ts +++ b/JC-Salon-Frontend/src/api/index.ts @@ -11,6 +11,7 @@ import type { IdType } from '@/utils/id' import { clearAdminSessionStorage } from '@/utils/admin-session' import { attachRequestSignature } from '@/utils/request-signature' import { isApiAuthFreePath } from './auth-free-paths' +import { AGREEMENT_REQUIRED_EVENT, isAgreementPending, setAgreementPending } from '../utils/agreement-gate' import { getApiResponseMessage, isPermissionErrorMessage, @@ -77,6 +78,24 @@ const getStoredAccessToken = (isAdmin = false) => { : (localStorage.getItem('accessToken') || sessionStorage.getItem('accessToken')) } +/** + * 协议门禁接口在后台登录态下也需要使用管理员 token;其余沿用原有 admin 路径判断。 + */ +const isAdminScopedUrl = (url?: string) => { + if (!url) return false + if (url.includes('/admin/') || url.includes('/order/admin/')) return true + const hasAdminToken = Boolean(localStorage.getItem('adminAccessToken') || sessionStorage.getItem('adminAccessToken')) + return hasAdminToken && (url.includes('/legal-agreement/pending') || url.includes('/legal-agreement/accept')) +} + +const AGREEMENT_GATE_ALLOWLIST = ['/legal-agreement/', '/admin/auth/', '/user/logout', '/user/info'] +/** + * 服务端协议同意拦截返回的业务码。收到后前端锁定业务请求并引导用户去阅读/同意最新版协议。 + */ +const AGREEMENT_VERSION_REQUIRED_CODE = 4510 +const AGREEMENT_REQUIRED_DEDUPE_MS = 5000 +let lastAgreementRequiredTime = 0 + /** * Purpose: getStoredRefreshToken supports index.ts by holding or executing the get stored refresh token 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. @@ -141,6 +160,26 @@ const showError = (msg: string) => { message.error(msg) } +/** + * 处理服务端 4510(未同意最新协议): + * 锁定后续业务请求、广播事件让后台布局弹出既有的同意弹层,并提示用户。 + * 非后台场景没有弹层,直接新开协议阅读页,引导用户阅读后重新登录同意。 + */ +const handleAgreementRequired = (res: any, isAdminRequest: boolean) => { + setAgreementPending(true) + if (typeof window !== 'undefined') { + window.dispatchEvent(new CustomEvent(AGREEMENT_REQUIRED_EVENT, { detail: res?.data || {} })) + } + if (Date.now() - lastAgreementRequiredTime < AGREEMENT_REQUIRED_DEDUPE_MS) { + return + } + lastAgreementRequiredTime = Date.now() + showError(normalizeApiErrorMessage(res?.message || '用户协议与隐私政策已更新,请阅读并同意后继续使用')) + if (!isAdminRequest && typeof window !== 'undefined') { + window.open('/legal/user-terms.html', '_blank', 'noopener') + } +} + const resetSystemFailureWindow = () => { systemFailureTimes = [] } @@ -238,7 +277,11 @@ const handleTokenExpired = (isAdmin = false, failedToken: string | null = null) api.interceptors.request.use( async config => { - const isAdminRequest = config.url?.includes('/admin/') || config.url?.includes('/order/admin/') + if (isAgreementPending() && !AGREEMENT_GATE_ALLOWLIST.some(path => config.url?.includes(path))) { + return Promise.reject(new Error('请先阅读并同意最新版用户协议与隐私政策')) + } + + const isAdminRequest = isAdminScopedUrl(config.url) let token = isAdminRequest ? (localStorage.getItem('adminAccessToken') || sessionStorage.getItem('adminAccessToken')) : (localStorage.getItem('accessToken') || sessionStorage.getItem('accessToken')) @@ -268,6 +311,11 @@ api.interceptors.response.use( response => { resetSystemFailureWindow() const res = response.data + if (Number(res?.code) === AGREEMENT_VERSION_REQUIRED_CODE) { + const errorMsg = normalizeApiErrorMessage(res?.message || '用户协议与隐私政策已更新,请阅读并同意后继续使用') + handleAgreementRequired(res, isAdminScopedUrl(response.config?.url)) + return Promise.reject(new Error(errorMsg)) + } if (res.code !== 200) { const errorMsg = normalizeApiErrorMessage(res.message || '请求失败') if (!isPermissionErrorMessage(errorMsg)) { @@ -286,7 +334,7 @@ api.interceptors.response.use( if (error.response?.status === 401) { // 检查是否是后台管理的API请求 - const isAdminRequest = originalRequest.url?.includes('/admin/') || originalRequest.url?.includes('/order/admin/') + const isAdminRequest = isAdminScopedUrl(originalRequest.url) const requestToken = getRequestToken(originalRequest) const isRealTokenExpired = isTokenExpiredResponse(error, requestToken) diff --git a/JC-Salon-Frontend/src/api/user.ts b/JC-Salon-Frontend/src/api/user.ts index 53072cd9..b8e70888 100644 --- a/JC-Salon-Frontend/src/api/user.ts +++ b/JC-Salon-Frontend/src/api/user.ts @@ -261,11 +261,32 @@ export interface ContactInfoVO { platformContactText?: string } +/** + * 后台单次拨号取号响应。 + */ +export interface CustomerDialResult { + mode: 'DIRECT' | 'PRIVACY_NUMBER' + dialNumber: string + expiresInSeconds: number +} + /** * userApi groups all API calls for this page domain. * Call guide: pass the typed payload or identifier into the method below, and use the returned Promise in the page script. */ export const userApi = { + /** + * 后台管理员按预约/订单上下文单次取号,号码不入库、不缓存。 + */ + dialCustomer: async (params: { customerId?: IdType; appointmentId?: IdType; orderId?: IdType }): Promise => { + return await api.post('/manager/customers/dial', null, { + params: { + customerId: params.customerId || undefined, + appointmentId: params.appointmentId || undefined, + orderId: params.orderId || undefined + } + }) as unknown as CustomerDialResult + }, getUserInfo: async (): Promise => { return await api.get('/user/info') as unknown as UserVO }, diff --git a/JC-Salon-Frontend/src/utils/agreement-gate.ts b/JC-Salon-Frontend/src/utils/agreement-gate.ts new file mode 100644 index 00000000..9f52ae6f --- /dev/null +++ b/JC-Salon-Frontend/src/utils/agreement-gate.ts @@ -0,0 +1,16 @@ +/** + * 协议同意门禁状态:登录后检测到未同意的新版本时置位, + * 请求层据此拦截非协议类业务请求,避免用户绕过弹层继续操作。 + */ +let agreementPending = false + +/** + * 服务端返回 4510 时广播的事件名,页面层(如后台布局)监听后重新检查协议状态并展示同意弹层。 + */ +export const AGREEMENT_REQUIRED_EVENT = 'jayucloud:agreement-required' + +export const setAgreementPending = (value: boolean) => { + agreementPending = value +} + +export const isAgreementPending = () => agreementPending diff --git a/JC-Salon-Frontend/src/views/ArtistOrderView.vue b/JC-Salon-Frontend/src/views/ArtistOrderView.vue index 557989ef..f23465be 100644 --- a/JC-Salon-Frontend/src/views/ArtistOrderView.vue +++ b/JC-Salon-Frontend/src/views/ArtistOrderView.vue @@ -67,6 +67,13 @@
预约用户:{{ order.customerNickname || '用户' }} 联系电话:{{ order.customerPhoneMasked }} + 呼叫
@@ -215,6 +222,7 @@ const route = useRoute() * Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow. */ const orders = ref([]) +const dialingOrderId = ref(null) /** * Purpose: orderRefs supports ArtistOrderView.vue by holding or executing the order refs 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. @@ -659,6 +667,29 @@ const confirmQuote = async () => { } } +/** 按订单上下文单次取号后发起拨号,号码不落库、不缓存;散客无 userId 时仅用订单定位。 */ +const dialCustomer = async (order: any) => { + if (!order?.id) { + message.warning('缺少订单上下文,无法取号') + return + } + dialingOrderId.value = order.id + try { + const result = await userApi.dialCustomer({ + customerId: order.userId || undefined, + orderId: order.id + }) + if (!result?.dialNumber) { + throw new Error('未获取到可拨打号码') + } + window.location.href = `tel:${result.dialNumber}` + } catch (error: any) { + message.error(error?.message || '取号失败') + } finally { + dialingOrderId.value = null + } +} + /** completeOrder is a local helper used by this page script. */ const completeOrder = (orderId: IdType) => { Modal.confirm({ diff --git a/JC-Salon-Frontend/src/views/admin/AdminLayout.vue b/JC-Salon-Frontend/src/views/admin/AdminLayout.vue index 000e6a46..29ea9a21 100644 --- a/JC-Salon-Frontend/src/views/admin/AdminLayout.vue +++ b/JC-Salon-Frontend/src/views/admin/AdminLayout.vue @@ -70,11 +70,30 @@
+ + +
+

新版本{{ agreementVersionText ? `(${agreementVersionText})` : '' }}已发布,请阅读并同意后继续使用后台。

+ + 同意并继续 +
+
@@ -419,6 +485,22 @@ onMounted(() => { color: #fff; } +.agreement-gate { + display: grid; + gap: 14px; + color: #315650; + line-height: 1.7; +} + +.agreement-gate p { + margin: 0; +} + +.agreement-gate__links a { + color: var(--theme-primary-action); + font-weight: 700; +} + @media (max-width: 960px) { .header, .content { diff --git a/JC-Salon-Frontend/src/views/admin/SystemSettingsView.vue b/JC-Salon-Frontend/src/views/admin/SystemSettingsView.vue index caf41043..16eeafa5 100644 --- a/JC-Salon-Frontend/src/views/admin/SystemSettingsView.vue +++ b/JC-Salon-Frontend/src/views/admin/SystemSettingsView.vue @@ -16,7 +16,7 @@
- +
@@ -306,6 +306,61 @@ 回调资料仍不完整,暂时不能进行微信 URL 验证。 安全接入加密主密钥尚未配置,Token 与 AESKey 不会保存。
+ +
+
+
+ 跨环境回调转发 + CROSS ENV +

微信只向一个环境推送异步图片审核结果;命中不到本地任务时,按回调 extra 中的部署环境标识转发到真正创建任务的环境。默认关闭。

+
+ 保存转发设置 +
+
+
+
启用跨环境转发
+

关闭时未命中本地任务的回调只记录不转发。

+
+
+ {{ moderationForwardEnabled ? '已启用' : '未启用' }} +
+
+
+
共享密钥
+

16-128 位,仅用于服务端 HMAC-SHA256 转发验签,不写日志;各环境需配置相同密钥。

+
+ + {{ clearModerationForwardSecret ? '撤销清除' : '清除' }} +
+
+ {{ clearModerationForwardSecret ? '保存后清除' : secureStatus?.moderationForwardSecretConfigured ? '已配置' : '待配置' }} +
+
+
+
{{ env.label }}回调地址
+

必须精确指向 /api/integration/wechat/content-moderation/callback;HTTP 仅允许内网主机。

+
+ +
+
+
+
+
+ 最近转发结果 + NO_ENV / TARGET_MISSING 不自动重试,补齐配置或人工处理后可重放。 +
+
暂无转发记录
+
    +
  • + {{ forwardStatusLabel(item.status) }} + {{ item.sourceEnv || '-' }} → {{ item.targetEnv || '-' }} + {{ item.traceId }} + {{ formatProbeTime(item.createdAt) }} + {{ item.lastError }} +
  • +
+
+
@@ -420,7 +475,7 @@ @@ -1034,16 +1139,22 @@ watch(activeSection, () => { .settings-tab.is-active::after { content: ''; position: absolute; left: 0; right: 0; bottom: -11px; height: 2px; border-radius: 2px; background: var(--theme-primary); } .settings-health { display: inline-flex; align-items: center; gap: 7px; color: var(--admin-mobile-muted); font-size: 12px; white-space: nowrap; } .settings-health i { width: 7px; height: 7px; border-radius: 50%; background: var(--theme-primary); } -.settings-body { display: grid; grid-template-columns: 194px minmax(0, 1fr); gap: 18px; align-items: start; } -.settings-subnav { position: sticky; top: 16px; display: flex; flex-direction: column; gap: 2px; padding: 8px; border: 1px solid var(--admin-mobile-border); border-radius: 12px; background: color-mix(in srgb, var(--theme-card-bg) 88%, transparent); } -.settings-subnav__label { padding: 6px 8px 8px; color: var(--admin-mobile-muted); font-size: 10px; font-weight: 800; letter-spacing: .1em; text-transform: uppercase; } -.settings-subnav__item { display: flex; width: 100%; align-items: center; justify-content: space-between; gap: 8px; min-height: 34px; padding: 7px 9px; border: 0; border-radius: 7px; background: none; color: var(--admin-mobile-muted); font: inherit; font-size: 12px; text-align: left; cursor: pointer; } -.settings-subnav__item:hover { background: color-mix(in srgb, var(--theme-primary) 6%, transparent); color: var(--theme-primary-action); } -.settings-subnav__item.is-active { background: var(--admin-mobile-accent-soft); color: var(--theme-primary-action); font-weight: 700; } +.settings-body { display: block; } +.settings-subnav { display: flex; max-width: 100%; align-items: center; gap: 6px; margin-bottom: 12px; padding: 7px; overflow-x: auto; border: 1px solid var(--admin-mobile-border); border-radius: 10px; background: color-mix(in srgb, var(--theme-card-bg) 88%, transparent); scrollbar-width: none; } +.settings-subnav::-webkit-scrollbar { display: none; } +.settings-subnav__label { display: none; } +.settings-subnav__item { display: flex; flex: none; width: auto; align-items: center; justify-content: space-between; gap: 6px; min-height: 30px; padding: 5px 11px; border: 1px solid transparent; border-radius: 999px; background: color-mix(in srgb, var(--theme-primary) 4%, transparent); color: var(--admin-mobile-muted); font: inherit; font-size: 12px; text-align: left; white-space: nowrap; cursor: pointer; } +.settings-subnav__item:hover { border-color: color-mix(in srgb, var(--theme-primary) 35%, var(--admin-mobile-border)); background: color-mix(in srgb, var(--theme-primary) 7%, transparent); color: var(--theme-primary-action); } +.settings-subnav__item.is-active { border-color: color-mix(in srgb, var(--theme-primary) 35%, var(--admin-mobile-border)); background: var(--admin-mobile-accent-soft); color: var(--theme-primary-action); font-weight: 700; } .settings-subnav__item em { flex: none; min-width: 18px; height: 18px; padding: 0 5px; border: 1px solid var(--admin-mobile-border); border-radius: 9px; background: var(--theme-card-bg); color: var(--admin-mobile-muted); font-size: 10px; font-style: normal; line-height: 16px; text-align: center; } .settings-content { min-width: 0; } .settings-groups { display: flex; flex-direction: column; gap: 14px; } .settings-group { min-width: 0; scroll-margin-top: 16px; border: 1px solid var(--admin-mobile-border); border-radius: 14px; background: color-mix(in srgb, var(--theme-card-bg) 92%, transparent); box-shadow: 0 1px 2px rgba(23, 33, 31, .03); } +.settings-group.is-located { animation: settings-locate 1.5s ease-out; } +@keyframes settings-locate { + 0% { box-shadow: 0 0 0 3px color-mix(in srgb, var(--theme-primary) 42%, transparent); border-color: color-mix(in srgb, var(--theme-primary) 55%, var(--admin-mobile-border)); } + 100% { box-shadow: 0 1px 2px rgba(23, 33, 31, .03); } +} .settings-group__head { display: flex; align-items: flex-start; justify-content: space-between; gap: 14px; padding: 15px 18px 12px; border-bottom: 1px solid var(--admin-mobile-border); } .settings-group__head-main { min-width: 0; } .settings-group__title { display: flex; align-items: center; gap: 8px; flex-wrap: wrap; } @@ -1152,13 +1263,6 @@ watch(activeSection, () => { .field-grid.cols-3 { grid-template-columns: repeat(2, minmax(0, 1fr)); } .field--wide { grid-column: auto; } } -@media (max-width: 1180px) { - .settings-body { grid-template-columns: 1fr; gap: 12px; } - .settings-subnav { position: static; flex-direction: row; align-items: center; gap: 4px; padding: 7px; overflow-x: auto; scrollbar-width: none; } - .settings-subnav::-webkit-scrollbar { display: none; } - .settings-subnav__label { display: none; } - .settings-subnav__item { width: auto; flex: none; min-height: 30px; padding: 5px 10px; white-space: nowrap; } -} @media (max-width: 960px) { .field-grid.cols-2, .field-grid.cols-3 { grid-template-columns: 1fr; } .field__desc { min-height: 0; } @@ -1181,5 +1285,59 @@ watch(activeSection, () => { .svc__desc { white-space: normal; display: -webkit-box; -webkit-line-clamp: 1; -webkit-box-orient: vertical; } .field__save { margin-left: 0; } } +.settings-subsection { + margin-top: 18px; + padding-top: 16px; + border-top: 1px dashed var(--border-color, #e5e7eb); +} +.settings-subsection__head { + display: flex; + align-items: flex-start; + justify-content: space-between; + gap: 16px; + margin-bottom: 12px; +} +.settings-subsection__head strong { font-size: 14px; } +.settings-subsection__head .tag { margin-left: 8px; } +.settings-subsection__head p { margin: 4px 0 0; } +.forward-recent { margin-top: 14px; } +.forward-recent__head { + display: flex; + flex-wrap: wrap; + align-items: baseline; + gap: 10px; + margin-bottom: 8px; +} +.forward-recent__list { + display: flex; + flex-direction: column; + gap: 6px; + margin: 0; + padding: 0; + list-style: none; +} +.forward-recent__list li { + display: flex; + flex-wrap: wrap; + align-items: center; + gap: 8px; + padding: 7px 10px; + border: 1px solid var(--border-color, #e5e7eb); + border-radius: 8px; + font-size: 12px; +} +.forward-recent__trace { + flex: 1 1 180px; + min-width: 0; + overflow: hidden; + text-overflow: ellipsis; + white-space: nowrap; + font-family: ui-monospace, SFMono-Regular, Menlo, monospace; +} +.forward-recent__time { color: var(--text-color-secondary, #6b7280); } +.forward-recent__error { color: var(--danger-color, #c0392b); } +@media (max-width: 760px) { + .settings-subsection__head { flex-direction: column; align-items: stretch; } +} diff --git a/JC-Salon-Frontend/src/views/admin/UsersView.vue b/JC-Salon-Frontend/src/views/admin/UsersView.vue index 7a949b6c..2ceba4c2 100644 --- a/JC-Salon-Frontend/src/views/admin/UsersView.vue +++ b/JC-Salon-Frontend/src/views/admin/UsersView.vue @@ -214,10 +214,11 @@ @@ -625,6 +626,22 @@ const formState = reactive({ /** wechatQrUploading tracks QR upload state in the user modal. */ const wechatQrUploading = ref(false) +/** originalPhone keeps the phone value loaded from the backend so edits can be detected. */ +const originalPhone = ref('') + +/** phonePlaceholder explains that an existing masked phone is kept unless a new number is typed. */ +const phonePlaceholder = computed(() => + isEdit.value && originalPhone.value ? '已设置手机号,留空表示不修改' : '请输入手机号' +) + +/** phoneChanged is true only when the user typed a real, different phone number during editing. */ +const phoneChanged = computed(() => { + if (!isEdit.value) return true + const current = formState.phone.trim() + if (!current || isMaskedSensitiveValue(current)) return false + return current !== originalPhone.value.trim() +}) + /** handleAccountInput is a local helper used by this page script. */ const handleAccountInput = () => { const normalized = sanitizeAccountInput(formState.account) @@ -642,6 +659,14 @@ const handlePhoneInput = () => { formState.contactPhone = formState.phone } +/** handlePhoneFocus clears the masked placeholder value so stars can never be submitted as a phone number. */ +const handlePhoneFocus = () => { + if (isMaskedSensitiveValue(formState.phone)) { + formState.phone = '' + formState.contactPhone = '' + } +} + /** beforeUploadWechatQr validates QR image files before upload. */ const beforeUploadWechatQr = (file: File) => { const isImage = file.type.startsWith('image/') @@ -754,7 +779,7 @@ const formRules = { phone: [ { validator: async (_rule: unknown, value: string) => { - if (isEdit.value && !value?.trim()) return Promise.resolve() + if (isEdit.value && (!value?.trim() || isMaskedSensitiveValue(value))) return Promise.resolve() await validatePhoneUniqueness(value) return Promise.resolve() }, @@ -1001,6 +1026,7 @@ const resetFilters = () => { /** resetFormState is a local helper used by this page script. */ const resetFormState = () => { + originalPhone.value = '' Object.assign(formState, { account: '', nickname: '', @@ -1093,11 +1119,13 @@ const showAddModal = () => { const showEditModal = (record: any) => { isEdit.value = true currentUser.value = record + const loadedPhone = String(record.phone || record.contactPhone || '').trim() + originalPhone.value = loadedPhone Object.assign(formState, { account: isMaskedSensitiveValue(record.account) ? '' : record.account, nickname: record.nickname, - phone: isMaskedSensitiveValue(record.phone || record.contactPhone) ? '' : (record.phone || record.contactPhone || ''), - contactPhone: isMaskedSensitiveValue(record.phone || record.contactPhone) ? '' : (record.phone || record.contactPhone || ''), + phone: loadedPhone, + contactPhone: loadedPhone, birthday: record.birthday || '', wechatId: record.wechatId || '', wechatQrCode: record.wechatQrCode || '', @@ -1107,10 +1135,6 @@ const showEditModal = (record: any) => { }) restoreDraft() if (isMaskedSensitiveValue(formState.account)) formState.account = '' - if (isMaskedSensitiveValue(formState.phone)) { - formState.phone = '' - formState.contactPhone = '' - } modalVisible.value = true } @@ -1147,8 +1171,10 @@ const handleModalOk = async () => { ...(formState.password.trim() ? { password: formState.password.trim() } : {}) } - if (isEdit.value && !formState.account.trim()) delete requestData.account - if (isEdit.value && !primaryPhone) { + if (isEdit.value && (!formState.account.trim() || isMaskedSensitiveValue(formState.account))) { + delete requestData.account + } + if (isEdit.value && (!phoneChanged.value || !primaryPhone || isMaskedSensitiveValue(primaryPhone))) { delete requestData.phone delete requestData.contactPhone } diff --git a/JC-Salon-WeChat/api/auth.js b/JC-Salon-WeChat/api/auth.js index fb243f31..83104e4f 100644 --- a/JC-Salon-WeChat/api/auth.js +++ b/JC-Salon-WeChat/api/auth.js @@ -167,6 +167,14 @@ module.exports = { }) }, + acceptAgreements(clientType = 'WECHAT_MINI') { + return request({ + url: '/legal-agreement/accept', + method: 'POST', + params: { clientType } + }) + }, + switchShop(shopId) { return request({ url: '/user/switch-shop', diff --git a/JC-Salon-WeChat/api/customers.js b/JC-Salon-WeChat/api/customers.js index c76e2c53..a3cf3106 100644 --- a/JC-Salon-WeChat/api/customers.js +++ b/JC-Salon-WeChat/api/customers.js @@ -46,6 +46,23 @@ module.exports = { }) }, + /** + * 后台按预约/订单上下文单次取号,号码不入库、不缓存;散客可不传 customerId。 + */ + dialCustomer(params) { + const source = params || {} + const query = {} + if (source.customerId) query.customerId = source.customerId + if (source.appointmentId) query.appointmentId = source.appointmentId + if (source.orderId) query.orderId = source.orderId + return request({ + url: '/manager/customers/dial', + method: 'POST', + data: {}, + params: query + }) + }, + create(data) { return request({ url: '/manager/customers', diff --git a/JC-Salon-WeChat/app.js b/JC-Salon-WeChat/app.js index d06ab5c5..487c64e3 100644 --- a/JC-Salon-WeChat/app.js +++ b/JC-Salon-WeChat/app.js @@ -2,6 +2,7 @@ const auth = require('./utils/auth') const authApi = require('./api/auth') const { BRAND_CONFIG } = require('./utils/config') const profileCache = require('./utils/profile-cache') +const { toUserMessage } = require('./utils/toast') App({ globalData: { @@ -79,7 +80,7 @@ App({ this.globalData.userInfo = null this.publishWechatLoginState({ status: 'ERROR', - message: error.message || '自动登录失败,请点击重试' + message: toUserMessage(error, '自动登录失败,请点击重试') }) this.goLogin() } diff --git a/JC-Salon-WeChat/pages/account-settings/index.js b/JC-Salon-WeChat/pages/account-settings/index.js index 4ccbd5a6..62d7286f 100644 --- a/JC-Salon-WeChat/pages/account-settings/index.js +++ b/JC-Salon-WeChat/pages/account-settings/index.js @@ -1,6 +1,7 @@ const userApi = require('../../api/user') const auth = require('../../utils/auth') const profileCache = require('../../utils/profile-cache') +const { showErrorToast, toUserMessage } = require('../../utils/toast') Page({ data: { @@ -26,7 +27,7 @@ Page({ const closureRequest = await userApi.getAccountClosure() this.setData({ closureRequest: closureRequest || null }) } catch (error) { - this.setData({ closureError: error.message || '注销状态加载失败' }) + this.setData({ closureError: toUserMessage(error, '注销状态加载失败') }) } finally { this.setData({ closureLoading: false }) } @@ -46,7 +47,7 @@ Page({ this.setData({ closureRequest }) wx.showToast({ title: '注销申请已提交' }) } catch (error) { - wx.showToast({ title: error.message || '申请提交失败', icon: 'none' }) + showErrorToast(error, '申请提交失败') } }, @@ -58,7 +59,7 @@ Page({ await this.loadClosureRequest() wx.showToast({ title: '申请已撤回' }) } catch (error) { - wx.showToast({ title: error.message || '撤回失败', icon: 'none' }) + showErrorToast(error, '撤回失败') } }, @@ -71,7 +72,7 @@ Page({ const session = auth.getSession() app.setSession({ ...session, userInfo: { ...(session.userInfo || {}), ...profile } }) } catch (error) { - wx.showToast({ title: error.message || '账号信息加载失败', icon: 'none' }) + showErrorToast(error, '账号信息加载失败') } finally { this.setData({ loading: false }) } @@ -103,7 +104,7 @@ Page({ await this.loadProfile({ force: true }) wx.showToast({ title: '手机号已绑定' }) } catch (error) { - wx.showToast({ title: error.message || '绑定失败', icon: 'none' }) + showErrorToast(error, '绑定失败') } finally { this.setData({ binding: false }) } @@ -122,7 +123,7 @@ Page({ this.startCountdown() wx.showToast({ title: '验证码已发送' }) } catch (error) { - wx.showToast({ title: error.message || '验证码发送失败', icon: 'none' }) + showErrorToast(error, '验证码发送失败') } finally { this.setData({ codeLoading: false }) } @@ -151,7 +152,7 @@ Page({ await this.loadProfile({ force: true }) wx.showToast({ title: '手机号已绑定' }) } catch (error) { - wx.showToast({ title: error.message || '绑定失败', icon: 'none' }) + showErrorToast(error, '绑定失败') } finally { this.setData({ binding: false }) } @@ -178,7 +179,7 @@ Page({ await this.loadProfile({ force: true }) wx.showToast({ title: '手机号已解绑' }) } catch (error) { - wx.showToast({ title: error.message || '解绑失败', icon: 'none' }) + showErrorToast(error, '解绑失败') } finally { this.setData({ binding: false }) } diff --git a/JC-Salon-WeChat/pages/appointment-detail/index.js b/JC-Salon-WeChat/pages/appointment-detail/index.js index c49e37eb..98947bf6 100644 --- a/JC-Salon-WeChat/pages/appointment-detail/index.js +++ b/JC-Salon-WeChat/pages/appointment-detail/index.js @@ -1,5 +1,7 @@ const planningApi = require('../../api/planning') +const customersApi = require('../../api/customers') const { markPlanningRefresh } = require('../../utils/planning-refresh') +const { showErrorToast, toUserMessage } = require('../../utils/toast') function displayValue(value, fallback) { if (value === null || value === undefined) return fallback @@ -24,6 +26,7 @@ Page({ showComplete: false, showCancel: false, updating: false, + dialing: false, loadError: '' }, @@ -41,7 +44,7 @@ Page({ appointment: {}, avatarText: '', timeText: '', - loadError: error.message || '预约详情加载失败' + loadError: toUserMessage(error, '预约详情加载失败') }) } }, @@ -97,7 +100,7 @@ Page({ wx.showToast({ title: '已更新' }) this.loadDetail() } catch (error) { - wx.showToast({ title: error.message || '操作失败', icon: 'none' }) + showErrorToast(error, '操作失败') } finally { this.setData({ updating: false }) } @@ -130,6 +133,31 @@ Page({ }) }, + async dialCustomer() { + const appointment = this.data.appointment || {} + if (this.data.dialing) return + if (!appointment.customerPhoneAvailable || !appointment.orderId) { + wx.showToast({ title: '该客户暂无可拨打的手机号', icon: 'none' }) + return + } + this.setData({ dialing: true }) + try { + const result = await customersApi.dialCustomer({ + customerId: appointment.customerId, + appointmentId: appointment.orderItemId, + orderId: appointment.orderId + }) + if (!result || !result.dialNumber) { + throw new Error('未获取到可拨打号码') + } + wx.makePhoneCall({ phoneNumber: result.dialNumber }) + } catch (error) { + showErrorToast(error, '取号失败') + } finally { + this.setData({ dialing: false }) + } + }, + goTransfer() { if (!this.data.showTransfer) return wx.navigateTo({ url: `/pages/artist-transfer/index?id=${this.data.id}` }) diff --git a/JC-Salon-WeChat/pages/appointment-detail/index.test.js b/JC-Salon-WeChat/pages/appointment-detail/index.test.js index 22edb2da..2b3be24d 100644 --- a/JC-Salon-WeChat/pages/appointment-detail/index.test.js +++ b/JC-Salon-WeChat/pages/appointment-detail/index.test.js @@ -95,4 +95,7 @@ const styles = fs.readFileSync(path.join(__dirname, 'index.wxss'), 'utf8') ;['订单编号', '服务项目', '美甲师', '时长', '成交金额', '取消原因', 'remarkText', 'customerPhoneText'].forEach(text => assert(markup.includes(text))) assert.match(markup, /class="primary-btn transfer-action"/) assert.match(markup, /class="danger-btn"/) +assert.match(markup, /appointment\.customerPhoneAvailable && appointment\.orderId/) +assert.strictEqual(markup.includes('appointment.customerId && appointment.orderId'), false) assert.match(styles, /\.transfer-action\s*\{[^}]*box-shadow/) +assert.match(styles, /\.call-btn\s*\{/) diff --git a/JC-Salon-WeChat/pages/appointment-detail/index.wxml b/JC-Salon-WeChat/pages/appointment-detail/index.wxml index 97af5b86..285f2f7c 100644 --- a/JC-Salon-WeChat/pages/appointment-detail/index.wxml +++ b/JC-Salon-WeChat/pages/appointment-detail/index.wxml @@ -10,7 +10,16 @@ {{avatarText}} {{appointment.customerNameText}} - {{appointment.customerPhoneText}} + + {{appointment.customerPhoneText}} + + {{appointment.historicalBackfill ? '历史补单 · ' : ''}}{{appointment.statusText}} diff --git a/JC-Salon-WeChat/pages/appointment-detail/index.wxss b/JC-Salon-WeChat/pages/appointment-detail/index.wxss index 54a5b15e..2df450ce 100644 --- a/JC-Salon-WeChat/pages/appointment-detail/index.wxss +++ b/JC-Salon-WeChat/pages/appointment-detail/index.wxss @@ -67,6 +67,24 @@ font-size: 24rpx; } +.phone-row { + display: flex; + align-items: center; + gap: 12rpx; +} + +.call-btn { + flex-shrink: 0; + margin: 0; + padding: 0 18rpx; + border-radius: 999rpx; + background: #edf6ef; + color: #247b63; + font-size: 22rpx; + font-weight: 800; + line-height: 44rpx; +} + .status-tag { flex-shrink: 0; padding: 8rpx 14rpx; diff --git a/JC-Salon-WeChat/pages/appointment-form/entity-selector.test.js b/JC-Salon-WeChat/pages/appointment-form/entity-selector.test.js index a09e6503..4aa8b0a4 100644 --- a/JC-Salon-WeChat/pages/appointment-form/entity-selector.test.js +++ b/JC-Salon-WeChat/pages/appointment-form/entity-selector.test.js @@ -36,17 +36,17 @@ function createPage() { async function run() { const page = createPage() - page.selectCustomer({ detail: { item: { id: 18, name: '小周', phone: '13800138000' } } }) + page.selectCustomer({ detail: { item: { id: 18, name: '小周', phone: '138****8000' } } }) assert.strictEqual(page.data.form.customerUserId, 18) assert.strictEqual(page.data.form.customerName, '小周') - assert.strictEqual(page.data.form.phone, '13800138000') + assert.strictEqual(page.data.form.phone, '') assert.strictEqual(page.data.customerSheetVisible, false) page.data.form.customerUserId = 18 page.onCustomerInput({ currentTarget: { dataset: { field: 'customerName' } }, detail: { value: '新客户' } }) assert.strictEqual(page.data.form.customerUserId, '') assert.strictEqual(page.data.form.customerName, '新客户') - assert.strictEqual(page.data.form.phone, '13800138000') + assert.strictEqual(page.data.form.phone, '') customersApi.matchIdentityForAppointment = async () => [] customersApi.create = async () => { throw new Error('预约客户建档应随预约请求提交') } @@ -61,10 +61,11 @@ async function run() { assert.strictEqual(name, '小周') assert.strictEqual(wechatId, undefined) assert.strictEqual(phone, '13800138000') - return [{ id: '18', name: '小周', phone: '13800138000' }] + return [{ id: '18', name: '小周', phone: '138****8000' }] } assert.strictEqual(await page.ensureCustomerBeforeSubmit(), true) assert.strictEqual(page.data.form.customerUserId, '18') + assert.strictEqual(page.data.form.phone, '13800138000') page.data.artists = [{ id: 1, name: '小周' }, { id: 2, name: '小李' }] page.onArtistSearch({ detail: { value: '李' } }) diff --git a/JC-Salon-WeChat/pages/appointment-form/index.js b/JC-Salon-WeChat/pages/appointment-form/index.js index 1709fc88..64577cff 100644 --- a/JC-Salon-WeChat/pages/appointment-form/index.js +++ b/JC-Salon-WeChat/pages/appointment-form/index.js @@ -4,6 +4,7 @@ const customersApi = require('../../api/customers') const dateUtil = require('../../utils/date') const { markPlanningRefresh } = require('../../utils/planning-refresh') const { uploadObjectFile } = require('../../utils/upload') +const { showErrorToast, toUserMessage } = require('../../utils/toast') const DRAFT_STORAGE_PREFIX = 'managerAppointmentDraft' const DRAFT_TTL_MS = 7 * 24 * 60 * 60 * 1000 @@ -520,6 +521,7 @@ function normalizeCustomer(customer) { id: customer.id, name, phone, + phoneAvailable: customer.phoneAvailable === true || (Boolean(phone) && !String(phone).includes('*')), displayName: name || phone || '客户', displayPhone: phone || '未填写手机号', createdAt: customerCreatedAt(customer) @@ -664,7 +666,7 @@ Page({ try { draft = readDraft() } catch (error) { - wx.showToast({ title: error.message || '预约草稿读取失败', icon: 'none' }) + showErrorToast(error, '预约草稿读取失败') } } const draftForm = draft && draft.form ? draft.form : {} @@ -757,7 +759,7 @@ Page({ this.setData({ products: [], filteredProducts: [], - productError: error.message || '作品列表加载失败' + productError: toUserMessage(error, '作品列表加载失败') }) } finally { this.setData({ loadingProducts: false }) @@ -826,8 +828,8 @@ Page({ businessEndTime: '', selectedArtist: unassignedSelection, 'form.artistId': '', - artistError: error.message || '美甲师列表加载失败', - conflictTip: error.message || '美甲师列表加载失败', + artistError: toUserMessage(error, '美甲师列表加载失败'), + conflictTip: toUserMessage(error, '美甲师列表加载失败'), conflictLevel: 'danger' }) } @@ -860,7 +862,7 @@ Page({ }) this.refreshCustomerSuggestions(this.data.form.customerName, this.data.form.phone) } catch (error) { - this.setData({ customerDirectory: [], customerOptions: [], customerError: error.message || '客户列表加载失败' }) + this.setData({ customerDirectory: [], customerOptions: [], customerError: toUserMessage(error, '客户列表加载失败') }) } finally { this.setData({ customerLoading: false }) } @@ -952,7 +954,7 @@ Page({ if (requestSeq !== this._customerSuggestionSeq) return const rows = Array.isArray(result) ? result : (result.list || []) const remoteSuggestions = rows.map(normalizeCustomer) - .filter(customer => (!name || customer.name.toLowerCase().includes(name)) && (!phone || customer.phone.toLowerCase().includes(phone))) + .filter(customer => !name || customer.name.toLowerCase().includes(name)) .slice(0, 3) .map(buildCustomerSelectorItem) this.setData({ customerSuggestions: remoteSuggestions }) @@ -971,7 +973,8 @@ Page({ this.setData({ 'form.customerUserId': customer.id, 'form.customerName': customer.name, - 'form.phone': customer.phone || '', + // 后端仅返回脱敏号码,不回填到表单,避免把脱敏值当真实号码提交 + 'form.phone': '', 'form.createCustomerRecord': false, customerSuggestions: [], customerSheetVisible: false, @@ -1000,11 +1003,25 @@ Page({ return } const keyword = String(keywordValue === undefined ? this.data.customerKeyword : keywordValue || '').trim() + if (keyword) { + // 号码已全场景脱敏,按手机号检索必须交给后端精确匹配 + try { + const result = await customersApi.listForAppointment({ page: 1, size: 100, keyword }) + const rows = Array.isArray(result) ? result : (result.list || []) + this.setData({ + customerOptions: this.sortCustomerOptions(rows.map(normalizeCustomer)), + customerError: '' + }) + } catch (error) { + this.setData({ customerOptions: [], customerError: toUserMessage(error, '客户加载失败') }) + } + return + } if (this.data.customerDirectory.length === 0) await this.loadCustomerDirectory() - const matches = this.data.customerDirectory.filter(customer => - !keyword || `${customer.name} ${customer.phone}`.toLowerCase().includes(keyword.toLowerCase()) - ) - this.setData({ customerOptions: this.sortCustomerOptions(matches), customerError: '' }) + this.setData({ + customerOptions: this.sortCustomerOptions(this.data.customerDirectory), + customerError: '' + }) }, changeCustomerView(event) { @@ -1013,11 +1030,10 @@ Page({ toggleCustomerSort() { const customerNewestFirst = !this.data.customerNewestFirst - const keyword = String(this.data.customerKeyword || '').trim().toLowerCase() - const matches = this.data.customerDirectory.filter(customer => - !keyword || `${customer.name} ${customer.phone}`.toLowerCase().includes(keyword) - ) - this.setData({ customerNewestFirst, customerOptions: this.sortCustomerOptions(matches, customerNewestFirst) }) + this.setData({ + customerNewestFirst, + customerOptions: this.sortCustomerOptions(this.data.customerOptions, customerNewestFirst) + }) }, retryCustomerSearch() { @@ -1032,7 +1048,8 @@ Page({ this.setData({ 'form.customerUserId': customer.id, 'form.customerName': customer.name, - 'form.phone': customer.phone || '', + // 选择已有客户时不回填脱敏号码,手机号仅在用户主动修改时提交 + 'form.phone': '', 'form.createCustomerRecord': false, customerSheetVisible: false, customerKeyword: '', @@ -1105,7 +1122,7 @@ Page({ return true } catch (error) { this.setData({ draftSavedAtText: '草稿保存失败,请点击保存草稿重试' }) - if (showToast) wx.showToast({ title: error.message || '草稿保存失败', icon: 'none' }) + if (showToast) showErrorToast(error, '草稿保存失败') return false } }, @@ -1132,7 +1149,7 @@ Page({ try { removeDraftForm() } catch (error) { - wx.showToast({ title: error.message || '草稿清理失败,请稍后重试', icon: 'none' }) + showErrorToast(error, '草稿清理失败,请稍后重试') return } const defaults = this._entryDefaults || {} @@ -1401,7 +1418,7 @@ Page({ wx.showToast({ title: `已添加${filePaths.length}张图片`, icon: 'success' }) } } catch (error) { - wx.showToast({ title: error.message || '图片上传失败', icon: 'none' }) + showErrorToast(error, '图片上传失败') } finally { this.setData({ manualImageUploading: false }) } @@ -1607,7 +1624,7 @@ Page({ timePickerMinutes: [], selectedTimeCandidate: '', 'form.appointmentTime': '', - timeError: error.message || '营业时间加载失败', + timeError: toUserMessage(error, '营业时间加载失败'), businessHoursMissing: false, timeLoading: false, timeSelectTip: '营业时间加载失败' @@ -1682,7 +1699,7 @@ Page({ timePickerMinutes: [], selectedTimeCandidate: '', 'form.appointmentTime': '', - timeError: error.message || '可约时间加载失败', + timeError: toUserMessage(error, '可约时间加载失败'), businessHoursMissing: false, timeSelectTip: '可约时间加载失败' }) @@ -1852,7 +1869,7 @@ Page({ this.setData({ conflictTip: tip, conflictLevel: 'free' }) return { ok: true, tip } } catch (error) { - const tip = error.message || '排班校验失败,请稍后重试' + const tip = toUserMessage(error, '排班校验失败,请稍后重试') this.setData({ conflictTip: tip, conflictLevel: 'danger' }) return { ok: false, tip } } @@ -1925,7 +1942,6 @@ Page({ this.setData({ 'form.customerUserId': customer.id, 'form.customerName': customer.name, - 'form.phone': customer.phone, 'form.createCustomerRecord': false }) } else { @@ -1947,7 +1963,7 @@ Page({ this.setData({ 'form.createCustomerRecord': Boolean(createChoice.confirm) }) return true } catch (error) { - wx.showToast({ title: error.message || '客户校验失败,请稍后重试', icon: 'none' }) + showErrorToast(error, '客户校验失败,请稍后重试') return false } finally { this.setData({ loading: false }) @@ -2065,7 +2081,7 @@ Page({ if ((error.message || '').includes('有效期') || (error.message || '').includes('到期')) { await showBusinessExpiryNotice() } else { - wx.showToast({ title: error.message || '提交失败', icon: 'none' }) + showErrorToast(error, '提交失败') } } finally { this.setData({ loading: false }) diff --git a/JC-Salon-WeChat/pages/artist-transfer/index.js b/JC-Salon-WeChat/pages/artist-transfer/index.js index 51d28295..d7e0b46b 100644 --- a/JC-Salon-WeChat/pages/artist-transfer/index.js +++ b/JC-Salon-WeChat/pages/artist-transfer/index.js @@ -1,6 +1,7 @@ const planningApi = require('../../api/planning') const dateUtil = require('../../utils/date') const { markPlanningRefresh } = require('../../utils/planning-refresh') +const { showErrorToast, toUserMessage } = require('../../utils/toast') Page({ data: { @@ -42,7 +43,7 @@ Page({ }) return true } catch (error) { - this.setData({ loadError: error.message || '预约详情加载失败' }) + this.setData({ loadError: toUserMessage(error, '预约详情加载失败') }) return false } }, @@ -76,7 +77,7 @@ Page({ artistItems: [], selectedArtistId: '', selectedArtist: {}, - loadError: error.message || '美甲师列表加载失败' + loadError: toUserMessage(error, '美甲师列表加载失败') }) } }, @@ -154,7 +155,7 @@ Page({ wx.showToast({ title: this.data.isUnassigned ? '已分配' : '已改派' }) setTimeout(() => wx.navigateBack(), 500) } catch (error) { - wx.showToast({ title: error.message || '改派失败', icon: 'none' }) + showErrorToast(error, '改派失败') } finally { this.setData({ loading: false }) } diff --git a/JC-Salon-WeChat/pages/backfill-order/index.js b/JC-Salon-WeChat/pages/backfill-order/index.js index 665c051d..43b7da69 100644 --- a/JC-Salon-WeChat/pages/backfill-order/index.js +++ b/JC-Salon-WeChat/pages/backfill-order/index.js @@ -4,6 +4,7 @@ const productsApi = require('../../api/products') const customersApi = require('../../api/customers') const dateUtil = require('../../utils/date') const { uploadObjectFile } = require('../../utils/upload') +const { showErrorToast, toUserMessage } = require('../../utils/toast') function normalizeProduct(product, artists) { const artistIds = String(product.bookableArtists || '').split(',').map(id => id.trim()).filter(Boolean) @@ -92,10 +93,10 @@ Page({ manualProductSheetVisible: false }) }, - async loadArtists(preferredArtistId) { this.setData({ loadingArtists: true }); try { const result = await employeesApi.list({ page: 1, size: 100 }); const list = result.list || result || []; const artists = list.map(item => ({ ...item, name: item.name || item.nickname || item.account || `美甲师${item.id}` })); const selected = artists.find(item => String(item.id) === String(preferredArtistId || this.data.form.artistId)); this.setData({ artists, artistOptions: artists.map(item => ({ id: item.id, title: item.name, subtitle: item.phone || '' })), selectedArtistName: selected ? selected.name : '', 'form.artistId': selected ? selected.id : '', artistError: '' }); this.refreshProductOptions() } catch (error) { this.setData({ artists: [], artistOptions: [], artistError: error.message || '美甲师加载失败' }) } finally { this.setData({ loadingArtists: false }) } }, - async loadProducts() { this.setData({ loadingProducts: true }); try { const result = await productsApi.list({ page: 1, size: 100 }); this.setData({ products: result.list || result || [], productError: '' }); this.refreshProductOptions() } catch (error) { this.setData({ products: [], productOptions: [], productError: error.message || '款式加载失败' }) } finally { this.setData({ loadingProducts: false }) } }, + async loadArtists(preferredArtistId) { this.setData({ loadingArtists: true }); try { const result = await employeesApi.list({ page: 1, size: 100 }); const list = result.list || result || []; const artists = list.map(item => ({ ...item, name: item.name || item.nickname || item.account || `美甲师${item.id}` })); const selected = artists.find(item => String(item.id) === String(preferredArtistId || this.data.form.artistId)); this.setData({ artists, artistOptions: artists.map(item => ({ id: item.id, title: item.name, subtitle: item.phone || '' })), selectedArtistName: selected ? selected.name : '', 'form.artistId': selected ? selected.id : '', artistError: '' }); this.refreshProductOptions() } catch (error) { this.setData({ artists: [], artistOptions: [], artistError: toUserMessage(error, '美甲师加载失败') }) } finally { this.setData({ loadingArtists: false }) } }, + async loadProducts() { this.setData({ loadingProducts: true }); try { const result = await productsApi.list({ page: 1, size: 100 }); this.setData({ products: result.list || result || [], productError: '' }); this.refreshProductOptions() } catch (error) { this.setData({ products: [], productOptions: [], productError: toUserMessage(error, '款式加载失败') }) } finally { this.setData({ loadingProducts: false }) } }, refreshProductOptions() { const keyword = String(this.data.productKeyword || '').trim().toLowerCase(); const all = (this.data.products || []).map(product => normalizeProduct(product, this.data.artists)); this.setData({ productOptions: all.filter(item => !keyword || `${item.title} ${item.artistText} ${item.durationText} ${item.tagList.join(' ')}`.toLowerCase().includes(keyword)) }) }, - async loadCustomers() { this.setData({ loadingCustomers: true }); try { const result = customersApi.listForAppointment ? await customersApi.listForAppointment({ page: 1, size: 100 }) : await customersApi.list({ page: 1, size: 100 }); const options = (result.list || result || []).map(normalizeCustomer); this.setData({ allCustomerOptions: options, customerOptions: options, customerError: '' }) } catch (error) { this.setData({ customerError: error.message || '客户加载失败' }) } finally { this.setData({ loadingCustomers: false }) } }, + async loadCustomers() { this.setData({ loadingCustomers: true }); try { const result = customersApi.listForAppointment ? await customersApi.listForAppointment({ page: 1, size: 100 }) : await customersApi.list({ page: 1, size: 100 }); const options = (result.list || result || []).map(normalizeCustomer); this.setData({ allCustomerOptions: options, customerOptions: options, customerError: '' }) } catch (error) { this.setData({ customerError: toUserMessage(error, '客户加载失败') }) } finally { this.setData({ loadingCustomers: false }) } }, openProductSelector() { this.setData({ manualProductSheetVisible: true, manualProductTitleLength: String(this.data.manualProductDraft.title || '').length }) }, openProductLibrary() { this.setData({ manualProductSheetVisible: false, productSelectorVisible: true }) }, closeProductSelector() { this.setData({ productSelectorVisible: false }) }, @@ -114,11 +115,11 @@ Page({ searchCustomers(event) { const keyword = String(event.detail.value || '').toLowerCase(); this.setData({ customerKeyword: keyword, customerOptions: this.data.allCustomerOptions.filter(item => !keyword || `${item.name} ${item.phone}`.toLowerCase().includes(keyword)) }) }, selectProduct(event) { const item = event.detail.item || {}; const duration = String(item.serviceDurationMinutes || String(item.approximateDuration || '').replace(/[^0-9]/g, '') || '60'); this.setData({ 'form.productId': item.id, 'form.manualProductTitle': '', 'form.amount': item.price == null ? this.data.form.amount : String(item.price), 'form.durationMinutes': duration, selectedProduct: item, selectedProductTitle: item.title, selectedProductPriceText: item.priceText || '价格待定', manualProductDraft: { title: '', price: '', durationMinutes: duration, description: '' }, productSelectorVisible: false, manualProductSheetVisible: false }) }, selectArtist(event) { const item = event.detail.item; this.setData({ 'form.artistId': item.id, selectedArtistName: item.title, artistSelectorVisible: false }) }, - selectCustomer(event) { const item = event.detail.item || {}; this.setData({ 'form.customerUserId': item.id, 'form.customerName': item.name || item.title, 'form.phone': item.phone || '', customerSelectorVisible: false }) }, + selectCustomer(event) { const item = event.detail.item || {}; this.setData({ 'form.customerUserId': item.id, 'form.customerName': item.name || item.title, 'form.phone': '', customerSelectorVisible: false }) }, useWalkIn() { this.setData({ 'form.customerUserId': '', 'form.customerName': '', 'form.wechatId': '', 'form.phone': '', customerSelectorVisible: false }) }, onCustomerInput(event) { this.setData({ [`form.${event.currentTarget.dataset.field}`]: event.detail.value, 'form.customerUserId': '' }) }, useManualProduct() { const title = String(this.data.manualProductDraft.title || '').trim(); const priceText = String(this.data.manualProductDraft.price || this.data.form.amount || '').trim(); const price = Number(priceText); const images = this.data.form.manualProductImages || []; if (this.data.form.productId) { if (!priceText || !Number.isFinite(price) || price < 0) { wx.showToast({ title: '请输入正确的款式价格', icon: 'none' }); return } this.setData({ 'form.amount': priceText, 'form.durationMinutes': String(this.data.manualProductDraft.durationMinutes || '60'), manualProductSheetVisible: false }); return } if (!title && !images.length) { wx.showToast({ title: '请填写款式名称或添加图片', icon: 'none' }); return } if (!priceText || !Number.isFinite(price) || price < 0) { wx.showToast({ title: '请输入正确的款式价格', icon: 'none' }); return } const duration = String(this.data.manualProductDraft.durationMinutes || '60'); this.setData({ 'form.productId': '', 'form.manualProductTitle': title, 'form.manualProductDescription': this.data.manualProductDraft.description || '', 'form.manualProductPrice': priceText, 'form.amount': priceText, 'form.durationMinutes': duration, 'manualProductDraft.price': priceText, selectedProduct: {}, selectedProductTitle: title, selectedProductPriceText: `¥${price}`, productSelectorVisible: false, manualProductSheetVisible: false }) }, - async chooseManualProductImage() { if (this.data.manualImageUploading) return; const remaining = 9 - (this.data.form.manualProductImages || []).length; if (remaining <= 0) { wx.showToast({ title: '最多添加9张图片', icon: 'none' }); return } try { this.setData({ manualImageUploading: true }); const paths = await chooseImages(remaining); for (const filePath of paths) { const result = await uploadObjectFile(filePath); const fileId = result.id || result.fileId; if (!fileId) throw new Error('图片上传成功但未返回文件ID'); this.setData(imagePatch((this.data.form.manualProductImages || []).concat({ fileId: String(fileId), fileUrl: result.fileUrl || result.primaryUrl || '', previewUrl: filePath }))) } } catch (error) { wx.showToast({ title: error.message || '图片上传失败', icon: 'none' }) } finally { this.setData({ manualImageUploading: false }) } }, + async chooseManualProductImage() { if (this.data.manualImageUploading) return; const remaining = 9 - (this.data.form.manualProductImages || []).length; if (remaining <= 0) { wx.showToast({ title: '最多添加9张图片', icon: 'none' }); return } try { this.setData({ manualImageUploading: true }); const paths = await chooseImages(remaining); for (const filePath of paths) { const result = await uploadObjectFile(filePath); const fileId = result.id || result.fileId; if (!fileId) throw new Error('图片上传成功但未返回文件ID'); this.setData(imagePatch((this.data.form.manualProductImages || []).concat({ fileId: String(fileId), fileUrl: result.fileUrl || result.primaryUrl || '', previewUrl: filePath }))) } } catch (error) { showErrorToast(error, '图片上传失败') } finally { this.setData({ manualImageUploading: false }) } }, removeManualProductImage(event) { const index = Number(event.currentTarget.dataset.index); this.setData(imagePatch((this.data.form.manualProductImages || []).filter((item, itemIndex) => itemIndex !== index))) }, onManualProductImageError(event) { const index = Number(event.currentTarget.dataset.index); const images = this.data.form.manualProductImages || []; if (!images[index] || !images[index].fileUrl) return; const fallback = images.slice(); fallback[index] = { ...fallback[index], previewUrl: fallback[index].fileUrl }; this.setData(imagePatch(fallback)) }, onSelectedProductImageError() { this.setData({ 'selectedProduct.coverImage': '' }) }, @@ -126,5 +127,5 @@ Page({ onDateChange(event) { this.setData({ 'form.serviceDate': event.detail.value }) }, onTimeChange(event) { this.setData({ 'form.serviceTime': event.detail.value }) }, selectStatus(event) { this.setData({ 'form.status': Number(event.currentTarget.dataset.status) }) }, - async submit() { const form = this.data.form; if (!form.serviceDate || (!form.productId && !String(form.manualProductTitle || '').trim() && !(form.manualProductImages || []).length) || !String(form.amount || '').trim() || !form.artistId) { wx.showToast({ title: '请补全款式、金额、日期和美甲师', icon: 'none' }); return } if (form.phone && !/^1[3-9]\d{9}$/.test(String(form.phone).trim())) { wx.showToast({ title: '请输入正确手机号', icon: 'none' }); return } this.setData({ submitting: true }); try { const payload = { ...form, amount: Number(form.amount), manualProductPrice: Number(form.manualProductPrice || form.amount), durationMinutes: Number(form.durationMinutes) || 60, manualProductImageFileIds: String(form.manualProductImageFileIds || '').trim() || undefined, customerName: String(form.customerName || '').trim() || undefined, wechatId: String(form.wechatId || '').trim() || undefined, phone: String(form.phone || '').trim() || undefined, serviceTime: String(form.serviceTime || '').trim() || undefined }; if (!payload.manualProductTitle && payload.manualProductImageFileIds) payload.manualProductTitle = String(form.customerName || '').trim() || '散客款式'; await planningApi.createBackfillOrder(payload); wx.showToast({ title: '历史补单已保存', icon: 'success' }); const app = getApp(); app.globalData.planningNeedRefresh = true; setTimeout(() => wx.navigateBack(), 500) } catch (error) { wx.showToast({ title: error.message || '保存失败', icon: 'none' }) } finally { this.setData({ submitting: false }) } } + async submit() { const form = this.data.form; if (!form.serviceDate || (!form.productId && !String(form.manualProductTitle || '').trim() && !(form.manualProductImages || []).length) || !String(form.amount || '').trim() || !form.artistId) { wx.showToast({ title: '请补全款式、金额、日期和美甲师', icon: 'none' }); return } if (form.phone && !/^1[3-9]\d{9}$/.test(String(form.phone).trim())) { wx.showToast({ title: '请输入正确手机号', icon: 'none' }); return } this.setData({ submitting: true }); try { const payload = { ...form, amount: Number(form.amount), manualProductPrice: Number(form.manualProductPrice || form.amount), durationMinutes: Number(form.durationMinutes) || 60, manualProductImageFileIds: String(form.manualProductImageFileIds || '').trim() || undefined, customerName: String(form.customerName || '').trim() || undefined, wechatId: String(form.wechatId || '').trim() || undefined, phone: String(form.phone || '').trim() || undefined, serviceTime: String(form.serviceTime || '').trim() || undefined }; if (!payload.manualProductTitle && payload.manualProductImageFileIds) payload.manualProductTitle = String(form.customerName || '').trim() || '散客款式'; await planningApi.createBackfillOrder(payload); wx.showToast({ title: '历史补单已保存', icon: 'success' }); const app = getApp(); app.globalData.planningNeedRefresh = true; setTimeout(() => wx.navigateBack(), 500) } catch (error) { showErrorToast(error, '保存失败') } finally { this.setData({ submitting: false }) } } }) diff --git a/JC-Salon-WeChat/pages/customer-detail/index.js b/JC-Salon-WeChat/pages/customer-detail/index.js index 721f2dd8..de65293a 100644 --- a/JC-Salon-WeChat/pages/customer-detail/index.js +++ b/JC-Salon-WeChat/pages/customer-detail/index.js @@ -1,4 +1,5 @@ const customersApi = require('../../api/customers') +const { toUserMessage } = require('../../utils/toast') function canCreateAppointment() { const app = getApp() @@ -61,7 +62,7 @@ Page({ customer: {}, stats: { orderCount: 0, amount: 0, lastTime: '-' }, orders: [], - loadError: error.message || '客户详情加载失败' + loadError: toUserMessage(error, '客户详情加载失败') }) } }, diff --git a/JC-Salon-WeChat/pages/customers/index.js b/JC-Salon-WeChat/pages/customers/index.js index 87a88a3e..a853da7d 100644 --- a/JC-Salon-WeChat/pages/customers/index.js +++ b/JC-Salon-WeChat/pages/customers/index.js @@ -1,4 +1,5 @@ const customersApi = require('../../api/customers') +const { showErrorToast, toUserMessage } = require('../../utils/toast') Page({ data: { @@ -42,7 +43,7 @@ Page({ } catch (error) { this.setData({ customers: [], - loadError: error.message || '客户列表加载失败' + loadError: toUserMessage(error, '客户列表加载失败') }) } }, @@ -134,11 +135,11 @@ Page({ return } } catch (lookupError) { - wx.showToast({ title: lookupError.message || '客户重复,请重新查询已有客户', icon: 'none' }) + showErrorToast(lookupError, '客户重复,请重新查询已有客户') return } } - wx.showToast({ title: error.message || '新增失败', icon: 'none' }) + showErrorToast(error, '新增失败') } finally { this.setData({ creating: false }) } diff --git a/JC-Salon-WeChat/pages/employee-create/index.js b/JC-Salon-WeChat/pages/employee-create/index.js index b712102c..3ccf5857 100644 --- a/JC-Salon-WeChat/pages/employee-create/index.js +++ b/JC-Salon-WeChat/pages/employee-create/index.js @@ -1,5 +1,6 @@ const employeesApi = require('../../api/employees') const { chooseImageFilePath, uploadObjectFile } = require('../../utils/upload') +const { showErrorToast, toUserMessage } = require('../../utils/toast') const EMPLOYEE_COLORS = ['#7BA7C7', '#8FB89A', '#A894C7', '#D7A86E', '#D98DA5', '#79A6A3', '#B9A16B', '#9BA9C8'] @@ -66,7 +67,7 @@ Page({ 'form.avatarUrl': filePath }) } catch (error) { - wx.showToast({ title: error.message || '头像上传失败', icon: 'none' }) + showErrorToast(error, '头像上传失败') } finally { this.setData({ avatarUploading: false }) } @@ -122,7 +123,7 @@ Page({ } await this.offerPendingAssociation() } catch (error) { - wx.showToast({ title: error.message || '新增失败', icon: 'none' }) + showErrorToast(error, '新增失败') } finally { this.setData({ creating: false }) } @@ -144,7 +145,7 @@ Page({ this.setData({ associatingApplication: false }) wx.showModal({ title: '关联审核未完成', - content: error.message || '美甲师档案已创建,可重试关联申请。', + content: toUserMessage(error, '美甲师档案已创建,可重试关联申请。'), confirmText: '重试', cancelText: '稍后处理', success: result => { @@ -207,7 +208,7 @@ Page({ this.setData({ associationSheetVisible: false, onboardingVisible: true }) wx.showToast({ title: '已预关联申请', icon: 'success' }) } catch (error) { - wx.showToast({ title: error.message || '关联失败,请重新选择', icon: 'none' }) + showErrorToast(error, '关联失败,请重新选择') this.setData({ associationSelectedId: '' }) } finally { this.setData({ associationLoading: false }) @@ -258,7 +259,7 @@ Page({ }).catch(error => { wx.showModal({ title: '默认排班设置失败', - content: error.message || '未设置排班前,该美甲师暂不可预约。请重试或返回排班设置。', + content: toUserMessage(error, '未设置排班前,该美甲师暂不可预约。请重试或返回排班设置。'), confirmText: '重试', cancelText: '稍后设置', success: result => { diff --git a/JC-Salon-WeChat/pages/employee-detail/index.js b/JC-Salon-WeChat/pages/employee-detail/index.js index aafcebdd..6c5a6147 100644 --- a/JC-Salon-WeChat/pages/employee-detail/index.js +++ b/JC-Salon-WeChat/pages/employee-detail/index.js @@ -1,4 +1,5 @@ const employeesApi = require('../../api/employees') +const { toUserMessage } = require('../../utils/toast') const EMPLOYEE_COLORS = ['#7AA9C2', '#8EB99B', '#BDA7D8', '#D7B17D', '#D98D8D'] @@ -35,7 +36,7 @@ Page({ } catch (error) { this.setData({ employee: {}, - loadError: error.message || '美甲师详情加载失败' + loadError: toUserMessage(error, '美甲师详情加载失败') }) } }, diff --git a/JC-Salon-WeChat/pages/employees/index.js b/JC-Salon-WeChat/pages/employees/index.js index a926a20f..bab67d5e 100644 --- a/JC-Salon-WeChat/pages/employees/index.js +++ b/JC-Salon-WeChat/pages/employees/index.js @@ -1,6 +1,7 @@ const employeesApi = require('../../api/employees') const planningApi = require('../../api/planning') const dateUtil = require('../../utils/date') +const { showErrorToast, toUserMessage } = require('../../utils/toast') const EMPLOYEE_COLORS = ['#7AA9C2', '#8EB99B', '#BDA7D8', '#D7B17D', '#D98D8D'] @@ -93,7 +94,7 @@ Page({ })) this.setData({ reviewApplications: applications, reviewPendingCount: applications.length }) } catch (error) { - this.setData({ reviewError: error.message || '审核申请加载失败' }) + this.setData({ reviewError: toUserMessage(error, '审核申请加载失败') }) } finally { this.setData({ reviewLoading: false }) } @@ -142,7 +143,7 @@ Page({ if (result.confirm) this.createEmployeeForApplication(applicationId, application && application.applicationNo) } } catch (error) { - this.setData({ associationError: error.message || '未关联美甲师加载失败' }) + this.setData({ associationError: toUserMessage(error, '未关联美甲师加载失败') }) } finally { this.setData({ associationLoading: false }) } @@ -248,7 +249,7 @@ Page({ wx.showToast({ title: successMessage, icon: 'success' }) await Promise.all([this.loadReviewApplications(), this.loadEmployees()]) } catch (error) { - wx.showToast({ title: error.message || '申请状态已变化,请刷新重试', icon: 'none' }) + showErrorToast(error, '申请状态已变化,请刷新重试') await this.loadReviewApplications() } finally { this.setData({ reviewingId: '' }) @@ -292,7 +293,7 @@ Page({ } catch (error) { this.setData({ employees: [], - loadError: error.message || '美甲师列表加载失败' + loadError: toUserMessage(error, '美甲师列表加载失败') }) } }, diff --git a/JC-Salon-WeChat/pages/export/index.js b/JC-Salon-WeChat/pages/export/index.js index dcf6be69..6d1fc727 100644 --- a/JC-Salon-WeChat/pages/export/index.js +++ b/JC-Salon-WeChat/pages/export/index.js @@ -2,6 +2,7 @@ const dateUtil = require('../../utils/date') const planningApi = require('../../api/planning') const customersApi = require('../../api/customers') const employeesApi = require('../../api/employees') +const { toUserMessage } = require('../../utils/toast') const PREVIEW_SIZE = 10 @@ -64,7 +65,7 @@ Page({ } catch (error) { this.setData({ previewRows: [], - previewError: error.message || '预览数据加载失败' + previewError: toUserMessage(error, '预览数据加载失败') }) } finally { this.setData({ previewLoading: false }) diff --git a/JC-Salon-WeChat/pages/legal/index.js b/JC-Salon-WeChat/pages/legal/index.js index b77d000d..5425e8c1 100644 --- a/JC-Salon-WeChat/pages/legal/index.js +++ b/JC-Salon-WeChat/pages/legal/index.js @@ -1,9 +1,18 @@ const authApi = require('../../api/auth') +const auth = require('../../utils/auth') +const request = require('../../utils/request') +const { showErrorToast } = require('../../utils/toast') Page({ - data: { loading: true, agreement: null }, + data: { loading: true, agreement: null, mode: '', agreements: [], accepted: false, accepting: false }, onLoad(options) { + if (options && options.mode === 'accept') { + wx.setNavigationBarTitle({ title: '阅读并同意协议' }) + this.setData({ mode: 'accept' }) + this.loadAll() + return + } this.load(options && options.type) }, @@ -15,9 +24,81 @@ Page({ const agreement = (Array.isArray(agreements) ? agreements : []).find(item => item.agreementType === agreementType) this.setData({ agreement: agreement || null }) } catch (error) { - wx.showToast({ title: error.message || '协议加载失败', icon: 'none' }) + showErrorToast(error, '协议加载失败') } finally { this.setData({ loading: false }) } + }, + + async loadAll() { + this.setData({ loading: true }) + try { + const agreements = await authApi.getCurrentAgreements() + this.setData({ agreements: Array.isArray(agreements) ? agreements : [] }) + } catch (error) { + showErrorToast(error, '协议加载失败') + } finally { + this.setData({ loading: false }) + } + }, + + /** + * 切后台(来电、复制协议文本)只暂停挂起请求的超时计时,绝不结算; + * 回到前台后按剩余可见时长恢复,若挂起请求已不存在则恢复逻辑自动 no-op。 + */ + onHide() { + request.pausePendingAgreementTimeout() + }, + + onShow() { + request.resumePendingAgreementTimeout() + }, + + onUnload() { + this.discardPendingIfNotAccepted() + }, + + /** + * 只有真正离开协议页(返回导致页面卸载)才结算被 4510 挂起的请求,避免调用方 loading 永久卡住; + * 切后台只暂停计时、不结算;同意成功后也不再触发。 + */ + discardPendingIfNotAccepted() { + if (this.data.mode !== 'accept' || this.agreementAccepted) { + return + } + request.discardPendingAgreement() + }, + + toggleAgreement() { + if (this.data.accepting) { + return + } + this.setData({ accepted: !this.data.accepted }) + }, + + async acceptAndContinue() { + if (!this.data.accepted || this.data.accepting) { + return + } + this.setData({ accepting: true }) + try { + await authApi.acceptAgreements('WECHAT_MINI') + this.agreementAccepted = true + wx.showToast({ title: '已同意', icon: 'success' }) + // 同意成功后重放首个被 4510 拦下的请求一次;失败不再循环。 + request.retryPendingAfterAgreement() + setTimeout(() => { + wx.navigateBack({ + fail: () => wx.reLaunch({ url: '/pages/planning/index' }) + }) + }, 300) + } catch (error) { + // accept 返回 401 时请求层已清会话并跳登录页,这里不再叠加提示。 + if (auth.getAccessToken()) { + showErrorToast(error, '同意失败,请重试') + } + } finally { + this.setData({ accepting: false }) + } } }) diff --git a/JC-Salon-WeChat/pages/legal/index.test.js b/JC-Salon-WeChat/pages/legal/index.test.js new file mode 100644 index 00000000..213ed26d --- /dev/null +++ b/JC-Salon-WeChat/pages/legal/index.test.js @@ -0,0 +1,67 @@ +const assert = require('assert') + +let pageDefinition + +global.wx = { + getAccountInfoSync: () => ({ miniProgram: { envVersion: 'develop' } }), + getDeviceInfo: () => ({ platform: 'devtools' }), + getStorageSync: () => undefined, + setStorageSync: () => {}, + removeStorageSync: () => {}, + setNavigationBarTitle: () => {}, + showToast: () => {}, + showModal: () => {}, + navigateBack: () => {}, + navigateTo: () => {}, + redirectTo: () => {}, + reLaunch: () => {}, + request: () => {} +} +global.getApp = () => ({ globalData: {} }) +global.Page = definition => { pageDefinition = definition } + +const requestUtil = require('../../utils/request') +let discardCalls = 0 +let pauseCalls = 0 +let resumeCalls = 0 +requestUtil.discardPendingAgreement = () => { discardCalls += 1 } +requestUtil.pausePendingAgreementTimeout = () => { pauseCalls += 1 } +requestUtil.resumePendingAgreementTimeout = () => { resumeCalls += 1 } + +require('./index') + +function createPage(mode, agreementAccepted = false) { + const page = Object.create(pageDefinition) + page.data = { ...pageDefinition.data, mode } + page.agreementAccepted = agreementAccepted + page.setData = function setData(values) { + Object.assign(this.data, values) + } + return page +} + +const reader = createPage('') +pageDefinition.onUnload.call(reader) +assert.strictEqual(discardCalls, 0) + +// 切后台:只暂停超时计时,绝不结算 +const hiddenPage = createPage('accept') +pageDefinition.onHide.call(hiddenPage) +assert.strictEqual(pauseCalls, 1) +assert.strictEqual(discardCalls, 0) + +// 回到前台:恢复计时(是否真的有挂起由请求层自行判断,页面不重复结算) +pageDefinition.onShow.call(hiddenPage) +assert.strictEqual(resumeCalls, 1) +assert.strictEqual(discardCalls, 0) + +// 真正离开协议页(返回触发页面卸载)仍然结算 +const unloadedPage = createPage('accept') +pageDefinition.onUnload.call(unloadedPage) +assert.strictEqual(discardCalls, 1) + +const acceptedPage = createPage('accept', true) +pageDefinition.onUnload.call(acceptedPage) +assert.strictEqual(discardCalls, 1) + +console.log('legal page agreement lifecycle test passed') diff --git a/JC-Salon-WeChat/pages/legal/index.wxml b/JC-Salon-WeChat/pages/legal/index.wxml index 0af0b193..303daba3 100644 --- a/JC-Salon-WeChat/pages/legal/index.wxml +++ b/JC-Salon-WeChat/pages/legal/index.wxml @@ -1,9 +1,25 @@ - + 正在加载… + + + {{item.title}} + 版本 {{item.version}} + {{item.content}} + + 当前内容暂不可用,请稍后重试。 + {{agreement.title}} 版本 {{agreement.version}} {{agreement.content}} 当前内容暂不可用,请稍后重试。 + + + + {{accepted ? '✓' : ''}} + 我已阅读并同意《用户隐私政策》《用户协议》 + + + diff --git a/JC-Salon-WeChat/pages/legal/index.wxss b/JC-Salon-WeChat/pages/legal/index.wxss index fc225a77..31857ee8 100644 --- a/JC-Salon-WeChat/pages/legal/index.wxss +++ b/JC-Salon-WeChat/pages/legal/index.wxss @@ -1,6 +1,69 @@ .legal-page { padding: 24rpx; } +.legal-page-accept { padding-bottom: calc(220rpx + env(safe-area-inset-bottom)); } .legal-document { padding: 32rpx; } .legal-title { display: block; color: #24332e; font-size: 36rpx; font-weight: 700; } .legal-version { display: block; margin-top: 12rpx; color: #75827d; font-size: 24rpx; } .legal-content { display: block; margin-top: 28rpx; color: #3e4c47; font-size: 28rpx; line-height: 1.9; white-space: pre-wrap; } .legal-state { padding: 80rpx 24rpx; color: #71807a; text-align: center; } + +.legal-action-bar { + position: fixed; + left: 0; + right: 0; + bottom: 0; + padding: 20rpx 24rpx calc(20rpx + env(safe-area-inset-bottom)); + background: #ffffff; + box-shadow: 0 -8rpx 24rpx rgba(36, 51, 46, .08); +} + +.legal-consent { + display: flex; + align-items: center; + min-height: 40rpx; +} + +.legal-check { + display: flex; + align-items: center; + justify-content: center; + width: 28rpx; + height: 28rpx; + flex: none; + margin-right: 10rpx; + border: 2rpx solid #b7bdb9; + border-radius: 7rpx; + color: #ffffff; + font-size: 19rpx; +} + +.legal-check.checked { + border-color: #247b63; + background: #247b63; +} + +.legal-consent-text { + color: #3e4c47; + font-size: 24rpx; + line-height: 1.5; +} + +.legal-accept-button { + margin-top: 16rpx; + height: 92rpx; + border-radius: 999rpx; + background: #247b63; + color: #ffffff; + font-size: 30rpx; + font-weight: 500; + line-height: 92rpx; +} + +.legal-accept-button::after { + border: 0; +} + +.legal-accept-button[disabled] { + background: #247b63; + color: #ffffff; + opacity: .45; +} diff --git a/JC-Salon-WeChat/pages/login/index.js b/JC-Salon-WeChat/pages/login/index.js index fd0112d8..27a5b275 100644 --- a/JC-Salon-WeChat/pages/login/index.js +++ b/JC-Salon-WeChat/pages/login/index.js @@ -3,6 +3,7 @@ const auth = require('../../utils/auth') const { BRAND_CONFIG } = require('../../utils/config') const loginFlow = require('../../utils/login-flow') const { requestSubscribeMessages } = require('../../utils/subscribe-message') +const { showErrorToast, toUserMessage } = require('../../utils/toast') function wxLoginCode() { return new Promise((resolve, reject) => wx.login({ @@ -68,7 +69,7 @@ Page({ const agreements = await authApi.getCurrentAgreements() this.setData({ agreements: Array.isArray(agreements) ? agreements : [] }) } catch (error) { - this.setData({ agreementError: error.message || '协议加载失败' }) + this.setData({ agreementError: toUserMessage(error, '协议加载失败') }) } finally { this.setData({ agreementLoading: false }) } @@ -156,7 +157,7 @@ Page({ this.setData({ loginState: result }) await this.handleResult(result) } catch (error) { - const state = { status: 'ERROR', message: error.message || '快捷登录失败,请重试' } + const state = { status: 'ERROR', message: toUserMessage(error, '快捷登录失败,请重试') } this.setData({ loginState: state }) this.handleResult(state) } finally { @@ -193,7 +194,7 @@ Page({ : status === 'REJECTED' ? '申请需要修改' : status === 'DISABLED' ? '账号暂不可用' : status === 'NEED_MANUAL_LOGIN' ? '需要完成注册' : '登录失败' - const content = result.registrationRejectReason || result.message || '请稍后重试' + const content = result.registrationRejectReason || toUserMessage(result, '请稍后重试') const canRetry = status === 'ERROR' || status === 'NEED_MANUAL_LOGIN' || status === 'REJECTED' wx.showModal({ title, @@ -234,7 +235,7 @@ Page({ if (result.status !== 'SUCCESS' || !result.accessToken) throw new Error(result.message || '进入门店失败') await this.finishLogin(result, true) } catch (error) { - wx.showToast({ title: error.message || '进入门店失败', icon: 'none' }) + showErrorToast(error, '进入门店失败') } finally { this.setData({ switchingShop: false }) } diff --git a/JC-Salon-WeChat/pages/planning/index.js b/JC-Salon-WeChat/pages/planning/index.js index bd3e264e..32baa04d 100644 --- a/JC-Salon-WeChat/pages/planning/index.js +++ b/JC-Salon-WeChat/pages/planning/index.js @@ -6,6 +6,7 @@ const { uploadProfileImage } = require('../../utils/upload') const { normalizeAvatar } = require('../../utils/profile-card') const profileCache = require('../../utils/profile-cache') const employeesApi = require('../../api/employees') +const { showErrorToast, toUserMessage } = require('../../utils/toast') function canCreateAppointment() { const app = getApp() @@ -14,7 +15,7 @@ function canCreateAppointment() { } function resolveCalendarErrorMessage(error) { - return error && error.message ? error.message : '日程数据加载失败' + return toUserMessage(error, '日程数据加载失败') } function toLocalDate(value) { @@ -287,7 +288,7 @@ Page({ 'profileForm.avatarFileId': uploaded && uploaded.fileId ? String(uploaded.fileId) : '' }) } catch (error) { - wx.showToast({ title: error.message || '头像上传失败', icon: 'none' }) + showErrorToast(error, '头像上传失败') } finally { this.setData({ profileSaving: false }) } @@ -313,7 +314,7 @@ Page({ this.setData({ profilePromptVisible: false }) wx.showToast({ title: '资料已保存', duration: 3000 }) } catch (error) { - wx.showToast({ title: error.message || '资料保存失败', icon: 'none', duration: 3000 }) + showErrorToast(error, '资料保存失败', { duration: 3000 }) } finally { this.setData({ profileSaving: false }) } @@ -872,7 +873,7 @@ Page({ wx.showToast({ title: Number(event.currentTarget.dataset.status) === 2 ? '补单已完成' : '预约已确认', icon: 'success' }) this.loadCalendar() } catch (error) { - wx.showToast({ title: error.message || '预约状态更新失败', icon: 'none' }) + showErrorToast(error, '预约状态更新失败') } }, @@ -903,7 +904,7 @@ Page({ wx.showToast({ title: '预约已取消', icon: 'success' }) this.loadCalendar() } catch (error) { - wx.showToast({ title: error.message || '预约取消失败', icon: 'none' }) + showErrorToast(error, '预约取消失败') } } }) diff --git a/JC-Salon-WeChat/pages/profile-edit/index.js b/JC-Salon-WeChat/pages/profile-edit/index.js index ad97a190..2dea052b 100644 --- a/JC-Salon-WeChat/pages/profile-edit/index.js +++ b/JC-Salon-WeChat/pages/profile-edit/index.js @@ -4,6 +4,7 @@ const { chooseImageFilePath, uploadProfileImage } = require('../../utils/upload' const { buildProfileCard, normalizeAvatar } = require('../../utils/profile-card') const { BRAND_CONFIG } = require('../../utils/config') const profileCache = require('../../utils/profile-cache') +const { showErrorToast } = require('../../utils/toast') function resolveRoleText(type) { const role = Number(type) @@ -65,7 +66,7 @@ Page({ const profile = await profileCache.getProfile(options) this.syncProfileToSession(profile) } catch (error) { - wx.showToast({ title: error.message || '个人信息加载失败', icon: 'none' }) + showErrorToast(error, '个人信息加载失败') } finally { this.setData({ loading: false }) } @@ -146,7 +147,7 @@ Page({ if (!filePath) return await this.uploadAvatar(filePath) } catch (error) { - wx.showToast({ title: error.message || '头像上传失败', icon: 'none' }) + showErrorToast(error, '头像上传失败') } }, @@ -159,7 +160,7 @@ Page({ try { await this.uploadAvatar(event.detail && event.detail.avatarUrl) } catch (error) { - wx.showToast({ title: error.message || '微信头像获取失败', icon: 'none' }) + showErrorToast(error, '微信头像获取失败') } }, @@ -190,7 +191,7 @@ Page({ wx.showToast({ title: '已保存', icon: 'success', duration: 3000 }) setTimeout(() => wx.navigateBack(), 350) } catch (error) { - wx.showToast({ title: error.message || '保存失败', icon: 'none', duration: 3000 }) + showErrorToast(error, '保存失败', { duration: 3000 }) } finally { this.setData({ saving: false }) } diff --git a/JC-Salon-WeChat/pages/profile/index.js b/JC-Salon-WeChat/pages/profile/index.js index c1dd3649..aea5edca 100644 --- a/JC-Salon-WeChat/pages/profile/index.js +++ b/JC-Salon-WeChat/pages/profile/index.js @@ -4,6 +4,7 @@ const planningApi = require('../../api/planning') const { buildProfileCard } = require('../../utils/profile-card') const profileCache = require('../../utils/profile-cache') const authApi = require('../../api/auth') +const { showErrorToast } = require('../../utils/toast') function resolveRoleText(type) { const role = Number(type) @@ -62,7 +63,7 @@ Page({ } }) } catch (error) { - wx.showToast({ title: error.message || '今日概览加载失败', icon: 'none' }) + showErrorToast(error, '今日概览加载失败') } finally { this.setData({ overviewLoading: false }) } @@ -113,7 +114,7 @@ Page({ const profile = await profileCache.getProfile() this.syncProfileToSession(profile) } catch (error) { - wx.showToast({ title: error.message || '个人信息加载失败', icon: 'none' }) + showErrorToast(error, '个人信息加载失败') } }, diff --git a/JC-Salon-WeChat/pages/register/index.js b/JC-Salon-WeChat/pages/register/index.js index 5ac24897..679abe47 100644 --- a/JC-Salon-WeChat/pages/register/index.js +++ b/JC-Salon-WeChat/pages/register/index.js @@ -1,4 +1,5 @@ const authApi = require('../../api/auth') +const { showErrorToast, toUserMessage } = require('../../utils/toast') Page({ data: { @@ -53,7 +54,7 @@ Page({ shopSelectorItems: this.filterShops(shopOptions, this.data.shopKeyword) }) } catch (error) { - this.setData({ shopOptions: [], shopSelectorItems: [], shopError: error.message || '门店列表加载失败' }) + this.setData({ shopOptions: [], shopSelectorItems: [], shopError: toUserMessage(error, '门店列表加载失败') }) } finally { this.setData({ shopLoading: false }) } @@ -94,7 +95,7 @@ Page({ const result = await authApi.uploadRegistrationAvatar(this.data.registrationTicket, filePath) this.setData({ 'form.applicantAvatarFileId': result.fileId || result.id, 'form.applicantAvatarUrl': filePath }) } catch (error) { - wx.showToast({ title: error.message || '头像上传失败', icon: 'none' }) + showErrorToast(error, '头像上传失败') } finally { this.setData({ avatarUploading: false }) } @@ -209,7 +210,7 @@ Page({ this.setData({ ticketInvalid: true }) return } - wx.showToast({ title: message, icon: 'none' }) + showErrorToast(error, '提交失败') } finally { this.setData({ loading: false }) } diff --git a/JC-Salon-WeChat/pages/schedule-setting/index.js b/JC-Salon-WeChat/pages/schedule-setting/index.js index e7e0ac04..dd22a53b 100644 --- a/JC-Salon-WeChat/pages/schedule-setting/index.js +++ b/JC-Salon-WeChat/pages/schedule-setting/index.js @@ -1,6 +1,7 @@ const employeesApi = require('../../api/employees') const dateUtil = require('../../utils/date') const { markPlanningRefresh } = require('../../utils/planning-refresh') +const { showErrorToast, toUserMessage } = require('../../utils/toast') const PRESETS = [ { value: 'DOUBLE_REST', label: '双休', workDays: [1, 2, 3, 4, 5], startTime: '09:00', endTime: '17:00' }, @@ -137,7 +138,7 @@ Page({ })) }) } catch (error) { - wx.showToast({ title: error.message || '排班规则加载失败', icon: 'none' }) + showErrorToast(error, '排班规则加载失败') } finally { this.setData({ loading: false }) } @@ -252,7 +253,7 @@ Page({ await this.loadRule() } } catch (error) { - const message = error.message || '保存失败' + const message = toUserMessage(error, '保存失败') wx.showModal({ title: '排班保存失败', content: message, showCancel: false, confirmText: '知道了' }) } finally { this.setData({ saving: false }) @@ -283,7 +284,7 @@ Page({ wx.showToast({ title: '例外已保存', icon: 'success' }) await this.loadRule() } catch (error) { - const message = error.message || '例外保存失败' + const message = toUserMessage(error, '例外保存失败') wx.showModal({ title: '特殊日期保存失败', content: message, showCancel: false, confirmText: '知道了' }) } finally { this.setData({ saving: false }) diff --git a/JC-Salon-WeChat/pages/shop-settings/index.js b/JC-Salon-WeChat/pages/shop-settings/index.js index b89de91c..9af58551 100644 --- a/JC-Salon-WeChat/pages/shop-settings/index.js +++ b/JC-Salon-WeChat/pages/shop-settings/index.js @@ -1,6 +1,7 @@ const { BRAND_CONFIG } = require('../../utils/config') const profileCache = require('../../utils/profile-cache') const shopApi = require('../../api/shop') +const { showErrorToast, toUserMessage } = require('../../utils/toast') function resolveNameStatus(value) { const status = String(value || '').toUpperCase() @@ -95,7 +96,7 @@ Page({ }) } catch (error) { this.setData({ - settingsError: error.message || '设置加载失败', + settingsError: toUserMessage(error, '设置加载失败'), businessHoursConfigured: false, 'form.weeklyHours': [] }) @@ -139,7 +140,7 @@ Page({ this.setData({ businessHoursConfigured: normalizedHours.some(day => day.open) }) wx.showToast({ title: '预约设置已生效', icon: 'success' }) } catch (error) { - wx.showToast({ title: error.message || '保存失败,请重试', icon: 'none' }) + showErrorToast(error, '保存失败,请重试') } finally { this.setData({ settingsSaving: false }) } @@ -157,7 +158,7 @@ Page({ wx.showToast({ title: '店铺名称已提交审核', icon: 'success' }) await this.loadProfileAndSettings({ force: true }) } catch (error) { - wx.showToast({ title: error.message || '提交审核失败', icon: 'none' }) + showErrorToast(error, '提交审核失败') } finally { this.setData({ nameSaving: false }) } diff --git a/JC-Salon-WeChat/utils/request.js b/JC-Salon-WeChat/utils/request.js index 1fd07145..2cc4ac43 100644 --- a/JC-Salon-WeChat/utils/request.js +++ b/JC-Salon-WeChat/utils/request.js @@ -7,6 +7,30 @@ const HEADER_NONCE = 'X-Nonce' const HEADER_SIGNATURE = 'X-Signature' const HEADER_SIGNATURE_VERSION = 'X-Sign-Version' +/** + * 服务端协议同意拦截返回的业务码:登录用户未同意最新版协议时返回 4510。 + */ +const AGREEMENT_VERSION_REQUIRED_CODE = 4510 +/** 挂起请求被放弃时的自定义错误码,调用方据此区分“未完成协议同意”与普通业务失败。 */ +const AGREEMENT_NOT_ACCEPTED_CODE = 'AGREEMENT_NOT_ACCEPTED' +const AGREEMENT_NOT_ACCEPTED_MESSAGE = '未完成协议同意' +/** 面向用户的友好文案:内部错误码与文案保持技术语义,展示层统一经 resolveUserMessage 转换。 */ +const AGREEMENT_NOT_ACCEPTED_USER_MESSAGE = '协议未确认,请稍后重试' +/** + * 挂起请求最长等待时间(3 分钟),只作为“避免页面 loading 永久卡死”的兜底。 + * 用户阅读两份协议可能耗时较久,不能因为超时提前判定操作失败; + * 超时结算后不再自动重放该请求,但用户稍后再同意协议仍会正常记录同意, + * 只是原请求需要用户重新发起。 + */ +const AGREEMENT_PENDING_TIMEOUT_MS = 180000 +const AGREEMENT_PAGE_URL = '/pages/legal/index?mode=accept' +/** + * 一屏多个请求同时命中 4510 时只允许弹一次弹窗; + * 首个被拦下的请求挂起等待用户在协议页同意后重放,新的 4510 会先结算旧的挂起请求。 + */ +let agreementPromptVisible = false +let agreementBlockedRequest = null + function buildUrl(url, params) { const sourceParams = params || {} const baseUrl = sourceParams.__baseUrl ? sourceParams.__baseUrl : API_DOMAIN @@ -43,6 +67,9 @@ function redirectToLoginAfterExpired(message) { if (!auth.beginSessionExpiredHandling()) { return } + // 真正的登录失效才清会话;同时丢弃协议重试目标,避免把旧会话的请求带到新会话。 + agreementBlockedRequest = null + agreementPromptVisible = false clearRuntimeSession() wx.showToast({ title: message, @@ -65,6 +92,234 @@ function handleUnauthorized(response, url) { return normalizeError(message, response) } +function cloneRequestOptions(options) { + return { + url: options.url, + method: options.method, + data: options.data, + params: options.params, + header: options.header, + timeout: options.timeout + } +} + +function createAgreementNotAcceptedError(raw) { + const error = normalizeError(AGREEMENT_NOT_ACCEPTED_MESSAGE, raw) + error.code = AGREEMENT_NOT_ACCEPTED_CODE + return error +} + +/** + * 集中把内部错误文案映射成可直接展示给用户的文案,避免各页面自行硬编码。 + * AGREEMENT_NOT_ACCEPTED 的内部语义保持“未完成协议同意”,展示为“协议未确认,请稍后重试”。 + */ +function resolveUserMessage(error, fallbackMessage) { + if (error && error.code === AGREEMENT_NOT_ACCEPTED_CODE) { + return AGREEMENT_NOT_ACCEPTED_USER_MESSAGE + } + return (error && error.message) || fallbackMessage +} + +/** + * 创建挂起请求容器:保证 resolve/reject 各只生效一次,并携带 3 分钟兜底定时器。 + * 结算或开始重放时统一清理引用与定时器,避免内存泄漏和后续误重放。 + */ +function createBlockedAgreementRequest(options, resolve, reject) { + const entry = { + options: cloneRequestOptions(options), + settled: false, + retrying: false, + timer: null, + startedAt: null, + remainingMs: AGREEMENT_PENDING_TIMEOUT_MS + } + const cleanup = () => { + if (entry.timer) { + clearTimeout(entry.timer) + entry.timer = null + } + entry.startedAt = null + if (agreementBlockedRequest === entry) { + agreementBlockedRequest = null + } + } + /** + * 启动(或恢复)超时兜底计时;已结算、已开始重放或计时已在运行时为 no-op, + * 保证同一请求不会被重复计时或二次结算。 + */ + entry.startTimer = delay => { + if (entry.settled || entry.retrying || entry.timer) { + return + } + entry.remainingMs = delay + entry.startedAt = Date.now() + entry.timer = setTimeout(() => { + entry.timer = null + entry.startedAt = null + entry.rejectNotAccepted() + }, delay) + } + /** + * 切后台时暂停计时:清除定时器并记下剩余可见时长,后台期间不会触发结算。 + */ + entry.pauseTimer = () => { + if (!entry.timer) { + return + } + const elapsed = Date.now() - entry.startedAt + entry.remainingMs = Math.max(0, entry.remainingMs - elapsed) + clearTimeout(entry.timer) + entry.timer = null + entry.startedAt = null + } + /** + * 回到前台按剩余时间恢复计时;挂起请求已被结算/已取走重放时为 no-op。 + */ + entry.resumeTimer = () => { + if (entry.settled || entry.retrying || entry.timer) { + return + } + entry.startTimer(entry.remainingMs) + } + entry.resolveOnce = value => { + if (entry.settled) { + return + } + entry.settled = true + cleanup() + resolve(value) + } + entry.rejectNotAccepted = raw => { + if (entry.settled) { + return + } + entry.settled = true + cleanup() + reject(createAgreementNotAcceptedError(raw)) + } + entry.rejectOriginal = error => { + if (entry.settled) { + return + } + entry.settled = true + cleanup() + reject(error) + } + entry.takeForRetry = () => { + if (entry.settled || entry.retrying) { + return null + } + entry.retrying = true + cleanup() + return Object.assign(cloneRequestOptions(entry.options), { _agreementRetry: 1 }) + } + entry.startTimer(AGREEMENT_PENDING_TIMEOUT_MS) + return entry +} + +/** + * 处理 4510:不清会话,弹窗引导用户去协议页同意。 + * 新 4510 到来时先按“未完成协议同意”结算旧的挂起请求,避免堆积多个 pending。 + */ +function handleAgreementVersionRequired(response, options, resolve, reject) { + const message = resolveResponseMessage(response, '用户协议与隐私政策已更新,请阅读并同意后继续使用') + if (isAuthFreePath(options.url) || Number(options._agreementRetry) > 0) { + reject(normalizeError(message, response)) + return + } + + if (agreementBlockedRequest) { + agreementBlockedRequest.rejectNotAccepted(response) + } + agreementBlockedRequest = createBlockedAgreementRequest(options, resolve, reject) + + if (agreementPromptVisible) { + return + } + agreementPromptVisible = true + wx.showModal({ + title: '协议版本已更新', + content: message, + confirmText: '查看并同意', + cancelText: '稍后', + success(result) { + agreementPromptVisible = false + if (result && result.confirm) { + wx.navigateTo({ + url: AGREEMENT_PAGE_URL, + fail: () => wx.redirectTo({ url: AGREEMENT_PAGE_URL }) + }) + return + } + // 稍后:停留当前页,只给轻提示,不清会话;挂起请求走同一条“未同意”出口。 + wx.showToast({ + title: '请先同意最新协议后再操作', + icon: 'none' + }) + discardPendingAgreement() + }, + fail() { + agreementPromptVisible = false + discardPendingAgreement() + } + }) +} + +/** + * 放弃当前挂起请求:用于“稍后”以及真正离开协议页(返回触发页面卸载), + * 统一按“未完成协议同意”结算;切后台(onHide)不触发结算。 + */ +function discardPendingAgreement() { + const blocked = agreementBlockedRequest + if (!blocked) { + return + } + blocked.rejectNotAccepted() +} + +/** + * 协议页切后台时调用:暂停挂起请求的超时计时,后台期间不会触发结算。 + * 挂起请求已不存在(已结算/已取走重放)时为 no-op。 + */ +function pausePendingAgreementTimeout() { + const blocked = agreementBlockedRequest + if (!blocked) { + return + } + blocked.pauseTimer() +} + +/** + * 协议页回到前台时调用:按剩余可见时长恢复计时。 + * 挂起请求已不存在(例如后台期间已在别处完成同意、或被新的 4510 结算)时为 no-op, + * 不会重复计时或二次结算。 + */ +function resumePendingAgreementTimeout() { + const blocked = agreementBlockedRequest + if (!blocked) { + return + } + blocked.resumeTimer() +} + +/** + * 用户在协议页同意成功后调用:重放首个被 4510 拦下的原请求一次。 + * 取走待重放请求时即清理定时器与挂起引用,后续返回/超时不会打断已开始的成功重放; + * 重放会重新生成签名头(nonce/签名),不复用旧请求的一次性头; + * 若重放仍失败(包括再次 4510),直接把结果交回原调用方,不再弹窗、不再重试。 + */ +function retryPendingAfterAgreement() { + const blocked = agreementBlockedRequest + if (!blocked) { + return + } + const options = blocked.takeForRetry() + if (!options) { + return + } + request(options).then(blocked.resolveOnce, blocked.rejectOriginal) +} + function extractPath(value) { const target = String(value || '') if (!target) { @@ -174,6 +429,10 @@ function request(options) { resolve(payload.data) return } + if (Number(payload.code) === AGREEMENT_VERSION_REQUIRED_CODE) { + handleAgreementVersionRequired({ data: payload }, options, resolve, reject) + return + } if (Number(payload.code) === 401) { reject(handleUnauthorized({ data: payload }, options.url)) return @@ -193,5 +452,11 @@ function request(options) { request.buildSignatureHeaders = buildSignatureHeaders request.toBackendRequestPath = toBackendRequestPath request.handleUnauthorized = handleUnauthorized +request.retryPendingAfterAgreement = retryPendingAfterAgreement +request.discardPendingAgreement = discardPendingAgreement +request.pausePendingAgreementTimeout = pausePendingAgreementTimeout +request.resumePendingAgreementTimeout = resumePendingAgreementTimeout +request.resolveUserMessage = resolveUserMessage +request.AGREEMENT_NOT_ACCEPTED_CODE = AGREEMENT_NOT_ACCEPTED_CODE module.exports = request diff --git a/JC-Salon-WeChat/utils/request.test.js b/JC-Salon-WeChat/utils/request.test.js index abfafdac..f5a037ca 100644 --- a/JC-Salon-WeChat/utils/request.test.js +++ b/JC-Salon-WeChat/utils/request.test.js @@ -3,7 +3,10 @@ const assert = require('assert') const storage = {} const requests = [] const navigations = [] +const navigateToPages = [] const scheduled = [] +const modals = [] +const toasts = [] let clearedSessions = 0 let globalData = { wechatLoginState: { status: 'SUCCESS', accessToken: 'expired-token' } } @@ -14,8 +17,11 @@ global.wx = { setStorageSync: (key, value) => { storage[key] = value }, removeStorageSync: key => { delete storage[key] }, request: options => requests.push(options), - showToast: () => {}, - reLaunch: options => navigations.push(options.url) + showToast: options => toasts.push(options), + showModal: options => modals.push(options), + reLaunch: options => navigations.push(options.url), + navigateTo: options => navigateToPages.push(options.url), + redirectTo: options => navigateToPages.push(options.url) } global.getApp = () => ({ globalData, @@ -25,26 +31,69 @@ global.getApp = () => ({ globalData.wechatLoginState = null } }) -global.setTimeout = callback => { - scheduled.push(callback) - return scheduled.length +global.setTimeout = (callback, delay) => { + const entry = { callback, delay: Number(delay) || 0, cleared: false } + scheduled.push(entry) + return entry } +global.clearTimeout = entry => { + if (entry) { + entry.cleared = true + } +} +// 可控时钟:用于验证“切后台暂停 / 回前台按剩余时间恢复”的可见时长累计。 +const clock = { now: 1700000000000 } +Date.now = () => clock.now const auth = require('./auth') const request = require('./request') +const AGREEMENT_NOT_ACCEPTED_CODE = request.AGREEMENT_NOT_ACCEPTED_CODE + +function respondLatest(statusCode, data) { + requests[requests.length - 1].success({ statusCode, data }) +} + +function resolveWithData(data) { + respondLatest(200, { code: 200, data }) +} + +function pendingTimers(delay) { + return scheduled.filter(item => !item.cleared && item.delay === delay) +} + +function runTimer(delay) { + const entry = pendingTimers(delay).shift() + if (!entry) { + throw new Error(`No pending timer for ${delay}ms`) + } + entry.cleared = true + entry.callback() +} + +function startRequest(options) { + return { promise: request(options) } +} + +function trackSettlement(promise) { + const state = { settled: false } + promise.then(() => { state.settled = true }, () => { state.settled = true }) + return state +} async function rejectWithUnauthorized(options) { const pending = request(options).then( () => { throw new Error('Expected request to reject') }, error => error ) - requests[requests.length - 1].success({ - statusCode: 401, - data: { message: '登录已过期,请重新登录' } - }) + respondLatest(401, { message: '登录已过期,请重新登录' }) return pending } +function assertAgreementPendingError(error) { + assert.strictEqual(error.code, AGREEMENT_NOT_ACCEPTED_CODE) + assert.strictEqual(error.message, '未完成协议同意') +} + async function run() { auth.setSession({ accessToken: 'expired-token' }, true) @@ -56,20 +105,210 @@ async function run() { await rejectWithUnauthorized({ url: '/manager/calendar' }) assert.strictEqual(clearedSessions, 1) assert.strictEqual(globalData.wechatLoginState, null) - assert.strictEqual(scheduled.length, 1) - scheduled.shift()() + assert.strictEqual(pendingTimers(700).length, 1) + runTimer(700) assert.deepStrictEqual(navigations, ['/pages/login/index']) await rejectWithUnauthorized({ url: '/manager/customers' }) assert.strictEqual(clearedSessions, 1) + assert.strictEqual(pendingTimers(700).length, 0) assert.deepStrictEqual(navigations, ['/pages/login/index']) auth.setSession({ accessToken: 'new-login-token' }, true) await rejectWithUnauthorized({ url: '/manager/calendar' }) assert.strictEqual(clearedSessions, 2) - assert.strictEqual(scheduled.length, 1) - scheduled.shift()() + assert.strictEqual(pendingTimers(700).length, 1) + runTimer(700) assert.deepStrictEqual(navigations, ['/pages/login/index', '/pages/login/index']) + + const agreementMessage = '用户协议与隐私政策已更新(当前版本 2026.11.04-R2),请阅读并同意后继续使用' + auth.setSession({ accessToken: 'agreement-token' }, true) + const blocked = startRequest({ url: '/manager/orders', method: 'POST', data: { page: 1 } }) + const originalNonce = requests[requests.length - 1].header['X-Nonce'] + respondLatest(200, { code: 4510, message: agreementMessage }) + + // 4510 不清会话、不跳登录页,只弹一次弹窗,并挂起 3 分钟兜底定时器(30 秒内不会因超时结算) + assert.strictEqual(clearedSessions, 2) + assert.deepStrictEqual(navigations, ['/pages/login/index', '/pages/login/index']) + assert.strictEqual(modals.length, 1) + assert.strictEqual(modals[0].confirmText, '查看并同意') + assert.strictEqual(modals[0].cancelText, '稍后') + assert.strictEqual(modals[0].content, agreementMessage) + assert.strictEqual(pendingTimers(180000).length, 1) + // 超时已放宽到 3 分钟,不再存在 30 秒定时器;切后台(onHide)不会额外结算, + // 因此 30 秒内无论用户是否切后台,挂起请求都保持 pending。 + assert.strictEqual(pendingTimers(30000).length, 0) + + // 查看并同意:进入协议页,挂起期间定时器仍在跑 + modals[0].success({ confirm: true, cancel: false }) + assert.deepStrictEqual(navigateToPages, ['/pages/legal/index?mode=accept']) + assert.strictEqual(clearedSessions, 2) + assert.strictEqual(pendingTimers(180000).length, 1) + + // 同意后自动重放首个被拦请求一次:取走时清定时器、重新生成 nonce,原调用方无感 + const requestsBeforeRetry = requests.length + request.retryPendingAfterAgreement() + assert.strictEqual(requests.length, requestsBeforeRetry + 1) + assert.strictEqual(pendingTimers(180000).length, 0) + const retriedRequest = requests[requests.length - 1] + assert.strictEqual(retriedRequest.url.includes('/manager/orders'), true) + assert.deepStrictEqual(retriedRequest.data, { page: 1 }) + assert.notStrictEqual(retriedRequest.header['X-Nonce'], originalNonce) + resolveWithData({ page: 1, items: [] }) + const retriedValue = await blocked.promise + assert.deepStrictEqual(retriedValue, { page: 1, items: [] }) + + // 已成功结算后,重复 discard/retry 不再产生请求,也不会二次结算 + request.discardPendingAgreement() + const requestsAfterSettled = requests.length + request.retryPendingAfterAgreement() + assert.strictEqual(requests.length, requestsAfterSettled) + assert.deepStrictEqual(await blocked.promise, { page: 1, items: [] }) + assert.strictEqual(modals.length, 1) + + // 新的 4510 到来:旧的挂起请求先按“未完成协议同意”结算,新请求成为待重放目标 + auth.setSession({ accessToken: 'replace-token' }, true) + const oldRequest = startRequest({ url: '/manager/orders', method: 'POST', data: { page: 2 } }) + respondLatest(200, { code: 4510, message: agreementMessage }) + assert.strictEqual(modals.length, 2) + const oldErrorPromise = oldRequest.promise.catch(error => error) + assert.strictEqual(pendingTimers(180000).length, 1) + + const newRequest = startRequest({ url: '/manager/customers', method: 'POST', data: { page: 3 } }) + respondLatest(200, { code: 4510, message: agreementMessage }) + assert.strictEqual(modals.length, 2) + const oldError = await oldErrorPromise + assertAgreementPendingError(oldError) + assert.strictEqual(pendingTimers(180000).length, 1) + + modals[1].success({ confirm: true, cancel: false }) + assert.strictEqual(navigateToPages.length, 2) + const requestsBeforeReplaceRetry = requests.length + request.retryPendingAfterAgreement() + assert.strictEqual(requests.length, requestsBeforeReplaceRetry + 1) + const replaceRetry = requests[requests.length - 1] + assert.strictEqual(replaceRetry.url.includes('/manager/customers'), true) + assert.deepStrictEqual(replaceRetry.data, { page: 3 }) + resolveWithData({ page: 3, items: [] }) + const newValue = await newRequest.promise + assert.deepStrictEqual(newValue, { page: 3, items: [] }) + + // 协议页返回未同意:丢弃挂起请求并清理定时器,之后不会误重放 + auth.setSession({ accessToken: 'back-token' }, true) + const backRequest = startRequest({ url: '/manager/orders', method: 'POST', data: { page: 4 } }) + respondLatest(200, { code: 4510, message: agreementMessage }) + assert.strictEqual(modals.length, 3) + const backErrorPromise = backRequest.promise.catch(error => error) + modals[2].success({ confirm: true, cancel: false }) + assert.strictEqual(pendingTimers(180000).length, 1) + request.discardPendingAgreement() + const backError = await backErrorPromise + assertAgreementPendingError(backError) + assert.strictEqual(pendingTimers(180000).length, 0) + const requestsBeforeBackRetry = requests.length + request.retryPendingAfterAgreement() + assert.strictEqual(requests.length, requestsBeforeBackRetry) + + // 3 分钟超时兜底:只有真的超时才会 reject;超时后用户再同意只记录同意,不再自动重放 + auth.setSession({ accessToken: 'timeout-token' }, true) + const timedRequest = startRequest({ url: '/manager/orders', method: 'POST', data: { page: 5 } }) + respondLatest(200, { code: 4510, message: agreementMessage }) + assert.strictEqual(modals.length, 4) + const timedErrorPromise = timedRequest.promise.catch(error => error) + assert.strictEqual(pendingTimers(180000).length, 1) + // 3 分钟以内不结算:模拟用户在协议页停留/切后台 30 秒,仍有 2 分 30 秒余量。 + assert.strictEqual(pendingTimers(30000).length, 0) + runTimer(180000) + const timedError = await timedErrorPromise + assertAgreementPendingError(timedError) + assert.strictEqual(pendingTimers(180000).length, 0) + modals[3].success({ confirm: true, cancel: false }) + const requestsBeforeTimeoutConfirm = requests.length + request.retryPendingAfterAgreement() + assert.strictEqual(requests.length, requestsBeforeTimeoutConfirm) + + // 稍后:统一走“未完成协议同意”出口,只轻提示,不清会话 + auth.setSession({ accessToken: 'later-token' }, true) + const laterRequest = startRequest({ url: '/manager/orders', method: 'POST', data: { page: 6 } }) + respondLatest(200, { code: 4510, message: agreementMessage }) + assert.strictEqual(modals.length, 5) + const laterPromise = laterRequest.promise.catch(error => error) + modals[4].success({ confirm: false, cancel: true }) + const laterError = await laterPromise + assertAgreementPendingError(laterError) + assert.strictEqual(toasts[toasts.length - 1].title, '请先同意最新协议后再操作') + assert.strictEqual(pendingTimers(180000).length, 0) + assert.strictEqual(clearedSessions, 2) + assert.deepStrictEqual(navigations, ['/pages/login/index', '/pages/login/index']) + + // accept 返回 401(token 确实过期)才允许清会话并跳登录页 + auth.setSession({ accessToken: 'almost-expired-token' }, true) + await rejectWithUnauthorized({ url: '/legal-agreement/accept', method: 'POST' }) + assert.strictEqual(clearedSessions, 3) + assert.strictEqual(pendingTimers(700).length, 1) + runTimer(700) + assert.deepStrictEqual(navigations, ['/pages/login/index', '/pages/login/index', '/pages/login/index']) + + // 文案映射:内部错误 message 保持技术语义,展示层由公共提示工具统一映射为用户友好文案 + const mappedError = new Error('x') + mappedError.code = AGREEMENT_NOT_ACCEPTED_CODE + assert.strictEqual(mappedError.code, 'AGREEMENT_NOT_ACCEPTED') + assert.strictEqual(request.resolveUserMessage(mappedError, '兜底文案'), '协议未确认,请稍后重试') + assert.strictEqual(request.resolveUserMessage(new Error('业务失败'), '兜底文案'), '业务失败') + assert.strictEqual(request.resolveUserMessage(null, '兜底文案'), '兜底文案') + const { showErrorToast, toUserMessage } = require('./toast') + showErrorToast(mappedError, '兜底文案') + assert.strictEqual(toasts[toasts.length - 1].title, '协议未确认,请稍后重试') + assert.strictEqual(toasts[toasts.length - 1].icon, 'none') + // 内联错误态 / 弹窗等非 toast 出口复用同一映射 + assert.strictEqual(toUserMessage(mappedError, '兜底文案'), '协议未确认,请稍后重试') + assert.strictEqual(toUserMessage(new Error('业务失败'), '兜底文案'), '业务失败') + + // 切后台暂停:后台 2 分钟不计入可见时长,后台期间到点也不结算 + auth.setSession({ accessToken: 'pause-token' }, true) + const pausedRequest = startRequest({ url: '/manager/orders', method: 'POST', data: { page: 6 } }) + respondLatest(200, { code: 4510, message: agreementMessage }) + const pausedState = trackSettlement(pausedRequest.promise) + assert.strictEqual(pendingTimers(180000).length, 1) + + clock.now += 120000 + request.pausePendingAgreementTimeout() + assert.strictEqual(pendingTimers(180000).length, 0) + // 后台再停留 2 分钟(累计后台 4 分钟):没有定时器,绝不会结算 + clock.now += 120000 + await Promise.resolve() + assert.strictEqual(pausedState.settled, false) + + // 回前台按剩余 1 分钟恢复;可见时长累计 2 分钟 + 59 秒仍未满 3 分钟,不结算 + request.resumePendingAgreementTimeout() + assert.strictEqual(pendingTimers(60000).length, 1) + clock.now += 59000 + await Promise.resolve() + assert.strictEqual(pausedState.settled, false) + // 可见时长走满 3 分钟后,兜底定时器触发结算 + runTimer(60000) + const pausedError = await pausedRequest.promise.catch(error => error) + assertAgreementPendingError(pausedError) + + // 回前台时挂起已不存在(已超时结算):恢复计时为 no-op,不报错、不新增定时器 + request.resumePendingAgreementTimeout() + assert.strictEqual(pendingTimers(60000).length, 0) + assert.strictEqual(pendingTimers(180000).length, 0) + + // 后台期间从别处完成同意:挂起已被取走重放,回前台的恢复计时同样为 no-op + auth.setSession({ accessToken: 'resume-after-agree-token' }, true) + const agreedRequest = startRequest({ url: '/manager/orders', method: 'POST', data: { page: 7 } }) + respondLatest(200, { code: 4510, message: agreementMessage }) + request.pausePendingAgreementTimeout() + assert.strictEqual(pendingTimers(180000).length, 0) + const requestsBeforeAgreeRetry = requests.length + request.retryPendingAfterAgreement() + assert.strictEqual(requests.length, requestsBeforeAgreeRetry + 1) + resolveWithData({ page: 7, items: [] }) + assert.deepStrictEqual(await agreedRequest.promise, { page: 7, items: [] }) + request.resumePendingAgreementTimeout() + assert.strictEqual(pendingTimers(180000).length, 0) + assert.strictEqual(pendingTimers(60000).length, 0) } run().catch(error => { diff --git a/JC-Salon-WeChat/utils/toast.js b/JC-Salon-WeChat/utils/toast.js new file mode 100644 index 00000000..936ea620 --- /dev/null +++ b/JC-Salon-WeChat/utils/toast.js @@ -0,0 +1,25 @@ +const request = require('./request') + +/** + * 统一的错误提示入口:页面只调用这里 toast 请求错误。 + * 内部技术文案(如 AGREEMENT_NOT_ACCEPTED)在此集中映射为用户可读文案, + * 避免各个页面各自硬编码一段映射逻辑。 + */ +function showErrorToast(error, fallbackMessage, options) { + wx.showToast(Object.assign({ + title: request.resolveUserMessage(error, fallbackMessage), + icon: 'none' + }, options || {})) +} + +/** + * 内联错误态、弹窗等非 toast 展示出口共用同一套映射,避免技术文案漏到用户眼前。 + */ +function toUserMessage(error, fallbackMessage) { + return request.resolveUserMessage(error, fallbackMessage) +} + +module.exports = { + showErrorToast, + toUserMessage +} diff --git a/nacos/namespaces/dev/jayucloud-artlist/DEFAULT_GROUP/core.yaml b/nacos/namespaces/dev/jayucloud-artlist/DEFAULT_GROUP/core.yaml index 075434e6..ee068974 100644 --- a/nacos/namespaces/dev/jayucloud-artlist/DEFAULT_GROUP/core.yaml +++ b/nacos/namespaces/dev/jayucloud-artlist/DEFAULT_GROUP/core.yaml @@ -66,6 +66,14 @@ jayucloud-artlist: order-create: limit: 10 window-seconds: 60 + contact-info-read: + limit: 30 + window-seconds: 60 + contact-dial: + limit: 10 + window-seconds: 60 + dial: + provider: direct cache: local-max-size: 2048 product-detail: diff --git a/nacos/namespaces/dev/jayucloud-artlist/DEFAULT_GROUP/secret.yaml b/nacos/namespaces/dev/jayucloud-artlist/DEFAULT_GROUP/secret.yaml index 69e8c1a2..a8bbcffb 100644 --- a/nacos/namespaces/dev/jayucloud-artlist/DEFAULT_GROUP/secret.yaml +++ b/nacos/namespaces/dev/jayucloud-artlist/DEFAULT_GROUP/secret.yaml @@ -27,3 +27,10 @@ aliyun: oss: access-key-id: LTAI5t9divmxMWHiKhLSRdDd access-key-secret: U4BlsNpy7ISLbWYrQUsBMswaRH8G9Q + +# 手机号加密:与 jayucloud-salon 同环境的密钥保持一致,保证 phone_hash 可跨业务线比对。 +jayucloud-artlist: + privacy: + phone-crypto: + encryption-key: "Y+Y5vAG/yUVDEvEQ3L5IQOO1ZFsbJp6l4wvrNR69mKM=" + index-key: "4/wLgcudBE8XNVBjnUle1A2H1L0ePV0rKUbX3VFeAzU=" diff --git a/nacos/namespaces/dev/jayucloud-salon/DEFAULT_GROUP/core.yaml b/nacos/namespaces/dev/jayucloud-salon/DEFAULT_GROUP/core.yaml index 5f789af5..b6fb9761 100644 --- a/nacos/namespaces/dev/jayucloud-salon/DEFAULT_GROUP/core.yaml +++ b/nacos/namespaces/dev/jayucloud-salon/DEFAULT_GROUP/core.yaml @@ -38,6 +38,9 @@ mybatis: map-underscore-to-camel-case: true jayucloud-salon: + deploy: + # 部署环境标识,用于微信内容审核回调的跨环境路由;缺失时 Core 启动失败 + env: dev wechat: mini: app-id: wxb6d77f7c07020d51 @@ -51,6 +54,9 @@ jayucloud-salon: brand: message-template-name: JayuCloud-Salon manager-register-shop-description: 甲屿店务注册店铺 + dial: + # direct:直拨真实号码;privacy-number:隐私号码(未对接时明确报错,绝不回退真实号码) + provider: direct privacy: content-moderation: # 仅 DEV 允许在后台设置中使用本地模拟审核;SIT/PROD 继续失败关闭。 @@ -87,6 +93,9 @@ jayucloud-salon: order-create: limit: 10 window-seconds: 60 + customer-dial: + limit: 10 + window-seconds: 60 cache: local-max-size: 2048 product-detail: diff --git a/nacos/namespaces/prod/jayucloud-artlist/DEFAULT_GROUP/core.yaml b/nacos/namespaces/prod/jayucloud-artlist/DEFAULT_GROUP/core.yaml index 63ba85fa..a7e24c06 100644 --- a/nacos/namespaces/prod/jayucloud-artlist/DEFAULT_GROUP/core.yaml +++ b/nacos/namespaces/prod/jayucloud-artlist/DEFAULT_GROUP/core.yaml @@ -66,6 +66,14 @@ jayucloud-artlist: order-create: limit: 10 window-seconds: 60 + contact-info-read: + limit: 30 + window-seconds: 60 + contact-dial: + limit: 10 + window-seconds: 60 + dial: + provider: direct cache: local-max-size: 2048 product-detail: diff --git a/nacos/namespaces/prod/jayucloud-artlist/DEFAULT_GROUP/secret.yaml b/nacos/namespaces/prod/jayucloud-artlist/DEFAULT_GROUP/secret.yaml index 69e8c1a2..643d8794 100644 --- a/nacos/namespaces/prod/jayucloud-artlist/DEFAULT_GROUP/secret.yaml +++ b/nacos/namespaces/prod/jayucloud-artlist/DEFAULT_GROUP/secret.yaml @@ -27,3 +27,11 @@ aliyun: oss: access-key-id: LTAI5t9divmxMWHiKhLSRdDd access-key-secret: U4BlsNpy7ISLbWYrQUsBMswaRH8G9Q + +# 手机号加密:与 jayucloud-salon 同环境的密钥保持一致,保证 phone_hash 可跨业务线比对。 +# 生产密钥沿用 jayucloud-salon 生产配置;如需独立轮换,必须两条线同步替换 index-key,否则 hash 不可比对。 +jayucloud-artlist: + privacy: + phone-crypto: + encryption-key: "zelWItNk7yyDA/LGkq4+Mqo0IOyBzAUmgyR4qLL1htw=" + index-key: "01lUBIigsJL/GW/SeYLigYC4ngiY9ntknX+ScDeuNzQ=" diff --git a/nacos/namespaces/prod/jayucloud-salon/DEFAULT_GROUP/core.yaml b/nacos/namespaces/prod/jayucloud-salon/DEFAULT_GROUP/core.yaml index deb8140e..994885d0 100644 --- a/nacos/namespaces/prod/jayucloud-salon/DEFAULT_GROUP/core.yaml +++ b/nacos/namespaces/prod/jayucloud-salon/DEFAULT_GROUP/core.yaml @@ -37,6 +37,9 @@ mybatis: map-underscore-to-camel-case: true jayucloud-salon: + deploy: + # 部署环境标识,用于微信内容审核回调的跨环境路由;缺失时 Core 启动失败 + env: prod wechat: mini: app-id: wxb6d77f7c07020d51 @@ -50,6 +53,9 @@ jayucloud-salon: brand: message-template-name: JayuCloud-Salon manager-register-shop-description: 甲屿店务注册店铺 + dial: + # direct:直拨真实号码;privacy-number:隐私号码(未对接时明确报错,绝不回退真实号码) + provider: direct privacy: content-moderation: # 微信审核平台接入前失败关闭,内容进入隔离/人工复核,不自动放行。 @@ -87,6 +93,9 @@ jayucloud-salon: order-create: limit: 10 window-seconds: 60 + customer-dial: + limit: 10 + window-seconds: 60 cache: local-max-size: 2048 product-detail: diff --git a/nacos/namespaces/sit/jayucloud-artlist/DEFAULT_GROUP/core.yaml b/nacos/namespaces/sit/jayucloud-artlist/DEFAULT_GROUP/core.yaml index 944cd2bd..15c130fd 100644 --- a/nacos/namespaces/sit/jayucloud-artlist/DEFAULT_GROUP/core.yaml +++ b/nacos/namespaces/sit/jayucloud-artlist/DEFAULT_GROUP/core.yaml @@ -66,6 +66,14 @@ jayucloud-artlist: order-create: limit: 10 window-seconds: 60 + contact-info-read: + limit: 30 + window-seconds: 60 + contact-dial: + limit: 10 + window-seconds: 60 + dial: + provider: direct cache: local-max-size: 2048 product-detail: diff --git a/nacos/namespaces/sit/jayucloud-artlist/DEFAULT_GROUP/secret.yaml b/nacos/namespaces/sit/jayucloud-artlist/DEFAULT_GROUP/secret.yaml index 7b57509c..43cc1e1c 100644 --- a/nacos/namespaces/sit/jayucloud-artlist/DEFAULT_GROUP/secret.yaml +++ b/nacos/namespaces/sit/jayucloud-artlist/DEFAULT_GROUP/secret.yaml @@ -27,3 +27,10 @@ aliyun: oss: access-key-id: LTAI5t9divmxMWHiKhLSRdDd access-key-secret: U4BlsNpy7ISLbWYrQUsBMswaRH8G9Q + +# 手机号加密:与 jayucloud-salon 同环境的密钥保持一致,保证 phone_hash 可跨业务线比对。 +jayucloud-artlist: + privacy: + phone-crypto: + encryption-key: "/+Hq9v64U+5SHdBIw1w/6smGsbHh5224NSOvrn1o/fw=" + index-key: "bEQkH9PtYIMbe1SnO5z0lntr7esGl1ZrxI4Yg+XkFY8=" diff --git a/nacos/namespaces/sit/jayucloud-salon/DEFAULT_GROUP/core.yaml b/nacos/namespaces/sit/jayucloud-salon/DEFAULT_GROUP/core.yaml index 43316412..1a2e2db1 100644 --- a/nacos/namespaces/sit/jayucloud-salon/DEFAULT_GROUP/core.yaml +++ b/nacos/namespaces/sit/jayucloud-salon/DEFAULT_GROUP/core.yaml @@ -37,6 +37,9 @@ mybatis: map-underscore-to-camel-case: true jayucloud-salon: + deploy: + # 部署环境标识,用于微信内容审核回调的跨环境路由;缺失时 Core 启动失败 + env: sit wechat: mini: app-id: wxb6d77f7c07020d51 @@ -50,6 +53,9 @@ jayucloud-salon: brand: message-template-name: JayuCloud-Salon manager-register-shop-description: 甲屿店务注册店铺 + dial: + # direct:直拨真实号码;privacy-number:隐私号码(未对接时明确报错,绝不回退真实号码) + provider: direct privacy: content-moderation: # 仅 DEV 允许模拟审核;SIT 必须在后台配置微信审核并保持失败关闭。 @@ -86,6 +92,9 @@ jayucloud-salon: order-create: limit: 10 window-seconds: 60 + customer-dial: + limit: 10 + window-seconds: 60 cache: local-max-size: 2048 product-detail: diff --git a/scripts/ArtList数据迁移与会话隔离配置说明_20261104.md b/scripts/ArtList数据迁移与会话隔离配置说明_20261104.md index c0c7a467..d35ab51b 100644 --- a/scripts/ArtList数据迁移与会话隔离配置说明_20261104.md +++ b/scripts/ArtList数据迁移与会话隔离配置说明_20261104.md @@ -2,7 +2,7 @@ - 日期:2026-11-04 - 范围:`JC-ArtList-Core` 的 Flyway 数据库迁移接入、Redis 会话库隔离 -- 涉及配置:`nacos/namespaces/{dev,sit,prod}/jayucloud-artlist/DEFAULT_GROUP/core.yaml`、同目录 `infra.yaml` +- 涉及配置:`nacos/namespaces/{dev,sit,prod}/jayucloud-artlist/DEFAULT_GROUP/core.yaml`、同目录 `infra.yaml`、`secret.yaml` ## 一、本次改了什么 @@ -17,6 +17,8 @@ > **口径:不做数据迁移,空库从 V1 全量初始化。** 三个环境均按此口径执行,不存在“把存量库 baseline 到 V1”的场景。 + - 新增 `V2__手机号加密与手机号哈希_20261104.sql`:`t_user` 增加 `phone_cipher`/`phone_hash`/`contact_phone_cipher`/`contact_phone_hash`,删除明文列 `phone`/`contact_phone` 及索引 `idx_phone`,新增 `uk_user_phone_hash` 唯一索引与 `idx_user_contact_phone_hash` 普通索引;脚本幂等可重复执行。 + 2. **Redis 会话库迁移** - ArtList 的 `spring.redis.database` 从 `0` 改为 `1`,与 Salon 的 `0` 分开,避免两者会话 key 空间互相干扰。 - 会话 key 前缀统一为 `artlist:auth:session:` 与 `artlist:auth:user:sessions:`,覆盖登录校验、刷新令牌、踢下线等全部读写路径。 @@ -92,3 +94,17 @@ 3. 启动 `JC-ArtList-Core`,检查日志中 Flyway 迁移记录与 `flyway_schema_history` 内容。 4. 重新登录一次,确认会话写入 Redis `db 1`(`INFO keyspace` 或 `KEYS artlist:auth:session:*` 使用 `-n 1`)。 5. 验证旧登录态确实失效(使用旧 token 请求应返回未登录)。 + +## 七、手机号加密配置(`secret.yaml`) + +1. **新增配置项**:三个环境 `nacos/namespaces/{dev,sit,prod}/jayucloud-artlist/DEFAULT_GROUP/secret.yaml` 增加 + `jayucloud-artlist.privacy.phone-crypto.encryption-key` 与 `index-key`。 +2. **用途**: + - `encryption-key`:AES-GCM 加密手机号,落库到 `t_user.phone_cipher` / `contact_phone_cipher`; + - `index-key`:HMAC-SHA256 生成 `phone_hash` / `contact_phone_hash`,用于等值查询与唯一去重。 +3. **与 Salon 的关系**:算法与 Salon 的 `PhoneCrypto` 逐字一致(AES/GCM/NoPadding、12 字节随机 IV、128 位 tag、`enc:v1:` 前缀;HMAC-SHA256,规范化为 `trim`)。三个环境分别与同环境 Salon 的密钥保持一致,因此同环境两条线的 `phone_hash` 可直接比对;密文因随机 IV 各自独立,不要求可比。 +4. **三环境差异**:dev/sit/prod 均为独立密钥,不做跨环境共享;prod 生产密钥沿用 Salon 生产配置,**轮换时必须两条线同步替换 `index-key`**,否则跨线查询失效。 +5. **缺失时行为**:任一密钥缺失、非 Base64、长度不足 32 字节、或两项相同,`PhoneCrypto` 初始化即抛异常,应用启动失败(不会以明文降级)。 +6. **轮换与回退风险**:更换 `encryption-key` 会导致既有密文无法解密(需新增补偿迁移重新加密);更换 `index-key` 会导致既有哈希全部失效(需重建哈希);两种轮换都属于破坏性操作,必须先备份并评估。 +7. **安全要求**:仓库只放与环境一致的密钥引用,禁止在代码、日志、异常、审计中输出明文手机号;如需彻底外置,改为部署时注入,并同步 dev/sit/prod 的 Nacos。 +