完成Salon小程序合规整改

This commit is contained in:
2026-10-22 00:27:12 +08:00
parent 1120f9d5a9
commit da1f2d2cba
99 changed files with 2815 additions and 702 deletions
@@ -32,6 +32,7 @@ import org.springframework.context.annotation.Configuration;
"com.xiaowang.jayucloud.salon.core.modules.payment.mapper",
"com.xiaowang.jayucloud.salon.core.modules.planning.mapper",
"com.xiaowang.jayucloud.salon.core.modules.product.mapper",
"com.xiaowang.jayucloud.salon.core.modules.privacy.mapper",
"com.xiaowang.jayucloud.salon.core.modules.registration.mapper",
"com.xiaowang.jayucloud.salon.core.modules.security.mapper",
"com.xiaowang.jayucloud.salon.core.modules.shop.mapper",
@@ -0,0 +1,15 @@
package com.xiaowang.jayucloud.salon.core.config;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
@Data
@Configuration
@ConfigurationProperties(prefix = "jayucloud-salon.privacy.phone-crypto")
public class PhoneCryptoProperties {
private String encryptionKey;
private String indexKey;
private boolean backfillEnabled;
private int backfillPageSize = 500;
}
@@ -13,7 +13,7 @@ import lombok.Data;
public class UpdatePhoneRequestDTO {
/**
* 原手机号
* 兼容旧客户端的原手机号字段;服务端不使用该字段进行身份校验。
*/
private String oldPhone;
@@ -2,6 +2,7 @@ package com.xiaowang.jayucloud.salon.core.modules.auth.service.impl;
import com.xiaowang.jayucloud.salon.core.modules.integration.service.MessageHubClientService;
import com.xiaowang.jayucloud.salon.core.modules.auth.service.VerificationCodeService;
import com.xiaowang.jayucloud.salon.core.support.privacy.PhoneCrypto;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
@@ -52,6 +53,10 @@ public class VerificationCodeServiceImpl implements VerificationCodeService {
*/
private final MessageHubClientService messageHubClientService;
private String phoneKey(String phone) {
return PhoneCrypto.current().index(phone);
}
@Override
/**
* Run business method `generateVerificationCode`.
@@ -94,14 +99,14 @@ 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 codeKey = CODE_PREFIX + phoneKey(phone);
String sendTimeKey = SEND_TIME_PREFIX + phoneKey(phone);
messageHubClientService.sendSmsVerificationCode(sceneCode, phone, code);
redisTemplate.opsForValue().set(codeKey, code, Duration.ofMinutes(CODE_EXPIRE_MINUTES));
redisTemplate.opsForValue().set(sendTimeKey, String.valueOf(System.currentTimeMillis()),
Duration.ofSeconds(RESEND_INTERVAL_SECONDS));
log.info("验证码已发送,手机号: {}, sceneCode: {}", phone, sceneCode);
log.info("验证码已发送,手机号: {}, sceneCode: {}", PhoneCrypto.current().mask(phone), sceneCode);
}
@Override
@@ -113,21 +118,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 + phoneKey(phone);
String storedCode = redisTemplate.opsForValue().get(codeKey);
if (storedCode == null) {
log.warn("验证码不存在或已过期,手机号: {}", phone);
log.warn("验证码不存在或已过期,手机号: {}", PhoneCrypto.current().mask(phone));
return false;
}
if (!storedCode.equals(code)) {
log.warn("验证码错误,手机号: {}", phone);
log.warn("验证码错误,手机号: {}", PhoneCrypto.current().mask(phone));
return false;
}
redisTemplate.delete(codeKey);
log.info("验证码验证成功,手机号: {}", phone);
log.info("验证码验证成功,手机号: {}", PhoneCrypto.current().mask(phone));
return true;
}
@@ -139,7 +144,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 + phoneKey(phone);
String sendTime = redisTemplate.opsForValue().get(sendTimeKey);
return sendTime == null;
}
@@ -71,4 +71,7 @@ public class CommentDO extends BaseEntity {
*/
@TableField("is_delete")
private Integer isDelete;
@TableField("moderation_status")
private String moderationStatus;
}
@@ -14,6 +14,10 @@ import com.xiaowang.jayucloud.salon.core.modules.user.mapper.UserMapper;
import com.xiaowang.jayucloud.salon.core.modules.content.service.CommentService;
import com.xiaowang.jayucloud.salon.core.modules.file.service.ObjectStorageFileService;
import com.xiaowang.jayucloud.salon.core.modules.file.support.ObjectStorageUrlSupport;
import com.xiaowang.jayucloud.salon.core.modules.privacy.service.ContentModerationService;
import com.xiaowang.jayucloud.salon.core.modules.privacy.vo.ContentModerationResultVO;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.xiaowang.jayucloud.salon.core.modules.content.vo.CommentVO;
import com.xiaowang.jayucloud.salon.core.modules.file.vo.ObjectStorageFileVO;
import lombok.RequiredArgsConstructor;
@@ -57,6 +61,8 @@ public class CommentServiceImpl extends ServiceImpl<CommentMapper, CommentDO> im
private final ProductMapper productMapper;
private final ObjectStorageFileService objectStorageFileService;
private final ObjectStorageUrlSupport objectStorageUrlSupport;
private final ContentModerationService contentModerationService;
private final ObjectMapper objectMapper;
@Override
/**
@@ -155,7 +161,9 @@ public class CommentServiceImpl extends ServiceImpl<CommentMapper, CommentDO> im
}
commentDO.setLikeCount(0);
commentDO.setIsDelete(0);
commentDO.setModerationStatus("PENDING");
commentMapper.insert(commentDO);
moderateComment(commentDO, currentUserId);
return commentDO.getId();
}
@@ -173,8 +181,11 @@ public class CommentServiceImpl extends ServiceImpl<CommentMapper, CommentDO> im
return false;
}
commentDO.setCommentContent(sanitizeContent(commentDTO.getCommentContent()));
commentDO.setModerationStatus("PENDING");
commentDO.setUpdateTime(LocalDateTime.now());
return commentMapper.updateById(commentDO) > 0;
boolean updated = commentMapper.updateById(commentDO) > 0;
if (updated) moderateComment(commentDO, commentDO.getUserId());
return updated;
}
@Override
@@ -216,8 +227,11 @@ public class CommentServiceImpl extends ServiceImpl<CommentMapper, CommentDO> im
throw new RuntimeException("只能修改自己的评论");
}
commentDO.setCommentContent(sanitizeContent(commentDTO.getCommentContent()));
commentDO.setModerationStatus("PENDING");
commentDO.setUpdateTime(LocalDateTime.now());
return commentMapper.updateById(commentDO) > 0;
boolean updated = commentMapper.updateById(commentDO) > 0;
if (updated) moderateComment(commentDO, currentUserId);
return updated;
}
@Override
@@ -230,7 +244,7 @@ public class CommentServiceImpl extends ServiceImpl<CommentMapper, CommentDO> im
*/
public boolean deleteComment(Long id, Long currentUserId) {
CommentDO commentDO = commentMapper.selectById(id);
if (commentDO == null || Integer.valueOf(1).equals(commentDO.getIsDelete())) {
if (commentDO == null || Integer.valueOf(1).equals(commentDO.getIsDelete()) || !"APPROVED".equals(commentDO.getModerationStatus())) {
return false;
}
if (currentUserId == null || !currentUserId.equals(commentDO.getUserId())) {
@@ -315,6 +329,7 @@ public class CommentServiceImpl extends ServiceImpl<CommentMapper, CommentDO> im
Wrappers.lambdaQuery(CommentDO.class)
.eq(CommentDO::getUserId, userId)
.eq(CommentDO::getIsDelete, 0)
.eq(CommentDO::getModerationStatus, "APPROVED")
.orderByDesc(CommentDO::getCreateTime)
);
return commentDOs.stream()
@@ -334,6 +349,7 @@ public class CommentServiceImpl extends ServiceImpl<CommentMapper, CommentDO> im
Wrappers.lambdaQuery(CommentDO.class)
.eq(CommentDO::getShopId, shopId)
.eq(CommentDO::getIsDelete, 0)
.eq(CommentDO::getModerationStatus, "APPROVED")
.orderByDesc(CommentDO::getCreateTime)
);
return commentDOs.stream()
@@ -353,6 +369,7 @@ public class CommentServiceImpl extends ServiceImpl<CommentMapper, CommentDO> im
Wrappers.lambdaQuery(CommentDO.class)
.eq(CommentDO::getProductId, productId)
.eq(CommentDO::getIsDelete, 0)
.eq(CommentDO::getModerationStatus, "APPROVED")
.orderByDesc(CommentDO::getCreateTime)
);
/**
@@ -376,6 +393,7 @@ public class CommentServiceImpl extends ServiceImpl<CommentMapper, CommentDO> im
Wrappers.lambdaQuery(CommentDO.class)
.eq(CommentDO::getParentCommentId, parentCommentId)
.eq(CommentDO::getIsDelete, 0)
.eq(CommentDO::getModerationStatus, "APPROVED")
.orderByAsc(CommentDO::getCreateTime)
);
return commentDOs.stream()
@@ -397,6 +415,7 @@ public class CommentServiceImpl extends ServiceImpl<CommentMapper, CommentDO> im
List<CommentDO> commentDOs = commentMapper.selectList(
Wrappers.lambdaQuery(CommentDO.class)
.eq(CommentDO::getIsDelete, 0)
.eq(CommentDO::getModerationStatus, "APPROVED")
.eq(productId != null && productId > 0, CommentDO::getProductId, productId)
.eq(userId != null && userId > 0, CommentDO::getUserId, userId)
.eq(shopId != null && shopId > 0, CommentDO::getShopId, shopId)
@@ -569,7 +588,23 @@ public class CommentServiceImpl extends ServiceImpl<CommentMapper, CommentDO> im
* @return private com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper<CommentDO> result consumed by the caller or returned to the frontend
*/
private com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper<CommentDO> activeQuery() {
return Wrappers.lambdaQuery(CommentDO.class).eq(CommentDO::getIsDelete, 0);
return Wrappers.lambdaQuery(CommentDO.class).eq(CommentDO::getIsDelete, 0)
.eq(CommentDO::getModerationStatus, "APPROVED");
}
private void moderateComment(CommentDO comment, Long userId) {
try {
ContentModerationResultVO result = contentModerationService.assess("COMMENT", comment.getId(), userId,
comment.getCommentContent() + "\n" + String.valueOf(comment.getImageFileIds()),
objectMapper.writeValueAsString(java.util.Map.of(
"commentContent", comment.getCommentContent(),
"imageFileIds", comment.getImageFileIds() == null ? "" : comment.getImageFileIds())));
comment.setModerationStatus(result.getStatus());
comment.setUpdateTime(LocalDateTime.now());
commentMapper.updateById(comment);
} catch (JsonProcessingException exception) {
throw new IllegalStateException("评论审核内容序列化失败", exception);
}
}
/**
@@ -1,14 +1,17 @@
package com.xiaowang.jayucloud.salon.core.modules.integration.dto;
import com.xiaowang.jayucloud.salon.core.common.dto.AgreementAwareRequest;
import lombok.Data;
import javax.validation.constraints.NotBlank;
import java.util.Map;
/**
* 微信小程序自动登录请求。
*/
@Data
public class WechatMiniAutoLoginRequestDTO {
public class WechatMiniAutoLoginRequestDTO implements AgreementAwareRequest {
@NotBlank(message = "微信登录凭证不能为空")
/**
@@ -20,4 +23,8 @@ public class WechatMiniAutoLoginRequestDTO {
* Field `preferredShopId` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled.
*/
private Long preferredShopId;
private Boolean agreementAccepted;
private Map<String, String> agreementVersions;
private String clientType;
}
@@ -5,6 +5,7 @@ import com.fasterxml.jackson.databind.JsonNode;
import com.xiaowang.jayucloud.salon.core.config.BrandProperties;
import com.xiaowang.jayucloud.salon.core.modules.integration.entity.MessageHubPushConfigDO;
import com.xiaowang.jayucloud.salon.core.modules.integration.service.MessageHubClientService;
import com.xiaowang.jayucloud.salon.core.support.privacy.PhoneCrypto;
import com.xiaowang.jayucloud.salon.core.modules.integration.service.MessageHubPushConfigService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
@@ -138,7 +139,7 @@ public class MessageHubClientServiceImpl implements MessageHubClientService {
message.getMessageProperties().setHeader("X-MessageHub-Access-Token", requireAccessToken());
rabbitTemplate.send(ingressExchange, ingressRoutingKey, message);
log.info("短信验证码消息已投递到 MessageHub,sceneCode: {}, phone: {}, exchange: {}, sourceSystem: {}, templateCode: {}",
sceneCode, phone, ingressExchange, messageBody.get("sourceSystem"), messageBody.get("templateCode"));
sceneCode, PhoneCrypto.current().mask(phone), ingressExchange, messageBody.get("sourceSystem"), messageBody.get("templateCode"));
} catch (Exception exception) {
log.error("发送短信验证码失败", exception);
throw new RuntimeException("发送短信验证码失败: " + exception.getMessage(), exception);
@@ -17,6 +17,7 @@ import com.xiaowang.jayucloud.salon.core.modules.registration.mapper.WorkbenchRe
import com.xiaowang.jayucloud.salon.core.modules.user.entity.UserDO;
import com.xiaowang.jayucloud.salon.core.modules.integration.entity.WechatMiniBindingDO;
import com.xiaowang.jayucloud.salon.core.modules.user.mapper.UserMapper;
import com.xiaowang.jayucloud.salon.core.support.privacy.PhoneCrypto;
import com.xiaowang.jayucloud.salon.core.modules.integration.mapper.WechatMiniBindingMapper;
import com.xiaowang.jayucloud.salon.core.modules.user.service.UserService;
import com.xiaowang.jayucloud.salon.core.modules.integration.service.WechatMiniAuthService;
@@ -500,12 +501,15 @@ public class WechatMiniAuthServiceImpl implements WechatMiniAuthService {
if (!StringUtils.hasText(phone)) {
return null;
}
return userMapper.selectOne(
new LambdaQueryWrapper<UserDO>()
.eq(UserDO::getPhone, phone)
.eq(UserDO::getIsDelete, 0)
.last("limit 1")
);
UserDO user = userMapper.selectOne(new LambdaQueryWrapper<UserDO>()
.eq(UserDO::getPhoneHash, PhoneCrypto.current().index(phone.trim()))
.eq(UserDO::getIsDelete, 0)
.last("limit 1"));
if (user == null) {
Long legacyId = userMapper.findLegacyIdByPhone(phone.trim());
user = legacyId == null ? null : userMapper.selectById(legacyId);
}
return user;
}
/**
@@ -123,7 +123,7 @@ public class WechatMiniLoginResultVO {
resultVO.setMessage("手机号尚未绑定店铺,请先完成身份注册");
resultVO.setRegistrationRequired(true);
resultVO.setRegistrationTicket(loginResponse.getRegistrationTicket());
resultVO.setPhone(loginResponse.getPhone());
resultVO.setPhone(maskPhone(loginResponse.getPhone()));
resultVO.setRegistrationReason(loginResponse.getRegistrationReason());
resultVO.setRegistrationStatus(loginResponse.getRegistrationStatus());
resultVO.setRegistrationRejectReason(loginResponse.getRegistrationRejectReason());
@@ -131,6 +131,13 @@ public class WechatMiniLoginResultVO {
return resultVO;
}
private static String maskPhone(String phone) {
if (phone == null || phone.length() != 11 || !phone.matches("1[3-9]\\d{9}")) {
return phone;
}
return phone.substring(0, 3) + "****" + phone.substring(7);
}
public static WechatMiniLoginResultVO selectShop(
String message,
String ticket,
@@ -15,6 +15,7 @@ import com.xiaowang.jayucloud.salon.core.modules.message.service.AnnouncementSer
import com.xiaowang.jayucloud.salon.core.modules.security.support.AdminScopeHelper;
import com.xiaowang.jayucloud.salon.core.modules.message.vo.AnnouncementVO;
import com.xiaowang.jayucloud.salon.core.modules.message.vo.MessageTargetOptionsVO;
import com.xiaowang.jayucloud.salon.core.support.privacy.PhoneCrypto;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
@@ -83,6 +84,7 @@ public class AnnouncementServiceImpl extends ServiceImpl<AnnouncementMapper, Ann
* Variable `adminScopeHelper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls.
*/
private final AdminScopeHelper adminScopeHelper;
private final PhoneCrypto phoneCrypto;
@Override
@Transactional(rollbackFor = Exception.class)
@@ -212,7 +214,7 @@ public class AnnouncementServiceImpl extends ServiceImpl<AnnouncementMapper, Ann
MessageTargetOptionsVO.UserOptionVO vo = new MessageTargetOptionsVO.UserOptionVO();
vo.setId(user.getId());
vo.setNickname(user.getNickname());
vo.setAccount(user.getAccount());
vo.setAccount(phoneCrypto.mask(user.getAccount()));
vo.setShopId(user.getShopId());
vo.setShopName(shopNameMap.get(user.getShopId()));
vo.setType(user.getType());
@@ -20,6 +20,7 @@ import com.xiaowang.jayucloud.salon.core.modules.file.support.ObjectStorageUrlSu
import com.xiaowang.jayucloud.salon.core.modules.message.vo.MessageTargetOptionsVO;
import com.xiaowang.jayucloud.salon.core.modules.file.vo.ObjectStorageFileVO;
import com.xiaowang.jayucloud.salon.core.modules.message.vo.SystemMessageVO;
import com.xiaowang.jayucloud.salon.core.support.privacy.PhoneCrypto;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
@@ -97,6 +98,7 @@ public class SystemMessageServiceImpl extends ServiceImpl<SystemMessageMapper, S
* Variable `objectStorageFileService`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls.
*/
private final ObjectStorageFileService objectStorageFileService;
private final PhoneCrypto phoneCrypto;
/**
* Variable `objectStorageUrlSupport`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls.
*/
@@ -267,7 +269,7 @@ public class SystemMessageServiceImpl extends ServiceImpl<SystemMessageMapper, S
MessageTargetOptionsVO.UserOptionVO vo = new MessageTargetOptionsVO.UserOptionVO();
vo.setId(user.getId());
vo.setNickname(user.getNickname());
vo.setAccount(user.getAccount());
vo.setAccount(phoneCrypto.mask(user.getAccount()));
vo.setShopId(user.getShopId());
vo.setShopName(shopNameMap.get(user.getShopId()));
vo.setType(user.getType());
@@ -1,6 +1,9 @@
package com.xiaowang.jayucloud.salon.core.modules.order.entity;
import com.baomidou.mybatisplus.annotation.TableName;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.FieldFill;
import com.xiaowang.jayucloud.salon.core.support.privacy.PhoneEncryptionTypeHandler;
import lombok.Data;
import java.math.BigDecimal;
@@ -8,7 +11,7 @@ import java.time.LocalDateTime;
import com.xiaowang.jayucloud.salon.core.common.entity.BaseEntity;
@Data
@TableName("t_order")
@TableName(value = "t_order", autoResultMap = true)
/**
* OrderDO maps to a database table row. Mapper classes persist and query this object.
* Field and parameter names are kept consistent with the frontend/API payload to make tracing easier.
@@ -55,7 +58,10 @@ public class OrderDO extends BaseEntity {
private String refundStatus;
private String customerRemark;
private String customerNameSnapshot;
@TableField(typeHandler = PhoneEncryptionTypeHandler.class)
private String customerPhoneSnapshot;
@TableField(value = "customer_phone_snapshot_hash", fill = FieldFill.INSERT_UPDATE)
private String customerPhoneSnapshotHash;
private String quoteStatus;
private String orderSource;
private Integer quoteUserConfirmed;
@@ -1,32 +0,0 @@
package com.xiaowang.jayucloud.salon.core.modules.payment.controller.front;
import com.xiaowang.jayucloud.salon.core.common.Result;
import com.xiaowang.jayucloud.salon.core.modules.payment.service.PaymentService;
import com.xiaowang.jayucloud.salon.core.modules.payment.vo.PaymentOrderVO;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletRequest;
@RestController
@RequestMapping("/payment")
@RequiredArgsConstructor
public class PaymentController {
private final PaymentService paymentService;
@PostMapping("/order/{orderId}/prepare")
public Result<PaymentOrderVO> prepareOrderPayment(HttpServletRequest request, @PathVariable Long orderId) {
Long userId = (Long) request.getAttribute("userId");
return Result.success(paymentService.prepareOrderPayment(userId, orderId));
}
@PostMapping("/order/{orderId}/mock-success")
public Result<PaymentOrderVO> mockSuccess(HttpServletRequest request, @PathVariable Long orderId) {
Long userId = (Long) request.getAttribute("userId");
return Result.success(paymentService.manualConfirmOrderPaid(userId, orderId, "mock-success"));
}
}
@@ -0,0 +1,65 @@
package com.xiaowang.jayucloud.salon.core.modules.privacy.controller.admin;
import com.xiaowang.jayucloud.salon.core.annotation.OperationGuard;
import com.xiaowang.jayucloud.salon.core.common.Result;
import com.xiaowang.jayucloud.salon.core.modules.privacy.dto.AccountClosureProcessDTO;
import com.xiaowang.jayucloud.salon.core.modules.privacy.service.AccountClosureService;
import com.xiaowang.jayucloud.salon.core.modules.privacy.vo.AccountClosureRequestVO;
import com.xiaowang.jayucloud.salon.core.modules.user.entity.UserDO;
import com.xiaowang.jayucloud.salon.core.modules.user.mapper.UserMapper;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.xiaowang.jayucloud.salon.core.modules.privacy.vo.ClosureSuccessorManagerVO;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.stream.Collectors;
@RestController
@RequiredArgsConstructor
@RequestMapping("/admin/privacy/account-closure")
public class AdminAccountClosureController {
private final AccountClosureService accountClosureService;
private final UserMapper userMapper;
@GetMapping("/pending")
public Result<List<AccountClosureRequestVO>> pending(HttpServletRequest request) {
requirePlatformAdmin(request);
return Result.success(accountClosureService.listPending());
}
@GetMapping("/successor-managers")
public Result<List<ClosureSuccessorManagerVO>> successorManagers(HttpServletRequest request) {
requirePlatformAdmin(request);
List<ClosureSuccessorManagerVO> managers = userMapper.selectList(Wrappers.lambdaQuery(UserDO.class)
.eq(UserDO::getType, 2).eq(UserDO::getStatus, 1).eq(UserDO::getIsDelete, 0)
.select(UserDO::getId, UserDO::getNickname, UserDO::getShopId)
.orderByAsc(UserDO::getNickname))
.stream().map(user -> new ClosureSuccessorManagerVO(user.getId(), user.getNickname(), user.getShopId()))
.collect(Collectors.toList());
return Result.success(managers);
}
@PostMapping("/{id}/process")
@OperationGuard(action = "admin-account-closure-process", ttlSeconds = 10, message = "申请处理中,请勿重复提交")
public Result<Boolean> process(HttpServletRequest request, @PathVariable Long id,
@RequestBody AccountClosureProcessDTO dto) {
Long reviewerId = requirePlatformAdmin(request);
return Result.success(accountClosureService.process(reviewerId, id, dto));
}
private Long requirePlatformAdmin(HttpServletRequest request) {
Object value = request.getAttribute("userId");
if (!(value instanceof Long)) throw new IllegalArgumentException("登录状态已失效");
Long userId = (Long) value;
UserDO actor = userMapper.selectById(userId);
if (actor == null || !Integer.valueOf(4).equals(actor.getType())) throw new IllegalArgumentException("无权处理注销申请");
return userId;
}
}
@@ -0,0 +1,56 @@
package com.xiaowang.jayucloud.salon.core.modules.privacy.controller.admin;
import com.xiaowang.jayucloud.salon.core.annotation.OperationGuard;
import com.xiaowang.jayucloud.salon.core.common.Result;
import com.xiaowang.jayucloud.salon.core.modules.privacy.dto.ContentModerationReviewDTO;
import com.xiaowang.jayucloud.salon.core.modules.privacy.entity.ContentModerationRecordDO;
import com.xiaowang.jayucloud.salon.core.modules.privacy.service.ContentModerationService;
import com.xiaowang.jayucloud.salon.core.modules.user.entity.UserDO;
import com.xiaowang.jayucloud.salon.core.modules.user.mapper.UserMapper;
import lombok.RequiredArgsConstructor;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.List;
@RestController
@RequiredArgsConstructor
@Validated
@RequestMapping("/admin/privacy/content-moderation")
public class AdminContentModerationController {
private final ContentModerationService contentModerationService;
private final UserMapper userMapper;
@GetMapping("/pending")
public Result<List<ContentModerationRecordDO>> pending(HttpServletRequest request) {
requirePlatformAdmin(request);
return Result.success(contentModerationService.listPending());
}
@PostMapping("/{id}/review")
@OperationGuard(action = "admin-content-moderation-review", ttlSeconds = 5, message = "复核处理中,请勿重复提交")
public Result<Boolean> review(HttpServletRequest request, @PathVariable Long id,
@Valid @RequestBody ContentModerationReviewDTO dto) {
Long reviewerId = requirePlatformAdmin(request);
if (dto.getApproved() == null) throw new IllegalArgumentException("请选择通过或拒绝");
return Result.success(contentModerationService.review(reviewerId, id, dto.getApproved(), dto.getReason()));
}
private Long requirePlatformAdmin(HttpServletRequest request) {
Object value = request.getAttribute("userId");
if (!(value instanceof Long)) throw new IllegalArgumentException("登录状态已失效");
Long userId = (Long) value;
UserDO actor = userMapper.selectById(userId);
if (actor == null || !Integer.valueOf(4).equals(actor.getType()) || !Integer.valueOf(1).equals(actor.getStatus())) {
throw new IllegalArgumentException("无权处理内容复核");
}
return userId;
}
}
@@ -0,0 +1,43 @@
package com.xiaowang.jayucloud.salon.core.modules.privacy.controller.admin;
import com.xiaowang.jayucloud.salon.core.common.Result;
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.support.privacy.PhoneBackfillReport;
import com.xiaowang.jayucloud.salon.core.support.privacy.PhoneDataBackfillService;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletRequest;
@RestController
@RequiredArgsConstructor
@RequestMapping("/admin/privacy/phone-backfill")
public class AdminPhoneBackfillController {
private final PhoneDataBackfillService backfillService;
private final UserMapper userMapper;
@GetMapping("/report")
public Result<PhoneBackfillReport> report(HttpServletRequest request) {
requirePlatformAdmin(request);
return Result.success(backfillService.backfill(true));
}
@PostMapping("/run")
public Result<PhoneBackfillReport> run(HttpServletRequest request) {
requirePlatformAdmin(request);
return Result.success(backfillService.backfill(false));
}
private void requirePlatformAdmin(HttpServletRequest request) {
Object value = request.getAttribute("userId");
if (!(value instanceof Long)) throw new IllegalArgumentException("登录状态已失效");
UserDO actor = userMapper.selectById((Long) value);
if (actor == null || !Integer.valueOf(4).equals(actor.getType()) || !Integer.valueOf(1).equals(actor.getStatus())) {
throw new IllegalArgumentException("无权执行手机号数据处理");
}
}
}
@@ -0,0 +1,44 @@
package com.xiaowang.jayucloud.salon.core.modules.privacy.controller.front;
import com.xiaowang.jayucloud.salon.core.annotation.OperationGuard;
import com.xiaowang.jayucloud.salon.core.common.Result;
import com.xiaowang.jayucloud.salon.core.modules.privacy.service.AccountClosureService;
import com.xiaowang.jayucloud.salon.core.modules.privacy.vo.AccountClosureRequestVO;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletRequest;
@RestController
@RequiredArgsConstructor
@RequestMapping("/user/account-closure")
public class AccountClosureController {
private final AccountClosureService accountClosureService;
@PostMapping
@OperationGuard(action = "account-closure-request", ttlSeconds = 10, message = "注销申请处理中,请勿重复提交")
public Result<AccountClosureRequestVO> request(HttpServletRequest request) {
return Result.success(accountClosureService.request(userId(request)));
}
@GetMapping("/me")
public Result<AccountClosureRequestVO> getMine(HttpServletRequest request) {
return Result.success(accountClosureService.getMine(userId(request)));
}
@DeleteMapping("/me")
@OperationGuard(action = "account-closure-withdraw", ttlSeconds = 10, message = "撤回处理中,请勿重复操作")
public Result<Boolean> withdraw(HttpServletRequest request) {
return Result.success(accountClosureService.withdraw(userId(request)));
}
private Long userId(HttpServletRequest request) {
Object value = request.getAttribute("userId");
if (!(value instanceof Long)) throw new IllegalArgumentException("登录状态已失效");
return (Long) value;
}
}
@@ -0,0 +1,13 @@
package com.xiaowang.jayucloud.salon.core.modules.privacy.dto;
import lombok.Data;
import java.util.List;
@Data
public class AccountClosureProcessDTO {
private String decision;
private Long successorManagerId;
private List<Long> archiveShopIds;
private String note;
}
@@ -0,0 +1,12 @@
package com.xiaowang.jayucloud.salon.core.modules.privacy.dto;
import lombok.Data;
import javax.validation.constraints.NotBlank;
@Data
public class ContentModerationReviewDTO {
private Boolean approved;
@NotBlank
private String reason;
}
@@ -0,0 +1,24 @@
package com.xiaowang.jayucloud.salon.core.modules.privacy.entity;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import com.xiaowang.jayucloud.salon.core.common.entity.BaseEntity;
import lombok.Getter;
import lombok.Setter;
import java.time.LocalDateTime;
@Getter
@Setter
@TableName("t_account_closure_request")
public class AccountClosureRequestDO extends BaseEntity {
@TableId(type = IdType.ASSIGN_ID)
private Long id;
private Long userId;
private String status;
private LocalDateTime requestedAt;
private LocalDateTime processedAt;
private Long reviewerId;
private String reviewerNote;
}
@@ -0,0 +1,29 @@
package com.xiaowang.jayucloud.salon.core.modules.privacy.entity;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import com.xiaowang.jayucloud.salon.core.common.entity.BaseEntity;
import lombok.Getter;
import lombok.Setter;
import java.time.LocalDateTime;
@Getter
@Setter
@TableName("t_content_moderation_record")
public class ContentModerationRecordDO extends BaseEntity {
@TableId(type = IdType.ASSIGN_ID)
private Long id;
private String contentType;
private Long businessId;
private Long userId;
private String status;
private String provider;
private String resultCode;
private String reason;
private String payloadJson;
private Long reviewedBy;
private LocalDateTime reviewedAt;
private Integer attemptCount;
}
@@ -0,0 +1,7 @@
package com.xiaowang.jayucloud.salon.core.modules.privacy.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.xiaowang.jayucloud.salon.core.modules.privacy.entity.AccountClosureRequestDO;
public interface AccountClosureRequestMapper extends BaseMapper<AccountClosureRequestDO> {
}
@@ -0,0 +1,7 @@
package com.xiaowang.jayucloud.salon.core.modules.privacy.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.xiaowang.jayucloud.salon.core.modules.privacy.entity.ContentModerationRecordDO;
public interface ContentModerationRecordMapper extends BaseMapper<ContentModerationRecordDO> {
}
@@ -0,0 +1,7 @@
package com.xiaowang.jayucloud.salon.core.modules.privacy.moderation;
public interface ContentModerationProvider {
String providerName();
ModerationOutcome review(String contentType, String content);
}
@@ -0,0 +1,33 @@
package com.xiaowang.jayucloud.salon.core.modules.privacy.moderation;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Component;
@Component
@ConditionalOnProperty(
prefix = "jayucloud-salon.privacy.content-moderation",
name = "provider",
havingValue = "mock"
)
public class LocalMockContentModerationProvider implements ContentModerationProvider {
@Override
public String providerName() {
return "LOCAL_MOCK";
}
@Override
public ModerationOutcome review(String contentType, String content) {
String value = content == null ? "" : content;
if (value.contains("[[MOCK:FAIL]]")) throw new IllegalStateException("本地模拟审核故障");
if (value.contains("[[MOCK:REJECT]]")) {
return new ModerationOutcome(ModerationOutcome.Status.REJECTED, "MOCK_REJECT", "本地模拟命中拒绝场景");
}
if (value.contains("[[MOCK:PENDING]]")) {
return new ModerationOutcome(ModerationOutcome.Status.PENDING, "MOCK_PENDING", "本地模拟进入人工复核");
}
if (value.contains("[[MOCK:APPROVE]]")) {
return new ModerationOutcome(ModerationOutcome.Status.APPROVED, "MOCK_APPROVE", "本地模拟通过场景");
}
return new ModerationOutcome(ModerationOutcome.Status.PENDING, "MOCK_UNMATCHED", "未命中模拟场景,默认进入人工复核");
}
}
@@ -0,0 +1,5 @@
package com.xiaowang.jayucloud.salon.core.modules.privacy.moderation;
public record ModerationOutcome(Status status, String code, String reason) {
public enum Status { APPROVED, PENDING, REJECTED, RETRY }
}
@@ -0,0 +1,27 @@
package com.xiaowang.jayucloud.salon.core.modules.privacy.moderation;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.stereotype.Component;
@Component
@ConditionalOnProperty(
prefix = "jayucloud-salon.privacy.content-moderation",
name = "provider",
havingValue = "disabled",
matchIfMissing = true
)
public class UnconfiguredContentModerationProvider implements ContentModerationProvider {
@Override
public String providerName() {
return "UNCONFIGURED";
}
@Override
public ModerationOutcome review(String contentType, String content) {
return new ModerationOutcome(
ModerationOutcome.Status.RETRY,
"PROVIDER_NOT_CONFIGURED",
"内容审核平台尚未接入,内容已隔离等待人工复核"
);
}
}
@@ -0,0 +1,14 @@
package com.xiaowang.jayucloud.salon.core.modules.privacy.service;
import com.xiaowang.jayucloud.salon.core.modules.privacy.dto.AccountClosureProcessDTO;
import com.xiaowang.jayucloud.salon.core.modules.privacy.vo.AccountClosureRequestVO;
import java.util.List;
public interface AccountClosureService {
AccountClosureRequestVO request(Long userId);
AccountClosureRequestVO getMine(Long userId);
boolean withdraw(Long userId);
List<AccountClosureRequestVO> listPending();
boolean process(Long reviewerId, Long requestId, AccountClosureProcessDTO dto);
}
@@ -0,0 +1,12 @@
package com.xiaowang.jayucloud.salon.core.modules.privacy.service;
import com.xiaowang.jayucloud.salon.core.modules.privacy.entity.ContentModerationRecordDO;
import com.xiaowang.jayucloud.salon.core.modules.privacy.vo.ContentModerationResultVO;
import java.util.List;
public interface ContentModerationService {
ContentModerationResultVO assess(String contentType, Long businessId, Long userId, String content, String payloadJson);
List<ContentModerationRecordDO> listPending();
boolean review(Long reviewerId, Long recordId, boolean approved, String reason);
}
@@ -0,0 +1,297 @@
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.LambdaUpdateWrapper;
import com.xiaowang.jayucloud.salon.core.modules.integration.entity.WechatMiniBindingDO;
import com.xiaowang.jayucloud.salon.core.modules.integration.mapper.WechatMiniBindingMapper;
import com.xiaowang.jayucloud.salon.core.modules.order.entity.OrderDO;
import com.xiaowang.jayucloud.salon.core.modules.order.mapper.OrderMapper;
import com.xiaowang.jayucloud.salon.core.modules.privacy.dto.AccountClosureProcessDTO;
import com.xiaowang.jayucloud.salon.core.modules.privacy.entity.AccountClosureRequestDO;
import com.xiaowang.jayucloud.salon.core.modules.privacy.mapper.AccountClosureRequestMapper;
import com.xiaowang.jayucloud.salon.core.modules.privacy.service.AccountClosureService;
import com.xiaowang.jayucloud.salon.core.modules.privacy.vo.AccountClosureRequestVO;
import com.xiaowang.jayucloud.salon.core.modules.security.entity.UserShopRoleDO;
import com.xiaowang.jayucloud.salon.core.modules.security.mapper.UserShopRoleMapper;
import com.xiaowang.jayucloud.salon.core.modules.shop.entity.ShopDO;
import com.xiaowang.jayucloud.salon.core.modules.shop.entity.UserShopBindingDO;
import com.xiaowang.jayucloud.salon.core.modules.shop.mapper.ShopMapper;
import com.xiaowang.jayucloud.salon.core.modules.shop.mapper.UserShopBindingMapper;
import com.xiaowang.jayucloud.salon.core.modules.user.entity.UserDO;
import com.xiaowang.jayucloud.salon.core.modules.user.entity.UserRelationDO;
import com.xiaowang.jayucloud.salon.core.modules.user.mapper.UserMapper;
import com.xiaowang.jayucloud.salon.core.modules.user.mapper.UserRelationMapper;
import com.xiaowang.jayucloud.salon.core.modules.user.mapper.UserAgreementConsentMapper;
import com.xiaowang.jayucloud.salon.core.modules.security.mapper.SecurityAuditLogMapper;
import com.xiaowang.jayucloud.salon.core.support.security.UserSessionService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors;
@Service
@RequiredArgsConstructor
public class AccountClosureServiceImpl implements AccountClosureService {
private static final String PENDING = "PENDING";
private static final String WITHDRAWN = "WITHDRAWN";
private static final String APPROVED = "APPROVED";
private static final String REJECTED = "REJECTED";
private final AccountClosureRequestMapper requestMapper;
private final UserMapper userMapper;
private final ShopMapper shopMapper;
private final UserShopBindingMapper bindingMapper;
private final UserShopRoleMapper shopRoleMapper;
private final UserRelationMapper relationMapper;
private final WechatMiniBindingMapper wechatBindingMapper;
private final UserAgreementConsentMapper consentMapper;
private final SecurityAuditLogMapper securityAuditLogMapper;
private final OrderMapper orderMapper;
private final UserSessionService sessionService;
@Override
@Transactional(rollbackFor = Exception.class)
public AccountClosureRequestVO request(Long userId) {
UserDO user = userMapper.selectOne(new LambdaQueryWrapper<UserDO>()
.eq(UserDO::getId, userId).eq(UserDO::getIsDelete, 0).last("FOR UPDATE"));
if (user == null) throw new IllegalStateException("账号不存在或已注销");
if (Integer.valueOf(4).equals(user.getType())) throw new IllegalStateException("管理员账号不能申请注销");
AccountClosureRequestDO pending = requestMapper.selectOne(new LambdaQueryWrapper<AccountClosureRequestDO>()
.eq(AccountClosureRequestDO::getUserId, userId)
.eq(AccountClosureRequestDO::getStatus, PENDING)
.orderByDesc(AccountClosureRequestDO::getRequestedAt)
.last("limit 1"));
if (pending != null) return toVO(pending, user);
AccountClosureRequestDO request = new AccountClosureRequestDO();
request.setUserId(userId);
request.setStatus(PENDING);
request.setRequestedAt(LocalDateTime.now());
requestMapper.insert(request);
return toVO(request, user);
}
@Override
public AccountClosureRequestVO getMine(Long userId) {
AccountClosureRequestDO request = requestMapper.selectOne(new LambdaQueryWrapper<AccountClosureRequestDO>()
.eq(AccountClosureRequestDO::getUserId, userId)
.orderByDesc(AccountClosureRequestDO::getRequestedAt)
.last("limit 1"));
if (request == null) return null;
UserDO user = userMapper.selectById(userId);
return toVO(request, user);
}
@Override
@Transactional(rollbackFor = Exception.class)
public boolean withdraw(Long userId) {
AccountClosureRequestDO request = requestMapper.selectOne(new LambdaQueryWrapper<AccountClosureRequestDO>()
.eq(AccountClosureRequestDO::getUserId, userId)
.eq(AccountClosureRequestDO::getStatus, PENDING)
.orderByDesc(AccountClosureRequestDO::getRequestedAt)
.last("limit 1"));
if (request == null) return false;
request.setStatus(WITHDRAWN);
request.setProcessedAt(LocalDateTime.now());
return requestMapper.updateById(request) > 0;
}
@Override
public List<AccountClosureRequestVO> listPending() {
return requestMapper.selectList(new LambdaQueryWrapper<AccountClosureRequestDO>()
.eq(AccountClosureRequestDO::getStatus, PENDING)
.orderByAsc(AccountClosureRequestDO::getRequestedAt))
.stream()
.map(request -> toVO(request, userMapper.selectById(request.getUserId())))
.collect(Collectors.toList());
}
@Override
@Transactional(rollbackFor = Exception.class)
public boolean process(Long reviewerId, Long requestId, AccountClosureProcessDTO dto) {
if (dto == null || (!"APPROVE".equals(dto.getDecision()) && !"REJECT".equals(dto.getDecision()))) {
throw new IllegalArgumentException("请选择批准或驳回");
}
AccountClosureRequestDO request = requestMapper.selectById(requestId);
if (request == null || !PENDING.equals(request.getStatus())) throw new IllegalStateException("注销申请已处理或不存在");
int claimed = requestMapper.update(null, new LambdaUpdateWrapper<AccountClosureRequestDO>()
.eq(AccountClosureRequestDO::getId, requestId)
.eq(AccountClosureRequestDO::getStatus, PENDING)
.set(AccountClosureRequestDO::getStatus, "PROCESSING"));
if (claimed != 1) throw new IllegalStateException("注销申请已处理或正在处理中");
UserDO user = requireActiveUser(request.getUserId());
if ("REJECT".equals(dto.getDecision())) {
if (!StringUtils.hasText(dto.getNote())) throw new IllegalArgumentException("驳回原因不能为空");
request.setStatus(REJECTED);
request.setReviewerNote(dto.getNote().trim());
} else {
transferOrArchiveShops(user, dto);
anonymizeUser(user);
request.setStatus(APPROVED);
request.setReviewerNote(StringUtils.hasText(dto.getNote()) ? dto.getNote().trim() : "已完成资料清理与会话撤销");
}
request.setReviewerId(reviewerId);
request.setProcessedAt(LocalDateTime.now());
return requestMapper.updateById(request) > 0;
}
private void transferOrArchiveShops(UserDO user, AccountClosureProcessDTO dto) {
List<UserShopBindingDO> bindings = bindingMapper.selectList(new LambdaQueryWrapper<UserShopBindingDO>()
.eq(UserShopBindingDO::getUserId, user.getId())
.eq(UserShopBindingDO::getIsDelete, 0)
.eq(UserShopBindingDO::getStatus, 1));
if (bindings.isEmpty()) return;
if (!Integer.valueOf(2).equals(user.getType())) {
bindingMapper.update(null, new LambdaUpdateWrapper<UserShopBindingDO>()
.eq(UserShopBindingDO::getUserId, user.getId()).eq(UserShopBindingDO::getIsDelete, 0)
.set(UserShopBindingDO::getIsDelete, 1).set(UserShopBindingDO::getUpdateTime, LocalDateTime.now()));
shopRoleMapper.update(null, new LambdaUpdateWrapper<UserShopRoleDO>()
.eq(UserShopRoleDO::getUserId, user.getId()).eq(UserShopRoleDO::getIsDelete, 0)
.set(UserShopRoleDO::getIsDelete, 1).set(UserShopRoleDO::getUpdateTime, LocalDateTime.now()));
return;
}
if (dto.getSuccessorManagerId() != null) {
UserDO successor = requireActiveUser(dto.getSuccessorManagerId());
if (!Integer.valueOf(2).equals(successor.getType()) || Objects.equals(successor.getId(), user.getId())) {
throw new IllegalArgumentException("接手账号必须是其他已启用店长");
}
for (UserShopBindingDO binding : bindings) {
UserShopBindingDO successorBinding = bindingMapper.selectOne(new LambdaQueryWrapper<UserShopBindingDO>()
.eq(UserShopBindingDO::getUserId, successor.getId())
.eq(UserShopBindingDO::getShopId, binding.getShopId())
.eq(UserShopBindingDO::getIsDelete, 0)
.last("limit 1"));
if (successorBinding == null) {
bindingMapper.update(null, new LambdaUpdateWrapper<UserShopBindingDO>()
.eq(UserShopBindingDO::getId, binding.getId())
.set(UserShopBindingDO::getUserId, successor.getId())
.set(UserShopBindingDO::getUpdateTime, LocalDateTime.now()));
} else {
bindingMapper.update(null, new LambdaUpdateWrapper<UserShopBindingDO>()
.eq(UserShopBindingDO::getId, binding.getId())
.set(UserShopBindingDO::getIsDelete, 1)
.set(UserShopBindingDO::getUpdateTime, LocalDateTime.now()));
}
}
List<UserShopRoleDO> roles = shopRoleMapper.selectList(new LambdaQueryWrapper<UserShopRoleDO>()
.eq(UserShopRoleDO::getUserId, user.getId()).eq(UserShopRoleDO::getIsDelete, 0));
for (UserShopRoleDO role : roles) {
UserShopRoleDO existing = shopRoleMapper.selectOne(new LambdaQueryWrapper<UserShopRoleDO>()
.eq(UserShopRoleDO::getUserId, successor.getId())
.eq(UserShopRoleDO::getShopId, role.getShopId())
.eq(UserShopRoleDO::getRoleId, role.getRoleId())
.eq(UserShopRoleDO::getIsDelete, 0)
.last("limit 1"));
if (existing == null) {
shopRoleMapper.update(null, new LambdaUpdateWrapper<UserShopRoleDO>()
.eq(UserShopRoleDO::getId, role.getId())
.set(UserShopRoleDO::getUserId, successor.getId())
.set(UserShopRoleDO::getUpdateTime, LocalDateTime.now()));
} else {
shopRoleMapper.update(null, new LambdaUpdateWrapper<UserShopRoleDO>()
.eq(UserShopRoleDO::getId, role.getId())
.set(UserShopRoleDO::getIsDelete, 1)
.set(UserShopRoleDO::getUpdateTime, LocalDateTime.now()));
}
}
return;
}
Set<Long> shopIds = bindings.stream().map(UserShopBindingDO::getShopId).collect(Collectors.toSet());
if (dto.getArchiveShopIds() == null || !dto.getArchiveShopIds().containsAll(shopIds)) {
throw new IllegalArgumentException("必须明确归档该账号关联的全部门店");
}
shopMapper.update(null, new LambdaUpdateWrapper<ShopDO>()
.in(ShopDO::getId, shopIds)
.set(ShopDO::getStatus, 0)
.set(ShopDO::getUpdateTime, LocalDateTime.now()));
bindingMapper.update(null, new LambdaUpdateWrapper<UserShopBindingDO>()
.eq(UserShopBindingDO::getUserId, user.getId()).eq(UserShopBindingDO::getIsDelete, 0)
.set(UserShopBindingDO::getIsDelete, 1).set(UserShopBindingDO::getUpdateTime, LocalDateTime.now()));
shopRoleMapper.update(null, new LambdaUpdateWrapper<UserShopRoleDO>()
.eq(UserShopRoleDO::getUserId, user.getId()).eq(UserShopRoleDO::getIsDelete, 0)
.set(UserShopRoleDO::getIsDelete, 1).set(UserShopRoleDO::getUpdateTime, LocalDateTime.now()));
}
private void anonymizeUser(UserDO user) {
Long userId = user.getId();
sessionService.revokeAllUserSessions(userId);
wechatBindingMapper.delete(new LambdaQueryWrapper<WechatMiniBindingDO>().eq(WechatMiniBindingDO::getUserId, userId));
relationMapper.update(null, new LambdaUpdateWrapper<UserRelationDO>()
.eq(UserRelationDO::getUserId, userId).eq(UserRelationDO::getIsDelete, 0)
.set(UserRelationDO::getIsDelete, 1).set(UserRelationDO::getUpdateTime, LocalDateTime.now()));
relationMapper.update(null, new LambdaUpdateWrapper<UserRelationDO>()
.eq(UserRelationDO::getParentUserId, userId).eq(UserRelationDO::getIsDelete, 0)
.set(UserRelationDO::getParentUserId, null).set(UserRelationDO::getUpdateTime, LocalDateTime.now()));
orderMapper.update(null, new LambdaUpdateWrapper<OrderDO>()
.eq(OrderDO::getUserId, userId)
.set(OrderDO::getUserId, null)
.set(OrderDO::getCustomerNameSnapshot, "已注销用户")
.set(OrderDO::getCustomerPhoneSnapshot, null)
.set(OrderDO::getCustomerPhoneSnapshotHash, null)
.set(OrderDO::getUpdateTime, LocalDateTime.now()));
consentMapper.update(null, new LambdaUpdateWrapper<com.xiaowang.jayucloud.salon.core.modules.user.entity.UserAgreementConsentDO>()
.eq(com.xiaowang.jayucloud.salon.core.modules.user.entity.UserAgreementConsentDO::getUserId, userId)
.set(com.xiaowang.jayucloud.salon.core.modules.user.entity.UserAgreementConsentDO::getUserId, null));
securityAuditLogMapper.update(null, new LambdaUpdateWrapper<com.xiaowang.jayucloud.salon.core.modules.security.entity.SecurityAuditLogDO>()
.eq(com.xiaowang.jayucloud.salon.core.modules.security.entity.SecurityAuditLogDO::getUserId, userId)
.set(com.xiaowang.jayucloud.salon.core.modules.security.entity.SecurityAuditLogDO::getUserId, null)
.set(com.xiaowang.jayucloud.salon.core.modules.security.entity.SecurityAuditLogDO::getAccount, "已注销用户"));
user.setNickname("已注销用户");
user.setAccount(null);
user.setAccountHash(null);
user.setPassword(null);
user.setPhone(null);
user.setPhoneHash(null);
user.setContactPhone(null);
user.setContactPhoneHash(null);
user.setPhoneVerified(0);
user.setEmail(null);
user.setEmailVerified(0);
user.setBirthday(null);
user.setWechatId(null);
user.setWechatQrCode(null);
user.setAvatar(null);
user.setSignature(null);
user.setShopId(null);
user.setStatus(0);
user.setIsDelete(1);
user.setUpdateTime(LocalDateTime.now());
userMapper.updateById(user);
}
private UserDO requireActiveUser(Long userId) {
UserDO user = userMapper.selectById(userId);
if (user == null || Integer.valueOf(1).equals(user.getIsDelete())) throw new IllegalStateException("账号不存在或已注销");
return user;
}
private AccountClosureRequestVO toVO(AccountClosureRequestDO request, UserDO user) {
AccountClosureRequestVO vo = new AccountClosureRequestVO();
vo.setId(request.getId());
vo.setUserId(request.getUserId());
vo.setNickname(user == null ? "已注销用户" : user.getNickname());
vo.setUserType(user == null ? null : user.getType());
vo.setStatus(request.getStatus());
vo.setRequestedAt(request.getRequestedAt());
vo.setProcessingTargetText("目标:15个工作日内完成,具体时长视门店移交或归档流程而定。");
if (user != null && Integer.valueOf(2).equals(user.getType())) {
List<UserShopBindingDO> bindings = bindingMapper.selectList(new LambdaQueryWrapper<UserShopBindingDO>()
.eq(UserShopBindingDO::getUserId, user.getId())
.eq(UserShopBindingDO::getIsDelete, 0)
.eq(UserShopBindingDO::getStatus, 1));
List<Long> shopIds = bindings.stream().map(UserShopBindingDO::getShopId).distinct().collect(Collectors.toList());
vo.setShopIds(shopIds);
vo.setShopNames(shopIds.isEmpty() ? List.of() : shopMapper.selectBatchIds(shopIds).stream().map(ShopDO::getShopName).collect(Collectors.toList()));
}
vo.setProcessedAt(request.getProcessedAt());
vo.setReviewerNote(request.getReviewerNote());
return vo;
}
}
@@ -0,0 +1,123 @@
package com.xiaowang.jayucloud.salon.core.modules.privacy.service.impl;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.xiaowang.jayucloud.salon.core.modules.product.entity.ProductDO;
import com.xiaowang.jayucloud.salon.core.modules.product.mapper.ProductMapper;
import com.xiaowang.jayucloud.salon.core.modules.content.entity.CommentDO;
import com.xiaowang.jayucloud.salon.core.modules.content.mapper.CommentMapper;
import com.xiaowang.jayucloud.salon.core.modules.privacy.entity.ContentModerationRecordDO;
import com.xiaowang.jayucloud.salon.core.modules.privacy.mapper.ContentModerationRecordMapper;
import com.xiaowang.jayucloud.salon.core.modules.privacy.moderation.ContentModerationProvider;
import com.xiaowang.jayucloud.salon.core.modules.privacy.moderation.ModerationOutcome;
import com.xiaowang.jayucloud.salon.core.modules.privacy.service.ContentModerationService;
import com.xiaowang.jayucloud.salon.core.modules.privacy.vo.ContentModerationResultVO;
import com.xiaowang.jayucloud.salon.core.modules.user.entity.UserDO;
import com.xiaowang.jayucloud.salon.core.modules.user.mapper.UserMapper;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.util.StringUtils;
import java.time.LocalDateTime;
import java.util.List;
@Service
@RequiredArgsConstructor
public class ContentModerationServiceImpl implements ContentModerationService {
private final ContentModerationProvider provider;
private final ContentModerationRecordMapper recordMapper;
private final ProductMapper productMapper;
private final CommentMapper commentMapper;
private final UserMapper userMapper;
private final ObjectMapper objectMapper;
@Override
@Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRES_NEW)
public ContentModerationResultVO assess(String contentType, Long businessId, Long userId, String content, String payloadJson) {
ModerationOutcome outcome;
try {
outcome = provider.review(contentType, content);
} catch (RuntimeException exception) {
outcome = new ModerationOutcome(ModerationOutcome.Status.RETRY, "PROVIDER_FAILURE", "内容审核服务暂不可用,内容已隔离等待重试");
}
ContentModerationRecordDO record = new ContentModerationRecordDO();
record.setContentType(contentType);
record.setBusinessId(businessId);
record.setUserId(userId);
record.setStatus(outcome.status().name());
record.setProvider(provider.providerName());
record.setResultCode(outcome.code());
record.setReason(outcome.reason());
record.setPayloadJson(outcome.status() == ModerationOutcome.Status.APPROVED ? null : payloadJson);
record.setAttemptCount(1);
recordMapper.insert(record);
ContentModerationResultVO result = new ContentModerationResultVO();
result.setRecordId(record.getId());
result.setStatus(outcome.status().name());
result.setReason(outcome.reason());
return result;
}
@Override
public List<ContentModerationRecordDO> listPending() {
return recordMapper.selectList(new LambdaQueryWrapper<ContentModerationRecordDO>()
.in(ContentModerationRecordDO::getStatus, "PENDING", "RETRY")
.orderByAsc(ContentModerationRecordDO::getCreateTime));
}
@Override
@Transactional(rollbackFor = Exception.class)
public boolean review(Long reviewerId, Long recordId, boolean approved, String reason) {
if (!StringUtils.hasText(reason)) throw new IllegalArgumentException("复核说明不能为空");
ContentModerationRecordDO record = recordMapper.selectById(recordId);
if (record == null || !("PENDING".equals(record.getStatus()) || "RETRY".equals(record.getStatus()))) {
throw new IllegalStateException("该内容已复核或不存在");
}
if (approved) applyApprovedPayload(record);
if ("COMMENT".equals(record.getContentType()) && record.getBusinessId() != null) {
CommentDO comment = commentMapper.selectById(record.getBusinessId());
if (comment != null && !Integer.valueOf(1).equals(comment.getIsDelete())) {
comment.setModerationStatus(approved ? "APPROVED" : "REJECTED");
comment.setUpdateTime(LocalDateTime.now());
commentMapper.updateById(comment);
}
}
record.setStatus(approved ? "APPROVED" : "REJECTED");
record.setReviewedBy(reviewerId);
record.setReviewedAt(LocalDateTime.now());
record.setReason(reason.trim());
record.setPayloadJson(null);
return recordMapper.updateById(record) > 0;
}
private void applyApprovedPayload(ContentModerationRecordDO record) {
if (!StringUtils.hasText(record.getPayloadJson())) return;
try {
JsonNode payload = objectMapper.readTree(record.getPayloadJson());
if ("PRODUCT".equals(record.getContentType()) && record.getBusinessId() != null) {
ProductDO product = productMapper.selectById(record.getBusinessId());
if (product != null && !Integer.valueOf(1).equals(product.getIsDelete())) {
product.setFrontVisible(payload.path("frontVisible").asInt(1));
product.setUpdateTime(LocalDateTime.now());
productMapper.updateById(product);
}
} else if (("USER_PROFILE".equals(record.getContentType()) || "USER_AVATAR".equals(record.getContentType()))
&& record.getUserId() != null) {
UserDO user = userMapper.selectById(record.getUserId());
if (user != null && !Integer.valueOf(1).equals(user.getIsDelete())) {
if (payload.hasNonNull("nickname")) user.setNickname(payload.path("nickname").asText());
if (payload.hasNonNull("signature")) user.setSignature(payload.path("signature").asText());
if (payload.hasNonNull("avatar")) user.setAvatar(payload.path("avatar").asText());
user.setUpdateTime(LocalDateTime.now());
userMapper.updateById(user);
}
}
} catch (Exception exception) {
throw new IllegalStateException("隔离内容载荷无法解析,未应用复核结果", exception);
}
}
}
@@ -0,0 +1,21 @@
package com.xiaowang.jayucloud.salon.core.modules.privacy.vo;
import lombok.Data;
import java.time.LocalDateTime;
import java.util.List;
@Data
public class AccountClosureRequestVO {
private Long id;
private Long userId;
private String nickname;
private Integer userType;
private List<Long> shopIds;
private List<String> shopNames;
private String status;
private LocalDateTime requestedAt;
private String processingTargetText;
private LocalDateTime processedAt;
private String reviewerNote;
}
@@ -0,0 +1,12 @@
package com.xiaowang.jayucloud.salon.core.modules.privacy.vo;
import lombok.AllArgsConstructor;
import lombok.Data;
@Data
@AllArgsConstructor
public class ClosureSuccessorManagerVO {
private Long id;
private String nickname;
private Long shopId;
}
@@ -0,0 +1,10 @@
package com.xiaowang.jayucloud.salon.core.modules.privacy.vo;
import lombok.Data;
@Data
public class ContentModerationResultVO {
private Long recordId;
private String status;
private String reason;
}
@@ -5,6 +5,8 @@ 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.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.xiaowang.jayucloud.salon.core.config.AppCacheProperties;
import com.xiaowang.jayucloud.salon.core.modules.product.dto.ProductDTO;
import com.xiaowang.jayucloud.salon.core.modules.marketing.entity.CouponDO;
@@ -24,8 +26,11 @@ import com.xiaowang.jayucloud.salon.core.modules.file.vo.ObjectStorageFileVO;
import com.xiaowang.jayucloud.salon.core.common.vo.PageResultVO;
import com.xiaowang.jayucloud.salon.core.modules.product.vo.ProductVO;
import com.xiaowang.jayucloud.salon.core.modules.product.vo.TagInfo;
import com.xiaowang.jayucloud.salon.core.modules.privacy.service.ContentModerationService;
import com.xiaowang.jayucloud.salon.core.modules.privacy.vo.ContentModerationResultVO;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import java.time.Duration;
@@ -113,6 +118,8 @@ public class ProductServiceImpl extends ServiceImpl<ProductMapper, ProductDO> im
* Variable `appCacheProperties`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls.
*/
private final AppCacheProperties appCacheProperties;
private final ContentModerationService contentModerationService;
private final ObjectMapper objectMapper;
@Override
/**
@@ -121,6 +128,7 @@ public class ProductServiceImpl extends ServiceImpl<ProductMapper, ProductDO> im
* @param productDTO parameter `productDTO` supplied by the caller
* @return Long result consumed by the caller or returned to the frontend
*/
@Transactional(rollbackFor = Exception.class)
public Long createProduct(ProductDTO productDTO) {
validateBookableArtists(productDTO.getShopId(), productDTO.getBookableArtists());
validateAvailableCoupons(productDTO.getShopId(), productDTO.getAvailableCoupons());
@@ -138,10 +146,14 @@ public class ProductServiceImpl extends ServiceImpl<ProductMapper, ProductDO> im
productDO.setApproximateDuration(productDTO.getApproximateDuration());
productDO.setBookableArtists(bookableArtistSupport.filterValidBookableArtists(productDTO.getShopId(), productDTO.getBookableArtists()));
productDO.setAvailableCoupons(productDTO.getAvailableCoupons());
productDO.setFrontVisible(resolveFrontVisible(productDTO.getFrontVisible()));
Integer requestedFrontVisible = resolveFrontVisible(productDTO.getFrontVisible());
productDO.setFrontVisible(0);
productDO.setSourceType(resolveSourceType(productDTO.getSourceType()));
productDO.setIsDelete(0);
productMapper.insert(productDO);
ContentModerationResultVO moderation = assessProduct(productDO, requestedFrontVisible);
productDO.setFrontVisible("APPROVED".equals(moderation.getStatus()) ? requestedFrontVisible : 0);
productMapper.updateById(productDO);
evictPublicProductCaches(productDO.getId());
return productDO.getId();
}
@@ -154,6 +166,7 @@ public class ProductServiceImpl extends ServiceImpl<ProductMapper, ProductDO> im
* @param productDTO parameter `productDTO` supplied by the caller
* @return boolean result consumed by the caller or returned to the frontend
*/
@Transactional(rollbackFor = Exception.class)
public boolean updateProduct(Long id, ProductDTO productDTO) {
ProductDO productDO = productMapper.selectById(id);
if (productDO == null) {
@@ -178,10 +191,14 @@ public class ProductServiceImpl extends ServiceImpl<ProductMapper, ProductDO> im
productDO.setApproximateDuration(productDTO.getApproximateDuration());
productDO.setBookableArtists(bookableArtistSupport.filterValidBookableArtists(productDTO.getShopId(), productDTO.getBookableArtists()));
productDO.setAvailableCoupons(productDTO.getAvailableCoupons());
productDO.setFrontVisible(resolveUpdateFrontVisible(productDO.getFrontVisible(), productDTO.getFrontVisible()));
Integer requestedFrontVisible = resolveUpdateFrontVisible(productDO.getFrontVisible(), productDTO.getFrontVisible());
productDO.setFrontVisible(0);
productDO.setSourceType(resolveUpdateSourceType(productDO.getSourceType(), productDTO.getSourceType()));
boolean updated = productMapper.updateById(productDO) > 0;
if (updated) {
ContentModerationResultVO moderation = assessProduct(productDO, requestedFrontVisible);
productDO.setFrontVisible("APPROVED".equals(moderation.getStatus()) ? requestedFrontVisible : 0);
productMapper.updateById(productDO);
/**
* Run business method `evictPublicProductCaches`.
* Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result.
@@ -193,6 +210,22 @@ public class ProductServiceImpl extends ServiceImpl<ProductMapper, ProductDO> im
return updated;
}
private ContentModerationResultVO assessProduct(ProductDO product, Integer requestedFrontVisible) {
String content = String.join("\n", List.of(
safe(product.getTitle()), safe(product.getDescription()), safe(product.getTargetAudience()),
safe(product.getPrecautions()), safe(product.getTags()), safe(product.getImageFileIds())));
try {
String payload = objectMapper.writeValueAsString(java.util.Map.of("frontVisible", requestedFrontVisible == null ? 1 : requestedFrontVisible));
return contentModerationService.assess("PRODUCT", product.getId(), null, content, payload);
} catch (JsonProcessingException exception) {
throw new IllegalStateException("作品审核内容序列化失败", exception);
}
}
private String safe(String value) {
return value == null ? "" : value;
}
@Override
/**
* Delete, revoke, or logically remove a record.
@@ -9,6 +9,7 @@ import com.xiaowang.jayucloud.salon.core.modules.shop.entity.ShopDO;
import com.xiaowang.jayucloud.salon.core.modules.shop.mapper.ShopMapper;
import com.xiaowang.jayucloud.salon.core.modules.user.entity.UserDO;
import com.xiaowang.jayucloud.salon.core.modules.user.mapper.UserMapper;
import com.xiaowang.jayucloud.salon.core.support.privacy.PhoneCrypto;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@@ -38,7 +39,14 @@ public class WorkbenchRegistrationController {
@GetMapping("/register/status")
public Result<WorkbenchRegistrationStatusVO> status(@RequestParam String phone) {
UserDO user = userMapper.selectOne(Wrappers.lambdaQuery(UserDO.class).eq(UserDO::getPhone, phone).eq(UserDO::getIsDelete, 0).last("limit 1"));
String normalizedPhone = phone == null ? "" : phone.trim();
UserDO user = userMapper.selectOne(Wrappers.lambdaQuery(UserDO.class)
.eq(UserDO::getPhoneHash, PhoneCrypto.current().index(normalizedPhone))
.eq(UserDO::getIsDelete, 0).last("limit 1"));
if (user == null) {
Long legacyId = userMapper.findLegacyIdByPhone(normalizedPhone);
user = legacyId == null ? null : userMapper.selectById(legacyId);
}
if (user == null) {
throw new IllegalArgumentException("未找到注册申请");
}
@@ -60,13 +60,6 @@ public class SecurityAuditLogDO extends BaseEntity {
*/
private String ipAddress;
@TableField("device_id")
/**
* Purpose: deviceId supports SecurityAuditLogDO.java by holding or executing the device id business role.
* Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state.
*/
private String deviceId;
@TableField("operate_time")
/**
* Purpose: operateTime supports SecurityAuditLogDO.java by holding or executing the operate time business role.
@@ -5,7 +5,6 @@ import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xiaowang.jayucloud.salon.core.modules.security.entity.SecurityAuditLogDO;
import com.xiaowang.jayucloud.salon.core.modules.security.mapper.SecurityAuditLogMapper;
import com.xiaowang.jayucloud.salon.core.modules.security.service.SecurityAuditLogService;
import com.xiaowang.jayucloud.salon.core.support.security.RequestThrottleService;
import com.xiaowang.jayucloud.salon.core.common.vo.PageResultVO;
import com.xiaowang.jayucloud.salon.core.modules.security.vo.SecurityAuditLogVO;
import lombok.RequiredArgsConstructor;
@@ -38,12 +37,11 @@ public class SecurityAuditLogServiceImpl implements SecurityAuditLogService {
try {
SecurityAuditLogDO log = new SecurityAuditLogDO();
log.setUserId(userId);
log.setAccount(limit(account, 80));
log.setAccount(maskPhoneAccount(account));
log.setAction(limit(action, 80));
log.setResult(limit(result, 20));
log.setReason(limit(reason, 500));
log.setIpAddress(limit(resolveClientIp(request), 80));
log.setDeviceId(limit(request == null ? null : request.getHeader(RequestThrottleService.DEVICE_ID_HEADER), 120));
log.setOperateTime(LocalDateTime.now());
auditLogMapper.insert(log);
} catch (Exception ignored) {
@@ -101,7 +99,6 @@ public class SecurityAuditLogServiceImpl implements SecurityAuditLogService {
vo.setResult(log.getResult());
vo.setReason(log.getReason());
vo.setIpAddress(log.getIpAddress());
vo.setDeviceId(log.getDeviceId());
vo.setOperateTime(log.getOperateTime());
return vo;
}
@@ -132,4 +129,12 @@ public class SecurityAuditLogServiceImpl implements SecurityAuditLogService {
}
return value.substring(0, max);
}
private String maskPhoneAccount(String value) {
if (value == null) return null;
String normalized = value.trim();
return normalized.matches("1[3-9]\\d{9}")
? normalized.substring(0, 3) + "****" + normalized.substring(7)
: limit(normalized, 80);
}
}
@@ -46,11 +46,6 @@ public class SecurityAuditLogVO {
* Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state.
*/
private String ipAddress;
/**
* Purpose: deviceId supports SecurityAuditLogVO.java by holding or executing the device id business role.
* Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state.
*/
private String deviceId;
/**
* Purpose: operateTime supports SecurityAuditLogVO.java by holding or executing the operate time business role.
* Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state.
@@ -201,8 +201,7 @@ public class LegalAgreementServiceImpl implements LegalAgreementService {
version,
entry,
clientType,
resolveClientIp(httpRequest),
httpRequest == null ? null : httpRequest.getHeader(RequestThrottleService.DEVICE_ID_HEADER)
resolveClientIp(httpRequest)
));
}
@@ -225,7 +224,7 @@ public class LegalAgreementServiceImpl implements LegalAgreementService {
* Purpose: upsertConsent supports LegalAgreementServiceImpl.java by holding or executing the upsert consent business role.
* Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state.
*/
private void upsertConsent(Long userId, String type, String version, String entry, String clientType, String ip, String deviceId) {
private void upsertConsent(Long userId, String type, String version, String entry, String clientType, String ip) {
if (!StringUtils.hasText(version)) {
return;
}
@@ -240,7 +239,6 @@ public class LegalAgreementServiceImpl implements LegalAgreementService {
consent.setEntry(entry);
consent.setClientType(clientType);
consent.setIpAddress(ip);
consent.setDeviceId(deviceId);
consent.setConsentTime(LocalDateTime.now());
if (existing == null) {
consentMapper.insert(consent);
@@ -23,8 +23,10 @@ import com.xiaowang.jayucloud.salon.core.modules.security.service.ShopRoleServic
import com.xiaowang.jayucloud.salon.core.modules.auth.service.VerificationCodeService;
import com.xiaowang.jayucloud.salon.core.modules.integration.service.WechatMiniAuthService;
import com.xiaowang.jayucloud.salon.core.modules.system.service.LegalAgreementService;
import com.xiaowang.jayucloud.salon.core.modules.privacy.service.AccountClosureService;
import com.xiaowang.jayucloud.salon.core.modules.security.service.SecurityAuditLogService;
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.file.support.ObjectStorageUrlSupport;
import com.xiaowang.jayucloud.salon.core.support.security.RequestThrottleService;
import com.xiaowang.jayucloud.salon.core.utils.AccountValidationUtils;
@@ -124,6 +126,7 @@ 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;
private final AccountClosureService accountClosureService;
/**
* 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.
@@ -343,10 +346,7 @@ public class UserController {
*/
public Result<AvailabilityVO> checkAccountAvailability(@PathVariable String account) {
String normalizedAccount = AccountValidationUtils.requireValidAccount(account);
UserDO userDO = userMapper.selectOne(
com.baomidou.mybatisplus.core.toolkit.Wrappers.lambdaQuery(UserDO.class)
.eq(UserDO::getAccount, normalizedAccount)
);
UserDO userDO = findUserByAccount(normalizedAccount);
boolean available = userDO == null || Integer.valueOf(1).equals(userDO.getIsDelete());
String message = available ? "账号可用" : "账号已被注册";
return Result.success(new AvailabilityVO(available, message));
@@ -361,12 +361,7 @@ public class UserController {
*/
public Result<LoginAccountAvailabilityVO> checkLoginAccountAvailability(@PathVariable String account) {
String normalizedAccount = AccountValidationUtils.requireValidAccount(account);
UserDO userDO = userMapper.selectOne(
com.baomidou.mybatisplus.core.toolkit.Wrappers.lambdaQuery(UserDO.class)
.eq(UserDO::getAccount, normalizedAccount)
.eq(UserDO::getIsDelete, 0)
.last("limit 1")
);
UserDO userDO = findUserByAccount(normalizedAccount);
boolean exists = userDO != null;
String nickname = exists ? userDO.getNickname() : null;
String message = exists
@@ -405,11 +400,14 @@ public class UserController {
* @return Result<AvailabilityVO> result consumed by the caller or returned to the frontend
*/
public Result<AvailabilityVO> checkPhoneAvailability(@PathVariable String phone) {
UserDO userDO = userMapper.selectOne(
com.baomidou.mybatisplus.core.toolkit.Wrappers.lambdaQuery(UserDO.class)
.eq(UserDO::getPhone, phone)
.eq(UserDO::getIsDelete, 0)
);
String normalizedPhone = phone == null ? "" : phone.trim();
UserDO userDO = userMapper.selectOne(com.baomidou.mybatisplus.core.toolkit.Wrappers.lambdaQuery(UserDO.class)
.eq(UserDO::getPhoneHash, PhoneCrypto.current().index(normalizedPhone))
.eq(UserDO::getIsDelete, 0));
if (userDO == null) {
Long legacyId = userMapper.findLegacyIdByPhone(normalizedPhone);
userDO = legacyId == null ? null : userMapper.selectById(legacyId);
}
boolean available = userDO == null;
String message = available ? "手机号可用" : "该手机号已被注册";
return Result.success(new AvailabilityVO(available, message));
@@ -473,13 +471,18 @@ public class UserController {
* @param requestDTO parameter `requestDTO` supplied by the caller
* @return Result<WechatMiniLoginResultVO> result consumed by the caller or returned to the frontend
*/
public Result<WechatMiniLoginResultVO> wechatMiniAutoLogin(@Valid @RequestBody WechatMiniAutoLoginRequestDTO requestDTO) {
return Result.success(wechatMiniAuthService.autoLogin(requestDTO));
public Result<WechatMiniLoginResultVO> wechatMiniAutoLogin(HttpServletRequest request,
@Valid @RequestBody WechatMiniAutoLoginRequestDTO requestDTO) {
legalAgreementService.requireAccepted(requestDTO);
WechatMiniLoginResultVO result = wechatMiniAuthService.autoLogin(requestDTO);
recordWechatConsentIfLoggedIn(result, requestDTO, "WECHAT_MINI_AUTO_LOGIN", request);
return Result.success(result);
}
@PostMapping("/wechat-mini/status")
@OperationGuard(action = "wechat-mini-status", ttlSeconds = 2, message = "状态检测中,请稍后重试")
public Result<WechatMiniLoginResultVO> wechatMiniStatus(@Valid @RequestBody WechatMiniAutoLoginRequestDTO requestDTO) {
legalAgreementService.requireAccepted(requestDTO);
return Result.success(wechatMiniAuthService.status(requestDTO));
}
@@ -553,12 +556,7 @@ public class UserController {
legalAgreementService.requireAccepted(registerRequestDTO);
try {
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::getIsDelete, 0)
.last("limit 1")
);
UserDO userDO = findUserByAccount(AccountValidationUtils.requireValidAccount(registerRequestDTO.getAccount()));
if (userDO != null) {
legalAgreementService.recordConsent(userDO.getId(), registerRequestDTO, "USER_REGISTER", request);
securityAuditLogService.record(userDO.getId(), userDO.getAccount(), "USER_REGISTER", "SUCCESS", null, request);
@@ -616,6 +614,30 @@ public class UserController {
return Result.success(true);
}
@PostMapping("/send-current-password-code")
@OperationGuard(action = "send-current-password-code", ttlSeconds = 60, message = "验证码已发送,请勿重复操作")
public Result<Boolean> sendCurrentPasswordVerificationCode(HttpServletRequest request) {
Long userId = (Long) request.getAttribute("userId");
if (userId == null) {
throw new RuntimeException("请登录后操作");
}
UserDO user = userMapper.selectById(userId);
if (user == null || Integer.valueOf(1).equals(user.getIsDelete())
|| (user.getStatus() != null && !Integer.valueOf(1).equals(user.getStatus()))
|| !org.springframework.util.StringUtils.hasText(user.getPhone())
|| !Integer.valueOf(1).equals(user.getPhoneVerified())) {
throw new RuntimeException("当前账号未绑定已验证手机号");
}
String phone = user.getPhone();
requestThrottleService.checkSendCode(request, phone);
if (!verificationCodeService.canResend(phone)) {
throw new RuntimeException("验证码发送过于频繁,请1分钟后再试");
}
verificationCodeService.sendVerificationCode(phone, "USER_CHANGE_PASSWORD_SMS_CODE");
return Result.success(true);
}
/**
* 通过手机号验证码重置密码
*
@@ -715,6 +737,20 @@ public class UserController {
return Result.success(success);
}
@PostMapping("/unbind-phone")
@OperationGuard(action = "user-unbind-phone", ttlSeconds = 10, message = "手机号解绑处理中,请勿重复提交")
public Result<Boolean> unbindPhone(HttpServletRequest request, @RequestBody BindPhoneRequestDTO requestDTO) {
Long userId = (Long) request.getAttribute("userId");
return Result.success(userService.unbindPhone(userId, requestDTO == null ? null : requestDTO.getVerificationCode()));
}
@PostMapping("/unbind-phone/send-code")
@OperationGuard(action = "user-unbind-phone-send-code", ttlSeconds = 60, message = "验证码已发送,请勿重复操作")
public Result<Boolean> sendUnbindPhoneCode(HttpServletRequest request) {
Long userId = (Long) request.getAttribute("userId");
return Result.success(userService.sendUnbindPhoneCode(userId));
}
@PostMapping("/wechat-mini/bind-phone")
@OperationGuard(action = "wechat-mini-bind-phone", ttlSeconds = 10, message = "手机号绑定处理中,请勿重复提交")
public Result<Boolean> bindWechatMiniPhone(HttpServletRequest request,
@@ -981,8 +1017,8 @@ public class UserController {
return Result.error("管理员账号无法注销");
}
boolean success = userService.deleteUser(userId);
return Result.success(success);
accountClosureService.request(userId);
return Result.success(true);
}
/**
@@ -1029,6 +1065,22 @@ public class UserController {
return sanitized;
}
private UserDO findUserByAccount(String account) {
String normalized = account == null ? "" : account.trim();
boolean phoneAccount = PhoneCrypto.current().isMobilePhone(normalized);
com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper<UserDO> query =
com.baomidou.mybatisplus.core.toolkit.Wrappers.lambdaQuery(UserDO.class)
.eq(UserDO::getIsDelete, 0)
.last("limit 1");
query.eq(UserDO::getAccountHash, PhoneCrypto.current().index(normalized));
UserDO user = userMapper.selectOne(query);
if (user == null) {
Long legacyId = userMapper.findLegacyIdByAccount(normalized);
user = legacyId == null ? null : userMapper.selectById(legacyId);
}
return user;
}
@Data
/**
* Purpose: PasswordDTO supports UserController.java by holding or executing the password dto business role.
@@ -59,13 +59,6 @@ public class UserAgreementConsentDO extends BaseEntity {
*/
private String ipAddress;
@TableField("device_id")
/**
* Purpose: deviceId supports UserAgreementConsentDO.java by holding or executing the device id business role.
* Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state.
*/
private String deviceId;
@TableField("consent_time")
/**
* Purpose: consentTime supports UserAgreementConsentDO.java by holding or executing the consent time business role.
@@ -5,6 +5,9 @@ import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableLogic;
import com.baomidou.mybatisplus.annotation.TableName;
import com.baomidou.mybatisplus.annotation.FieldFill;
import com.xiaowang.jayucloud.salon.core.support.privacy.PhoneEncryptionTypeHandler;
import com.xiaowang.jayucloud.salon.core.support.privacy.AccountPhoneTypeHandler;
import lombok.Getter;
import lombok.Setter;
import lombok.EqualsAndHashCode;
@@ -22,7 +25,7 @@ import com.xiaowang.jayucloud.salon.core.common.entity.BaseEntity;
@Getter
@Setter
@EqualsAndHashCode(callSuper = true)
@TableName("t_user")
@TableName(value = "t_user", autoResultMap = true)
public class UserDO extends BaseEntity {
/**
@@ -46,21 +49,30 @@ public class UserDO extends BaseEntity {
/**
* 用户账号(登录用)
*/
@TableField("account")
@TableField(value = "account", typeHandler = AccountPhoneTypeHandler.class)
private String account;
@TableField(value = "account_hash", fill = FieldFill.INSERT_UPDATE)
private String accountHash;
/**
* 手机号
*/
@TableField("phone")
@TableField(value = "phone", typeHandler = PhoneEncryptionTypeHandler.class)
private String phone;
@TableField(value = "phone_hash", fill = FieldFill.INSERT_UPDATE)
private String phoneHash;
/**
* 联系电话
*/
@TableField("contact_phone")
@TableField(value = "contact_phone", typeHandler = PhoneEncryptionTypeHandler.class)
private String contactPhone;
@TableField(value = "contact_phone_hash", fill = FieldFill.INSERT_UPDATE)
private String contactPhoneHash;
/**
* 生日
*/
@@ -2,6 +2,10 @@ package com.xiaowang.jayucloud.salon.core.modules.user.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.xiaowang.jayucloud.salon.core.modules.user.entity.UserDO;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import java.util.List;
/**
* 系统用户信息表 Mapper
@@ -11,4 +15,16 @@ import com.xiaowang.jayucloud.salon.core.modules.user.entity.UserDO;
* @date 2026-02-13
*/
public interface UserMapper extends BaseMapper<UserDO> {
@Select("SELECT id FROM t_user WHERE account = #{account} AND account_hash IS NULL AND is_delete = 0 LIMIT 1")
Long findLegacyIdByAccount(@Param("account") String account);
@Select("SELECT id FROM t_user WHERE phone = #{phone} AND phone_hash IS NULL AND is_delete = 0 LIMIT 1")
Long findLegacyIdByPhone(@Param("phone") String phone);
@Select("SELECT id FROM t_user WHERE contact_phone = #{phone} AND contact_phone_hash IS NULL AND is_delete = 0 LIMIT 1")
Long findLegacyIdByContactPhone(@Param("phone") String phone);
@Select("SELECT id FROM t_user WHERE contact_phone = #{phone} AND contact_phone_hash IS NULL AND is_delete = 0")
List<Long> findLegacyIdsByContactPhone(@Param("phone") String phone);
}
@@ -241,6 +241,10 @@ public interface UserService extends IService<UserDO> {
*/
boolean bindPhone(Long userId, BindPhoneRequestDTO bindPhoneRequestDTO);
boolean unbindPhone(Long userId, String verificationCode);
boolean sendUnbindPhoneCode(Long userId);
/**
* Run business method `bindEmail`.
* Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result.
@@ -38,10 +38,15 @@ import com.xiaowang.jayucloud.salon.core.modules.file.support.ObjectStorageUrlSu
import com.xiaowang.jayucloud.salon.core.modules.security.support.PermissionCatalog;
import com.xiaowang.jayucloud.salon.core.support.security.UserSessionService;
import com.xiaowang.jayucloud.salon.core.support.id.TimeOrderedSnowflakeIdGenerator;
import com.xiaowang.jayucloud.salon.core.support.privacy.PhoneCrypto;
import com.xiaowang.jayucloud.salon.core.modules.security.support.PermissionPolicy;
import com.xiaowang.jayucloud.salon.core.support.RequestShopContext;
import com.xiaowang.jayucloud.salon.core.modules.shop.support.UserShopBindingSupport;
import com.xiaowang.jayucloud.salon.core.modules.user.support.UserProfileFieldSupport;
import com.xiaowang.jayucloud.salon.core.modules.privacy.service.ContentModerationService;
import com.xiaowang.jayucloud.salon.core.modules.privacy.vo.ContentModerationResultVO;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.xiaowang.jayucloud.salon.core.utils.AccountValidationUtils;
import com.xiaowang.jayucloud.salon.core.utils.JwtUtil;
import com.xiaowang.jayucloud.salon.core.modules.auth.vo.LoginShopSelectionVO;
@@ -134,6 +139,9 @@ public class UserServiceImpl extends ServiceImpl<UserMapper, UserDO> implements
* Variable `userMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls.
*/
private final UserMapper userMapper;
private final PhoneCrypto phoneCrypto;
private final ContentModerationService contentModerationService;
private final ObjectMapper objectMapper;
private final ShopMapper shopMapper;
/**
* Variable `jwtUtil`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls.
@@ -363,11 +371,7 @@ public class UserServiceImpl extends ServiceImpl<UserMapper, UserDO> implements
private Long createUserInternal(UserDTO userDTO, boolean allowMissingCustomerPhone) {
String validatedAccount = AccountValidationUtils.requireValidAccount(userDTO.getAccount());
// 检查账号是否已存在
UserDO existingUser = userMapper.selectOne(
Wrappers.lambdaQuery(UserDO.class)
.eq(UserDO::getAccount, validatedAccount)
.eq(UserDO::getIsDelete, 0)
);
UserDO existingUser = findUserByAccount(validatedAccount);
if (existingUser != null) {
/**
* Run business method `RuntimeException`.
@@ -508,8 +512,7 @@ public class UserServiceImpl extends ServiceImpl<UserMapper, UserDO> implements
.eq(UserDO::getIsDelete, 0);
if (StringUtils.hasText(phone)) {
String normalizedPhone = phone.trim();
wrapper.and(query -> query.eq(UserDO::getPhone, normalizedPhone)
.or().eq(UserDO::getContactPhone, normalizedPhone));
addPhoneMatch(wrapper, normalizedPhone);
}
if (shopId != null && shopId > 0) {
List<Long> shopUserIds = userShopBindingSupport.listUserIdsByShopId(shopId, true);
@@ -524,9 +527,9 @@ public class UserServiceImpl extends ServiceImpl<UserMapper, UserDO> implements
UserVO customer = new UserVO();
customer.setId(user.getId());
customer.setNickname(user.getNickname());
customer.setAccount(user.getAccount());
customer.setPhone(user.getPhone());
customer.setContactPhone(user.getContactPhone());
customer.setAccount(phoneCrypto.mask(user.getAccount()));
customer.setPhone(phoneCrypto.mask(user.getPhone()));
customer.setContactPhone(phoneCrypto.mask(user.getContactPhone()));
customer.setAvatar(resolveAccessibleAvatar(user.getAvatar()));
return customer;
}).collect(Collectors.toList());
@@ -594,11 +597,8 @@ public class UserServiceImpl extends ServiceImpl<UserMapper, UserDO> implements
// 更新账号(如果提供且变更)
String normalizedAccount = AccountValidationUtils.validateOptionalAccount(userDTO.getAccount());
if (normalizedAccount != null && !normalizedAccount.equals(userDO.getAccount())) {
UserDO existingUser = userMapper.selectOne(
Wrappers.lambdaQuery(UserDO.class)
.eq(UserDO::getAccount, normalizedAccount)
.eq(UserDO::getIsDelete, 0)
);
UserDO existingUser = findUserByAccount(normalizedAccount);
if (existingUser != null && Objects.equals(existingUser.getId(), id)) existingUser = null;
if (existingUser != null) {
/**
* Run business method `RuntimeException`.
@@ -721,7 +721,11 @@ public class UserServiceImpl extends ServiceImpl<UserMapper, UserDO> implements
.eq(UserDO::getId, id)
.eq(UserDO::getIsDelete, 0)
.set(UserDO::getAccount, buildDeletedAccount(userDO))
.set(UserDO::getPhone, buildDeletedPhone(userDO))
.set(UserDO::getPhone, null)
.set(UserDO::getContactPhone, null)
.set(UserDO::getPhoneHash, null)
.set(UserDO::getContactPhoneHash, null)
.set(UserDO::getAccountHash, null)
.set(UserDO::getStatus, 0)
.set(UserDO::getIsDelete, 1)
.set(UserDO::getUpdateTime, now)
@@ -809,11 +813,7 @@ public class UserServiceImpl extends ServiceImpl<UserMapper, UserDO> implements
@Override
public UserVO getUserByAccount(String account) {
String normalizedAccount = AccountValidationUtils.requireValidAccount(account);
UserDO userDO = userMapper.selectOne(
Wrappers.lambdaQuery(UserDO.class)
.eq(UserDO::getAccount, normalizedAccount)
.eq(UserDO::getIsDelete, 0)
);
UserDO userDO = findUserByAccount(normalizedAccount);
if (userDO == null || Integer.valueOf(1).equals(userDO.getIsDelete())) {
return null;
}
@@ -853,10 +853,10 @@ public class UserServiceImpl extends ServiceImpl<UserMapper, UserDO> 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.setAccount(phoneCrypto.mask(userDO.getAccount()));
userVO.setPhone(phoneCrypto.mask(userDO.getPhone()));
userVO.setPhoneVerified(userDO.getPhoneVerified());
userVO.setContactPhone(userDO.getContactPhone());
userVO.setContactPhone(phoneCrypto.mask(userDO.getContactPhone()));
userVO.setBirthday(userDO.getBirthday());
userVO.setWechatId(userDO.getWechatId());
userVO.setWechatQrCode(resolveAccessibleProfileImage(userDO.getWechatQrCode()));
@@ -930,12 +930,7 @@ public class UserServiceImpl extends ServiceImpl<UserMapper, UserDO> implements
}
AccountValidationUtils.ensureValidAccountFormat(normalizedAccount);
UserDO userDO = userMapper.selectOne(
Wrappers.lambdaQuery(UserDO.class)
.eq(UserDO::getAccount, normalizedAccount)
.eq(UserDO::getIsDelete, 0)
.last("limit 1")
);
UserDO userDO = findUserByAccount(normalizedAccount);
if (userDO == null) {
return buildLoginShopSelection(List.of(), false, "该账号不存在");
}
@@ -980,12 +975,7 @@ public class UserServiceImpl extends ServiceImpl<UserMapper, UserDO> implements
return buildLoginShopSelection(List.of(), false, "请输入手机号后再选择店铺");
}
UserDO userDO = userMapper.selectOne(
Wrappers.lambdaQuery(UserDO.class)
.eq(UserDO::getPhone, normalizedPhone)
.eq(UserDO::getIsDelete, 0)
.last("limit 1")
);
UserDO userDO = findUserByPhone(normalizedPhone);
if (userDO == null) {
return buildLoginShopSelection(
userShopBindingSupport.listAllActiveShopOptions(),
@@ -1035,12 +1025,7 @@ public class UserServiceImpl extends ServiceImpl<UserMapper, UserDO> implements
}
AccountValidationUtils.ensureValidAccountFormat(normalizedAccount);
UserDO userDO = userMapper.selectOne(
Wrappers.lambdaQuery(UserDO.class)
.eq(UserDO::getAccount, normalizedAccount)
.eq(UserDO::getIsDelete, 0)
.last("limit 1")
);
UserDO userDO = findUserByAccount(normalizedAccount);
if (userDO == null) {
return buildLoginShopSelection(List.of(), false, "该账号不存在");
}
@@ -1083,10 +1068,7 @@ public class UserServiceImpl extends ServiceImpl<UserMapper, UserDO> implements
*/
public LoginResponseVO login(LoginRequestDTO loginRequestDTO) {
String normalizedAccount = AccountValidationUtils.requireValidAccount(loginRequestDTO.getAccount());
UserDO userDO = userMapper.selectOne(
Wrappers.lambdaQuery(UserDO.class)
.eq(UserDO::getAccount, normalizedAccount)
);
UserDO userDO = findUserByAccount(normalizedAccount);
/**
* Run business method `assertLoginAccountAvailable`.
@@ -1157,11 +1139,7 @@ public class UserServiceImpl extends ServiceImpl<UserMapper, UserDO> implements
private LoginResponseVO phoneLoginByVerifiedPhone(String phone, Long shopId, boolean rememberMe) {
String normalizedPhone = normalizeVerifiedPhone(phone);
UserDO userDO = userMapper.selectOne(
Wrappers.lambdaQuery(UserDO.class)
.eq(UserDO::getPhone, normalizedPhone)
.eq(UserDO::getIsDelete, 0)
);
UserDO userDO = findUserByPhone(normalizedPhone);
if (userDO == null) {
return buildRegistrationRequiredResponse(normalizedPhone, null, "PHONE_NOT_REGISTERED");
@@ -1218,12 +1196,7 @@ public class UserServiceImpl extends ServiceImpl<UserMapper, UserDO> implements
* @return LoginResponseVO result consumed by the caller or returned to the frontend
*/
public LoginResponseVO loginByVerifiedPhone(String phone, Long shopId) {
UserDO userDO = userMapper.selectOne(
Wrappers.lambdaQuery(UserDO.class)
.eq(UserDO::getPhone, phone)
.eq(UserDO::getIsDelete, 0)
.last("limit 1")
);
UserDO userDO = findUserByPhone(phone);
if (userDO == null) {
if (shopId == null || shopId == 0) {
@@ -1331,10 +1304,7 @@ public class UserServiceImpl extends ServiceImpl<UserMapper, UserDO> implements
*/
public LoginResponseVO adminLogin(LoginRequestDTO loginRequestDTO) {
String normalizedAccount = AccountValidationUtils.requireValidAccount(loginRequestDTO.getAccount());
UserDO userDO = userMapper.selectOne(
Wrappers.lambdaQuery(UserDO.class)
.eq(UserDO::getAccount, normalizedAccount)
);
UserDO userDO = findUserByAccount(normalizedAccount);
/**
* Run business method `assertLoginAccountAvailable`.
@@ -1540,10 +1510,7 @@ public class UserServiceImpl extends ServiceImpl<UserMapper, UserDO> implements
throw new RuntimeException("验证码错误或已过期");
}
UserDO existingUser = userMapper.selectOne(
Wrappers.lambdaQuery(UserDO.class)
.eq(UserDO::getAccount, validatedAccount)
);
UserDO existingUser = findUserByAccount(validatedAccount);
if (existingUser != null) {
if (existingUser.getIsDelete() == 0) {
@@ -1563,11 +1530,7 @@ public class UserServiceImpl extends ServiceImpl<UserMapper, UserDO> implements
}
}
UserDO existingPhoneUser = userMapper.selectOne(
Wrappers.lambdaQuery(UserDO.class)
.eq(UserDO::getPhone, registerRequestDTO.getPhone())
.eq(UserDO::getIsDelete, 0)
);
UserDO existingPhoneUser = findUserByPhone(registerRequestDTO.getPhone());
if (existingPhoneUser != null) {
/**
@@ -1633,12 +1596,7 @@ public class UserServiceImpl extends ServiceImpl<UserMapper, UserDO> implements
throw new RuntimeException("店铺名称不能为空");
}
UserDO existingUser = userMapper.selectOne(
Wrappers.lambdaQuery(UserDO.class)
.eq(UserDO::getAccount, phone)
.eq(UserDO::getIsDelete, 0)
.last("limit 1")
);
UserDO existingUser = findUserByAccount(phone);
if (existingUser != null) {
throw new RuntimeException("该手机号已注册");
}
@@ -1782,6 +1740,19 @@ public class UserServiceImpl extends ServiceImpl<UserMapper, UserDO> implements
*/
assertUserAvailable(userDO);
if (userDTO.getNickname() != null || userDTO.getSignature() != null
|| (userDTO.getAvatar() != null && !userDTO.getAvatar().isEmpty())) {
Map<String, String> content = new java.util.LinkedHashMap<>();
content.put("nickname", userDTO.getNickname());
content.put("signature", userDTO.getSignature());
content.put("avatar", userDTO.getAvatar() == null || userDTO.getAvatar().isEmpty()
? null : normalizeStoredAvatar(userDTO.getAvatar()));
String serialized = serializeModerationPayload(content);
ContentModerationResultVO moderation = contentModerationService.assess("USER_PROFILE", userId, userId,
String.join("\n", content.values().stream().filter(Objects::nonNull).toList()), serialized);
requireApprovedContent(moderation);
}
if (userDTO.getNickname() != null) {
userDO.setNickname(userDTO.getNickname());
}
@@ -1990,10 +1961,15 @@ public class UserServiceImpl extends ServiceImpl<UserMapper, UserDO> 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));
wrapper.and(w -> {
w.like(UserDO::getAccount, keyword).or().like(UserDO::getNickname, keyword);
if (phoneCrypto.isMobilePhone(keyword.trim())) {
String hash = phoneCrypto.index(keyword.trim());
w.or().eq(UserDO::getAccountHash, hash)
.or().eq(UserDO::getPhoneHash, hash)
.or().eq(UserDO::getContactPhoneHash, hash);
}
});
}
if (shopId != null && shopId > 0) {
List<Long> userIds = userShopBindingSupport.listUserIdsByShopId(shopId, true);
@@ -2035,10 +2011,10 @@ public class UserServiceImpl extends ServiceImpl<UserMapper, UserDO> implements
wrapper.le(UserDO::getCreateTime, LocalDateTime.parse(createdTo));
}
if (Boolean.TRUE.equals(hasPhone)) {
wrapper.isNotNull(UserDO::getPhone);
wrapper.and(w -> w.isNotNull(UserDO::getPhone).or().isNotNull(UserDO::getPhoneHash));
}
if (Boolean.FALSE.equals(hasPhone)) {
wrapper.isNull(UserDO::getPhone);
wrapper.isNull(UserDO::getPhone).isNull(UserDO::getPhoneHash);
}
wrapper.orderByDesc(UserDO::getCreateTime);
@@ -2254,11 +2230,30 @@ public class UserServiceImpl extends ServiceImpl<UserMapper, UserDO> implements
* @return result consumed by the caller or returned to the frontend
*/
assertUserAvailable(userDO);
userDO.setAvatar(avatarUrl);
String storedAvatar = normalizeStoredAvatar(avatarUrl);
ContentModerationResultVO moderation = contentModerationService.assess("USER_AVATAR", userId, userId,
avatarUrl, serializeModerationPayload(java.util.Map.of("avatar", storedAvatar)));
requireApprovedContent(moderation);
userDO.setAvatar(storedAvatar);
userDO.setUpdateTime(LocalDateTime.now());
return userMapper.updateById(userDO) > 0;
}
private String serializeModerationPayload(Object payload) {
try {
return objectMapper.writeValueAsString(payload);
} catch (JsonProcessingException exception) {
throw new IllegalStateException("无法保存待复核内容", exception);
}
}
private void requireApprovedContent(ContentModerationResultVO result) {
if (result == null || !"APPROVED".equals(result.getStatus())) {
String reason = result == null ? null : result.getReason();
throw new IllegalStateException(StringUtils.hasText(reason) ? reason : "内容正在审核中,暂未更新");
}
}
@Override
/**
* Update an existing record.
@@ -2305,8 +2300,7 @@ public class UserServiceImpl extends ServiceImpl<UserMapper, UserDO> implements
* @return boolean result consumed by the caller or returned to the frontend
*/
public boolean updatePhone(Long userId, UpdatePhoneRequestDTO updatePhoneDTO) {
String oldPhone = updatePhoneDTO.getOldPhone();
String newPhone = updatePhoneDTO.getNewPhone();
String newPhone = validateUserPhone(updatePhoneDTO.getNewPhone(), userId, true);
String verificationCode = updatePhoneDTO.getVerificationCode();
UserDO userDO = userMapper.selectById(userId);
@@ -2325,15 +2319,6 @@ public class UserServiceImpl extends ServiceImpl<UserMapper, UserDO> 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`.
* Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result.
@@ -2342,14 +2327,6 @@ public class UserServiceImpl extends ServiceImpl<UserMapper, UserDO> implements
* @return result consumed by the caller or returned to the frontend
*/
validateVerificationCode(newPhone, verificationCode);
/**
* 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.
* @param newPhone parameter `newPhone` supplied by the caller
* @param userId parameter `userId` supplied by the caller
* @return result consumed by the caller or returned to the frontend
*/
ensurePhoneNotUsed(newPhone, userId);
userDO.setPhone(newPhone);
userDO.setPhoneVerified(1);
@@ -2357,6 +2334,37 @@ public class UserServiceImpl extends ServiceImpl<UserMapper, UserDO> implements
return userMapper.updateById(userDO) > 0;
}
@Override
@Transactional(rollbackFor = Exception.class)
public boolean unbindPhone(Long userId, String verificationCode) {
UserDO userDO = userMapper.selectById(userId);
assertUserAvailable(userDO);
String phone = userDO.getPhone();
if (!StringUtils.hasText(phone) || !Integer.valueOf(1).equals(userDO.getPhoneVerified())) {
throw new RuntimeException("当前账号未绑定已验证手机号");
}
validateVerificationCode(phone, verificationCode);
userDO.setPhone(null);
userDO.setPhoneHash(null);
userDO.setPhoneVerified(0);
userDO.setUpdateTime(LocalDateTime.now());
return userMapper.updateById(userDO) > 0;
}
@Override
public boolean sendUnbindPhoneCode(Long userId) {
UserDO userDO = userMapper.selectById(userId);
assertUserAvailable(userDO);
if (!StringUtils.hasText(userDO.getPhone()) || !Integer.valueOf(1).equals(userDO.getPhoneVerified())) {
throw new RuntimeException("当前账号未绑定已验证手机号");
}
if (!verificationCodeService.canResend(userDO.getPhone())) {
throw new RuntimeException("验证码发送过于频繁,请稍后重试");
}
verificationCodeService.sendVerificationCode(userDO.getPhone(), "USER_UNBIND_PHONE");
return true;
}
@Override
/**
* Run business method `resetPasswordByPhone`.
@@ -2379,10 +2387,7 @@ public class UserServiceImpl extends ServiceImpl<UserMapper, UserDO> implements
validateVerificationCode(phone, verificationCode);
// 根据手机号查找用户
LambdaQueryWrapper<UserDO> wrapper = Wrappers.lambdaQuery(UserDO.class);
wrapper.eq(UserDO::getPhone, phone);
wrapper.eq(UserDO::getIsDelete, 0);
UserDO userDO = userMapper.selectOne(wrapper);
UserDO userDO = findUserByPhone(phone);
if (userDO == null) {
/**
@@ -2917,7 +2922,8 @@ public class UserServiceImpl extends ServiceImpl<UserMapper, UserDO> implements
LoginResponseVO.UserInfo userInfo = new LoginResponseVO.UserInfo();
userInfo.setId(userDO.getId());
userInfo.setAccount(userDO.getAccount());
// 登录响应只用于展示账号标识,手机号账号不得以明文返回。
userInfo.setAccount(phoneCrypto.mask(userDO.getAccount()));
userInfo.setNickname(userDO.getNickname());
userInfo.setAvatar(resolveAccessibleAvatar(userDO.getAvatar()));
userInfo.setType(userDO.getType());
@@ -3104,12 +3110,17 @@ public class UserServiceImpl extends ServiceImpl<UserMapper, UserDO> implements
*/
private void ensurePhoneNotUsed(String phone, Long currentUserId) {
LambdaQueryWrapper<UserDO> 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);
}
if (userMapper.selectOne(wrapper) != null) {
UserDO existing = userMapper.selectOne(wrapper);
if (existing == null) {
Long legacyId = userMapper.findLegacyIdByPhone(phone);
existing = legacyId == null || Objects.equals(legacyId, currentUserId) ? null : userMapper.selectById(legacyId);
}
if (existing != null) {
/**
* 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.
@@ -3128,13 +3139,52 @@ public class UserServiceImpl extends ServiceImpl<UserMapper, UserDO> implements
.eq(UserDO::getType, 0)
.eq(UserDO::getIsDelete, 0);
if (StringUtils.hasText(phone)) {
wrapper.and(query -> query.eq(UserDO::getPhone, phone)
.or().eq(UserDO::getContactPhone, phone));
addPhoneMatch(wrapper, phone);
}
if (userMapper.selectCount(wrapper) > 0) {
throw new RuntimeException("客户已存在,请选择已有客户");
}
}
private void addPhoneMatch(LambdaQueryWrapper<UserDO> wrapper, String phone) {
String hash = phoneCrypto.index(phone.trim());
List<Long> legacyIds = new ArrayList<>();
Long legacyPhoneId = userMapper.findLegacyIdByPhone(phone.trim());
if (legacyPhoneId != null) legacyIds.add(legacyPhoneId);
for (Long legacyContactId : userMapper.findLegacyIdsByContactPhone(phone.trim())) {
if (!legacyIds.contains(legacyContactId)) legacyIds.add(legacyContactId);
}
wrapper.and(query -> {
query.eq(UserDO::getPhoneHash, hash).or().eq(UserDO::getContactPhoneHash, hash);
if (!legacyIds.isEmpty()) query.or().in(UserDO::getId, legacyIds);
});
}
private UserDO findUserByAccount(String account) {
if (!StringUtils.hasText(account)) return null;
LambdaQueryWrapper<UserDO> query = Wrappers.lambdaQuery(UserDO.class).eq(UserDO::getIsDelete, 0);
query.eq(UserDO::getAccountHash, phoneCrypto.index(account.trim()));
UserDO user = userMapper.selectOne(query.last("limit 1"));
if (user == null) {
Long legacyId = userMapper.findLegacyIdByAccount(account.trim());
user = legacyId == null ? null : userMapper.selectById(legacyId);
}
return user;
}
private UserDO findUserByPhone(String phone) {
if (!StringUtils.hasText(phone)) return null;
String normalized = phone.trim();
UserDO user = userMapper.selectOne(Wrappers.lambdaQuery(UserDO.class)
.eq(UserDO::getPhoneHash, phoneCrypto.index(normalized))
.eq(UserDO::getIsDelete, 0)
.last("limit 1"));
if (user == null) {
Long legacyId = userMapper.findLegacyIdByPhone(normalized);
user = legacyId == null ? null : userMapper.selectById(legacyId);
}
return user;
}
/**
* Run business method `buildRelationVO`.
* Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result.
@@ -0,0 +1,31 @@
package com.xiaowang.jayucloud.salon.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;
public class AccountPhoneTypeHandler extends BaseTypeHandler<String> {
@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));
}
}
@@ -0,0 +1,17 @@
package com.xiaowang.jayucloud.salon.core.support.privacy;
import lombok.Data;
import java.util.List;
@Data
public class PhoneBackfillReport {
private boolean dryRun;
private int userRowsToUpdate;
private int userRowsUpdated;
private int orderRowsToUpdate;
private int orderRowsUpdated;
private int accountConflictRows;
private int phoneConflictRows;
private List<Long> conflictingUserIds;
}
@@ -0,0 +1,124 @@
package com.xiaowang.jayucloud.salon.core.support.privacy;
import com.xiaowang.jayucloud.salon.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.Base64;
@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 (java.util.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 encryptAccount(String value) {
return isMobilePhone(value) ? encrypt(value) : value;
}
public String decryptAccount(String value) {
return value != null && value.startsWith(CIPHER_PREFIX) ? decrypt(value) : value;
}
public boolean isMobilePhone(String value) {
return value != null && value.trim().matches("1[3-9]\\d{9}");
}
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 = java.util.Arrays.copyOfRange(payload, 0, 12);
byte[] encrypted = java.util.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);
}
}
public boolean isEncrypted(String value) {
return value != null && value.startsWith(CIPHER_PREFIX);
}
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 java.util.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-salon.privacy." + name);
try {
return Base64.getDecoder().decode(value.trim());
} catch (IllegalArgumentException exception) {
throw new IllegalStateException("Nacos配置必须使用Base64编码: " + name, exception);
}
}
}
@@ -0,0 +1,112 @@
package com.xiaowang.jayucloud.salon.core.support.privacy;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.xiaowang.jayucloud.salon.core.config.PhoneCryptoProperties;
import com.xiaowang.jayucloud.salon.core.modules.order.entity.OrderDO;
import com.xiaowang.jayucloud.salon.core.modules.order.mapper.OrderMapper;
import com.xiaowang.jayucloud.salon.core.modules.user.entity.UserDO;
import com.xiaowang.jayucloud.salon.core.modules.user.mapper.UserMapper;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.function.Function;
import java.util.stream.Collectors;
@Service
@RequiredArgsConstructor
public class PhoneDataBackfillService {
private final UserMapper userMapper;
private final OrderMapper orderMapper;
private final PhoneCrypto phoneCrypto;
private final PhoneCryptoProperties properties;
@Transactional(rollbackFor = Exception.class)
public PhoneBackfillReport backfill(boolean dryRun) {
if (!dryRun && !properties.isBackfillEnabled()) {
throw new IllegalStateException("请先在 Salon Nacos secret.yaml 启用 phone-crypto.backfill-enabled");
}
List<UserDO> users = userMapper.selectList(Wrappers.lambdaQuery(UserDO.class));
Map<String, List<Long>> accountGroups = groupValues(users, UserDO::getAccount);
Map<String, List<Long>> phoneGroups = groupValues(users, UserDO::getPhone);
Set<Long> accountConflicts = duplicateIds(accountGroups);
Set<Long> phoneConflicts = duplicateIds(phoneGroups);
Set<Long> conflictingIds = new HashSet<>(accountConflicts);
conflictingIds.addAll(phoneConflicts);
List<UserDO> usersToUpdate = users.stream()
.filter(user -> !conflictingIds.contains(user.getId()))
.filter(this::hasPendingUserFields)
.toList();
List<OrderDO> ordersToUpdate = orderMapper.selectList(Wrappers.lambdaQuery(OrderDO.class)
.isNotNull(OrderDO::getCustomerPhoneSnapshot)
.isNull(OrderDO::getCustomerPhoneSnapshotHash))
.stream()
.filter(order -> StringUtils.hasText(order.getCustomerPhoneSnapshot()))
.toList();
PhoneBackfillReport report = new PhoneBackfillReport();
report.setDryRun(dryRun);
report.setUserRowsToUpdate(usersToUpdate.size());
report.setOrderRowsToUpdate(ordersToUpdate.size());
report.setAccountConflictRows(accountConflicts.size());
report.setPhoneConflictRows(phoneConflicts.size());
report.setConflictingUserIds(conflictingIds.stream().sorted().toList());
if (dryRun) return report;
if (!conflictingIds.isEmpty()) {
throw new IllegalStateException("检测到手机号或登录账号重复,已停止全部回填;请先处理冲突用户 ID:"
+ report.getConflictingUserIds());
}
int pageSize = Math.max(1, Math.min(properties.getBackfillPageSize(), 2000));
for (int start = 0; start < usersToUpdate.size(); start += pageSize) {
int end = Math.min(start + pageSize, usersToUpdate.size());
List<UserDO> batch = usersToUpdate.subList(start, end);
for (UserDO user : batch) {
userMapper.updateById(user);
report.setUserRowsUpdated(report.getUserRowsUpdated() + 1);
}
}
for (int start = 0; start < ordersToUpdate.size(); start += pageSize) {
int end = Math.min(start + pageSize, ordersToUpdate.size());
List<OrderDO> batch = ordersToUpdate.subList(start, end);
for (OrderDO order : batch) {
orderMapper.updateById(order);
report.setOrderRowsUpdated(report.getOrderRowsUpdated() + 1);
}
}
return report;
}
private Map<String, List<Long>> groupValues(List<UserDO> users, Function<UserDO, String> valueGetter) {
Map<String, List<Long>> groups = new HashMap<>();
for (UserDO user : users) {
String value = valueGetter.apply(user);
if (StringUtils.hasText(value)) {
groups.computeIfAbsent(phoneCrypto.index(value), ignored -> new ArrayList<>()).add(user.getId());
}
}
return groups;
}
private Set<Long> duplicateIds(Map<String, List<Long>> groups) {
return groups.values().stream()
.filter(ids -> ids.size() > 1)
.flatMap(List::stream)
.collect(Collectors.toSet());
}
private boolean hasPendingUserFields(UserDO user) {
return (StringUtils.hasText(user.getAccount()) && !StringUtils.hasText(user.getAccountHash()))
|| (StringUtils.hasText(user.getPhone()) && !StringUtils.hasText(user.getPhoneHash()))
|| (StringUtils.hasText(user.getContactPhone()) && !StringUtils.hasText(user.getContactPhoneHash()));
}
}
@@ -0,0 +1,31 @@
package com.xiaowang.jayucloud.salon.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;
public class PhoneEncryptionTypeHandler extends BaseTypeHandler<String> {
@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));
}
}
@@ -0,0 +1,39 @@
package com.xiaowang.jayucloud.salon.core.support.privacy;
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;
@Component
public class SensitivePhoneMetaObjectHandler implements MetaObjectHandler {
@Override
public void insertFill(MetaObject metaObject) {
fillIndexes(metaObject);
}
@Override
public void updateFill(MetaObject metaObject) {
fillIndexes(metaObject);
}
private void fillIndexes(MetaObject metaObject) {
setAccountIndex(metaObject);
setIndex(metaObject, "phone", "phoneHash");
setIndex(metaObject, "contactPhone", "contactPhoneHash");
setIndex(metaObject, "customerPhoneSnapshot", "customerPhoneSnapshotHash");
}
private void setAccountIndex(MetaObject metaObject) {
if (!metaObject.hasGetter("account") || !metaObject.hasSetter("accountHash")) return;
Object value = metaObject.getValue("account");
String account = value == null ? null : String.valueOf(value);
metaObject.setValue("accountHash", account == null ? null : PhoneCrypto.current().index(account));
}
private void setIndex(MetaObject metaObject, String source, String target) {
if (!metaObject.hasGetter(source) || !metaObject.hasSetter(target)) return;
Object value = metaObject.getValue(source);
String hash = value == null ? null : PhoneCrypto.current().index(String.valueOf(value));
metaObject.setValue(target, hash);
}
}
@@ -129,8 +129,7 @@ public class OperationGuardService {
"public",
safeAction,
subject,
sanitize(resolveClientIp(request)),
sanitize(resolveDeviceId(request))
sanitize(resolveClientIp(request))
);
}
@@ -304,13 +303,6 @@ public class OperationGuardService {
* Purpose: resolveDeviceId supports OperationGuardService.java by holding or executing the resolve device id business role.
* Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state.
*/
private String resolveDeviceId(HttpServletRequest request) {
if (request == null) {
return "-";
}
return request.getHeader(RequestThrottleService.DEVICE_ID_HEADER);
}
/**
* Purpose: sanitize supports OperationGuardService.java by holding or executing the sanitize business role.
* Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state.
@@ -24,7 +24,6 @@ public class RequestThrottleService {
* Purpose: DEVICE_ID_HEADER supports RequestThrottleService.java by holding or executing the device id header business role.
* Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state.
*/
public static final String DEVICE_ID_HEADER = "X-Device-Id";
/**
* Purpose: stringRedisTemplate supports RequestThrottleService.java by holding or executing the string redis template business role.
@@ -145,7 +144,6 @@ public class RequestThrottleService {
String raw = String.join("|",
category,
sanitize(resolveClientIp(request)),
sanitize(resolveDeviceId(request)),
sanitize(subject)
);
String key = "rate:" + DigestUtils.md5DigestAsHex(raw.getBytes(StandardCharsets.UTF_8));
@@ -190,7 +188,7 @@ public class RequestThrottleService {
* Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state.
*/
private String buildLoginLockRaw(HttpServletRequest request, String account) {
return String.join("|", sanitize(resolveClientIp(request)), sanitize(resolveDeviceId(request)), sanitize(account));
return String.join("|", sanitize(resolveClientIp(request)), sanitize(account));
}
/**
@@ -216,10 +214,6 @@ public class RequestThrottleService {
* Purpose: resolveDeviceId supports RequestThrottleService.java by holding or executing the resolve device id business role.
* Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state.
*/
private String resolveDeviceId(HttpServletRequest request) {
return request == null ? null : request.getHeader(DEVICE_ID_HEADER);
}
/**
* Purpose: sanitize supports RequestThrottleService.java by holding or executing the sanitize business role.
* Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state.
@@ -0,0 +1,85 @@
package com.xiaowang.jayucloud.salon.core.modules.user.controller.front;
import com.xiaowang.jayucloud.salon.core.common.Result;
import com.xiaowang.jayucloud.salon.core.modules.auth.service.VerificationCodeService;
import com.xiaowang.jayucloud.salon.core.modules.file.service.ChunkUploadService;
import com.xiaowang.jayucloud.salon.core.modules.file.service.PrimaryObjectStorageService;
import com.xiaowang.jayucloud.salon.core.modules.file.support.ObjectStorageUrlSupport;
import com.xiaowang.jayucloud.salon.core.modules.integration.service.WechatMiniAuthService;
import com.xiaowang.jayucloud.salon.core.modules.privacy.service.AccountClosureService;
import com.xiaowang.jayucloud.salon.core.modules.security.service.ShopRoleService;
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.modules.system.service.LegalAgreementService;
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.UserAssetService;
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.security.RequestThrottleService;
import org.junit.jupiter.api.Test;
import javax.servlet.http.HttpServletRequest;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
class UserControllerPhonePrivacyTest {
@Test
void sendsPasswordCodeToVerifiedPhoneFromCurrentAccount() {
UserService userService = mock(UserService.class);
UserAssetService userAssetService = mock(UserAssetService.class);
PrimaryObjectStorageService primaryObjectStorageService = mock(PrimaryObjectStorageService.class);
ChunkUploadService chunkUploadService = mock(ChunkUploadService.class);
VerificationCodeService verificationCodeService = mock(VerificationCodeService.class);
UserMapper userMapper = mock(UserMapper.class);
AdminScopeHelper adminScopeHelper = mock(AdminScopeHelper.class);
ShopRoleService shopRoleService = mock(ShopRoleService.class);
TimeOrderedSnowflakeIdGenerator idGenerator = mock(TimeOrderedSnowflakeIdGenerator.class);
WechatMiniAuthService wechatMiniAuthService = mock(WechatMiniAuthService.class);
ObjectStorageUrlSupport objectStorageUrlSupport = mock(ObjectStorageUrlSupport.class);
RequestThrottleService requestThrottleService = mock(RequestThrottleService.class);
LegalAgreementService legalAgreementService = mock(LegalAgreementService.class);
AccountClosureService accountClosureService = mock(AccountClosureService.class);
SecurityAuditLogService securityAuditLogService = mock(SecurityAuditLogService.class);
UserController controller = new UserController(userService, userAssetService, primaryObjectStorageService,
chunkUploadService, verificationCodeService, userMapper, adminScopeHelper, shopRoleService,
idGenerator, wechatMiniAuthService, objectStorageUrlSupport, requestThrottleService,
legalAgreementService, accountClosureService, securityAuditLogService);
HttpServletRequest request = mock(HttpServletRequest.class);
when(request.getAttribute("userId")).thenReturn(27L);
UserDO user = new UserDO();
user.setId(27L);
user.setPhone("13812345678");
user.setPhoneVerified(1);
user.setStatus(1);
user.setIsDelete(0);
when(userMapper.selectById(27L)).thenReturn(user);
when(verificationCodeService.canResend(user.getPhone())).thenReturn(true);
Result<Boolean> result = controller.sendCurrentPasswordVerificationCode(request);
assertEquals(true, result.getData());
verify(requestThrottleService).checkSendCode(request, user.getPhone());
verify(verificationCodeService).sendVerificationCode(user.getPhone(), "USER_CHANGE_PASSWORD_SMS_CODE");
}
@Test
void rejectsPasswordCodeRequestWithoutAuthenticatedUser() {
UserController controller = new UserController(mock(UserService.class), mock(UserAssetService.class),
mock(PrimaryObjectStorageService.class), mock(ChunkUploadService.class),
mock(VerificationCodeService.class), mock(UserMapper.class), mock(AdminScopeHelper.class),
mock(ShopRoleService.class), mock(TimeOrderedSnowflakeIdGenerator.class),
mock(WechatMiniAuthService.class), mock(ObjectStorageUrlSupport.class),
mock(RequestThrottleService.class), mock(LegalAgreementService.class),
mock(AccountClosureService.class), mock(SecurityAuditLogService.class));
HttpServletRequest request = mock(HttpServletRequest.class);
assertThrows(RuntimeException.class, () -> controller.sendCurrentPasswordVerificationCode(request));
}
}
@@ -0,0 +1,52 @@
package com.xiaowang.jayucloud.salon.core.modules.user.service.impl;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.xiaowang.jayucloud.salon.core.modules.auth.dto.UpdatePhoneRequestDTO;
import com.xiaowang.jayucloud.salon.core.modules.auth.service.VerificationCodeService;
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.support.privacy.PhoneCrypto;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
@ExtendWith(MockitoExtension.class)
class UserServicePhoneUpdateTest {
@Mock private UserMapper userMapper;
@Mock private PhoneCrypto phoneCrypto;
@Mock private VerificationCodeService verificationCodeService;
@InjectMocks private UserServiceImpl userService;
@Test
void updatesPhoneWithoutTrustingMaskedOldPhoneFromClient() {
UserDO currentUser = new UserDO();
currentUser.setId(27L);
currentUser.setPhone("13812345678");
currentUser.setPhoneVerified(1);
currentUser.setStatus(1);
currentUser.setIsDelete(0);
when(userMapper.selectById(27L)).thenReturn(currentUser);
when(phoneCrypto.index("13912345678")).thenReturn("new-phone-hash");
when(userMapper.selectOne(any(Wrapper.class))).thenReturn(null);
when(userMapper.findLegacyIdByPhone("13912345678")).thenReturn(null);
when(verificationCodeService.verifyCode("13912345678", "123456")).thenReturn(true);
when(userMapper.updateById(currentUser)).thenReturn(1);
UpdatePhoneRequestDTO request = new UpdatePhoneRequestDTO();
request.setOldPhone("138****5678");
request.setNewPhone("13912345678");
request.setVerificationCode("123456");
assertTrue(userService.updatePhone(27L, request));
verify(userMapper).updateById(currentUser);
assertTrue("13912345678".equals(currentUser.getPhone()));
}
}
@@ -0,0 +1,38 @@
<!doctype html>
<html lang="zh-CN">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="color-scheme" content="light">
<title>甲屿手纪 Salon 隐私政策</title>
<style>
body{max-width:860px;margin:0 auto;padding:32px 20px;color:#24332e;font:16px/1.8 system-ui,-apple-system,"Microsoft YaHei",sans-serif}h1{font-size:28px}h2{margin-top:28px;font-size:19px}p,li{color:#40504a}.note{padding:12px 16px;background:#eff7f2;border-radius:8px}
</style>
</head>
<body>
<h1>甲屿手纪 Salon 隐私政策</h1>
<p>版本:2026.10.21 更新日期:2026年10月21日</p>
<p class="note">本政策适用于 Salon 门店工作台的店长与员工账号。实际上线前,运营方应核实主体、短信服务商、消息通道、对象存储及微信后台隐私指引,并据实更新本政策。</p>
<h2>一、处理的信息及用途</h2>
<ul>
<li>登录:在用户主动同意后,通过微信登录获取 OpenID,用于识别和关联账号。</li>
<li>可选资料:用户主动选择时处理昵称和头像;未提供时使用系统默认展示。</li>
<li>手机号:用户主动选择绑定或更换时处理,用于账号找回和必要业务联系,不用于营销;不绑定不影响基础工作台使用。</li>
<li>门店业务资料:店长和员工可能录入客户姓名、可选联系电话、预约、作品和订单信息,以履行门店服务管理。客户业务资料不构成客户的小程序登录账号。</li>
<li>安全运行:服务端会处理请求所需的网络地址、登录会话和操作审计信息,不读取设备标识、IMEI、MAC、麦克风或用户定位。</li>
</ul>
<h2>二、用户主动触发的权限</h2>
<p>仅在用户主动选择头像、作品图片等操作后调用选图能力;仅在用户主动绑定手机号时调用微信手机号能力或发送短信验证码。短信只用于验证绑定、变更或解绑,不用于营销。手机号绑定和解绑前会显示用途说明。</p>
<h2>三、存储与保护</h2>
<p>账号、客户和订单快照中的手机号采用 AES-GCM 加密保存,另以独立 HMAC 索引支持查重。普通页面、日志和导出对手机号脱敏;完整号码仅在业务需要且权限允许时展示。账号密钥由各环境配置管理,运营方需限制配置访问并保留审计。</p>
<h2>四、第三方服务</h2>
<p>服务依赖微信小程序登录与用户主动触发的微信能力;验证码由部署环境启用的短信服务商发送;通知由配置的消息通道处理;头像、作品等文件存储于部署环境配置的对象存储服务。运营方上线前应在微信后台列明实际服务商,并确认其处理范围和协议。</p>
<h2>五、内容审核</h2>
<p>当前代码仅使用本地模拟审核 Provider,不调用微信内容安全接口。模拟结果只用于开发验证,不代表真实审核能力。接入正式审核前将完成单独评估、隐私指引更新和数据流说明。</p>
<h2>六、保留、注销和解绑</h2>
<p>用户可在小程序“我的-账号设置”申请注销或解绑手机号。解绑通过当前号码验证码核验后立即清除手机号密文和索引。注销申请经管理员完成门店移交或归档后撤销会话,并在目标15个工作日内删除或匿名化 OpenID、昵称、头像、手机号等个人资料。必要订单、预约和经营记录在去除账号身份关联后按产品目标保留五年;该期限及范围由运营方上线前核实。</p>
<h2>七、政策更新与联系</h2>
<p>处理目的、数据类别或服务商发生重要变化时,我们会更新本政策并在需要时重新征求同意。用户可以在账号设置查看注销申请状态、撤回待处理申请并提交隐私相关请求;也可联系所属门店管理员。</p>
<p>本文件是产品说明,不构成法律意见;上线前应由运营方或专业顾问结合实际处理活动审阅。</p>
</body>
</html>
@@ -0,0 +1,31 @@
<!doctype html>
<html lang="zh-CN">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<meta name="color-scheme" content="light">
<title>甲屿手纪 Salon 用户协议</title>
<style>
body{max-width:860px;margin:0 auto;padding:32px 20px;color:#24332e;font:16px/1.8 system-ui,-apple-system,"Microsoft YaHei",sans-serif}h1{font-size:28px}h2{margin-top:28px;font-size:19px}p{margin:12px 0;color:#40504a}.note{padding:12px 16px;background:#eff7f2;border-radius:8px}
</style>
</head>
<body>
<h1>甲屿手纪 Salon 用户协议</h1>
<p>版本:2026.10.21 更新日期:2026年10月21日</p>
<p class="note">本服务面向经门店授权的店长和员工,提供门店日程、预约、客户业务资料和经营记录管理。预约金额是业务记录,不表示本平台已收款;当前不提供充值、订阅或平台虚拟权益购买。</p>
<h2>一、接受协议</h2>
<p>使用前请阅读本协议及《隐私政策》。登录时须主动选择同意;未同意时不会交换微信登录凭证,也不能继续使用。协议更新后需重新确认。</p>
<h2>二、账号与使用权限</h2>
<p>微信 OpenID 用于关联工作台账号。账号仅供本人使用,不得转借。昵称和头像可选;手机号可选绑定,不绑定不影响基础功能。离职或不再获授权时,门店管理员可以调整账号权限。</p>
<h2>三、业务资料与内容</h2>
<p>使用者仅可录入履行门店业务所需且有权处理的客户、预约、作品和员工资料,并应确保上传文字和图片来源合法,不得上传违法、侵权、欺诈或侵害他人权益的内容。用户可随时更正自己提交的非业务资料。</p>
<p>头像、作品、评论等内容当前使用本地模拟审核流程,仅用于开发验证,不代表已接入微信内容安全审核。正式上线前,平台将依据实际审核服务更新隐私指引和本协议说明。</p>
<h2>四、业务记录与金额</h2>
<p>订单及预约页面展示的金额用于门店经营记录,不构成平台收款、支付或退款承诺。当前平台不提供充值或订阅交易。不得将工作台用于未经授权的资金收取或虚拟权益交易。</p>
<h2>五、账号注销</h2>
<p>用户可在小程序“我的-账号设置”提交注销申请并在处理前撤回。管理员完成必要的门店移交或归档后撤销会话并清理或匿名化个人账号资料。目标处理期限为15个工作日,具体取决于门店交接;必要的订单、预约和经营记录将去除身份关联后按产品目标保留五年。</p>
<h2>六、服务调整与联系</h2>
<p>平台会在合理范围内维护服务,并在功能或数据处理方式发生重要变化时更新说明。隐私相关申请可从账号设置发起;其他问题请联系所属门店管理员。</p>
<p>本协议为产品说明文本,正式发布前应由运营方根据实际主体、业务和适用法律完成审核。</p>
</body>
</html>
+69
View File
@@ -2001,5 +2001,74 @@ export const adminWorkbenchRegistrationApi = {
}
}
export interface AccountClosureRequestVO {
id: IdType
userId: IdType
nickname: string
userType?: number
shopIds?: IdType[]
shopNames?: string[]
status: string
requestedAt?: string
processingTargetText?: string
processedAt?: string
reviewerNote?: string
}
export interface ClosureSuccessorManagerVO {
id: IdType
nickname?: string
shopId?: IdType
}
export interface ContentModerationRecordVO {
id: IdType
contentType: string
businessId?: IdType
userId?: IdType
status: string
provider: string
resultCode?: string
reason?: string
payloadJson?: string
attemptCount?: number
createTime?: string
}
export interface PhoneBackfillReportVO {
dryRun: boolean
userRowsToUpdate: number
orderRowsToUpdate: number
userRowsUpdated: number
orderRowsUpdated: number
accountConflictRows: number
phoneConflictRows: number
conflictingUserIds: IdType[]
}
export const adminPrivacyComplianceApi = {
listClosures() {
return adminApi.get<AccountClosureRequestVO[]>('/privacy/account-closure/pending') as unknown as Promise<AccountClosureRequestVO[]>
},
listSuccessorManagers() {
return adminApi.get<ClosureSuccessorManagerVO[]>('/privacy/account-closure/successor-managers') as unknown as Promise<ClosureSuccessorManagerVO[]>
},
processClosure(id: IdType, data: { decision: string; successorManagerId?: IdType; archiveShopIds?: IdType[]; note?: string }) {
return adminApi.post<boolean>(`/privacy/account-closure/${id}/process`, data)
},
listModeration() {
return adminApi.get<ContentModerationRecordVO[]>('/privacy/content-moderation/pending') as unknown as Promise<ContentModerationRecordVO[]>
},
reviewContent(id: IdType, data: { approved: boolean; reason: string }) {
return adminApi.post<boolean>(`/privacy/content-moderation/${id}/review`, data)
},
phoneBackfillReport() {
return adminApi.get<PhoneBackfillReportVO>('/privacy/phone-backfill/report') as unknown as Promise<PhoneBackfillReportVO>
},
runPhoneBackfill() {
return adminApi.post<PhoneBackfillReportVO>('/privacy/phone-backfill/run') as unknown as Promise<PhoneBackfillReportVO>
}
}
export { adminApi }
export default adminApi
-9
View File
@@ -155,15 +155,6 @@ export interface GrowthSummaryVO {
reviewCount?: number
}
export const paymentApi = {
prepareOrderPayment: async (orderId: IdType): Promise<PaymentOrderVO> => {
return await api.post<PaymentOrderVO>(`/payment/order/${orderId}/prepare`) as unknown as PaymentOrderVO
},
mockSuccess: async (orderId: IdType): Promise<PaymentOrderVO> => {
return await api.post<PaymentOrderVO>(`/payment/order/${orderId}/mock-success`) as unknown as PaymentOrderVO
}
}
export const afterSaleApi = {
apply: async (data: AfterSaleApplyRequest): Promise<AfterSaleVO> => {
return await api.post<AfterSaleVO>('/after-sale/apply', data) as unknown as AfterSaleVO
+13 -3
View File
@@ -202,7 +202,6 @@ 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
newPhone: string
verificationCode: string
}
@@ -388,6 +387,9 @@ export const userApi = {
sendVerificationCode: (data: { phone: string; sceneCode?: string }) => {
return api.post('/user/send-verification-code', data)
},
sendCurrentPasswordVerificationCode: () => {
return api.post('/user/send-current-password-code')
},
/**
* `switchShop` 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.
@@ -464,6 +466,14 @@ export const userApi = {
* Call guide: supply the parameters below, await the returned Promise, and handle loading / error UI in the caller.
*/
deactivateAccount: () => {
return api.delete('/user/deactivate')
}
return api.post('/user/account-closure', {})
},
getAccountClosure: async () => await api.get('/user/account-closure/me') as unknown as Promise<{
id: IdType
status: string
requestedAt?: string
processingTargetText?: string
reviewerNote?: string
} | null>,
withdrawAccountClosure: () => api.delete('/user/account-closure/me')
}
@@ -26,6 +26,7 @@ export const adminNavigationItems: AdminNavigationItem[] = [
{ path: ADMIN_HOME_PATH, iconKey: 'home', label: '首页', permissionCode: '' },
{ path: '/admin/users', iconKey: 'user', label: '店长账号', permissionCode: 'user:view' },
{ path: '/admin/registrations', iconKey: 'team', label: '注册审核', permissionCode: 'user:view' },
{ path: '/admin/privacy', iconKey: 'security', label: '隐私与内容复核', permissionCode: 'legal_agreement:manage' },
{ path: '/admin/shops', iconKey: 'home', label: '店铺管理', permissionCode: 'shop:view' },
{ path: '/admin/settings', iconKey: 'tool', label: '系统设置', permissionCode: 'messagehub:config:manage' },
{ path: '/admin/profile', iconKey: 'user', label: '个人设置', permissionCode: '' }
+1 -1
View File
@@ -9,7 +9,7 @@ import {
const pageNames = [
['', 'HomeView', 'admin', undefined],
['users', 'UsersView', 'admin-users', 'user:view'], ['registrations', 'WorkbenchRegistrationView', 'admin-registrations', 'user:view'], ['shops', 'ShopsView', 'admin-shops', 'shop:view'],
['users', 'UsersView', 'admin-users', 'user:view'], ['registrations', 'WorkbenchRegistrationView', 'admin-registrations', 'user:view'], ['privacy', 'PrivacyComplianceView', 'admin-privacy', 'legal_agreement:manage'], ['shops', 'ShopsView', 'admin-shops', 'shop:view'],
['profile', 'ProfileView', 'admin-profile', undefined], ['settings', 'SystemSettingsView', 'admin-settings', 'messagehub:config:manage']
] as const
@@ -20,16 +20,6 @@ const HEADER_SIGNATURE = 'X-Signature'
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
*/
const HEADER_SIGNATURE_VERSION = 'X-Sign-Version'
/**
* Purpose: DEVICE_ID_HEADER supports request-signature.ts by holding or executing the device id header page or API role.
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
*/
const DEVICE_ID_HEADER = 'X-Device-Id'
/**
* Purpose: DEVICE_ID_STORAGE_KEY supports request-signature.ts by holding or executing the device id storage key page or API role.
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
*/
const DEVICE_ID_STORAGE_KEY = 'jayucloud-salon-device-id'
/**
* Purpose: SIGNATURE_VERSION supports request-signature.ts by holding or executing the signature version 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.
@@ -245,20 +235,6 @@ function randomNonce() {
* Purpose: getDeviceId supports request-signature.ts by holding or executing the get device id page or API role.
* Usage: import, call, read, or update this function from the owning page/module while preserving the surrounding loading and permission flow.
*/
export function getDeviceId() {
try {
const stored = localStorage.getItem(DEVICE_ID_STORAGE_KEY)
if (stored) {
return stored
}
const next = `web-${randomNonce()}`
localStorage.setItem(DEVICE_ID_STORAGE_KEY, next)
return next
} catch {
return `web-${randomNonce()}`
}
}
/**
* Purpose: setHeader supports request-signature.ts by holding or executing the set header page or API role.
* Usage: import, call, read, or update this function from the owning page/module while preserving the surrounding loading and permission flow.
@@ -448,8 +424,6 @@ export async function attachRequestSignature(
accessToken?: string | null,
options: RequestSignatureOptions = {}
) {
setHeader(config, DEVICE_ID_HEADER, getDeviceId())
const method = String(config.method || 'GET').toUpperCase()
if (!accessToken || options.authFree || isSafeMethod(method)) {
return config
@@ -353,6 +353,7 @@ const handleClearChangePasswordDraft = (showMessage = true) => {
// 倒计时
/** countdown is a reactive state variable used by the template and event handlers. */
const countdown = ref(0)
const closureRequest = ref<{ id: string | number; status: string; requestedAt?: string; processingTargetText?: string; reviewerNote?: string } | null>(null)
// 账号设置选项
/** accountSettings is a reactive state variable used by the template and event handlers. */
@@ -421,7 +422,14 @@ const updateAccountSettings = () => {
key: 'deactivateAccount',
title: '注销账号',
icon: LockOutlined,
bgColor: '#fff1f0'
bgColor: '#fff1f0',
desc: closureRequest.value?.status === 'PENDING'
? '申请处理中,点击查看或撤回'
: closureRequest.value?.status === 'REJECTED'
? `上次申请未通过:${closureRequest.value.reviewerNote || '可重新申请'}`
: closureRequest.value?.status === 'APPROVED'
? '资料清理已完成'
: '申请注销账号,处理前可撤回'
})
accountSettings.value = settings
@@ -431,8 +439,12 @@ const updateAccountSettings = () => {
/** fetchUserInfo is an async page action. Trigger it from the template or lifecycle hook, then await the result. */
const fetchUserInfo = async () => {
try {
const response = await userApi.getUserInfo() as any
const [response, closure] = await Promise.all([
userApi.getUserInfo() as Promise<any>,
userApi.getAccountClosure().catch(() => null)
])
userInfo.value = response
closureRequest.value = closure || null
// 检查是否绑定手机号
hasPhone.value = !!userInfo.value.phone
// 检查是否设置密码(通过localStorage中的标识)
@@ -546,18 +558,8 @@ const handleSendChangePasswordVerificationCode = async () => {
return
}
const phone = userInfo.value.phone
const phoneRegex = /^1[3-9]\d{9}$/
if (!phoneRegex.test(phone)) {
message.error('手机号格式不正确')
return
}
try {
await runWithGlobalLoading(() => userApi.sendVerificationCode({
phone,
sceneCode: 'USER_CHANGE_PASSWORD_SMS_CODE'
}))
await runWithGlobalLoading(() => userApi.sendCurrentPasswordVerificationCode())
message.success('验证码发送成功')
startCountdown()
} catch (error) {
@@ -626,7 +628,6 @@ const handleChangePhoneSubmit = async () => {
try {
await runWithGlobalLoading(async () => {
await userApi.updatePhone({
oldPhone: userInfo.value.phone!,
newPhone: changePhoneForm.newPhone,
verificationCode: changePhoneForm.verificationCode
})
@@ -697,34 +698,30 @@ const handleChangePasswordCancel = () => {
// 处理注销账号
/** handleDeactivateAccount is an async page action. Trigger it from the template or lifecycle hook, then await the result. */
const handleDeactivateAccount = async () => {
const pending = closureRequest.value?.status === 'PENDING'
Modal.confirm({
title: '确认注销账号',
content: '注销账号后,您的所有数据将被删除且无法恢复。确定要注销账号吗?',
okText: '确认注销',
okType: 'danger',
title: pending ? '撤回注销申请' : '申请注销账号',
content: pending
? '申请仍在处理中。确定撤回后,账号将继续保持可用。'
: '提交后由管理人员处理。完成后会清理账号资料,必要业务记录会匿名化保留;处理前可在此撤回。目标处理期限为15个工作日。',
okText: pending ? '撤回申请' : '提交申请',
okType: pending ? 'default' : 'danger',
cancelText: '取消',
onOk: async () => {
await runWithGlobalLoading(async () => {
try {
await userApi.deactivateAccount()
message.success('账号注销成功')
if (pending) {
await userApi.withdrawAccountClosure()
message.success('注销申请已撤回')
} else {
await userApi.deactivateAccount()
message.success('注销申请已提交')
}
closureRequest.value = await userApi.getAccountClosure() || null
updateAccountSettings()
} catch (error) {
console.error('注销账号失败:', error)
message.error('注销账号失败')
} finally {
// 无论成功或失败,都清除本地存储的用户信息
localStorage.removeItem('accessToken')
localStorage.removeItem('refreshToken')
localStorage.removeItem('userInfo')
localStorage.removeItem('adminAccessToken')
localStorage.removeItem('adminRefreshToken')
localStorage.removeItem('adminUserInfo')
localStorage.removeItem('needSetPassword')
localStorage.removeItem('userPermissions')
sessionStorage.removeItem('accessToken')
sessionStorage.removeItem('adminAccessToken')
// 跳转到登录页
router.push('/')
console.error('处理注销申请失败:', error)
message.error(error instanceof Error ? error.message : '处理注销申请失败')
}
})
}
@@ -3,7 +3,7 @@ import { computed, onMounted, ref } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { LeftOutlined } from '@ant-design/icons-vue'
import { message, Modal } from 'ant-design-vue'
import { afterSaleApi, orderApi, paymentApi } from '../api/order'
import { afterSaleApi, orderApi } from '../api/order'
import type { AfterSaleVO, OrderArtistChangeRequestVO, OrderArtistReviewVO } from '../api/order'
import { userApi, type ContactInfoVO } from '@/api/user'
import type { IdType } from '@/utils/id'
@@ -35,10 +35,7 @@ const formatDateTime = (value?: string) => value ? String(value).replace('T', '
const isQuoteStatus = (status?: unknown) => Number(status) === 0
const isQuoteConfirming = computed(() => isQuoteStatus(order.value?.status))
const statusClass = (status?: number) => isQuoteStatus(status) ? 'quote' : status === 2 ? 'done' : status === 3 ? 'cancelled' : status === 4 ? 'in-service' : 'pending'
const isOrderPaid = (target: any) => String(target?.paymentStatus || '').toUpperCase() === 'PAID'
const canPreparePayment = computed(() => !isQuoteConfirming.value && Number(order.value?.status) === 1 && !isOrderPaid(order.value))
const canMockPay = computed(() => !isQuoteConfirming.value && Number(order.value?.status) === 1 && String(order.value?.paymentStatus || '').toUpperCase() === 'PAYING')
const canApplyAfterSale = computed(() => !isQuoteConfirming.value && (Number(order.value?.status) === 2 || isOrderPaid(order.value)))
const canApplyAfterSale = computed(() => !isQuoteConfirming.value && Number(order.value?.status) === 2)
const timeline = computed(() => {
const current = order.value || {}
@@ -197,24 +194,6 @@ const confirmQuote = () => {
})
}
const preparePayment = async () => {
if (!order.value?.id) return
await runWithGlobalLoading(async () => {
await paymentApi.prepareOrderPayment(order.value.id)
await loadOrder()
})
message.success('支付单已准备')
}
const mockPay = async () => {
if (!order.value?.id) return
await runWithGlobalLoading(async () => {
await paymentApi.mockSuccess(order.value.id)
await loadOrder()
})
message.success('模拟支付成功')
}
const cancelOrder = () => {
if (!order.value?.id) return
Modal.confirm({
@@ -357,8 +336,6 @@ onMounted(loadOrder)
</section>
<section class="action-bar">
<a-button v-if="canPreparePayment" @click="preparePayment">准备支付</a-button>
<a-button v-if="canMockPay" type="primary" @click="mockPay">模拟支付</a-button>
<a-button v-if="canApplyAfterSale" @click="router.push({ path: '/after-sale/apply', query: { orderId } })">申请售后</a-button>
<a-button v-if="order.status === 1" danger @click="cancelOrder">取消订单</a-button>
</section>
+9 -44
View File
@@ -200,8 +200,6 @@
<div class="order-card__actions">
<button v-if="orderNeedsReview(order)" type="button" class="order-action order-action--primary" @click="openReviewModal(firstPendingReview(order))">去评价</button>
<button v-if="canPreparePayment(order)" type="button" class="order-action order-action--primary" @click="preparePayment(order)">立即支付</button>
<button v-if="canMockPay(order)" type="button" class="order-action order-action--primary" @click="mockPay(order)">立即支付</button>
<button type="button" class="order-action" @click="router.push(`/orders/${order.id}`)">查看详情</button>
<button v-if="canApplyAfterSale(order)" type="button" class="order-action" @click="openAfterSaleModal(order)">申请售后</button>
<button v-if="hasRebookableItems(order)" type="button" class="order-action order-action--primary" @click="rebookOrder(order)">复刻同款</button>
@@ -301,7 +299,7 @@ import { useRoute, useRouter } from 'vue-router'
import { LeftOutlined, ShoppingOutlined, UserOutlined } from '@ant-design/icons-vue'
import { message, Modal } from 'ant-design-vue'
import { cartApi } from '../api/cart'
import { afterSaleApi, orderApi, paymentApi } from '../api/order'
import { afterSaleApi, orderApi } from '../api/order'
import type { OrderArtistChangeRequestVO, OrderArtistReviewVO } from '../api/order'
import { userApi } from '@/api/user'
import type { IdType } from '@/utils/id'
@@ -337,8 +335,8 @@ const orderReviews = ref<Record<string, OrderArtistReviewVO[]>>({})
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
*/
const pendingChangeRequests = ref<OrderArtistChangeRequestVO[]>([])
type OrderStatusFilter = 'all' | 'priceConfirming' | 'pendingPayment' | 'active' | 'pendingReview' | 'completed'
const ORDER_STATUS_FILTER_VALUES: OrderStatusFilter[] = ['all', 'priceConfirming', 'pendingPayment', 'active', 'pendingReview', 'completed']
type OrderStatusFilter = 'all' | 'priceConfirming' | 'pendingService' | 'active' | 'pendingReview' | 'completed'
const ORDER_STATUS_FILTER_VALUES: OrderStatusFilter[] = ['all', 'priceConfirming', 'pendingService', 'active', 'pendingReview', 'completed']
const normalizeRouteStatusFilter = (value: unknown): OrderStatusFilter | undefined => {
const raw = Array.isArray(value) ? value[0] : value
return ORDER_STATUS_FILTER_VALUES.includes(raw as OrderStatusFilter) ? raw as OrderStatusFilter : undefined
@@ -421,7 +419,7 @@ const statusTabs = computed(() => {
const tabs: Array<{ label: string, value: OrderStatusFilter }> = [
{ label: '全部', value: 'all' },
{ label: '确认价格中', value: 'priceConfirming' },
{ label: '待支付', value: 'pendingPayment' },
{ label: '待服务', value: 'pendingService' },
{ label: '预约中', value: 'active' },
{ label: '待评价', value: 'pendingReview' },
{ label: '已完成', value: 'completed' }
@@ -467,12 +465,7 @@ const focusedOrderItemId = ref('')
const focusedReviewId = ref('')
const isQuoteConfirming = (order: any) => Number(order?.status) === 0
const orderPaymentStatus = (order: any) => String(order.paymentStatus || order.payStatus || '').toUpperCase()
const isOrderPaid = (order: any) => orderPaymentStatus(order) === 'PAID'
const orderNeedsPayment = (order: any) => Number(order.status) === 1 && !isOrderPaid(order)
const canPreparePayment = (order: any) => orderNeedsPayment(order) && orderPaymentStatus(order) !== 'PAYING'
const canMockPay = (order: any) => Number(order.status) === 1 && orderPaymentStatus(order) === 'PAYING'
const canApplyAfterSale = (order: any) => !isQuoteConfirming(order) && (Number(order.status) === 2 || isOrderPaid(order))
const canApplyAfterSale = (order: any) => !isQuoteConfirming(order) && Number(order.status) === 2
/**
* Purpose: sameId supports OrderView.vue by holding or executing the same id page or API role.
@@ -554,14 +547,12 @@ const orderNeedsReview = (order: any) => {
return Number(order.status) === 2 && Boolean(firstPendingReview(order))
}
const orderIsActive = (order: any) => {
return Number(order.status) === 1 && !orderNeedsPayment(order)
}
const orderIsActive = (order: any) => Number(order.status) === 1
const orderMatchesStatus = (order: any, status: OrderStatusFilter) => {
if (status === 'all') return true
if (status === 'priceConfirming') return isQuoteConfirming(order)
if (status === 'pendingPayment') return orderNeedsPayment(order)
if (status === 'pendingService') return Number(order.status) === 1
if (status === 'active') return orderIsActive(order)
if (status === 'pendingReview') return orderNeedsReview(order)
if (status === 'completed') return Number(order.status) === 2
@@ -571,9 +562,8 @@ const orderMatchesStatus = (order: any, status: OrderStatusFilter) => {
const orderDisplayStatus = (order: any) => {
if (isQuoteConfirming(order)) return order.statusText || '确认价格中'
if (Number(order.status) === 3) return '已取消'
if (orderNeedsPayment(order)) return '待支付'
if (orderNeedsReview(order)) return '待评价'
if (Number(order.status) === 1) return order.statusText || '预约中'
if (Number(order.status) === 1) return order.statusText || '待服务'
if (Number(order.status) === 2) return '已完成'
return order.statusText || '订单状态'
}
@@ -581,7 +571,6 @@ const orderDisplayStatus = (order: any) => {
const orderStatusClass = (order: any) => {
if (isQuoteConfirming(order)) return 'price-confirming'
if (Number(order.status) === 3) return 'cancelled'
if (orderNeedsPayment(order)) return 'pending-payment'
if (orderNeedsReview(order)) return 'pending-review'
if (Number(order.status) === 1) return 'active'
if (Number(order.status) === 2) return 'completed'
@@ -608,7 +597,7 @@ const orderTimeText = (order: any) => {
const orderAmountLabel = (order: any) => {
if (isQuoteConfirming(order)) return '参考金额'
return orderNeedsPayment(order) ? '订单金额' : '实付金额'
return Number(order.status) === 0 ? '参考金额' : '订单金额'
}
const orderExtensionItems = (order: any) => {
@@ -767,30 +756,6 @@ const resetFilters = () => {
filters.maxAmount = undefined
}
const preparePayment = async (order: any) => {
try {
await runWithGlobalLoading(async () => {
await paymentApi.prepareOrderPayment(order.id)
await loadOrders()
})
message.success('支付已准备,请继续完成支付')
} catch (error: any) {
message.error(error?.message || '支付准备失败')
}
}
const mockPay = async (order: any) => {
try {
await runWithGlobalLoading(async () => {
await paymentApi.mockSuccess(order.id)
await loadOrders()
})
message.success('支付成功')
} catch (error: any) {
message.error(error?.message || '支付失败')
}
}
const submitQuoteReply = async (order: any) => {
const key = quoteOrderKey(order)
const remark = String(quoteReplyForms[key] || '').trim()
@@ -237,10 +237,7 @@ const handleSendVerificationCode = async () => {
}
try {
await runWithGlobalLoading(() => userApi.sendVerificationCode({
phone: userPhone.value,
sceneCode: 'USER_CHANGE_PASSWORD_SMS_CODE'
}))
await runWithGlobalLoading(() => userApi.sendCurrentPasswordVerificationCode())
message.success('验证码发送成功')
startCountdown()
} catch (error: any) {
+19 -221
View File
@@ -2,31 +2,22 @@
import { computed, onMounted, ref, shallowRef } from 'vue'
import { useRouter } from 'vue-router'
import {
CreditCardOutlined,
CrownOutlined,
GiftOutlined,
HistoryOutlined,
LeftOutlined,
PayCircleOutlined,
PercentageOutlined,
SafetyCertificateOutlined,
ScissorOutlined,
ShoppingOutlined,
StarFilled,
TrophyOutlined
} from '@ant-design/icons-vue'
import { message } from 'ant-design-vue'
import { userApi, type BalanceHistoryItem, type UserAssetVO, type VipRechargePlanVO } from '@/api/user'
import { userApi, type BalanceHistoryItem, type UserAssetVO } from '@/api/user'
const router = useRouter()
const loading = shallowRef(false)
const rechargeOpen = shallowRef(false)
const visibleHistoryCount = shallowRef(3)
const asset = ref<UserAssetVO | null>(null)
const history = ref<BalanceHistoryItem[]>([])
const plans = ref<VipRechargePlanVO[]>([])
const selectedPlan = ref<VipRechargePlanVO | null>(null)
const rechargeSectionRef = ref<HTMLElement | null>(null)
interface LevelStep {
name: string
@@ -74,10 +65,6 @@ const sceneIcon = (item: BalanceHistoryItem) => {
const memberLevel = computed(() => asset.value?.vipLevel || '普通会员')
const totalRecharge = computed(() => Number(asset.value?.totalRechargeAmount || 0))
const balanceAmount = computed(() => Number(asset.value?.balance || 0))
const sortedPlans = computed(() => [...plans.value].sort((left, right) => {
const sortDelta = Number(left.sortOrder || 0) - Number(right.sortOrder || 0)
return sortDelta || Number(left.rechargeAmount || 0) - Number(right.rechargeAmount || 0)
}))
const visibleHistory = computed(() => history.value.slice(0, visibleHistoryCount.value))
const canLoadMoreHistory = computed(() => visibleHistoryCount.value < history.value.length)
const currentStep = computed(() => {
@@ -93,9 +80,7 @@ const levelProgress = computed(() => {
})
const nextLevelText = computed(() => nextStep.value ? `下一等级:${nextStep.value.name}` : '已达最高等级')
const remainingAmountText = computed(() => {
const next = nextStep.value
if (!next) return '继续保持你的专属礼遇'
return `再充值 ¥${money(Math.max(next.amount - totalRecharge.value, 0))} 可升级`
return nextStep.value ? '等级按已有业务记录自动计算' : '当前等级已达最高等级'
})
const validityText = computed(() => {
const start = formatTime(asset.value?.vipStartTime)
@@ -104,48 +89,6 @@ const validityText = computed(() => {
if (expire === '--') return `${start} 起生效`
return `${start} - ${expire}`
})
const benefitCards = computed(() => [
{
icon: GiftOutlined,
title: '生日礼遇',
desc: '生日月专属美甲套装',
tone: 'rose'
},
{
icon: SafetyCertificateOutlined,
title: '优先预约',
desc: '热门时段优先锁定档期',
tone: 'gold'
},
{
icon: PercentageOutlined,
title: '专属优惠',
desc: asset.value?.benefitInfo || '会员专属折扣权益',
tone: 'slate'
},
{
icon: CrownOutlined,
title: '护理礼遇',
desc: '精选护理权益持续更新',
tone: 'cream'
}
])
const planTag = (index: number) => {
if (index === 0) return '超值'
if (index === 1) return '最佳选择'
return '尊享'
}
const openPlan = (plan: VipRechargePlanVO) => {
selectedPlan.value = plan
rechargeOpen.value = true
}
const scrollToRecharge = () => {
rechargeSectionRef.value?.scrollIntoView({ behavior: 'smooth', block: 'start' })
}
const loadMoreHistory = () => {
visibleHistoryCount.value += 3
}
@@ -159,7 +102,6 @@ const loadData = async () => {
])
asset.value = assetRes
history.value = historyRes || []
plans.value = await userApi.listMyVipRechargePlans().catch(() => [])
} catch (error: any) {
message.error(error?.message || '获取 VIP 信息失败')
} finally {
@@ -176,10 +118,8 @@ onMounted(loadData)
<button class="topbar-button" type="button" aria-label="返回" @click="router.back()">
<LeftOutlined />
</button>
<h1>VIP中心</h1>
<button class="topbar-button" type="button" aria-label="购物车" @click="router.push('/cart')">
<ShoppingOutlined />
</button>
<h1>会员权益</h1>
<span class="topbar-button-placeholder" aria-hidden="true"></span>
</header>
<a-spin :spinning="loading">
@@ -223,27 +163,6 @@ onMounted(loadData)
<TrophyOutlined class="hero-watermark" />
</section>
<section class="vip-section">
<div class="section-head">
<h3>会员特权</h3>
<button type="button" @click="scrollToRecharge">查看全部</button>
</div>
<div class="benefit-grid">
<article
v-for="item in benefitCards"
:key="item.title"
class="benefit-card"
:class="`benefit-card--${item.tone}`"
>
<span class="benefit-icon">
<component :is="item.icon" />
</span>
<strong>{{ item.title }}</strong>
<p>{{ item.desc }}</p>
</article>
</div>
</section>
<section class="vip-section member-info-section">
<div class="section-head">
<h3>会员信息</h3>
@@ -268,30 +187,11 @@ onMounted(loadData)
</div>
</section>
<section ref="rechargeSectionRef" class="vip-section recharge-section">
<section class="vip-section account-notice">
<div class="section-head">
<h3>快速充值</h3>
<h3>权益说明</h3>
</div>
<div v-if="sortedPlans.length" class="plan-grid">
<article
v-for="(plan, index) in sortedPlans"
:key="String(plan.id)"
class="plan-card"
:class="{ 'plan-card--featured': index === 1 }"
>
<div class="plan-tag" :class="{ 'plan-tag--featured': index === 1 }">
{{ planTag(index) }}
</div>
<span class="plan-title">{{ plan.title || plan.vipLevel }}</span>
<div class="plan-price">
<small>¥</small>
<strong>{{ money(plan.rechargeAmount).replace('.00', '') }}</strong>
</div>
<p>赠送 <b>¥{{ money(plan.giftAmount) }}</b> 奖励金</p>
<button type="button" @click="openPlan(plan)">立即充值</button>
</article>
</div>
<a-empty v-else description="暂无可展示充值档位" />
<p>当前页面仅展示已有会员权益、余额和历史记录,不提供在线充值或订阅操作。</p>
</section>
<section class="vip-section history-section">
@@ -328,14 +228,6 @@ onMounted(loadData)
</main>
</a-spin>
<a-modal v-model:open="rechargeOpen" title="充值档位说明" :footer="null">
<div class="plan-modal" v-if="selectedPlan">
<span class="modal-icon"><CreditCardOutlined /></span>
<h3>{{ selectedPlan.title || selectedPlan.vipLevel }}</h3>
<p>充值 ¥{{ money(selectedPlan.rechargeAmount) }},赠送 ¥{{ money(selectedPlan.giftAmount) }} 奖励金。</p>
<p>{{ selectedPlan.description || '该档位仅展示,暂不发起支付。' }}</p>
</div>
</a-modal>
</div>
</template>
@@ -414,6 +306,11 @@ onMounted(loadData)
font-size: 21px;
}
.topbar-button-placeholder {
width: 40px;
height: 40px;
}
.vip-main {
display: grid;
gap: 32px;
@@ -734,84 +631,18 @@ onMounted(loadData)
line-height: 1.35;
}
.plan-grid {
display: grid;
gap: 16px;
}
.plan-card {
position: relative;
display: grid;
gap: 13px;
padding: 24px;
.account-notice {
padding: 18px;
border: 1px solid var(--vip-outline-soft);
border-radius: 24px;
background: color-mix(in srgb, var(--vip-surface) 86%, transparent);
}
.plan-card--featured {
border-color: rgba(119, 90, 25, 0.24);
background: linear-gradient(135deg, rgba(255, 250, 240, 0.92), rgba(254, 212, 136, 0.28));
}
.plan-tag {
justify-self: start;
padding: 5px 11px;
border-radius: 999px;
color: var(--vip-primary);
background: var(--vip-blush-soft);
font-size: 10px;
font-weight: 900;
}
.plan-tag--featured {
position: absolute;
top: -11px;
right: 22px;
color: var(--vip-hero-text);
background: var(--vip-gold);
}
.plan-title {
color: var(--vip-muted);
}
.plan-price {
display: flex;
align-items: baseline;
gap: 5px;
color: var(--vip-primary);
}
.plan-price strong {
font-family: Georgia, 'Times New Roman', serif;
font-size: 40px;
line-height: 1;
}
.plan-card p {
.account-notice p {
margin: 0;
color: var(--vip-muted);
font-size: 14px;
}
.plan-card p b {
color: var(--vip-primary);
}
.plan-card button {
width: 100%;
min-height: 46px;
border: 0;
border-radius: 999px;
color: var(--vip-hero-text);
background: var(--vip-primary);
font-size: 14px;
font-weight: 850;
cursor: pointer;
box-shadow: 0 14px 28px rgba(124, 83, 87, 0.2);
}
.plan-card--featured button {
background: var(--vip-gold);
font-size: 13px;
line-height: 1.7;
}
.history-card {
@@ -897,36 +728,6 @@ onMounted(loadData)
cursor: pointer;
}
.plan-modal {
display: grid;
gap: 10px;
text-align: center;
}
.modal-icon {
display: grid;
width: 54px;
height: 54px;
margin: 0 auto;
place-items: center;
border-radius: 999px;
color: var(--vip-primary);
background: var(--vip-blush-soft);
font-size: 25px;
}
.plan-modal h3 {
margin: 4px 0 0;
font-size: 18px;
font-weight: 850;
}
.plan-modal p {
margin: 0;
color: var(--vip-muted);
line-height: 1.65;
}
@media (max-width: 370px) {
.vip-main {
padding-right: 14px;
@@ -950,8 +751,5 @@ onMounted(loadData)
border-top-right-radius: 32px;
}
.plan-grid {
grid-template-columns: repeat(3, minmax(0, 1fr));
}
}
</style>
@@ -173,15 +173,6 @@ const visibleModules = computed(() => {
icon: MessageOutlined,
permissionCode: 'announcement:view'
},
{
key: 'vip-plans',
title: 'VIP充值配置',
description: '维护充值档位和 VIP 等级来源。',
path: '/admin/vip-recharge-plans',
icon: GiftOutlined,
permissionCode: 'user:vip:manage',
requireShopContext: true
},
{
key: 'parameters',
title: '参数管理',
@@ -0,0 +1,277 @@
<template>
<div class="privacy-page">
<a-alert
type="warning"
show-icon
message="内容审核当前为本地模拟流程,不会调用微信内容安全接口。正式上线前需接入审核服务并复核隐私指引。"
class="page-notice"
/>
<a-tabs v-model:active-key="activeTab" @change="loadActiveTab">
<a-tab-pane key="closures" tab="账号注销申请">
<a-table :columns="closureColumns" :data-source="closures" :loading="closureLoading" row-key="id" :scroll="{ x: 'max-content' }">
<template #bodyCell="{ column, record }">
<template v-if="column.key === 'account'">{{ record.nickname }}({{ record.userType === 2 ? '店长' : '员工' }})</template>
<template v-else-if="column.key === 'shops'">{{ (record.shopNames || []).join('、') || '无关联门店' }}</template>
<template v-else-if="column.key === 'time'">{{ record.requestedAt || '-' }}</template>
<template v-else-if="column.key === 'action'">
<a-space>
<a-button type="link" @click="openClosure(record as AccountClosureRequestVO, 'APPROVE')">处理</a-button>
<a-button type="link" danger @click="openClosure(record as AccountClosureRequestVO, 'REJECT')">驳回</a-button>
</a-space>
</template>
</template>
</a-table>
</a-tab-pane>
<a-tab-pane key="moderation" tab="内容复核">
<a-table :columns="moderationColumns" :data-source="moderation" :loading="moderationLoading" row-key="id" :scroll="{ x: 'max-content' }">
<template #bodyCell="{ column, record }">
<template v-if="column.key === 'type'">{{ moderationType(record.contentType) }}</template>
<template v-else-if="column.key === 'content'">
<pre class="payload-preview">{{ formatPayload(record.payloadJson) }}</pre>
</template>
<template v-else-if="column.key === 'status'">{{ record.status === 'RETRY' ? '待复核(模拟服务故障)' : '待复核' }}</template>
<template v-else-if="column.key === 'action'">
<a-space>
<a-button type="link" @click="openModeration(record as ContentModerationRecordVO, true)">通过</a-button>
<a-button type="link" danger @click="openModeration(record as ContentModerationRecordVO, false)">拒绝</a-button>
</a-space>
</template>
</template>
</a-table>
</a-tab-pane>
<a-tab-pane key="backfill" tab="手机号加密回填">
<a-space direction="vertical" size="middle" class="backfill-panel">
<p>先查看冲突和待处理记录数。正式回填仅在 Nacos 显式启用后可执行;检测到重复数据时会整批停止,不覆盖冲突记录。</p>
<a-space>
<a-button :loading="backfillLoading" @click="loadBackfillReport">检查数据</a-button>
<a-button type="primary" danger :disabled="!backfillReport || hasBackfillConflicts" :loading="backfillLoading" @click="runBackfill">执行回填</a-button>
</a-space>
<a-descriptions v-if="backfillReport" bordered :column="2" size="small">
<a-descriptions-item label="待处理账号">{{ backfillReport.userRowsToUpdate }}</a-descriptions-item>
<a-descriptions-item label="待处理订单">{{ backfillReport.orderRowsToUpdate }}</a-descriptions-item>
<a-descriptions-item label="账号冲突">{{ backfillReport.accountConflictRows }}</a-descriptions-item>
<a-descriptions-item label="手机号冲突">{{ backfillReport.phoneConflictRows }}</a-descriptions-item>
</a-descriptions>
<a-alert v-if="backfillReport?.conflictingUserIds?.length" type="error" show-icon message="发现冲突,已禁止执行回填" :description="`涉及账号 ID:${backfillReport.conflictingUserIds.join('、')}`" />
</a-space>
</a-tab-pane>
</a-tabs>
<a-modal v-model:open="closureOpen" :title="closureDecision === 'APPROVE' ? '处理注销申请' : '驳回注销申请'" :confirm-loading="actionLoading" :mask-closable="false" @ok="submitClosure">
<template v-if="closureTarget && closureDecision === 'APPROVE'">
<div v-if="closureTarget.userType === 2 && closureTarget.shopIds?.length" class="closure-shops">
<p>关联门店:{{ (closureTarget.shopNames || []).join('、') }}</p>
<a-radio-group v-model:value="closureMode">
<a-radio value="transfer">移交门店</a-radio>
<a-radio value="archive">归档全部门店</a-radio>
</a-radio-group>
<a-select v-if="closureMode === 'transfer'" v-model:value="successorManagerId" class="full-width" placeholder="选择接手店长" :options="successorOptions" />
</div>
<p v-else>确认清理该账号资料并撤销其会话?必要业务记录会保留并去除账号身份关联。</p>
</template>
<a-form-item :label="closureDecision === 'REJECT' ? '驳回原因' : '处理说明'">
<a-textarea v-model:value="closureNote" :rows="3" :placeholder="closureDecision === 'REJECT' ? '请填写驳回原因' : '可填写处理说明'" />
</a-form-item>
</a-modal>
<a-modal v-model:open="moderationOpen" :title="moderationApproved ? '通过内容复核' : '拒绝内容'" :confirm-loading="actionLoading" :mask-closable="false" @ok="submitModeration">
<p v-if="moderationTarget">{{ moderationType(moderationTarget.contentType) }}内容,记录号 {{ moderationTarget.id }}</p>
<a-form-item label="复核说明"><a-textarea v-model:value="moderationReason" :rows="3" placeholder="说明本次模拟复核结果" /></a-form-item>
</a-modal>
</div>
</template>
<script setup lang="ts">
import { computed, onMounted, ref } from 'vue'
import { message, Modal } from 'ant-design-vue'
import {
adminPrivacyComplianceApi,
type AccountClosureRequestVO,
type ClosureSuccessorManagerVO,
type ContentModerationRecordVO,
type PhoneBackfillReportVO
} from '@/api/admin'
const activeTab = ref('closures')
const closures = ref<AccountClosureRequestVO[]>([])
const moderation = ref<ContentModerationRecordVO[]>([])
const successorManagers = ref<ClosureSuccessorManagerVO[]>([])
const backfillReport = ref<PhoneBackfillReportVO | null>(null)
const closureLoading = ref(false)
const moderationLoading = ref(false)
const backfillLoading = ref(false)
const actionLoading = ref(false)
const closureOpen = ref(false)
const closureTarget = ref<AccountClosureRequestVO | null>(null)
const closureDecision = ref<'APPROVE' | 'REJECT'>('APPROVE')
const closureMode = ref<'transfer' | 'archive'>('transfer')
const successorManagerId = ref<string | number>()
const closureNote = ref('')
const moderationOpen = ref(false)
const moderationTarget = ref<ContentModerationRecordVO | null>(null)
const moderationApproved = ref(false)
const moderationReason = ref('')
const hasBackfillConflicts = computed(() => Boolean(backfillReport.value?.accountConflictRows || backfillReport.value?.phoneConflictRows))
const successorOptions = computed(() => successorManagers.value.map(manager => ({ label: `${manager.nickname || '店长'}(${manager.id})`, value: manager.id })))
const closureColumns = [
{ title: '申请人', key: 'account' },
{ title: '关联门店', key: 'shops' },
{ title: '申请时间', key: 'time' },
{ title: '处理', key: 'action', width: 140 }
]
const moderationColumns = [
{ title: '类型', key: 'type', width: 120 },
{ title: '隔离内容', key: 'content', width: 420 },
{ title: '状态', key: 'status', width: 180 },
{ title: '提交时间', dataIndex: 'createTime', key: 'createTime' },
{ title: '复核', key: 'action', width: 140 }
]
async function loadClosures() {
closureLoading.value = true
try {
const [items, managers] = await Promise.all([
adminPrivacyComplianceApi.listClosures(),
adminPrivacyComplianceApi.listSuccessorManagers()
])
closures.value = items || []
successorManagers.value = managers || []
} catch (error) {
message.error(error instanceof Error ? error.message : '获取注销申请失败')
} finally {
closureLoading.value = false
}
}
async function loadModeration() {
moderationLoading.value = true
try { moderation.value = await adminPrivacyComplianceApi.listModeration() || [] }
catch (error) { message.error(error instanceof Error ? error.message : '获取复核列表失败') }
finally { moderationLoading.value = false }
}
function loadActiveTab() {
if (activeTab.value === 'closures') void loadClosures()
if (activeTab.value === 'moderation') void loadModeration()
if (activeTab.value === 'backfill') void loadBackfillReport()
}
function openClosure(record: AccountClosureRequestVO, decision: 'APPROVE' | 'REJECT') {
closureTarget.value = record
closureDecision.value = decision
closureMode.value = 'transfer'
successorManagerId.value = undefined
closureNote.value = decision === 'REJECT' ? '' : '已完成门店交接或归档,并按要求清理账号资料。'
closureOpen.value = true
}
async function submitClosure() {
if (!closureTarget.value) return
if (closureDecision.value === 'REJECT' && !closureNote.value.trim()) {
message.warning('请填写驳回原因')
return
}
const managerHasShops = closureDecision.value === 'APPROVE' && closureTarget.value.userType === 2 && (closureTarget.value.shopIds || []).length > 0
if (managerHasShops && closureMode.value === 'transfer' && !successorManagerId.value) {
message.warning('请选择接手店长')
return
}
if (managerHasShops && closureMode.value === 'archive' && !(await confirmArchive())) return
actionLoading.value = true
try {
await adminPrivacyComplianceApi.processClosure(closureTarget.value.id, {
decision: closureDecision.value,
successorManagerId: managerHasShops && closureMode.value === 'transfer' ? successorManagerId.value : undefined,
archiveShopIds: managerHasShops && closureMode.value === 'archive' ? closureTarget.value.shopIds : undefined,
note: closureNote.value.trim() || undefined
})
message.success(closureDecision.value === 'APPROVE' ? '账号资料已处理' : '申请已驳回')
closureOpen.value = false
await loadClosures()
} catch (error) { message.error(error instanceof Error ? error.message : '处理失败') }
finally { actionLoading.value = false }
}
function confirmArchive() {
return new Promise<boolean>(resolve => Modal.confirm({
title: '确认归档全部门店?',
content: '归档后关联门店将停止营业,请确认已完成必要交接。',
okText: '确认归档',
cancelText: '返回',
onOk: () => resolve(true),
onCancel: () => resolve(false)
}))
}
function openModeration(record: ContentModerationRecordVO, approved: boolean) {
moderationTarget.value = record
moderationApproved.value = approved
moderationReason.value = approved ? '本地模拟复核通过。' : ''
moderationOpen.value = true
}
async function submitModeration() {
if (!moderationTarget.value) return
if (!moderationReason.value.trim()) {
message.warning('请填写复核说明')
return
}
actionLoading.value = true
try {
await adminPrivacyComplianceApi.reviewContent(moderationTarget.value.id, { approved: moderationApproved.value, reason: moderationReason.value.trim() })
message.success(moderationApproved.value ? '内容已通过复核' : '内容已拒绝')
moderationOpen.value = false
await loadModeration()
} catch (error) { message.error(error instanceof Error ? error.message : '复核失败') }
finally { actionLoading.value = false }
}
async function loadBackfillReport() {
backfillLoading.value = true
try { backfillReport.value = await adminPrivacyComplianceApi.phoneBackfillReport() }
catch (error) { message.error(error instanceof Error ? error.message : '检查失败') }
finally { backfillLoading.value = false }
}
function runBackfill() {
Modal.confirm({
title: '执行手机号加密回填?',
content: '该操作只更新无重复冲突的历史账号和订单手机号。请确认已在目标环境 Nacos 显式开启回填开关。',
okText: '执行回填',
cancelText: '取消',
onOk: async () => {
backfillLoading.value = true
try {
backfillReport.value = await adminPrivacyComplianceApi.runPhoneBackfill()
message.success(`回填完成:账号 ${backfillReport.value.userRowsUpdated} 条,订单 ${backfillReport.value.orderRowsUpdated} 条`)
} catch (error) { message.error(error instanceof Error ? error.message : '回填失败') }
finally { backfillLoading.value = false }
}
})
}
function moderationType(type: string) {
return ({ USER_PROFILE: '个人资料', USER_AVATAR: '头像', PRODUCT: '作品', COMMENT: '评论' } as Record<string, string>)[type] || type
}
function formatPayload(value?: string) {
if (!value) return '无待复核载荷'
try { return JSON.stringify(JSON.parse(value), null, 2) } catch { return value }
}
onMounted(loadActiveTab)
</script>
<style scoped>
.privacy-page { display: grid; gap: 16px; }
.page-notice { border-radius: 8px; }
.payload-preview { max-width: 420px; max-height: 180px; margin: 0; overflow: auto; white-space: pre-wrap; word-break: break-word; font-size: 12px; }
.backfill-panel { width: 100%; padding: 8px 0; }
.closure-shops { display: grid; gap: 12px; margin-bottom: 16px; }
.closure-shops p { margin: 0; }
.full-width { width: 100%; margin-top: 12px; }
</style>
@@ -220,7 +220,7 @@
<a-form-item label="账号" name="account">
<a-input
v-model:value="formState.account"
placeholder="请输入账号"
:placeholder="isEdit && isMaskedSensitiveValue(currentUser?.account) ? '已设置账号,留空保持不变' : '请输入账号'"
@input="handleAccountInput"
/>
</a-form-item>
@@ -230,7 +230,7 @@
<a-form-item label="手机号" name="phone">
<a-input
v-model:value="formState.phone"
placeholder="请输入手机号"
:placeholder="isEdit && isMaskedSensitiveValue(currentUser?.phone) ? '已设置手机号,留空保持不变' : '请输入手机号'"
:maxlength="11"
inputmode="numeric"
autocomplete="off"
@@ -964,6 +964,8 @@ const validatePhoneUniqueness = async (value: string) => {
}
}
const isMaskedSensitiveValue = (value?: string | null) => /^1[3-9]\d\*{4}\d{4}$/.test(String(value || '').trim())
const validateOptionalPasswordStrength = (value?: string) => {
const password = value?.trim()
if (!password) {
@@ -1089,14 +1091,21 @@ const handleClearVipDraft = (showMessage = true) => {
*/
const formRules = {
account: [
{ required: true, message: '请输入账号', trigger: 'blur' },
{ pattern: ACCOUNT_REGEX, message: ACCOUNT_RULE_MESSAGE, trigger: 'blur' }
{
validator: (_rule: unknown, value: string) => {
if (isEdit.value && !value?.trim()) return Promise.resolve()
if (!value?.trim()) return Promise.reject('请输入账号')
if (!ACCOUNT_REGEX.test(value.trim())) return Promise.reject(ACCOUNT_RULE_MESSAGE)
return Promise.resolve()
},
trigger: 'blur'
}
],
nickname: [{ required: true, message: '请输入昵称', trigger: 'blur' }],
phone: [
{ required: true, message: '请输入手机号', trigger: 'blur' },
{
validator: async (_rule: unknown, value: string) => {
if (isEdit.value && !value?.trim()) return Promise.resolve()
await validatePhoneUniqueness(value)
return Promise.resolve()
},
@@ -1480,10 +1489,10 @@ const showEditModal = (record: any) => {
isEdit.value = true
currentUser.value = record
Object.assign(formState, {
account: record.account,
account: isMaskedSensitiveValue(record.account) ? '' : record.account,
nickname: record.nickname,
phone: record.phone || record.contactPhone || '',
contactPhone: record.phone || record.contactPhone || '',
phone: isMaskedSensitiveValue(record.phone || record.contactPhone) ? '' : (record.phone || record.contactPhone || ''),
contactPhone: isMaskedSensitiveValue(record.phone || record.contactPhone) ? '' : (record.phone || record.contactPhone || ''),
birthday: record.birthday || '',
wechatId: record.wechatId || '',
wechatQrCode: record.wechatQrCode || '',
@@ -1492,6 +1501,11 @@ const showEditModal = (record: any) => {
shopIds: resolveEditableShopIds(record)
})
restoreDraft()
if (isMaskedSensitiveValue(formState.account)) formState.account = ''
if (isMaskedSensitiveValue(formState.phone)) {
formState.phone = ''
formState.contactPhone = ''
}
modalVisible.value = true
}
@@ -1584,6 +1598,12 @@ const handleModalOk = async () => {
...(formState.password.trim() ? { password: formState.password.trim() } : {})
}
if (isEdit.value && !formState.account.trim()) delete requestData.account
if (isEdit.value && !primaryPhone) {
delete requestData.phone
delete requestData.contactPhone
}
if (isEdit.value && currentUserType.value !== 4) {
delete requestData.shopIds
delete requestData.shopId
@@ -21,7 +21,7 @@ import adminApi, {
adminWorkbenchRegistrationApi
} from '../../src/api/admin'
import api from '../../src/api'
import { afterSaleApi, growthApi, paymentApi } from '../../src/api/order'
import { afterSaleApi, growthApi } from '../../src/api/order'
type CapturedRequest = {
method?: string
@@ -115,15 +115,11 @@ describe('vNext API contracts', () => {
const requests: CapturedRequest[] = []
api.defaults.adapter = captureAdapter(requests)
await paymentApi.prepareOrderPayment(42)
await paymentApi.mockSuccess(42)
await afterSaleApi.apply({ orderId: 42, type: 'REFUND', reason: 'schedule changed', refundAmount: 88 })
await afterSaleApi.listMy({ page: 1, size: 5 })
await growthApi.getSummary()
expect(requests).toEqual([
{ method: 'post', url: '/payment/order/42/prepare', params: undefined, data: undefined },
{ method: 'post', url: '/payment/order/42/mock-success', params: undefined, data: undefined },
{ method: 'post', url: '/after-sale/apply', params: undefined, data: { orderId: 42, type: 'REFUND', reason: 'schedule changed', refundAmount: 88 } },
{ method: 'get', url: '/after-sale/my', params: { page: 1, size: 5 }, data: undefined },
{ method: 'get', url: '/growth/summary', params: undefined, data: undefined }
+30
View File
@@ -40,6 +40,24 @@ module.exports = {
})
},
unbindPhone(verificationCode) {
return request({
url: '/user/unbind-phone',
method: 'POST',
params: { __baseUrl: API_DOMAIN },
data: { verificationCode }
})
},
sendUnbindPhoneCode() {
return request({
url: '/user/unbind-phone/send-code',
method: 'POST',
params: { __baseUrl: API_DOMAIN },
data: {}
})
},
sendBindPhoneCode(phone) {
return request({
url: '/user/send-verification-code',
@@ -47,5 +65,17 @@ module.exports = {
params: { __baseUrl: API_DOMAIN },
data: { phone, sceneCode: 'USER_BIND_PHONE' }
})
},
getAccountClosure() {
return request({ url: '/user/account-closure/me', params: { __baseUrl: API_DOMAIN } })
},
requestAccountClosure() {
return request({ url: '/user/account-closure', method: 'POST', params: { __baseUrl: API_DOMAIN }, data: {} })
},
withdrawAccountClosure() {
return request({ url: '/user/account-closure/me', method: 'DELETE', params: { __baseUrl: API_DOMAIN } })
}
}
+28 -2
View File
@@ -36,6 +36,10 @@ async function run() {
reset({ rememberMe: true, agreementVersions: { USER_TERMS: '1', PRIVACY_POLICY: '1' } })
let statusCalled = false
authApi.wechatStatus = async () => { statusCalled = true; return { status: 'READY' } }
authApi.getCurrentAgreements = async () => [
{ agreementType: 'USER_TERMS', version: '1' },
{ agreementType: 'PRIVACY_POLICY', version: '1' }
]
authApi.wechatQuickLogin = async () => ({ status: 'SUCCESS', accessToken: 'token', userInfo: { id: 1 } })
await appDefinition.runWechatBootstrap()
assert.deepStrictEqual(navigations, ['/pages/planning/index'])
@@ -47,14 +51,32 @@ async function run() {
reset({ rememberMe: false })
let quickLoginCalled = false
authApi.wechatStatus = async () => ({ status: 'READY' })
let agreementsRead = false
authApi.getCurrentAgreements = async () => { agreementsRead = true; return [] }
authApi.wechatQuickLogin = async () => { quickLoginCalled = true }
await appDefinition.runWechatBootstrap()
assert.deepStrictEqual(navigations, ['/pages/login/index'])
assert.strictEqual(quickLoginCalled, false)
assert.strictEqual(codeSequence, 1)
assert.strictEqual(agreementsRead, false)
assert.strictEqual(codeSequence, 0)
reset({ rememberMe: true, agreementVersions: { USER_TERMS: '1', PRIVACY_POLICY: '1' } })
let codeRequestedAfterVersionChange = false
authApi.getCurrentAgreements = async () => [
{ agreementType: 'USER_TERMS', version: '2' },
{ agreementType: 'PRIVACY_POLICY', version: '1' }
]
authApi.wechatQuickLogin = async () => { codeRequestedAfterVersionChange = true }
await appDefinition.runWechatBootstrap()
assert.deepStrictEqual(navigations, ['/pages/login/index'])
assert.strictEqual(codeRequestedAfterVersionChange, false)
assert.strictEqual(codeSequence, 0)
reset({ rememberMe: true, agreementVersions: { USER_TERMS: '1', PRIVACY_POLICY: '1' } })
authApi.getCurrentAgreements = async () => [
{ agreementType: 'USER_TERMS', version: '1' },
{ agreementType: 'PRIVACY_POLICY', version: '1' }
]
authApi.wechatQuickLogin = async () => { throw new Error('网络异常') }
await appDefinition.runWechatBootstrap()
assert.deepStrictEqual(navigations, ['/pages/login/index'])
@@ -62,6 +84,10 @@ async function run() {
assert.strictEqual(appDefinition.globalData.wechatLoginState.status, 'ERROR')
reset({ rememberMe: true, agreementVersions: { USER_TERMS: '1', PRIVACY_POLICY: '1' } })
authApi.getCurrentAgreements = async () => [
{ agreementType: 'USER_TERMS', version: '1' },
{ agreementType: 'PRIVACY_POLICY', version: '1' }
]
authApi.wechatQuickLogin = async () => ({ status: 'SELECT_SHOP', ticket: 'ticket', shops: [{ id: 2 }] })
await appDefinition.runWechatBootstrap()
assert.deepStrictEqual(navigations, ['/pages/login/index'])
+25 -2
View File
@@ -41,10 +41,20 @@ App({
try {
const preference = auth.getLoginPreference()
if (!preference || !preference.rememberMe) {
const status = await authApi.wechatStatus(await this.getWechatCode())
this.publishWechatLoginState(status)
auth.clearSession()
this.globalData.userInfo = null
this.publishWechatLoginState({ status: 'NEED_AGREEMENT' })
this.goLogin()
return
}
const agreements = await authApi.getCurrentAgreements()
const currentVersions = agreementVersions(agreements)
// 协议版本变化后必须重新征求同意,不能先交换 code 再补弹窗。
if (!hasMatchingAgreementVersions(preference.agreementVersions, currentVersions)) {
auth.clearSession()
this.globalData.userInfo = null
this.publishWechatLoginState({ status: 'NEED_AGREEMENT' })
this.goLogin()
return
}
@@ -124,3 +134,16 @@ App({
this.globalData.openEmployeeReview = false
}
})
function agreementVersions(agreements) {
return (Array.isArray(agreements) ? agreements : []).reduce((versions, item) => {
if (item && item.agreementType && item.version) versions[item.agreementType] = item.version
return versions
}, {})
}
function hasMatchingAgreementVersions(accepted, current) {
return Boolean(accepted && current && accepted.USER_TERMS && accepted.PRIVACY_POLICY
&& accepted.USER_TERMS === current.USER_TERMS
&& accepted.PRIVACY_POLICY === current.PRIVACY_POLICY)
}
+1
View File
@@ -19,6 +19,7 @@
"pages/profile/index",
"pages/profile-edit/index",
"pages/account-settings/index",
"pages/legal/index",
"pages/shop-settings/index",
"pages/export/index",
"pages/password/index",
@@ -12,10 +12,51 @@ Page({
codeLoading: false,
countdown: 0,
timer: null,
smsExpanded: false
smsExpanded: false,
unbindMode: false,
closureRequest: null
},
onShow() { this.loadProfile() },
onShow() { this.loadProfile(); this.loadClosureRequest() },
async loadClosureRequest() {
try {
const closureRequest = await userApi.getAccountClosure()
this.setData({ closureRequest: closureRequest || null })
} catch (error) {
this.setData({ closureRequest: null })
}
},
async requestClosure() {
const confirmed = await new Promise(resolve => wx.showModal({
title: '申请注销账号',
content: '申请提交后由管理人员处理。完成后会清理账号身份资料,必要业务记录仍按保存要求保留。你可以在处理前撤回。',
confirmText: '提交申请',
success: result => resolve(result.confirm),
fail: () => resolve(false)
}))
if (!confirmed) return
try {
const closureRequest = await userApi.requestAccountClosure()
this.setData({ closureRequest })
wx.showToast({ title: '注销申请已提交' })
} catch (error) {
wx.showToast({ title: error.message || '申请提交失败', icon: 'none' })
}
},
async withdrawClosure() {
const confirmed = await new Promise(resolve => wx.showModal({ title: '撤回注销申请', content: '确定撤回账号注销申请吗?', success: result => resolve(result.confirm), fail: () => resolve(false) }))
if (!confirmed) return
try {
await userApi.withdrawAccountClosure()
await this.loadClosureRequest()
wx.showToast({ title: '申请已撤回' })
} catch (error) {
wx.showToast({ title: error.message || '撤回失败', icon: 'none' })
}
},
async loadProfile(options = {}) {
this.setData({ loading: true })
@@ -39,7 +80,11 @@ Page({
},
toggleSms() {
this.setData({ smsExpanded: !this.data.smsExpanded })
this.setData({ smsExpanded: !this.data.smsExpanded, unbindMode: false })
},
beginUnbind() {
this.setData({ smsExpanded: true, unbindMode: true, 'smsForm.code': '' })
},
async bindWechatPhone(event) {
@@ -62,13 +107,14 @@ Page({
async sendCode() {
const phone = String(this.data.smsForm.phone || '')
if (!/^1[3-9]\d{9}$/.test(phone)) {
if (!this.data.unbindMode && !/^1[3-9]\d{9}$/.test(phone)) {
wx.showToast({ title: '请输入正确手机号', icon: 'none' }); return
}
if (this.data.codeLoading || this.data.countdown) return
this.setData({ codeLoading: true })
try {
await userApi.sendBindPhoneCode(phone)
if (this.data.unbindMode) await userApi.sendUnbindPhoneCode()
else await userApi.sendBindPhoneCode(phone)
this.startCountdown()
wx.showToast({ title: '验证码已发送' })
} catch (error) {
@@ -107,6 +153,33 @@ Page({
}
},
async unbindSmsPhone() {
const code = String(this.data.smsForm.code || '')
if (!/^\d{6}$/.test(code)) {
wx.showToast({ title: '请输入当前手机号收到的6位验证码', icon: 'none' }); return
}
const confirmed = await new Promise(resolve => wx.showModal({
title: '解绑手机号',
content: '解绑后手机号将从账号资料中删除,短信验证码仅用于验证当前手机号。确定继续吗?',
confirmText: '确认解绑',
success: result => resolve(result.confirm),
fail: () => resolve(false)
}))
if (!confirmed) return
this.setData({ binding: true })
try {
await userApi.unbindPhone(code)
profileCache.invalidate()
this.setData({ unbindMode: false, smsExpanded: false, 'smsForm.code': '' })
await this.loadProfile({ force: true })
wx.showToast({ title: '手机号已解绑' })
} catch (error) {
wx.showToast({ title: error.message || '解绑失败', icon: 'none' })
} finally {
this.setData({ binding: false })
}
},
async logout() {
const confirmed = await new Promise(resolve => wx.showModal({ title: '退出登录', content: '退出后将关闭自动登录,并清除本机提醒设置。', success: result => resolve(result.confirm), fail: () => resolve(false) }))
if (!confirmed) return
@@ -3,14 +3,28 @@
<view class="card phone-card">
<view class="section-title">手机号</view>
<view class="phone-status"><text>{{profile.phoneVerified == 1 ? (profile.maskedPhone || profile.phone) : '尚未绑定'}}</text><text class="status-tag {{profile.phoneVerified == 1 ? 'done' : ''}}">{{profile.phoneVerified == 1 ? '已验证' : '待绑定'}}</text></view>
<view class="privacy-note">手机号绑定为可选,不绑定不影响基础使用。仅用于账号找回和必要订单通知;不会用于营销。</view>
<button class="wechat-phone-btn" open-type="getPhoneNumber" loading="{{binding}}" bindgetphonenumber="bindWechatPhone">快速{{profile.phoneVerified == 1 ? '更换' : '绑定'}}手机号</button>
<view class="sms-entry" bindtap="toggleSms"><text>{{profile.phoneVerified == 1 ? '使用短信验证码更换' : '使用短信验证码绑定'}}</text><text class="sms-arrow {{smsExpanded ? 'expanded' : ''}}">›</text></view>
<view wx:if="{{smsExpanded}}" class="sms-panel">
<view class="field"><input value="{{smsForm.phone}}" data-field="phone" bindinput="onInput" type="number" maxlength="11" placeholder="请输入手机号" /></view>
<view wx:if="{{!unbindMode}}" class="field"><input value="{{smsForm.phone}}" data-field="phone" bindinput="onInput" type="number" maxlength="11" placeholder="请输入手机号" /></view>
<view wx:if="{{unbindMode}}" class="privacy-note">验证码将发送到当前绑定的{{profile.maskedPhone || '手机号'}},仅用于核验解绑操作。</view>
<view wx:if="{{!unbindMode}}" class="privacy-note">发送前再次确认:手机号仅用于账号找回和必要订单通知,不用于营销。</view>
<view class="code-row"><input value="{{smsForm.code}}" data-field="code" bindinput="onInput" type="number" maxlength="6" placeholder="6位验证码" /><button bindtap="sendCode" disabled="{{codeLoading || countdown > 0}}">{{countdown > 0 ? countdown + 's' : '获取验证码'}}</button></view>
<button class="sms-bind-btn" loading="{{binding}}" bindtap="bindSmsPhone">验证并绑定</button>
<button wx:if="{{!unbindMode}}" class="sms-bind-btn" loading="{{binding}}" bindtap="bindSmsPhone">验证并绑定</button>
<button wx:if="{{unbindMode}}" class="sms-bind-btn" loading="{{binding}}" bindtap="unbindSmsPhone">验证并解绑</button>
</view>
<view wx:if="{{profile.phoneVerified == 1}}" class="sms-entry unbind-entry" bindtap="beginUnbind"><text>解绑当前手机号</text><text class="sms-arrow">›</text></view>
</view>
<view class="account-note">微信身份是账号登录标识,手机号是可选资料,不作为主账号 ID。</view>
<view class="card closure-card">
<view class="section-title">账号注销</view>
<view wx:if="{{closureRequest && (closureRequest.status === 'PENDING' || closureRequest.status === 'PROCESSING')}}" class="privacy-note">申请处理中,{{closureRequest.processingTargetText || '以管理人员审核和门店交接进度为准'}}</view>
<view wx:elif="{{closureRequest && closureRequest.status === 'APPROVED'}}" class="privacy-note">账号资料已完成清理。</view>
<view wx:elif="{{closureRequest && closureRequest.status === 'REJECTED'}}" class="privacy-note">上次申请未通过:{{closureRequest.reviewerNote || '请联系管理人员'}}</view>
<view wx:else class="privacy-note">可申请注销工作台账号。提交后可在管理人员处理前撤回。</view>
<button wx:if="{{closureRequest && closureRequest.status === 'PENDING'}}" class="closure-btn secondary" bindtap="withdrawClosure">撤回注销申请</button>
<button wx:elif="{{!closureRequest || closureRequest.status !== 'APPROVED'}}" class="closure-btn" bindtap="requestClosure">申请注销账号</button>
</view>
<view class="account-note">手机号仅用于账号安全与必要联系,不作为微信快捷登录标识。</view>
<button class="logout-btn" bindtap="logout">退出登录</button>
</view>
@@ -1,2 +1,16 @@
.settings-page { padding-top:24rpx; }.identity-card { display:flex; align-items:center; padding:26rpx; }.identity-mark { display:flex; align-items:center; justify-content:center; width:68rpx; height:68rpx; border-radius:20rpx; background:#e5f4ed; color:#247b63; font-size:28rpx; font-weight:800; }.identity-copy { display:flex; flex:1; flex-direction:column; margin-left:18rpx; }.identity-title,.section-title { color:#17211f; font-size:28rpx; font-weight:800; }.identity-status { margin-top:6rpx; color:#71807a; font-size:21rpx; }.linked-badge,.status-tag { padding:7rpx 14rpx; border-radius:999rpx; background:#e5f2e8; color:#397055; font-size:20rpx; }
.phone-card { margin-top:20rpx; padding:28rpx; }.phone-status { display:flex; align-items:center; justify-content:space-between; margin-top:20rpx; padding:20rpx; border-radius:14rpx; background:#f3f7f4; color:#71807a; font-size:26rpx; }.status-tag { background:#fff0db; color:#9a682e; }.status-tag.done { background:#e5f2e8; color:#397055; }.wechat-phone-btn,.sms-bind-btn { height:80rpx; margin-top:22rpx; border-radius:14rpx; background:#247b63; color:#fff; font-size:26rpx; line-height:80rpx; }.sms-entry { display:flex; min-height:82rpx; align-items:center; margin-top:22rpx; border-top:1rpx solid #e5ebe7; color:#71807a; font-size:23rpx; }.sms-arrow { margin-left:auto; color:#95a198; font-size:36rpx; transition:transform 180ms ease; }.sms-arrow.expanded { transform:rotate(90deg); }.sms-panel { padding-top:2rpx; }.field input,.code-row input { box-sizing:border-box; height:78rpx; padding:0 20rpx; border:1rpx solid #dde8e0; border-radius:12rpx; background:#f8faf8; }.code-row { display:flex; gap:12rpx; margin-top:14rpx; }.code-row input { min-width:0; flex:1; }.code-row button { width:190rpx; height:78rpx; padding:0; border-radius:12rpx; background:#e7f0ea; color:#426c57; font-size:23rpx; line-height:78rpx; }.sms-bind-btn { background:#eef4f0; color:#247b63; }.account-note { margin:24rpx 18rpx; color:#71807a; font-size:21rpx; line-height:1.6; }.logout-btn { margin-top:52rpx; background:transparent; color:#a24f42; font-size:25rpx; }
.privacy-note {
margin: 12rpx 0;
color: #73817b;
font-size: 24rpx;
line-height: 1.6;
}
.unbind-entry {
color: #8a5555;
}
.closure-card { margin-top: 20rpx; padding: 28rpx; }
.closure-btn { height: 76rpx; margin-top: 18rpx; border-radius: 12rpx; background: #fff1ef; color: #9a5147; font-size: 24rpx; line-height: 76rpx; }
.closure-btn.secondary { background: #eef4f0; color: #426c57; }
+23
View File
@@ -0,0 +1,23 @@
const authApi = require('../../api/auth')
Page({
data: { loading: true, agreement: null },
onLoad(options) {
this.load(options && options.type)
},
async load(type) {
const agreementType = type === 'PRIVACY_POLICY' ? 'PRIVACY_POLICY' : 'USER_TERMS'
this.setData({ loading: true })
try {
const agreements = await authApi.getCurrentAgreements()
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' })
} finally {
this.setData({ loading: false })
}
}
})
+5
View File
@@ -0,0 +1,5 @@
{
"navigationBarTitleText": "协议与隐私",
"navigationBarBackgroundColor": "#F3F7F4",
"navigationBarTextStyle": "black"
}
+9
View File
@@ -0,0 +1,9 @@
<view class="page legal-page">
<view wx:if="{{loading}}" class="legal-state">正在加载…</view>
<view wx:elif="{{agreement}}" class="legal-document card">
<text class="legal-title">{{agreement.title}}</text>
<text class="legal-version">版本 {{agreement.version}}</text>
<text class="legal-content" selectable>{{agreement.content}}</text>
</view>
<view wx:else class="legal-state">当前内容暂不可用,请稍后重试。</view>
</view>
+6
View File
@@ -0,0 +1,6 @@
.legal-page { padding: 24rpx; }
.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; }
+2
View File
@@ -32,6 +32,8 @@ Page({
{ title: '账号设置', url: '/pages/account-settings/index' },
{ title: '店铺设置', url: '/pages/shop-settings/index' },
{ title: '数据导出', url: '/pages/export/index' },
{ title: '用户协议', url: '/pages/legal/index?type=USER_TERMS' },
{ title: '隐私政策', url: '/pages/legal/index?type=PRIVACY_POLICY' },
{ title: '关于系统', url: '/pages/about/index' }
]
},
-36
View File
@@ -1,36 +0,0 @@
const DEVICE_ID_KEY = 'jayucloud-salon_device_id'
function createDeviceId() {
const randomText = Math.random().toString(36).slice(2, 10)
return `manager-mini-device-${Date.now()}-${randomText}`
}
function assertStorageApi() {
if (typeof wx === 'undefined' || typeof wx.getStorageSync !== 'function' || typeof wx.setStorageSync !== 'function') {
throw new Error('wx storage API is required to build request signature device id')
}
}
function readDeviceId() {
assertStorageApi()
return wx.getStorageSync(DEVICE_ID_KEY) || ''
}
function writeDeviceId(value) {
assertStorageApi()
wx.setStorageSync(DEVICE_ID_KEY, value)
}
function getDeviceId() {
const current = readDeviceId()
if (current) {
return current
}
const next = createDeviceId()
writeDeviceId(next)
return next
}
module.exports = {
getDeviceId
}
+1 -5
View File
@@ -1,9 +1,7 @@
const { ADMIN_API_BASE_URL, REQUEST_TIMEOUT, ENABLE_REQUEST_SIGNING } = require('./config')
const auth = require('./auth')
const { getDeviceId } = require('./device')
const { sha256Hex, hmacSha256Hex, buildCanonicalParams, buildJsonPayload, randomNonce } = require('./crypto')
const DEVICE_ID_HEADER = 'X-Device-Id'
const HEADER_TIMESTAMP = 'X-Timestamp'
const HEADER_NONCE = 'X-Nonce'
const HEADER_SIGNATURE = 'X-Signature'
@@ -123,9 +121,7 @@ function isAuthFreePath(url) {
}
function buildSignatureHeaders(options) {
const headers = {
[DEVICE_ID_HEADER]: getDeviceId()
}
const headers = {}
const method = String(options.method || 'GET').toUpperCase()
const accessToken = auth.getAccessToken()
if (accessToken && !isAuthFreePath(options.url)) {
@@ -0,0 +1,62 @@
# Salon 合规整改配置说明
更新时间:2026-10-21
## 配置范围
本说明覆盖 Salon Core 的本地内容审核 Provider、手机号加密与索引、历史手机号回填,以及协议静态页和 SQL 基线。配置样例位于 `nacos/namespaces/<environment>/jayucloud-salon/DEFAULT_GROUP/`。本次只修改仓库文件,不连接或发布实际 Nacos、数据库和微信后台。
## 内容审核 MOCK
`core.yaml` 使用以下配置:
```yaml
jayucloud-salon:
privacy:
content-moderation:
provider: mock
```
- 仅 DEV 使用 `mock`。本地模拟仅在内容含 `[[MOCK:APPROVE]]`、`[[MOCK:REJECT]]`、`[[MOCK:PENDING]]` 或 `[[MOCK:FAIL]]` 时触发对应测试结果;未命中时进入待复核。
- SIT 和 PROD 使用 `disabled`。未配置或 Provider 故障时 fail-closed,内容进入隔离/人工复核,不会自动放行。
- 此 Provider 只用于开发与测试,不请求微信接口,不构成正式审核能力。禁止把 MOCK 结果作为上线审核结论。
- 后续接入微信内容安全平台时,应新增正式 Provider,并另行完成微信后台隐私指引、第三方处理方、内容传输范围及失败重试流程评估。
## 手机号密钥
`secret.yaml` 中各环境使用独立的 Base64 密钥:
```yaml
jayucloud-salon:
privacy:
phone-crypto:
encryption-key: "<每环境独立的32字节AES密钥,Base64编码>"
index-key: "<每环境独立的HMAC密钥,至少32字节,Base64编码>"
backfill-enabled: false
backfill-page-size: 500
```
- AES-GCM 密钥用于账号、客户和訂單快照手机号加密;HMAC 密钥独立用于查重、檢索,不可与加密密钥相同。
- 密钥必须由维护人员按环境生成并妥善备份;不能在各环境间复用。更换密钥前必须先完成密文重加密方案,直接替换会导致历史手机号不可解密。
- 仓库中的 Nacos 文件是配置源,不代表已发布到 Nacos。发布前需确认目标环境密钥已替换为专用值、配置读取权限受限且审计可追溯。
## 历史手机号回填
- 新空库字段及索引已合入 `docs/scripts/sql/init/jayucloud-salon.sql`。已部署数据库不得重跑完整初始化脚本;需先独立编制并审核对应的版本变更脚本。
- 后台“隐私合规”页可先生成 dry-run 冲突报告。发现账号或手机号重复时,批次停止且不覆盖冲突数据。
- 执行回填必须先在目标环境显式开启 `backfill-enabled`,核对冲突报告与备份后再执行;完成后立即关闭开关。
- 本次没有对任何数据库执行 SQL 或回填。
## 协议版本与静态内容
- 面向用户的静态协议页面位于 `JC-Salon-Frontend/public/legal/`;小程序协议入口位于 `JC-Salon-WeChat/pages/legal/`。
- 小程序同意门禁使用后端 `t_legal_agreement` 当前版本。协议正文或版本变更时,应同步更新静态页面、初始化 SQL 种子和后端当前版本,并重新征求用户同意。
- 正式上线前由运营方填写并验证长期稳定的公开访问域名,并核对实际主体、短信服务商、消息通道、对象存储以及微信后台隐私指引。
## 上线前检查
1. 确认目标环境 Provider:DEV 为 `mock`,SIT/PROD 为 `disabled` 或届时经评审接入的正式 Provider。
2. 确认手机号密钥在环境间独立,且未开启回填开关;核对 Nacos 权限和变更审计。
3. 确认静态协议链接长期可访问,正文、版本与后端协议种子一致。
4. 确认微信后台隐私指引与代码实际使用的权限、数据类别和第三方服务商一致。
5. 内容审核未完成微信平台接入和正式环境验收前,不得宣称已具备微信内容安全审核能力。
+94 -14
View File
@@ -88,6 +88,7 @@ create table t_comment
parent_comment_id bigint unsigned default 0 null comment '父级评论ID(0表示为根评论)',
rating_score tinyint unsigned default 5 null comment '评论评分:1-5星',
image_file_ids text null comment '评论图片文件ID集合,多个ID以逗号分隔',
moderation_status varchar(20) default 'APPROVED' not null comment '本地模拟审核状态:PENDING/APPROVED/REJECTED/RETRY',
like_count int unsigned default 0 null comment '评论点赞数',
create_time datetime default CURRENT_TIMESTAMP not null comment '评论创建时间',
update_time datetime default CURRENT_TIMESTAMP not null on update CURRENT_TIMESTAMP comment '评论更新时间',
@@ -345,7 +346,8 @@ create table t_order
coupon_source_type varchar(32) null comment '优惠来源类型',
customer_remark varchar(500) null comment '用户询价预约备注',
customer_name_snapshot varchar(100) null comment '补单客户名称快照',
customer_phone_snapshot varchar(32) null comment '补单客户手机号快照',
customer_phone_snapshot varchar(128) null comment '加密补单客户手机号快照',
customer_phone_snapshot_hash char(64) null comment '补单客户手机号HMAC索引',
order_source varchar(32) default 'NORMAL_APPOINTMENT' not null comment '订单来源:NORMAL_APPOINTMENT/HISTORICAL_BACKFILL',
status tinyint unsigned default 1 not null comment '订单状态:0-价格确认中,1-待服务,2-已完成,3-已取消,4-服务中',
create_time datetime default CURRENT_TIMESTAMP not null comment '创建时间',
@@ -612,9 +614,12 @@ create table t_user
primary key comment '用户主键索引',
shop_id bigint unsigned default 0 null comment '所属店铺ID,关联店铺表主键(0表示无所属店铺)',
nickname varchar(50) not null comment '用户昵称',
account varchar(50) null comment '用户账号(登录用,微信快捷登录用户可为空)',
phone varchar(50) null comment '手机号',
contact_phone varchar(50) null comment '联系电话',
account varchar(128) null comment '用户账号(手机号账号加密存储)',
account_hash char(64) null comment '账号HMAC索引',
phone varchar(128) null comment '手机号AES-GCM密文',
phone_hash char(64) null comment '手机号HMAC索引',
contact_phone varchar(128) null comment '联系电话AES-GCM密文',
contact_phone_hash char(64) null comment '联系电话HMAC索引',
birthday date null comment '生日',
wechat_id varchar(100) null comment '微信号',
wechat_qr_code varchar(512) null comment '微信二维码',
@@ -631,10 +636,10 @@ create table t_user
is_delete tinyint unsigned default 0 null comment '逻辑删除:0-未删,1-已删',
status tinyint unsigned default 1 null comment '用户状态:1-正常,0-禁用',
avatar varchar(512) null comment '头像链接',
constraint uk_account
unique (account) comment '用户账号唯一索引',
constraint uk_user_phone
unique (phone) comment '用户手机号唯一索引(允许多行NULL)'
constraint uk_user_phone_hash
unique (phone_hash) comment '用户手机号HMAC唯一索引(允许多行NULL)',
constraint uk_user_account_hash
unique (account_hash) comment '手机号账号HMAC唯一索引(允许多行NULL)'
)
comment '系统用户信息表';
@@ -930,6 +935,41 @@ DROP PROCEDURE IF EXISTS sp_add_column_if_not_exists;
DROP PROCEDURE IF EXISTS sp_add_index_if_not_exists;
DROP PROCEDURE IF EXISTS sp_add_unique_index_if_not_exists;
CREATE TABLE IF NOT EXISTS t_account_closure_request (
id bigint unsigned NOT NULL COMMENT '账号注销申请ID',
user_id bigint unsigned NOT NULL COMMENT '申请人用户ID',
status varchar(20) NOT NULL DEFAULT 'PENDING' COMMENT '申请状态:PENDING/APPROVED/REJECTED/WITHDRAWN',
requested_at datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '申请时间',
processed_at datetime NULL COMMENT '处理时间',
reviewer_id bigint unsigned NULL COMMENT '处理人用户ID',
reviewer_note varchar(500) NULL COMMENT '处理说明',
create_time datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
update_time datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
PRIMARY KEY (id),
KEY idx_account_closure_user_status (user_id, status),
KEY idx_account_closure_status_time (status, requested_at)
) COMMENT='账号注销申请记录';
CREATE TABLE IF NOT EXISTS t_content_moderation_record (
id bigint unsigned NOT NULL COMMENT '内容审核记录ID',
content_type varchar(40) NOT NULL COMMENT '内容类型:USER_PROFILE/USER_AVATAR/PRODUCT/COMMENT',
business_id bigint unsigned NULL COMMENT '业务记录ID',
user_id bigint unsigned NULL COMMENT '内容提交人',
status varchar(20) NOT NULL COMMENT '审核状态:PENDING/APPROVED/REJECTED/RETRY',
provider varchar(30) NOT NULL DEFAULT 'LOCAL_MOCK' COMMENT '审核Provider标识',
result_code varchar(40) NULL COMMENT 'Provider结果代码',
reason varchar(500) NULL COMMENT '审核或复核说明',
payload_json mediumtext NULL COMMENT '隔离内容载荷,仅待审核记录可访问',
reviewed_by bigint unsigned NULL COMMENT '复核人用户ID',
reviewed_at datetime NULL COMMENT '复核时间',
attempt_count int NOT NULL DEFAULT 0 COMMENT '处理尝试次数',
create_time datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
update_time datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
PRIMARY KEY (id),
KEY idx_content_moderation_status_time (status, create_time),
KEY idx_content_moderation_business (content_type, business_id)
) COMMENT='本地内容审核隔离与复核记录';
DELIMITER $$
CREATE PROCEDURE sp_add_column_if_not_exists(
@@ -1047,7 +1087,47 @@ CALL sp_add_column_if_not_exists('t_user', 'contact_phone', 'varchar(50) NULL CO
CALL sp_add_column_if_not_exists('t_user', 'birthday', 'date NULL COMMENT ''生日''');
CALL sp_add_column_if_not_exists('t_user', 'wechat_id', 'varchar(100) NULL COMMENT ''微信号''');
CALL sp_add_column_if_not_exists('t_user', 'wechat_qr_code', 'varchar(512) NULL COMMENT ''微信二维码''');
CALL sp_add_column_if_not_exists('t_user', 'account_hash', 'char(64) NULL COMMENT ''账号HMAC索引''');
CALL sp_add_column_if_not_exists('t_user', 'phone_hash', 'char(64) NULL COMMENT ''手机号HMAC索引''');
CALL sp_add_column_if_not_exists('t_user', 'contact_phone_hash', 'char(64) NULL COMMENT ''联系电话HMAC索引''');
CALL sp_add_column_if_not_exists('t_comment', 'moderation_status', 'varchar(20) NOT NULL DEFAULT ''APPROVED'' COMMENT ''本地模拟审核状态:PENDING/APPROVED/REJECTED/RETRY''');
ALTER TABLE t_user MODIFY COLUMN account varchar(128) NULL COMMENT '手机号账号AES-GCM密文';
ALTER TABLE t_user MODIFY COLUMN phone varchar(128) NULL COMMENT '手机号AES-GCM密文';
ALTER TABLE t_user MODIFY COLUMN contact_phone varchar(128) NULL COMMENT '联系电话AES-GCM密文';
SET @drop_legacy_account_index_sql = IF(
EXISTS(SELECT 1 FROM information_schema.STATISTICS WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = 't_user' AND INDEX_NAME = 'uk_account'),
'ALTER TABLE t_user DROP INDEX uk_account', 'SELECT 1'
);
PREPARE stmt_drop_legacy_account_index FROM @drop_legacy_account_index_sql;
EXECUTE stmt_drop_legacy_account_index;
DEALLOCATE PREPARE stmt_drop_legacy_account_index;
SET @drop_legacy_phone_index_sql = IF(
EXISTS(SELECT 1 FROM information_schema.STATISTICS WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = 't_user' AND INDEX_NAME = 'uk_user_phone'),
'ALTER TABLE t_user DROP INDEX uk_user_phone', 'SELECT 1'
);
PREPARE stmt_drop_legacy_phone_index FROM @drop_legacy_phone_index_sql;
EXECUTE stmt_drop_legacy_phone_index;
DEALLOCATE PREPARE stmt_drop_legacy_phone_index;
CALL sp_add_unique_index_if_not_exists('t_user', 'uk_user_phone_hash', '(`phone_hash`)');
CALL sp_add_unique_index_if_not_exists('t_user', 'uk_user_account_hash', '(`account_hash`)');
CALL sp_add_index_if_not_exists('t_user', 'idx_user_contact_phone_hash', '(`contact_phone_hash`)');
CALL sp_add_column_if_not_exists('t_order', 'customer_phone_snapshot_hash', 'char(64) NULL COMMENT ''补单客户手机号HMAC索引''');
ALTER TABLE t_order MODIFY COLUMN customer_phone_snapshot varchar(128) NULL COMMENT '加密补单客户手机号快照';
CALL sp_add_index_if_not_exists('t_order', 'idx_order_customer_phone_snapshot_hash', '(`customer_phone_snapshot_hash`)');
SET @drop_consent_device_id_sql = IF(
EXISTS(SELECT 1 FROM information_schema.COLUMNS WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = 't_user_agreement_consent' AND COLUMN_NAME = 'device_id'),
'ALTER TABLE t_user_agreement_consent DROP COLUMN device_id', 'SELECT 1'
);
PREPARE stmt_drop_consent_device_id FROM @drop_consent_device_id_sql;
EXECUTE stmt_drop_consent_device_id;
DEALLOCATE PREPARE stmt_drop_consent_device_id;
SET @drop_audit_device_id_sql = IF(
EXISTS(SELECT 1 FROM information_schema.COLUMNS WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = 't_security_audit_log' AND COLUMN_NAME = 'device_id'),
'ALTER TABLE t_security_audit_log DROP COLUMN device_id', 'SELECT 1'
);
PREPARE stmt_drop_audit_device_id FROM @drop_audit_device_id_sql;
EXECUTE stmt_drop_audit_device_id;
DEALLOCATE PREPARE stmt_drop_audit_device_id;
UPDATE t_balance_change_detail
SET before_balance = COALESCE(before_balance, current_balance - amount),
after_balance = COALESCE(after_balance, current_balance),
@@ -2209,13 +2289,12 @@ CREATE TABLE IF NOT EXISTS t_legal_agreement (
CREATE TABLE IF NOT EXISTS t_user_agreement_consent (
id bigint NOT NULL COMMENT '同意记录ID',
user_id bigint NOT NULL COMMENT '用户ID',
user_id bigint NULL COMMENT '用户ID;注销后解除身份关联,保留最小同意凭证',
agreement_type varchar(32) NOT NULL COMMENT '协议类型',
version varchar(32) NOT NULL COMMENT '同意版本号',
entry varchar(64) NULL COMMENT '同意入口:login/register/phone-login/wechat-mini',
client_type varchar(32) NULL COMMENT '客户端类型:WEB/WECHAT_MINI',
ip_address varchar(64) NULL COMMENT '同意IP',
device_id varchar(128) NULL COMMENT '设备ID',
consent_time datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '同意时间',
create_time datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
update_time datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
@@ -2224,6 +2303,8 @@ CREATE TABLE IF NOT EXISTS t_user_agreement_consent (
KEY idx_user_agreement_user (user_id, agreement_type)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='用户协议同意记录';
ALTER TABLE t_user_agreement_consent MODIFY COLUMN user_id bigint NULL COMMENT '用户ID;注销后解除身份关联,保留最小同意凭证';
CREATE TABLE IF NOT EXISTS t_security_audit_log (
id bigint NOT NULL COMMENT '审计日志ID',
user_id bigint NULL COMMENT '操作用户ID',
@@ -2232,7 +2313,6 @@ CREATE TABLE IF NOT EXISTS t_security_audit_log (
result varchar(32) NOT NULL COMMENT '结果:SUCCESS/FAIL',
reason varchar(255) NULL COMMENT '失败或补充原因',
ip_address varchar(64) NULL COMMENT '请求IP',
device_id varchar(128) NULL COMMENT '设备ID',
operate_time datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '操作时间',
create_time datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
update_time datetime NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '更新时间',
@@ -2274,8 +2354,8 @@ DEALLOCATE PREPARE stmt_system_parameter_enabled;
INSERT INTO t_legal_agreement (id, agreement_type, title, version, content, status, effective_time, create_time, update_time, is_delete)
VALUES
(313931273555138001, 'USER_TERMS', '用户协议', '2026.05.18', '欢迎使用 Jiayu Salon 甲屿店务。请在使用账号、预约、订单、会员、消息等功能前仔细阅读本协议。继续登录或注册即表示你已理解并同意平台基础服务规则、账号安全要求、订单预约规则和依法合规使用要求。', 1, NOW(), NOW(), NOW(), 0),
(313931273555138002, 'PRIVACY_POLICY', '隐私政策', '2026.05.18', 'Jiayu Salon 甲屿店务会在提供登录注册、预约下单、会员余额、消息通知和客户服务时处理必要的手机号、昵称、门店归属、订单与设备信息。我们仅在业务需要和法律允许范围内使用这些信息,并采取访问控制、脱敏展示和审计记录等措施保护数据安全。', 1, NOW(), NOW(), NOW(), 0)
(313931273555138001, 'USER_TERMS', '用户协议', '2026.10.21', '欢迎使用甲屿手纪 Salon 门店工作台。本服务供经门店授权的店长和员工管理门店日程、预约、员工和经营记录使用。登录前须阅读并明确同意本协议与隐私政策;不同意时不会交换微信登录凭证,也不能继续使用。微信 OpenID 用于识别账号,昵称和头像为可选资料,手机号绑定为可选,不绑定不影响基础工作台使用。页面中的预约金额仅为门店经营记录,不代表本平台已经收款;当前不提供充值、订阅或平台虚拟权益购买。请仅提交有权处理的业务信息,并确保上传的文字、图片具备合法来源。可在账号设置申请注销;管理员确认门店移交或归档后清理账号资料和登录身份。依法及履行必要业务所需的订单、预约和经营记录可能以匿名化形式保留,目标保留期为五年。', 1, NOW(), NOW(), NOW(), 0),
(313931273555138002, 'PRIVACY_POLICY', '隐私政策', '2026.10.21', '我们处理信息仅用于提供门店工作台:登录时由用户主动同意后调用微信登录并接收 OpenID;昵称、头像仅在用户主动补充或更新时处理;手机号仅在用户主动绑定或更换时获取,用于账号找回和必要的业务联系,不用于营销。店长和员工可能为预约及订单录入客户姓名、可选手机号和服务信息,这些是门店业务资料,不是客户小程序账号。我们不主动采集设备标识、IMEI、MAC、定位或麦克风信息;选择图片只在用户主动操作后调用。账号、客户和订单快照中的手机号使用 AES-GCM 加密保存,并用独立 HMAC 索引完成查重;常规界面、日志和导出对手机号脱敏。服务运行可能使用微信登录、短信服务商、消息通道和按环境配置的对象存储服务。用户可在账号设置申请注销或解绑手机号;注销申请经审核后撤销会话并在目标十五个工作日内删除或匿名化个人资料,订单、预约及经营凭证按产品目标保留五年并解除账号身份关联。头像、作品、评论等内容目前由本地模拟审核流程处理,结果仅用于开发验证,不代表已接入微信内容安全审核,正式上线前将另行完成实际审核平台和隐私指引配置。隐私内容上线前须由运营方核实数据处理方、时限和适用法律要求。', 1, NOW(), NOW(), NOW(), 0)
ON DUPLICATE KEY UPDATE
title = VALUES(title),
content = VALUES(content),
@@ -1,6 +1,6 @@
# JayuCloud 运行与发布配置总说明
更新时间:2026-10-16
更新时间:2026-10-21
本文是 `docs/scripts/` 下运行、配置、发布和回退规则的唯一说明入口。可执行脚本和初始化 SQL 保持独立文件,不在本文中重复粘贴。
@@ -78,6 +78,7 @@ MessageHub 的地址、交换机、路由和来源系统放在对应环境 `core
- OpenID 快捷登录接口、注册审核、手机号绑定和登录状态机见 Salon Core 代码及初始化 SQL。
- 历史补单使用订单来源 `HISTORICAL_BACKFILL`;状态 `4` 为“服务中”。补单必须归属员工,可不填写客户和具体服务时间,不创建预约占用。
- 初始化 SQL 已包含注册审核表、短信供应商种子、员工审核提醒参数及补单相关字段;已部署数据库不得直接重跑完整初始化脚本。
- 内容审核平台尚未接入微信服务。仅 DEV 配置启用确定性本地 mock;SIT/PROD 使用 fail-closed Provider,内容会隔离等待复核,不可将 mock 结果作为真实审核结论。具体参数和密钥维护说明见 `docs/scripts/Salon合规整改配置说明_20261021.md`。
## 8. 操作前检查
@@ -0,0 +1,45 @@
# Salon 小程序合规整改设计
## 目标与边界
本次面向 Salon 店长/员工工作台,补齐协议同意门禁、账号手机号保护与解绑、注销申请处理、内容审核隔离及支付模拟入口清理。顾客仍只是门店业务资料,不作为小程序登录账号。ArtList、线上数据库、Nacos 实例和微信后台均不在本次操作范围。
内容审核本次使用本地 MOCK 服务和确定性测试结果,不请求微信内容安全接口。审核服务采用可替换接口,线上接入微信前需另行实现并配置正式 Provider。MOCK 结果不作为真实合规审核能力。
## 账号及协议
- 当前协议版本必须在小程序调用 `wx.login` 前加载并与本机同意版本比较;新用户必须明确点击同意后才获取登录凭证。协议不预勾选,拒绝后退出小程序。
- OpenID 仍通过微信绑定表关联内部用户主键。昵称和头像保持可选。
- 手机号只在用户主动绑定时采集;短信用途在绑定界面和验证码发送前展示。支持微信一键绑定、短信绑定和用原号码验证码解绑。
- 已登录账号修改手机号时,服务端以当前会话绑定的手机号为准,兼容旧客户端传来的脱敏旧号码;修改密码验证码由服务端读取当前账号手机号发送,前端不再把脱敏号码当作真实号码提交。
- 手机号、账号中的手机号和业务订单手机号快照由 AES-GCM 加密;HMAC 索引单独用于唯一性查询。所有常规列表和安全日志输出脱敏值。
- 存储密钥由 Nacos 样例管理,每个环境独立生成;数据库回填默认为 dry-run,正式回填前须开启专用开关并先确认冲突报告。
## 注销
- 本人提交注销申请后可以查看或撤回;后台审核人可处理门店移交或归档后完成注销。
- 有门店的店长提交时必须选择接手店长;没有可移交门店或不再运营的门店由后台显式归档,不自动删除历史订单。
- 完成注销时撤销全部会话,清理或匿名化身份资料、OpenID 绑定和账号手机号;订单、预约、补单和业绩记录保留并移除个人身份关联,保留期限按产品目标五年控制。
- 不复用后台物理/逻辑删除用户的服务语义。
## 内容审核 MOCK
- 建立 `ContentModerationProvider` 抽象和仅用于当前本地验证的 MOCK 实现;支持通过、拒绝、待复核和模拟服务故障结果。
- 文本、头像及作品图片进入待审核记录;未通过或待复核内容不公开。MOCK 故障时失败关闭并可重试。
- 管理端提供待复核列表、通过/拒绝及理由。拒绝的图片/头像不应用,作品保持不公开;违规处置由审核人显式执行。
- 不采集或上报内容至第三方;后续微信审核需在单独设计中增加 Provider、权限、微信后台指引和数据流说明。
## 支付、静态协议和数据库
- 移除模拟支付成功前台入口及未启用的订阅/充值交互;预约金额仍是经营记录,不表示平台收款。
- 在 Salon 前端发布长期稳定的用户协议和隐私政策静态页面,小程序保留可访问入口。
- 空库初始化基线加入注销申请、审核记录及手机号索引/审核状态字段,并以幂等兼容 DDL 表达已有结构更新。不连接或执行任何数据库。
## 验收
- 未同意/协议版本过期时不调用 `wx.login` 或 OpenID 交换;拒绝协议后退出。
- 账号手机号绑定可选,验证码只由用户主动触发;解绑必须验证当前号码。
- 注销申请独立于后台删除;处理结果撤销会话并清理个人资料,业务记录保留。
- MOCK 审核的通过、拒绝、故障路径可确定性测试;待审核/拒绝内容不可公开;无微信审核请求。
- 公开协议可读取;小程序不显示模拟充值/支付成功入口。
- 完成 Core 测试与编译、小程序测试、Salon 前端测试与构建、SQL 静态检查及差异检查。
+18
View File
@@ -1,5 +1,12 @@
# 项目变更记录
## 2026-10-22 Salon 合规整改收尾:手机号脱敏兼容与内容审核 MOCK
- 内容审核当前仅接入本地 MOCK Provider:开发环境可确定性模拟通过、拒绝、待复核和故障;SIT/生产未接入微信平台时失败关闭并隔离,不宣称具备正式审核能力。
- 手机号字段使用 AES-GCM 密文和独立 HMAC 索引,后台及常规接口脱敏展示;修改手机号不再把脱敏旧号码提交给后端,服务端以当前登录账号为准并继续校验新号码验证码和唯一性。
- 修改密码验证码新增登录态专用发送接口,由服务端读取当前账号已验证手机号,前端不再使用脱敏号码发送验证码。
- 验证:Salon Core 28 项测试、Salon 前端 83 项测试和构建、小程序 21 项测试、`git diff --check` 通过;未连接实际数据库、Nacos 或微信后台。
## 2026-10-21 Salon 补录款式弹窗对齐新增页
- 问题:补录页面打开后直接进入款式列表,手动录入弹层与新增预约页样式和入口不一致。
@@ -250,3 +257,14 @@
- 上传中的图片禁止重复操作,部分上传失败时保留已成功图片。
- 草稿增加多图数组并兼容原有单图字段;提交仍使用逗号分隔的 `manualProductImageFileIds`,不改后端、数据库或 ArtList。
- 新增设计文档 `docs/superpowers/specs/2026-10-21-salon新增预约多图款式录入-design.md`。
## 2026-10-21 Salon 小程序合规整改
- 登录前增加协议版本门禁和明确的同意/退出选项;未同意或版本过期时不调用 `wx.login`,协议同意留存版本、入口和时间。
- 手机号绑定改为用户主动操作,增加短信验证解绑;账号、客户和订单手机号采用 AES-GCM 密文与独立 HMAC 索引,常规账号资料、客户列表和安全日志脱敏。
- 新增账号注销申请、撤回、后台处理、店长门店移交/归档、会话撤销和身份资料清理;订单经营记录按产品目标保留并解除身份关联。
- 新增内容审核 Provider 接口与确定性本地 MOCK 流程,覆盖个人资料、头像、作品和评论;未审核内容隔离,DEV 以外默认 fail-closed。本次不调用微信审核服务。
- 移除小程序模拟支付成功入口、用户侧充值交互和后台 VIP 充值配置导航;保留历史余额与流水数据。
- 新增 Salon 静态用户协议/隐私政策页面及隐私合规后台入口;手机号回填和注销审核参数、字段、索引并入 Salon 初始化 SQL。
- 新增配置说明 `docs/scripts/Salon合规整改配置说明_20261021.md`,更新 `docs/scripts/运行与发布配置总说明.md`,明确 DEV mock、SIT/PROD fail-closed 和密钥回填边界。
- Core 单元测试 25 项、小程序全部现有测试及 Salon 前端单元测试 83 项通过;Salon 前端类型检查和生产构建通过。内容审核目前仅为 mock,微信后台配置、真实 Nacos 发布和数据库执行均未进行。
@@ -34,6 +34,10 @@ jayucloud-salon:
brand:
message-template-name: JayuCloud-Salon
manager-register-shop-description: 甲屿店务注册店铺
privacy:
content-moderation:
# 仅开发环境使用确定性本地 mock;接入微信平台前不得晋级到 SIT/生产。
provider: mock
security:
jwt:
issuer: jayucloud-salon
@@ -26,3 +26,11 @@ aliyun:
oss:
access-key-id: LTAI5t9divmxMWHiKhLSRdDd
access-key-secret: U4BlsNpy7ISLbWYrQUsBMswaRH8G9Q
jayucloud-salon:
privacy:
phone-crypto:
encryption-key: "Y+Y5vAG/yUVDEvEQ3L5IQOO1ZFsbJp6l4wvrNR69mKM="
index-key: "4/wLgcudBE8XNVBjnUle1A2H1L0ePV0rKUbX3VFeAzU="
backfill-enabled: false
backfill-page-size: 500
@@ -33,6 +33,10 @@ jayucloud-salon:
brand:
message-template-name: JayuCloud-Salon
manager-register-shop-description: 甲屿店务注册店铺
privacy:
content-moderation:
# 微信审核平台接入前失败关闭,内容进入隔离/人工复核,不自动放行。
provider: disabled
security:
jwt:
issuer: jayucloud-salon
@@ -27,3 +27,11 @@ aliyun:
oss:
access-key-id: LTAI5t9divmxMWHiKhLSRdDd
access-key-secret: U4BlsNpy7ISLbWYrQUsBMswaRH8G9Q
jayucloud-salon:
privacy:
phone-crypto:
encryption-key: "zelWItNk7yyDA/LGkq4+Mqo0IOyBzAUmgyR4qLL1htw="
index-key: "01lUBIigsJL/GW/SeYLigYC4ngiY9ntknX+ScDeuNzQ="
backfill-enabled: false
backfill-page-size: 500
@@ -33,6 +33,10 @@ jayucloud-salon:
brand:
message-template-name: JayuCloud-Salon
manager-register-shop-description: 甲屿店务注册店铺
privacy:
content-moderation:
# 微信审核平台接入前失败关闭,内容进入隔离/人工复核,不自动放行。
provider: disabled
security:
jwt:
issuer: jayucloud-salon
@@ -31,3 +31,11 @@ aliyun:
messagehub:
client:
access-token: ""
jayucloud-salon:
privacy:
phone-crypto:
encryption-key: "/+Hq9v64U+5SHdBIw1w/6smGsbHh5224NSOvrn1o/fw="
index-key: "bEQkH9PtYIMbe1SnO5z0lntr7esGl1ZrxI4Yg+XkFY8="
backfill-enabled: false
backfill-page-size: 500