Salon 侧全场景脱敏与拨号单次取号改造:收掉预约选择客户的完整手机号出口,新增按门店与订单上下文授权的拨号取号端点及隐私号占位渠道,前端改为脱敏展示加呼叫取号,并同步更新协议条款
自动发布开发环境 Nacos 配置 / publish (push) Successful in 24s

This commit is contained in:
2026-11-04 22:02:51 +08:00
parent bbe1473b70
commit 05493923e4
33 changed files with 697 additions and 28 deletions
@@ -28,6 +28,8 @@ public class RateLimitProperties {
private LimitRule orderCreate = new LimitRule(10, 60);
private LimitRule customerDial = new LimitRule(10, 60);
@Data
/**
* Purpose: LimitRule supports RateLimitProperties.java by holding or executing the limit rule business role.
@@ -33,6 +33,8 @@ import com.xiaowang.jayucloud.salon.core.modules.shop.service.ShopService;
import com.xiaowang.jayucloud.salon.core.modules.shop.vo.ShopVO;
import com.xiaowang.jayucloud.salon.core.modules.shop.vo.ShopAppointmentSettingsVO;
import com.xiaowang.jayucloud.salon.core.modules.manager.vo.AppointmentCustomerOptionVO;
import com.xiaowang.jayucloud.salon.core.modules.privacy.service.CustomerDialService;
import com.xiaowang.jayucloud.salon.core.modules.privacy.vo.CustomerDialVO;
import com.xiaowang.jayucloud.salon.core.modules.user.dto.UserDTO;
import com.xiaowang.jayucloud.salon.core.modules.user.entity.UserDO;
import com.xiaowang.jayucloud.salon.core.modules.user.service.UserService;
@@ -49,6 +51,7 @@ import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.time.LocalDate;
import java.util.List;
@@ -65,6 +68,7 @@ public class AdminManagerController {
private final ProductService productService;
private final ShopService shopService;
private final AdminScopeHelper adminScopeHelper;
private final CustomerDialService customerDialService;
@GetMapping("/planning/calendar")
@RequirePermission("schedule:view")
@@ -179,6 +183,17 @@ public class AdminManagerController {
return Result.success(userService.listCustomersForAppointment(page, size, keyword, shopId));
}
@PostMapping("/customers/{customerId}/dial")
@RequirePermission("user:view")
public Result<CustomerDialVO> dialCustomer(HttpServletRequest request,
HttpServletResponse response,
@PathVariable Long customerId,
@RequestParam Long orderId) {
UserDO currentUser = adminScopeHelper.getCurrentUser(request);
response.setHeader("Cache-Control", "no-store");
return Result.success(customerDialService.dial(currentUser, customerId, orderId, request));
}
@GetMapping("/customers/{id}")
@RequirePermission("user:view")
public Result<UserVO> customer(HttpServletRequest request, @PathVariable Long id) {
@@ -11,7 +11,10 @@ public class AppointmentCustomerOptionVO {
@JsonSerialize(using = ToStringSerializer.class)
private Long id;
private String name;
/** 脱敏后的手机号,永不返回完整号码 */
private String phone;
/** 是否存在可拨打的手机号,呼叫按钮据此展示 */
private Boolean phoneAvailable;
private String avatar;
private LocalDateTime createdAt;
}
@@ -37,6 +37,7 @@ import com.xiaowang.jayucloud.salon.core.modules.file.support.ObjectStorageUrlSu
import com.xiaowang.jayucloud.salon.core.modules.planning.support.PlanningCalendarSupport;
import com.xiaowang.jayucloud.salon.core.modules.planning.support.PlanningTodayOverviewSupport;
import com.xiaowang.jayucloud.salon.core.support.id.TimeOrderedSnowflakeIdGenerator;
import com.xiaowang.jayucloud.salon.core.support.privacy.PhoneCrypto;
import com.xiaowang.jayucloud.salon.core.modules.planning.vo.PlanningAppointmentVO;
import com.xiaowang.jayucloud.salon.core.modules.planning.vo.PlanningArtistCountVO;
import com.xiaowang.jayucloud.salon.core.modules.planning.vo.PlanningArtistVO;
@@ -103,6 +104,7 @@ public class PlanningServiceImpl implements PlanningService {
private final WechatSubscribeMessageService wechatSubscribeMessageService;
private final TimeOrderedSnowflakeIdGenerator snowflakeIdGenerator;
private final ObjectStorageUrlSupport objectStorageUrlSupport;
private final PhoneCrypto phoneCrypto;
@Override
public PlanningCalendarVO getCalendar(UserDO currentUser, LocalDate startDate, LocalDate endDate, Long artistId) {
@@ -621,7 +623,11 @@ public class PlanningServiceImpl implements PlanningService {
vo.setOrderItemId(item == null ? reservation == null ? null : reservation.getOrderItemId() : item.getId());
vo.setCustomerId(customer == null ? order == null ? null : order.getUserId() : customer.getId());
vo.setCustomerName(customer == null ? firstNonBlank(order == null ? null : order.getCustomerNameSnapshot(), "散客") : firstNonBlank(customer.getNickname(), customer.getAccount(), "到店客户"));
vo.setCustomerPhone(customer == null ? order == null ? null : order.getCustomerPhoneSnapshot() : firstNonBlank(customer.getContactPhone(), customer.getPhone(), ""));
String plainPhone = customer == null
? (order == null ? null : order.getCustomerPhoneSnapshot())
: firstNonBlank(customer.getContactPhone(), customer.getPhone(), "");
vo.setCustomerPhone(phoneCrypto.mask(plainPhone));
vo.setCustomerPhoneAvailable(StringUtils.hasText(plainPhone) && !plainPhone.contains("*"));
vo.setProductId(product == null ? item == null ? null : item.getProductId() : product.getId());
vo.setProductTitle(reservation != null && hasText(reservation.getProductTitle())
? reservation.getProductTitle()
@@ -11,7 +11,10 @@ public class PlanningAppointmentVO {
private Long orderItemId;
private Long customerId;
private String customerName;
/** 脱敏后的客户手机号,完整号码仅通过拨号取号端点单次获取 */
private String customerPhone;
/** 是否存在可拨打的手机号,呼叫按钮据此展示 */
private Boolean customerPhoneAvailable;
private Long productId;
private String productTitle;
private Long artistId;
@@ -0,0 +1,17 @@
package com.xiaowang.jayucloud.salon.core.modules.privacy.config;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
/**
* 拨号取号配置。
* provider 取值:direct(直拨真实号码)或 privacy-number(隐私号码,暂未对接)。
*/
@Data
@Configuration
@ConfigurationProperties(prefix = "jayucloud-salon.dial")
public class DialProperties {
private String provider = "direct";
}
@@ -0,0 +1,14 @@
package com.xiaowang.jayucloud.salon.core.modules.privacy.dial;
/**
* 拨号返回模式。
*/
public final class DialMode {
public static final String DIRECT = "DIRECT";
public static final String PRIVACY_NUMBER = "PRIVACY_NUMBER";
private DialMode() {
}
}
@@ -0,0 +1,29 @@
package com.xiaowang.jayucloud.salon.core.modules.privacy.dial;
/**
* 单次取号结果,仅在本次响应中返回,不落库、不写日志、不缓存。
*/
public class DialTarget {
private final String mode;
private final String dialNumber;
private final int expiresInSeconds;
public DialTarget(String mode, String dialNumber, int expiresInSeconds) {
this.mode = mode;
this.dialNumber = dialNumber;
this.expiresInSeconds = expiresInSeconds;
}
public String getMode() {
return mode;
}
public String getDialNumber() {
return dialNumber;
}
public int getExpiresInSeconds() {
return expiresInSeconds;
}
}
@@ -0,0 +1,20 @@
package com.xiaowang.jayucloud.salon.core.modules.privacy.dial;
import com.xiaowang.jayucloud.salon.core.modules.order.entity.OrderDO;
import com.xiaowang.jayucloud.salon.core.modules.user.entity.UserDO;
/**
* 拨号目标渠道。不同渠道返回不同的号码类型,调用方不得自行降级为真实号码。
*/
public interface DialTargetProvider {
/**
* 配置项中使用的渠道标识,例如 direct、privacy-number。
*/
String providerKey();
/**
* 解析本次拨号目标。
*/
DialTarget resolve(UserDO customer, OrderDO order);
}
@@ -0,0 +1,54 @@
package com.xiaowang.jayucloud.salon.core.modules.privacy.dial;
import com.xiaowang.jayucloud.salon.core.common.BusinessException;
import com.xiaowang.jayucloud.salon.core.modules.order.entity.OrderDO;
import com.xiaowang.jayucloud.salon.core.modules.user.entity.UserDO;
import com.xiaowang.jayucloud.salon.core.support.privacy.PhoneCrypto;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
/**
* 直拨渠道:实时读取客户档案中的号码,仅在本次响应返回。
*/
@Component
@RequiredArgsConstructor
public class DirectDialTargetProvider implements DialTargetProvider {
private final PhoneCrypto phoneCrypto;
@Override
public String providerKey() {
return "direct";
}
@Override
public DialTarget resolve(UserDO customer, OrderDO order) {
String plainPhone = resolvePlainPhone(customer, order);
if (!StringUtils.hasText(plainPhone) || plainPhone.contains("*")) {
throw new BusinessException(422, "该客户未登记可拨打的手机号");
}
return new DialTarget(DialMode.DIRECT, plainPhone.trim(), 0);
}
private String resolvePlainPhone(UserDO customer, OrderDO order) {
if (customer != null) {
if (StringUtils.hasText(customer.getContactPhone())) {
String contactPhone = phoneCrypto.decrypt(customer.getContactPhone());
if (StringUtils.hasText(contactPhone)) {
return contactPhone;
}
}
if (StringUtils.hasText(customer.getPhone())) {
String phone = phoneCrypto.decrypt(customer.getPhone());
if (StringUtils.hasText(phone)) {
return phone;
}
}
}
if (order != null && StringUtils.hasText(order.getCustomerPhoneSnapshot())) {
return phoneCrypto.decrypt(order.getCustomerPhoneSnapshot());
}
return null;
}
}
@@ -0,0 +1,28 @@
package com.xiaowang.jayucloud.salon.core.modules.privacy.dial;
import com.xiaowang.jayucloud.salon.core.common.BusinessException;
import com.xiaowang.jayucloud.salon.core.modules.order.entity.OrderDO;
import com.xiaowang.jayucloud.salon.core.modules.user.entity.UserDO;
import org.springframework.stereotype.Component;
/**
* 隐私号码占位渠道:未对接时明确报错,绝不静默回退为真实号码。
*/
@Component
public class PlaceholderPrivacyNumberProvider implements DialTargetProvider {
public static final int NOT_CONFIGURED_CODE = 4250;
public static final String NOT_CONFIGURED_BUSINESS_CODE = "DIAL_PRIVACY_NUMBER_NOT_CONFIGURED";
@Override
public String providerKey() {
return "privacy-number";
}
@Override
public DialTarget resolve(UserDO customer, OrderDO order) {
throw new BusinessException(NOT_CONFIGURED_CODE,
"隐私号码服务未配置(" + NOT_CONFIGURED_BUSINESS_CODE + "),请联系平台开通");
}
}
@@ -0,0 +1,14 @@
package com.xiaowang.jayucloud.salon.core.modules.privacy.service;
import com.xiaowang.jayucloud.salon.core.modules.privacy.vo.CustomerDialVO;
import com.xiaowang.jayucloud.salon.core.modules.user.entity.UserDO;
import javax.servlet.http.HttpServletRequest;
/**
* 客户拨号取号服务:按门店范围与订单上下文单次授权,号码不落库、不写日志、不缓存。
*/
public interface CustomerDialService {
CustomerDialVO dial(UserDO currentUser, Long customerId, Long orderId, HttpServletRequest request);
}
@@ -0,0 +1,94 @@
package com.xiaowang.jayucloud.salon.core.modules.privacy.service.impl;
import com.xiaowang.jayucloud.salon.core.common.BusinessException;
import com.xiaowang.jayucloud.salon.core.modules.order.entity.OrderDO;
import com.xiaowang.jayucloud.salon.core.modules.order.mapper.OrderMapper;
import com.xiaowang.jayucloud.salon.core.modules.privacy.config.DialProperties;
import com.xiaowang.jayucloud.salon.core.modules.privacy.dial.DialTarget;
import com.xiaowang.jayucloud.salon.core.modules.privacy.dial.DialTargetProvider;
import com.xiaowang.jayucloud.salon.core.modules.privacy.service.CustomerDialService;
import com.xiaowang.jayucloud.salon.core.modules.privacy.vo.CustomerDialVO;
import com.xiaowang.jayucloud.salon.core.modules.security.support.AdminScopeHelper;
import com.xiaowang.jayucloud.salon.core.modules.security.support.SecurityAuditActions;
import com.xiaowang.jayucloud.salon.core.modules.security.support.SecurityAuditSupport;
import com.xiaowang.jayucloud.salon.core.modules.user.entity.UserDO;
import com.xiaowang.jayucloud.salon.core.modules.user.service.UserService;
import com.xiaowang.jayucloud.salon.core.support.security.RequestThrottleService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Objects;
/**
* 客户拨号取号实现:先校验门店范围与订单归属,再按配置渠道单次取号并记录审计。
*/
@Service
@RequiredArgsConstructor
public class CustomerDialServiceImpl implements CustomerDialService {
private static final String AUDIT_ACTION = SecurityAuditActions.CUSTOMER_DIAL;
private final AdminScopeHelper adminScopeHelper;
private final UserService userService;
private final OrderMapper orderMapper;
private final RequestThrottleService requestThrottleService;
private final SecurityAuditSupport securityAuditSupport;
private final DialProperties dialProperties;
private final List<DialTargetProvider> providers;
@Override
public CustomerDialVO dial(UserDO currentUser, Long customerId, Long orderId, HttpServletRequest request) {
adminScopeHelper.requireShopContext(currentUser, "请先选择店铺后再拨号");
Long currentShopId = currentUser.getShopId();
requestThrottleService.checkCustomerDial(request, currentUser.getId());
UserDO customer = userService.getById(customerId);
if (customer == null || Objects.equals(1, customer.getIsDelete()) || !Objects.equals(0, customer.getType())) {
throw new BusinessException(404, "客户不存在");
}
adminScopeHelper.ensureUserAccessibleInCurrentShop(currentUser, customerId, "无权拨打其他店铺客户");
OrderDO order = orderMapper.selectById(orderId);
if (order == null || Objects.equals(1, order.getIsDelete()) || !Objects.equals(customerId, order.getUserId())) {
throw new BusinessException(403, "该客户与订单不匹配,或无权拨打");
}
if (!Objects.equals(currentShopId, order.getShopId())) {
throw new BusinessException(403, "无权拨打其他店铺订单客户");
}
DialTargetProvider provider = resolveProvider();
String reason = "customerId=" + customerId + ";orderId=" + orderId + ";provider=" + provider.providerKey();
try {
DialTarget target = provider.resolve(customer, order);
securityAuditSupport.success(request, AUDIT_ACTION, reason + ";mode=" + target.getMode() + ";result=SUCCESS");
CustomerDialVO vo = new CustomerDialVO();
vo.setMode(target.getMode());
vo.setDialNumber(target.getDialNumber());
vo.setExpiresInSeconds(target.getExpiresInSeconds());
return vo;
} catch (BusinessException exception) {
securityAuditSupport.fail(request, AUDIT_ACTION,
reason + ";result=FAIL;errorCode=" + exception.getCode());
throw exception;
} catch (RuntimeException exception) {
securityAuditSupport.fail(request, AUDIT_ACTION,
reason + ";result=FAIL;errorType=" + exception.getClass().getSimpleName());
throw exception;
}
}
private DialTargetProvider resolveProvider() {
String configured = StringUtils.hasText(dialProperties.getProvider())
? dialProperties.getProvider().trim()
: "direct";
for (DialTargetProvider provider : providers) {
if (configured.equalsIgnoreCase(provider.providerKey())) {
return provider;
}
}
throw new BusinessException(500, "拨号渠道配置无效(jayucloud-salon.dial.provider=" + configured + ")");
}
}
@@ -0,0 +1,19 @@
package com.xiaowang.jayucloud.salon.core.modules.privacy.vo;
import lombok.Data;
/**
* 单次拨号取号响应。
*/
@Data
public class CustomerDialVO {
/** DIRECT:真实号码;PRIVACY_NUMBER:隐私号码 */
private String mode;
/** 本次可拨打的号码,仅用于当前客户端一次性拨号 */
private String dialNumber;
/** 号码有效秒数,DIRECT 为 0 表示不设时效 */
private Integer expiresInSeconds;
}
@@ -108,6 +108,7 @@ public final class SecurityAuditActions {
public static final String ANALYTICS_VIEW = "ANALYTICS_VIEW";
public static final String PERFORMANCE_VIEW = "PERFORMANCE_VIEW";
public static final String SECURE_CONFIG_UPDATE = "SECURE_CONFIG_UPDATE";
public static final String CUSTOMER_DIAL = "CUSTOMER_DIAL";
private SecurityAuditActions() {
}
@@ -629,7 +629,9 @@ public class UserServiceImpl extends ServiceImpl<UserMapper, UserDO> implements
AppointmentCustomerOptionVO customer = new AppointmentCustomerOptionVO();
customer.setId(user.getId());
customer.setName(user.getNickname());
customer.setPhone(resolveCustomerPhone(user));
String plainPhone = resolveCustomerPhone(user);
customer.setPhone(phoneCrypto.mask(plainPhone));
customer.setPhoneAvailable(StringUtils.hasText(plainPhone));
customer.setAvatar(resolveAccessibleAvatar(user.getAvatar()));
customer.setCreatedAt(user.getCreateTime());
return customer;
@@ -658,7 +660,9 @@ public class UserServiceImpl extends ServiceImpl<UserMapper, UserDO> implements
AppointmentCustomerOptionVO option = new AppointmentCustomerOptionVO();
option.setId(user.getId());
option.setName(user.getNickname());
option.setPhone(resolveCustomerPhone(user));
String plainPhone = resolveCustomerPhone(user);
option.setPhone(phoneCrypto.mask(plainPhone));
option.setPhoneAvailable(StringUtils.hasText(plainPhone));
option.setAvatar(resolveAccessibleAvatar(user.getAvatar()));
option.setCreatedAt(user.getCreateTime());
return option;
@@ -90,6 +90,14 @@ public class RequestThrottleService {
assertAllowed("agreement-read", request, sanitize(agreementType), rateLimitProperties.getAgreementRead(), "协议读取过于频繁,请稍后再试");
}
/**
* 客户拨号取号按用户维度限流,避免管理员批量拉取完整号码。
*/
public void checkCustomerDial(HttpServletRequest request, Long userId) {
assertAllowed("customer-dial", request, userId == null ? "" : String.valueOf(userId),
rateLimitProperties.getCustomerDial(), "拨号取号过于频繁,请稍后再试");
}
/**
* Purpose: checkAuthenticatedWrite supports RequestThrottleService.java by holding or executing the check authenticated write business role.
* Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state.
@@ -0,0 +1,51 @@
-- 隐私政策与用户协议条款修订:对齐“全场景脱敏 + 拨号按需单次取号 + 可接隐私号码”口径
-- 版本:2026.11.04(V18)
-- 说明:仅更新当前生效版本的条款正文,不新增协议版本、不触发重新同意;静态 HTML 正文由 public/legal 读库渲染,不再维护副本。
UPDATE t_legal_agreement
SET content = REPLACE(
content,
'常规页面展示脱敏号码,完整号码仅在必要业务场景和权限校验通过时展示。',
'所有页面统一脱敏展示;确需联系客户时,须通过门店数据权限与预约/订单上下文校验后按需单次取号拨号,不批量展示完整号码;接入隐私号码服务时返回临时隐私号码。'
),
update_time = NOW()
WHERE agreement_type = 'USER_TERMS'
AND status = 1
AND is_delete = 0
AND content LIKE '%常规页面展示脱敏号码,完整号码仅在必要业务场景和权限校验通过时展示。%';
UPDATE t_legal_agreement
SET content = REPLACE(
content,
'常规客户列表、详情页、日志、导出文件、通知消息及面向第三方的展示,手机号一律脱敏。',
'全部客户列表、详情页、日志、导出文件、通知消息及面向第三方的展示,手机号一律脱敏。'
),
update_time = NOW()
WHERE agreement_type = 'PRIVACY_POLICY'
AND status = 1
AND is_delete = 0
AND content LIKE '%常规客户列表、详情页、日志、导出文件、通知消息及面向第三方的展示,手机号一律脱敏。%';
UPDATE t_legal_agreement
SET content = REPLACE(
content,
'仅在门店预约选择客户、需要与客户进行业务联系等必要场景,且请求通过门店数据权限校验时,才向授权人员展示完整号码。',
'确需与客户进行业务联系时,由授权人员在门店数据权限和预约/订单上下文校验通过后按需单次取号:直拨模式仅返回本次拨号号码,隐私号码模式返回临时隐私号码;完整号码不下发列表、不落库、不写日志、不进入缓存,且隐私号码未开通时不会回退为真实号码。'
),
update_time = NOW()
WHERE agreement_type = 'PRIVACY_POLICY'
AND status = 1
AND is_delete = 0
AND content LIKE '%仅在门店预约选择客户、需要与客户进行业务联系等必要场景,且请求通过门店数据权限校验时,才向授权人员展示完整号码。%';
UPDATE t_legal_agreement
SET content = REPLACE(
content,
'客户本人资料页、员工账号资料页默认展示脱敏号码;',
'客户本人资料页、员工账号资料页一律展示脱敏号码;'
),
update_time = NOW()
WHERE agreement_type = 'PRIVACY_POLICY'
AND status = 1
AND is_delete = 0
AND content LIKE '%客户本人资料页、员工账号资料页默认展示脱敏号码;%';
@@ -29,6 +29,7 @@ import com.xiaowang.jayucloud.salon.core.modules.user.entity.UserDO;
import com.xiaowang.jayucloud.salon.core.modules.user.mapper.UserMapper;
import com.xiaowang.jayucloud.salon.core.modules.user.service.UserService;
import com.xiaowang.jayucloud.salon.core.support.id.TimeOrderedSnowflakeIdGenerator;
import com.xiaowang.jayucloud.salon.core.support.privacy.PhoneCrypto;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
@@ -69,6 +70,7 @@ class PlanningServiceImplTest {
@Mock private WechatSubscribeMessageService wechatSubscribeMessageService;
@Mock private TimeOrderedSnowflakeIdGenerator snowflakeIdGenerator;
@Mock private ObjectStorageUrlSupport objectStorageUrlSupport;
@Mock private PhoneCrypto phoneCrypto;
private PlanningServiceImpl service;
@@ -77,7 +79,7 @@ class PlanningServiceImplTest {
service = new PlanningServiceImpl(adminScopeHelper, userMapper, userService, nailArtistInfoMapper, artistScheduleMapper,
artistScheduleExceptionMapper, appointmentReservationMapper, orderMapper, orderItemMapper,
productMapper, shopMapper, shopBusinessExpiryService, shopBusinessScheduleService, appointmentCapacityService, orderService, wechatSubscribeMessageService, snowflakeIdGenerator,
objectStorageUrlSupport);
objectStorageUrlSupport, phoneCrypto);
ShopBusinessHoursDayVO defaultOpenDay = new ShopBusinessHoursDayVO();
defaultOpenDay.setOpen(true);
defaultOpenDay.setStartTime("10:00");
@@ -514,13 +516,15 @@ class PlanningServiceImplTest {
when(orderItemMapper.selectById(64L)).thenReturn(item);
when(orderMapper.selectById(54L)).thenReturn(order);
when(userMapper.selectList(any(Wrapper.class))).thenReturn(java.util.List.of());
when(phoneCrypto.mask("13800138000")).thenReturn("138****8000");
com.xiaowang.jayucloud.salon.core.modules.planning.vo.PlanningAppointmentVO result =
service.getAppointment(operator, 64L);
assertNull(result.getCustomerId());
assertEquals("散客预约", result.getCustomerName());
assertEquals("13800138000", result.getCustomerPhone());
assertEquals("138****8000", result.getCustomerPhone());
assertEquals(Boolean.TRUE, result.getCustomerPhoneAvailable());
assertEquals("门店临时闭店", result.getCancelReason());
verify(userMapper, never()).selectById(org.mockito.ArgumentMatchers.isNull());
}
@@ -0,0 +1,138 @@
package com.xiaowang.jayucloud.salon.core.modules.privacy.service.impl;
import com.xiaowang.jayucloud.salon.core.common.BusinessException;
import com.xiaowang.jayucloud.salon.core.modules.order.entity.OrderDO;
import com.xiaowang.jayucloud.salon.core.modules.order.mapper.OrderMapper;
import com.xiaowang.jayucloud.salon.core.modules.privacy.config.DialProperties;
import com.xiaowang.jayucloud.salon.core.modules.privacy.dial.DialMode;
import com.xiaowang.jayucloud.salon.core.modules.privacy.dial.DialTargetProvider;
import com.xiaowang.jayucloud.salon.core.modules.privacy.dial.DirectDialTargetProvider;
import com.xiaowang.jayucloud.salon.core.modules.privacy.dial.PlaceholderPrivacyNumberProvider;
import com.xiaowang.jayucloud.salon.core.modules.privacy.vo.CustomerDialVO;
import com.xiaowang.jayucloud.salon.core.modules.security.support.AdminScopeHelper;
import com.xiaowang.jayucloud.salon.core.modules.security.support.SecurityAuditSupport;
import com.xiaowang.jayucloud.salon.core.modules.user.entity.UserDO;
import com.xiaowang.jayucloud.salon.core.modules.user.service.UserService;
import com.xiaowang.jayucloud.salon.core.support.privacy.PhoneCrypto;
import com.xiaowang.jayucloud.salon.core.support.security.RequestThrottleService;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
@ExtendWith(MockitoExtension.class)
class CustomerDialServiceImplTest {
@Mock private AdminScopeHelper adminScopeHelper;
@Mock private UserService userService;
@Mock private OrderMapper orderMapper;
@Mock private RequestThrottleService requestThrottleService;
@Mock private SecurityAuditSupport securityAuditSupport;
@Mock private PhoneCrypto phoneCrypto;
@Mock private HttpServletRequest request;
private CustomerDialServiceImpl service;
private UserDO currentUser;
private UserDO customer;
private OrderDO order;
@BeforeEach
void setUp() {
DialProperties properties = new DialProperties();
List<DialTargetProvider> providers = List.of(
new DirectDialTargetProvider(phoneCrypto),
new PlaceholderPrivacyNumberProvider());
service = new CustomerDialServiceImpl(adminScopeHelper, userService, orderMapper,
requestThrottleService, securityAuditSupport, properties, providers);
currentUser = new UserDO();
currentUser.setId(9L);
currentUser.setType(2);
currentUser.setShopId(1L);
customer = new UserDO();
customer.setId(100L);
customer.setType(0);
customer.setIsDelete(0);
order = new OrderDO();
order.setId(10L);
order.setUserId(100L);
order.setShopId(1L);
order.setIsDelete(0);
}
@Test
void directProviderReturnsFullNumberOnceAndWritesAudit() {
customer.setPhone("encrypted-phone");
when(phoneCrypto.decrypt("encrypted-phone")).thenReturn("13800138000");
when(userService.getById(100L)).thenReturn(customer);
when(orderMapper.selectById(10L)).thenReturn(order);
CustomerDialVO result = service.dial(currentUser, 100L, 10L, request);
assertEquals(DialMode.DIRECT, result.getMode());
assertEquals("13800138000", result.getDialNumber());
verify(requestThrottleService).checkCustomerDial(request, 9L);
verify(securityAuditSupport).success(eq(request), anyString(), anyString());
}
@Test
void rejectsOrderOfAnotherShop() {
order.setShopId(2L);
when(userService.getById(100L)).thenReturn(customer);
when(orderMapper.selectById(10L)).thenReturn(order);
BusinessException error = assertThrows(BusinessException.class,
() -> service.dial(currentUser, 100L, 10L, request));
assertEquals(403, error.getCode());
}
@Test
void rejectsOrderThatDoesNotBelongToCustomer() {
order.setUserId(101L);
when(userService.getById(100L)).thenReturn(customer);
when(orderMapper.selectById(10L)).thenReturn(order);
BusinessException error = assertThrows(BusinessException.class,
() -> service.dial(currentUser, 100L, 10L, request));
assertEquals(403, error.getCode());
}
@Test
void privacyNumberProviderReportsNotConfiguredWithoutFallingBackToRealNumber() {
service = new CustomerDialServiceImpl(adminScopeHelper, userService, orderMapper,
requestThrottleService, securityAuditSupport, privacyProperties(), List.of(
new DirectDialTargetProvider(phoneCrypto),
new PlaceholderPrivacyNumberProvider()));
customer.setPhone("encrypted-phone");
when(userService.getById(100L)).thenReturn(customer);
when(orderMapper.selectById(10L)).thenReturn(order);
BusinessException error = assertThrows(BusinessException.class,
() -> service.dial(currentUser, 100L, 10L, request));
assertEquals(PlaceholderPrivacyNumberProvider.NOT_CONFIGURED_CODE, error.getCode());
verify(securityAuditSupport).fail(eq(request), anyString(), anyString());
}
private DialProperties privacyProperties() {
DialProperties properties = new DialProperties();
properties.setProvider("privacy-number");
return properties;
}
}
@@ -75,7 +75,7 @@ class UserServiceCustomerMatchingTest {
}
@Test
void appointmentIdentityLookupReturnsOnlyExactTupleAndFullPhone() {
void appointmentIdentityLookupReturnsOnlyExactTupleAndMaskedPhone() {
UserDO existing = new UserDO();
existing.setId(92L);
existing.setNickname("周女士");
@@ -85,6 +85,7 @@ class UserServiceCustomerMatchingTest {
existing.setIsDelete(0);
when(userMapper.selectList(any(Wrapper.class))).thenReturn(List.of(existing));
when(phoneCrypto.decrypt("encrypted-phone")).thenReturn("13800138000");
when(phoneCrypto.mask("13800138000")).thenReturn("138****8000");
List<com.xiaowang.jayucloud.salon.core.modules.manager.vo.AppointmentCustomerOptionVO> matches =
userService.findCustomerIdentityMatches("周女士", "wx-zhou", "13800138000", null);
@@ -92,12 +93,13 @@ class UserServiceCustomerMatchingTest {
userService.findCustomerIdentityMatches("周女士", "wx-another", "13800138000", null);
assertEquals(1, matches.size());
assertEquals("13800138000", matches.get(0).getPhone());
assertEquals("138****8000", matches.get(0).getPhone());
assertEquals(Boolean.TRUE, matches.get(0).getPhoneAvailable());
assertTrue(wrongWechat.isEmpty());
}
@Test
void appointmentIdentityLookupFallsBackToLegacyContactPhone() {
void appointmentIdentityLookupFallsBackToLegacyContactPhoneWithMaskedPhone() {
UserDO existing = new UserDO();
existing.setId(93L);
existing.setNickname("周女士");
@@ -107,11 +109,13 @@ class UserServiceCustomerMatchingTest {
existing.setIsDelete(0);
when(userMapper.selectList(any(Wrapper.class))).thenReturn(List.of(existing));
when(phoneCrypto.decrypt("encrypted-contact-phone")).thenReturn("13800138000");
when(phoneCrypto.mask("13800138000")).thenReturn("138****8000");
List<com.xiaowang.jayucloud.salon.core.modules.manager.vo.AppointmentCustomerOptionVO> matches =
userService.findCustomerIdentityMatches("周女士", "wx-zhou", "13800138000", null);
assertEquals(1, matches.size());
assertEquals("13800138000", matches.get(0).getPhone());
assertEquals("138****8000", matches.get(0).getPhone());
assertEquals(Boolean.TRUE, matches.get(0).getPhoneAvailable());
}
}
+17
View File
@@ -261,11 +261,28 @@ export interface ContactInfoVO {
platformContactText?: string
}
/**
* 后台单次拨号取号响应。
*/
export interface CustomerDialResult {
mode: 'DIRECT' | 'PRIVACY_NUMBER'
dialNumber: string
expiresInSeconds: number
}
/**
* userApi groups all API calls for this page domain.
* Call guide: pass the typed payload or identifier into the method below, and use the returned Promise in the page script.
*/
export const userApi = {
/**
* 后台管理员按预约/订单上下文单次取号,号码不入库、不缓存。
*/
dialCustomer: async (customerId: IdType, orderId: IdType): Promise<CustomerDialResult> => {
return await api.post<CustomerDialResult>(`/manager/customers/${customerId}/dial`, null, {
params: { orderId }
}) as unknown as CustomerDialResult
},
getUserInfo: async (): Promise<UserVO> => {
return await api.get<UserVO>('/user/info') as unknown as UserVO
},
@@ -67,6 +67,13 @@
<div class="customer-meta">
<span>预约用户:{{ order.customerNickname || '用户' }}</span>
<span v-if="order.customerPhoneMasked">联系电话:{{ order.customerPhoneMasked }}</span>
<a-button
v-if="order.customerPhoneMasked && order.userId"
size="small"
type="link"
:loading="dialingOrderId === order.id"
@click="dialCustomer(order)"
>呼叫</a-button>
</div>
<div v-if="isQuoteOrder(order)" class="quote-summary">
@@ -215,6 +222,7 @@ const route = useRoute()
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
*/
const orders = ref<any[]>([])
const dialingOrderId = ref<IdType | null>(null)
/**
* Purpose: orderRefs supports ArtistOrderView.vue by holding or executing the order refs page or API role.
* Usage: import, call, read, or update this const from the owning page/module while preserving the surrounding loading and permission flow.
@@ -659,6 +667,26 @@ const confirmQuote = async () => {
}
}
/** 按订单上下文单次取号后发起拨号,号码不落库、不缓存。 */
const dialCustomer = async (order: any) => {
if (!order?.userId || !order?.id) {
message.warning('缺少订单上下文,无法取号')
return
}
dialingOrderId.value = order.id
try {
const result = await userApi.dialCustomer(order.userId, order.id)
if (!result?.dialNumber) {
throw new Error('未获取到可拨打号码')
}
window.location.href = `tel:${result.dialNumber}`
} catch (error: any) {
message.error(error?.message || '取号失败')
} finally {
dialingOrderId.value = null
}
}
/** completeOrder is a local helper used by this page script. */
const completeOrder = (orderId: IdType) => {
Modal.confirm({
+12
View File
@@ -46,6 +46,18 @@ module.exports = {
})
},
/**
* 后台按预约/订单上下文单次取号,号码不入库、不缓存。
*/
dialCustomer(customerId, orderId) {
return request({
url: `/manager/customers/${customerId}/dial`,
method: 'POST',
data: {},
params: { orderId }
})
},
create(data) {
return request({
url: '/manager/customers',
@@ -1,4 +1,5 @@
const planningApi = require('../../api/planning')
const customersApi = require('../../api/customers')
const { markPlanningRefresh } = require('../../utils/planning-refresh')
function displayValue(value, fallback) {
@@ -24,6 +25,7 @@ Page({
showComplete: false,
showCancel: false,
updating: false,
dialing: false,
loadError: ''
},
@@ -130,6 +132,27 @@ Page({
})
},
async dialCustomer() {
const appointment = this.data.appointment || {}
if (this.data.dialing) return
if (!appointment.customerPhoneAvailable || !appointment.customerId || !appointment.orderId) {
wx.showToast({ title: '该客户暂无可拨打的手机号', icon: 'none' })
return
}
this.setData({ dialing: true })
try {
const result = await customersApi.dialCustomer(appointment.customerId, appointment.orderId)
if (!result || !result.dialNumber) {
throw new Error('未获取到可拨打号码')
}
wx.makePhoneCall({ phoneNumber: result.dialNumber })
} catch (error) {
wx.showToast({ title: error.message || '取号失败', icon: 'none' })
} finally {
this.setData({ dialing: false })
}
},
goTransfer() {
if (!this.data.showTransfer) return
wx.navigateTo({ url: `/pages/artist-transfer/index?id=${this.data.id}` })
@@ -10,7 +10,16 @@
<view class="avatar">{{avatarText}}</view>
<view>
<text class="customer">{{appointment.customerNameText}}</text>
<text class="phone">{{appointment.customerPhoneText}}</text>
<view class="phone-row">
<text class="phone">{{appointment.customerPhoneText}}</text>
<button
wx:if="{{appointment.customerPhoneAvailable && appointment.customerId && appointment.orderId}}"
class="call-btn"
size="mini"
loading="{{dialing}}"
bindtap="dialCustomer"
>呼叫</button>
</view>
</view>
</view>
<text class="status-tag {{appointment.status === 2 ? 'completed' : appointment.status === 3 ? 'cancelled' : ''}}">{{appointment.historicalBackfill ? '历史补单 · ' : ''}}{{appointment.statusText}}</text>
@@ -67,6 +67,24 @@
font-size: 24rpx;
}
.phone-row {
display: flex;
align-items: center;
gap: 12rpx;
}
.call-btn {
flex-shrink: 0;
margin: 0;
padding: 0 18rpx;
border-radius: 999rpx;
background: #edf6ef;
color: #247b63;
font-size: 22rpx;
font-weight: 800;
line-height: 44rpx;
}
.status-tag {
flex-shrink: 0;
padding: 8rpx 14rpx;
@@ -36,17 +36,17 @@ function createPage() {
async function run() {
const page = createPage()
page.selectCustomer({ detail: { item: { id: 18, name: '小周', phone: '13800138000' } } })
page.selectCustomer({ detail: { item: { id: 18, name: '小周', phone: '138****8000' } } })
assert.strictEqual(page.data.form.customerUserId, 18)
assert.strictEqual(page.data.form.customerName, '小周')
assert.strictEqual(page.data.form.phone, '13800138000')
assert.strictEqual(page.data.form.phone, '')
assert.strictEqual(page.data.customerSheetVisible, false)
page.data.form.customerUserId = 18
page.onCustomerInput({ currentTarget: { dataset: { field: 'customerName' } }, detail: { value: '新客户' } })
assert.strictEqual(page.data.form.customerUserId, '')
assert.strictEqual(page.data.form.customerName, '新客户')
assert.strictEqual(page.data.form.phone, '13800138000')
assert.strictEqual(page.data.form.phone, '')
customersApi.matchIdentityForAppointment = async () => []
customersApi.create = async () => { throw new Error('预约客户建档应随预约请求提交') }
@@ -61,10 +61,11 @@ async function run() {
assert.strictEqual(name, '小周')
assert.strictEqual(wechatId, undefined)
assert.strictEqual(phone, '13800138000')
return [{ id: '18', name: '小周', phone: '13800138000' }]
return [{ id: '18', name: '小周', phone: '138****8000' }]
}
assert.strictEqual(await page.ensureCustomerBeforeSubmit(), true)
assert.strictEqual(page.data.form.customerUserId, '18')
assert.strictEqual(page.data.form.phone, '13800138000')
page.data.artists = [{ id: 1, name: '小周' }, { id: 2, name: '小李' }]
page.onArtistSearch({ detail: { value: '李' } })
+28 -13
View File
@@ -520,6 +520,7 @@ function normalizeCustomer(customer) {
id: customer.id,
name,
phone,
phoneAvailable: customer.phoneAvailable === true || (Boolean(phone) && !String(phone).includes('*')),
displayName: name || phone || '客户',
displayPhone: phone || '未填写手机号',
createdAt: customerCreatedAt(customer)
@@ -952,7 +953,7 @@ Page({
if (requestSeq !== this._customerSuggestionSeq) return
const rows = Array.isArray(result) ? result : (result.list || [])
const remoteSuggestions = rows.map(normalizeCustomer)
.filter(customer => (!name || customer.name.toLowerCase().includes(name)) && (!phone || customer.phone.toLowerCase().includes(phone)))
.filter(customer => !name || customer.name.toLowerCase().includes(name))
.slice(0, 3)
.map(buildCustomerSelectorItem)
this.setData({ customerSuggestions: remoteSuggestions })
@@ -971,7 +972,8 @@ Page({
this.setData({
'form.customerUserId': customer.id,
'form.customerName': customer.name,
'form.phone': customer.phone || '',
// 后端仅返回脱敏号码,不回填到表单,避免把脱敏值当真实号码提交
'form.phone': '',
'form.createCustomerRecord': false,
customerSuggestions: [],
customerSheetVisible: false,
@@ -1000,11 +1002,25 @@ Page({
return
}
const keyword = String(keywordValue === undefined ? this.data.customerKeyword : keywordValue || '').trim()
if (keyword) {
// 号码已全场景脱敏,按手机号检索必须交给后端精确匹配
try {
const result = await customersApi.listForAppointment({ page: 1, size: 100, keyword })
const rows = Array.isArray(result) ? result : (result.list || [])
this.setData({
customerOptions: this.sortCustomerOptions(rows.map(normalizeCustomer)),
customerError: ''
})
} catch (error) {
this.setData({ customerOptions: [], customerError: error.message || '客户加载失败' })
}
return
}
if (this.data.customerDirectory.length === 0) await this.loadCustomerDirectory()
const matches = this.data.customerDirectory.filter(customer =>
!keyword || `${customer.name} ${customer.phone}`.toLowerCase().includes(keyword.toLowerCase())
)
this.setData({ customerOptions: this.sortCustomerOptions(matches), customerError: '' })
this.setData({
customerOptions: this.sortCustomerOptions(this.data.customerDirectory),
customerError: ''
})
},
changeCustomerView(event) {
@@ -1013,11 +1029,10 @@ Page({
toggleCustomerSort() {
const customerNewestFirst = !this.data.customerNewestFirst
const keyword = String(this.data.customerKeyword || '').trim().toLowerCase()
const matches = this.data.customerDirectory.filter(customer =>
!keyword || `${customer.name} ${customer.phone}`.toLowerCase().includes(keyword)
)
this.setData({ customerNewestFirst, customerOptions: this.sortCustomerOptions(matches, customerNewestFirst) })
this.setData({
customerNewestFirst,
customerOptions: this.sortCustomerOptions(this.data.customerOptions, customerNewestFirst)
})
},
retryCustomerSearch() {
@@ -1032,7 +1047,8 @@ Page({
this.setData({
'form.customerUserId': customer.id,
'form.customerName': customer.name,
'form.phone': customer.phone || '',
// 选择已有客户时不回填脱敏号码,手机号仅在用户主动修改时提交
'form.phone': '',
'form.createCustomerRecord': false,
customerSheetVisible: false,
customerKeyword: '',
@@ -1925,7 +1941,6 @@ Page({
this.setData({
'form.customerUserId': customer.id,
'form.customerName': customer.name,
'form.phone': customer.phone,
'form.createCustomerRecord': false
})
} else {
@@ -114,7 +114,7 @@ Page({
searchCustomers(event) { const keyword = String(event.detail.value || '').toLowerCase(); this.setData({ customerKeyword: keyword, customerOptions: this.data.allCustomerOptions.filter(item => !keyword || `${item.name} ${item.phone}`.toLowerCase().includes(keyword)) }) },
selectProduct(event) { const item = event.detail.item || {}; const duration = String(item.serviceDurationMinutes || String(item.approximateDuration || '').replace(/[^0-9]/g, '') || '60'); this.setData({ 'form.productId': item.id, 'form.manualProductTitle': '', 'form.amount': item.price == null ? this.data.form.amount : String(item.price), 'form.durationMinutes': duration, selectedProduct: item, selectedProductTitle: item.title, selectedProductPriceText: item.priceText || '价格待定', manualProductDraft: { title: '', price: '', durationMinutes: duration, description: '' }, productSelectorVisible: false, manualProductSheetVisible: false }) },
selectArtist(event) { const item = event.detail.item; this.setData({ 'form.artistId': item.id, selectedArtistName: item.title, artistSelectorVisible: false }) },
selectCustomer(event) { const item = event.detail.item || {}; this.setData({ 'form.customerUserId': item.id, 'form.customerName': item.name || item.title, 'form.phone': item.phone || '', customerSelectorVisible: false }) },
selectCustomer(event) { const item = event.detail.item || {}; this.setData({ 'form.customerUserId': item.id, 'form.customerName': item.name || item.title, 'form.phone': '', customerSelectorVisible: false }) },
useWalkIn() { this.setData({ 'form.customerUserId': '', 'form.customerName': '', 'form.wechatId': '', 'form.phone': '', customerSelectorVisible: false }) },
onCustomerInput(event) { this.setData({ [`form.${event.currentTarget.dataset.field}`]: event.detail.value, 'form.customerUserId': '' }) },
useManualProduct() { const title = String(this.data.manualProductDraft.title || '').trim(); const priceText = String(this.data.manualProductDraft.price || this.data.form.amount || '').trim(); const price = Number(priceText); const images = this.data.form.manualProductImages || []; if (this.data.form.productId) { if (!priceText || !Number.isFinite(price) || price < 0) { wx.showToast({ title: '请输入正确的款式价格', icon: 'none' }); return } this.setData({ 'form.amount': priceText, 'form.durationMinutes': String(this.data.manualProductDraft.durationMinutes || '60'), manualProductSheetVisible: false }); return } if (!title && !images.length) { wx.showToast({ title: '请填写款式名称或添加图片', icon: 'none' }); return } if (!priceText || !Number.isFinite(price) || price < 0) { wx.showToast({ title: '请输入正确的款式价格', icon: 'none' }); return } const duration = String(this.data.manualProductDraft.durationMinutes || '60'); this.setData({ 'form.productId': '', 'form.manualProductTitle': title, 'form.manualProductDescription': this.data.manualProductDraft.description || '', 'form.manualProductPrice': priceText, 'form.amount': priceText, 'form.durationMinutes': duration, 'manualProductDraft.price': priceText, selectedProduct: {}, selectedProductTitle: title, selectedProductPriceText: `¥${price}`, productSelectorVisible: false, manualProductSheetVisible: false }) },
@@ -51,6 +51,9 @@ jayucloud-salon:
brand:
message-template-name: JayuCloud-Salon
manager-register-shop-description: 甲屿店务注册店铺
dial:
# direct:直拨真实号码;privacy-number:隐私号码(未对接时明确报错,绝不回退真实号码)
provider: direct
privacy:
content-moderation:
# 仅 DEV 允许在后台设置中使用本地模拟审核;SIT/PROD 继续失败关闭。
@@ -87,6 +90,9 @@ jayucloud-salon:
order-create:
limit: 10
window-seconds: 60
customer-dial:
limit: 10
window-seconds: 60
cache:
local-max-size: 2048
product-detail:
@@ -50,6 +50,9 @@ jayucloud-salon:
brand:
message-template-name: JayuCloud-Salon
manager-register-shop-description: 甲屿店务注册店铺
dial:
# direct:直拨真实号码;privacy-number:隐私号码(未对接时明确报错,绝不回退真实号码)
provider: direct
privacy:
content-moderation:
# 微信审核平台接入前失败关闭,内容进入隔离/人工复核,不自动放行。
@@ -87,6 +90,9 @@ jayucloud-salon:
order-create:
limit: 10
window-seconds: 60
customer-dial:
limit: 10
window-seconds: 60
cache:
local-max-size: 2048
product-detail:
@@ -50,6 +50,9 @@ jayucloud-salon:
brand:
message-template-name: JayuCloud-Salon
manager-register-shop-description: 甲屿店务注册店铺
dial:
# direct:直拨真实号码;privacy-number:隐私号码(未对接时明确报错,绝不回退真实号码)
provider: direct
privacy:
content-moderation:
# 仅 DEV 允许模拟审核;SIT 必须在后台配置微信审核并保持失败关闭。
@@ -86,6 +89,9 @@ jayucloud-salon:
order-create:
limit: 10
window-seconds: 60
customer-dial:
limit: 10
window-seconds: 60
cache:
local-max-size: 2048
product-detail: