mirror of
https://gitee.com/qqtt-ah/ai-crm.git
synced 2026-11-24 14:29:20 +08:00
init
This commit is contained in:
@@ -0,0 +1,27 @@
|
||||
package top.xyquan.ecomdmbbackend;
|
||||
|
||||
import org.apache.ibatis.annotations.Mapper;
|
||||
import org.mybatis.spring.annotation.MapperScan;
|
||||
import org.springframework.boot.SpringApplication;
|
||||
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||
import org.springframework.scheduling.annotation.EnableAsync;
|
||||
import org.springframework.scheduling.annotation.EnableScheduling;
|
||||
|
||||
import java.util.TimeZone;
|
||||
|
||||
import top.xyquan.ecomdmbbackend.common.time.BizClock;
|
||||
|
||||
@SpringBootApplication
|
||||
@EnableAsync
|
||||
@EnableScheduling
|
||||
@MapperScan(
|
||||
basePackages = "top.xyquan.ecomdmbbackend.modules",
|
||||
annotationClass = Mapper.class
|
||||
)
|
||||
public class EComDMBBackendApplication {
|
||||
|
||||
public static void main(String[] args) {
|
||||
TimeZone.setDefault(TimeZone.getTimeZone(BizClock.ZONE));
|
||||
SpringApplication.run(EComDMBBackendApplication.class, args);
|
||||
}
|
||||
}
|
||||
+19
@@ -0,0 +1,19 @@
|
||||
package top.xyquan.ecomdmbbackend.common.annotation;
|
||||
|
||||
import java.lang.annotation.ElementType;
|
||||
import java.lang.annotation.Retention;
|
||||
import java.lang.annotation.RetentionPolicy;
|
||||
import java.lang.annotation.Target;
|
||||
|
||||
/**
|
||||
* 开放接口 Scope 校验(仅用于 /api/open/** Controller)
|
||||
*/
|
||||
@Target(ElementType.METHOD)
|
||||
@Retention(RetentionPolicy.RUNTIME)
|
||||
public @interface RequireOpenScope {
|
||||
|
||||
/** 所需 scope,如 order:import */
|
||||
String value();
|
||||
|
||||
String description() default "";
|
||||
}
|
||||
+34
@@ -0,0 +1,34 @@
|
||||
package top.xyquan.ecomdmbbackend.common.annotation;
|
||||
|
||||
import java.lang.annotation.ElementType;
|
||||
import java.lang.annotation.Retention;
|
||||
import java.lang.annotation.RetentionPolicy;
|
||||
import java.lang.annotation.Target;
|
||||
|
||||
/**
|
||||
* 权限控制注解
|
||||
* 用于标记需要权限验证的接口
|
||||
*
|
||||
* 权限判定逻辑:
|
||||
* - 超管(Token.super=true):直接放行(拥有所有权限)
|
||||
* - 普通用户:从 org_position_permission 表查询岗位拥有的权限码进行判定
|
||||
*/
|
||||
@Target({ ElementType.METHOD, ElementType.TYPE })
|
||||
@Retention(RetentionPolicy.RUNTIME)
|
||||
public @interface RequirePermission {
|
||||
|
||||
/**
|
||||
* 权限码,如 "company:create", "user:read"
|
||||
*/
|
||||
String value() default "";
|
||||
|
||||
/**
|
||||
* 权限描述
|
||||
*/
|
||||
String description() default "";
|
||||
|
||||
/**
|
||||
* 是否允许超级管理员访问(默认允许)
|
||||
*/
|
||||
boolean allowSuper() default true;
|
||||
}
|
||||
+40
@@ -0,0 +1,40 @@
|
||||
package top.xyquan.ecomdmbbackend.common.annotation;
|
||||
|
||||
import java.lang.annotation.ElementType;
|
||||
import java.lang.annotation.Retention;
|
||||
import java.lang.annotation.RetentionPolicy;
|
||||
import java.lang.annotation.Target;
|
||||
|
||||
/**
|
||||
* 角色权限注解
|
||||
* 用于简单的角色权限控制
|
||||
*/
|
||||
@Target({ ElementType.METHOD, ElementType.TYPE })
|
||||
@Retention(RetentionPolicy.RUNTIME)
|
||||
public @interface RequireRole {
|
||||
|
||||
/**
|
||||
* 允许的角色列表(已废弃,保留仅为兼容;判定改用 allowSuper/allowCompany/allowUser)
|
||||
*/
|
||||
String[] value() default {};
|
||||
|
||||
/**
|
||||
* 权限描述
|
||||
*/
|
||||
String description() default "";
|
||||
|
||||
/**
|
||||
* 是否允许超级管理员访问(默认允许)
|
||||
*/
|
||||
boolean allowSuper() default true;
|
||||
|
||||
/**
|
||||
* 是否允许公司拥有者访问(默认允许)
|
||||
*/
|
||||
boolean allowCompany() default true;
|
||||
|
||||
/**
|
||||
* 是否允许普通用户访问(默认不允许)
|
||||
*/
|
||||
boolean allowUser() default false;
|
||||
}
|
||||
+46
@@ -0,0 +1,46 @@
|
||||
package top.xyquan.ecomdmbbackend.common.aspect;
|
||||
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.aspectj.lang.ProceedingJoinPoint;
|
||||
import org.aspectj.lang.annotation.Around;
|
||||
import org.aspectj.lang.annotation.Aspect;
|
||||
import org.aspectj.lang.reflect.MethodSignature;
|
||||
import org.springframework.stereotype.Component;
|
||||
import top.xyquan.ecomdmbbackend.common.annotation.RequireOpenScope;
|
||||
import top.xyquan.ecomdmbbackend.common.exception.BusinessException;
|
||||
import top.xyquan.ecomdmbbackend.modules.open.common.context.OpenApiContextHolder;
|
||||
import top.xyquan.ecomdmbbackend.modules.open.common.security.OpenApiPrincipal;
|
||||
|
||||
import java.lang.reflect.Method;
|
||||
import java.util.Set;
|
||||
|
||||
/**
|
||||
* 开放接口 Scope 校验切面
|
||||
*/
|
||||
@Aspect
|
||||
@Component
|
||||
@Slf4j
|
||||
public class OpenScopeAspect {
|
||||
|
||||
@Around("@annotation(top.xyquan.ecomdmbbackend.common.annotation.RequireOpenScope)")
|
||||
public Object checkScope(ProceedingJoinPoint joinPoint) throws Throwable {
|
||||
MethodSignature signature = (MethodSignature) joinPoint.getSignature();
|
||||
Method method = signature.getMethod();
|
||||
RequireOpenScope annotation = method.getAnnotation(RequireOpenScope.class);
|
||||
|
||||
OpenApiPrincipal principal = OpenApiContextHolder.get();
|
||||
if (principal == null) {
|
||||
throw new BusinessException("40301", "Scope 不足:未通过 API Key 认证");
|
||||
}
|
||||
|
||||
Set<String> permissionCodes = principal.permissionCodes();
|
||||
String requiredScope = annotation.value();
|
||||
if (permissionCodes == null || !permissionCodes.contains(requiredScope)) {
|
||||
log.warn("Scope 校验失败 - keyId: {}, required: {}, actual: {}",
|
||||
principal.apiKeyId(), requiredScope, permissionCodes);
|
||||
throw new BusinessException("40301", "Scope 不足: " + annotation.description());
|
||||
}
|
||||
|
||||
return joinPoint.proceed();
|
||||
}
|
||||
}
|
||||
+73
@@ -0,0 +1,73 @@
|
||||
package top.xyquan.ecomdmbbackend.common.aspect;
|
||||
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.aspectj.lang.ProceedingJoinPoint;
|
||||
import org.aspectj.lang.annotation.Around;
|
||||
import org.aspectj.lang.annotation.Aspect;
|
||||
import org.aspectj.lang.reflect.MethodSignature;
|
||||
import org.springframework.stereotype.Component;
|
||||
import top.xyquan.ecomdmbbackend.common.annotation.RequirePermission;
|
||||
import top.xyquan.ecomdmbbackend.common.exception.BusinessException;
|
||||
import top.xyquan.ecomdmbbackend.modules.sys.permission.service.PermissionCheckService;
|
||||
import top.xyquan.ecomdmbbackend.utils.CurrentUserContext;
|
||||
|
||||
import java.lang.reflect.Method;
|
||||
|
||||
/**
|
||||
* 权限验证切面
|
||||
* 用于拦截带有@RequirePermission注解的方法并进行权限验证
|
||||
* 权限判定逻辑:
|
||||
* - super:按 allowSuper 放行
|
||||
* - 非超管 + owner:仅校验平台分配给公司的权限(org_company_permission),不校验岗位
|
||||
* - 非超管 + member:公司权限 + 岗位权限双校验
|
||||
*/
|
||||
@Aspect
|
||||
@Component
|
||||
@Slf4j
|
||||
public class PermissionAspect {
|
||||
|
||||
private final CurrentUserContext currentUserContext;
|
||||
private final PermissionCheckService permissionCheckService;
|
||||
|
||||
public PermissionAspect(CurrentUserContext currentUserContext, PermissionCheckService permissionCheckService) {
|
||||
this.currentUserContext = currentUserContext;
|
||||
this.permissionCheckService = permissionCheckService;
|
||||
}
|
||||
|
||||
@Around("@annotation(top.xyquan.ecomdmbbackend.common.annotation.RequirePermission)")
|
||||
public Object checkPermission(ProceedingJoinPoint joinPoint) throws Throwable {
|
||||
MethodSignature signature = (MethodSignature) joinPoint.getSignature();
|
||||
Method method = signature.getMethod();
|
||||
RequirePermission annotation = method.getAnnotation(RequirePermission.class);
|
||||
|
||||
if (annotation == null) {
|
||||
return joinPoint.proceed();
|
||||
}
|
||||
|
||||
boolean isSuper = Boolean.TRUE.equals(currentUserContext.getCurrentUserPayload().getIsSuper());
|
||||
String companyRole = currentUserContext.getCurrentUserPayload().getCompanyRole();
|
||||
Long companyId = currentUserContext.getCurrentCompanyId();
|
||||
Long positionId = currentUserContext.getCurrentUserPayload().getPositionId();
|
||||
|
||||
log.debug("权限验证 - 超管: {}, 公司角色: {}, 公司ID: {}, 岗位ID: {}, 权限码: {}",
|
||||
isSuper, companyRole, companyId, positionId, annotation.value());
|
||||
|
||||
boolean hasPermission;
|
||||
if (isSuper) {
|
||||
hasPermission = annotation.allowSuper();
|
||||
} else if ("owner".equalsIgnoreCase(companyRole)) {
|
||||
hasPermission = permissionCheckService.hasCompanyAssignedPermission(companyId, annotation.value());
|
||||
} else {
|
||||
hasPermission = permissionCheckService.hasPermissionByPosition(positionId, annotation.value(), companyId);
|
||||
}
|
||||
|
||||
if (!hasPermission) {
|
||||
log.warn("权限验证失败 - 超管: {}, 岗位ID: {}, 权限码: {}, 描述: {}",
|
||||
isSuper, positionId, annotation.value(), annotation.description());
|
||||
throw new BusinessException("权限不足: " + annotation.description());
|
||||
}
|
||||
|
||||
log.debug("权限验证通过 - 超管: {}, 权限码: {}", isSuper, annotation.value());
|
||||
return joinPoint.proceed();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
package top.xyquan.ecomdmbbackend.common.aspect;
|
||||
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.aspectj.lang.ProceedingJoinPoint;
|
||||
import org.aspectj.lang.annotation.Around;
|
||||
import org.aspectj.lang.annotation.Aspect;
|
||||
import org.aspectj.lang.reflect.MethodSignature;
|
||||
import org.springframework.stereotype.Component;
|
||||
import top.xyquan.ecomdmbbackend.common.annotation.RequireRole;
|
||||
import top.xyquan.ecomdmbbackend.common.exception.BusinessException;
|
||||
import top.xyquan.ecomdmbbackend.utils.CurrentUserContext;
|
||||
|
||||
import java.lang.reflect.Method;
|
||||
|
||||
/**
|
||||
* 角色权限验证切面
|
||||
* 通过 Token 中的 super 字段判定超管,其余按公司成员角色判定
|
||||
*/
|
||||
@Aspect
|
||||
@Component
|
||||
@Slf4j
|
||||
public class RoleAspect {
|
||||
|
||||
private final CurrentUserContext currentUserContext;
|
||||
|
||||
public RoleAspect(CurrentUserContext currentUserContext) {
|
||||
this.currentUserContext = currentUserContext;
|
||||
}
|
||||
|
||||
@Around("@annotation(top.xyquan.ecomdmbbackend.common.annotation.RequireRole)")
|
||||
public Object checkRole(ProceedingJoinPoint joinPoint) throws Throwable {
|
||||
MethodSignature signature = (MethodSignature) joinPoint.getSignature();
|
||||
Method method = signature.getMethod();
|
||||
RequireRole annotation = method.getAnnotation(RequireRole.class);
|
||||
|
||||
if (annotation == null) {
|
||||
return joinPoint.proceed();
|
||||
}
|
||||
|
||||
boolean isSuper = Boolean.TRUE.equals(currentUserContext.getCurrentUserPayload().getIsSuper());
|
||||
|
||||
log.debug("角色权限验证 - 超管: {}, 注解配置: {}", isSuper, annotation.description());
|
||||
|
||||
boolean hasPermission;
|
||||
if (isSuper) {
|
||||
hasPermission = annotation.allowSuper();
|
||||
} else if (annotation.allowCompany()) {
|
||||
String companyRole = currentUserContext.getCurrentCompanyRole();
|
||||
if ("owner".equals(companyRole)) {
|
||||
hasPermission = true;
|
||||
log.debug("角色权限验证 - 用户是公司拥有者");
|
||||
} else {
|
||||
hasPermission = annotation.allowUser();
|
||||
}
|
||||
} else {
|
||||
hasPermission = annotation.allowUser();
|
||||
}
|
||||
|
||||
if (!hasPermission) {
|
||||
log.warn("角色权限验证失败 - 超管: {}, 描述: {}", isSuper, annotation.description());
|
||||
throw new BusinessException("权限不足: " + annotation.description());
|
||||
}
|
||||
|
||||
log.debug("角色权限验证通过 - 超管: {}", isSuper);
|
||||
return joinPoint.proceed();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
package top.xyquan.ecomdmbbackend.common.config;
|
||||
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.context.annotation.EnableAspectJAutoProxy;
|
||||
|
||||
/**
|
||||
* AOP配置类
|
||||
* 启用AspectJ自动代理,确保权限控制切面正常工作
|
||||
*/
|
||||
@Configuration
|
||||
@EnableAspectJAutoProxy(proxyTargetClass = true)
|
||||
public class AopConfig {
|
||||
}
|
||||
+221
@@ -0,0 +1,221 @@
|
||||
package top.xyquan.ecomdmbbackend.common.config;
|
||||
|
||||
import com.fasterxml.jackson.core.JsonGenerator;
|
||||
import com.fasterxml.jackson.core.JsonParser;
|
||||
import com.fasterxml.jackson.databind.DeserializationContext;
|
||||
import com.fasterxml.jackson.databind.JsonDeserializer;
|
||||
import com.fasterxml.jackson.databind.JsonSerializer;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.databind.SerializerProvider;
|
||||
import com.fasterxml.jackson.databind.module.SimpleModule;
|
||||
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.context.annotation.Primary;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.time.LocalDate;
|
||||
import java.time.LocalDateTime;
|
||||
import java.time.ZonedDateTime;
|
||||
import java.time.format.DateTimeFormatter;
|
||||
import java.time.format.DateTimeParseException;
|
||||
import java.util.Arrays;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* 日期时间配置类
|
||||
* 支持多种时间格式的自动解析
|
||||
*/
|
||||
@Configuration
|
||||
public class DateTimeConfig {
|
||||
|
||||
/**
|
||||
* 支持的时间格式列表
|
||||
*/
|
||||
private static final List<DateTimeFormatter> DATE_TIME_FORMATTERS = Arrays.asList(
|
||||
// 标准格式:yyyy-MM-dd HH:mm:ss
|
||||
DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"),
|
||||
// ISO 8601格式:yyyy-MM-ddTHH:mm:ss
|
||||
DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss"),
|
||||
// 带毫秒的ISO格式:yyyy-MM-ddTHH:mm:ss.SSS
|
||||
DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSS"),
|
||||
// 带毫秒的标准格式:yyyy-MM-dd HH:mm:ss.SSS
|
||||
DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.SSS"),
|
||||
// 日期格式:yyyy-MM-dd
|
||||
DateTimeFormatter.ofPattern("yyyy-MM-dd"),
|
||||
// 中文格式:yyyy年MM月dd日 HH:mm:ss
|
||||
DateTimeFormatter.ofPattern("yyyy年MM月dd日 HH:mm:ss"),
|
||||
// 中文格式:yyyy年MM月dd日
|
||||
DateTimeFormatter.ofPattern("yyyy年MM月dd日"),
|
||||
// 斜杠格式:yyyy/MM/dd HH:mm:ss
|
||||
DateTimeFormatter.ofPattern("yyyy/MM/dd HH:mm:ss"),
|
||||
// 斜杠格式:yyyy/MM/dd
|
||||
DateTimeFormatter.ofPattern("yyyy/MM/dd"),
|
||||
// 点格式:yyyy.MM.dd HH:mm:ss
|
||||
DateTimeFormatter.ofPattern("yyyy.MM.dd HH:mm:ss"),
|
||||
// 点格式:yyyy.MM.dd
|
||||
DateTimeFormatter.ofPattern("yyyy.MM.dd"),
|
||||
// 年月格式:yyyy-MM
|
||||
DateTimeFormatter.ofPattern("yyyy-MM")
|
||||
);
|
||||
|
||||
/**
|
||||
* 支持带时区的时间格式列表
|
||||
*/
|
||||
private static final List<DateTimeFormatter> ZONED_DATE_TIME_FORMATTERS = Arrays.asList(
|
||||
// ISO 8601带时区格式:yyyy-MM-ddTHH:mm:ss.SSSZ
|
||||
DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"),
|
||||
// ISO 8601带时区格式:yyyy-MM-ddTHH:mm:ssZ
|
||||
DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss'Z'"),
|
||||
// ISO 8601带时区格式:yyyy-MM-ddTHH:mm:ss.SSSXXX
|
||||
DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSSXXX"),
|
||||
// ISO 8601带时区格式:yyyy-MM-ddTHH:mm:ssXXX
|
||||
DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ssXXX"),
|
||||
// ISO 8601带时区格式:yyyy-MM-ddTHH:mm:ss.SSSZ
|
||||
DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSSZ"),
|
||||
// ISO 8601带时区格式:yyyy-MM-ddTHH:mm:ssZ
|
||||
DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ssZ")
|
||||
);
|
||||
|
||||
/**
|
||||
* 自定义LocalDate反序列化器
|
||||
*/
|
||||
public static class FlexibleLocalDateDeserializer extends JsonDeserializer<LocalDate> {
|
||||
@Override
|
||||
public LocalDate deserialize(JsonParser p, DeserializationContext ctxt) throws IOException {
|
||||
String dateString = p.getText().trim();
|
||||
|
||||
if (dateString == null || dateString.isEmpty()) {
|
||||
return null;
|
||||
}
|
||||
|
||||
// 年月格式特殊处理(yyyy-MM 长度为7),返回该月第一天
|
||||
if (dateString.length() == 7) {
|
||||
int year = Integer.parseInt(dateString.substring(0, 4));
|
||||
int month = Integer.parseInt(dateString.substring(5, 7));
|
||||
return LocalDate.of(year, month, 1);
|
||||
}
|
||||
|
||||
for (DateTimeFormatter formatter : DATE_TIME_FORMATTERS) {
|
||||
try {
|
||||
return LocalDate.parse(dateString, formatter);
|
||||
} catch (DateTimeParseException e) {
|
||||
// 继续尝试下一个格式
|
||||
}
|
||||
}
|
||||
|
||||
// 如果所有格式都失败,尝试从 ISO ZonedDateTime 解析再转 LocalDate
|
||||
for (DateTimeFormatter formatter : ZONED_DATE_TIME_FORMATTERS) {
|
||||
try {
|
||||
ZonedDateTime zdt = ZonedDateTime.parse(dateString, formatter);
|
||||
return zdt.toLocalDate();
|
||||
} catch (DateTimeParseException e) {
|
||||
// 继续尝试下一个格式
|
||||
}
|
||||
}
|
||||
|
||||
throw new IOException("无法解析日期格式: " + dateString);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 自定义LocalDate序列化器
|
||||
* 统一输出格式为 yyyy-MM-dd
|
||||
*/
|
||||
public static class StandardLocalDateSerializer extends JsonSerializer<LocalDate> {
|
||||
private static final DateTimeFormatter OUTPUT_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd");
|
||||
|
||||
@Override
|
||||
public void serialize(LocalDate value, JsonGenerator gen, SerializerProvider serializers) throws IOException {
|
||||
if (value == null) {
|
||||
gen.writeNull();
|
||||
} else {
|
||||
gen.writeString(value.format(OUTPUT_FORMATTER));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 自定义LocalDateTime反序列化器
|
||||
*/
|
||||
public static class FlexibleLocalDateTimeDeserializer extends JsonDeserializer<LocalDateTime> {
|
||||
@Override
|
||||
public LocalDateTime deserialize(JsonParser p, DeserializationContext ctxt) throws IOException {
|
||||
String dateTimeString = p.getText().trim();
|
||||
|
||||
if (dateTimeString == null || dateTimeString.isEmpty()) {
|
||||
return null;
|
||||
}
|
||||
|
||||
// 首先尝试带时区的格式
|
||||
for (DateTimeFormatter formatter : ZONED_DATE_TIME_FORMATTERS) {
|
||||
try {
|
||||
ZonedDateTime zonedDateTime = ZonedDateTime.parse(dateTimeString, formatter);
|
||||
return zonedDateTime.toLocalDateTime();
|
||||
} catch (DateTimeParseException e) {
|
||||
// 继续尝试下一个格式
|
||||
}
|
||||
}
|
||||
|
||||
// 然后尝试不带时区的格式
|
||||
for (DateTimeFormatter formatter : DATE_TIME_FORMATTERS) {
|
||||
try {
|
||||
return LocalDateTime.parse(dateTimeString, formatter);
|
||||
} catch (DateTimeParseException e) {
|
||||
// 继续尝试下一个格式
|
||||
}
|
||||
}
|
||||
|
||||
// 如果所有格式都失败,抛出异常
|
||||
throw new IOException("无法解析时间格式: " + dateTimeString +
|
||||
"。支持的格式包括: yyyy-MM-dd HH:mm:ss, yyyy-MM-ddTHH:mm:ss, yyyy-MM-ddTHH:mm:ss.SSSZ, yyyy-MM-dd等");
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 自定义LocalDateTime序列化器
|
||||
* 统一输出格式为 yyyy-MM-dd HH:mm:ss
|
||||
*/
|
||||
public static class StandardLocalDateTimeSerializer extends JsonSerializer<LocalDateTime> {
|
||||
private static final DateTimeFormatter OUTPUT_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
|
||||
|
||||
@Override
|
||||
public void serialize(LocalDateTime value, JsonGenerator gen, SerializerProvider serializers) throws IOException {
|
||||
if (value == null) {
|
||||
gen.writeNull();
|
||||
} else {
|
||||
gen.writeString(value.format(OUTPUT_FORMATTER));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 配置ObjectMapper支持多种时间格式
|
||||
*/
|
||||
@Bean
|
||||
@Primary
|
||||
public ObjectMapper objectMapper() {
|
||||
ObjectMapper mapper = new ObjectMapper();
|
||||
|
||||
// 注册Java时间模块
|
||||
mapper.registerModule(new JavaTimeModule());
|
||||
|
||||
// 创建自定义模块
|
||||
SimpleModule dateTimeModule = new SimpleModule();
|
||||
// 添加反序列化器(输入)
|
||||
dateTimeModule.addDeserializer(LocalDateTime.class, new FlexibleLocalDateTimeDeserializer());
|
||||
// 添加序列化器(输出)
|
||||
dateTimeModule.addSerializer(LocalDateTime.class, new StandardLocalDateTimeSerializer());
|
||||
|
||||
// 注册自定义模块
|
||||
mapper.registerModule(dateTimeModule);
|
||||
|
||||
// 单独为 LocalDate 注册反序列化器和序列化器(覆盖 JavaTimeModule 的默认实现)
|
||||
SimpleModule localDateModule = new SimpleModule();
|
||||
localDateModule.addDeserializer(LocalDate.class, new FlexibleLocalDateDeserializer());
|
||||
localDateModule.addSerializer(LocalDate.class, new StandardLocalDateSerializer());
|
||||
mapper.registerModule(localDateModule);
|
||||
|
||||
return mapper;
|
||||
}
|
||||
}
|
||||
+49
@@ -0,0 +1,49 @@
|
||||
package top.xyquan.ecomdmbbackend.common.config;
|
||||
|
||||
import com.baomidou.mybatisplus.annotation.DbType;
|
||||
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
|
||||
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
|
||||
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
|
||||
import org.apache.ibatis.reflection.MetaObject;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
|
||||
import top.xyquan.ecomdmbbackend.common.time.BizClock;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
/**
|
||||
* MyBatis Plus配置
|
||||
*/
|
||||
@Configuration
|
||||
public class MybatisPlusConfig {
|
||||
|
||||
/**
|
||||
* 分页插件
|
||||
*/
|
||||
@Bean
|
||||
public MybatisPlusInterceptor mybatisPlusInterceptor() {
|
||||
MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
|
||||
interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
|
||||
return interceptor;
|
||||
}
|
||||
|
||||
/**
|
||||
* 自动填充处理器
|
||||
*/
|
||||
@Bean
|
||||
public MetaObjectHandler metaObjectHandler() {
|
||||
return new MetaObjectHandler() {
|
||||
@Override
|
||||
public void insertFill(MetaObject metaObject) {
|
||||
this.strictInsertFill(metaObject, "createTime", LocalDateTime.class, BizClock.nowLdt());
|
||||
this.strictInsertFill(metaObject, "updateTime", LocalDateTime.class, BizClock.nowLdt());
|
||||
}
|
||||
|
||||
@Override
|
||||
public void updateFill(MetaObject metaObject) {
|
||||
this.strictUpdateFill(metaObject, "updateTime", LocalDateTime.class, BizClock.nowLdt());
|
||||
}
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
package top.xyquan.ecomdmbbackend.common.config;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonAutoDetect;
|
||||
import com.fasterxml.jackson.annotation.PropertyAccessor;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.data.redis.connection.RedisConnectionFactory;
|
||||
import org.springframework.data.redis.core.RedisTemplate;
|
||||
import org.springframework.data.redis.core.StringRedisTemplate;
|
||||
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
|
||||
import org.springframework.data.redis.serializer.StringRedisSerializer;
|
||||
|
||||
/**
|
||||
* Redis配置类
|
||||
*/
|
||||
@Configuration
|
||||
public class RedisConfig {
|
||||
|
||||
/**
|
||||
* 配置RedisTemplate
|
||||
*/
|
||||
@Bean
|
||||
public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory connectionFactory) {
|
||||
RedisTemplate<String, Object> template = new RedisTemplate<>();
|
||||
template.setConnectionFactory(connectionFactory);
|
||||
|
||||
// 使用Jackson2JsonRedisSerializer来序列化和反序列化redis的value值
|
||||
ObjectMapper objectMapper = new ObjectMapper();
|
||||
objectMapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
|
||||
objectMapper.registerModule(new JavaTimeModule());
|
||||
|
||||
Jackson2JsonRedisSerializer<Object> jackson2JsonRedisSerializer =
|
||||
new Jackson2JsonRedisSerializer<>(objectMapper, Object.class);
|
||||
|
||||
// 使用StringRedisSerializer来序列化和反序列化redis的key值
|
||||
StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();
|
||||
|
||||
// key采用String的序列化方式
|
||||
template.setKeySerializer(stringRedisSerializer);
|
||||
// hash的key也采用String的序列化方式
|
||||
template.setHashKeySerializer(stringRedisSerializer);
|
||||
// value序列化方式采用jackson
|
||||
template.setValueSerializer(jackson2JsonRedisSerializer);
|
||||
// hash的value序列化方式采用jackson
|
||||
template.setHashValueSerializer(jackson2JsonRedisSerializer);
|
||||
|
||||
template.afterPropertiesSet();
|
||||
return template;
|
||||
}
|
||||
|
||||
/** Stream 队列使用纯字符串序列化 */
|
||||
@Bean
|
||||
public StringRedisTemplate stringRedisTemplate(RedisConnectionFactory connectionFactory) {
|
||||
return new StringRedisTemplate(connectionFactory);
|
||||
}
|
||||
}
|
||||
|
||||
+20
@@ -0,0 +1,20 @@
|
||||
package top.xyquan.ecomdmbbackend.common.config;
|
||||
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.scheduling.TaskScheduler;
|
||||
import org.springframework.scheduling.concurrent.ThreadPoolTaskScheduler;
|
||||
|
||||
@Configuration
|
||||
public class SchedulingConfig {
|
||||
|
||||
@Bean
|
||||
public TaskScheduler taskScheduler() {
|
||||
ThreadPoolTaskScheduler scheduler = new ThreadPoolTaskScheduler();
|
||||
scheduler.setPoolSize(4);
|
||||
scheduler.setThreadNamePrefix("mq-delay-");
|
||||
scheduler.setRemoveOnCancelPolicy(true);
|
||||
scheduler.initialize();
|
||||
return scheduler;
|
||||
}
|
||||
}
|
||||
+107
@@ -0,0 +1,107 @@
|
||||
package top.xyquan.ecomdmbbackend.common.config;
|
||||
|
||||
import jakarta.servlet.DispatcherType;
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import jakarta.servlet.http.HttpServletResponse;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
|
||||
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
|
||||
import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer;
|
||||
import org.springframework.security.config.http.SessionCreationPolicy;
|
||||
import org.springframework.security.core.AuthenticationException;
|
||||
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
|
||||
import org.springframework.security.crypto.password.PasswordEncoder;
|
||||
import org.springframework.security.web.AuthenticationEntryPoint;
|
||||
import org.springframework.security.web.SecurityFilterChain;
|
||||
import org.springframework.security.web.access.AccessDeniedHandler;
|
||||
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
|
||||
import top.xyquan.ecomdmbbackend.common.filter.JwtAuthenticationFilter;
|
||||
import top.xyquan.ecomdmbbackend.modules.agent.mcp.security.AgentMcpAuthenticationFilter;
|
||||
import top.xyquan.ecomdmbbackend.modules.open.common.filter.ApiKeyAuthenticationFilter;
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
/**
|
||||
* Spring Security配置
|
||||
*/
|
||||
@Configuration
|
||||
@EnableWebSecurity
|
||||
public class SecurityConfig {
|
||||
|
||||
private final JwtAuthenticationFilter jwtAuthenticationFilter;
|
||||
private final ApiKeyAuthenticationFilter apiKeyAuthenticationFilter;
|
||||
private final AgentMcpAuthenticationFilter agentMcpAuthenticationFilter;
|
||||
|
||||
public SecurityConfig(JwtAuthenticationFilter jwtAuthenticationFilter,
|
||||
ApiKeyAuthenticationFilter apiKeyAuthenticationFilter,
|
||||
AgentMcpAuthenticationFilter agentMcpAuthenticationFilter) {
|
||||
this.jwtAuthenticationFilter = jwtAuthenticationFilter;
|
||||
this.apiKeyAuthenticationFilter = apiKeyAuthenticationFilter;
|
||||
this.agentMcpAuthenticationFilter = agentMcpAuthenticationFilter;
|
||||
}
|
||||
|
||||
@Bean
|
||||
public PasswordEncoder passwordEncoder() {
|
||||
return new BCryptPasswordEncoder();
|
||||
}
|
||||
|
||||
@Bean
|
||||
public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception {
|
||||
http
|
||||
.csrf(AbstractHttpConfigurer::disable)
|
||||
.sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
|
||||
.authorizeHttpRequests(auth -> auth
|
||||
// SSE:建连走 REQUEST(仍需 JWT);断开后 Tomcat 的 ASYNC/ERROR/FORWARD 调度无 SecurityContext,
|
||||
// 再鉴权会 AccessDenied,且 response 已提交只会刷噪音堆栈
|
||||
.dispatcherTypeMatchers(
|
||||
DispatcherType.ASYNC,
|
||||
DispatcherType.ERROR,
|
||||
DispatcherType.FORWARD)
|
||||
.permitAll()
|
||||
.requestMatchers("/api/auth/login", "/api/auth/register", "/api/auth/refresh").permitAll()
|
||||
.requestMatchers("/api/channel/pdd/auth/callback").permitAll()
|
||||
.requestMatchers("/uploads/**").permitAll() // 允许直接访问上传的文件
|
||||
.anyRequest().authenticated())
|
||||
.exceptionHandling(exceptions -> exceptions
|
||||
.authenticationEntryPoint(new CustomAuthenticationEntryPoint())
|
||||
.accessDeniedHandler(committedSafeAccessDeniedHandler()))
|
||||
// 自定义 Filter 均锚定 UsernamePasswordAuthenticationFilter;后注册的执行更靠前
|
||||
// 顺序意图:/mcp 先 Agent,/api/open 先 ApiKey,其余走 JWT
|
||||
.addFilterBefore(jwtAuthenticationFilter, UsernamePasswordAuthenticationFilter.class)
|
||||
.addFilterBefore(apiKeyAuthenticationFilter, UsernamePasswordAuthenticationFilter.class)
|
||||
.addFilterBefore(agentMcpAuthenticationFilter, UsernamePasswordAuthenticationFilter.class);
|
||||
|
||||
return http.build();
|
||||
}
|
||||
|
||||
/**
|
||||
* SSE 等长连接断开时 response 可能已 committed,此时写 403 会二次失败。
|
||||
*/
|
||||
private static AccessDeniedHandler committedSafeAccessDeniedHandler() {
|
||||
return (request, response, accessDeniedException) -> {
|
||||
if (response.isCommitted()) {
|
||||
return;
|
||||
}
|
||||
response.setStatus(HttpServletResponse.SC_FORBIDDEN);
|
||||
response.setContentType("application/json;charset=UTF-8");
|
||||
response.getWriter().write("{\"code\":403,\"message\":\"无权限访问\",\"data\":null}");
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 自定义认证入口点,返回401状态码
|
||||
*/
|
||||
private static class CustomAuthenticationEntryPoint implements AuthenticationEntryPoint {
|
||||
@Override
|
||||
public void commence(HttpServletRequest request, HttpServletResponse response,
|
||||
AuthenticationException authException) throws IOException {
|
||||
if (response.isCommitted()) {
|
||||
return;
|
||||
}
|
||||
response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
|
||||
response.setContentType("application/json;charset=UTF-8");
|
||||
response.getWriter().write("{\"code\":401,\"message\":\"登录已过期,请重新登录\",\"data\":null}");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
package top.xyquan.ecomdmbbackend.common.config;
|
||||
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.lang.NonNull;
|
||||
import org.springframework.web.servlet.config.annotation.CorsRegistry;
|
||||
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
|
||||
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
|
||||
|
||||
/**
|
||||
* Web配置
|
||||
*/
|
||||
@Configuration
|
||||
public class WebConfig implements WebMvcConfigurer {
|
||||
|
||||
@Override
|
||||
public void addResourceHandlers(@NonNull ResourceHandlerRegistry registry) {
|
||||
// 配置静态资源处理
|
||||
// 部署时可将 static/ 挂载到工作目录,优先于 jar 内 classpath
|
||||
registry.addResourceHandler("/static/**")
|
||||
.addResourceLocations("file:./static/", "classpath:/static/");
|
||||
|
||||
// 配置上传文件访问 - 使用绝对路径
|
||||
registry.addResourceHandler("/uploads/**")
|
||||
.addResourceLocations("file:./uploads/");
|
||||
}
|
||||
|
||||
@Override
|
||||
public void addCorsMappings(@NonNull CorsRegistry registry) {
|
||||
registry.addMapping("/**")
|
||||
.allowedOriginPatterns("*")
|
||||
.allowedMethods("GET", "POST", "PUT", "PATCH", "DELETE", "OPTIONS")
|
||||
.allowedHeaders("*")
|
||||
.exposedHeaders("Content-Disposition")
|
||||
.allowCredentials(true)
|
||||
.maxAge(3600);
|
||||
}
|
||||
}
|
||||
+23
@@ -0,0 +1,23 @@
|
||||
package top.xyquan.ecomdmbbackend.common.exception;
|
||||
|
||||
import lombok.Getter;
|
||||
|
||||
/**
|
||||
* 业务异常
|
||||
*/
|
||||
@Getter
|
||||
public class BusinessException extends RuntimeException {
|
||||
|
||||
private final String code;
|
||||
|
||||
public BusinessException(String message) {
|
||||
super(message);
|
||||
this.code = "BUSINESS_ERROR";
|
||||
}
|
||||
|
||||
public BusinessException(String code, String message) {
|
||||
super(message);
|
||||
this.code = code;
|
||||
}
|
||||
|
||||
}
|
||||
+112
@@ -0,0 +1,112 @@
|
||||
package top.xyquan.ecomdmbbackend.common.exception;
|
||||
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.security.access.AccessDeniedException;
|
||||
import org.springframework.security.core.AuthenticationException;
|
||||
import org.springframework.validation.BindException;
|
||||
import org.springframework.validation.FieldError;
|
||||
import org.springframework.web.bind.MethodArgumentNotValidException;
|
||||
import org.springframework.web.bind.annotation.ExceptionHandler;
|
||||
import org.springframework.web.bind.annotation.ResponseStatus;
|
||||
import org.springframework.web.bind.annotation.RestControllerAdvice;
|
||||
import org.springframework.web.servlet.NoHandlerFoundException;
|
||||
import top.xyquan.ecomdmbbackend.common.response.ApiResponse;
|
||||
import top.xyquan.ecomdmbbackend.modules.sys.license.LicenseException;
|
||||
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
/**
|
||||
* 全局异常处理器
|
||||
*/
|
||||
@RestControllerAdvice
|
||||
public class GlobalExceptionHandler {
|
||||
|
||||
/**
|
||||
* 处理 License 授权异常
|
||||
*/
|
||||
@ExceptionHandler(LicenseException.class)
|
||||
@ResponseStatus(HttpStatus.FORBIDDEN)
|
||||
public ApiResponse<String> handleLicenseException(LicenseException e) {
|
||||
return ApiResponse.fail(e.getMessage());
|
||||
}
|
||||
|
||||
/**
|
||||
* 处理业务异常
|
||||
*/
|
||||
@ExceptionHandler(BusinessException.class)
|
||||
@ResponseStatus(HttpStatus.BAD_REQUEST)
|
||||
public ApiResponse<String> handleBusinessException(BusinessException e) {
|
||||
return ApiResponse.fail(e.getMessage());
|
||||
}
|
||||
|
||||
/**
|
||||
* 处理运行时异常
|
||||
*/
|
||||
@ExceptionHandler(RuntimeException.class)
|
||||
@ResponseStatus(HttpStatus.BAD_REQUEST)
|
||||
public ApiResponse<String> handleRuntimeException(RuntimeException e) {
|
||||
return ApiResponse.fail(e.getMessage());
|
||||
}
|
||||
|
||||
/**
|
||||
* 处理参数验证异常
|
||||
*/
|
||||
@ExceptionHandler(MethodArgumentNotValidException.class)
|
||||
@ResponseStatus(HttpStatus.BAD_REQUEST)
|
||||
public ApiResponse<String> handleValidationException(MethodArgumentNotValidException e) {
|
||||
String message = e.getBindingResult().getFieldErrors().stream()
|
||||
.map(FieldError::getDefaultMessage)
|
||||
.collect(Collectors.joining(", "));
|
||||
return ApiResponse.fail("参数验证失败: " + message);
|
||||
}
|
||||
|
||||
/**
|
||||
* 处理绑定异常
|
||||
*/
|
||||
@ExceptionHandler(BindException.class)
|
||||
@ResponseStatus(HttpStatus.BAD_REQUEST)
|
||||
public ApiResponse<String> handleBindException(BindException e) {
|
||||
String message = e.getFieldErrors().stream()
|
||||
.map(FieldError::getDefaultMessage)
|
||||
.collect(Collectors.joining(", "));
|
||||
return ApiResponse.fail("参数绑定失败: " + message);
|
||||
}
|
||||
|
||||
/**
|
||||
* 处理认证异常
|
||||
*/
|
||||
@ExceptionHandler(AuthenticationException.class)
|
||||
@ResponseStatus(HttpStatus.UNAUTHORIZED)
|
||||
public ApiResponse<String> handleAuthenticationException(AuthenticationException e) {
|
||||
return ApiResponse.fail("认证失败: " + e.getMessage());
|
||||
}
|
||||
|
||||
/**
|
||||
* 处理权限异常
|
||||
*/
|
||||
@ExceptionHandler(AccessDeniedException.class)
|
||||
@ResponseStatus(HttpStatus.FORBIDDEN)
|
||||
public ApiResponse<String> handleAccessDeniedException(AccessDeniedException e) {
|
||||
return ApiResponse.fail("权限不足: " + e.getMessage());
|
||||
}
|
||||
|
||||
/**
|
||||
* 处理404异常
|
||||
*/
|
||||
@ExceptionHandler(NoHandlerFoundException.class)
|
||||
@ResponseStatus(HttpStatus.NOT_FOUND)
|
||||
public ApiResponse<String> handleNoHandlerFoundException(NoHandlerFoundException e) {
|
||||
return ApiResponse.fail("请求的资源不存在: " + e.getRequestURL());
|
||||
}
|
||||
|
||||
/**
|
||||
* 处理其他异常
|
||||
*/
|
||||
@ExceptionHandler(Exception.class)
|
||||
@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
|
||||
public ApiResponse<String> handleException(Exception e) {
|
||||
// 记录详细错误信息到日志
|
||||
e.printStackTrace();
|
||||
return ApiResponse.fail("系统内部错误: " + e.getMessage());
|
||||
}
|
||||
}
|
||||
+100
@@ -0,0 +1,100 @@
|
||||
package top.xyquan.ecomdmbbackend.common.filter;
|
||||
|
||||
import jakarta.servlet.FilterChain;
|
||||
import jakarta.servlet.ServletException;
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import jakarta.servlet.http.HttpServletResponse;
|
||||
import org.springframework.lang.NonNull;
|
||||
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
|
||||
import org.springframework.security.core.context.SecurityContextHolder;
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.springframework.util.StringUtils;
|
||||
import org.springframework.web.filter.OncePerRequestFilter;
|
||||
import top.xyquan.ecomdmbbackend.utils.JwtUtils;
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
/**
|
||||
* JWT认证过滤器
|
||||
*/
|
||||
@Component
|
||||
public class JwtAuthenticationFilter extends OncePerRequestFilter {
|
||||
|
||||
private final JwtUtils jwtUtils;
|
||||
|
||||
public JwtAuthenticationFilter(JwtUtils jwtUtils) {
|
||||
this.jwtUtils = jwtUtils;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected boolean shouldNotFilter(@NonNull HttpServletRequest request) {
|
||||
String uri = request.getRequestURI();
|
||||
if (uri == null) {
|
||||
return false;
|
||||
}
|
||||
return uri.startsWith("/api/open/")
|
||||
|| uri.equals("/mcp")
|
||||
|| uri.startsWith("/mcp/")
|
||||
|| uri.startsWith("/api/internal/agent/")
|
||||
|| uri.startsWith("/api/channel/pdd/auth/callback")
|
||||
|| uri.startsWith("/channel/pdd/auth/callback");
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void doFilterInternal(
|
||||
@NonNull HttpServletRequest request,
|
||||
@NonNull HttpServletResponse response,
|
||||
@NonNull FilterChain filterChain)
|
||||
throws ServletException, IOException {
|
||||
|
||||
// 添加调试日志
|
||||
logger.debug("JWT Filter处理请求: " + request.getMethod() + " " + request.getRequestURI());
|
||||
|
||||
try {
|
||||
// 从请求头中获取JWT Token
|
||||
String token = getTokenFromRequest(request);
|
||||
|
||||
if (StringUtils.hasText(token) && jwtUtils.validateToken(token)) {
|
||||
// 从Token中获取用户ID
|
||||
String userId = jwtUtils.getUserIdFromToken(token);
|
||||
Long companyId = jwtUtils.getCompanyIdFromToken(token);
|
||||
|
||||
if (StringUtils.hasText(userId)) {
|
||||
// 创建认证信息,将token作为credentials传递
|
||||
UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(
|
||||
userId, token, null);
|
||||
|
||||
// 设置认证信息到Security上下文
|
||||
SecurityContextHolder.getContext().setAuthentication(authentication);
|
||||
logger.debug("JWT认证成功,用户ID: " + userId);
|
||||
logger.debug("JWT认证成功,公司ID: " + companyId);
|
||||
logger.debug("JWT认证成功,Token: " + token);
|
||||
}
|
||||
} else {
|
||||
logger.debug("JWT Token无效或为空");
|
||||
}
|
||||
} catch (Exception e) {
|
||||
// Token验证失败,不设置认证信息,继续执行过滤器链
|
||||
logger.debug("JWT Token验证失败: " + e.getMessage());
|
||||
}
|
||||
|
||||
filterChain.doFilter(request, response);
|
||||
}
|
||||
|
||||
/**
|
||||
* 从请求头或query参数中获取JWT Token
|
||||
*/
|
||||
private String getTokenFromRequest(HttpServletRequest request) {
|
||||
// 优先从 Authorization header 获取
|
||||
String bearerToken = request.getHeader("Authorization");
|
||||
if (StringUtils.hasText(bearerToken) && bearerToken.startsWith("Bearer ")) {
|
||||
return bearerToken.substring(7);
|
||||
}
|
||||
// 回退:从 query 参数获取(EventSource 无法自定义 header)
|
||||
String queryToken = request.getParameter("token");
|
||||
if (StringUtils.hasText(queryToken)) {
|
||||
return queryToken;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
}
|
||||
+31
@@ -0,0 +1,31 @@
|
||||
package top.xyquan.ecomdmbbackend.common.model.dto;
|
||||
|
||||
import jakarta.validation.constraints.Min;
|
||||
import jakarta.validation.constraints.NotNull;
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Data;
|
||||
import lombok.NoArgsConstructor;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
@Data
|
||||
@AllArgsConstructor
|
||||
@NoArgsConstructor
|
||||
public class PageQueryDTO<T> {
|
||||
|
||||
//页码,从1开始
|
||||
@NotNull(message = "页码不能为空")
|
||||
@Min(value = 1, message = "页码必须大于0")
|
||||
private Integer page = 1;
|
||||
|
||||
//每页大小
|
||||
@NotNull(message = "每页大小不能为空")
|
||||
@Min(value = 1, message = "每页大小必须大于0")
|
||||
private Integer pageSize = 10;
|
||||
|
||||
// 查询条件
|
||||
private T filters;
|
||||
|
||||
// 排序规则列表(优先级从高到低)
|
||||
private List<SortDTO> sorts;
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
package top.xyquan.ecomdmbbackend.common.model.dto;
|
||||
|
||||
import jakarta.validation.constraints.NotBlank;
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Data;
|
||||
import lombok.NoArgsConstructor;
|
||||
|
||||
/**
|
||||
* 排序参数DTO
|
||||
*/
|
||||
@Data
|
||||
@AllArgsConstructor
|
||||
@NoArgsConstructor
|
||||
public class SortDTO {
|
||||
|
||||
/**
|
||||
* 排序字段名(对应数据库字段名)
|
||||
*/
|
||||
@NotBlank(message = "排序字段不能为空")
|
||||
private String field;
|
||||
|
||||
/**
|
||||
* 排序规则:asc | desc
|
||||
*/
|
||||
private String order = "desc";
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
package top.xyquan.ecomdmbbackend.common.model.vo;
|
||||
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Data;
|
||||
import lombok.NoArgsConstructor;
|
||||
|
||||
import java.io.Serializable;
|
||||
import java.util.List;
|
||||
|
||||
@Data
|
||||
@AllArgsConstructor
|
||||
@NoArgsConstructor
|
||||
public class PageResultVO<T> implements Serializable {
|
||||
private List<T> records; // 当前页数据
|
||||
private Long total; // 总条数
|
||||
private Integer page; // 当前页码
|
||||
private Integer pageSize; // 每页条数
|
||||
private Integer totalPages; // 总页数
|
||||
private Boolean hasNextPage; // 是否有下一页
|
||||
private Boolean hasPrevPage; // 是否有上一页
|
||||
|
||||
// 构造函数
|
||||
public PageResultVO(List<T> records, Long total, Integer page, Integer pageSize) {
|
||||
this.records = records;
|
||||
this.total = total;
|
||||
this.page = page;
|
||||
this.pageSize = pageSize;
|
||||
this.totalPages = (int) Math.ceil((double) total / pageSize);
|
||||
this.hasNextPage = page < this.totalPages;
|
||||
this.hasPrevPage = page > 1;
|
||||
}
|
||||
|
||||
// 静态工厂方法,用于创建分页响应对象
|
||||
public static <T> PageResultVO<T> create(List<T> list, Long total, Integer page, Integer pageSize) {
|
||||
return new PageResultVO<>(list, total, page, pageSize);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
package top.xyquan.ecomdmbbackend.common.mq;
|
||||
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Builder;
|
||||
import lombok.Data;
|
||||
import lombok.NoArgsConstructor;
|
||||
|
||||
/**
|
||||
* 渠道订单引用:镜像表主键。
|
||||
* 转换侧按 id 查渠道镜像;内部单按平台单号幂等键定位。
|
||||
*/
|
||||
@Data
|
||||
@Builder
|
||||
@NoArgsConstructor
|
||||
@AllArgsConstructor
|
||||
public class ChannelOrderRef {
|
||||
|
||||
/** 渠道镜像订单主键(如 channel_pdd_order.id) */
|
||||
private Long channelOrderId;
|
||||
}
|
||||
+33
@@ -0,0 +1,33 @@
|
||||
package top.xyquan.ecomdmbbackend.common.mq;
|
||||
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.amqp.rabbit.core.RabbitTemplate;
|
||||
import org.springframework.scheduling.TaskScheduler;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import java.time.Instant;
|
||||
|
||||
/**
|
||||
* 锁冲突等场景延后重投 MQ:用调度线程延迟,不阻塞 listener 消费线程。
|
||||
*/
|
||||
@Slf4j
|
||||
@Component
|
||||
@RequiredArgsConstructor
|
||||
public class DelayedMqRepublisher {
|
||||
|
||||
private final RabbitTemplate rabbitTemplate;
|
||||
private final TaskScheduler taskScheduler;
|
||||
|
||||
public void republish(String exchange, String routingKey, Object message, long delayMs) {
|
||||
long delay = Math.max(delayMs, 100L);
|
||||
Instant when = Instant.now().plusMillis(delay);
|
||||
taskScheduler.schedule(() -> {
|
||||
try {
|
||||
rabbitTemplate.convertAndSend(exchange, routingKey, message);
|
||||
} catch (Exception e) {
|
||||
log.error("延迟重投 MQ 失败 exchange={} rk={}", exchange, routingKey, e);
|
||||
}
|
||||
}, when);
|
||||
}
|
||||
}
|
||||
+33
@@ -0,0 +1,33 @@
|
||||
package top.xyquan.ecomdmbbackend.common.mq;
|
||||
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Builder;
|
||||
import lombok.Data;
|
||||
import lombok.NoArgsConstructor;
|
||||
|
||||
import java.time.OffsetDateTime;
|
||||
import java.util.List;
|
||||
|
||||
@Data
|
||||
@Builder
|
||||
@NoArgsConstructor
|
||||
@AllArgsConstructor
|
||||
public class OrderConvertMessage {
|
||||
|
||||
private String messageId;
|
||||
private Long companyId;
|
||||
private Long shopId;
|
||||
private String platform;
|
||||
private OrderConvertMode mode;
|
||||
/** FULL_DAY 必填:成交自然日 yyyy-MM-dd */
|
||||
private String statDate;
|
||||
/** 渠道镜像订单主键列表(增量按页必带;全量日可带,空则按店+成交日查渠道表) */
|
||||
private List<ChannelOrderRef> orders;
|
||||
private String syncBatchId;
|
||||
/** 全量同步任务 id(与 convertTaskId 区分) */
|
||||
private Long taskId;
|
||||
/** 全量转换任务 id;有则消费侧回写 convert 控制面 */
|
||||
private Long convertTaskId;
|
||||
private OffsetDateTime occurredAt;
|
||||
private Integer retryCount;
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
package top.xyquan.ecomdmbbackend.common.mq;
|
||||
|
||||
/**
|
||||
* 订单转换消息模式:全量日与增量共用同一转换队列。
|
||||
*/
|
||||
public enum OrderConvertMode {
|
||||
FULL_DAY,
|
||||
INC
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
package top.xyquan.ecomdmbbackend.common.mq;
|
||||
|
||||
/**
|
||||
* 订单同步 / 转换 / BI 管线 MQ 常量。
|
||||
*/
|
||||
public final class OrderMqConstants {
|
||||
|
||||
public static final String EXCHANGE = "ecom.order.topic";
|
||||
|
||||
public static final String RK_ORDER_SYNC_PDD_FULL = "order.sync.pdd.full";
|
||||
public static final String QUEUE_ORDER_SYNC_PDD_FULL = "order.sync.pdd.full";
|
||||
public static final String QUEUE_ORDER_SYNC_PDD_FULL_DLQ = "order.sync.pdd.full.dlq";
|
||||
|
||||
public static final String RK_ORDER_SYNC_PDD_INC = "order.sync.pdd.inc";
|
||||
public static final String QUEUE_ORDER_SYNC_PDD_INC = "order.sync.pdd.inc";
|
||||
public static final String QUEUE_ORDER_SYNC_PDD_INC_DLQ = "order.sync.pdd.inc.dlq";
|
||||
|
||||
public static final String RK_ORDER_CONVERT_PDD_FULL = "order.convert.pdd.full";
|
||||
public static final String QUEUE_ORDER_CONVERT_PDD_FULL = "order.convert.pdd.full";
|
||||
public static final String QUEUE_ORDER_CONVERT_PDD_FULL_DLQ = "order.convert.pdd.full.dlq";
|
||||
|
||||
public static final String RK_ORDER_CONVERT_PDD_INC = "order.convert.pdd.inc";
|
||||
public static final String QUEUE_ORDER_CONVERT_PDD_INC = "order.convert.pdd.inc";
|
||||
public static final String QUEUE_ORDER_CONVERT_PDD_INC_DLQ = "order.convert.pdd.inc.dlq";
|
||||
|
||||
public static final String RK_BI_STAT_FULL = "bi.stat.full";
|
||||
public static final String QUEUE_BI_STAT_FULL = "bi.stat.full";
|
||||
public static final String QUEUE_BI_STAT_FULL_DLQ = "bi.stat.full.dlq";
|
||||
|
||||
public static final String RK_BI_STAT_INC = "bi.stat.inc";
|
||||
public static final String QUEUE_BI_STAT_INC = "bi.stat.inc";
|
||||
public static final String QUEUE_BI_STAT_INC_DLQ = "bi.stat.inc.dlq";
|
||||
|
||||
/** 转换未绑定时异步拉商品详情并自动建品/回绑 */
|
||||
public static final String RK_ORDER_PRODUCT_AUTO_CREATE_PDD = "order.product.auto-create.pdd";
|
||||
public static final String QUEUE_ORDER_PRODUCT_AUTO_CREATE_PDD = "order.product.auto-create.pdd";
|
||||
public static final String QUEUE_ORDER_PRODUCT_AUTO_CREATE_PDD_DLQ = "order.product.auto-create.pdd.dlq";
|
||||
|
||||
private OrderMqConstants() {
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
package top.xyquan.ecomdmbbackend.common.mq;
|
||||
|
||||
/**
|
||||
* BI 全量任务创建来源。
|
||||
*/
|
||||
public final class TaskTriggerSource {
|
||||
|
||||
/** 用户手动创建 */
|
||||
public static final String MANUAL = "MANUAL";
|
||||
/** 上游全量转换任务 */
|
||||
public static final String CONVERT = "CONVERT";
|
||||
/** 脏日账本自动/手动重算 */
|
||||
public static final String DIRTY_DAY = "DIRTY_DAY";
|
||||
|
||||
/** @deprecated 已退役订单成本同步链路,历史任务只读展示 */
|
||||
@Deprecated
|
||||
public static final String COST_SYNC = "COST_SYNC";
|
||||
/** @deprecated 已退役迁品 apply 链路,由 DIRTY_DAY 替代 */
|
||||
@Deprecated
|
||||
public static final String SKU_MIGRATE = "SKU_MIGRATE";
|
||||
/** @deprecated 成本影响面账本,由 DIRTY_DAY 替代 */
|
||||
@Deprecated
|
||||
public static final String IMPACT = "IMPACT";
|
||||
|
||||
private TaskTriggerSource() {
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
package top.xyquan.ecomdmbbackend.common.response;
|
||||
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Data;
|
||||
import lombok.NoArgsConstructor;
|
||||
|
||||
@Data
|
||||
@AllArgsConstructor
|
||||
@NoArgsConstructor
|
||||
public class ApiResponse<T> {
|
||||
private int code;
|
||||
private String message;
|
||||
private T data;
|
||||
|
||||
public static <T> ApiResponse<T> success(T data) {
|
||||
return new ApiResponse<>(0, "操作成功", data);
|
||||
}
|
||||
|
||||
public static <T> ApiResponse<T> success(String message, T data) {
|
||||
return new ApiResponse<>(0, message, data);
|
||||
}
|
||||
|
||||
public static <T> ApiResponse<T> success() {
|
||||
return new ApiResponse<>(0, "操作成功", null);
|
||||
}
|
||||
|
||||
public static ApiResponse<Void> success(String message) {
|
||||
return new ApiResponse<>(0, message, null);
|
||||
}
|
||||
|
||||
public static <T> ApiResponse<T> fail(String message) {
|
||||
return new ApiResponse<>(1, message, null);
|
||||
}
|
||||
|
||||
public static <T> ApiResponse<T> fail(int code, String message) {
|
||||
return new ApiResponse<>(code, message, null);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
package top.xyquan.ecomdmbbackend.common.time;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.time.LocalDate;
|
||||
import java.time.LocalDateTime;
|
||||
import java.time.OffsetDateTime;
|
||||
import java.time.ZoneId;
|
||||
|
||||
/**
|
||||
* 业务时钟:全链路统一 Asia/Shanghai 墙钟,避免容器 JVM 默认 UTC 导致时间差 8 小时。
|
||||
*/
|
||||
public final class BizClock {
|
||||
|
||||
public static final ZoneId ZONE = ZoneId.of("Asia/Shanghai");
|
||||
|
||||
private BizClock() {
|
||||
}
|
||||
|
||||
public static LocalDateTime nowLdt() {
|
||||
return LocalDateTime.now(ZONE);
|
||||
}
|
||||
|
||||
public static LocalDate today() {
|
||||
return LocalDate.now(ZONE);
|
||||
}
|
||||
|
||||
public static OffsetDateTime nowOdt() {
|
||||
return OffsetDateTime.now(ZONE);
|
||||
}
|
||||
|
||||
/** epoch 比较用,与 {@link Instant#now()} 语义一致 */
|
||||
public static Instant nowInstant() {
|
||||
return Instant.now();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
package top.xyquan.ecomdmbbackend.common.utils;
|
||||
|
||||
import org.springframework.beans.BeanUtils;
|
||||
|
||||
import java.util.Objects;
|
||||
|
||||
/**
|
||||
* 属性拷贝工具:在调用 Spring {@link BeanUtils#copyProperties} 前断言 source/target 非空,
|
||||
* 消除 IDE 空值分析对 {@code BeanUtils.copyProperties} 入参的 Null type safety 警告。
|
||||
*/
|
||||
public final class BeanCopyUtils {
|
||||
|
||||
private BeanCopyUtils() {
|
||||
}
|
||||
|
||||
public static void copyProperties(Object source, Object target) {
|
||||
BeanUtils.copyProperties(Objects.requireNonNull(source), Objects.requireNonNull(target));
|
||||
}
|
||||
|
||||
public static void copyProperties(Object source, Object target, String... ignoreProperties) {
|
||||
Object nonNullSource = Objects.requireNonNull(source);
|
||||
Object nonNullTarget = Objects.requireNonNull(target);
|
||||
// varargs 在分析器里可能是可空数组,需显式断言后再传给 Spring
|
||||
String[] nonNullIgnores = Objects.requireNonNull(ignoreProperties);
|
||||
if (nonNullIgnores.length == 0) {
|
||||
BeanUtils.copyProperties(nonNullSource, nonNullTarget);
|
||||
return;
|
||||
}
|
||||
BeanUtils.copyProperties(nonNullSource, nonNullTarget, nonNullIgnores);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,117 @@
|
||||
package top.xyquan.ecomdmbbackend.common.utils;
|
||||
|
||||
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
|
||||
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
|
||||
import top.xyquan.ecomdmbbackend.common.model.dto.SortDTO;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.concurrent.ConcurrentHashMap;
|
||||
|
||||
/**
|
||||
* 排序工具类
|
||||
* 将 SortDTO 列表应用到 LambdaQueryWrapper
|
||||
*/
|
||||
public class SortUtils {
|
||||
|
||||
private SortUtils() {}
|
||||
|
||||
/**
|
||||
* 缓存:实体类 -> 字段名 -> 列名字符串
|
||||
*/
|
||||
private static final Map<Class<?>, Map<String, String>> COLUMN_CACHE = new ConcurrentHashMap<>();
|
||||
|
||||
/**
|
||||
* 应用排序规则到查询包装器
|
||||
* 支持多字段排序,优先级按列表顺序
|
||||
*/
|
||||
public static <T> void applySorts(
|
||||
LambdaQueryWrapper<T> wrapper,
|
||||
Class<T> entityClass,
|
||||
List<SortDTO> sorts) {
|
||||
|
||||
if (sorts == null || sorts.isEmpty()) {
|
||||
return;
|
||||
}
|
||||
|
||||
Map<String, String> fieldMap = getFieldColumnMap(entityClass);
|
||||
List<String> orderClauses = new ArrayList<>();
|
||||
|
||||
for (SortDTO sort : sorts) {
|
||||
if (StringUtils.isBlank(sort.getField())) {
|
||||
continue;
|
||||
}
|
||||
|
||||
String field = sort.getField().trim();
|
||||
String order = StringUtils.isBlank(sort.getOrder())
|
||||
? "desc"
|
||||
: sort.getOrder().trim().toLowerCase();
|
||||
|
||||
String columnName = findColumnName(fieldMap, field);
|
||||
if (columnName == null) {
|
||||
continue;
|
||||
}
|
||||
|
||||
boolean isAsc = "asc".equals(order);
|
||||
orderClauses.add(columnName + " " + (isAsc ? "ASC" : "DESC"));
|
||||
}
|
||||
|
||||
if (!orderClauses.isEmpty()) {
|
||||
// 一次添加所有排序子句,避免多次 last() 调用覆盖
|
||||
wrapper.last("ORDER BY " + String.join(", ", orderClauses));
|
||||
}
|
||||
}
|
||||
|
||||
private static <T> Map<String, String> getFieldColumnMap(Class<T> entityClass) {
|
||||
return COLUMN_CACHE.computeIfAbsent(entityClass, clazz -> {
|
||||
Map<String, String> map = new ConcurrentHashMap<>();
|
||||
try {
|
||||
for (var field : clazz.getDeclaredFields()) {
|
||||
var tableField = field.getAnnotation(
|
||||
com.baomidou.mybatisplus.annotation.TableField.class);
|
||||
String column;
|
||||
if (tableField != null && !tableField.value().isEmpty()) {
|
||||
column = tableField.value();
|
||||
} else {
|
||||
column = camelToSnake(field.getName());
|
||||
}
|
||||
map.put(field.getName(), column);
|
||||
map.put(camelToSnake(field.getName()), column);
|
||||
map.put(snakeToCamel(field.getName()), column);
|
||||
map.put(column, column);
|
||||
}
|
||||
} catch (Exception ignored) {}
|
||||
return map;
|
||||
});
|
||||
}
|
||||
|
||||
private static String findColumnName(Map<String, String> fieldMap, String field) {
|
||||
if (fieldMap.containsKey(field)) return fieldMap.get(field);
|
||||
String snake = camelToSnake(field);
|
||||
if (fieldMap.containsKey(snake)) return fieldMap.get(snake);
|
||||
String camel = snakeToCamel(field);
|
||||
if (fieldMap.containsKey(camel)) return fieldMap.get(camel);
|
||||
return null;
|
||||
}
|
||||
|
||||
public static String camelToSnake(String str) {
|
||||
if (str == null || str.isEmpty()) return str;
|
||||
return str.replaceAll("([a-z])([A-Z]+)", "$1_$2").toLowerCase();
|
||||
}
|
||||
|
||||
public static String snakeToCamel(String str) {
|
||||
if (str == null || str.isEmpty()) return str;
|
||||
StringBuilder sb = new StringBuilder();
|
||||
boolean upperNext = false;
|
||||
for (char c : str.toCharArray()) {
|
||||
if (c == '_') {
|
||||
upperNext = true;
|
||||
} else {
|
||||
sb.append(upperNext ? Character.toUpperCase(c) : c);
|
||||
upperNext = false;
|
||||
}
|
||||
}
|
||||
return sb.toString();
|
||||
}
|
||||
}
|
||||
+20
@@ -0,0 +1,20 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.agent.llm.config;
|
||||
|
||||
import lombok.Data;
|
||||
import org.springframework.boot.context.properties.ConfigurationProperties;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
/**
|
||||
* 租户模型 API Key 加解密与 Redis 缓存。
|
||||
*/
|
||||
@Data
|
||||
@Component
|
||||
@ConfigurationProperties(prefix = "ecom.agent.llm")
|
||||
public class AgentLlmProperties {
|
||||
|
||||
/** AES 密钥材料;空则回退 jwt.secret */
|
||||
private String secret = "";
|
||||
|
||||
/** Redis 运行时缓存 TTL 秒 */
|
||||
private long runtimeCacheTtlSeconds = 600;
|
||||
}
|
||||
+98
@@ -0,0 +1,98 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.agent.llm.controller;
|
||||
|
||||
import jakarta.validation.Valid;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.web.bind.annotation.DeleteMapping;
|
||||
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.PutMapping;
|
||||
import org.springframework.web.bind.annotation.RequestBody;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
import top.xyquan.ecomdmbbackend.common.annotation.RequirePermission;
|
||||
import top.xyquan.ecomdmbbackend.common.response.ApiResponse;
|
||||
import top.xyquan.ecomdmbbackend.modules.agent.llm.model.dto.CreateAgentLlmProviderDTO;
|
||||
import top.xyquan.ecomdmbbackend.modules.agent.llm.model.dto.ProbeAgentLlmModelsDTO;
|
||||
import top.xyquan.ecomdmbbackend.modules.agent.llm.model.dto.SetAgentLlmModelEnabledDTO;
|
||||
import top.xyquan.ecomdmbbackend.modules.agent.llm.model.dto.UpdateAgentLlmProviderDTO;
|
||||
import top.xyquan.ecomdmbbackend.modules.agent.llm.model.dto.UpsertAgentLlmProviderModelsDTO;
|
||||
import top.xyquan.ecomdmbbackend.modules.agent.llm.model.vo.AgentLlmEnabledModelsVO;
|
||||
import top.xyquan.ecomdmbbackend.modules.agent.llm.model.vo.AgentLlmProbeModelsResultVO;
|
||||
import top.xyquan.ecomdmbbackend.modules.agent.llm.model.vo.AgentLlmProviderListVO;
|
||||
import top.xyquan.ecomdmbbackend.modules.agent.llm.model.vo.AgentLlmProviderVO;
|
||||
import top.xyquan.ecomdmbbackend.modules.agent.llm.service.AgentCompanyLlmSettingsService;
|
||||
|
||||
/**
|
||||
* 公司多提供商模型 API(浏览器 JWT)。
|
||||
*/
|
||||
@RestController
|
||||
@RequestMapping("/api/company")
|
||||
@RequiredArgsConstructor
|
||||
public class AgentCompanyLlmSettingsController {
|
||||
|
||||
private final AgentCompanyLlmSettingsService settingsService;
|
||||
|
||||
@GetMapping("/agent-llm-providers")
|
||||
@RequirePermission(value = "agent:llm-settings", description = "查看模型提供商", allowSuper = true)
|
||||
public ApiResponse<AgentLlmProviderListVO> listProviders() {
|
||||
return ApiResponse.success(settingsService.listProvidersForCurrentCompany());
|
||||
}
|
||||
|
||||
@GetMapping("/agent-llm-providers/{id}")
|
||||
@RequirePermission(value = "agent:llm-settings", description = "查看模型提供商", allowSuper = true)
|
||||
public ApiResponse<AgentLlmProviderVO> getProvider(@PathVariable("id") Long id) {
|
||||
return ApiResponse.success(settingsService.getProviderForCurrentCompany(id));
|
||||
}
|
||||
|
||||
@PostMapping("/agent-llm-providers")
|
||||
@RequirePermission(value = "agent:llm-settings", description = "创建模型提供商", allowSuper = true)
|
||||
public ApiResponse<AgentLlmProviderVO> createProvider(@Valid @RequestBody CreateAgentLlmProviderDTO dto) {
|
||||
return ApiResponse.success("创建成功", settingsService.createProvider(dto));
|
||||
}
|
||||
|
||||
@PutMapping("/agent-llm-providers/{id}")
|
||||
@RequirePermission(value = "agent:llm-settings", description = "更新模型提供商", allowSuper = true)
|
||||
public ApiResponse<AgentLlmProviderVO> updateProvider(
|
||||
@PathVariable("id") Long id,
|
||||
@RequestBody UpdateAgentLlmProviderDTO dto) {
|
||||
return ApiResponse.success("保存成功", settingsService.updateProvider(id, dto));
|
||||
}
|
||||
|
||||
@DeleteMapping("/agent-llm-providers/{id}")
|
||||
@RequirePermission(value = "agent:llm-settings", description = "删除模型提供商", allowSuper = true)
|
||||
public ApiResponse<Void> deleteProvider(@PathVariable("id") Long id) {
|
||||
settingsService.deleteProvider(id);
|
||||
return ApiResponse.success("删除成功", null);
|
||||
}
|
||||
|
||||
@PutMapping("/agent-llm-providers/{id}/models")
|
||||
@RequirePermission(value = "agent:llm-settings", description = "更新启用模型", allowSuper = true)
|
||||
public ApiResponse<AgentLlmProviderVO> upsertModels(
|
||||
@PathVariable("id") Long id,
|
||||
@Valid @RequestBody UpsertAgentLlmProviderModelsDTO dto) {
|
||||
return ApiResponse.success("保存成功", settingsService.upsertProviderModels(id, dto));
|
||||
}
|
||||
|
||||
@PutMapping("/agent-llm-providers/{id}/models/enabled")
|
||||
@RequirePermission(value = "agent:llm-settings", description = "启用或禁用模型", allowSuper = true)
|
||||
public ApiResponse<AgentLlmProviderVO> setModelEnabled(
|
||||
@PathVariable("id") Long id,
|
||||
@Valid @RequestBody SetAgentLlmModelEnabledDTO dto) {
|
||||
return ApiResponse.success("已更新", settingsService.setModelEnabled(id, dto));
|
||||
}
|
||||
|
||||
@PostMapping("/agent-llm-settings/probe-models")
|
||||
@RequirePermission(value = "agent:llm-settings", description = "探测模型列表", allowSuper = true)
|
||||
public ApiResponse<AgentLlmProbeModelsResultVO> probeModels(
|
||||
@RequestBody ProbeAgentLlmModelsDTO dto) {
|
||||
return ApiResponse.success(settingsService.probeModels(dto));
|
||||
}
|
||||
|
||||
/** 聊天选模型:仅启用列表,无 Key */
|
||||
@GetMapping("/agent-llm-models")
|
||||
@RequirePermission(value = "agent:chat", description = "查看可用模型", allowSuper = true)
|
||||
public ApiResponse<AgentLlmEnabledModelsVO> listEnabledModels() {
|
||||
return ApiResponse.success(settingsService.listEnabledModelsForChat());
|
||||
}
|
||||
}
|
||||
+59
@@ -0,0 +1,59 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.agent.llm.controller;
|
||||
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.util.StringUtils;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RequestParam;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
import top.xyquan.ecomdmbbackend.common.exception.BusinessException;
|
||||
import top.xyquan.ecomdmbbackend.common.response.ApiResponse;
|
||||
import top.xyquan.ecomdmbbackend.modules.agent.llm.model.vo.AgentLlmRuntimeVO;
|
||||
import top.xyquan.ecomdmbbackend.modules.agent.llm.service.AgentCompanyLlmSettingsService;
|
||||
import top.xyquan.ecomdmbbackend.modules.agent.mcp.config.AgentMcpProperties;
|
||||
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.security.MessageDigest;
|
||||
|
||||
/**
|
||||
* Agent 内部拉取运行时模型配置(服务 Bearer,不下发浏览器)。
|
||||
*/
|
||||
@RestController
|
||||
@RequestMapping("/api/internal/agent")
|
||||
@RequiredArgsConstructor
|
||||
public class AgentInternalLlmController {
|
||||
|
||||
private final AgentCompanyLlmSettingsService settingsService;
|
||||
private final AgentMcpProperties mcpProperties;
|
||||
|
||||
@GetMapping("/llm-runtime")
|
||||
public ApiResponse<AgentLlmRuntimeVO> runtime(
|
||||
@RequestParam("companyId") Long companyId,
|
||||
@RequestParam(value = "providerId", required = false) Long providerId,
|
||||
@RequestParam(value = "model", required = false) String model,
|
||||
HttpServletRequest request) {
|
||||
assertAgentBearer(request);
|
||||
if (companyId == null) {
|
||||
throw new BusinessException("companyId 不能为空");
|
||||
}
|
||||
return ApiResponse.success(settingsService.getRuntime(companyId, providerId, model));
|
||||
}
|
||||
|
||||
private void assertAgentBearer(HttpServletRequest request) {
|
||||
String configured = mcpProperties.getBearerToken();
|
||||
if (!StringUtils.hasText(configured)) {
|
||||
throw new BusinessException("Agent 内部凭证未配置");
|
||||
}
|
||||
String authorization = request.getHeader("Authorization");
|
||||
if (!StringUtils.hasText(authorization) || !authorization.startsWith("Bearer ")) {
|
||||
throw new BusinessException("缺少 Agent Bearer");
|
||||
}
|
||||
String provided = authorization.substring(7).trim();
|
||||
byte[] a = configured.getBytes(StandardCharsets.UTF_8);
|
||||
byte[] b = provided.getBytes(StandardCharsets.UTF_8);
|
||||
if (!MessageDigest.isEqual(a, b)) {
|
||||
throw new BusinessException("Agent Bearer 无效");
|
||||
}
|
||||
}
|
||||
}
|
||||
+9
@@ -0,0 +1,9 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.agent.llm.mapper;
|
||||
|
||||
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
|
||||
import org.apache.ibatis.annotations.Mapper;
|
||||
import top.xyquan.ecomdmbbackend.modules.agent.llm.model.po.AgentCompanyLlmModelPO;
|
||||
|
||||
@Mapper
|
||||
public interface AgentCompanyLlmModelMapper extends BaseMapper<AgentCompanyLlmModelPO> {
|
||||
}
|
||||
+9
@@ -0,0 +1,9 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.agent.llm.mapper;
|
||||
|
||||
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
|
||||
import org.apache.ibatis.annotations.Mapper;
|
||||
import top.xyquan.ecomdmbbackend.modules.agent.llm.model.po.AgentCompanyLlmProviderPO;
|
||||
|
||||
@Mapper
|
||||
public interface AgentCompanyLlmProviderMapper extends BaseMapper<AgentCompanyLlmProviderPO> {
|
||||
}
|
||||
+12
@@ -0,0 +1,12 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.agent.llm.mapper;
|
||||
|
||||
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
|
||||
import org.apache.ibatis.annotations.Mapper;
|
||||
import top.xyquan.ecomdmbbackend.modules.agent.llm.model.po.AgentCompanyLlmSettingsPO;
|
||||
|
||||
/**
|
||||
* 公司模型 API 配置 Mapper。
|
||||
*/
|
||||
@Mapper
|
||||
public interface AgentCompanyLlmSettingsMapper extends BaseMapper<AgentCompanyLlmSettingsPO> {
|
||||
}
|
||||
+24
@@ -0,0 +1,24 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.agent.llm.model.dto;
|
||||
|
||||
import jakarta.validation.constraints.NotBlank;
|
||||
import lombok.Data;
|
||||
|
||||
/**
|
||||
* 启用模型条目。
|
||||
*/
|
||||
@Data
|
||||
public class AgentLlmModelItemDTO {
|
||||
|
||||
@NotBlank(message = "model 不能为空")
|
||||
private String model;
|
||||
|
||||
private String label;
|
||||
|
||||
/** 正整数;空/0 表示自动估计 */
|
||||
private Integer contextWindow;
|
||||
|
||||
private Boolean isDefault;
|
||||
|
||||
/** 是否启用;缺省 true */
|
||||
private Boolean enabled;
|
||||
}
|
||||
+24
@@ -0,0 +1,24 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.agent.llm.model.dto;
|
||||
|
||||
import jakarta.validation.constraints.NotBlank;
|
||||
import lombok.Data;
|
||||
|
||||
/**
|
||||
* 创建提供商。
|
||||
*/
|
||||
@Data
|
||||
public class CreateAgentLlmProviderDTO {
|
||||
|
||||
@NotBlank(message = "baseUrl 不能为空")
|
||||
private String baseUrl;
|
||||
|
||||
@NotBlank(message = "apiKey 不能为空")
|
||||
private String apiKey;
|
||||
|
||||
private String displayName;
|
||||
|
||||
/**
|
||||
* API 协议:auto | completions | responses;空则 auto
|
||||
*/
|
||||
private String apiStyle;
|
||||
}
|
||||
+24
@@ -0,0 +1,24 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.agent.llm.model.dto;
|
||||
|
||||
import lombok.Data;
|
||||
|
||||
/**
|
||||
* 探测提供商 /v1/models;可用已存 Key 或临时 Key。
|
||||
*/
|
||||
@Data
|
||||
public class ProbeAgentLlmModelsDTO {
|
||||
|
||||
/** 探测用的 Base URL;useStoredKey 且传 providerId 时可空(用库中 URL) */
|
||||
private String baseUrl;
|
||||
|
||||
/**
|
||||
* 临时 Key;与 useStoredKey 二选一。
|
||||
*/
|
||||
private String apiKey;
|
||||
|
||||
/** 为 true 时使用已保存的 apiKey(须指定 providerId) */
|
||||
private Boolean useStoredKey;
|
||||
|
||||
/** 使用已存密钥时指定提供商 */
|
||||
private Long providerId;
|
||||
}
|
||||
+18
@@ -0,0 +1,18 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.agent.llm.model.dto;
|
||||
|
||||
import jakarta.validation.constraints.NotBlank;
|
||||
import jakarta.validation.constraints.NotNull;
|
||||
import lombok.Data;
|
||||
|
||||
/**
|
||||
* 切换模型启用状态。
|
||||
*/
|
||||
@Data
|
||||
public class SetAgentLlmModelEnabledDTO {
|
||||
|
||||
@NotBlank(message = "model 不能为空")
|
||||
private String model;
|
||||
|
||||
@NotNull(message = "enabled 不能为空")
|
||||
private Boolean enabled;
|
||||
}
|
||||
+24
@@ -0,0 +1,24 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.agent.llm.model.dto;
|
||||
|
||||
import lombok.Data;
|
||||
|
||||
/**
|
||||
* 更新提供商凭证(apiKey 留空则不改)。
|
||||
*/
|
||||
@Data
|
||||
public class UpdateAgentLlmProviderDTO {
|
||||
|
||||
/** 非空则更新 Base URL */
|
||||
private String baseUrl;
|
||||
|
||||
/** 非空且非掩码则更新 Key */
|
||||
private String apiKey;
|
||||
|
||||
/** 传 null 表示不改;传空串可清空备注 */
|
||||
private String displayName;
|
||||
|
||||
/**
|
||||
* API 协议:auto | completions | responses;null 不改
|
||||
*/
|
||||
private String apiStyle;
|
||||
}
|
||||
+18
@@ -0,0 +1,18 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.agent.llm.model.dto;
|
||||
|
||||
import jakarta.validation.Valid;
|
||||
import jakarta.validation.constraints.NotEmpty;
|
||||
import lombok.Data;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* 某提供商下启用模型列表(增量 upsert,按 model 字符串匹配)。
|
||||
*/
|
||||
@Data
|
||||
public class UpsertAgentLlmProviderModelsDTO {
|
||||
|
||||
@NotEmpty(message = "至少启用一个模型")
|
||||
@Valid
|
||||
private List<AgentLlmModelItemDTO> models;
|
||||
}
|
||||
+54
@@ -0,0 +1,54 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.agent.llm.model.po;
|
||||
|
||||
import com.baomidou.mybatisplus.annotation.IdType;
|
||||
import com.baomidou.mybatisplus.annotation.TableField;
|
||||
import com.baomidou.mybatisplus.annotation.TableId;
|
||||
import com.baomidou.mybatisplus.annotation.TableName;
|
||||
import lombok.Data;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
/**
|
||||
* 公司已启用的 LLM 模型。
|
||||
*/
|
||||
@Data
|
||||
@TableName("agent_company_llm_model")
|
||||
public class AgentCompanyLlmModelPO {
|
||||
|
||||
@TableId(value = "id", type = IdType.AUTO)
|
||||
private Long id;
|
||||
|
||||
@TableField("company_id")
|
||||
private Long companyId;
|
||||
|
||||
@TableField("provider_id")
|
||||
private Long providerId;
|
||||
|
||||
@TableField("model")
|
||||
private String model;
|
||||
|
||||
@TableField("label")
|
||||
private String label;
|
||||
|
||||
@TableField("context_window")
|
||||
private Integer contextWindow;
|
||||
|
||||
@TableField("is_default")
|
||||
private Boolean isDefault;
|
||||
|
||||
/** 是否启用:true 可聊天选用 */
|
||||
@TableField("enabled")
|
||||
private Boolean enabled;
|
||||
|
||||
@TableField("create_by")
|
||||
private Long createBy;
|
||||
|
||||
@TableField("update_by")
|
||||
private Long updateBy;
|
||||
|
||||
@TableField("create_time")
|
||||
private LocalDateTime createTime;
|
||||
|
||||
@TableField("update_time")
|
||||
private LocalDateTime updateTime;
|
||||
}
|
||||
+56
@@ -0,0 +1,56 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.agent.llm.model.po;
|
||||
|
||||
import com.baomidou.mybatisplus.annotation.IdType;
|
||||
import com.baomidou.mybatisplus.annotation.TableField;
|
||||
import com.baomidou.mybatisplus.annotation.TableId;
|
||||
import com.baomidou.mybatisplus.annotation.TableName;
|
||||
import lombok.Data;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
/**
|
||||
* 公司 Agent LLM 提供商凭证(一套 base_url + api_key)。
|
||||
*/
|
||||
@Data
|
||||
@TableName("agent_company_llm_provider")
|
||||
public class AgentCompanyLlmProviderPO {
|
||||
|
||||
@TableId(value = "id", type = IdType.AUTO)
|
||||
private Long id;
|
||||
|
||||
@TableField("company_id")
|
||||
private Long companyId;
|
||||
|
||||
@TableField("base_url")
|
||||
private String baseUrl;
|
||||
|
||||
@TableField("api_key_encrypted")
|
||||
private String apiKeyEncrypted;
|
||||
|
||||
@TableField("api_key_suffix")
|
||||
private String apiKeySuffix;
|
||||
|
||||
@TableField("display_name")
|
||||
private String displayName;
|
||||
|
||||
/**
|
||||
* API 协议:auto | completions | responses
|
||||
*/
|
||||
@TableField("api_style")
|
||||
private String apiStyle;
|
||||
|
||||
@TableField("extra_headers_json")
|
||||
private String extraHeadersJson;
|
||||
|
||||
@TableField("create_by")
|
||||
private Long createBy;
|
||||
|
||||
@TableField("update_by")
|
||||
private Long updateBy;
|
||||
|
||||
@TableField("create_time")
|
||||
private LocalDateTime createTime;
|
||||
|
||||
@TableField("update_time")
|
||||
private LocalDateTime updateTime;
|
||||
}
|
||||
+54
@@ -0,0 +1,54 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.agent.llm.model.po;
|
||||
|
||||
import com.baomidou.mybatisplus.annotation.IdType;
|
||||
import com.baomidou.mybatisplus.annotation.TableField;
|
||||
import com.baomidou.mybatisplus.annotation.TableId;
|
||||
import com.baomidou.mybatisplus.annotation.TableName;
|
||||
import lombok.Data;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
/**
|
||||
* 公司 Agent 模型 API 配置。
|
||||
*/
|
||||
@Data
|
||||
@TableName("agent_company_llm_settings")
|
||||
public class AgentCompanyLlmSettingsPO {
|
||||
|
||||
@TableId(value = "id", type = IdType.AUTO)
|
||||
private Long id;
|
||||
|
||||
@TableField("company_id")
|
||||
private Long companyId;
|
||||
|
||||
@TableField("base_url")
|
||||
private String baseUrl;
|
||||
|
||||
@TableField("api_key_encrypted")
|
||||
private String apiKeyEncrypted;
|
||||
|
||||
@TableField("api_key_suffix")
|
||||
private String apiKeySuffix;
|
||||
|
||||
@TableField("model")
|
||||
private String model;
|
||||
|
||||
/** 模型上下文窗口(token);null 表示由 Agent 按模型名估计 */
|
||||
@TableField("context_window")
|
||||
private Integer contextWindow;
|
||||
|
||||
@TableField("extra_headers_json")
|
||||
private String extraHeadersJson;
|
||||
|
||||
@TableField("create_by")
|
||||
private Long createBy;
|
||||
|
||||
@TableField("update_by")
|
||||
private Long updateBy;
|
||||
|
||||
@TableField("create_time")
|
||||
private LocalDateTime createTime;
|
||||
|
||||
@TableField("update_time")
|
||||
private LocalDateTime updateTime;
|
||||
}
|
||||
+11
@@ -0,0 +1,11 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.agent.llm.model.vo;
|
||||
|
||||
import lombok.Data;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
@Data
|
||||
public class AgentLlmEnabledModelsVO {
|
||||
private List<AgentLlmModelVO> items = new ArrayList<>();
|
||||
}
|
||||
+23
@@ -0,0 +1,23 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.agent.llm.model.vo;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonProperty;
|
||||
import lombok.Data;
|
||||
|
||||
/**
|
||||
* 已启用模型条目(对外;含提供商消歧)。
|
||||
*/
|
||||
@Data
|
||||
public class AgentLlmModelVO {
|
||||
private Long id;
|
||||
private Long providerId;
|
||||
private String providerDisplayName;
|
||||
private String model;
|
||||
private String label;
|
||||
private Integer contextWindow;
|
||||
|
||||
@JsonProperty("isDefault")
|
||||
private boolean isDefault;
|
||||
|
||||
/** 是否启用(聊天仅可选启用的) */
|
||||
private boolean enabled;
|
||||
}
|
||||
+10
@@ -0,0 +1,10 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.agent.llm.model.vo;
|
||||
|
||||
import lombok.Data;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
@Data
|
||||
public class AgentLlmProbeModelsResultVO {
|
||||
private List<AgentLlmProbedModelVO> items;
|
||||
}
|
||||
+13
@@ -0,0 +1,13 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.agent.llm.model.vo;
|
||||
|
||||
import lombok.Data;
|
||||
|
||||
/**
|
||||
* 探测到的提供商模型(不落库)。
|
||||
*/
|
||||
@Data
|
||||
public class AgentLlmProbedModelVO {
|
||||
private String id;
|
||||
/** 厂商扩展字段解析;多数为 null */
|
||||
private Integer contextWindow;
|
||||
}
|
||||
+14
@@ -0,0 +1,14 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.agent.llm.model.vo;
|
||||
|
||||
import lombok.Data;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* 公司提供商列表。
|
||||
*/
|
||||
@Data
|
||||
public class AgentLlmProviderListVO {
|
||||
private List<AgentLlmProviderVO> items = new ArrayList<>();
|
||||
}
|
||||
+24
@@ -0,0 +1,24 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.agent.llm.model.vo;
|
||||
|
||||
import lombok.Data;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* 提供商(Key 仅掩码)+ 其下启用模型。
|
||||
*/
|
||||
@Data
|
||||
public class AgentLlmProviderVO {
|
||||
private Long id;
|
||||
private boolean configured;
|
||||
private String baseUrl;
|
||||
private String displayName;
|
||||
private String apiKeyMasked;
|
||||
private String updateTime;
|
||||
/**
|
||||
* API 协议:auto | completions | responses
|
||||
*/
|
||||
private String apiStyle;
|
||||
private List<AgentLlmModelVO> models = new ArrayList<>();
|
||||
}
|
||||
+23
@@ -0,0 +1,23 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.agent.llm.model.vo;
|
||||
|
||||
import lombok.Data;
|
||||
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* 仅供 Agent 内部拉取的运行时配置(含明文 apiKey)。
|
||||
*/
|
||||
@Data
|
||||
public class AgentLlmRuntimeVO {
|
||||
private Long providerId;
|
||||
private String baseUrl;
|
||||
private String apiKey;
|
||||
private String model;
|
||||
/** 上下文窗口 token;可能为 null */
|
||||
private Integer contextWindow;
|
||||
/**
|
||||
* API 协议:auto | completions | responses
|
||||
*/
|
||||
private String apiStyle;
|
||||
private Map<String, String> extraHeaders;
|
||||
}
|
||||
+47
@@ -0,0 +1,47 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.agent.llm.service;
|
||||
|
||||
import top.xyquan.ecomdmbbackend.modules.agent.llm.model.dto.CreateAgentLlmProviderDTO;
|
||||
import top.xyquan.ecomdmbbackend.modules.agent.llm.model.dto.ProbeAgentLlmModelsDTO;
|
||||
import top.xyquan.ecomdmbbackend.modules.agent.llm.model.dto.SetAgentLlmModelEnabledDTO;
|
||||
import top.xyquan.ecomdmbbackend.modules.agent.llm.model.dto.UpdateAgentLlmProviderDTO;
|
||||
import top.xyquan.ecomdmbbackend.modules.agent.llm.model.dto.UpsertAgentLlmProviderModelsDTO;
|
||||
import top.xyquan.ecomdmbbackend.modules.agent.llm.model.vo.AgentLlmEnabledModelsVO;
|
||||
import top.xyquan.ecomdmbbackend.modules.agent.llm.model.vo.AgentLlmProbeModelsResultVO;
|
||||
import top.xyquan.ecomdmbbackend.modules.agent.llm.model.vo.AgentLlmProviderListVO;
|
||||
import top.xyquan.ecomdmbbackend.modules.agent.llm.model.vo.AgentLlmProviderVO;
|
||||
import top.xyquan.ecomdmbbackend.modules.agent.llm.model.vo.AgentLlmRuntimeVO;
|
||||
|
||||
/**
|
||||
* 公司多提供商模型 API:凭证 CRUD + 按提供商增量 upsert 启用模型。
|
||||
*/
|
||||
public interface AgentCompanyLlmSettingsService {
|
||||
|
||||
AgentLlmProviderListVO listProvidersForCurrentCompany();
|
||||
|
||||
AgentLlmProviderVO getProviderForCurrentCompany(Long providerId);
|
||||
|
||||
AgentLlmProviderVO createProvider(CreateAgentLlmProviderDTO dto);
|
||||
|
||||
AgentLlmProviderVO updateProvider(Long providerId, UpdateAgentLlmProviderDTO dto);
|
||||
|
||||
void deleteProvider(Long providerId);
|
||||
|
||||
/** 按 (provider_id, model) 增量 upsert,不删再建仍保留的行 */
|
||||
AgentLlmProviderVO upsertProviderModels(Long providerId, UpsertAgentLlmProviderModelsDTO dto);
|
||||
|
||||
/** 启用/禁用某模型(禁用若为默认则自动改派) */
|
||||
AgentLlmProviderVO setModelEnabled(Long providerId, SetAgentLlmModelEnabledDTO dto);
|
||||
|
||||
AgentLlmProbeModelsResultVO probeModels(ProbeAgentLlmModelsDTO dto);
|
||||
|
||||
/** 聊天用:启用模型列表(无 Key,含 providerId) */
|
||||
AgentLlmEnabledModelsVO listEnabledModelsForChat();
|
||||
|
||||
/**
|
||||
* Agent 内部:运行时明文。
|
||||
*
|
||||
* @param providerId 与 model 同时为空 → 公司默认;仅 model 时若唯一匹配则用之,否则须带 providerId
|
||||
* @param model 空则取默认(或该 provider 下默认/首个)
|
||||
*/
|
||||
AgentLlmRuntimeVO getRuntime(Long companyId, Long providerId, String model);
|
||||
}
|
||||
+647
@@ -0,0 +1,647 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.agent.llm.service.impl;
|
||||
|
||||
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
|
||||
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
|
||||
import com.fasterxml.jackson.core.type.TypeReference;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.data.redis.core.StringRedisTemplate;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
import org.springframework.util.StringUtils;
|
||||
import top.xyquan.ecomdmbbackend.common.exception.BusinessException;
|
||||
import top.xyquan.ecomdmbbackend.modules.agent.llm.config.AgentLlmProperties;
|
||||
import top.xyquan.ecomdmbbackend.modules.agent.llm.mapper.AgentCompanyLlmModelMapper;
|
||||
import top.xyquan.ecomdmbbackend.modules.agent.llm.mapper.AgentCompanyLlmProviderMapper;
|
||||
import top.xyquan.ecomdmbbackend.modules.agent.llm.model.dto.AgentLlmModelItemDTO;
|
||||
import top.xyquan.ecomdmbbackend.modules.agent.llm.model.dto.CreateAgentLlmProviderDTO;
|
||||
import top.xyquan.ecomdmbbackend.modules.agent.llm.model.dto.ProbeAgentLlmModelsDTO;
|
||||
import top.xyquan.ecomdmbbackend.modules.agent.llm.model.dto.SetAgentLlmModelEnabledDTO;
|
||||
import top.xyquan.ecomdmbbackend.modules.agent.llm.model.dto.UpdateAgentLlmProviderDTO;
|
||||
import top.xyquan.ecomdmbbackend.modules.agent.llm.model.dto.UpsertAgentLlmProviderModelsDTO;
|
||||
import top.xyquan.ecomdmbbackend.modules.agent.llm.model.po.AgentCompanyLlmModelPO;
|
||||
import top.xyquan.ecomdmbbackend.modules.agent.llm.model.po.AgentCompanyLlmProviderPO;
|
||||
import top.xyquan.ecomdmbbackend.modules.agent.llm.model.vo.AgentLlmEnabledModelsVO;
|
||||
import top.xyquan.ecomdmbbackend.modules.agent.llm.model.vo.AgentLlmModelVO;
|
||||
import top.xyquan.ecomdmbbackend.modules.agent.llm.model.vo.AgentLlmProbeModelsResultVO;
|
||||
import top.xyquan.ecomdmbbackend.modules.agent.llm.model.vo.AgentLlmProviderListVO;
|
||||
import top.xyquan.ecomdmbbackend.modules.agent.llm.model.vo.AgentLlmProviderVO;
|
||||
import top.xyquan.ecomdmbbackend.modules.agent.llm.model.vo.AgentLlmRuntimeVO;
|
||||
import top.xyquan.ecomdmbbackend.modules.agent.llm.service.AgentCompanyLlmSettingsService;
|
||||
import top.xyquan.ecomdmbbackend.modules.agent.llm.support.AgentLlmCrypto;
|
||||
import top.xyquan.ecomdmbbackend.modules.agent.llm.support.OpenAiCompatibleModelsProbe;
|
||||
import top.xyquan.ecomdmbbackend.utils.CurrentUserContext;
|
||||
|
||||
import java.time.Duration;
|
||||
import java.time.format.DateTimeFormatter;
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.HashSet;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
import java.util.Set;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
/**
|
||||
* 公司多提供商模型 API:MySQL 存密文;Redis 按 company+provider+model 缓存明文。
|
||||
*/
|
||||
@Slf4j
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
public class AgentCompanyLlmSettingsServiceImpl implements AgentCompanyLlmSettingsService {
|
||||
|
||||
private static final DateTimeFormatter ISO = DateTimeFormatter.ISO_LOCAL_DATE_TIME;
|
||||
|
||||
private final AgentCompanyLlmProviderMapper providerMapper;
|
||||
private final AgentCompanyLlmModelMapper modelMapper;
|
||||
private final AgentLlmCrypto crypto;
|
||||
private final AgentLlmProperties llmProperties;
|
||||
private final CurrentUserContext currentUserContext;
|
||||
private final StringRedisTemplate stringRedisTemplate;
|
||||
private final ObjectMapper objectMapper;
|
||||
private final OpenAiCompatibleModelsProbe modelsProbe;
|
||||
|
||||
@Override
|
||||
public AgentLlmProviderListVO listProvidersForCurrentCompany() {
|
||||
Long companyId = currentUserContext.getCurrentCompanyId();
|
||||
AgentLlmProviderListVO vo = new AgentLlmProviderListVO();
|
||||
for (AgentCompanyLlmProviderPO p : listProviders(companyId)) {
|
||||
vo.getItems().add(toProviderVo(p, listModelsByProvider(companyId, p.getId())));
|
||||
}
|
||||
return vo;
|
||||
}
|
||||
|
||||
@Override
|
||||
public AgentLlmProviderVO getProviderForCurrentCompany(Long providerId) {
|
||||
Long companyId = currentUserContext.getCurrentCompanyId();
|
||||
AgentCompanyLlmProviderPO provider = requireOwnedProvider(companyId, providerId);
|
||||
return toProviderVo(provider, listModelsByProvider(companyId, providerId));
|
||||
}
|
||||
|
||||
@Override
|
||||
@Transactional(rollbackFor = Exception.class)
|
||||
public AgentLlmProviderVO createProvider(CreateAgentLlmProviderDTO dto) {
|
||||
Long companyId = currentUserContext.getCurrentCompanyId();
|
||||
Long userId = currentUserContext.getCurrentUserId();
|
||||
String baseUrl = dto.getBaseUrl().trim().replaceAll("/+$", "");
|
||||
String plain = dto.getApiKey().trim();
|
||||
if (!StringUtils.hasText(plain) || plain.startsWith("****")) {
|
||||
throw new BusinessException("创建提供商必须填写有效 apiKey");
|
||||
}
|
||||
|
||||
AgentCompanyLlmProviderPO po = new AgentCompanyLlmProviderPO();
|
||||
po.setCompanyId(companyId);
|
||||
po.setBaseUrl(baseUrl);
|
||||
po.setApiKeyEncrypted(crypto.encrypt(plain));
|
||||
po.setApiKeySuffix(plain.length() >= 4 ? plain.substring(plain.length() - 4) : plain);
|
||||
po.setDisplayName(trimToNull(dto.getDisplayName()));
|
||||
po.setApiStyle(normalizeApiStyle(dto.getApiStyle()));
|
||||
po.setCreateBy(userId);
|
||||
po.setUpdateBy(userId);
|
||||
providerMapper.insert(po);
|
||||
evictRuntimeCache(companyId);
|
||||
return toProviderVo(po, List.of());
|
||||
}
|
||||
|
||||
@Override
|
||||
@Transactional(rollbackFor = Exception.class)
|
||||
public AgentLlmProviderVO updateProvider(Long providerId, UpdateAgentLlmProviderDTO dto) {
|
||||
Long companyId = currentUserContext.getCurrentCompanyId();
|
||||
Long userId = currentUserContext.getCurrentUserId();
|
||||
AgentCompanyLlmProviderPO existing = requireOwnedProvider(companyId, providerId);
|
||||
|
||||
if (StringUtils.hasText(dto.getBaseUrl())) {
|
||||
existing.setBaseUrl(dto.getBaseUrl().trim().replaceAll("/+$", ""));
|
||||
}
|
||||
if (StringUtils.hasText(dto.getApiKey()) && !dto.getApiKey().trim().startsWith("****")) {
|
||||
String plain = dto.getApiKey().trim();
|
||||
existing.setApiKeyEncrypted(crypto.encrypt(plain));
|
||||
existing.setApiKeySuffix(plain.length() >= 4 ? plain.substring(plain.length() - 4) : plain);
|
||||
}
|
||||
if (dto.getDisplayName() != null) {
|
||||
existing.setDisplayName(trimToNull(dto.getDisplayName()));
|
||||
}
|
||||
if (dto.getApiStyle() != null) {
|
||||
existing.setApiStyle(normalizeApiStyle(dto.getApiStyle()));
|
||||
}
|
||||
existing.setUpdateBy(userId);
|
||||
providerMapper.updateById(existing);
|
||||
evictRuntimeCache(companyId);
|
||||
warmCacheForProvider(existing);
|
||||
return toProviderVo(existing, listModelsByProvider(companyId, providerId));
|
||||
}
|
||||
|
||||
@Override
|
||||
@Transactional(rollbackFor = Exception.class)
|
||||
public void deleteProvider(Long providerId) {
|
||||
Long companyId = currentUserContext.getCurrentCompanyId();
|
||||
requireOwnedProvider(companyId, providerId);
|
||||
boolean hadDefault = listModelsByProvider(companyId, providerId).stream()
|
||||
.anyMatch(m -> Boolean.TRUE.equals(m.getIsDefault()));
|
||||
// 模型 FK CASCADE
|
||||
providerMapper.deleteById(providerId);
|
||||
if (hadDefault) {
|
||||
ensureCompanyHasDefault(companyId, currentUserContext.getCurrentUserId());
|
||||
}
|
||||
evictRuntimeCache(companyId);
|
||||
}
|
||||
|
||||
@Override
|
||||
@Transactional(rollbackFor = Exception.class)
|
||||
public AgentLlmProviderVO upsertProviderModels(Long providerId, UpsertAgentLlmProviderModelsDTO dto) {
|
||||
Long companyId = currentUserContext.getCurrentCompanyId();
|
||||
Long userId = currentUserContext.getCurrentUserId();
|
||||
AgentCompanyLlmProviderPO provider = requireOwnedProvider(companyId, providerId);
|
||||
|
||||
List<AgentLlmModelItemDTO> items = normalizeModelItemsForProvider(dto.getModels());
|
||||
Map<String, AgentCompanyLlmModelPO> existingByModel = listModelsByProvider(companyId, providerId)
|
||||
.stream()
|
||||
.collect(Collectors.toMap(AgentCompanyLlmModelPO::getModel, m -> m, (a, b) -> a, LinkedHashMap::new));
|
||||
|
||||
Set<String> keep = new HashSet<>();
|
||||
boolean requestSetsDefault = items.stream().anyMatch(i -> Boolean.TRUE.equals(i.getIsDefault()));
|
||||
Long newDefaultModelRowId = null;
|
||||
|
||||
for (AgentLlmModelItemDTO item : items) {
|
||||
String modelId = item.getModel().trim();
|
||||
keep.add(modelId);
|
||||
boolean enabled = item.getEnabled() == null || Boolean.TRUE.equals(item.getEnabled());
|
||||
if (Boolean.TRUE.equals(item.getIsDefault()) && !enabled) {
|
||||
throw new BusinessException("禁用的模型不能设为公司默认: " + modelId);
|
||||
}
|
||||
AgentCompanyLlmModelPO row = existingByModel.get(modelId);
|
||||
if (row == null) {
|
||||
row = new AgentCompanyLlmModelPO();
|
||||
row.setCompanyId(companyId);
|
||||
row.setProviderId(providerId);
|
||||
row.setModel(modelId);
|
||||
row.setLabel(trimToNull(item.getLabel()));
|
||||
row.setContextWindow(normalizeContextWindow(item.getContextWindow()));
|
||||
row.setIsDefault(false);
|
||||
row.setEnabled(enabled);
|
||||
row.setCreateBy(userId);
|
||||
row.setUpdateBy(userId);
|
||||
modelMapper.insert(row);
|
||||
} else {
|
||||
row.setLabel(trimToNull(item.getLabel()));
|
||||
row.setContextWindow(normalizeContextWindow(item.getContextWindow()));
|
||||
row.setEnabled(enabled);
|
||||
row.setUpdateBy(userId);
|
||||
modelMapper.updateById(row);
|
||||
}
|
||||
if (Boolean.TRUE.equals(item.getIsDefault())) {
|
||||
newDefaultModelRowId = row.getId();
|
||||
}
|
||||
}
|
||||
|
||||
for (AgentCompanyLlmModelPO old : existingByModel.values()) {
|
||||
if (!keep.contains(old.getModel())) {
|
||||
modelMapper.deleteById(old.getId());
|
||||
}
|
||||
}
|
||||
|
||||
if (requestSetsDefault && newDefaultModelRowId != null) {
|
||||
clearCompanyDefaults(companyId);
|
||||
modelMapper.update(null, new LambdaUpdateWrapper<AgentCompanyLlmModelPO>()
|
||||
.eq(AgentCompanyLlmModelPO::getId, newDefaultModelRowId)
|
||||
.set(AgentCompanyLlmModelPO::getIsDefault, true)
|
||||
.set(AgentCompanyLlmModelPO::getUpdateBy, userId));
|
||||
} else {
|
||||
ensureCompanyHasDefault(companyId, userId);
|
||||
}
|
||||
|
||||
List<AgentCompanyLlmModelPO> saved = listModelsByProvider(companyId, providerId);
|
||||
evictRuntimeCache(companyId);
|
||||
warmCacheForProvider(provider);
|
||||
return toProviderVo(provider, saved);
|
||||
}
|
||||
|
||||
@Override
|
||||
@Transactional(rollbackFor = Exception.class)
|
||||
public AgentLlmProviderVO setModelEnabled(Long providerId, SetAgentLlmModelEnabledDTO dto) {
|
||||
Long companyId = currentUserContext.getCurrentCompanyId();
|
||||
Long userId = currentUserContext.getCurrentUserId();
|
||||
AgentCompanyLlmProviderPO provider = requireOwnedProvider(companyId, providerId);
|
||||
String modelId = dto.getModel().trim();
|
||||
boolean enabled = Boolean.TRUE.equals(dto.getEnabled());
|
||||
|
||||
AgentCompanyLlmModelPO row = modelMapper.selectOne(new LambdaQueryWrapper<AgentCompanyLlmModelPO>()
|
||||
.eq(AgentCompanyLlmModelPO::getCompanyId, companyId)
|
||||
.eq(AgentCompanyLlmModelPO::getProviderId, providerId)
|
||||
.eq(AgentCompanyLlmModelPO::getModel, modelId)
|
||||
.last("LIMIT 1"));
|
||||
if (row == null) {
|
||||
throw new BusinessException("模型不存在: " + modelId);
|
||||
}
|
||||
row.setEnabled(enabled);
|
||||
row.setUpdateBy(userId);
|
||||
if (!enabled && Boolean.TRUE.equals(row.getIsDefault())) {
|
||||
row.setIsDefault(false);
|
||||
}
|
||||
modelMapper.updateById(row);
|
||||
ensureCompanyHasDefault(companyId, userId);
|
||||
evictRuntimeCache(companyId);
|
||||
warmCacheForProvider(provider);
|
||||
return toProviderVo(provider, listModelsByProvider(companyId, providerId));
|
||||
}
|
||||
|
||||
@Override
|
||||
public AgentLlmProbeModelsResultVO probeModels(ProbeAgentLlmModelsDTO dto) {
|
||||
Long companyId = currentUserContext.getCurrentCompanyId();
|
||||
if (dto == null) {
|
||||
throw new BusinessException("请求体不能为空");
|
||||
}
|
||||
|
||||
String baseUrl;
|
||||
String apiKey;
|
||||
if (Boolean.TRUE.equals(dto.getUseStoredKey())) {
|
||||
if (dto.getProviderId() == null) {
|
||||
throw new BusinessException("使用已存密钥时须指定 providerId");
|
||||
}
|
||||
AgentCompanyLlmProviderPO provider = requireOwnedProvider(companyId, dto.getProviderId());
|
||||
baseUrl = StringUtils.hasText(dto.getBaseUrl())
|
||||
? dto.getBaseUrl().trim().replaceAll("/+$", "")
|
||||
: provider.getBaseUrl();
|
||||
apiKey = crypto.decrypt(provider.getApiKeyEncrypted());
|
||||
} else {
|
||||
if (!StringUtils.hasText(dto.getBaseUrl())) {
|
||||
throw new BusinessException("baseUrl 不能为空");
|
||||
}
|
||||
baseUrl = dto.getBaseUrl().trim().replaceAll("/+$", "");
|
||||
if (!StringUtils.hasText(dto.getApiKey()) || dto.getApiKey().trim().startsWith("****")) {
|
||||
throw new BusinessException("请填写 apiKey,或勾选使用已保存的密钥");
|
||||
}
|
||||
apiKey = dto.getApiKey().trim();
|
||||
}
|
||||
|
||||
AgentLlmProbeModelsResultVO vo = new AgentLlmProbeModelsResultVO();
|
||||
vo.setItems(modelsProbe.listModels(baseUrl, apiKey));
|
||||
return vo;
|
||||
}
|
||||
|
||||
@Override
|
||||
public AgentLlmEnabledModelsVO listEnabledModelsForChat() {
|
||||
Long companyId = currentUserContext.getCurrentCompanyId();
|
||||
Map<Long, AgentCompanyLlmProviderPO> providers = listProviders(companyId).stream()
|
||||
.collect(Collectors.toMap(AgentCompanyLlmProviderPO::getId, p -> p));
|
||||
AgentLlmEnabledModelsVO vo = new AgentLlmEnabledModelsVO();
|
||||
List<AgentLlmModelVO> items = new ArrayList<>();
|
||||
for (AgentCompanyLlmModelPO m : listEnabledModels(companyId)) {
|
||||
items.add(toModelVo(m, providers.get(m.getProviderId())));
|
||||
}
|
||||
vo.setItems(items);
|
||||
return vo;
|
||||
}
|
||||
|
||||
@Override
|
||||
public AgentLlmRuntimeVO getRuntime(Long companyId, Long providerId, String model) {
|
||||
if (companyId == null) {
|
||||
throw new BusinessException("companyId 不能为空");
|
||||
}
|
||||
List<AgentCompanyLlmModelPO> models = listEnabledModels(companyId);
|
||||
if (models.isEmpty()) {
|
||||
throw new BusinessException("公司尚未启用任何模型");
|
||||
}
|
||||
|
||||
AgentCompanyLlmModelPO selected = resolveModelRow(models, providerId, model);
|
||||
AgentCompanyLlmProviderPO provider = providerMapper.selectById(selected.getProviderId());
|
||||
if (provider == null || !Objects.equals(provider.getCompanyId(), companyId)) {
|
||||
throw new BusinessException("提供商不存在");
|
||||
}
|
||||
|
||||
AgentLlmRuntimeVO cached = readRuntimeCache(companyId, provider.getId(), selected.getModel());
|
||||
if (cached != null) {
|
||||
return cached;
|
||||
}
|
||||
AgentLlmRuntimeVO runtime = buildRuntimeForModel(provider, selected);
|
||||
cacheRuntime(companyId, runtime);
|
||||
return runtime;
|
||||
}
|
||||
|
||||
private AgentCompanyLlmModelPO resolveModelRow(
|
||||
List<AgentCompanyLlmModelPO> models, Long providerId, String model) {
|
||||
boolean hasModel = StringUtils.hasText(model);
|
||||
String want = hasModel ? model.trim() : null;
|
||||
|
||||
if (providerId != null && hasModel) {
|
||||
return models.stream()
|
||||
.filter(m -> providerId.equals(m.getProviderId()) && want.equals(m.getModel()))
|
||||
.findFirst()
|
||||
.orElseThrow(() -> new BusinessException(
|
||||
"模型未启用或不存在: providerId=" + providerId + ", model=" + want));
|
||||
}
|
||||
if (providerId != null) {
|
||||
List<AgentCompanyLlmModelPO> under = models.stream()
|
||||
.filter(m -> providerId.equals(m.getProviderId()))
|
||||
.toList();
|
||||
if (under.isEmpty()) {
|
||||
throw new BusinessException("该提供商尚未启用任何模型");
|
||||
}
|
||||
return under.stream()
|
||||
.filter(m -> Boolean.TRUE.equals(m.getIsDefault()))
|
||||
.findFirst()
|
||||
.orElse(under.get(0));
|
||||
}
|
||||
if (hasModel) {
|
||||
List<AgentCompanyLlmModelPO> matched = models.stream()
|
||||
.filter(m -> want.equals(m.getModel()))
|
||||
.toList();
|
||||
if (matched.isEmpty()) {
|
||||
throw new BusinessException("模型未启用或不存在: " + want);
|
||||
}
|
||||
if (matched.size() > 1) {
|
||||
throw new BusinessException("存在同名模型,请指定 providerId: " + want);
|
||||
}
|
||||
return matched.get(0);
|
||||
}
|
||||
return models.stream()
|
||||
.filter(m -> Boolean.TRUE.equals(m.getIsDefault()))
|
||||
.findFirst()
|
||||
.orElse(models.get(0));
|
||||
}
|
||||
|
||||
private List<AgentLlmModelItemDTO> normalizeModelItemsForProvider(List<AgentLlmModelItemDTO> raw) {
|
||||
if (raw == null || raw.isEmpty()) {
|
||||
throw new BusinessException("至少启用一个模型");
|
||||
}
|
||||
Set<String> seen = new HashSet<>();
|
||||
List<AgentLlmModelItemDTO> out = new ArrayList<>();
|
||||
int defaultIdx = -1;
|
||||
for (AgentLlmModelItemDTO item : raw) {
|
||||
if (item == null || !StringUtils.hasText(item.getModel())) {
|
||||
continue;
|
||||
}
|
||||
String id = item.getModel().trim();
|
||||
if (!seen.add(id)) {
|
||||
continue;
|
||||
}
|
||||
AgentLlmModelItemDTO copy = new AgentLlmModelItemDTO();
|
||||
copy.setModel(id);
|
||||
copy.setLabel(item.getLabel());
|
||||
copy.setContextWindow(item.getContextWindow());
|
||||
copy.setIsDefault(Boolean.TRUE.equals(item.getIsDefault()));
|
||||
copy.setEnabled(item.getEnabled() == null || Boolean.TRUE.equals(item.getEnabled()));
|
||||
if (Boolean.TRUE.equals(copy.getIsDefault())) {
|
||||
defaultIdx = out.size();
|
||||
}
|
||||
out.add(copy);
|
||||
}
|
||||
if (out.isEmpty()) {
|
||||
throw new BusinessException("至少启用一个模型");
|
||||
}
|
||||
if (defaultIdx >= 0) {
|
||||
for (int i = 0; i < out.size(); i++) {
|
||||
out.get(i).setIsDefault(i == defaultIdx);
|
||||
}
|
||||
// 默认必须启用
|
||||
out.get(defaultIdx).setEnabled(true);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
private void clearCompanyDefaults(Long companyId) {
|
||||
modelMapper.update(null, new LambdaUpdateWrapper<AgentCompanyLlmModelPO>()
|
||||
.eq(AgentCompanyLlmModelPO::getCompanyId, companyId)
|
||||
.eq(AgentCompanyLlmModelPO::getIsDefault, true)
|
||||
.set(AgentCompanyLlmModelPO::getIsDefault, false));
|
||||
}
|
||||
|
||||
private void ensureCompanyHasDefault(Long companyId, Long userId) {
|
||||
List<AgentCompanyLlmModelPO> enabled = listEnabledModels(companyId);
|
||||
if (enabled.isEmpty()) {
|
||||
// 无可用模型则清掉所有默认标记
|
||||
clearCompanyDefaults(companyId);
|
||||
return;
|
||||
}
|
||||
boolean has = enabled.stream().anyMatch(m -> Boolean.TRUE.equals(m.getIsDefault()));
|
||||
if (has) {
|
||||
return;
|
||||
}
|
||||
AgentCompanyLlmModelPO first = enabled.get(0);
|
||||
clearCompanyDefaults(companyId);
|
||||
modelMapper.update(null, new LambdaUpdateWrapper<AgentCompanyLlmModelPO>()
|
||||
.eq(AgentCompanyLlmModelPO::getId, first.getId())
|
||||
.set(AgentCompanyLlmModelPO::getIsDefault, true)
|
||||
.set(AgentCompanyLlmModelPO::getUpdateBy, userId));
|
||||
}
|
||||
|
||||
private AgentLlmRuntimeVO buildRuntimeForModel(
|
||||
AgentCompanyLlmProviderPO provider, AgentCompanyLlmModelPO model) {
|
||||
AgentLlmRuntimeVO vo = new AgentLlmRuntimeVO();
|
||||
vo.setProviderId(provider.getId());
|
||||
vo.setBaseUrl(provider.getBaseUrl());
|
||||
vo.setApiKey(crypto.decrypt(provider.getApiKeyEncrypted()));
|
||||
vo.setModel(model.getModel());
|
||||
vo.setContextWindow(model.getContextWindow());
|
||||
vo.setApiStyle(normalizeApiStyle(provider.getApiStyle()));
|
||||
vo.setExtraHeaders(parseHeaders(provider.getExtraHeadersJson()));
|
||||
return vo;
|
||||
}
|
||||
|
||||
private void warmCacheForProvider(AgentCompanyLlmProviderPO provider) {
|
||||
try {
|
||||
for (AgentCompanyLlmModelPO m : listModelsByProvider(provider.getCompanyId(), provider.getId())) {
|
||||
if (!Boolean.TRUE.equals(m.getEnabled())) {
|
||||
continue;
|
||||
}
|
||||
cacheRuntime(provider.getCompanyId(), buildRuntimeForModel(provider, m));
|
||||
}
|
||||
} catch (Exception e) {
|
||||
log.warn("预热 LLM 运行时缓存失败 companyId={} providerId={}",
|
||||
provider.getCompanyId(), provider.getId(), e);
|
||||
}
|
||||
}
|
||||
|
||||
private static String normalizeApiStyle(String raw) {
|
||||
if (!StringUtils.hasText(raw)) {
|
||||
return "auto";
|
||||
}
|
||||
String s = raw.trim().toLowerCase();
|
||||
if ("auto".equals(s) || "completions".equals(s) || "responses".equals(s)) {
|
||||
return s;
|
||||
}
|
||||
throw new BusinessException("apiStyle 必须是 auto / completions / responses");
|
||||
}
|
||||
|
||||
private static Integer normalizeContextWindow(Integer raw) {
|
||||
if (raw == null || raw <= 0) {
|
||||
return null;
|
||||
}
|
||||
return raw;
|
||||
}
|
||||
|
||||
private static String trimToNull(String s) {
|
||||
if (!StringUtils.hasText(s)) {
|
||||
return null;
|
||||
}
|
||||
String t = s.trim();
|
||||
return t.isEmpty() ? null : t;
|
||||
}
|
||||
|
||||
private Map<String, String> parseHeaders(String json) {
|
||||
if (!StringUtils.hasText(json)) {
|
||||
return Map.of();
|
||||
}
|
||||
try {
|
||||
return objectMapper.readValue(json, new TypeReference<Map<String, String>>() {
|
||||
});
|
||||
} catch (Exception e) {
|
||||
return Map.of();
|
||||
}
|
||||
}
|
||||
|
||||
private AgentCompanyLlmProviderPO requireOwnedProvider(Long companyId, Long providerId) {
|
||||
if (providerId == null) {
|
||||
throw new BusinessException("providerId 不能为空");
|
||||
}
|
||||
AgentCompanyLlmProviderPO provider = providerMapper.selectById(providerId);
|
||||
if (provider == null || !Objects.equals(provider.getCompanyId(), companyId)) {
|
||||
throw new BusinessException("提供商不存在");
|
||||
}
|
||||
return provider;
|
||||
}
|
||||
|
||||
private List<AgentCompanyLlmProviderPO> listProviders(Long companyId) {
|
||||
return providerMapper.selectList(new LambdaQueryWrapper<AgentCompanyLlmProviderPO>()
|
||||
.eq(AgentCompanyLlmProviderPO::getCompanyId, companyId)
|
||||
.orderByAsc(AgentCompanyLlmProviderPO::getId));
|
||||
}
|
||||
|
||||
/** 聊天/runtime:仅启用中的模型 */
|
||||
private List<AgentCompanyLlmModelPO> listEnabledModels(Long companyId) {
|
||||
return modelMapper.selectList(new LambdaQueryWrapper<AgentCompanyLlmModelPO>()
|
||||
.eq(AgentCompanyLlmModelPO::getCompanyId, companyId)
|
||||
.eq(AgentCompanyLlmModelPO::getEnabled, true)
|
||||
.orderByDesc(AgentCompanyLlmModelPO::getIsDefault)
|
||||
.orderByAsc(AgentCompanyLlmModelPO::getProviderId)
|
||||
.orderByAsc(AgentCompanyLlmModelPO::getId));
|
||||
}
|
||||
|
||||
private List<AgentCompanyLlmModelPO> listModelsByProvider(Long companyId, Long providerId) {
|
||||
return modelMapper.selectList(new LambdaQueryWrapper<AgentCompanyLlmModelPO>()
|
||||
.eq(AgentCompanyLlmModelPO::getCompanyId, companyId)
|
||||
.eq(AgentCompanyLlmModelPO::getProviderId, providerId)
|
||||
.orderByDesc(AgentCompanyLlmModelPO::getEnabled)
|
||||
.orderByDesc(AgentCompanyLlmModelPO::getIsDefault)
|
||||
.orderByAsc(AgentCompanyLlmModelPO::getId));
|
||||
}
|
||||
|
||||
private AgentLlmModelVO toModelVo(AgentCompanyLlmModelPO m, AgentCompanyLlmProviderPO provider) {
|
||||
AgentLlmModelVO mv = new AgentLlmModelVO();
|
||||
mv.setId(m.getId());
|
||||
mv.setProviderId(m.getProviderId());
|
||||
if (provider != null) {
|
||||
mv.setProviderDisplayName(
|
||||
StringUtils.hasText(provider.getDisplayName())
|
||||
? provider.getDisplayName()
|
||||
: provider.getBaseUrl());
|
||||
}
|
||||
mv.setModel(m.getModel());
|
||||
mv.setLabel(m.getLabel());
|
||||
mv.setContextWindow(m.getContextWindow());
|
||||
mv.setDefault(Boolean.TRUE.equals(m.getIsDefault()));
|
||||
mv.setEnabled(m.getEnabled() == null || Boolean.TRUE.equals(m.getEnabled()));
|
||||
return mv;
|
||||
}
|
||||
|
||||
private AgentLlmProviderVO toProviderVo(
|
||||
AgentCompanyLlmProviderPO provider, List<AgentCompanyLlmModelPO> models) {
|
||||
AgentLlmProviderVO vo = new AgentLlmProviderVO();
|
||||
vo.setId(provider.getId());
|
||||
vo.setConfigured(true);
|
||||
vo.setBaseUrl(provider.getBaseUrl());
|
||||
vo.setDisplayName(provider.getDisplayName());
|
||||
vo.setApiStyle(normalizeApiStyle(provider.getApiStyle()));
|
||||
vo.setApiKeyMasked("****" + (provider.getApiKeySuffix() == null ? "" : provider.getApiKeySuffix()));
|
||||
if (provider.getUpdateTime() != null) {
|
||||
vo.setUpdateTime(provider.getUpdateTime().format(ISO));
|
||||
}
|
||||
List<AgentLlmModelVO> modelVos = new ArrayList<>();
|
||||
for (AgentCompanyLlmModelPO m : models) {
|
||||
modelVos.add(toModelVo(m, provider));
|
||||
}
|
||||
vo.setModels(modelVos);
|
||||
return vo;
|
||||
}
|
||||
|
||||
private static String redisKey(Long companyId, Long providerId, String model) {
|
||||
return "agent:llm:rt:" + companyId + ":" + providerId + ":" + model;
|
||||
}
|
||||
|
||||
private void cacheRuntime(Long companyId, AgentLlmRuntimeVO runtime) {
|
||||
try {
|
||||
Map<String, Object> payload = new HashMap<>();
|
||||
payload.put("provider_id", runtime.getProviderId());
|
||||
payload.put("base_url", runtime.getBaseUrl());
|
||||
payload.put("api_key", runtime.getApiKey());
|
||||
payload.put("model", runtime.getModel());
|
||||
payload.put("context_window", runtime.getContextWindow());
|
||||
payload.put("api_style", runtime.getApiStyle() == null ? "auto" : runtime.getApiStyle());
|
||||
payload.put("extra_headers",
|
||||
runtime.getExtraHeaders() == null ? Map.of() : runtime.getExtraHeaders());
|
||||
stringRedisTemplate.opsForValue().set(
|
||||
redisKey(companyId, runtime.getProviderId(), runtime.getModel()),
|
||||
objectMapper.writeValueAsString(payload),
|
||||
Duration.ofSeconds(Math.max(60, llmProperties.getRuntimeCacheTtlSeconds())));
|
||||
} catch (Exception e) {
|
||||
log.warn("写入 LLM Redis 缓存失败 companyId={}", companyId, e);
|
||||
}
|
||||
}
|
||||
|
||||
private AgentLlmRuntimeVO readRuntimeCache(Long companyId, Long providerId, String model) {
|
||||
try {
|
||||
String raw = stringRedisTemplate.opsForValue().get(redisKey(companyId, providerId, model));
|
||||
if (!StringUtils.hasText(raw)) {
|
||||
return null;
|
||||
}
|
||||
Map<String, Object> map = objectMapper.readValue(raw, new TypeReference<>() {
|
||||
});
|
||||
AgentLlmRuntimeVO vo = new AgentLlmRuntimeVO();
|
||||
Object pid = map.get("provider_id");
|
||||
if (pid instanceof Number n) {
|
||||
vo.setProviderId(n.longValue());
|
||||
} else {
|
||||
vo.setProviderId(providerId);
|
||||
}
|
||||
vo.setBaseUrl(String.valueOf(map.get("base_url")));
|
||||
vo.setApiKey(String.valueOf(map.get("api_key")));
|
||||
vo.setModel(String.valueOf(map.get("model")));
|
||||
Object cw = map.get("context_window");
|
||||
if (cw instanceof Number n) {
|
||||
vo.setContextWindow(n.intValue());
|
||||
} else if (cw != null && StringUtils.hasText(String.valueOf(cw))
|
||||
&& !"null".equalsIgnoreCase(String.valueOf(cw))) {
|
||||
try {
|
||||
vo.setContextWindow(Integer.parseInt(String.valueOf(cw)));
|
||||
} catch (NumberFormatException ignored) {
|
||||
vo.setContextWindow(null);
|
||||
}
|
||||
} else {
|
||||
vo.setContextWindow(null);
|
||||
}
|
||||
Object style = map.get("api_style");
|
||||
vo.setApiStyle(style == null ? "auto" : normalizeApiStyle(String.valueOf(style)));
|
||||
Object headers = map.get("extra_headers");
|
||||
if (headers instanceof Map<?, ?> m) {
|
||||
Map<String, String> h = new HashMap<>();
|
||||
m.forEach((k, v) -> h.put(String.valueOf(k), String.valueOf(v)));
|
||||
vo.setExtraHeaders(h);
|
||||
} else {
|
||||
vo.setExtraHeaders(Map.of());
|
||||
}
|
||||
return vo;
|
||||
} catch (Exception e) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
private void evictRuntimeCache(Long companyId) {
|
||||
Set<String> keys = stringRedisTemplate.keys("agent:llm:rt:" + companyId + "*");
|
||||
if (keys != null && !keys.isEmpty()) {
|
||||
stringRedisTemplate.delete(keys);
|
||||
}
|
||||
}
|
||||
}
|
||||
+78
@@ -0,0 +1,78 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.agent.llm.support;
|
||||
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.springframework.util.StringUtils;
|
||||
import top.xyquan.ecomdmbbackend.common.exception.BusinessException;
|
||||
import top.xyquan.ecomdmbbackend.modules.agent.llm.config.AgentLlmProperties;
|
||||
|
||||
import javax.crypto.Cipher;
|
||||
import javax.crypto.SecretKey;
|
||||
import javax.crypto.spec.GCMParameterSpec;
|
||||
import javax.crypto.spec.SecretKeySpec;
|
||||
import java.nio.ByteBuffer;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.security.MessageDigest;
|
||||
import java.security.SecureRandom;
|
||||
import java.util.Base64;
|
||||
|
||||
/**
|
||||
* 租户 API Key AES-GCM 加解密(密钥由 ecom.agent.llm.secret 或 jwt.secret 派生)。
|
||||
*/
|
||||
@Component
|
||||
public class AgentLlmCrypto {
|
||||
|
||||
private static final String TRANSFORMATION = "AES/GCM/NoPadding";
|
||||
private static final int GCM_IV_LENGTH = 12;
|
||||
private static final int GCM_TAG_LENGTH = 128;
|
||||
|
||||
private final AgentLlmProperties llmProperties;
|
||||
private final String jwtSecret;
|
||||
|
||||
public AgentLlmCrypto(AgentLlmProperties llmProperties,
|
||||
@Value("${jwt.secret}") String jwtSecret) {
|
||||
this.llmProperties = llmProperties;
|
||||
this.jwtSecret = jwtSecret;
|
||||
}
|
||||
|
||||
public String encrypt(String plain) {
|
||||
try {
|
||||
byte[] iv = new byte[GCM_IV_LENGTH];
|
||||
new SecureRandom().nextBytes(iv);
|
||||
Cipher cipher = Cipher.getInstance(TRANSFORMATION);
|
||||
cipher.init(Cipher.ENCRYPT_MODE, secretKey(), new GCMParameterSpec(GCM_TAG_LENGTH, iv));
|
||||
byte[] cipherBytes = cipher.doFinal(plain.getBytes(StandardCharsets.UTF_8));
|
||||
ByteBuffer buffer = ByteBuffer.allocate(iv.length + cipherBytes.length);
|
||||
buffer.put(iv);
|
||||
buffer.put(cipherBytes);
|
||||
return Base64.getEncoder().encodeToString(buffer.array());
|
||||
} catch (Exception e) {
|
||||
throw new BusinessException("加密 API Key 失败");
|
||||
}
|
||||
}
|
||||
|
||||
public String decrypt(String token) {
|
||||
try {
|
||||
byte[] all = Base64.getDecoder().decode(token);
|
||||
ByteBuffer buffer = ByteBuffer.wrap(all);
|
||||
byte[] iv = new byte[GCM_IV_LENGTH];
|
||||
buffer.get(iv);
|
||||
byte[] cipherBytes = new byte[buffer.remaining()];
|
||||
buffer.get(cipherBytes);
|
||||
Cipher cipher = Cipher.getInstance(TRANSFORMATION);
|
||||
cipher.init(Cipher.DECRYPT_MODE, secretKey(), new GCMParameterSpec(GCM_TAG_LENGTH, iv));
|
||||
return new String(cipher.doFinal(cipherBytes), StandardCharsets.UTF_8);
|
||||
} catch (Exception e) {
|
||||
throw new BusinessException("解密 API Key 失败,请检查 ecom.agent.llm.secret");
|
||||
}
|
||||
}
|
||||
|
||||
private SecretKey secretKey() throws Exception {
|
||||
String material = StringUtils.hasText(llmProperties.getSecret())
|
||||
? llmProperties.getSecret()
|
||||
: jwtSecret;
|
||||
byte[] digest = MessageDigest.getInstance("SHA-256")
|
||||
.digest(material.getBytes(StandardCharsets.UTF_8));
|
||||
return new SecretKeySpec(digest, "AES");
|
||||
}
|
||||
}
|
||||
+136
@@ -0,0 +1,136 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.agent.llm.support;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.http.HttpEntity;
|
||||
import org.springframework.http.HttpHeaders;
|
||||
import org.springframework.http.HttpMethod;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.springframework.util.StringUtils;
|
||||
import org.springframework.web.client.RestClientException;
|
||||
import org.springframework.web.client.RestTemplate;
|
||||
import top.xyquan.ecomdmbbackend.common.exception.BusinessException;
|
||||
import top.xyquan.ecomdmbbackend.modules.agent.llm.model.vo.AgentLlmProbedModelVO;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* 出站探测 OpenAI Compatible GET /models(不落库、不打明文 Key 日志)。
|
||||
*/
|
||||
@Slf4j
|
||||
@Component
|
||||
@RequiredArgsConstructor
|
||||
public class OpenAiCompatibleModelsProbe {
|
||||
|
||||
private final ObjectMapper objectMapper;
|
||||
private final RestTemplate restTemplate = new RestTemplate();
|
||||
|
||||
public List<AgentLlmProbedModelVO> listModels(String baseUrl, String apiKey) {
|
||||
if (!StringUtils.hasText(baseUrl) || !StringUtils.hasText(apiKey)) {
|
||||
throw new BusinessException("探测模型需要 baseUrl 与 apiKey");
|
||||
}
|
||||
String root = baseUrl.trim().replaceAll("/+$", "");
|
||||
String url = root.endsWith("/v1") ? root + "/models" : root + "/v1/models";
|
||||
|
||||
HttpHeaders headers = new HttpHeaders();
|
||||
headers.setBearerAuth(apiKey.trim());
|
||||
headers.set(HttpHeaders.ACCEPT, "application/json");
|
||||
try {
|
||||
ResponseEntity<String> resp = restTemplate.exchange(
|
||||
url, HttpMethod.GET, new HttpEntity<>(headers), String.class);
|
||||
if (!resp.getStatusCode().is2xxSuccessful() || resp.getBody() == null) {
|
||||
throw new BusinessException("提供商返回异常 HTTP " + resp.getStatusCode().value());
|
||||
}
|
||||
return parse(resp.getBody());
|
||||
} catch (BusinessException e) {
|
||||
throw e;
|
||||
} catch (RestClientException e) {
|
||||
log.warn("探测 /models 失败: {}", e.getMessage());
|
||||
throw new BusinessException("无法加载模型列表:" + e.getMessage());
|
||||
} catch (Exception e) {
|
||||
log.warn("解析 /models 失败: {}", e.getMessage());
|
||||
throw new BusinessException("解析模型列表失败");
|
||||
}
|
||||
}
|
||||
|
||||
private List<AgentLlmProbedModelVO> parse(String body) throws Exception {
|
||||
JsonNode root = objectMapper.readTree(body);
|
||||
JsonNode data = root.get("data");
|
||||
if (data == null || !data.isArray()) {
|
||||
// 少数网关直接返回数组
|
||||
data = root.isArray() ? root : null;
|
||||
}
|
||||
if (data == null || !data.isArray()) {
|
||||
throw new BusinessException("模型列表格式无法识别");
|
||||
}
|
||||
List<AgentLlmProbedModelVO> out = new ArrayList<>();
|
||||
for (JsonNode node : data) {
|
||||
String id = text(node, "id");
|
||||
if (!StringUtils.hasText(id)) {
|
||||
continue;
|
||||
}
|
||||
AgentLlmProbedModelVO vo = new AgentLlmProbedModelVO();
|
||||
vo.setId(id);
|
||||
vo.setContextWindow(extractContextWindow(node));
|
||||
out.add(vo);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
private static Integer extractContextWindow(JsonNode node) {
|
||||
Integer n = intOrNull(node, "context_window");
|
||||
if (n != null) {
|
||||
return n;
|
||||
}
|
||||
n = intOrNull(node, "context_length");
|
||||
if (n != null) {
|
||||
return n;
|
||||
}
|
||||
n = intOrNull(node, "max_model_len");
|
||||
if (n != null) {
|
||||
return n;
|
||||
}
|
||||
n = intOrNull(node, "max_tokens");
|
||||
if (n != null && n >= 4096) {
|
||||
return n;
|
||||
}
|
||||
// 嵌套 meta
|
||||
JsonNode meta = node.get("meta");
|
||||
if (meta != null && meta.isObject()) {
|
||||
n = intOrNull(meta, "context_length");
|
||||
if (n != null) {
|
||||
return n;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
private static String text(JsonNode node, String field) {
|
||||
JsonNode v = node.get(field);
|
||||
return v == null || v.isNull() ? null : v.asText();
|
||||
}
|
||||
|
||||
private static Integer intOrNull(JsonNode node, String field) {
|
||||
JsonNode v = node.get(field);
|
||||
if (v == null || v.isNull()) {
|
||||
return null;
|
||||
}
|
||||
if (v.isNumber()) {
|
||||
int n = v.asInt();
|
||||
return n > 0 ? n : null;
|
||||
}
|
||||
if (v.isTextual()) {
|
||||
try {
|
||||
int n = Integer.parseInt(v.asText().trim());
|
||||
return n > 0 ? n : null;
|
||||
} catch (NumberFormatException e) {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
}
|
||||
+116
@@ -0,0 +1,116 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.agent.mcp.adapter.bi;
|
||||
|
||||
import top.xyquan.ecomdmbbackend.modules.agent.mcp.adapter.bi.model.BiKpiSlimVO;
|
||||
import top.xyquan.ecomdmbbackend.modules.agent.mcp.adapter.bi.model.BiProductOverviewSlimVO;
|
||||
import top.xyquan.ecomdmbbackend.modules.agent.mcp.adapter.bi.model.BiRankItemSlimVO;
|
||||
import top.xyquan.ecomdmbbackend.modules.agent.mcp.adapter.bi.model.BiShopOverviewSlimVO;
|
||||
import top.xyquan.ecomdmbbackend.modules.agent.mcp.adapter.bi.model.BiWorkbenchFinanceSlimVO;
|
||||
import top.xyquan.ecomdmbbackend.modules.bi.productoverview.model.vo.ProductOverviewVO;
|
||||
import top.xyquan.ecomdmbbackend.modules.bi.shopoverview.model.vo.ShopOverviewStatisticsVO;
|
||||
import top.xyquan.ecomdmbbackend.modules.bi.workbench.model.vo.WorkbenchFinanceSliceVO;
|
||||
import top.xyquan.ecomdmbbackend.modules.bi.workbench.model.vo.WorkbenchKpiItemVO;
|
||||
|
||||
import java.util.Collections;
|
||||
import java.util.List;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
/**
|
||||
* BI 胖 VO → Agent 瘦视图(防腐映射,不承载用例编排)。
|
||||
*/
|
||||
public final class BiMcpSlimMapper {
|
||||
|
||||
private BiMcpSlimMapper() {
|
||||
}
|
||||
|
||||
public static BiWorkbenchFinanceSlimVO toFinanceSlim(WorkbenchFinanceSliceVO full,
|
||||
String startDate,
|
||||
String endDate,
|
||||
Long shopId,
|
||||
String platformCode) {
|
||||
List<BiKpiSlimVO> kpis = full == null || full.getFinance() == null || full.getFinance().getKpis() == null
|
||||
? Collections.emptyList()
|
||||
: full.getFinance().getKpis().stream().map(BiMcpSlimMapper::toKpi).collect(Collectors.toList());
|
||||
return BiWorkbenchFinanceSlimVO.builder()
|
||||
.startDate(startDate)
|
||||
.endDate(endDate)
|
||||
.shopId(shopId)
|
||||
.platformCode(platformCode)
|
||||
.kpis(kpis)
|
||||
.build();
|
||||
}
|
||||
|
||||
public static BiShopOverviewSlimVO toShopSlim(ShopOverviewStatisticsVO full) {
|
||||
if (full == null) {
|
||||
return BiShopOverviewSlimVO.builder().build();
|
||||
}
|
||||
List<BiRankItemSlimVO> top10 = full.getProductSalesTop10() == null
|
||||
? Collections.emptyList()
|
||||
: full.getProductSalesTop10().stream()
|
||||
.map(i -> BiRankItemSlimVO.builder()
|
||||
.id(i.getProductId())
|
||||
.name(i.getProductName())
|
||||
.code(i.getProductCode())
|
||||
.orderCount(i.getOrderCount())
|
||||
.salesAmount(i.getSalesAmount())
|
||||
.build())
|
||||
.collect(Collectors.toList());
|
||||
return BiShopOverviewSlimVO.builder()
|
||||
.shopId(full.getShopId())
|
||||
.shopName(full.getShopName())
|
||||
.totalSalesAmount(full.getTotalSalesAmount())
|
||||
.totalOrderCount(full.getTotalOrderCount())
|
||||
.averageOrderValue(full.getAverageOrderValue())
|
||||
.totalPromotionFee(full.getTotalPromotionFee())
|
||||
.averageFeeRatio(full.getAverageFeeRatio())
|
||||
.totalNetProfitAfterTax(full.getTotalNetProfitAfterTax())
|
||||
.totalROI(full.getTotalROI())
|
||||
.monthOverMonthGrowth(full.getMonthOverMonthGrowth())
|
||||
.orderCountAchievementRate(full.getOrderCountAchievementRate())
|
||||
.salesAmountAchievementRate(full.getSalesAmountAchievementRate())
|
||||
.refundAmount(full.getRefundAmount())
|
||||
.productSalesTop10(top10)
|
||||
.build();
|
||||
}
|
||||
|
||||
public static BiProductOverviewSlimVO toProductSlim(ProductOverviewVO full) {
|
||||
if (full == null) {
|
||||
return BiProductOverviewSlimVO.builder().build();
|
||||
}
|
||||
List<BiRankItemSlimVO> top10 = full.getSpecSalesTop10() == null
|
||||
? Collections.emptyList()
|
||||
: full.getSpecSalesTop10().stream()
|
||||
.map(i -> BiRankItemSlimVO.builder()
|
||||
.id(i.getSkuId())
|
||||
.name(i.getSkuName())
|
||||
.code(i.getSkuCode())
|
||||
.orderCount(i.getOrderCount())
|
||||
.salesAmount(i.getSalesAmount())
|
||||
.build())
|
||||
.collect(Collectors.toList());
|
||||
return BiProductOverviewSlimVO.builder()
|
||||
.productId(full.getProductId())
|
||||
.productName(full.getProductName())
|
||||
.totalSalesAmount(full.getTotalSalesAmount())
|
||||
.totalOrderCount(full.getTotalOrderCount())
|
||||
.averageFeeRatio(full.getAverageFeeRatio())
|
||||
.totalNetProfitAfterTax(full.getTotalNetProfitAfterTax())
|
||||
.totalROI(full.getTotalROI())
|
||||
.monthOverMonthGrowth(full.getMonthOverMonthGrowth())
|
||||
.orderCountAchievementRate(full.getOrderCountAchievementRate())
|
||||
.salesAmountAchievementRate(full.getSalesAmountAchievementRate())
|
||||
.specSalesTop10(top10)
|
||||
.build();
|
||||
}
|
||||
|
||||
private static BiKpiSlimVO toKpi(WorkbenchKpiItemVO k) {
|
||||
return BiKpiSlimVO.builder()
|
||||
.label(k.getLabel())
|
||||
.value(k.getValue())
|
||||
.unit(k.getUnit())
|
||||
.changePct(k.getChangePct())
|
||||
.yoyChangePct(k.getYoyChangePct())
|
||||
.amountYuan(k.getAmountYuan())
|
||||
.sub(k.getSub())
|
||||
.build();
|
||||
}
|
||||
}
|
||||
+19
@@ -0,0 +1,19 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.agent.mcp.adapter.bi.model;
|
||||
|
||||
import lombok.Builder;
|
||||
import lombok.Data;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
|
||||
/** 工作台 KPI 瘦项(value 为原始数值,展示格式化由调用方负责)。 */
|
||||
@Data
|
||||
@Builder
|
||||
public class BiKpiSlimVO {
|
||||
private String label;
|
||||
private BigDecimal value;
|
||||
private String unit;
|
||||
private BigDecimal changePct;
|
||||
private BigDecimal yoyChangePct;
|
||||
private BigDecimal amountYuan;
|
||||
private String sub;
|
||||
}
|
||||
+24
@@ -0,0 +1,24 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.agent.mcp.adapter.bi.model;
|
||||
|
||||
import lombok.Builder;
|
||||
import lombok.Data;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.util.List;
|
||||
|
||||
/** 商品概览瘦视图(给 Agent)。 */
|
||||
@Data
|
||||
@Builder
|
||||
public class BiProductOverviewSlimVO {
|
||||
private Long productId;
|
||||
private String productName;
|
||||
private BigDecimal totalSalesAmount;
|
||||
private Integer totalOrderCount;
|
||||
private BigDecimal averageFeeRatio;
|
||||
private BigDecimal totalNetProfitAfterTax;
|
||||
private BigDecimal totalROI;
|
||||
private BigDecimal monthOverMonthGrowth;
|
||||
private BigDecimal orderCountAchievementRate;
|
||||
private BigDecimal salesAmountAchievementRate;
|
||||
private List<BiRankItemSlimVO> specSalesTop10;
|
||||
}
|
||||
+17
@@ -0,0 +1,17 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.agent.mcp.adapter.bi.model;
|
||||
|
||||
import lombok.Builder;
|
||||
import lombok.Data;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
|
||||
/** 排行瘦项(商品或规格)。 */
|
||||
@Data
|
||||
@Builder
|
||||
public class BiRankItemSlimVO {
|
||||
private Long id;
|
||||
private String name;
|
||||
private String code;
|
||||
private Integer orderCount;
|
||||
private BigDecimal salesAmount;
|
||||
}
|
||||
+27
@@ -0,0 +1,27 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.agent.mcp.adapter.bi.model;
|
||||
|
||||
import lombok.Builder;
|
||||
import lombok.Data;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.util.List;
|
||||
|
||||
/** 店铺概览瘦视图(给 Agent)。 */
|
||||
@Data
|
||||
@Builder
|
||||
public class BiShopOverviewSlimVO {
|
||||
private Long shopId;
|
||||
private String shopName;
|
||||
private BigDecimal totalSalesAmount;
|
||||
private Integer totalOrderCount;
|
||||
private BigDecimal averageOrderValue;
|
||||
private BigDecimal totalPromotionFee;
|
||||
private BigDecimal averageFeeRatio;
|
||||
private BigDecimal totalNetProfitAfterTax;
|
||||
private BigDecimal totalROI;
|
||||
private BigDecimal monthOverMonthGrowth;
|
||||
private BigDecimal orderCountAchievementRate;
|
||||
private BigDecimal salesAmountAchievementRate;
|
||||
private BigDecimal refundAmount;
|
||||
private List<BiRankItemSlimVO> productSalesTop10;
|
||||
}
|
||||
+17
@@ -0,0 +1,17 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.agent.mcp.adapter.bi.model;
|
||||
|
||||
import lombok.Builder;
|
||||
import lombok.Data;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/** 工作台经营概览瘦视图(给 Agent)。 */
|
||||
@Data
|
||||
@Builder
|
||||
public class BiWorkbenchFinanceSlimVO {
|
||||
private String startDate;
|
||||
private String endDate;
|
||||
private Long shopId;
|
||||
private String platformCode;
|
||||
private List<BiKpiSlimVO> kpis;
|
||||
}
|
||||
+212
@@ -0,0 +1,212 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.agent.mcp.adapter.catalog;
|
||||
|
||||
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
|
||||
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
|
||||
import org.springframework.stereotype.Component;
|
||||
import top.xyquan.ecomdmbbackend.modules.agent.mcp.adapter.catalog.model.CatalogProductHitVO;
|
||||
import top.xyquan.ecomdmbbackend.modules.agent.mcp.adapter.catalog.model.CatalogShopHitVO;
|
||||
import top.xyquan.ecomdmbbackend.modules.agent.mcp.adapter.catalog.model.CatalogSkuDetailVO;
|
||||
import top.xyquan.ecomdmbbackend.modules.agent.mcp.adapter.catalog.model.CatalogSkuHitVO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.platform.model.enums.PlatformCode;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.product.mapper.ProductMapper;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.product.model.po.ProductPO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.product.sku.mapper.ProductSkuMapper;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.product.sku.model.po.ProductSkuPO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.shop.mapper.ShopMapper;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.shop.model.po.ShopPO;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Comparator;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Map;
|
||||
import java.util.function.Function;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
/**
|
||||
* 租户内按名称/编码检索店铺、商品、SKU,只返回瘦字段。
|
||||
* 不走分页列表接口,避免把规格、成本、渠道授权塞进模型上下文。
|
||||
*/
|
||||
@Component
|
||||
public class CatalogLookupAdapter {
|
||||
|
||||
static final int FETCH = 40;
|
||||
static final int LIMIT = 8;
|
||||
|
||||
private final ShopMapper shopMapper;
|
||||
private final ProductMapper productMapper;
|
||||
private final ProductSkuMapper productSkuMapper;
|
||||
|
||||
public CatalogLookupAdapter(ShopMapper shopMapper,
|
||||
ProductMapper productMapper,
|
||||
ProductSkuMapper productSkuMapper) {
|
||||
this.shopMapper = shopMapper;
|
||||
this.productMapper = productMapper;
|
||||
this.productSkuMapper = productSkuMapper;
|
||||
}
|
||||
|
||||
public Slice<CatalogShopHitVO> searchShops(Long companyId, String keyword) {
|
||||
LambdaQueryWrapper<ShopPO> wrapper = new LambdaQueryWrapper<>();
|
||||
wrapper.eq(ShopPO::getCompanyId, companyId)
|
||||
.like(ShopPO::getName, keyword);
|
||||
List<ShopPO> rows = shopMapper.selectPage(new Page<>(1, FETCH, false), wrapper).getRecords();
|
||||
rows.sort(Comparator.comparingInt((ShopPO s) -> score(keyword, s.getName()))
|
||||
.thenComparing(ShopPO::getId, Comparator.nullsLast(Comparator.reverseOrder())));
|
||||
List<CatalogShopHitVO> hits = new ArrayList<>();
|
||||
for (ShopPO shop : head(rows)) {
|
||||
String code = shop.getPlatformCode();
|
||||
hits.add(CatalogShopHitVO.builder()
|
||||
.id(shop.getId())
|
||||
.name(shop.getName())
|
||||
.platformCode(code)
|
||||
.platformName(PlatformCode.ofCode(code).map(PlatformCode::getLabel).orElse(code))
|
||||
.build());
|
||||
}
|
||||
return new Slice<>(hits, rows.size() >= FETCH);
|
||||
}
|
||||
|
||||
public Slice<CatalogProductHitVO> searchProducts(Long companyId, String keyword) {
|
||||
LambdaQueryWrapper<ProductPO> wrapper = new LambdaQueryWrapper<>();
|
||||
wrapper.eq(ProductPO::getCompanyId, companyId)
|
||||
.and(w -> w.like(ProductPO::getName, keyword).or().like(ProductPO::getProductCode, keyword));
|
||||
List<ProductPO> rows = productMapper.selectPage(new Page<>(1, FETCH, false), wrapper).getRecords();
|
||||
rows.sort(Comparator.comparingInt((ProductPO p) -> score(keyword, p.getName(), p.getProductCode()))
|
||||
.thenComparing(ProductPO::getId, Comparator.nullsLast(Comparator.reverseOrder())));
|
||||
List<CatalogProductHitVO> hits = new ArrayList<>();
|
||||
for (ProductPO product : head(rows)) {
|
||||
hits.add(CatalogProductHitVO.builder()
|
||||
.id(product.getId())
|
||||
.name(product.getName())
|
||||
.productCode(product.getProductCode())
|
||||
.build());
|
||||
}
|
||||
return new Slice<>(hits, rows.size() >= FETCH);
|
||||
}
|
||||
|
||||
public Slice<CatalogSkuHitVO> searchSkus(Long companyId, String keyword) {
|
||||
List<Long> productIds = matchingProductIds(companyId, keyword);
|
||||
LambdaQueryWrapper<ProductSkuPO> wrapper = new LambdaQueryWrapper<>();
|
||||
wrapper.eq(ProductSkuPO::getCompanyId, companyId)
|
||||
.and(w -> {
|
||||
w.like(ProductSkuPO::getName, keyword)
|
||||
.or().like(ProductSkuPO::getSkuCode, keyword)
|
||||
.or().like(ProductSkuPO::getBarcode, keyword);
|
||||
if (!productIds.isEmpty()) {
|
||||
w.or().in(ProductSkuPO::getProductId, productIds);
|
||||
}
|
||||
});
|
||||
List<ProductSkuPO> rows = productSkuMapper.selectPage(new Page<>(1, FETCH, false), wrapper).getRecords();
|
||||
Map<Long, ProductPO> products = loadProducts(companyId, rows);
|
||||
rows.sort(Comparator.comparingInt((ProductSkuPO sku) -> scoreSku(keyword, sku, products.get(sku.getProductId())))
|
||||
.thenComparing(ProductSkuPO::getId, Comparator.nullsLast(Comparator.reverseOrder())));
|
||||
List<CatalogSkuHitVO> hits = new ArrayList<>();
|
||||
for (ProductSkuPO sku : head(rows)) {
|
||||
ProductPO product = products.get(sku.getProductId());
|
||||
hits.add(CatalogSkuHitVO.builder()
|
||||
.id(sku.getId())
|
||||
.name(sku.getName())
|
||||
.skuCode(sku.getSkuCode())
|
||||
.barcode(sku.getBarcode())
|
||||
.productId(sku.getProductId())
|
||||
.productName(product == null ? null : product.getName())
|
||||
.productCode(product == null ? null : product.getProductCode())
|
||||
.build());
|
||||
}
|
||||
return new Slice<>(hits, rows.size() >= FETCH);
|
||||
}
|
||||
|
||||
/** 按 SKU 编码精准取详情;未命中返回 null。 */
|
||||
public CatalogSkuDetailVO getSkuByCode(Long companyId, String skuCode) {
|
||||
if (companyId == null || skuCode == null || skuCode.isBlank()) {
|
||||
return null;
|
||||
}
|
||||
LambdaQueryWrapper<ProductSkuPO> wrapper = new LambdaQueryWrapper<>();
|
||||
wrapper.eq(ProductSkuPO::getCompanyId, companyId)
|
||||
.eq(ProductSkuPO::getSkuCode, skuCode.trim())
|
||||
.last("LIMIT 1");
|
||||
ProductSkuPO sku = productSkuMapper.selectOne(wrapper);
|
||||
if (sku == null) {
|
||||
return null;
|
||||
}
|
||||
ProductPO product = sku.getProductId() == null ? null : productMapper.selectById(sku.getProductId());
|
||||
if (product != null && !companyId.equals(product.getCompanyId())) {
|
||||
product = null;
|
||||
}
|
||||
return CatalogSkuDetailVO.builder()
|
||||
.id(sku.getId())
|
||||
.skuCode(sku.getSkuCode())
|
||||
.name(sku.getName())
|
||||
.barcode(sku.getBarcode())
|
||||
.attrs(sku.getAttrs())
|
||||
.specCombinationKey(sku.getSpecCombinationKey())
|
||||
.imageUrl(sku.getImageUrl())
|
||||
.status(sku.getStatus())
|
||||
.productId(sku.getProductId())
|
||||
.productName(product == null ? null : product.getName())
|
||||
.productCode(product == null ? null : product.getProductCode())
|
||||
.hint("已命中内部 SKU。用 name/attrs/specCombinationKey 写规格和重量,不要再向用户要这些值;本结果不含售价。不要复述数字 id。")
|
||||
.build();
|
||||
}
|
||||
|
||||
private List<Long> matchingProductIds(Long companyId, String keyword) {
|
||||
LambdaQueryWrapper<ProductPO> wrapper = new LambdaQueryWrapper<>();
|
||||
wrapper.eq(ProductPO::getCompanyId, companyId)
|
||||
.and(w -> w.like(ProductPO::getName, keyword).or().like(ProductPO::getProductCode, keyword))
|
||||
.select(ProductPO::getId);
|
||||
return productMapper.selectPage(new Page<>(1, FETCH, false), wrapper).getRecords().stream()
|
||||
.map(ProductPO::getId)
|
||||
.toList();
|
||||
}
|
||||
|
||||
private Map<Long, ProductPO> loadProducts(Long companyId, List<ProductSkuPO> skus) {
|
||||
List<Long> ids = skus.stream()
|
||||
.map(ProductSkuPO::getProductId)
|
||||
.filter(id -> id != null)
|
||||
.distinct()
|
||||
.toList();
|
||||
if (ids.isEmpty()) {
|
||||
return Map.of();
|
||||
}
|
||||
return productMapper.selectByIds(ids).stream()
|
||||
.filter(p -> companyId.equals(p.getCompanyId()))
|
||||
.collect(Collectors.toMap(ProductPO::getId, Function.identity(), (a, b) -> a));
|
||||
}
|
||||
|
||||
private static <T> List<T> head(List<T> rows) {
|
||||
if (rows.size() <= LIMIT) {
|
||||
return rows;
|
||||
}
|
||||
return rows.subList(0, LIMIT);
|
||||
}
|
||||
|
||||
private static int scoreSku(String keyword, ProductSkuPO sku, ProductPO product) {
|
||||
if (product == null) {
|
||||
return score(keyword, sku.getName(), sku.getSkuCode(), sku.getBarcode());
|
||||
}
|
||||
return score(keyword, sku.getName(), sku.getSkuCode(), sku.getBarcode(), product.getName(), product.getProductCode());
|
||||
}
|
||||
|
||||
/** 0 全等,1 前缀,2 包含,3 其余。越小越靠前。 */
|
||||
static int score(String keyword, String... fields) {
|
||||
String key = keyword.toLowerCase(Locale.ROOT);
|
||||
int best = 3;
|
||||
for (String field : fields) {
|
||||
if (field == null || field.isBlank()) {
|
||||
continue;
|
||||
}
|
||||
String value = field.trim().toLowerCase(Locale.ROOT);
|
||||
if (value.equals(key)) {
|
||||
return 0;
|
||||
}
|
||||
if (value.startsWith(key)) {
|
||||
best = Math.min(best, 1);
|
||||
} else if (value.contains(key)) {
|
||||
best = Math.min(best, 2);
|
||||
}
|
||||
}
|
||||
return best;
|
||||
}
|
||||
|
||||
public record Slice<T>(List<T> items, boolean truncated) {
|
||||
}
|
||||
}
|
||||
+13
@@ -0,0 +1,13 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.agent.mcp.adapter.catalog.model;
|
||||
|
||||
import lombok.Builder;
|
||||
import lombok.Data;
|
||||
|
||||
/** 商品检索瘦项。 */
|
||||
@Data
|
||||
@Builder
|
||||
public class CatalogProductHitVO {
|
||||
private Long id;
|
||||
private String name;
|
||||
private String productCode;
|
||||
}
|
||||
+19
@@ -0,0 +1,19 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.agent.mcp.adapter.catalog.model;
|
||||
|
||||
import lombok.Builder;
|
||||
import lombok.Data;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/** catalog_search 返回体。hint 告诉模型下一步怎么用 id,不要向用户索要。 */
|
||||
@Data
|
||||
@Builder
|
||||
public class CatalogSearchSlimVO {
|
||||
private String keyword;
|
||||
private String kind;
|
||||
private boolean truncated;
|
||||
private String hint;
|
||||
private List<CatalogShopHitVO> shops;
|
||||
private List<CatalogProductHitVO> products;
|
||||
private List<CatalogSkuHitVO> skus;
|
||||
}
|
||||
+14
@@ -0,0 +1,14 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.agent.mcp.adapter.catalog.model;
|
||||
|
||||
import lombok.Builder;
|
||||
import lombok.Data;
|
||||
|
||||
/** 店铺检索瘦项。店铺无独立编码,只回名称与平台。 */
|
||||
@Data
|
||||
@Builder
|
||||
public class CatalogShopHitVO {
|
||||
private Long id;
|
||||
private String name;
|
||||
private String platformCode;
|
||||
private String platformName;
|
||||
}
|
||||
+22
@@ -0,0 +1,22 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.agent.mcp.adapter.catalog.model;
|
||||
|
||||
import lombok.Builder;
|
||||
import lombok.Data;
|
||||
|
||||
/** 内部 SKU 详情瘦项,供发布场景生成标题/规格。 */
|
||||
@Data
|
||||
@Builder
|
||||
public class CatalogSkuDetailVO {
|
||||
private Long id;
|
||||
private String skuCode;
|
||||
private String name;
|
||||
private String barcode;
|
||||
private String attrs;
|
||||
private String specCombinationKey;
|
||||
private String imageUrl;
|
||||
private Integer status;
|
||||
private Long productId;
|
||||
private String productName;
|
||||
private String productCode;
|
||||
private String hint;
|
||||
}
|
||||
+17
@@ -0,0 +1,17 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.agent.mcp.adapter.catalog.model;
|
||||
|
||||
import lombok.Builder;
|
||||
import lombok.Data;
|
||||
|
||||
/** SKU 检索瘦项,带所属商品便于消歧。 */
|
||||
@Data
|
||||
@Builder
|
||||
public class CatalogSkuHitVO {
|
||||
private Long id;
|
||||
private String name;
|
||||
private String skuCode;
|
||||
private String barcode;
|
||||
private Long productId;
|
||||
private String productName;
|
||||
private String productCode;
|
||||
}
|
||||
+36
@@ -0,0 +1,36 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.agent.mcp.adapter.common;
|
||||
|
||||
import top.xyquan.ecomdmbbackend.common.exception.BusinessException;
|
||||
|
||||
import java.time.LocalDate;
|
||||
import java.time.format.DateTimeParseException;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* MCP 入参日期解析(yyyy-MM-dd),与具体业务域无关。
|
||||
*/
|
||||
public final class McpDateSupport {
|
||||
|
||||
private McpDateSupport() {
|
||||
}
|
||||
|
||||
public static LocalDate parseDate(String raw, String fieldName) {
|
||||
if (raw == null || raw.isBlank()) {
|
||||
throw new BusinessException(fieldName + " 不能为空");
|
||||
}
|
||||
try {
|
||||
return LocalDate.parse(raw.trim());
|
||||
} catch (DateTimeParseException e) {
|
||||
throw new BusinessException(fieldName + " 格式须为 yyyy-MM-dd");
|
||||
}
|
||||
}
|
||||
|
||||
public static List<LocalDate> toDateRange(String startDate, String endDate) {
|
||||
LocalDate start = parseDate(startDate, "startDate");
|
||||
LocalDate end = parseDate(endDate, "endDate");
|
||||
if (end.isBefore(start)) {
|
||||
throw new BusinessException("endDate 不能早于 startDate");
|
||||
}
|
||||
return List.of(start, end);
|
||||
}
|
||||
}
|
||||
+190
@@ -0,0 +1,190 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.agent.mcp.adapter.pdd;
|
||||
|
||||
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
|
||||
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
|
||||
import org.springframework.stereotype.Component;
|
||||
import top.xyquan.ecomdmbbackend.modules.agent.mcp.adapter.pdd.model.PddGoodsDetailSlimVO;
|
||||
import top.xyquan.ecomdmbbackend.modules.agent.mcp.adapter.pdd.model.PddGoodsHitVO;
|
||||
import top.xyquan.ecomdmbbackend.modules.agent.mcp.adapter.pdd.model.PddGoodsSkuSlimVO;
|
||||
import top.xyquan.ecomdmbbackend.modules.channel.pdd.goods.mapper.PddGoodsMapper;
|
||||
import top.xyquan.ecomdmbbackend.modules.channel.pdd.goods.mapper.PddGoodsSkuMapper;
|
||||
import top.xyquan.ecomdmbbackend.modules.channel.pdd.goods.model.po.PddGoodsPO;
|
||||
import top.xyquan.ecomdmbbackend.modules.channel.pdd.goods.model.po.PddGoodsSkuPO;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.LinkedHashSet;
|
||||
import java.util.List;
|
||||
import java.util.Locale;
|
||||
import java.util.Objects;
|
||||
import java.util.Set;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
/**
|
||||
* 租户内检索已同步的拼多多渠道商品(不调 POP 实时接口)。
|
||||
*/
|
||||
@Component
|
||||
public class PddGoodsLookupAdapter {
|
||||
|
||||
static final int FETCH = 40;
|
||||
static final int LIMIT = 8;
|
||||
static final int SKU_SAMPLE = 6;
|
||||
|
||||
private final PddGoodsMapper pddGoodsMapper;
|
||||
private final PddGoodsSkuMapper pddGoodsSkuMapper;
|
||||
|
||||
public PddGoodsLookupAdapter(PddGoodsMapper pddGoodsMapper, PddGoodsSkuMapper pddGoodsSkuMapper) {
|
||||
this.pddGoodsMapper = pddGoodsMapper;
|
||||
this.pddGoodsSkuMapper = pddGoodsSkuMapper;
|
||||
}
|
||||
|
||||
public Slice<PddGoodsHitVO> search(Long companyId, String keyword, Long shopId) {
|
||||
String kw = keyword.trim();
|
||||
Set<Long> goodsRowIds = new LinkedHashSet<>();
|
||||
|
||||
LambdaQueryWrapper<PddGoodsPO> byName = baseGoodsQuery(companyId, shopId);
|
||||
byName.and(w -> w.like(PddGoodsPO::getGoodsName, kw).or().eq(PddGoodsPO::getGoodsId, kw));
|
||||
for (PddGoodsPO g : pddGoodsMapper.selectPage(new Page<>(1, FETCH, false), byName).getRecords()) {
|
||||
goodsRowIds.add(g.getId());
|
||||
}
|
||||
|
||||
LambdaQueryWrapper<PddGoodsSkuPO> byOuter = new LambdaQueryWrapper<>();
|
||||
byOuter.eq(PddGoodsSkuPO::getCompanyId, companyId)
|
||||
.and(w -> w.eq(PddGoodsSkuPO::getOuterId, kw)
|
||||
.or().eq(PddGoodsSkuPO::getOuterGoodsId, kw)
|
||||
.or().like(PddGoodsSkuPO::getOuterId, kw)
|
||||
.or().like(PddGoodsSkuPO::getOuterGoodsId, kw));
|
||||
List<PddGoodsSkuPO> skuHits = pddGoodsSkuMapper
|
||||
.selectPage(new Page<>(1, FETCH, false), byOuter)
|
||||
.getRecords();
|
||||
for (PddGoodsSkuPO sku : skuHits) {
|
||||
if (sku.getGoodsRowId() != null) {
|
||||
goodsRowIds.add(sku.getGoodsRowId());
|
||||
}
|
||||
}
|
||||
|
||||
if (goodsRowIds.isEmpty()) {
|
||||
return new Slice<>(List.of(), false);
|
||||
}
|
||||
|
||||
List<PddGoodsPO> goods = pddGoodsMapper.selectByIds(goodsRowIds).stream()
|
||||
.filter(g -> companyId.equals(g.getCompanyId()))
|
||||
.filter(g -> !Integer.valueOf(1).equals(g.getIsPlatformDeleted()))
|
||||
.filter(g -> shopId == null || shopId.equals(g.getShopId()))
|
||||
.sorted((a, b) -> Integer.compare(score(kw, a.getGoodsName(), a.getGoodsId()),
|
||||
score(kw, b.getGoodsName(), b.getGoodsId())))
|
||||
.toList();
|
||||
boolean truncated = goods.size() > LIMIT || skuHits.size() >= FETCH;
|
||||
List<PddGoodsHitVO> hits = new ArrayList<>();
|
||||
for (PddGoodsPO g : head(goods)) {
|
||||
List<PddGoodsSkuPO> skus = listSkus(companyId, g.getId());
|
||||
hits.add(PddGoodsHitVO.builder()
|
||||
.id(g.getId())
|
||||
.goodsId(g.getGoodsId())
|
||||
.goodsName(g.getGoodsName())
|
||||
.shopId(g.getShopId())
|
||||
.mallId(g.getMallId())
|
||||
.isOnsale(g.getIsOnsale())
|
||||
.sampleOuterIds(sample(skus.stream().map(PddGoodsSkuPO::getOuterId).toList()))
|
||||
.sampleOuterGoodsIds(sample(skus.stream().map(PddGoodsSkuPO::getOuterGoodsId).toList()))
|
||||
.build());
|
||||
}
|
||||
return new Slice<>(hits, truncated);
|
||||
}
|
||||
|
||||
public PddGoodsDetailSlimVO detail(Long companyId, Long goodsRowId, String goodsId, Long shopId) {
|
||||
PddGoodsPO goods = null;
|
||||
if (goodsRowId != null) {
|
||||
goods = pddGoodsMapper.selectById(goodsRowId);
|
||||
} else if (goodsId != null && !goodsId.isBlank()) {
|
||||
LambdaQueryWrapper<PddGoodsPO> w = baseGoodsQuery(companyId, shopId);
|
||||
w.eq(PddGoodsPO::getGoodsId, goodsId.trim()).last("LIMIT 1");
|
||||
goods = pddGoodsMapper.selectOne(w);
|
||||
}
|
||||
if (goods == null || !companyId.equals(goods.getCompanyId())
|
||||
|| Integer.valueOf(1).equals(goods.getIsPlatformDeleted())) {
|
||||
return null;
|
||||
}
|
||||
List<PddGoodsSkuSlimVO> skus = listSkus(companyId, goods.getId()).stream()
|
||||
.map(s -> PddGoodsSkuSlimVO.builder()
|
||||
.skuId(s.getSkuId())
|
||||
.spec(s.getSpec())
|
||||
.specDetails(s.getSpecDetails())
|
||||
.outerGoodsId(s.getOuterGoodsId())
|
||||
.outerId(s.getOuterId())
|
||||
.build())
|
||||
.toList();
|
||||
return PddGoodsDetailSlimVO.builder()
|
||||
.id(goods.getId())
|
||||
.goodsId(goods.getGoodsId())
|
||||
.goodsName(goods.getGoodsName())
|
||||
.shopId(goods.getShopId())
|
||||
.mallId(goods.getMallId())
|
||||
.isOnsale(goods.getIsOnsale())
|
||||
.isMoreSku(goods.getIsMoreSku())
|
||||
.skus(skus)
|
||||
.hint("可模仿本商品的标题与规格结构(spec/specDetails);写回表单时只改规格轴,由页面重建 SKU 行。")
|
||||
.build();
|
||||
}
|
||||
|
||||
private List<PddGoodsSkuPO> listSkus(Long companyId, Long goodsRowId) {
|
||||
if (goodsRowId == null) {
|
||||
return List.of();
|
||||
}
|
||||
LambdaQueryWrapper<PddGoodsSkuPO> w = new LambdaQueryWrapper<>();
|
||||
w.eq(PddGoodsSkuPO::getCompanyId, companyId)
|
||||
.eq(PddGoodsSkuPO::getGoodsRowId, goodsRowId)
|
||||
.last("LIMIT 80");
|
||||
return pddGoodsSkuMapper.selectList(w);
|
||||
}
|
||||
|
||||
private static LambdaQueryWrapper<PddGoodsPO> baseGoodsQuery(Long companyId, Long shopId) {
|
||||
LambdaQueryWrapper<PddGoodsPO> w = new LambdaQueryWrapper<>();
|
||||
w.eq(PddGoodsPO::getCompanyId, companyId)
|
||||
.and(q -> q.isNull(PddGoodsPO::getIsPlatformDeleted)
|
||||
.or().ne(PddGoodsPO::getIsPlatformDeleted, 1));
|
||||
if (shopId != null) {
|
||||
w.eq(PddGoodsPO::getShopId, shopId);
|
||||
}
|
||||
return w;
|
||||
}
|
||||
|
||||
private static List<String> sample(List<String> values) {
|
||||
return values.stream()
|
||||
.filter(Objects::nonNull)
|
||||
.map(String::trim)
|
||||
.filter(s -> !s.isEmpty())
|
||||
.distinct()
|
||||
.limit(SKU_SAMPLE)
|
||||
.collect(Collectors.toList());
|
||||
}
|
||||
|
||||
private static <T> List<T> head(List<T> rows) {
|
||||
if (rows.size() <= LIMIT) {
|
||||
return rows;
|
||||
}
|
||||
return rows.subList(0, LIMIT);
|
||||
}
|
||||
|
||||
static int score(String keyword, String... fields) {
|
||||
String key = keyword.toLowerCase(Locale.ROOT);
|
||||
int best = 3;
|
||||
for (String field : fields) {
|
||||
if (field == null || field.isBlank()) {
|
||||
continue;
|
||||
}
|
||||
String value = field.trim().toLowerCase(Locale.ROOT);
|
||||
if (value.equals(key)) {
|
||||
return 0;
|
||||
}
|
||||
if (value.startsWith(key)) {
|
||||
best = Math.min(best, 1);
|
||||
} else if (value.contains(key)) {
|
||||
best = Math.min(best, 2);
|
||||
}
|
||||
}
|
||||
return best;
|
||||
}
|
||||
|
||||
public record Slice<T>(List<T> items, boolean truncated) {
|
||||
}
|
||||
}
|
||||
+21
@@ -0,0 +1,21 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.agent.mcp.adapter.pdd.model;
|
||||
|
||||
import lombok.Builder;
|
||||
import lombok.Data;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/** 渠道拼多多商品瘦详情。 */
|
||||
@Data
|
||||
@Builder
|
||||
public class PddGoodsDetailSlimVO {
|
||||
private Long id;
|
||||
private String goodsId;
|
||||
private String goodsName;
|
||||
private Long shopId;
|
||||
private Long mallId;
|
||||
private Integer isOnsale;
|
||||
private Integer isMoreSku;
|
||||
private String hint;
|
||||
private List<PddGoodsSkuSlimVO> skus;
|
||||
}
|
||||
+20
@@ -0,0 +1,20 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.agent.mcp.adapter.pdd.model;
|
||||
|
||||
import lombok.Builder;
|
||||
import lombok.Data;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/** 渠道拼多多商品检索命中。 */
|
||||
@Data
|
||||
@Builder
|
||||
public class PddGoodsHitVO {
|
||||
private Long id;
|
||||
private String goodsId;
|
||||
private String goodsName;
|
||||
private Long shopId;
|
||||
private Long mallId;
|
||||
private Integer isOnsale;
|
||||
private List<String> sampleOuterIds;
|
||||
private List<String> sampleOuterGoodsIds;
|
||||
}
|
||||
+16
@@ -0,0 +1,16 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.agent.mcp.adapter.pdd.model;
|
||||
|
||||
import lombok.Builder;
|
||||
import lombok.Data;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/** pdd_goods_search 返回体。 */
|
||||
@Data
|
||||
@Builder
|
||||
public class PddGoodsSearchSlimVO {
|
||||
private String keyword;
|
||||
private boolean truncated;
|
||||
private String hint;
|
||||
private List<PddGoodsHitVO> items;
|
||||
}
|
||||
+15
@@ -0,0 +1,15 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.agent.mcp.adapter.pdd.model;
|
||||
|
||||
import lombok.Builder;
|
||||
import lombok.Data;
|
||||
|
||||
/** 渠道 SKU 瘦项。 */
|
||||
@Data
|
||||
@Builder
|
||||
public class PddGoodsSkuSlimVO {
|
||||
private String skuId;
|
||||
private String spec;
|
||||
private String specDetails;
|
||||
private String outerGoodsId;
|
||||
private String outerId;
|
||||
}
|
||||
+92
@@ -0,0 +1,92 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.agent.mcp.application;
|
||||
|
||||
import org.springframework.stereotype.Service;
|
||||
import top.xyquan.ecomdmbbackend.modules.agent.mcp.adapter.bi.BiMcpSlimMapper;
|
||||
import top.xyquan.ecomdmbbackend.modules.agent.mcp.adapter.bi.model.BiProductOverviewSlimVO;
|
||||
import top.xyquan.ecomdmbbackend.modules.agent.mcp.adapter.bi.model.BiShopOverviewSlimVO;
|
||||
import top.xyquan.ecomdmbbackend.modules.agent.mcp.adapter.bi.model.BiWorkbenchFinanceSlimVO;
|
||||
import top.xyquan.ecomdmbbackend.modules.agent.mcp.adapter.common.McpDateSupport;
|
||||
import top.xyquan.ecomdmbbackend.modules.bi.productoverview.model.dto.ProductOverviewQueryDTO;
|
||||
import top.xyquan.ecomdmbbackend.modules.bi.productoverview.service.BiProductOverviewService;
|
||||
import top.xyquan.ecomdmbbackend.modules.bi.shopoverview.model.dto.ShopOverviewQueryDTO;
|
||||
import top.xyquan.ecomdmbbackend.modules.bi.shopoverview.service.BiShopOverviewService;
|
||||
import top.xyquan.ecomdmbbackend.modules.bi.workbench.model.dto.WorkbenchQueryDTO;
|
||||
import top.xyquan.ecomdmbbackend.modules.bi.workbench.service.BiWorkbenchService;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.time.LocalDate;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* BI MCP 用例编排:组装查询、调用 BI Service、裁剪为瘦视图。
|
||||
*/
|
||||
@Service
|
||||
public class BiMcpFacade {
|
||||
|
||||
private final BiWorkbenchService biWorkbenchService;
|
||||
private final BiShopOverviewService biShopOverviewService;
|
||||
private final BiProductOverviewService biProductOverviewService;
|
||||
|
||||
public BiMcpFacade(BiWorkbenchService biWorkbenchService,
|
||||
BiShopOverviewService biShopOverviewService,
|
||||
BiProductOverviewService biProductOverviewService) {
|
||||
this.biWorkbenchService = biWorkbenchService;
|
||||
this.biShopOverviewService = biShopOverviewService;
|
||||
this.biProductOverviewService = biProductOverviewService;
|
||||
}
|
||||
|
||||
public BiWorkbenchFinanceSlimVO workbenchFinance(String startDate,
|
||||
String endDate,
|
||||
String platformCode,
|
||||
Long shopId,
|
||||
BigDecimal taxRate) {
|
||||
List<LocalDate> range = McpDateSupport.toDateRange(startDate, endDate);
|
||||
WorkbenchQueryDTO query = new WorkbenchQueryDTO();
|
||||
query.setDateRange(range);
|
||||
query.setPlatformCode(blankToNull(platformCode));
|
||||
query.setShopId(shopId);
|
||||
if (taxRate != null) {
|
||||
query.setTaxRate(taxRate);
|
||||
}
|
||||
return BiMcpSlimMapper.toFinanceSlim(
|
||||
biWorkbenchService.financeSlice(query),
|
||||
range.get(0).toString(),
|
||||
range.get(range.size() - 1).toString(),
|
||||
shopId,
|
||||
query.getPlatformCode());
|
||||
}
|
||||
|
||||
public BiShopOverviewSlimVO shopOverview(Long shopId,
|
||||
String startDate,
|
||||
String endDate,
|
||||
BigDecimal taxRate) {
|
||||
ShopOverviewQueryDTO query = new ShopOverviewQueryDTO();
|
||||
query.setShopId(shopId);
|
||||
query.setDateRange(McpDateSupport.toDateRange(startDate, endDate));
|
||||
if (taxRate != null) {
|
||||
query.setTaxRate(taxRate);
|
||||
}
|
||||
return BiMcpSlimMapper.toShopSlim(biShopOverviewService.getShopOverview(query));
|
||||
}
|
||||
|
||||
public BiProductOverviewSlimVO productOverview(Long productId,
|
||||
String startDate,
|
||||
String endDate,
|
||||
Long shopId,
|
||||
BigDecimal taxRate) {
|
||||
ProductOverviewQueryDTO query = new ProductOverviewQueryDTO();
|
||||
query.setProductId(productId);
|
||||
List<LocalDate> range = McpDateSupport.toDateRange(startDate, endDate);
|
||||
query.setStartDate(range.get(0));
|
||||
query.setEndDate(range.get(range.size() - 1));
|
||||
query.setShopId(shopId);
|
||||
if (taxRate != null) {
|
||||
query.setTaxRate(taxRate);
|
||||
}
|
||||
return BiMcpSlimMapper.toProductSlim(biProductOverviewService.getProductOverview(query));
|
||||
}
|
||||
|
||||
private static String blankToNull(String value) {
|
||||
return value == null || value.isBlank() ? null : value.trim();
|
||||
}
|
||||
}
|
||||
+119
@@ -0,0 +1,119 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.agent.mcp.application;
|
||||
|
||||
import org.springframework.stereotype.Service;
|
||||
import top.xyquan.ecomdmbbackend.modules.agent.mcp.adapter.catalog.CatalogLookupAdapter;
|
||||
import top.xyquan.ecomdmbbackend.modules.agent.mcp.adapter.catalog.CatalogLookupAdapter.Slice;
|
||||
import top.xyquan.ecomdmbbackend.modules.agent.mcp.adapter.catalog.model.CatalogProductHitVO;
|
||||
import top.xyquan.ecomdmbbackend.modules.agent.mcp.adapter.catalog.model.CatalogSearchSlimVO;
|
||||
import top.xyquan.ecomdmbbackend.modules.agent.mcp.adapter.catalog.model.CatalogShopHitVO;
|
||||
import top.xyquan.ecomdmbbackend.modules.agent.mcp.adapter.catalog.model.CatalogSkuDetailVO;
|
||||
import top.xyquan.ecomdmbbackend.modules.agent.mcp.adapter.catalog.model.CatalogSkuHitVO;
|
||||
import top.xyquan.ecomdmbbackend.utils.CurrentUserContext;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* 目录检索用例:限定当前 MCP 租户,并把命中数写成给模型看的 hint。
|
||||
*/
|
||||
@Service
|
||||
public class CatalogMcpFacade {
|
||||
|
||||
private final CatalogLookupAdapter catalogLookupAdapter;
|
||||
private final CurrentUserContext currentUserContext;
|
||||
|
||||
public CatalogMcpFacade(CatalogLookupAdapter catalogLookupAdapter,
|
||||
CurrentUserContext currentUserContext) {
|
||||
this.catalogLookupAdapter = catalogLookupAdapter;
|
||||
this.currentUserContext = currentUserContext;
|
||||
}
|
||||
|
||||
public CatalogSearchSlimVO search(String keyword, String kind) {
|
||||
String kw = keyword == null ? "" : keyword.trim();
|
||||
String normalized = normalizeKind(kind);
|
||||
if (kw.isEmpty()) {
|
||||
return result(kw, normalized, false, List.of(), List.of(), List.of(),
|
||||
"keyword 不能为空。用店铺名、商品名、商品编码或 SKU 编码搜索,不要向用户要 ID。");
|
||||
}
|
||||
if (kw.length() > 64) {
|
||||
kw = kw.substring(0, 64);
|
||||
}
|
||||
Long companyId = currentUserContext.getCurrentCompanyId();
|
||||
Slice<CatalogShopHitVO> shops = want(normalized, "shop")
|
||||
? catalogLookupAdapter.searchShops(companyId, kw)
|
||||
: new Slice<>(List.of(), false);
|
||||
Slice<CatalogProductHitVO> products = want(normalized, "product")
|
||||
? catalogLookupAdapter.searchProducts(companyId, kw)
|
||||
: new Slice<>(List.of(), false);
|
||||
Slice<CatalogSkuHitVO> skus = want(normalized, "sku")
|
||||
? catalogLookupAdapter.searchSkus(companyId, kw)
|
||||
: new Slice<>(List.of(), false);
|
||||
boolean truncated = shops.truncated() || products.truncated() || skus.truncated();
|
||||
int total = shops.items().size() + products.items().size() + skus.items().size();
|
||||
return result(kw, normalized, truncated, shops.items(), products.items(), skus.items(),
|
||||
hint(total, truncated));
|
||||
}
|
||||
|
||||
public CatalogSkuDetailVO skuDetail(String skuCode) {
|
||||
String code = skuCode == null ? "" : skuCode.trim();
|
||||
if (code.isEmpty()) {
|
||||
return CatalogSkuDetailVO.builder()
|
||||
.hint("skuCode 不能为空。用内部规格编码查询。")
|
||||
.build();
|
||||
}
|
||||
Long companyId = currentUserContext.getCurrentCompanyId();
|
||||
CatalogSkuDetailVO detail = catalogLookupAdapter.getSkuByCode(companyId, code);
|
||||
if (detail == null) {
|
||||
return CatalogSkuDetailVO.builder()
|
||||
.skuCode(code)
|
||||
.hint("未找到该 SKU 编码。可改用 catalog_search kind=sku 模糊搜,或确认编码是否正确。")
|
||||
.build();
|
||||
}
|
||||
return detail;
|
||||
}
|
||||
|
||||
private static boolean want(String kind, String target) {
|
||||
return "all".equals(kind) || target.equals(kind);
|
||||
}
|
||||
|
||||
/** 非法 kind 按全部搜索,避免模型传错就空手而归。 */
|
||||
private static String normalizeKind(String kind) {
|
||||
if (kind == null || kind.isBlank()) {
|
||||
return "all";
|
||||
}
|
||||
String value = kind.trim().toLowerCase();
|
||||
return switch (value) {
|
||||
case "shop", "product", "sku", "all" -> value;
|
||||
default -> "all";
|
||||
};
|
||||
}
|
||||
|
||||
private static String hint(int total, boolean truncated) {
|
||||
String base = switch (total) {
|
||||
case 0 -> "没有匹配。换更完整的名称或编码再搜,不要向用户索要店铺 ID、商品 ID 或 SKU ID。";
|
||||
case 1 -> "唯一命中。直接用该 id 调用经营查询,不要再向用户确认 ID。";
|
||||
default -> "多条命中。只把名称、编码、平台列给用户选一条,禁止索要或复述数字 ID。";
|
||||
};
|
||||
if (truncated) {
|
||||
return base + "结果已截断,名称太宽时可让用户补充编码。";
|
||||
}
|
||||
return base;
|
||||
}
|
||||
|
||||
private static CatalogSearchSlimVO result(String keyword,
|
||||
String kind,
|
||||
boolean truncated,
|
||||
List<CatalogShopHitVO> shops,
|
||||
List<CatalogProductHitVO> products,
|
||||
List<CatalogSkuHitVO> skus,
|
||||
String hint) {
|
||||
return CatalogSearchSlimVO.builder()
|
||||
.keyword(keyword)
|
||||
.kind(kind)
|
||||
.truncated(truncated)
|
||||
.hint(hint)
|
||||
.shops(shops)
|
||||
.products(products)
|
||||
.skus(skus)
|
||||
.build();
|
||||
}
|
||||
}
|
||||
+80
@@ -0,0 +1,80 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.agent.mcp.application;
|
||||
|
||||
import org.springframework.stereotype.Service;
|
||||
import top.xyquan.ecomdmbbackend.modules.agent.mcp.adapter.pdd.PddGoodsLookupAdapter;
|
||||
import top.xyquan.ecomdmbbackend.modules.agent.mcp.adapter.pdd.PddGoodsLookupAdapter.Slice;
|
||||
import top.xyquan.ecomdmbbackend.modules.agent.mcp.adapter.pdd.model.PddGoodsDetailSlimVO;
|
||||
import top.xyquan.ecomdmbbackend.modules.agent.mcp.adapter.pdd.model.PddGoodsHitVO;
|
||||
import top.xyquan.ecomdmbbackend.modules.agent.mcp.adapter.pdd.model.PddGoodsSearchSlimVO;
|
||||
import top.xyquan.ecomdmbbackend.utils.CurrentUserContext;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* 拼多多渠道商品 MCP:只查本地已同步数据。
|
||||
*/
|
||||
@Service
|
||||
public class PddMcpFacade {
|
||||
|
||||
private final PddGoodsLookupAdapter pddGoodsLookupAdapter;
|
||||
private final CurrentUserContext currentUserContext;
|
||||
|
||||
public PddMcpFacade(PddGoodsLookupAdapter pddGoodsLookupAdapter,
|
||||
CurrentUserContext currentUserContext) {
|
||||
this.pddGoodsLookupAdapter = pddGoodsLookupAdapter;
|
||||
this.currentUserContext = currentUserContext;
|
||||
}
|
||||
|
||||
public PddGoodsSearchSlimVO search(String keyword, Long shopId) {
|
||||
String kw = keyword == null ? "" : keyword.trim();
|
||||
if (kw.isEmpty()) {
|
||||
return PddGoodsSearchSlimVO.builder()
|
||||
.keyword(kw)
|
||||
.truncated(false)
|
||||
.hint("keyword 不能为空。可用商品名、平台 goodsId、商家编码 outerId/outerGoodsId 搜索。")
|
||||
.items(List.of())
|
||||
.build();
|
||||
}
|
||||
if (kw.length() > 64) {
|
||||
kw = kw.substring(0, 64);
|
||||
}
|
||||
Long companyId = currentUserContext.getCurrentCompanyId();
|
||||
Slice<PddGoodsHitVO> slice = pddGoodsLookupAdapter.search(companyId, kw, shopId);
|
||||
int total = slice.items().size();
|
||||
String hint = switch (total) {
|
||||
case 0 -> "本地未命中已同步商品。可换编码/名称,或先在渠道商品里同步后再试。不要向用户要数字 ID。";
|
||||
case 1 -> "唯一命中。用返回的 id 调 pdd_goods_detail 取规格结构与标题。";
|
||||
default -> "多条命中。可自行选择最接近的一条模仿标题/规格,或请用户指定;禁止索要数字 ID。";
|
||||
};
|
||||
if (slice.truncated()) {
|
||||
hint += "结果已截断。";
|
||||
}
|
||||
return PddGoodsSearchSlimVO.builder()
|
||||
.keyword(kw)
|
||||
.truncated(slice.truncated())
|
||||
.hint(hint)
|
||||
.items(slice.items())
|
||||
.build();
|
||||
}
|
||||
|
||||
public PddGoodsDetailSlimVO detail(Long goodsRowId, String goodsId, Long shopId) {
|
||||
if (goodsRowId == null && (goodsId == null || goodsId.isBlank())) {
|
||||
return PddGoodsDetailSlimVO.builder()
|
||||
.hint("请提供 goodsRowId(搜索结果的 id)或 goodsId。")
|
||||
.skus(List.of())
|
||||
.build();
|
||||
}
|
||||
Long companyId = currentUserContext.getCurrentCompanyId();
|
||||
PddGoodsDetailSlimVO detail = pddGoodsLookupAdapter.detail(
|
||||
companyId, goodsRowId, goodsId, shopId);
|
||||
if (detail == null) {
|
||||
return PddGoodsDetailSlimVO.builder()
|
||||
.id(goodsRowId)
|
||||
.goodsId(goodsId)
|
||||
.hint("未找到该渠道商品(可能未同步或已平台删除)。")
|
||||
.skus(List.of())
|
||||
.build();
|
||||
}
|
||||
return detail;
|
||||
}
|
||||
}
|
||||
+24
@@ -0,0 +1,24 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.agent.mcp.config;
|
||||
|
||||
import lombok.Data;
|
||||
import org.springframework.boot.context.properties.ConfigurationProperties;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
/**
|
||||
* Agent 访问 MCP 的独立凭证配置(与 JWT / Open API Key 分离)。
|
||||
*/
|
||||
@Data
|
||||
@Component
|
||||
@ConfigurationProperties(prefix = "ecom.agent.mcp")
|
||||
public class AgentMcpProperties {
|
||||
|
||||
/**
|
||||
* Bearer token;为空则拒绝所有 /mcp 请求。
|
||||
*/
|
||||
private String bearerToken = "";
|
||||
|
||||
/**
|
||||
* 本地单租户 fallback;生产应由请求头 X-Agent-Company-Id 注入。
|
||||
*/
|
||||
private Long companyId;
|
||||
}
|
||||
+65
@@ -0,0 +1,65 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.agent.mcp.security;
|
||||
|
||||
import lombok.Getter;
|
||||
import org.springframework.security.core.Authentication;
|
||||
import org.springframework.security.core.GrantedAuthority;
|
||||
|
||||
import java.util.Collection;
|
||||
import java.util.Collections;
|
||||
|
||||
/**
|
||||
* MCP Agent 鉴权结果,写入 SecurityContext 供 /mcp 放行。
|
||||
*/
|
||||
@Getter
|
||||
public class AgentMcpAuthentication implements Authentication {
|
||||
|
||||
private final AgentMcpPrincipal principal;
|
||||
private boolean authenticated = true;
|
||||
|
||||
public AgentMcpAuthentication(AgentMcpPrincipal principal) {
|
||||
this.principal = principal;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Collection<? extends GrantedAuthority> getAuthorities() {
|
||||
return Collections.emptyList();
|
||||
}
|
||||
|
||||
@Override
|
||||
public Object getCredentials() {
|
||||
return "agent-mcp-token";
|
||||
}
|
||||
|
||||
@Override
|
||||
public Object getDetails() {
|
||||
return null;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Object getPrincipal() {
|
||||
return principal;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean isAuthenticated() {
|
||||
return authenticated;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setAuthenticated(boolean isAuthenticated) throws IllegalArgumentException {
|
||||
this.authenticated = isAuthenticated;
|
||||
}
|
||||
|
||||
@Override
|
||||
public String getName() {
|
||||
return principal.clientName();
|
||||
}
|
||||
|
||||
public Long getCompanyId() {
|
||||
return principal.companyId();
|
||||
}
|
||||
|
||||
public String getUserId() {
|
||||
return principal.userId();
|
||||
}
|
||||
}
|
||||
+133
@@ -0,0 +1,133 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.agent.mcp.security;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import jakarta.servlet.FilterChain;
|
||||
import jakarta.servlet.ServletException;
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import jakarta.servlet.http.HttpServletResponse;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.lang.NonNull;
|
||||
import org.springframework.security.core.context.SecurityContextHolder;
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.springframework.util.StringUtils;
|
||||
import org.springframework.web.filter.OncePerRequestFilter;
|
||||
import top.xyquan.ecomdmbbackend.common.response.ApiResponse;
|
||||
import top.xyquan.ecomdmbbackend.modules.agent.mcp.config.AgentMcpProperties;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.security.MessageDigest;
|
||||
|
||||
/**
|
||||
* Agent 鉴权:处理 /mcp 与 /api/internal/agent/**;Bearer 为服务凭证,租户来自请求头。
|
||||
*/
|
||||
@Slf4j
|
||||
@Component
|
||||
public class AgentMcpAuthenticationFilter extends OncePerRequestFilter {
|
||||
|
||||
public static final String HEADER_COMPANY_ID = "X-Agent-Company-Id";
|
||||
public static final String HEADER_USER_ID = "X-Agent-User-Id";
|
||||
|
||||
private static final String MCP_PATH = "/mcp";
|
||||
private static final String INTERNAL_PREFIX = "/api/internal/agent";
|
||||
|
||||
private final AgentMcpProperties properties;
|
||||
private final ObjectMapper objectMapper;
|
||||
|
||||
public AgentMcpAuthenticationFilter(AgentMcpProperties properties, ObjectMapper objectMapper) {
|
||||
this.properties = properties;
|
||||
this.objectMapper = objectMapper;
|
||||
}
|
||||
|
||||
@Override
|
||||
protected boolean shouldNotFilter(@NonNull HttpServletRequest request) {
|
||||
String uri = request.getRequestURI();
|
||||
if (uri == null) {
|
||||
return true;
|
||||
}
|
||||
return !(uri.equals(MCP_PATH)
|
||||
|| uri.startsWith(MCP_PATH + "/")
|
||||
|| uri.startsWith(INTERNAL_PREFIX));
|
||||
}
|
||||
|
||||
@Override
|
||||
protected void doFilterInternal(
|
||||
@NonNull HttpServletRequest request,
|
||||
@NonNull HttpServletResponse response,
|
||||
@NonNull FilterChain filterChain)
|
||||
throws ServletException, IOException {
|
||||
try {
|
||||
String configured = properties.getBearerToken();
|
||||
if (!StringUtils.hasText(configured)) {
|
||||
writeUnauthorized(response, "Agent 凭证未配置");
|
||||
return;
|
||||
}
|
||||
|
||||
String provided = extractBearer(request);
|
||||
if (!StringUtils.hasText(provided) || !tokenEquals(configured, provided)) {
|
||||
writeUnauthorized(response, "Agent 凭证无效或缺失");
|
||||
return;
|
||||
}
|
||||
|
||||
Long companyId = resolveCompanyId(request);
|
||||
String userId = resolveUserId(request);
|
||||
// /mcp 业务 tool 必须有 company;内部 llm-runtime 可用 query companyId,头可空
|
||||
boolean mcpCall = isMcpPath(request.getRequestURI());
|
||||
if (mcpCall && companyId == null) {
|
||||
writeUnauthorized(response, "缺少租户头 " + HEADER_COMPANY_ID);
|
||||
return;
|
||||
}
|
||||
|
||||
AgentMcpPrincipal principal = new AgentMcpPrincipal("agent-mcp", companyId, userId);
|
||||
SecurityContextHolder.getContext().setAuthentication(new AgentMcpAuthentication(principal));
|
||||
filterChain.doFilter(request, response);
|
||||
} finally {
|
||||
SecurityContextHolder.clearContext();
|
||||
}
|
||||
}
|
||||
|
||||
private Long resolveCompanyId(HttpServletRequest request) {
|
||||
String header = request.getHeader(HEADER_COMPANY_ID);
|
||||
if (StringUtils.hasText(header)) {
|
||||
try {
|
||||
return Long.parseLong(header.trim());
|
||||
} catch (NumberFormatException e) {
|
||||
log.warn("非法 {}={}", HEADER_COMPANY_ID, header);
|
||||
}
|
||||
}
|
||||
// 兼容旧配置:无头时回退静态 company-id(仅建议本地单租户)
|
||||
return properties.getCompanyId();
|
||||
}
|
||||
|
||||
private String resolveUserId(HttpServletRequest request) {
|
||||
String header = request.getHeader(HEADER_USER_ID);
|
||||
if (StringUtils.hasText(header)) {
|
||||
return header.trim();
|
||||
}
|
||||
return "0";
|
||||
}
|
||||
|
||||
private static boolean isMcpPath(String uri) {
|
||||
return uri != null && (uri.equals(MCP_PATH) || uri.startsWith(MCP_PATH + "/"));
|
||||
}
|
||||
|
||||
private String extractBearer(HttpServletRequest request) {
|
||||
String authorization = request.getHeader("Authorization");
|
||||
if (StringUtils.hasText(authorization) && authorization.startsWith("Bearer ")) {
|
||||
return authorization.substring(7).trim();
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
private static boolean tokenEquals(String expected, String actual) {
|
||||
byte[] a = expected.getBytes(StandardCharsets.UTF_8);
|
||||
byte[] b = actual.getBytes(StandardCharsets.UTF_8);
|
||||
return MessageDigest.isEqual(a, b);
|
||||
}
|
||||
|
||||
private void writeUnauthorized(HttpServletResponse response, String message) throws IOException {
|
||||
response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
|
||||
response.setContentType("application/json;charset=UTF-8");
|
||||
response.getWriter().write(objectMapper.writeValueAsString(ApiResponse.fail(40101, message)));
|
||||
}
|
||||
}
|
||||
+11
@@ -0,0 +1,11 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.agent.mcp.security;
|
||||
|
||||
/**
|
||||
* MCP / Agent 内部调用主体;companyId、userId 来自请求头(多租户)。
|
||||
*/
|
||||
public record AgentMcpPrincipal(String clientName, Long companyId, String userId) {
|
||||
|
||||
public AgentMcpPrincipal(String clientName, Long companyId) {
|
||||
this(clientName, companyId, "0");
|
||||
}
|
||||
}
|
||||
+18
@@ -0,0 +1,18 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.agent.mcp.tools;
|
||||
|
||||
import org.springaicommunity.mcp.annotation.McpTool;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* MCP 连通性探测 Tool;无业务编排。
|
||||
*/
|
||||
@Component
|
||||
public class AgentMcpHealthTools {
|
||||
|
||||
@McpTool(name = "mcp_ping", description = "探测 MCP 服务是否可用,返回固定 ok。")
|
||||
public Map<String, String> ping() {
|
||||
return Map.of("status", "ok", "server", "ecom-dmb-mcp");
|
||||
}
|
||||
}
|
||||
+59
@@ -0,0 +1,59 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.agent.mcp.tools;
|
||||
|
||||
import org.springaicommunity.mcp.annotation.McpTool;
|
||||
import org.springaicommunity.mcp.annotation.McpToolParam;
|
||||
import org.springframework.stereotype.Component;
|
||||
import top.xyquan.ecomdmbbackend.modules.agent.mcp.adapter.bi.model.BiProductOverviewSlimVO;
|
||||
import top.xyquan.ecomdmbbackend.modules.agent.mcp.adapter.bi.model.BiShopOverviewSlimVO;
|
||||
import top.xyquan.ecomdmbbackend.modules.agent.mcp.adapter.bi.model.BiWorkbenchFinanceSlimVO;
|
||||
import top.xyquan.ecomdmbbackend.modules.agent.mcp.application.BiMcpFacade;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
|
||||
/**
|
||||
* BI MCP Tool 入口:仅暴露 @McpTool,用例交给 {@link BiMcpFacade}。
|
||||
*/
|
||||
@Component
|
||||
public class BiMcpTools {
|
||||
|
||||
private final BiMcpFacade biMcpFacade;
|
||||
|
||||
public BiMcpTools(BiMcpFacade biMcpFacade) {
|
||||
this.biMcpFacade = biMcpFacade;
|
||||
}
|
||||
|
||||
@McpTool(
|
||||
name = "bi_workbench_finance",
|
||||
description = "查询工作台经营概览 KPI(销售额、单量、净利、费比等),按日期范围;可选平台/店铺筛选。租户取自 MCP 绑定的 companyId。shopId 只能来自 catalog_search 或用户消息 [引用],不要向用户索要。")
|
||||
public BiWorkbenchFinanceSlimVO workbenchFinance(
|
||||
@McpToolParam(description = "开始日期 yyyy-MM-dd", required = true) String startDate,
|
||||
@McpToolParam(description = "结束日期 yyyy-MM-dd", required = true) String endDate,
|
||||
@McpToolParam(description = "平台编码,可选", required = false) String platformCode,
|
||||
@McpToolParam(description = "店铺 ID,可选", required = false) Long shopId,
|
||||
@McpToolParam(description = "税率,默认 0.04", required = false) BigDecimal taxRate) {
|
||||
return biMcpFacade.workbenchFinance(startDate, endDate, platformCode, shopId, taxRate);
|
||||
}
|
||||
|
||||
@McpTool(
|
||||
name = "bi_shop_overview",
|
||||
description = "查询单店经营概览摘要:销售额、单量、净利、ROI、目标达成率,以及商品销量 Top10。shopId 来自 catalog_search 或用户消息 [引用],禁止向用户索要店铺 ID。")
|
||||
public BiShopOverviewSlimVO shopOverview(
|
||||
@McpToolParam(description = "店铺 ID", required = true) Long shopId,
|
||||
@McpToolParam(description = "开始日期 yyyy-MM-dd", required = true) String startDate,
|
||||
@McpToolParam(description = "结束日期 yyyy-MM-dd", required = true) String endDate,
|
||||
@McpToolParam(description = "税率,默认 0.04", required = false) BigDecimal taxRate) {
|
||||
return biMcpFacade.shopOverview(shopId, startDate, endDate, taxRate);
|
||||
}
|
||||
|
||||
@McpTool(
|
||||
name = "bi_product_overview",
|
||||
description = "查询单商品经营概览摘要:销售额、单量、净利、ROI、目标达成率,以及规格销量 Top10;可选限定店铺。productId/shopId 来自 catalog_search 或用户消息 [引用],禁止向用户索要 ID。")
|
||||
public BiProductOverviewSlimVO productOverview(
|
||||
@McpToolParam(description = "商品 ID", required = true) Long productId,
|
||||
@McpToolParam(description = "开始日期 yyyy-MM-dd", required = true) String startDate,
|
||||
@McpToolParam(description = "结束日期 yyyy-MM-dd", required = true) String endDate,
|
||||
@McpToolParam(description = "店铺 ID,可选", required = false) Long shopId,
|
||||
@McpToolParam(description = "税率,默认 0.04", required = false) BigDecimal taxRate) {
|
||||
return biMcpFacade.productOverview(productId, startDate, endDate, shopId, taxRate);
|
||||
}
|
||||
}
|
||||
+43
@@ -0,0 +1,43 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.agent.mcp.tools;
|
||||
|
||||
import org.springaicommunity.mcp.annotation.McpTool;
|
||||
import org.springaicommunity.mcp.annotation.McpToolParam;
|
||||
import org.springframework.stereotype.Component;
|
||||
import top.xyquan.ecomdmbbackend.modules.agent.mcp.adapter.catalog.model.CatalogSearchSlimVO;
|
||||
import top.xyquan.ecomdmbbackend.modules.agent.mcp.adapter.catalog.model.CatalogSkuDetailVO;
|
||||
import top.xyquan.ecomdmbbackend.modules.agent.mcp.application.CatalogMcpFacade;
|
||||
|
||||
/**
|
||||
* 目录检索 MCP:用名称/编码反查店铺、商品、SKU,再把 id 交给经营查询。
|
||||
*/
|
||||
@Component
|
||||
public class CatalogMcpTools {
|
||||
|
||||
private final CatalogMcpFacade catalogMcpFacade;
|
||||
|
||||
public CatalogMcpTools(CatalogMcpFacade catalogMcpFacade) {
|
||||
this.catalogMcpFacade = catalogMcpFacade;
|
||||
}
|
||||
|
||||
@McpTool(
|
||||
name = "catalog_search",
|
||||
description = "按名称或编码在当前租户检索店铺、商品、SKU,返回 id。"
|
||||
+ "用户提到店名、商品名、商品编码、SKU 编码/规格名时必须先调本工具,禁止向用户索要数字 ID。"
|
||||
+ "店铺没有编码,只按名称匹配。kind:shop、product、sku、all(默认 all)。"
|
||||
+ "恰好一条时用返回 id 调 bi_*;多条时只让用户按名称/编码选择。")
|
||||
public CatalogSearchSlimVO search(
|
||||
@McpToolParam(description = "店铺名、商品名、商品编码或 SKU 编码,必填", required = true) String keyword,
|
||||
@McpToolParam(description = "shop / product / sku / all,默认 all", required = false) String kind) {
|
||||
return catalogMcpFacade.search(keyword, kind);
|
||||
}
|
||||
|
||||
@McpTool(
|
||||
name = "catalog_sku_detail",
|
||||
description = "按内部 SKU 编码精准查询规格详情(名称、attrs、规格键、所属商品)。"
|
||||
+ "发布页表单已有商家编码时,整体编辑或改规格/重量/标题前必须先对本编码调用,"
|
||||
+ "用返回资料直接写入,不要向用户追问规格文案或重量。本接口不含售价。")
|
||||
public CatalogSkuDetailVO skuDetail(
|
||||
@McpToolParam(description = "内部 SKU 编码 skuCode,必填", required = true) String skuCode) {
|
||||
return catalogMcpFacade.skuDetail(skuCode);
|
||||
}
|
||||
}
|
||||
+43
@@ -0,0 +1,43 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.agent.mcp.tools;
|
||||
|
||||
import org.springaicommunity.mcp.annotation.McpTool;
|
||||
import org.springaicommunity.mcp.annotation.McpToolParam;
|
||||
import org.springframework.stereotype.Component;
|
||||
import top.xyquan.ecomdmbbackend.modules.agent.mcp.adapter.pdd.model.PddGoodsDetailSlimVO;
|
||||
import top.xyquan.ecomdmbbackend.modules.agent.mcp.adapter.pdd.model.PddGoodsSearchSlimVO;
|
||||
import top.xyquan.ecomdmbbackend.modules.agent.mcp.application.PddMcpFacade;
|
||||
|
||||
/**
|
||||
* 拼多多渠道商品 MCP:供发布场景模仿标题/规格。
|
||||
*/
|
||||
@Component
|
||||
public class PddMcpTools {
|
||||
|
||||
private final PddMcpFacade pddMcpFacade;
|
||||
|
||||
public PddMcpTools(PddMcpFacade pddMcpFacade) {
|
||||
this.pddMcpFacade = pddMcpFacade;
|
||||
}
|
||||
|
||||
@McpTool(
|
||||
name = "pdd_goods_search",
|
||||
description = "在当前租户已同步的拼多多渠道商品中检索。"
|
||||
+ "可用商品名、平台 goodsId、SKU 商家编码 outerId(out_sku_sn)或 outerGoodsId。"
|
||||
+ "只查本地库,不实时拉 POP。发布场景生成标题/规格前先搜再 detail。")
|
||||
public PddGoodsSearchSlimVO search(
|
||||
@McpToolParam(description = "商品名 / goodsId / outerId / outerGoodsId", required = true) String keyword,
|
||||
@McpToolParam(description = "渠道店铺 shopId,可选", required = false) Long shopId) {
|
||||
return pddMcpFacade.search(keyword, shopId);
|
||||
}
|
||||
|
||||
@McpTool(
|
||||
name = "pdd_goods_detail",
|
||||
description = "取已同步拼多多商品瘦详情:标题、规格文字、各 SKU 的 outerId/spec。"
|
||||
+ "goodsRowId 优先(来自 pdd_goods_search 的 id);也可用 goodsId。")
|
||||
public PddGoodsDetailSlimVO detail(
|
||||
@McpToolParam(description = "本地渠道商品行 id(搜索结果 id)", required = false) Long goodsRowId,
|
||||
@McpToolParam(description = "平台 goodsId", required = false) String goodsId,
|
||||
@McpToolParam(description = "渠道店铺 shopId,可选", required = false) Long shopId) {
|
||||
return pddMcpFacade.detail(goodsRowId, goodsId, shopId);
|
||||
}
|
||||
}
|
||||
+32
@@ -0,0 +1,32 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.bi.categoryoverview.controller;
|
||||
|
||||
import jakarta.validation.Valid;
|
||||
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 top.xyquan.ecomdmbbackend.common.annotation.RequirePermission;
|
||||
import top.xyquan.ecomdmbbackend.common.response.ApiResponse;
|
||||
import top.xyquan.ecomdmbbackend.modules.bi.categoryoverview.model.dto.CategoryOverviewQueryDTO;
|
||||
import top.xyquan.ecomdmbbackend.modules.bi.categoryoverview.model.vo.CategoryOverviewVO;
|
||||
import top.xyquan.ecomdmbbackend.modules.bi.categoryoverview.service.BiCategoryOverviewService;
|
||||
|
||||
/**
|
||||
* 品类概览 API:公司下指定品类的经营汇总。
|
||||
*/
|
||||
@RestController
|
||||
@RequestMapping("/api/bi/category")
|
||||
public class BiCategoryOverviewController {
|
||||
|
||||
private final BiCategoryOverviewService biCategoryOverviewService;
|
||||
|
||||
public BiCategoryOverviewController(BiCategoryOverviewService biCategoryOverviewService) {
|
||||
this.biCategoryOverviewService = biCategoryOverviewService;
|
||||
}
|
||||
|
||||
@PostMapping("/overview")
|
||||
@RequirePermission(value = "bi:category:overview", description = "查询品类概览", allowSuper = true)
|
||||
public ApiResponse<CategoryOverviewVO> overview(@Valid @RequestBody CategoryOverviewQueryDTO queryDTO) {
|
||||
return ApiResponse.success("获取品类概览成功", biCategoryOverviewService.getCategoryOverview(queryDTO));
|
||||
}
|
||||
}
|
||||
+37
@@ -0,0 +1,37 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.bi.categoryoverview.model.dto;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
|
||||
import jakarta.validation.constraints.NotNull;
|
||||
import jakarta.validation.constraints.Size;
|
||||
import lombok.Data;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.time.LocalDate;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* 品类概览查询:公司下指定品类汇总;日期支持 start/end 或 dateRange。
|
||||
*/
|
||||
@Data
|
||||
@JsonIgnoreProperties(ignoreUnknown = true)
|
||||
public class CategoryOverviewQueryDTO {
|
||||
|
||||
/** 品类 ID */
|
||||
@NotNull(message = "品类ID不能为空")
|
||||
private Long categoryId;
|
||||
|
||||
/** 开始日期(与 endDate 成对;也可改用 dateRange) */
|
||||
private LocalDate startDate;
|
||||
|
||||
/** 结束日期 */
|
||||
private LocalDate endDate;
|
||||
|
||||
/**
|
||||
* 日期范围(1 个=当天,2 个=起止);与 startDate/endDate 二选一,优先本字段。
|
||||
*/
|
||||
@Size(min = 1, max = 2, message = "日期范围数组必须包含1-2个日期")
|
||||
private List<LocalDate> dateRange;
|
||||
|
||||
/** 税率(默认 4%) */
|
||||
private BigDecimal taxRate = new BigDecimal("0.04");
|
||||
}
|
||||
+97
@@ -0,0 +1,97 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.bi.categoryoverview.model.vo;
|
||||
|
||||
import lombok.Data;
|
||||
import top.xyquan.ecomdmbbackend.modules.bi.workbench.model.vo.WorkbenchCostSliceVO;
|
||||
import top.xyquan.ecomdmbbackend.modules.bi.workbench.model.vo.WorkbenchKpiItemVO;
|
||||
import top.xyquan.ecomdmbbackend.modules.bi.workbench.model.vo.WorkbenchTrendPointVO;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* 品类概览响应:KPI/趋势与工作台同口径,附品类内商品表与销量占比。
|
||||
*/
|
||||
@Data
|
||||
public class CategoryOverviewVO {
|
||||
|
||||
private Long categoryId;
|
||||
|
||||
private String categoryName;
|
||||
|
||||
/** 与工作台经营概览同结构的 KPI 列表 */
|
||||
private List<WorkbenchKpiItemVO> kpis;
|
||||
|
||||
/** 成交/净销售/利润日趋势 */
|
||||
private List<WorkbenchTrendPointVO> dealTrend;
|
||||
|
||||
/** 品类内各商品净销售额占比(饼图) */
|
||||
private List<WorkbenchCostSliceVO> productSalesShare;
|
||||
|
||||
private String momCompareDateStart;
|
||||
private String momCompareDateEnd;
|
||||
private String yoyCompareDateStart;
|
||||
private String yoyCompareDateEnd;
|
||||
|
||||
/** 兼容扁平 KPI 摘要 */
|
||||
private BigDecimal totalSalesAmount;
|
||||
private BigDecimal monthOverMonthGrowth;
|
||||
private Integer totalOrderCount;
|
||||
private BigDecimal totalPromotionFee;
|
||||
private BigDecimal averageFeeRatio;
|
||||
private BigDecimal totalNetProfitAfterTax;
|
||||
private BigDecimal totalTaxAmount;
|
||||
private Integer totalTargetOrderCount;
|
||||
private BigDecimal totalTargetAmount;
|
||||
private BigDecimal orderCountAchievementRate;
|
||||
private BigDecimal salesAmountAchievementRate;
|
||||
private BigDecimal totalROI;
|
||||
private BigDecimal averageOrderValue;
|
||||
private BigDecimal refundAmount;
|
||||
private BigDecimal totalProfitBeforeTax;
|
||||
|
||||
private List<ProductSalesRankItem> productSalesTop10;
|
||||
|
||||
private ProductOverview productOverview;
|
||||
|
||||
@Data
|
||||
public static class ProductSalesRankItem {
|
||||
private Long productId;
|
||||
private String productName;
|
||||
private String productCode;
|
||||
private Integer orderCount;
|
||||
private BigDecimal salesAmount;
|
||||
}
|
||||
|
||||
@Data
|
||||
public static class ProductOverview {
|
||||
private ProductSummary total;
|
||||
private List<ProductSummary> products;
|
||||
}
|
||||
|
||||
@Data
|
||||
public static class ProductSummary {
|
||||
private Long productId;
|
||||
private String productName;
|
||||
private String productCode;
|
||||
private BigDecimal salesAmount;
|
||||
private BigDecimal dealAmount;
|
||||
private Integer salesOrderCount;
|
||||
private Integer dealOrderCount;
|
||||
private Integer dealQuantitySum;
|
||||
private Integer salesQuantitySum;
|
||||
private BigDecimal salesAverageOrderValue;
|
||||
private BigDecimal dealAverageOrderValue;
|
||||
private BigDecimal productCost;
|
||||
private BigDecimal shippingCost;
|
||||
private BigDecimal otherCost;
|
||||
private BigDecimal orderCost;
|
||||
private BigDecimal refundAmount;
|
||||
private BigDecimal totalPromotionFee;
|
||||
private BigDecimal brushFee;
|
||||
private BigDecimal feeRatio;
|
||||
private BigDecimal totalProfitBeforeTax;
|
||||
private BigDecimal salesTaxAmount;
|
||||
private BigDecimal profitAfterTax;
|
||||
private BigDecimal roi;
|
||||
}
|
||||
}
|
||||
+12
@@ -0,0 +1,12 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.bi.categoryoverview.service;
|
||||
|
||||
import top.xyquan.ecomdmbbackend.modules.bi.categoryoverview.model.dto.CategoryOverviewQueryDTO;
|
||||
import top.xyquan.ecomdmbbackend.modules.bi.categoryoverview.model.vo.CategoryOverviewVO;
|
||||
|
||||
/**
|
||||
* BI 品类概览:按品类汇总;订单读 Mongo 日汇聚,推广/刷单/目标读 MySQL。
|
||||
*/
|
||||
public interface BiCategoryOverviewService {
|
||||
|
||||
CategoryOverviewVO getCategoryOverview(CategoryOverviewQueryDTO queryDTO);
|
||||
}
|
||||
+495
@@ -0,0 +1,495 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.bi.categoryoverview.service.impl;
|
||||
|
||||
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
|
||||
import org.springframework.stereotype.Service;
|
||||
import top.xyquan.ecomdmbbackend.common.exception.BusinessException;
|
||||
import top.xyquan.ecomdmbbackend.modules.bi.categoryoverview.model.dto.CategoryOverviewQueryDTO;
|
||||
import top.xyquan.ecomdmbbackend.modules.bi.categoryoverview.model.vo.CategoryOverviewVO;
|
||||
import top.xyquan.ecomdmbbackend.modules.bi.categoryoverview.service.BiCategoryOverviewService;
|
||||
import top.xyquan.ecomdmbbackend.modules.bi.orderstat.model.document.BiOrderStatDailyProductDoc;
|
||||
import top.xyquan.ecomdmbbackend.modules.bi.orderstat.query.BiOrderStatQueryService;
|
||||
import top.xyquan.ecomdmbbackend.modules.bi.overview.model.agg.OverviewAggRows;
|
||||
import top.xyquan.ecomdmbbackend.modules.bi.overview.model.vo.CompanyOverviewVO;
|
||||
import top.xyquan.ecomdmbbackend.modules.bi.overview.service.CompanyOverviewService;
|
||||
import top.xyquan.ecomdmbbackend.modules.bi.workbench.model.vo.WorkbenchCostSliceVO;
|
||||
import top.xyquan.ecomdmbbackend.modules.bi.workbench.model.vo.WorkbenchTrendPointVO;
|
||||
import top.xyquan.ecomdmbbackend.modules.bi.workbench.support.BiFinanceKpiAssembler;
|
||||
import top.xyquan.ecomdmbbackend.modules.bi.workbench.support.BiWorkbenchFeeLoader;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.product.category.model.po.CategoryPO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.product.category.service.CategoryService;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.product.mapper.ProductMapper;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.product.model.po.ProductPO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.shop.model.po.ShopPO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.shop.monthlytarget.mapper.ShopMonthlyTargetMapper;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.shop.monthlytarget.model.po.ShopMonthlyTargetPO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.shop.service.ShopService;
|
||||
import top.xyquan.ecomdmbbackend.utils.CurrentUserContext;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.math.RoundingMode;
|
||||
import java.time.LocalDate;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Collections;
|
||||
import java.util.Comparator;
|
||||
import java.util.HashMap;
|
||||
import java.util.HashSet;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
import java.util.Set;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
/**
|
||||
* 品类概览:Mongo 商品日汇聚按品类过滤 + 费用分摊后的 KPI(与工作台同口径)。
|
||||
*/
|
||||
@Service
|
||||
public class BiCategoryOverviewServiceImpl implements BiCategoryOverviewService {
|
||||
|
||||
private static final BigDecimal DEFAULT_TAX_RATE = new BigDecimal("0.04");
|
||||
private static final int PRODUCT_SHARE_LIMIT = 12;
|
||||
|
||||
private final CurrentUserContext currentUserContext;
|
||||
private final CategoryService categoryService;
|
||||
private final ShopService shopService;
|
||||
private final BiOrderStatQueryService orderStatQueryService;
|
||||
private final BiWorkbenchFeeLoader feeLoader;
|
||||
private final CompanyOverviewService companyOverviewService;
|
||||
private final ShopMonthlyTargetMapper shopMonthlyTargetMapper;
|
||||
private final ProductMapper productMapper;
|
||||
|
||||
public BiCategoryOverviewServiceImpl(CurrentUserContext currentUserContext,
|
||||
CategoryService categoryService,
|
||||
ShopService shopService,
|
||||
BiOrderStatQueryService orderStatQueryService,
|
||||
BiWorkbenchFeeLoader feeLoader,
|
||||
CompanyOverviewService companyOverviewService,
|
||||
ShopMonthlyTargetMapper shopMonthlyTargetMapper,
|
||||
ProductMapper productMapper) {
|
||||
this.currentUserContext = currentUserContext;
|
||||
this.categoryService = categoryService;
|
||||
this.shopService = shopService;
|
||||
this.orderStatQueryService = orderStatQueryService;
|
||||
this.feeLoader = feeLoader;
|
||||
this.companyOverviewService = companyOverviewService;
|
||||
this.shopMonthlyTargetMapper = shopMonthlyTargetMapper;
|
||||
this.productMapper = productMapper;
|
||||
}
|
||||
|
||||
@Override
|
||||
public CategoryOverviewVO getCategoryOverview(CategoryOverviewQueryDTO queryDTO) {
|
||||
BigDecimal taxRate = queryDTO.getTaxRate() != null ? queryDTO.getTaxRate() : DEFAULT_TAX_RATE;
|
||||
Long companyId = currentUserContext.getCurrentCompanyId();
|
||||
LocalDate start = resolveStart(queryDTO);
|
||||
LocalDate end = resolveEnd(queryDTO);
|
||||
if (start.isAfter(end)) {
|
||||
throw new BusinessException("开始日期不能晚于结束日期");
|
||||
}
|
||||
|
||||
CategoryPO category = categoryService.getById(queryDTO.getCategoryId());
|
||||
if (category == null || !Objects.equals(category.getCompanyId(), companyId)) {
|
||||
throw new BusinessException("品类不存在");
|
||||
}
|
||||
|
||||
CategoryOverviewVO vo = new CategoryOverviewVO();
|
||||
vo.setCategoryId(category.getId());
|
||||
vo.setCategoryName(category.getName());
|
||||
|
||||
LocalDate[] mom = BiFinanceKpiAssembler.lastMonthSameSpan(start, end);
|
||||
LocalDate[] yoy = BiFinanceKpiAssembler.yoySameSpan(start, end);
|
||||
vo.setMomCompareDateStart(mom[0].toString());
|
||||
vo.setMomCompareDateEnd(mom[1].toString());
|
||||
vo.setYoyCompareDateStart(yoy[0].toString());
|
||||
vo.setYoyCompareDateEnd(yoy[1].toString());
|
||||
|
||||
PeriodBundle cur = loadPeriod(companyId, category.getId(), start, end, taxRate);
|
||||
PeriodBundle prev = loadPeriod(companyId, category.getId(), mom[0], mom[1], taxRate);
|
||||
PeriodBundle yoyBundle = loadPeriod(companyId, category.getId(), yoy[0], yoy[1], taxRate);
|
||||
|
||||
BiFinanceKpiAssembler.Totals curT = cur.totals();
|
||||
BiFinanceKpiAssembler.Totals prevT = prev.totals();
|
||||
BiFinanceKpiAssembler.Totals yoyT = yoyBundle.totals();
|
||||
|
||||
List<WorkbenchTrendPointVO> dealTrend =
|
||||
BiFinanceKpiAssembler.buildTrendFromDaily(cur.dailyRows(), start, end, curT);
|
||||
|
||||
vo.setKpis(BiFinanceKpiAssembler.buildKpis(curT, prevT, yoyT, start, end, taxRate));
|
||||
vo.setDealTrend(dealTrend);
|
||||
|
||||
Map<Long, ProductPO> products = loadProducts(cur.productIds());
|
||||
vo.setProductOverview(mapProductOverview(cur.productTable(), products, category.getId()));
|
||||
vo.setProductSalesShare(buildProductSalesShare(vo.getProductOverview(), curT.totalSales()));
|
||||
fillProductSalesTop10(vo);
|
||||
fillLegacyFlatFields(vo, curT, prevT);
|
||||
fillTargets(vo, companyId, cur.shopIds(), start, end, curT.totalSales(), curT.orderCount());
|
||||
return vo;
|
||||
}
|
||||
|
||||
/**
|
||||
* 加载单区间:涉及店铺全量建表以正确分摊费用,再取本品类行;趋势仅本品类商品日汇聚。
|
||||
*/
|
||||
private PeriodBundle loadPeriod(Long companyId, Long categoryId,
|
||||
LocalDate start, LocalDate end, BigDecimal taxRate) {
|
||||
Set<Long> categoryProductIds = loadProductIdsInCategory(companyId, categoryId);
|
||||
|
||||
List<ShopPO> allShops = shopService.list(new LambdaQueryWrapper<ShopPO>()
|
||||
.eq(ShopPO::getCompanyId, companyId));
|
||||
if (allShops.isEmpty()) {
|
||||
return new PeriodBundle(List.of(), Set.of(), BiFinanceKpiAssembler.Totals.empty(),
|
||||
List.of(), null);
|
||||
}
|
||||
|
||||
List<Long> allShopIds = allShops.stream().map(ShopPO::getId).filter(Objects::nonNull).toList();
|
||||
Map<Long, String> platformByShopId = allShops.stream()
|
||||
.filter(s -> s.getId() != null)
|
||||
.collect(Collectors.toMap(ShopPO::getId,
|
||||
s -> s.getPlatformCode() != null ? s.getPlatformCode() : "",
|
||||
(a, b) -> a));
|
||||
|
||||
List<BiOrderStatDailyProductDoc> allProductDocs =
|
||||
orderStatQueryService.listProductDocs(companyId, allShopIds, start, end);
|
||||
|
||||
List<BiOrderStatDailyProductDoc> categoryDocs = allProductDocs.stream()
|
||||
.filter(d -> d.getProductId() != null && categoryProductIds.contains(d.getProductId()))
|
||||
.toList();
|
||||
|
||||
List<OverviewAggRows.DailyRow> dailyRows =
|
||||
orderStatQueryService.toDailyRowsFromProductDocs(categoryDocs);
|
||||
|
||||
List<Long> shopIds = categoryDocs.stream()
|
||||
.map(BiOrderStatDailyProductDoc::getShopId)
|
||||
.filter(Objects::nonNull)
|
||||
.distinct()
|
||||
.collect(Collectors.toList());
|
||||
|
||||
if (shopIds.isEmpty() || categoryProductIds.isEmpty()) {
|
||||
return new PeriodBundle(List.of(), categoryProductIds, BiFinanceKpiAssembler.Totals.empty(),
|
||||
dailyRows, null);
|
||||
}
|
||||
|
||||
List<ShopPO> shops = allShops.stream()
|
||||
.filter(s -> s.getId() != null && shopIds.contains(s.getId()))
|
||||
.collect(Collectors.toList());
|
||||
|
||||
List<BiOrderStatDailyProductDoc> shopProductDocs = allProductDocs.stream()
|
||||
.filter(d -> d.getShopId() != null && shopIds.contains(d.getShopId()))
|
||||
.toList();
|
||||
|
||||
BiWorkbenchFeeLoader.FeeBundle fees = feeLoader.load(companyId, shopIds, start, end);
|
||||
List<OverviewAggRows.ShopProductRow> orderRows =
|
||||
orderStatQueryService.toShopProductRows(shopProductDocs, platformByShopId);
|
||||
CompanyOverviewVO.WorkbenchTableBundle tables =
|
||||
companyOverviewService.buildWorkbenchSummaryTablesFromAgg(
|
||||
taxRate, companyId, shops, orderRows,
|
||||
fees.promotionRows(), fees.brushRows(), start, end);
|
||||
|
||||
CompanyOverviewVO.CategorySummary categoryRow =
|
||||
findCategoryRow(tables.getCategoryTable(), categoryId);
|
||||
BiFinanceKpiAssembler.Totals totals = categoryRow != null
|
||||
? BiFinanceKpiAssembler.fromCategorySummary(categoryRow, taxRate)
|
||||
: BiFinanceKpiAssembler.Totals.empty();
|
||||
|
||||
return new PeriodBundle(shopIds, categoryProductIds, totals, dailyRows, tables.getProductTable());
|
||||
}
|
||||
|
||||
private Set<Long> loadProductIdsInCategory(Long companyId, Long categoryId) {
|
||||
List<ProductPO> products = productMapper.selectList(new LambdaQueryWrapper<ProductPO>()
|
||||
.eq(ProductPO::getCompanyId, companyId)
|
||||
.eq(ProductPO::getCategoryId, categoryId)
|
||||
.select(ProductPO::getId));
|
||||
Set<Long> ids = new HashSet<>();
|
||||
for (ProductPO p : products) {
|
||||
if (p != null && p.getId() != null) {
|
||||
ids.add(p.getId());
|
||||
}
|
||||
}
|
||||
return ids;
|
||||
}
|
||||
|
||||
private static LocalDate resolveStart(CategoryOverviewQueryDTO dto) {
|
||||
if (dto.getDateRange() != null && !dto.getDateRange().isEmpty()) {
|
||||
return dto.getDateRange().get(0);
|
||||
}
|
||||
if (dto.getStartDate() != null) {
|
||||
return dto.getStartDate();
|
||||
}
|
||||
throw new BusinessException("日期范围不能为空");
|
||||
}
|
||||
|
||||
private static LocalDate resolveEnd(CategoryOverviewQueryDTO dto) {
|
||||
if (dto.getDateRange() != null && !dto.getDateRange().isEmpty()) {
|
||||
return dto.getDateRange().size() == 1
|
||||
? dto.getDateRange().get(0)
|
||||
: dto.getDateRange().get(1);
|
||||
}
|
||||
if (dto.getEndDate() != null) {
|
||||
return dto.getEndDate();
|
||||
}
|
||||
throw new BusinessException("日期范围不能为空");
|
||||
}
|
||||
|
||||
private void fillLegacyFlatFields(CategoryOverviewVO vo,
|
||||
BiFinanceKpiAssembler.Totals cur,
|
||||
BiFinanceKpiAssembler.Totals prev) {
|
||||
vo.setTotalSalesAmount(BiFinanceKpiAssembler.yuan2(cur.totalSales()));
|
||||
vo.setTotalOrderCount(cur.orderCount());
|
||||
vo.setRefundAmount(BiFinanceKpiAssembler.yuan2(cur.totalRefund()));
|
||||
vo.setAverageOrderValue(BiFinanceKpiAssembler.yuan2(cur.averageOrderValue()));
|
||||
vo.setTotalPromotionFee(BiFinanceKpiAssembler.yuan2(cur.promotion()));
|
||||
vo.setAverageFeeRatio(cur.totalSales().compareTo(BigDecimal.ZERO) > 0
|
||||
? cur.promotion().divide(cur.totalSales(), 4, RoundingMode.HALF_UP)
|
||||
: BigDecimal.ZERO);
|
||||
vo.setTotalTaxAmount(BiFinanceKpiAssembler.yuan2(cur.tax()));
|
||||
vo.setTotalProfitBeforeTax(BiFinanceKpiAssembler.yuan2(
|
||||
cur.grossOrder().subtract(cur.promotion()).subtract(cur.brush())));
|
||||
vo.setTotalNetProfitAfterTax(BiFinanceKpiAssembler.yuan2(cur.netProfit()));
|
||||
vo.setTotalROI(cur.promotion().compareTo(BigDecimal.ZERO) > 0
|
||||
? cur.totalSales().divide(cur.promotion(), 2, RoundingMode.HALF_UP)
|
||||
: BigDecimal.ZERO);
|
||||
vo.setMonthOverMonthGrowth(BiFinanceKpiAssembler.pctChange(cur.totalSales(), prev.totalSales()));
|
||||
}
|
||||
|
||||
private void fillTargets(CategoryOverviewVO vo, Long companyId, List<Long> shopIds,
|
||||
LocalDate startDate, LocalDate endDate,
|
||||
BigDecimal sales, int orderCount) {
|
||||
if (shopIds == null || shopIds.isEmpty()) {
|
||||
return;
|
||||
}
|
||||
List<LocalDate> months = new ArrayList<>();
|
||||
LocalDate cur = startDate.withDayOfMonth(1);
|
||||
LocalDate endMonth = endDate.withDayOfMonth(1);
|
||||
while (!cur.isAfter(endMonth)) {
|
||||
months.add(cur);
|
||||
cur = cur.plusMonths(1);
|
||||
}
|
||||
List<ShopMonthlyTargetPO> targets = months.isEmpty() ? List.of()
|
||||
: shopMonthlyTargetMapper.selectList(new LambdaQueryWrapper<ShopMonthlyTargetPO>()
|
||||
.eq(ShopMonthlyTargetPO::getCompanyId, companyId)
|
||||
.in(ShopMonthlyTargetPO::getShopId, shopIds)
|
||||
.in(ShopMonthlyTargetPO::getTargetMonth, months));
|
||||
|
||||
BigDecimal targetAmt = targets.stream()
|
||||
.map(t -> t.getTargetAmount() != null ? t.getTargetAmount() : BigDecimal.ZERO)
|
||||
.reduce(BigDecimal.ZERO, BigDecimal::add);
|
||||
int targetOrders = targets.stream()
|
||||
.mapToInt(t -> t.getTargetOrderCount() != null ? t.getTargetOrderCount() : 0)
|
||||
.sum();
|
||||
vo.setTotalTargetAmount(targetAmt);
|
||||
vo.setTotalTargetOrderCount(targetOrders);
|
||||
vo.setSalesAmountAchievementRate(achievement(sales, targetAmt));
|
||||
vo.setOrderCountAchievementRate(achievement(BigDecimal.valueOf(orderCount), BigDecimal.valueOf(targetOrders)));
|
||||
}
|
||||
|
||||
private static BigDecimal achievement(BigDecimal actual, BigDecimal target) {
|
||||
if (target != null && target.compareTo(BigDecimal.ZERO) > 0) {
|
||||
return BiFinanceKpiAssembler.nz(actual).divide(target, 4, RoundingMode.HALF_UP)
|
||||
.multiply(new BigDecimal("100"));
|
||||
}
|
||||
return BiFinanceKpiAssembler.nz(actual).compareTo(BigDecimal.ZERO) > 0
|
||||
? new BigDecimal("100") : BigDecimal.ZERO;
|
||||
}
|
||||
|
||||
private List<WorkbenchCostSliceVO> buildProductSalesShare(CategoryOverviewVO.ProductOverview overview,
|
||||
BigDecimal salesTotal) {
|
||||
if (overview == null || overview.getProducts() == null || overview.getProducts().isEmpty()) {
|
||||
return List.of();
|
||||
}
|
||||
BigDecimal base = BiFinanceKpiAssembler.nz(salesTotal);
|
||||
return overview.getProducts().stream()
|
||||
.filter(p -> BiFinanceKpiAssembler.nz(p.getSalesAmount()).compareTo(BigDecimal.ZERO) > 0)
|
||||
.sorted(Comparator.comparing(CategoryOverviewVO.ProductSummary::getSalesAmount,
|
||||
Comparator.nullsFirst(BigDecimal::compareTo)).reversed())
|
||||
.limit(PRODUCT_SHARE_LIMIT)
|
||||
.map(p -> {
|
||||
BigDecimal amt = BiFinanceKpiAssembler.nz(p.getSalesAmount());
|
||||
BigDecimal pct = base.compareTo(BigDecimal.ZERO) > 0
|
||||
? amt.multiply(new BigDecimal("100")).divide(base, 2, RoundingMode.HALF_UP)
|
||||
: BigDecimal.ZERO;
|
||||
String name = p.getProductName() != null ? p.getProductName() : "商品";
|
||||
return WorkbenchCostSliceVO.builder()
|
||||
.name(name)
|
||||
.value(BiFinanceKpiAssembler.yuan2(amt))
|
||||
.pct(pct)
|
||||
.build();
|
||||
})
|
||||
.collect(Collectors.toList());
|
||||
}
|
||||
|
||||
private Map<Long, ProductPO> loadProducts(Set<Long> productIds) {
|
||||
if (productIds == null || productIds.isEmpty()) {
|
||||
return Map.of();
|
||||
}
|
||||
Map<Long, ProductPO> map = new HashMap<>();
|
||||
for (ProductPO p : productMapper.selectByIds(productIds)) {
|
||||
if (p != null && p.getId() != null) {
|
||||
map.put(p.getId(), p);
|
||||
}
|
||||
}
|
||||
return map;
|
||||
}
|
||||
|
||||
private static CompanyOverviewVO.CategorySummary findCategoryRow(
|
||||
CompanyOverviewVO.CategoryOverview table, Long categoryId) {
|
||||
if (table == null || table.getCategories() == null || categoryId == null) {
|
||||
return null;
|
||||
}
|
||||
return table.getCategories().stream()
|
||||
.filter(c -> Objects.equals(c.getCategoryId(), categoryId))
|
||||
.findFirst()
|
||||
.orElse(null);
|
||||
}
|
||||
|
||||
private static CategoryOverviewVO.ProductOverview mapProductOverview(
|
||||
CompanyOverviewVO.CategoryOverview table, Map<Long, ProductPO> products, Long categoryId) {
|
||||
CategoryOverviewVO.ProductOverview po = new CategoryOverviewVO.ProductOverview();
|
||||
if (table == null || table.getCategories() == null) {
|
||||
po.setProducts(List.of());
|
||||
return po;
|
||||
}
|
||||
List<CategoryOverviewVO.ProductSummary> list = table.getCategories().stream()
|
||||
.filter(c -> c.getCategoryId() != null && c.getCategoryId() > 0)
|
||||
.filter(c -> {
|
||||
ProductPO p = products.get(c.getCategoryId());
|
||||
return p != null && Objects.equals(p.getCategoryId(), categoryId);
|
||||
})
|
||||
.map(c -> mapToProductSummary(c, c.getCategoryId(), products))
|
||||
.sorted(Comparator.comparing(CategoryOverviewVO.ProductSummary::getSalesAmount,
|
||||
Comparator.nullsFirst(BigDecimal::compareTo)).reversed())
|
||||
.collect(Collectors.toList());
|
||||
po.setProducts(list);
|
||||
po.setTotal(sumProductSummaries(list));
|
||||
return po;
|
||||
}
|
||||
|
||||
private static CategoryOverviewVO.ProductSummary sumProductSummaries(
|
||||
List<CategoryOverviewVO.ProductSummary> list) {
|
||||
CategoryOverviewVO.ProductSummary t = new CategoryOverviewVO.ProductSummary();
|
||||
t.setProductName("合计");
|
||||
if (list == null || list.isEmpty()) {
|
||||
return t;
|
||||
}
|
||||
BigDecimal sales = BigDecimal.ZERO;
|
||||
BigDecimal deal = BigDecimal.ZERO;
|
||||
BigDecimal refund = BigDecimal.ZERO;
|
||||
BigDecimal productCost = BigDecimal.ZERO;
|
||||
BigDecimal shipping = BigDecimal.ZERO;
|
||||
BigDecimal other = BigDecimal.ZERO;
|
||||
BigDecimal orderCost = BigDecimal.ZERO;
|
||||
BigDecimal promo = BigDecimal.ZERO;
|
||||
BigDecimal brush = BigDecimal.ZERO;
|
||||
BigDecimal profitBefore = BigDecimal.ZERO;
|
||||
BigDecimal tax = BigDecimal.ZERO;
|
||||
BigDecimal profitAfter = BigDecimal.ZERO;
|
||||
int salesOrders = 0;
|
||||
int dealOrders = 0;
|
||||
int salesQty = 0;
|
||||
int dealQty = 0;
|
||||
for (CategoryOverviewVO.ProductSummary p : list) {
|
||||
sales = sales.add(BiFinanceKpiAssembler.nz(p.getSalesAmount()));
|
||||
deal = deal.add(BiFinanceKpiAssembler.nz(p.getDealAmount()));
|
||||
refund = refund.add(BiFinanceKpiAssembler.nz(p.getRefundAmount()));
|
||||
productCost = productCost.add(BiFinanceKpiAssembler.nz(p.getProductCost()));
|
||||
shipping = shipping.add(BiFinanceKpiAssembler.nz(p.getShippingCost()));
|
||||
other = other.add(BiFinanceKpiAssembler.nz(p.getOtherCost()));
|
||||
orderCost = orderCost.add(BiFinanceKpiAssembler.nz(p.getOrderCost()));
|
||||
promo = promo.add(BiFinanceKpiAssembler.nz(p.getTotalPromotionFee()));
|
||||
brush = brush.add(BiFinanceKpiAssembler.nz(p.getBrushFee()));
|
||||
profitBefore = profitBefore.add(BiFinanceKpiAssembler.nz(p.getTotalProfitBeforeTax()));
|
||||
tax = tax.add(BiFinanceKpiAssembler.nz(p.getSalesTaxAmount()));
|
||||
profitAfter = profitAfter.add(BiFinanceKpiAssembler.nz(p.getProfitAfterTax()));
|
||||
salesOrders += p.getSalesOrderCount() != null ? p.getSalesOrderCount() : 0;
|
||||
dealOrders += p.getDealOrderCount() != null ? p.getDealOrderCount() : 0;
|
||||
salesQty += p.getSalesQuantitySum() != null ? p.getSalesQuantitySum() : 0;
|
||||
dealQty += p.getDealQuantitySum() != null ? p.getDealQuantitySum() : 0;
|
||||
}
|
||||
t.setSalesAmount(sales);
|
||||
t.setDealAmount(deal);
|
||||
t.setRefundAmount(refund);
|
||||
t.setProductCost(productCost);
|
||||
t.setShippingCost(shipping);
|
||||
t.setOtherCost(other);
|
||||
t.setOrderCost(orderCost);
|
||||
t.setTotalPromotionFee(promo);
|
||||
t.setBrushFee(brush);
|
||||
t.setTotalProfitBeforeTax(profitBefore);
|
||||
t.setSalesTaxAmount(tax);
|
||||
t.setProfitAfterTax(profitAfter);
|
||||
t.setSalesOrderCount(salesOrders);
|
||||
t.setDealOrderCount(dealOrders);
|
||||
t.setSalesQuantitySum(salesQty);
|
||||
t.setDealQuantitySum(dealQty);
|
||||
t.setSalesAverageOrderValue(salesOrders > 0
|
||||
? sales.divide(BigDecimal.valueOf(salesOrders), 2, RoundingMode.HALF_UP) : BigDecimal.ZERO);
|
||||
t.setDealAverageOrderValue(dealOrders > 0
|
||||
? deal.divide(BigDecimal.valueOf(dealOrders), 2, RoundingMode.HALF_UP) : BigDecimal.ZERO);
|
||||
t.setFeeRatio(sales.compareTo(BigDecimal.ZERO) > 0
|
||||
? promo.divide(sales, 4, RoundingMode.HALF_UP) : BigDecimal.ZERO);
|
||||
t.setRoi(promo.compareTo(BigDecimal.ZERO) > 0
|
||||
? sales.divide(promo, 2, RoundingMode.HALF_UP) : BigDecimal.ZERO);
|
||||
return t;
|
||||
}
|
||||
|
||||
private static CategoryOverviewVO.ProductSummary mapToProductSummary(
|
||||
CompanyOverviewVO.CategorySummary c, Long productId, Map<Long, ProductPO> products) {
|
||||
CategoryOverviewVO.ProductSummary p = new CategoryOverviewVO.ProductSummary();
|
||||
if (c == null) {
|
||||
return p;
|
||||
}
|
||||
p.setProductId(productId);
|
||||
ProductPO product = productId != null ? products.get(productId) : null;
|
||||
p.setProductName(product != null ? product.getName() : c.getCategoryName());
|
||||
p.setProductCode(product != null ? product.getProductCode() : null);
|
||||
p.setSalesAmount(c.getSalesAmount());
|
||||
p.setDealAmount(c.getDealAmount());
|
||||
p.setSalesOrderCount(c.getSalesOrderCount());
|
||||
p.setDealOrderCount(c.getDealOrderCount());
|
||||
p.setDealQuantitySum(c.getDealQuantitySum());
|
||||
p.setSalesQuantitySum(c.getSalesQuantitySum());
|
||||
p.setSalesAverageOrderValue(c.getSalesAverageOrderValue());
|
||||
p.setDealAverageOrderValue(c.getDealAverageOrderValue());
|
||||
p.setProductCost(c.getProductCost());
|
||||
p.setShippingCost(c.getShippingCost());
|
||||
p.setOtherCost(c.getOtherCost());
|
||||
p.setOrderCost(c.getOrderCost());
|
||||
p.setRefundAmount(c.getRefundAmount());
|
||||
p.setTotalPromotionFee(c.getTotalPromotionFee());
|
||||
p.setBrushFee(c.getBrushFee());
|
||||
p.setFeeRatio(c.getFeeRatio());
|
||||
p.setTotalProfitBeforeTax(c.getTotalProfitBeforeTax());
|
||||
p.setSalesTaxAmount(c.getSalesTaxAmount());
|
||||
p.setProfitAfterTax(c.getProfitAfterTax());
|
||||
p.setRoi(c.getRoi());
|
||||
return p;
|
||||
}
|
||||
|
||||
private static void fillProductSalesTop10(CategoryOverviewVO vo) {
|
||||
CategoryOverviewVO.ProductOverview po = vo.getProductOverview();
|
||||
if (po == null || po.getProducts() == null || po.getProducts().isEmpty()) {
|
||||
vo.setProductSalesTop10(Collections.emptyList());
|
||||
return;
|
||||
}
|
||||
vo.setProductSalesTop10(po.getProducts().stream()
|
||||
.sorted(Comparator.comparing(
|
||||
(CategoryOverviewVO.ProductSummary p) ->
|
||||
p.getSalesOrderCount() != null ? p.getSalesOrderCount() : 0,
|
||||
Comparator.reverseOrder()))
|
||||
.limit(10)
|
||||
.map(p -> {
|
||||
CategoryOverviewVO.ProductSalesRankItem item =
|
||||
new CategoryOverviewVO.ProductSalesRankItem();
|
||||
item.setProductId(p.getProductId());
|
||||
item.setProductName(p.getProductName());
|
||||
item.setProductCode(p.getProductCode());
|
||||
item.setOrderCount(p.getSalesOrderCount());
|
||||
item.setSalesAmount(p.getSalesAmount());
|
||||
return item;
|
||||
})
|
||||
.collect(Collectors.toList()));
|
||||
}
|
||||
|
||||
private record PeriodBundle(List<Long> shopIds,
|
||||
Set<Long> productIds,
|
||||
BiFinanceKpiAssembler.Totals totals,
|
||||
List<OverviewAggRows.DailyRow> dailyRows,
|
||||
CompanyOverviewVO.CategoryOverview productTable) {
|
||||
}
|
||||
}
|
||||
+85
@@ -0,0 +1,85 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.bi.infra.config;
|
||||
|
||||
import org.bson.types.Decimal128;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.core.convert.converter.Converter;
|
||||
import org.springframework.data.convert.ReadingConverter;
|
||||
import org.springframework.data.convert.WritingConverter;
|
||||
import org.springframework.data.mongodb.core.convert.MongoCustomConversions;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.time.Instant;
|
||||
import java.time.LocalDate;
|
||||
import java.time.ZoneId;
|
||||
import java.time.ZoneOffset;
|
||||
import java.time.ZonedDateTime;
|
||||
import java.util.Date;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* Mongo 自定义转换:
|
||||
* <ul>
|
||||
* <li>BigDecimal ↔ Decimal128</li>
|
||||
* <li>LocalDate ↔ BSON Date:按<strong>日历日 UTC 0 点</strong>落库(仍是时间类型,可排序/范围查询;
|
||||
* Compass 显示为 {@code yyyy-MM-ddT00:00:00.000Z},避免东八区把「上海 0 点」看成前一天 16:00Z)</li>
|
||||
* </ul>
|
||||
*/
|
||||
@Configuration
|
||||
public class BiMongoConversionsConfig {
|
||||
|
||||
private static final ZoneId BIZ_ZONE = ZoneId.of("Asia/Shanghai");
|
||||
|
||||
@Bean
|
||||
public MongoCustomConversions mongoCustomConversions() {
|
||||
return new MongoCustomConversions(List.of(
|
||||
new BigDecimalToDecimal128Converter(),
|
||||
new Decimal128ToBigDecimalConverter(),
|
||||
new LocalDateToUtcDateConverter(),
|
||||
new DateToLocalDateConverter()));
|
||||
}
|
||||
|
||||
@WritingConverter
|
||||
static class BigDecimalToDecimal128Converter implements Converter<BigDecimal, Decimal128> {
|
||||
@Override
|
||||
public Decimal128 convert(BigDecimal source) {
|
||||
return new Decimal128(source);
|
||||
}
|
||||
}
|
||||
|
||||
@ReadingConverter
|
||||
static class Decimal128ToBigDecimalConverter implements Converter<Decimal128, BigDecimal> {
|
||||
@Override
|
||||
public BigDecimal convert(Decimal128 source) {
|
||||
return source.bigDecimalValue();
|
||||
}
|
||||
}
|
||||
|
||||
/** 日历日 → UTC 午夜 Date,例如 2026-08-10 → 2026-08-10T00:00:00.000Z */
|
||||
@WritingConverter
|
||||
static class LocalDateToUtcDateConverter implements Converter<LocalDate, Date> {
|
||||
@Override
|
||||
public Date convert(LocalDate source) {
|
||||
return Date.from(source.atStartOfDay(ZoneOffset.UTC).toInstant());
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Date → 日历日。
|
||||
* 新数据:UTC 午夜 → 按 UTC 取日期;
|
||||
* 旧数据:曾按 JVM/上海 0 点写入(常见为前一天 16:00Z)→ 按 Asia/Shanghai 取日期。
|
||||
*/
|
||||
@ReadingConverter
|
||||
static class DateToLocalDateConverter implements Converter<Date, LocalDate> {
|
||||
@Override
|
||||
public LocalDate convert(Date source) {
|
||||
Instant instant = source.toInstant();
|
||||
ZonedDateTime utc = instant.atZone(ZoneOffset.UTC);
|
||||
if (utc.getHour() == 0 && utc.getMinute() == 0 && utc.getSecond() == 0
|
||||
&& utc.getNano() == 0) {
|
||||
return utc.toLocalDate();
|
||||
}
|
||||
return instant.atZone(BIZ_ZONE).toLocalDate();
|
||||
}
|
||||
}
|
||||
}
|
||||
+35
@@ -0,0 +1,35 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.bi.infra.config;
|
||||
|
||||
import lombok.Data;
|
||||
import org.springframework.boot.context.properties.ConfigurationProperties;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
@Data
|
||||
@Component
|
||||
@ConfigurationProperties(prefix = "ecom.bi.stat")
|
||||
public class BiStatProperties {
|
||||
|
||||
/** 日计算锁 TTL(秒) */
|
||||
private long lockTtlSeconds = 600;
|
||||
|
||||
/** 遇同日锁忙时延迟毫秒 */
|
||||
private long incDelayMs = 5000;
|
||||
|
||||
/** 延迟最大重试次数 */
|
||||
private int incMaxRetry = 20;
|
||||
|
||||
/** BI 全量队列消费者并发(支持 "n" 或 "m-n") */
|
||||
private String fullListenerConcurrency = "2-4";
|
||||
|
||||
/** BI 增量队列消费者并发 */
|
||||
private String incListenerConcurrency = "2-4";
|
||||
|
||||
/** 增量店态成功/跳过写库节流秒数 */
|
||||
private long incStatusFlushSeconds = 30;
|
||||
|
||||
/** 增量健康度:滞后阈值(分钟) */
|
||||
private int incLagThresholdMinutes = 10;
|
||||
|
||||
/** 增量健康度:活跃判定窗口(小时);窗内无订单且无成功增量视为空闲 */
|
||||
private int incActivityWindowHours = 24;
|
||||
}
|
||||
+186
@@ -0,0 +1,186 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.bi.infra.config;
|
||||
|
||||
import org.springframework.amqp.core.Binding;
|
||||
import org.springframework.amqp.core.BindingBuilder;
|
||||
import org.springframework.amqp.core.Queue;
|
||||
import org.springframework.amqp.core.QueueBuilder;
|
||||
import org.springframework.amqp.core.TopicExchange;
|
||||
import org.springframework.amqp.rabbit.config.SimpleRabbitListenerContainerFactory;
|
||||
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
|
||||
import org.springframework.amqp.rabbit.core.RabbitTemplate;
|
||||
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
|
||||
import org.springframework.amqp.support.converter.MessageConverter;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import top.xyquan.ecomdmbbackend.common.mq.OrderMqConstants;
|
||||
|
||||
@Configuration
|
||||
public class RabbitBiConfig {
|
||||
|
||||
@Bean
|
||||
public MessageConverter jacksonMessageConverter() {
|
||||
return new Jackson2JsonMessageConverter();
|
||||
}
|
||||
|
||||
@Bean
|
||||
public RabbitTemplate rabbitTemplate(ConnectionFactory connectionFactory, MessageConverter jacksonMessageConverter) {
|
||||
RabbitTemplate template = new RabbitTemplate(connectionFactory);
|
||||
template.setMessageConverter(jacksonMessageConverter);
|
||||
return template;
|
||||
}
|
||||
|
||||
@Bean
|
||||
public SimpleRabbitListenerContainerFactory rabbitListenerContainerFactory(
|
||||
ConnectionFactory connectionFactory, MessageConverter jacksonMessageConverter) {
|
||||
SimpleRabbitListenerContainerFactory factory = new SimpleRabbitListenerContainerFactory();
|
||||
factory.setConnectionFactory(connectionFactory);
|
||||
factory.setMessageConverter(jacksonMessageConverter);
|
||||
return factory;
|
||||
}
|
||||
|
||||
@Bean
|
||||
public TopicExchange orderTopicExchange() {
|
||||
return new TopicExchange(OrderMqConstants.EXCHANGE, true, false);
|
||||
}
|
||||
|
||||
@Bean
|
||||
public Queue orderConvertPddFullQueue() {
|
||||
return QueueBuilder.durable(OrderMqConstants.QUEUE_ORDER_CONVERT_PDD_FULL)
|
||||
.withArgument("x-dead-letter-exchange", "")
|
||||
.withArgument("x-dead-letter-routing-key", OrderMqConstants.QUEUE_ORDER_CONVERT_PDD_FULL_DLQ)
|
||||
.build();
|
||||
}
|
||||
|
||||
@Bean
|
||||
public Queue orderConvertPddFullDlq() {
|
||||
return QueueBuilder.durable(OrderMqConstants.QUEUE_ORDER_CONVERT_PDD_FULL_DLQ).build();
|
||||
}
|
||||
|
||||
@Bean
|
||||
public Binding orderConvertPddFullBinding(Queue orderConvertPddFullQueue, TopicExchange orderTopicExchange) {
|
||||
return BindingBuilder.bind(orderConvertPddFullQueue)
|
||||
.to(orderTopicExchange)
|
||||
.with(OrderMqConstants.RK_ORDER_CONVERT_PDD_FULL);
|
||||
}
|
||||
|
||||
@Bean
|
||||
public Queue orderConvertPddIncQueue() {
|
||||
return QueueBuilder.durable(OrderMqConstants.QUEUE_ORDER_CONVERT_PDD_INC)
|
||||
.withArgument("x-dead-letter-exchange", "")
|
||||
.withArgument("x-dead-letter-routing-key", OrderMqConstants.QUEUE_ORDER_CONVERT_PDD_INC_DLQ)
|
||||
.build();
|
||||
}
|
||||
|
||||
@Bean
|
||||
public Queue orderConvertPddIncDlq() {
|
||||
return QueueBuilder.durable(OrderMqConstants.QUEUE_ORDER_CONVERT_PDD_INC_DLQ).build();
|
||||
}
|
||||
|
||||
@Bean
|
||||
public Binding orderConvertPddIncBinding(Queue orderConvertPddIncQueue, TopicExchange orderTopicExchange) {
|
||||
return BindingBuilder.bind(orderConvertPddIncQueue)
|
||||
.to(orderTopicExchange)
|
||||
.with(OrderMqConstants.RK_ORDER_CONVERT_PDD_INC);
|
||||
}
|
||||
|
||||
@Bean
|
||||
public Queue orderProductAutoCreatePddQueue() {
|
||||
return QueueBuilder.durable(OrderMqConstants.QUEUE_ORDER_PRODUCT_AUTO_CREATE_PDD)
|
||||
.withArgument("x-dead-letter-exchange", "")
|
||||
.withArgument("x-dead-letter-routing-key", OrderMqConstants.QUEUE_ORDER_PRODUCT_AUTO_CREATE_PDD_DLQ)
|
||||
.build();
|
||||
}
|
||||
|
||||
@Bean
|
||||
public Queue orderProductAutoCreatePddDlq() {
|
||||
return QueueBuilder.durable(OrderMqConstants.QUEUE_ORDER_PRODUCT_AUTO_CREATE_PDD_DLQ).build();
|
||||
}
|
||||
|
||||
@Bean
|
||||
public Binding orderProductAutoCreatePddBinding(Queue orderProductAutoCreatePddQueue,
|
||||
TopicExchange orderTopicExchange) {
|
||||
return BindingBuilder.bind(orderProductAutoCreatePddQueue)
|
||||
.to(orderTopicExchange)
|
||||
.with(OrderMqConstants.RK_ORDER_PRODUCT_AUTO_CREATE_PDD);
|
||||
}
|
||||
|
||||
@Bean
|
||||
public Queue biStatFullQueue() {
|
||||
return QueueBuilder.durable(OrderMqConstants.QUEUE_BI_STAT_FULL)
|
||||
.withArgument("x-dead-letter-exchange", "")
|
||||
.withArgument("x-dead-letter-routing-key", OrderMqConstants.QUEUE_BI_STAT_FULL_DLQ)
|
||||
.build();
|
||||
}
|
||||
|
||||
@Bean
|
||||
public Queue biStatFullDlq() {
|
||||
return QueueBuilder.durable(OrderMqConstants.QUEUE_BI_STAT_FULL_DLQ).build();
|
||||
}
|
||||
|
||||
@Bean
|
||||
public Binding biStatFullBinding(Queue biStatFullQueue, TopicExchange orderTopicExchange) {
|
||||
return BindingBuilder.bind(biStatFullQueue)
|
||||
.to(orderTopicExchange)
|
||||
.with(OrderMqConstants.RK_BI_STAT_FULL);
|
||||
}
|
||||
|
||||
@Bean
|
||||
public Queue biStatIncQueue() {
|
||||
return QueueBuilder.durable(OrderMqConstants.QUEUE_BI_STAT_INC)
|
||||
.withArgument("x-dead-letter-exchange", "")
|
||||
.withArgument("x-dead-letter-routing-key", OrderMqConstants.QUEUE_BI_STAT_INC_DLQ)
|
||||
.build();
|
||||
}
|
||||
|
||||
@Bean
|
||||
public Queue biStatIncDlq() {
|
||||
return QueueBuilder.durable(OrderMqConstants.QUEUE_BI_STAT_INC_DLQ).build();
|
||||
}
|
||||
|
||||
@Bean
|
||||
public Binding biStatIncBinding(Queue biStatIncQueue, TopicExchange orderTopicExchange) {
|
||||
return BindingBuilder.bind(biStatIncQueue)
|
||||
.to(orderTopicExchange)
|
||||
.with(OrderMqConstants.RK_BI_STAT_INC);
|
||||
}
|
||||
|
||||
@Bean
|
||||
public Queue orderSyncPddFullQueue() {
|
||||
return QueueBuilder.durable(OrderMqConstants.QUEUE_ORDER_SYNC_PDD_FULL)
|
||||
.withArgument("x-dead-letter-exchange", "")
|
||||
.withArgument("x-dead-letter-routing-key", OrderMqConstants.QUEUE_ORDER_SYNC_PDD_FULL_DLQ)
|
||||
.build();
|
||||
}
|
||||
|
||||
@Bean
|
||||
public Queue orderSyncPddFullDlq() {
|
||||
return QueueBuilder.durable(OrderMqConstants.QUEUE_ORDER_SYNC_PDD_FULL_DLQ).build();
|
||||
}
|
||||
|
||||
@Bean
|
||||
public Binding orderSyncPddFullBinding(Queue orderSyncPddFullQueue, TopicExchange orderTopicExchange) {
|
||||
return BindingBuilder.bind(orderSyncPddFullQueue)
|
||||
.to(orderTopicExchange)
|
||||
.with(OrderMqConstants.RK_ORDER_SYNC_PDD_FULL);
|
||||
}
|
||||
|
||||
@Bean
|
||||
public Queue orderSyncPddIncQueue() {
|
||||
return QueueBuilder.durable(OrderMqConstants.QUEUE_ORDER_SYNC_PDD_INC)
|
||||
.withArgument("x-dead-letter-exchange", "")
|
||||
.withArgument("x-dead-letter-routing-key", OrderMqConstants.QUEUE_ORDER_SYNC_PDD_INC_DLQ)
|
||||
.build();
|
||||
}
|
||||
|
||||
@Bean
|
||||
public Queue orderSyncPddIncDlq() {
|
||||
return QueueBuilder.durable(OrderMqConstants.QUEUE_ORDER_SYNC_PDD_INC_DLQ).build();
|
||||
}
|
||||
|
||||
@Bean
|
||||
public Binding orderSyncPddIncBinding(Queue orderSyncPddIncQueue, TopicExchange orderTopicExchange) {
|
||||
return BindingBuilder.bind(orderSyncPddIncQueue)
|
||||
.to(orderTopicExchange)
|
||||
.with(OrderMqConstants.RK_ORDER_SYNC_PDD_INC);
|
||||
}
|
||||
}
|
||||
+99
@@ -0,0 +1,99 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.bi.infra.lock;
|
||||
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.data.redis.core.StringRedisTemplate;
|
||||
import org.springframework.stereotype.Component;
|
||||
import top.xyquan.ecomdmbbackend.modules.bi.infra.config.BiStatProperties;
|
||||
|
||||
import java.time.Duration;
|
||||
import java.time.Instant;
|
||||
import java.time.LocalDate;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.UUID;
|
||||
|
||||
/**
|
||||
* BI 店+日计算锁(同日 FULL/INC 互斥;不同日可并行)。
|
||||
* 全量抢锁时登记会话 snapshotTime,供同日进行中的增量跳过/延后;
|
||||
* 持久化的「最新全量快照时间」以该日 Mongo 文档 dbSnapshotTime 为准。
|
||||
*/
|
||||
@Component
|
||||
@RequiredArgsConstructor
|
||||
public class BiStatComputeLock {
|
||||
|
||||
private static final String LOCK_PREFIX = "bi:stat:lock:";
|
||||
|
||||
private final StringRedisTemplate stringRedisTemplate;
|
||||
private final BiStatProperties biStatProperties;
|
||||
|
||||
/**
|
||||
* 抢占 (companyId, shopId, statDate) 日锁。
|
||||
*
|
||||
* @param snapshotTimeOrNull 全量传入会话快照时刻;增量传 null
|
||||
*/
|
||||
public Optional<Session> tryLock(Long companyId, Long shopId, LocalDate statDate,
|
||||
Instant snapshotTimeOrNull) {
|
||||
if (companyId == null || shopId == null || statDate == null) {
|
||||
return Optional.empty();
|
||||
}
|
||||
String key = lockKey(companyId, shopId, statDate);
|
||||
String token = UUID.randomUUID().toString();
|
||||
long ttl = Math.max(biStatProperties.getLockTtlSeconds(), 60);
|
||||
Boolean ok = stringRedisTemplate.opsForValue()
|
||||
.setIfAbsent(key + ":hold", token, Duration.ofSeconds(ttl));
|
||||
if (!Boolean.TRUE.equals(ok)) {
|
||||
return Optional.empty();
|
||||
}
|
||||
Map<String, String> meta = new HashMap<>();
|
||||
meta.put("token", token);
|
||||
if (snapshotTimeOrNull != null) {
|
||||
meta.put("snapshotTime", String.valueOf(snapshotTimeOrNull.toEpochMilli()));
|
||||
}
|
||||
stringRedisTemplate.opsForHash().putAll(key, meta);
|
||||
stringRedisTemplate.expire(key, Duration.ofSeconds(ttl));
|
||||
return Optional.of(new Session(key, token, snapshotTimeOrNull, companyId, shopId, statDate));
|
||||
}
|
||||
|
||||
public Optional<Instant> peekSessionSnapshot(Long companyId, Long shopId, LocalDate statDate) {
|
||||
Object v = stringRedisTemplate.opsForHash()
|
||||
.get(lockKey(companyId, shopId, statDate), "snapshotTime");
|
||||
return parseInstant(v);
|
||||
}
|
||||
|
||||
public boolean isLocked(Long companyId, Long shopId, LocalDate statDate) {
|
||||
return Boolean.TRUE.equals(stringRedisTemplate.hasKey(
|
||||
lockKey(companyId, shopId, statDate) + ":hold"));
|
||||
}
|
||||
|
||||
public void unlock(Session session) {
|
||||
if (session == null) {
|
||||
return;
|
||||
}
|
||||
String holdKey = session.key() + ":hold";
|
||||
String current = stringRedisTemplate.opsForValue().get(holdKey);
|
||||
if (session.token().equals(current)) {
|
||||
stringRedisTemplate.delete(holdKey);
|
||||
stringRedisTemplate.delete(session.key());
|
||||
}
|
||||
}
|
||||
|
||||
private static String lockKey(Long companyId, Long shopId, LocalDate statDate) {
|
||||
return LOCK_PREFIX + companyId + ":" + shopId + ":" + statDate;
|
||||
}
|
||||
|
||||
private static Optional<Instant> parseInstant(Object v) {
|
||||
if (v == null) {
|
||||
return Optional.empty();
|
||||
}
|
||||
try {
|
||||
return Optional.of(Instant.ofEpochMilli(Long.parseLong(v.toString())));
|
||||
} catch (NumberFormatException e) {
|
||||
return Optional.empty();
|
||||
}
|
||||
}
|
||||
|
||||
public record Session(String key, String token, Instant snapshotTime,
|
||||
Long companyId, Long shopId, LocalDate statDate) {
|
||||
}
|
||||
}
|
||||
+30
@@ -0,0 +1,30 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.bi.messaging;
|
||||
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Builder;
|
||||
import lombok.Data;
|
||||
import lombok.NoArgsConstructor;
|
||||
|
||||
import java.time.OffsetDateTime;
|
||||
|
||||
@Data
|
||||
@Builder
|
||||
@NoArgsConstructor
|
||||
@AllArgsConstructor
|
||||
public class BiFullCalcMessage {
|
||||
|
||||
private String messageId;
|
||||
private Long companyId;
|
||||
private Long shopId;
|
||||
private String platformCode;
|
||||
/** yyyy-MM-dd */
|
||||
private String statDate;
|
||||
private String syncBatchId;
|
||||
/** 上游全量转换任务 id(可选) */
|
||||
private Long convertTaskId;
|
||||
/** BI 全量计算任务 id;有则消费侧回写控制面 */
|
||||
private Long calcTaskId;
|
||||
private OffsetDateTime occurredAt;
|
||||
/** 锁冲突延迟重投次数 */
|
||||
private Integer retryCount;
|
||||
}
|
||||
+38
@@ -0,0 +1,38 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.bi.messaging;
|
||||
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Builder;
|
||||
import lombok.Data;
|
||||
import lombok.NoArgsConstructor;
|
||||
|
||||
import java.time.OffsetDateTime;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* 增量计算消息:转换侧算好各维度加减量,BI 侧按快照决定跳过或累加。
|
||||
*/
|
||||
@Data
|
||||
@Builder
|
||||
@NoArgsConstructor
|
||||
@AllArgsConstructor
|
||||
public class BiIncCalcMessage {
|
||||
|
||||
private String messageId;
|
||||
private Long companyId;
|
||||
private Long shopId;
|
||||
private String platformCode;
|
||||
/** yyyy-MM-dd */
|
||||
private String statDate;
|
||||
/**
|
||||
* 转换完成时内部订单的更新时间(ec_order.update_time / last_mapped_time)。
|
||||
* BI 与 Mongo 文档 dbSnapshotTime(最新一次全量事务快照开启时间)比较:≤ 快照则跳过。
|
||||
*/
|
||||
private OffsetDateTime internalOrderUpdateTime;
|
||||
private Long orderId;
|
||||
private Long channelOrderId;
|
||||
private BiStatMetricDelta shopDelta;
|
||||
private List<BiProductStatDelta> productDeltas;
|
||||
private List<BiSkuStatDelta> skuDeltas;
|
||||
private OffsetDateTime occurredAt;
|
||||
private Integer retryCount;
|
||||
}
|
||||
+16
@@ -0,0 +1,16 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.bi.messaging;
|
||||
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Builder;
|
||||
import lombok.Data;
|
||||
import lombok.NoArgsConstructor;
|
||||
|
||||
@Data
|
||||
@Builder
|
||||
@NoArgsConstructor
|
||||
@AllArgsConstructor
|
||||
public class BiProductStatDelta {
|
||||
|
||||
private Long productId;
|
||||
private BiStatMetricDelta metrics;
|
||||
}
|
||||
+18
@@ -0,0 +1,18 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.bi.messaging;
|
||||
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Builder;
|
||||
import lombok.Data;
|
||||
import lombok.NoArgsConstructor;
|
||||
|
||||
@Data
|
||||
@Builder
|
||||
@NoArgsConstructor
|
||||
@AllArgsConstructor
|
||||
public class BiSkuStatDelta {
|
||||
|
||||
private Long productId;
|
||||
/** 内部 SKU 主键(ec_product_sku.id);未绑定为 0 */
|
||||
private Long productSkuId;
|
||||
private BiStatMetricDelta metrics;
|
||||
}
|
||||
+105
@@ -0,0 +1,105 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.bi.messaging;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonAlias;
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Builder;
|
||||
import lombok.Data;
|
||||
import lombok.NoArgsConstructor;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
|
||||
/** 单维度指标增量(可正可负);净销售由读侧「成交 − 退款」推导,不存 sales*。 */
|
||||
@Data
|
||||
@Builder
|
||||
@NoArgsConstructor
|
||||
@AllArgsConstructor
|
||||
public class BiStatMetricDelta {
|
||||
|
||||
/** JsonAlias:兼容迁移前队列中仍带 gmv* 的旧消息 */
|
||||
@JsonAlias("gmvAmount")
|
||||
private BigDecimal dealAmount;
|
||||
@JsonAlias("gmvOrderCount")
|
||||
private Integer dealOrderCount;
|
||||
@JsonAlias("gmvQuantitySum")
|
||||
private Integer dealQuantitySum;
|
||||
private BigDecimal refundAmount;
|
||||
private Integer refundOrderCount;
|
||||
private Integer refundQuantitySum;
|
||||
private BigDecimal serviceFee;
|
||||
private BigDecimal productCost;
|
||||
private BigDecimal freightCost;
|
||||
private BigDecimal otherCost;
|
||||
|
||||
public static BiStatMetricDelta zeros() {
|
||||
return BiStatMetricDelta.builder()
|
||||
.dealAmount(BigDecimal.ZERO)
|
||||
.dealOrderCount(0)
|
||||
.dealQuantitySum(0)
|
||||
.refundAmount(BigDecimal.ZERO)
|
||||
.refundOrderCount(0)
|
||||
.refundQuantitySum(0)
|
||||
.serviceFee(BigDecimal.ZERO)
|
||||
.productCost(BigDecimal.ZERO)
|
||||
.freightCost(BigDecimal.ZERO)
|
||||
.otherCost(BigDecimal.ZERO)
|
||||
.build();
|
||||
}
|
||||
|
||||
public BiStatMetricDelta negate() {
|
||||
return BiStatMetricDelta.builder()
|
||||
.dealAmount(nz(dealAmount).negate())
|
||||
.dealOrderCount(-(dealOrderCount == null ? 0 : dealOrderCount))
|
||||
.dealQuantitySum(-(dealQuantitySum == null ? 0 : dealQuantitySum))
|
||||
.refundAmount(nz(refundAmount).negate())
|
||||
.refundOrderCount(-(refundOrderCount == null ? 0 : refundOrderCount))
|
||||
.refundQuantitySum(-(refundQuantitySum == null ? 0 : refundQuantitySum))
|
||||
.serviceFee(nz(serviceFee).negate())
|
||||
.productCost(nz(productCost).negate())
|
||||
.freightCost(nz(freightCost).negate())
|
||||
.otherCost(nz(otherCost).negate())
|
||||
.build();
|
||||
}
|
||||
|
||||
public BiStatMetricDelta plus(BiStatMetricDelta o) {
|
||||
if (o == null) {
|
||||
return this;
|
||||
}
|
||||
return BiStatMetricDelta.builder()
|
||||
.dealAmount(nz(dealAmount).add(nz(o.dealAmount)))
|
||||
.dealOrderCount(nzi(dealOrderCount) + nzi(o.dealOrderCount))
|
||||
.dealQuantitySum(nzi(dealQuantitySum) + nzi(o.dealQuantitySum))
|
||||
.refundAmount(nz(refundAmount).add(nz(o.refundAmount)))
|
||||
.refundOrderCount(nzi(refundOrderCount) + nzi(o.refundOrderCount))
|
||||
.refundQuantitySum(nzi(refundQuantitySum) + nzi(o.refundQuantitySum))
|
||||
.serviceFee(nz(serviceFee).add(nz(o.serviceFee)))
|
||||
.productCost(nz(productCost).add(nz(o.productCost)))
|
||||
.freightCost(nz(freightCost).add(nz(o.freightCost)))
|
||||
.otherCost(nz(otherCost).add(nz(o.otherCost)))
|
||||
.build();
|
||||
}
|
||||
|
||||
public BiStatMetricDelta minus(BiStatMetricDelta o) {
|
||||
return plus(o == null ? null : o.negate());
|
||||
}
|
||||
|
||||
public boolean isAllZero() {
|
||||
return nz(dealAmount).signum() == 0
|
||||
&& nzi(dealOrderCount) == 0
|
||||
&& nzi(dealQuantitySum) == 0
|
||||
&& nz(refundAmount).signum() == 0
|
||||
&& nzi(refundOrderCount) == 0
|
||||
&& nzi(refundQuantitySum) == 0
|
||||
&& nz(serviceFee).signum() == 0
|
||||
&& nz(productCost).signum() == 0
|
||||
&& nz(freightCost).signum() == 0
|
||||
&& nz(otherCost).signum() == 0;
|
||||
}
|
||||
|
||||
private static BigDecimal nz(BigDecimal v) {
|
||||
return v != null ? v : BigDecimal.ZERO;
|
||||
}
|
||||
|
||||
private static int nzi(Integer v) {
|
||||
return v != null ? v : 0;
|
||||
}
|
||||
}
|
||||
+91
@@ -0,0 +1,91 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.bi.orderstat.consumer;
|
||||
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.amqp.rabbit.annotation.RabbitListener;
|
||||
import org.springframework.stereotype.Component;
|
||||
import top.xyquan.ecomdmbbackend.common.mq.DelayedMqRepublisher;
|
||||
import top.xyquan.ecomdmbbackend.common.mq.OrderMqConstants;
|
||||
import top.xyquan.ecomdmbbackend.modules.bi.infra.config.BiStatProperties;
|
||||
import top.xyquan.ecomdmbbackend.modules.bi.messaging.BiFullCalcMessage;
|
||||
import top.xyquan.ecomdmbbackend.common.time.BizClock;
|
||||
import top.xyquan.ecomdmbbackend.modules.bi.orderstat.service.BiOrderStatCalcTaskService;
|
||||
import top.xyquan.ecomdmbbackend.modules.bi.orderstat.service.BiOrderStatDirtyDayService;
|
||||
import top.xyquan.ecomdmbbackend.modules.bi.orderstat.service.OrderDailyStatComputeService;
|
||||
|
||||
import java.time.LocalDate;
|
||||
|
||||
/**
|
||||
* BI 全量日计算消费者;有 calcTaskId 时回写全量计算控制面。
|
||||
*/
|
||||
@Slf4j
|
||||
@Component
|
||||
@RequiredArgsConstructor
|
||||
public class BiStatFullConsumer {
|
||||
|
||||
private final OrderDailyStatComputeService computeService;
|
||||
private final BiStatProperties biStatProperties;
|
||||
private final DelayedMqRepublisher delayedMqRepublisher;
|
||||
private final BiOrderStatCalcTaskService calcTaskService;
|
||||
private final BiOrderStatDirtyDayService dirtyDayService;
|
||||
|
||||
@RabbitListener(
|
||||
queues = OrderMqConstants.QUEUE_BI_STAT_FULL,
|
||||
concurrency = "${ecom.bi.stat.full-listener-concurrency:2-4}")
|
||||
public void onMessage(BiFullCalcMessage message) {
|
||||
if (message == null || message.getCompanyId() == null || message.getShopId() == null
|
||||
|| message.getStatDate() == null) {
|
||||
log.warn("BI full 消息非法: {}", message);
|
||||
return;
|
||||
}
|
||||
LocalDate statDate = LocalDate.parse(message.getStatDate());
|
||||
Long calcTaskId = message.getCalcTaskId();
|
||||
log.info("收到 BI 全量计算 messageId={} shopId={} statDate={} calcTaskId={}",
|
||||
message.getMessageId(), message.getShopId(), statDate, calcTaskId);
|
||||
if (calcTaskId != null) {
|
||||
calcTaskService.markDayRunning(calcTaskId, statDate);
|
||||
}
|
||||
try {
|
||||
boolean ok = computeService.tryComputeFull(
|
||||
message.getCompanyId(),
|
||||
message.getShopId(),
|
||||
statDate,
|
||||
message.getPlatformCode());
|
||||
if (!ok) {
|
||||
delayAndRepublish(message);
|
||||
return;
|
||||
}
|
||||
if (calcTaskId != null) {
|
||||
calcTaskService.markDaySuccess(calcTaskId, statDate, null);
|
||||
}
|
||||
dirtyDayService.markClean(message.getCompanyId(), message.getShopId(), statDate);
|
||||
} catch (Exception e) {
|
||||
if (calcTaskId != null) {
|
||||
calcTaskService.markDayFailed(calcTaskId, statDate, e.getMessage());
|
||||
}
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
|
||||
private void delayAndRepublish(BiFullCalcMessage message) {
|
||||
int retry = message.getRetryCount() == null ? 0 : message.getRetryCount();
|
||||
if (retry >= biStatProperties.getIncMaxRetry()) {
|
||||
if (message.getCalcTaskId() != null && message.getStatDate() != null) {
|
||||
calcTaskService.markDayFailed(
|
||||
message.getCalcTaskId(),
|
||||
LocalDate.parse(message.getStatDate()),
|
||||
"日锁延迟重试超限");
|
||||
}
|
||||
throw new IllegalStateException("BI full 延迟重试超限: " + message.getMessageId());
|
||||
}
|
||||
message.setRetryCount(retry + 1);
|
||||
message.setOccurredAt(BizClock.nowOdt());
|
||||
delayedMqRepublisher.republish(
|
||||
OrderMqConstants.EXCHANGE,
|
||||
OrderMqConstants.RK_BI_STAT_FULL,
|
||||
message,
|
||||
biStatProperties.getIncDelayMs());
|
||||
log.info("BI full 日锁占用,已安排延迟重投 messageId={} shopId={} statDate={} retry={}",
|
||||
message.getMessageId(), message.getShopId(), message.getStatDate(), message.getRetryCount());
|
||||
}
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user