mirror of
https://gitee.com/qqtt-ah/ecom-dmb.git
synced 2026-11-24 07:09:20 +08:00
refacor: 重构目录架构
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());
|
||||
}
|
||||
}
|
||||
+99
@@ -0,0 +1,99 @@
|
||||
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/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();
|
||||
}
|
||||
}
|
||||
+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;
|
||||
}
|
||||
+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);
|
||||
}
|
||||
}
|
||||
+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();
|
||||
}
|
||||
}
|
||||
+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 = "";
|
||||
|
||||
/**
|
||||
* Agent 绑定的公司 ID(BI 等读模型按租户隔离);为空则业务 tool 会失败。
|
||||
*/
|
||||
private Long companyId;
|
||||
}
|
||||
+61
@@ -0,0 +1,61 @@
|
||||
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();
|
||||
}
|
||||
}
|
||||
+94
@@ -0,0 +1,94 @@
|
||||
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 鉴权:仅处理 /mcp,校验独立 Bearer,与 JWT / Open API Key 分离。
|
||||
*/
|
||||
@Slf4j
|
||||
@Component
|
||||
public class AgentMcpAuthenticationFilter extends OncePerRequestFilter {
|
||||
|
||||
private static final String MCP_PATH = "/mcp";
|
||||
|
||||
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 + "/"));
|
||||
}
|
||||
|
||||
@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, "MCP 凭证未配置");
|
||||
return;
|
||||
}
|
||||
|
||||
String provided = extractBearer(request);
|
||||
if (!StringUtils.hasText(provided) || !tokenEquals(configured, provided)) {
|
||||
writeUnauthorized(response, "MCP 凭证无效或缺失");
|
||||
return;
|
||||
}
|
||||
|
||||
AgentMcpPrincipal principal = new AgentMcpPrincipal("agent-mcp", properties.getCompanyId());
|
||||
SecurityContextHolder.getContext().setAuthentication(new AgentMcpAuthentication(principal));
|
||||
filterChain.doFilter(request, response);
|
||||
} finally {
|
||||
SecurityContextHolder.clearContext();
|
||||
}
|
||||
}
|
||||
|
||||
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)));
|
||||
}
|
||||
}
|
||||
+7
@@ -0,0 +1,7 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.agent.mcp.security;
|
||||
|
||||
/**
|
||||
* MCP Agent 认证主体(m2m);companyId 绑定租户数据范围。
|
||||
*/
|
||||
public record AgentMcpPrincipal(String clientName, Long companyId) {
|
||||
}
|
||||
+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。")
|
||||
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。")
|
||||
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;可选限定店铺。")
|
||||
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);
|
||||
}
|
||||
}
|
||||
+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());
|
||||
}
|
||||
}
|
||||
+139
@@ -0,0 +1,139 @@
|
||||
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.infra.lock.BiStatComputeLock;
|
||||
import top.xyquan.ecomdmbbackend.modules.bi.messaging.BiIncCalcMessage;
|
||||
import top.xyquan.ecomdmbbackend.modules.bi.orderstat.model.document.BiOrderStatDailyShopDoc;
|
||||
import top.xyquan.ecomdmbbackend.modules.bi.orderstat.repository.BiOrderStatDailyRepository;
|
||||
import top.xyquan.ecomdmbbackend.common.time.BizClock;
|
||||
import top.xyquan.ecomdmbbackend.modules.bi.orderstat.service.BiOrderStatCalcTaskService;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.time.LocalDate;
|
||||
import java.util.Optional;
|
||||
|
||||
/**
|
||||
* BI 增量:与同店同日全量互斥;不同日可并行。
|
||||
* 比较消息中的内部订单更新时间 vs 该日 Mongo 文档最新全量快照时间(dbSnapshotTime);
|
||||
* 在快照内(≤)跳过,在外(>)才 $inc。同日全量进行中则按会话快照同样规则跳过或延后。
|
||||
*/
|
||||
@Slf4j
|
||||
@Component
|
||||
@RequiredArgsConstructor
|
||||
public class BiStatIncConsumer {
|
||||
|
||||
private final BiStatComputeLock computeLock;
|
||||
private final BiOrderStatDailyRepository repository;
|
||||
private final BiStatProperties biStatProperties;
|
||||
private final DelayedMqRepublisher delayedMqRepublisher;
|
||||
private final BiOrderStatCalcTaskService calcTaskService;
|
||||
|
||||
@RabbitListener(
|
||||
queues = OrderMqConstants.QUEUE_BI_STAT_INC,
|
||||
concurrency = "${ecom.bi.stat.inc-listener-concurrency:2-4}")
|
||||
public void onMessage(BiIncCalcMessage message) {
|
||||
if (message == null || message.getCompanyId() == null || message.getShopId() == null
|
||||
|| message.getStatDate() == null || message.getInternalOrderUpdateTime() == null) {
|
||||
log.warn("BI inc 消息非法: {}", message);
|
||||
return;
|
||||
}
|
||||
LocalDate statDate = LocalDate.parse(message.getStatDate());
|
||||
Instant internalUpdated = message.getInternalOrderUpdateTime().toInstant();
|
||||
|
||||
try {
|
||||
applyInc(message, statDate, internalUpdated);
|
||||
} catch (Exception e) {
|
||||
calcTaskService.recordIncFailureImmediate(
|
||||
message.getCompanyId(), message.getShopId(), e.getMessage());
|
||||
throw e;
|
||||
}
|
||||
}
|
||||
|
||||
private void applyInc(BiIncCalcMessage message, LocalDate statDate, Instant internalUpdated) {
|
||||
// 同日全量进行中:内部更新时间已在会话快照内则跳过,否则等全量结束后再比文档
|
||||
if (computeLock.isLocked(message.getCompanyId(), message.getShopId(), statDate)) {
|
||||
Optional<Instant> sessionSnapshot = computeLock.peekSessionSnapshot(
|
||||
message.getCompanyId(), message.getShopId(), statDate);
|
||||
if (sessionSnapshot.isPresent() && !internalUpdated.isAfter(sessionSnapshot.get())) {
|
||||
log.info("BI inc 跳过(同日全量会话快照内) messageId={} shopId={} statDate={}",
|
||||
message.getMessageId(), message.getShopId(), statDate);
|
||||
calcTaskService.recordIncAppliedThrottled(
|
||||
message.getCompanyId(), message.getShopId(), statDate, message.getOrderId(), true);
|
||||
return;
|
||||
}
|
||||
delayAndRepublish(message);
|
||||
return;
|
||||
}
|
||||
|
||||
Optional<BiOrderStatDailyShopDoc> shopDoc =
|
||||
repository.findShop(message.getCompanyId(), message.getShopId(), statDate);
|
||||
if (withinFullSnapshot(shopDoc, internalUpdated)) {
|
||||
log.info("BI inc 跳过(文档全量快照内) messageId={} shopId={} statDate={}",
|
||||
message.getMessageId(), message.getShopId(), statDate);
|
||||
calcTaskService.recordIncAppliedThrottled(
|
||||
message.getCompanyId(), message.getShopId(), statDate, message.getOrderId(), true);
|
||||
return;
|
||||
}
|
||||
|
||||
Optional<BiStatComputeLock.Session> session =
|
||||
computeLock.tryLock(message.getCompanyId(), message.getShopId(), statDate, null);
|
||||
if (session.isEmpty()) {
|
||||
delayAndRepublish(message);
|
||||
return;
|
||||
}
|
||||
try {
|
||||
shopDoc = repository.findShop(message.getCompanyId(), message.getShopId(), statDate);
|
||||
if (withinFullSnapshot(shopDoc, internalUpdated)) {
|
||||
log.info("BI inc 跳过(抢锁后文档全量快照内) shopId={} statDate={}",
|
||||
message.getShopId(), statDate);
|
||||
calcTaskService.recordIncAppliedThrottled(
|
||||
message.getCompanyId(), message.getShopId(), statDate, message.getOrderId(), true);
|
||||
return;
|
||||
}
|
||||
repository.applyIncDeltas(
|
||||
message.getCompanyId(),
|
||||
message.getShopId(),
|
||||
message.getPlatformCode(),
|
||||
statDate,
|
||||
message.getShopDelta(),
|
||||
message.getProductDeltas(),
|
||||
message.getSkuDeltas());
|
||||
calcTaskService.recordIncAppliedThrottled(
|
||||
message.getCompanyId(), message.getShopId(), statDate, message.getOrderId(), false);
|
||||
log.info("BI inc delta 已累加 shopId={} statDate={} orderId={}",
|
||||
message.getShopId(), statDate, message.getOrderId());
|
||||
} finally {
|
||||
computeLock.unlock(session.get());
|
||||
}
|
||||
}
|
||||
|
||||
/** 内部订单更新时间 ≤ 文档最新全量快照时间 → 已包含在全量结果中 */
|
||||
private static boolean withinFullSnapshot(Optional<BiOrderStatDailyShopDoc> shopDoc,
|
||||
Instant internalUpdated) {
|
||||
return shopDoc.isPresent()
|
||||
&& shopDoc.get().getDbSnapshotTime() != null
|
||||
&& !internalUpdated.isAfter(shopDoc.get().getDbSnapshotTime());
|
||||
}
|
||||
|
||||
private void delayAndRepublish(BiIncCalcMessage message) {
|
||||
int retry = message.getRetryCount() == null ? 0 : message.getRetryCount();
|
||||
if (retry >= biStatProperties.getIncMaxRetry()) {
|
||||
throw new IllegalStateException("BI inc 延迟重试超限: " + message.getMessageId());
|
||||
}
|
||||
message.setRetryCount(retry + 1);
|
||||
message.setOccurredAt(BizClock.nowOdt());
|
||||
delayedMqRepublisher.republish(
|
||||
OrderMqConstants.EXCHANGE,
|
||||
OrderMqConstants.RK_BI_STAT_INC,
|
||||
message,
|
||||
biStatProperties.getIncDelayMs());
|
||||
log.info("BI inc 日锁占用,已安排延迟重投 messageId={} shopId={} statDate={} retry={}",
|
||||
message.getMessageId(), message.getShopId(), message.getStatDate(), message.getRetryCount());
|
||||
}
|
||||
}
|
||||
+135
@@ -0,0 +1,135 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.bi.orderstat.controller;
|
||||
|
||||
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
|
||||
import jakarta.validation.Valid;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
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.RequestParam;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
import top.xyquan.ecomdmbbackend.common.annotation.RequirePermission;
|
||||
import top.xyquan.ecomdmbbackend.common.exception.BusinessException;
|
||||
import top.xyquan.ecomdmbbackend.common.response.ApiResponse;
|
||||
import top.xyquan.ecomdmbbackend.modules.bi.orderstat.model.dto.BiOrderStatFullCalcTaskCreateDTO;
|
||||
import top.xyquan.ecomdmbbackend.modules.bi.orderstat.model.po.BiOrderStatFullCalcTaskPO;
|
||||
import top.xyquan.ecomdmbbackend.modules.bi.orderstat.model.po.BiOrderStatIncCalcPO;
|
||||
import top.xyquan.ecomdmbbackend.modules.bi.orderstat.model.vo.BiOrderStatFullCalcTaskVO;
|
||||
import top.xyquan.ecomdmbbackend.modules.bi.orderstat.model.vo.BiOrderStatIncCalcStatusVO;
|
||||
import top.xyquan.ecomdmbbackend.modules.bi.orderstat.service.BiOrderStatCalcTaskService;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.shop.mapper.ShopMapper;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.shop.model.po.ShopPO;
|
||||
import top.xyquan.ecomdmbbackend.utils.CurrentUserContext;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
/**
|
||||
* BI 订单统计计算控制面:查询、人工恢复、手动全量计算。
|
||||
*/
|
||||
@RestController
|
||||
@RequestMapping("/api/bi/order-stat/calc")
|
||||
public class BiOrderStatCalcController {
|
||||
|
||||
private final BiOrderStatCalcTaskService calcTaskService;
|
||||
private final ShopMapper shopMapper;
|
||||
private final CurrentUserContext currentUserContext;
|
||||
|
||||
public BiOrderStatCalcController(BiOrderStatCalcTaskService calcTaskService,
|
||||
ShopMapper shopMapper,
|
||||
CurrentUserContext currentUserContext) {
|
||||
this.calcTaskService = calcTaskService;
|
||||
this.shopMapper = shopMapper;
|
||||
this.currentUserContext = currentUserContext;
|
||||
}
|
||||
|
||||
@GetMapping("/inc/status")
|
||||
@RequirePermission(value = "bi:order-stat:calc:read", description = "查询BI计算状态", allowSuper = true)
|
||||
public ApiResponse<BiOrderStatIncCalcStatusVO> incStatus(@RequestParam Long shopId) {
|
||||
ShopPO shop = requireOwnedShop(shopId);
|
||||
return ApiResponse.success(toIncVo(shop.getId(), calcTaskService.findIncState(shop.getId())));
|
||||
}
|
||||
|
||||
@PostMapping("/inc/resume")
|
||||
@RequirePermission(value = "bi:order-stat:calc:update", description = "恢复BI增量计算", allowSuper = true)
|
||||
public ApiResponse<BiOrderStatIncCalcStatusVO> resumeInc(@RequestParam Long shopId) {
|
||||
ShopPO shop = requireOwnedShop(shopId);
|
||||
BiOrderStatIncCalcPO state = calcTaskService.resumeInc(shop.getCompanyId(), shop.getId());
|
||||
return ApiResponse.success("已恢复计算", toIncVo(shop.getId(), state));
|
||||
}
|
||||
|
||||
@PostMapping("/full-task")
|
||||
@RequirePermission(value = "bi:order-stat:calc:create", description = "创建BI全量计算任务", allowSuper = true)
|
||||
public ApiResponse<BiOrderStatFullCalcTaskVO> createFullTask(
|
||||
@Valid @RequestBody BiOrderStatFullCalcTaskCreateDTO dto) {
|
||||
ShopPO shop = requireOwnedShop(dto.getShopId());
|
||||
BiOrderStatFullCalcTaskPO task = calcTaskService.createManualTask(
|
||||
shop.getCompanyId(),
|
||||
shop.getId(),
|
||||
shop.getPlatformCode(),
|
||||
dto.getDateFrom(),
|
||||
dto.getDateTo());
|
||||
return ApiResponse.success("任务已入队", toTaskVo(task));
|
||||
}
|
||||
|
||||
@GetMapping("/full-task/list")
|
||||
@RequirePermission(value = "bi:order-stat:calc:read", description = "查询BI全量计算任务", allowSuper = true)
|
||||
public ApiResponse<List<BiOrderStatFullCalcTaskVO>> listFullTasks(
|
||||
@RequestParam Long shopId,
|
||||
@RequestParam(required = false, defaultValue = "20") Integer limit) {
|
||||
ShopPO shop = requireOwnedShop(shopId);
|
||||
List<BiOrderStatFullCalcTaskPO> tasks =
|
||||
calcTaskService.listTasks(shop.getCompanyId(), shop.getId(),
|
||||
limit == null ? 20 : limit);
|
||||
return ApiResponse.success(tasks.stream().map(this::toTaskVo).collect(Collectors.toList()));
|
||||
}
|
||||
|
||||
private ShopPO requireOwnedShop(Long shopId) {
|
||||
Long companyId = currentUserContext.getCurrentCompanyId();
|
||||
ShopPO shop = shopMapper.selectOne(new LambdaQueryWrapper<ShopPO>()
|
||||
.eq(ShopPO::getId, shopId)
|
||||
.eq(ShopPO::getCompanyId, companyId)
|
||||
.last("LIMIT 1"));
|
||||
if (shop == null) {
|
||||
throw new BusinessException("店铺不存在或无权访问");
|
||||
}
|
||||
return shop;
|
||||
}
|
||||
|
||||
private static BiOrderStatIncCalcStatusVO toIncVo(Long shopId, BiOrderStatIncCalcPO state) {
|
||||
if (state == null) {
|
||||
return BiOrderStatIncCalcStatusVO.builder().shopId(shopId).build();
|
||||
}
|
||||
return BiOrderStatIncCalcStatusVO.builder()
|
||||
.shopId(shopId)
|
||||
.status(state.getStatus())
|
||||
.lastSummary(state.getLastSummary())
|
||||
.lastError(state.getLastError())
|
||||
.lastSuccessTime(state.getLastSuccessTime())
|
||||
.lastStatDate(state.getLastStatDate())
|
||||
.lastAppliedOrderId(state.getLastAppliedOrderId())
|
||||
.lastSkipped(state.getLastSkipped())
|
||||
.build();
|
||||
}
|
||||
|
||||
private BiOrderStatFullCalcTaskVO toTaskVo(BiOrderStatFullCalcTaskPO task) {
|
||||
return BiOrderStatFullCalcTaskVO.builder()
|
||||
.id(task.getId())
|
||||
.shopId(task.getShopId())
|
||||
.upstreamTaskId(task.getUpstreamTaskId())
|
||||
.triggerSource(task.getTriggerSource())
|
||||
.platformCode(task.getPlatformCode())
|
||||
.dateFrom(task.getDateFrom())
|
||||
.dateTo(task.getDateTo())
|
||||
.currentDate(task.getCurrentDate())
|
||||
.totalDays(task.getTotalDays())
|
||||
.doneDays(task.getDoneDays())
|
||||
.failedDays(task.getFailedDays())
|
||||
.skippedDays(task.getSkippedDays())
|
||||
.status(task.getStatus())
|
||||
.lastError(task.getLastError())
|
||||
.createTime(task.getCreateTime())
|
||||
.finishTime(task.getFinishTime())
|
||||
.build();
|
||||
}
|
||||
}
|
||||
+51
@@ -0,0 +1,51 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.bi.orderstat.controller;
|
||||
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.PostMapping;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RequestParam;
|
||||
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.orderstat.model.vo.BiOrderStatDirtyDayVO;
|
||||
import top.xyquan.ecomdmbbackend.modules.bi.orderstat.service.BiOrderStatDirtyDayService;
|
||||
import top.xyquan.ecomdmbbackend.utils.CurrentUserContext;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/** BI 订单日脏数据:健康度、待重算列表、一键 apply。 */
|
||||
@RestController
|
||||
@RequestMapping("/api/bi/order-stat/dirty")
|
||||
public class BiOrderStatDirtyDayController {
|
||||
|
||||
private final BiOrderStatDirtyDayService dirtyDayService;
|
||||
private final CurrentUserContext currentUserContext;
|
||||
|
||||
public BiOrderStatDirtyDayController(BiOrderStatDirtyDayService dirtyDayService,
|
||||
CurrentUserContext currentUserContext) {
|
||||
this.dirtyDayService = dirtyDayService;
|
||||
this.currentUserContext = currentUserContext;
|
||||
}
|
||||
|
||||
@GetMapping("/health")
|
||||
@RequirePermission(value = "bi:order-stat:calc:read", description = "BI脏数据健康度", allowSuper = true)
|
||||
public ApiResponse<BiOrderStatDirtyDayVO.HealthSummary> health() {
|
||||
Long companyId = currentUserContext.getCurrentCompanyId();
|
||||
return ApiResponse.success(dirtyDayService.healthSummary(companyId));
|
||||
}
|
||||
|
||||
@GetMapping("/pending")
|
||||
@RequirePermission(value = "bi:order-stat:calc:read", description = "BI待重算脏日列表", allowSuper = true)
|
||||
public ApiResponse<List<BiOrderStatDirtyDayVO.PendingRow>> listPending(
|
||||
@RequestParam(required = false, defaultValue = "200") Integer limit) {
|
||||
Long companyId = currentUserContext.getCurrentCompanyId();
|
||||
return ApiResponse.success(dirtyDayService.listPending(companyId, limit == null ? 200 : limit));
|
||||
}
|
||||
|
||||
@PostMapping("/apply-pending")
|
||||
@RequirePermission(value = "bi:order-stat:calc:create", description = "BI脏日一键重算", allowSuper = true)
|
||||
public ApiResponse<BiOrderStatDirtyDayVO.ApplyResult> applyPending() {
|
||||
Long companyId = currentUserContext.getCurrentCompanyId();
|
||||
return ApiResponse.success("重算任务已入队", dirtyDayService.applyAllPending(companyId));
|
||||
}
|
||||
}
|
||||
+92
@@ -0,0 +1,92 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.bi.orderstat.controller;
|
||||
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.PostMapping;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RequestParam;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
import top.xyquan.ecomdmbbackend.common.annotation.RequirePermission;
|
||||
import top.xyquan.ecomdmbbackend.common.exception.BusinessException;
|
||||
import top.xyquan.ecomdmbbackend.common.response.ApiResponse;
|
||||
import top.xyquan.ecomdmbbackend.modules.bi.orderstat.model.po.BiOrderStatIncCalcPO;
|
||||
import top.xyquan.ecomdmbbackend.modules.bi.orderstat.model.vo.BiOrderStatIncCalcStatusVO;
|
||||
import top.xyquan.ecomdmbbackend.modules.bi.orderstat.model.vo.BiOrderStatIncHealthVO;
|
||||
import top.xyquan.ecomdmbbackend.modules.bi.orderstat.service.BiOrderStatCalcTaskService;
|
||||
import top.xyquan.ecomdmbbackend.modules.bi.orderstat.service.BiOrderStatIncHealthService;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.shop.mapper.ShopMapper;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.shop.model.po.ShopPO;
|
||||
import top.xyquan.ecomdmbbackend.utils.CurrentUserContext;
|
||||
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/** BI 增量计算健康度:公司汇总、按店明细、恢复暂停。 */
|
||||
@RestController
|
||||
@RequestMapping("/api/bi/order-stat/inc")
|
||||
public class BiOrderStatIncHealthController {
|
||||
|
||||
private final BiOrderStatIncHealthService incHealthService;
|
||||
private final BiOrderStatCalcTaskService calcTaskService;
|
||||
private final ShopMapper shopMapper;
|
||||
private final CurrentUserContext currentUserContext;
|
||||
|
||||
public BiOrderStatIncHealthController(BiOrderStatIncHealthService incHealthService,
|
||||
BiOrderStatCalcTaskService calcTaskService,
|
||||
ShopMapper shopMapper,
|
||||
CurrentUserContext currentUserContext) {
|
||||
this.incHealthService = incHealthService;
|
||||
this.calcTaskService = calcTaskService;
|
||||
this.shopMapper = shopMapper;
|
||||
this.currentUserContext = currentUserContext;
|
||||
}
|
||||
|
||||
@GetMapping("/health")
|
||||
@RequirePermission(value = "bi:order-stat:calc:read", description = "BI增量计算健康度", allowSuper = true)
|
||||
public ApiResponse<BiOrderStatIncHealthVO.HealthSummary> health() {
|
||||
Long companyId = currentUserContext.getCurrentCompanyId();
|
||||
return ApiResponse.success(incHealthService.healthSummary(companyId));
|
||||
}
|
||||
|
||||
@GetMapping("/shops")
|
||||
@RequirePermission(value = "bi:order-stat:calc:read", description = "BI增量计算店列表", allowSuper = true)
|
||||
public ApiResponse<List<BiOrderStatIncHealthVO.ShopRow>> listShops() {
|
||||
Long companyId = currentUserContext.getCurrentCompanyId();
|
||||
return ApiResponse.success(incHealthService.listShopRows(companyId));
|
||||
}
|
||||
|
||||
@PostMapping("/resume-paused")
|
||||
@RequirePermission(value = "bi:order-stat:calc:update", description = "批量恢复BI增量暂停店", allowSuper = true)
|
||||
public ApiResponse<BiOrderStatIncHealthVO.ResumePausedResult> resumePaused() {
|
||||
Long companyId = currentUserContext.getCurrentCompanyId();
|
||||
return ApiResponse.success("已恢复暂停店", incHealthService.resumeAllPaused(companyId));
|
||||
}
|
||||
|
||||
@PostMapping("/resume")
|
||||
@RequirePermission(value = "bi:order-stat:calc:update", description = "恢复单店BI增量计算", allowSuper = true)
|
||||
public ApiResponse<BiOrderStatIncCalcStatusVO> resumeOne(@RequestParam Long shopId) {
|
||||
ShopPO shop = requireOwnedShop(shopId);
|
||||
BiOrderStatIncCalcPO state = calcTaskService.resumeInc(shop.getCompanyId(), shop.getId());
|
||||
return ApiResponse.success("已恢复计算", BiOrderStatIncCalcStatusVO.builder()
|
||||
.shopId(shop.getId())
|
||||
.status(state.getStatus())
|
||||
.lastSummary(state.getLastSummary())
|
||||
.lastError(state.getLastError())
|
||||
.lastSuccessTime(state.getLastSuccessTime())
|
||||
.lastStatDate(state.getLastStatDate())
|
||||
.lastAppliedOrderId(state.getLastAppliedOrderId())
|
||||
.lastSkipped(state.getLastSkipped())
|
||||
.build());
|
||||
}
|
||||
|
||||
private ShopPO requireOwnedShop(Long shopId) {
|
||||
Long companyId = currentUserContext.getCurrentCompanyId();
|
||||
ShopPO shop = shopMapper.selectOne(new LambdaQueryWrapper<ShopPO>()
|
||||
.eq(ShopPO::getId, shopId)
|
||||
.eq(ShopPO::getCompanyId, companyId)
|
||||
.last("LIMIT 1"));
|
||||
if (shop == null) {
|
||||
throw new BusinessException("店铺不存在或无权访问");
|
||||
}
|
||||
return shop;
|
||||
}
|
||||
}
|
||||
+9
@@ -0,0 +1,9 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.bi.orderstat.mapper;
|
||||
|
||||
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
|
||||
import org.apache.ibatis.annotations.Mapper;
|
||||
import top.xyquan.ecomdmbbackend.modules.bi.orderstat.model.po.BiOrderStatDirtyDayPO;
|
||||
|
||||
@Mapper
|
||||
public interface BiOrderStatDirtyDayMapper extends BaseMapper<BiOrderStatDirtyDayPO> {
|
||||
}
|
||||
+9
@@ -0,0 +1,9 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.bi.orderstat.mapper;
|
||||
|
||||
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
|
||||
import org.apache.ibatis.annotations.Mapper;
|
||||
import top.xyquan.ecomdmbbackend.modules.bi.orderstat.model.po.BiOrderStatFullCalcTaskDayPO;
|
||||
|
||||
@Mapper
|
||||
public interface BiOrderStatFullCalcTaskDayMapper extends BaseMapper<BiOrderStatFullCalcTaskDayPO> {
|
||||
}
|
||||
+9
@@ -0,0 +1,9 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.bi.orderstat.mapper;
|
||||
|
||||
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
|
||||
import org.apache.ibatis.annotations.Mapper;
|
||||
import top.xyquan.ecomdmbbackend.modules.bi.orderstat.model.po.BiOrderStatFullCalcTaskPO;
|
||||
|
||||
@Mapper
|
||||
public interface BiOrderStatFullCalcTaskMapper extends BaseMapper<BiOrderStatFullCalcTaskPO> {
|
||||
}
|
||||
+9
@@ -0,0 +1,9 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.bi.orderstat.mapper;
|
||||
|
||||
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
|
||||
import org.apache.ibatis.annotations.Mapper;
|
||||
import top.xyquan.ecomdmbbackend.modules.bi.orderstat.model.po.BiOrderStatIncCalcPO;
|
||||
|
||||
@Mapper
|
||||
public interface BiOrderStatIncCalcMapper extends BaseMapper<BiOrderStatIncCalcPO> {
|
||||
}
|
||||
+46
@@ -0,0 +1,46 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.bi.orderstat.model.document;
|
||||
|
||||
import lombok.Data;
|
||||
import org.springframework.data.annotation.Id;
|
||||
import org.springframework.data.mongodb.core.index.CompoundIndex;
|
||||
import org.springframework.data.mongodb.core.index.CompoundIndexes;
|
||||
import org.springframework.data.mongodb.core.mapping.Document;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.time.Instant;
|
||||
import java.time.LocalDate;
|
||||
|
||||
/** 商品日汇聚。净销售由读侧 deal − refund 推导;品类按商品主数据实时解析。 */
|
||||
@Data
|
||||
@Document(collection = "bi_order_stat_daily_product")
|
||||
@CompoundIndexes({
|
||||
@CompoundIndex(
|
||||
name = "uk_company_shop_prod_date",
|
||||
def = "{'companyId':1,'shopId':1,'productId':1,'statDate':1}",
|
||||
unique = true)
|
||||
})
|
||||
public class BiOrderStatDailyProductDoc {
|
||||
|
||||
@Id
|
||||
private String id;
|
||||
|
||||
private Long companyId;
|
||||
private Long shopId;
|
||||
private Long productId;
|
||||
private LocalDate statDate;
|
||||
|
||||
private BigDecimal dealAmount = BigDecimal.ZERO;
|
||||
private Integer dealOrderCount = 0;
|
||||
private Integer dealQuantitySum = 0;
|
||||
private BigDecimal refundAmount = BigDecimal.ZERO;
|
||||
private Integer refundOrderCount = 0;
|
||||
private Integer refundQuantitySum = 0;
|
||||
private BigDecimal serviceFee = BigDecimal.ZERO;
|
||||
private BigDecimal productCost = BigDecimal.ZERO;
|
||||
private BigDecimal freightCost = BigDecimal.ZERO;
|
||||
private BigDecimal otherCost = BigDecimal.ZERO;
|
||||
|
||||
private Instant dbSnapshotTime;
|
||||
private Instant computedAt;
|
||||
private String computeMode;
|
||||
}
|
||||
+47
@@ -0,0 +1,47 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.bi.orderstat.model.document;
|
||||
|
||||
import lombok.Data;
|
||||
import org.springframework.data.annotation.Id;
|
||||
import org.springframework.data.mongodb.core.index.CompoundIndex;
|
||||
import org.springframework.data.mongodb.core.index.CompoundIndexes;
|
||||
import org.springframework.data.mongodb.core.mapping.Document;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.time.Instant;
|
||||
import java.time.LocalDate;
|
||||
|
||||
/**
|
||||
* 店铺日汇聚。净销售由读侧 deal − refund 推导,不存 sales*。
|
||||
*/
|
||||
@Data
|
||||
@Document(collection = "bi_order_stat_daily_shop")
|
||||
@CompoundIndexes({
|
||||
@CompoundIndex(name = "uk_company_shop_date", def = "{'companyId':1,'shopId':1,'statDate':1}", unique = true),
|
||||
@CompoundIndex(name = "idx_company_date", def = "{'companyId':1,'statDate':1}")
|
||||
})
|
||||
public class BiOrderStatDailyShopDoc {
|
||||
|
||||
@Id
|
||||
private String id;
|
||||
|
||||
private Long companyId;
|
||||
private Long shopId;
|
||||
private String platformCode;
|
||||
private LocalDate statDate;
|
||||
|
||||
private BigDecimal dealAmount = BigDecimal.ZERO;
|
||||
private Integer dealOrderCount = 0;
|
||||
private Integer dealQuantitySum = 0;
|
||||
private BigDecimal refundAmount = BigDecimal.ZERO;
|
||||
private Integer refundOrderCount = 0;
|
||||
private Integer refundQuantitySum = 0;
|
||||
private BigDecimal serviceFee = BigDecimal.ZERO;
|
||||
private BigDecimal productCost = BigDecimal.ZERO;
|
||||
private BigDecimal freightCost = BigDecimal.ZERO;
|
||||
private BigDecimal otherCost = BigDecimal.ZERO;
|
||||
|
||||
/** 最新一次全量计算开启 MySQL 事务快照的时间;增量用内部订单更新时间与之比较 */
|
||||
private Instant dbSnapshotTime;
|
||||
private Instant computedAt;
|
||||
private String computeMode;
|
||||
}
|
||||
+48
@@ -0,0 +1,48 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.bi.orderstat.model.document;
|
||||
|
||||
import lombok.Data;
|
||||
import org.springframework.data.annotation.Id;
|
||||
import org.springframework.data.mongodb.core.index.CompoundIndex;
|
||||
import org.springframework.data.mongodb.core.index.CompoundIndexes;
|
||||
import org.springframework.data.mongodb.core.mapping.Document;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.time.Instant;
|
||||
import java.time.LocalDate;
|
||||
|
||||
/** SKU 日汇聚。净销售由读侧 deal − refund 推导。 */
|
||||
@Data
|
||||
@Document(collection = "bi_order_stat_daily_sku")
|
||||
@CompoundIndexes({
|
||||
@CompoundIndex(
|
||||
name = "uk_company_shop_sku_date",
|
||||
def = "{'companyId':1,'shopId':1,'productSkuId':1,'statDate':1}",
|
||||
unique = true)
|
||||
})
|
||||
public class BiOrderStatDailySkuDoc {
|
||||
|
||||
@Id
|
||||
private String id;
|
||||
|
||||
private Long companyId;
|
||||
private Long shopId;
|
||||
private Long productId;
|
||||
/** 内部 SKU 主键;未绑定为 0 */
|
||||
private Long productSkuId;
|
||||
private LocalDate statDate;
|
||||
|
||||
private BigDecimal dealAmount = BigDecimal.ZERO;
|
||||
private Integer dealOrderCount = 0;
|
||||
private Integer dealQuantitySum = 0;
|
||||
private BigDecimal refundAmount = BigDecimal.ZERO;
|
||||
private Integer refundOrderCount = 0;
|
||||
private Integer refundQuantitySum = 0;
|
||||
private BigDecimal serviceFee = BigDecimal.ZERO;
|
||||
private BigDecimal productCost = BigDecimal.ZERO;
|
||||
private BigDecimal freightCost = BigDecimal.ZERO;
|
||||
private BigDecimal otherCost = BigDecimal.ZERO;
|
||||
|
||||
private Instant dbSnapshotTime;
|
||||
private Instant computedAt;
|
||||
private String computeMode;
|
||||
}
|
||||
+23
@@ -0,0 +1,23 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.bi.orderstat.model.dto;
|
||||
|
||||
import jakarta.validation.constraints.NotNull;
|
||||
import lombok.Data;
|
||||
|
||||
import java.time.LocalDate;
|
||||
|
||||
/**
|
||||
* 手动创建 BI 全量计算任务(trigger_source=MANUAL,upstream_task_id 空)。
|
||||
*/
|
||||
@Data
|
||||
public class BiOrderStatFullCalcTaskCreateDTO {
|
||||
|
||||
/** 内部店 id(ec_shop.id) */
|
||||
@NotNull
|
||||
private Long shopId;
|
||||
|
||||
@NotNull
|
||||
private LocalDate dateFrom;
|
||||
|
||||
@NotNull
|
||||
private LocalDate dateTo;
|
||||
}
|
||||
+13
@@ -0,0 +1,13 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.bi.orderstat.model.dto;
|
||||
|
||||
import lombok.Data;
|
||||
|
||||
import java.time.LocalDate;
|
||||
|
||||
/** 订单反查:某 SKU 在日期窗内涉及的 (店, 自然日)。 */
|
||||
@Data
|
||||
public class ShopStatDateRow {
|
||||
|
||||
private Long shopId;
|
||||
private LocalDate statDate;
|
||||
}
|
||||
+58
@@ -0,0 +1,58 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.bi.orderstat.model.po;
|
||||
|
||||
import com.baomidou.mybatisplus.annotation.FieldFill;
|
||||
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.LocalDate;
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
/** BI 订单日脏数据:店 + order_time 自然日维度,待 FULL 重算。 */
|
||||
@Data
|
||||
@TableName("bi_order_stat_dirty_day")
|
||||
public class BiOrderStatDirtyDayPO {
|
||||
|
||||
public static final String STATUS_PENDING = "PENDING";
|
||||
public static final String STATUS_RUNNING = "RUNNING";
|
||||
public static final String STATUS_CLEAN = "CLEAN";
|
||||
|
||||
public static final String REASON_COST = "COST";
|
||||
public static final String REASON_PRODUCT_DIM = "PRODUCT_DIM";
|
||||
|
||||
@TableId(value = "id", type = IdType.AUTO)
|
||||
private Long id;
|
||||
|
||||
@TableField("company_id")
|
||||
private Long companyId;
|
||||
|
||||
@TableField("shop_id")
|
||||
private Long shopId;
|
||||
|
||||
@TableField("stat_date")
|
||||
private LocalDate statDate;
|
||||
|
||||
/** JSON 数组字符串,如 ["COST","PRODUCT_DIM"] */
|
||||
@TableField("reasons")
|
||||
private String reasons;
|
||||
|
||||
@TableField("status")
|
||||
private String status;
|
||||
|
||||
@TableField("source_refs")
|
||||
private String sourceRefs;
|
||||
|
||||
@TableField("apply_batch_id")
|
||||
private String applyBatchId;
|
||||
|
||||
@TableField(value = "create_time", fill = FieldFill.INSERT)
|
||||
private LocalDateTime createTime;
|
||||
|
||||
@TableField(value = "update_time", fill = FieldFill.INSERT_UPDATE)
|
||||
private LocalDateTime updateTime;
|
||||
|
||||
@TableField("applied_time")
|
||||
private LocalDateTime appliedTime;
|
||||
}
|
||||
+61
@@ -0,0 +1,61 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.bi.orderstat.model.po;
|
||||
|
||||
import com.baomidou.mybatisplus.annotation.FieldFill;
|
||||
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.LocalDate;
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
/**
|
||||
* BI 全量计算任务按天明细;RUNNING 以获日锁为准。
|
||||
*/
|
||||
@Data
|
||||
@TableName("bi_order_stat_full_calc_task_day")
|
||||
public class BiOrderStatFullCalcTaskDayPO {
|
||||
|
||||
public static final String STATUS_PENDING = "PENDING";
|
||||
public static final String STATUS_RUNNING = "RUNNING";
|
||||
public static final String STATUS_SUCCESS = "SUCCESS";
|
||||
public static final String STATUS_FAILED = "FAILED";
|
||||
public static final String STATUS_SKIPPED = "SKIPPED";
|
||||
|
||||
@TableId(value = "id", type = IdType.AUTO)
|
||||
private Long id;
|
||||
|
||||
@TableField("task_id")
|
||||
private Long taskId;
|
||||
|
||||
@TableField("company_id")
|
||||
private Long companyId;
|
||||
|
||||
@TableField("shop_id")
|
||||
private Long shopId;
|
||||
|
||||
@TableField("day")
|
||||
private LocalDate day;
|
||||
|
||||
@TableField("status")
|
||||
private String status;
|
||||
|
||||
@TableField("db_snapshot_time")
|
||||
private LocalDateTime dbSnapshotTime;
|
||||
|
||||
@TableField("last_error")
|
||||
private String lastError;
|
||||
|
||||
@TableField("start_time")
|
||||
private LocalDateTime startTime;
|
||||
|
||||
@TableField("finish_time")
|
||||
private LocalDateTime finishTime;
|
||||
|
||||
@TableField(value = "create_time", fill = FieldFill.INSERT)
|
||||
private LocalDateTime createTime;
|
||||
|
||||
@TableField(value = "update_time", fill = FieldFill.INSERT_UPDATE)
|
||||
private LocalDateTime updateTime;
|
||||
}
|
||||
+84
@@ -0,0 +1,84 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.bi.orderstat.model.po;
|
||||
|
||||
import com.baomidou.mybatisplus.annotation.FieldFill;
|
||||
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.LocalDate;
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
/**
|
||||
* BI 全量计算任务头;shop_id=ec_shop.id,上游转换任务软引用。
|
||||
*/
|
||||
@Data
|
||||
@TableName("bi_order_stat_full_calc_task")
|
||||
public class BiOrderStatFullCalcTaskPO {
|
||||
|
||||
public static final String STATUS_PENDING = "PENDING";
|
||||
public static final String STATUS_RUNNING = "RUNNING";
|
||||
public static final String STATUS_SUCCESS = "SUCCESS";
|
||||
public static final String STATUS_FAILED = "FAILED";
|
||||
public static final String STATUS_CANCELLED = "CANCELLED";
|
||||
|
||||
@TableId(value = "id", type = IdType.AUTO)
|
||||
private Long id;
|
||||
|
||||
@TableField("company_id")
|
||||
private Long companyId;
|
||||
|
||||
@TableField("shop_id")
|
||||
private Long shopId;
|
||||
|
||||
@TableField("platform_code")
|
||||
private String platformCode;
|
||||
|
||||
/** MANUAL / CONVERT / DIRTY_DAY(历史:COST_SYNC / SKU_MIGRATE) */
|
||||
@TableField("trigger_source")
|
||||
private String triggerSource;
|
||||
|
||||
/**
|
||||
* 上游任务 ID(软引用);CONVERT 时有值;DIRTY_DAY / MANUAL 为空。
|
||||
*/
|
||||
@TableField("upstream_task_id")
|
||||
private Long upstreamTaskId;
|
||||
|
||||
@TableField("date_from")
|
||||
private LocalDate dateFrom;
|
||||
|
||||
@TableField("date_to")
|
||||
private LocalDate dateTo;
|
||||
|
||||
/** MySQL 保留字 CURRENT_DATE,必须反引号转义 */
|
||||
@TableField("`current_date`")
|
||||
private LocalDate currentDate;
|
||||
|
||||
@TableField("total_days")
|
||||
private Integer totalDays;
|
||||
|
||||
@TableField("done_days")
|
||||
private Integer doneDays;
|
||||
|
||||
@TableField("failed_days")
|
||||
private Integer failedDays;
|
||||
|
||||
@TableField("skipped_days")
|
||||
private Integer skippedDays;
|
||||
|
||||
@TableField("status")
|
||||
private String status;
|
||||
|
||||
@TableField("last_error")
|
||||
private String lastError;
|
||||
|
||||
@TableField(value = "create_time", fill = FieldFill.INSERT)
|
||||
private LocalDateTime createTime;
|
||||
|
||||
@TableField(value = "update_time", fill = FieldFill.INSERT_UPDATE)
|
||||
private LocalDateTime updateTime;
|
||||
|
||||
@TableField("finish_time")
|
||||
private LocalDateTime finishTime;
|
||||
}
|
||||
+58
@@ -0,0 +1,58 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.bi.orderstat.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.LocalDate;
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
/**
|
||||
* BI 增量计算应用店态;shop_id=ec_shop.id。
|
||||
*/
|
||||
@Data
|
||||
@TableName("bi_order_stat_inc_calc")
|
||||
public class BiOrderStatIncCalcPO {
|
||||
|
||||
public static final int STATUS_OK = 1;
|
||||
public static final int STATUS_PAUSED = 2;
|
||||
|
||||
@TableId(value = "id", type = IdType.AUTO)
|
||||
private Long id;
|
||||
|
||||
@TableField("company_id")
|
||||
private Long companyId;
|
||||
|
||||
@TableField("shop_id")
|
||||
private Long shopId;
|
||||
|
||||
@TableField("status")
|
||||
private Integer status;
|
||||
|
||||
@TableField("last_error")
|
||||
private String lastError;
|
||||
|
||||
/** 最后一次计算摘要(成功说明或失败提示;展示优先) */
|
||||
@TableField("last_summary")
|
||||
private String lastSummary;
|
||||
|
||||
@TableField("last_success_time")
|
||||
private LocalDateTime lastSuccessTime;
|
||||
|
||||
@TableField("last_stat_date")
|
||||
private LocalDate lastStatDate;
|
||||
|
||||
@TableField("last_applied_order_id")
|
||||
private Long lastAppliedOrderId;
|
||||
|
||||
@TableField("last_skipped")
|
||||
private Integer lastSkipped;
|
||||
|
||||
@TableField("create_time")
|
||||
private LocalDateTime createTime;
|
||||
|
||||
@TableField("update_time")
|
||||
private LocalDateTime updateTime;
|
||||
}
|
||||
+56
@@ -0,0 +1,56 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.bi.orderstat.model.vo;
|
||||
|
||||
import lombok.Builder;
|
||||
import lombok.Data;
|
||||
|
||||
import java.time.LocalDate;
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.List;
|
||||
|
||||
public class BiOrderStatDirtyDayVO {
|
||||
|
||||
@Data
|
||||
@Builder
|
||||
public static class HealthSummary {
|
||||
/** 待重算自然日总数 */
|
||||
private int pendingDayCount;
|
||||
/** 涉及店铺数 */
|
||||
private int pendingShopCount;
|
||||
/** 最早待重算日 */
|
||||
private LocalDate oldestPendingDate;
|
||||
/** 是否存在 RUNNING */
|
||||
private boolean hasRunning;
|
||||
}
|
||||
|
||||
@Data
|
||||
@Builder
|
||||
public static class PendingRow {
|
||||
private Long id;
|
||||
private Long shopId;
|
||||
private String shopName;
|
||||
private LocalDate statDate;
|
||||
private List<String> reasons;
|
||||
private String status;
|
||||
private LocalDateTime updateTime;
|
||||
}
|
||||
|
||||
@Data
|
||||
@Builder
|
||||
public static class ApplyResult {
|
||||
private String applyBatchId;
|
||||
private int dirtyDayCount;
|
||||
private int taskCount;
|
||||
private List<TaskBrief> tasks;
|
||||
}
|
||||
|
||||
@Data
|
||||
@Builder
|
||||
public static class TaskBrief {
|
||||
private Long biCalcTaskId;
|
||||
private Long shopId;
|
||||
private LocalDate dateFrom;
|
||||
private LocalDate dateTo;
|
||||
private int totalDays;
|
||||
private String status;
|
||||
}
|
||||
}
|
||||
+36
@@ -0,0 +1,36 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.bi.orderstat.model.vo;
|
||||
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Builder;
|
||||
import lombok.Data;
|
||||
import lombok.NoArgsConstructor;
|
||||
|
||||
import java.time.LocalDate;
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
/** BI 全量计算任务摘要。 */
|
||||
@Data
|
||||
@Builder
|
||||
@NoArgsConstructor
|
||||
@AllArgsConstructor
|
||||
public class BiOrderStatFullCalcTaskVO {
|
||||
|
||||
private Long id;
|
||||
private Long shopId;
|
||||
/** MANUAL / CONVERT / DIRTY_DAY(历史:COST_SYNC / SKU_MIGRATE) */
|
||||
private String triggerSource;
|
||||
/** 上游任务 id;含义由 triggerSource 决定 */
|
||||
private Long upstreamTaskId;
|
||||
private String platformCode;
|
||||
private LocalDate dateFrom;
|
||||
private LocalDate dateTo;
|
||||
private LocalDate currentDate;
|
||||
private Integer totalDays;
|
||||
private Integer doneDays;
|
||||
private Integer failedDays;
|
||||
private Integer skippedDays;
|
||||
private String status;
|
||||
private String lastError;
|
||||
private LocalDateTime createTime;
|
||||
private LocalDateTime finishTime;
|
||||
}
|
||||
+27
@@ -0,0 +1,27 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.bi.orderstat.model.vo;
|
||||
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Builder;
|
||||
import lombok.Data;
|
||||
import lombok.NoArgsConstructor;
|
||||
|
||||
import java.time.LocalDate;
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
/** BI 增量计算店态(HTTP 展示)。 */
|
||||
@Data
|
||||
@Builder
|
||||
@NoArgsConstructor
|
||||
@AllArgsConstructor
|
||||
public class BiOrderStatIncCalcStatusVO {
|
||||
|
||||
private Long shopId;
|
||||
/** 1=正常 2=出错暂停 */
|
||||
private Integer status;
|
||||
private String lastSummary;
|
||||
private String lastError;
|
||||
private LocalDateTime lastSuccessTime;
|
||||
private LocalDate lastStatDate;
|
||||
private Long lastAppliedOrderId;
|
||||
private Integer lastSkipped;
|
||||
}
|
||||
+68
@@ -0,0 +1,68 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.bi.orderstat.model.vo;
|
||||
|
||||
import lombok.AllArgsConstructor;
|
||||
import lombok.Builder;
|
||||
import lombok.Data;
|
||||
import lombok.NoArgsConstructor;
|
||||
|
||||
import java.time.LocalDate;
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.List;
|
||||
|
||||
/** BI 增量计算健康度(公司汇总 + 店行)。 */
|
||||
public class BiOrderStatIncHealthVO {
|
||||
|
||||
/** 店健康档:OK / IDLE / LAGGED / PAUSED */
|
||||
public static final String KIND_OK = "OK";
|
||||
public static final String KIND_IDLE = "IDLE";
|
||||
public static final String KIND_LAGGED = "LAGGED";
|
||||
public static final String KIND_PAUSED = "PAUSED";
|
||||
|
||||
@Data
|
||||
@Builder
|
||||
@NoArgsConstructor
|
||||
@AllArgsConstructor
|
||||
public static class HealthSummary {
|
||||
private int shopCount;
|
||||
private int okCount;
|
||||
private int idleCount;
|
||||
private int laggedCount;
|
||||
private int pausedCount;
|
||||
/** 最差滞后分钟数;无滞后则为 null */
|
||||
private Long worstLagMinutes;
|
||||
private int lagThresholdMinutes;
|
||||
private int activityWindowHours;
|
||||
/** 无暂停且无滞后 */
|
||||
private boolean healthy;
|
||||
}
|
||||
|
||||
@Data
|
||||
@Builder
|
||||
@NoArgsConstructor
|
||||
@AllArgsConstructor
|
||||
public static class ShopRow {
|
||||
private Long shopId;
|
||||
private String shopName;
|
||||
private String platformCode;
|
||||
/** 店态:1 正常 2 暂停;无记录则为 null */
|
||||
private Integer status;
|
||||
/** OK / IDLE / LAGGED / PAUSED */
|
||||
private String healthKind;
|
||||
private Long lagMinutes;
|
||||
private LocalDateTime lastSuccessTime;
|
||||
private LocalDate lastStatDate;
|
||||
private String lastSummary;
|
||||
private String lastError;
|
||||
private boolean recentOrderActivity;
|
||||
private boolean recentIncSuccess;
|
||||
}
|
||||
|
||||
@Data
|
||||
@Builder
|
||||
@NoArgsConstructor
|
||||
@AllArgsConstructor
|
||||
public static class ResumePausedResult {
|
||||
private int resumedCount;
|
||||
private List<Long> shopIds;
|
||||
}
|
||||
}
|
||||
+444
@@ -0,0 +1,444 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.bi.orderstat.query;
|
||||
|
||||
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.stereotype.Service;
|
||||
import top.xyquan.ecomdmbbackend.modules.bi.orderstat.model.document.BiOrderStatDailyProductDoc;
|
||||
import top.xyquan.ecomdmbbackend.modules.bi.orderstat.model.document.BiOrderStatDailyShopDoc;
|
||||
import top.xyquan.ecomdmbbackend.modules.bi.orderstat.model.document.BiOrderStatDailySkuDoc;
|
||||
import top.xyquan.ecomdmbbackend.modules.bi.orderstat.repository.BiOrderStatDailyRepository;
|
||||
import top.xyquan.ecomdmbbackend.modules.bi.overview.model.agg.OverviewAggRows;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.product.mapper.ProductMapper;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.product.model.po.ProductPO;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.time.LocalDate;
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.HashSet;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
|
||||
/**
|
||||
* BI 订单日汇聚读查询:Mongo → 工作台/概览沿用的 {@link OverviewAggRows} 行形态。
|
||||
* <p>
|
||||
* 净销售三件套由读侧推导:{@code deal* − refund*},不再读 Mongo sales* 字段。
|
||||
* 品类归属按商品主数据实时解析,商品日文档不存 categoryId。
|
||||
*/
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
public class BiOrderStatQueryService {
|
||||
|
||||
private final BiOrderStatDailyRepository repository;
|
||||
private final ProductMapper productMapper;
|
||||
|
||||
public List<BiOrderStatDailyShopDoc> listShopDocs(Long companyId, List<Long> shopIds,
|
||||
LocalDate start, LocalDate end) {
|
||||
return repository.listShopDocs(companyId, shopIds, start, end);
|
||||
}
|
||||
|
||||
public List<BiOrderStatDailyProductDoc> listProductDocs(Long companyId, List<Long> shopIds,
|
||||
LocalDate start, LocalDate end) {
|
||||
return repository.listProductDocs(companyId, shopIds, start, end);
|
||||
}
|
||||
|
||||
public List<BiOrderStatDailyProductDoc> listProductDocs(Long companyId, List<Long> shopIds,
|
||||
Long productId,
|
||||
LocalDate start, LocalDate end) {
|
||||
return repository.listProductDocs(companyId, shopIds, productId, start, end);
|
||||
}
|
||||
|
||||
public List<BiOrderStatDailySkuDoc> listSkuDocs(Long companyId, Long productId,
|
||||
List<Long> shopIds,
|
||||
LocalDate start, LocalDate end) {
|
||||
return repository.listSkuDocs(companyId, productId, shopIds, start, end);
|
||||
}
|
||||
|
||||
/** 按 SKU 主键拉区间日文档(SKU 概览)。 */
|
||||
public List<BiOrderStatDailySkuDoc> listSkuDocsBySkuId(Long companyId, Long productSkuId,
|
||||
List<Long> shopIds,
|
||||
LocalDate start, LocalDate end) {
|
||||
return repository.listSkuDocsBySkuId(companyId, productSkuId, shopIds, start, end);
|
||||
}
|
||||
|
||||
/** 商品日文档按日历日合并(单商品趋势)。 */
|
||||
public List<OverviewAggRows.DailyRow> toDailyRowsFromProductDocs(
|
||||
List<BiOrderStatDailyProductDoc> productDocs) {
|
||||
Map<LocalDate, OverviewAggRows.DailyRow> byDay = new HashMap<>();
|
||||
for (BiOrderStatDailyProductDoc doc : productDocs) {
|
||||
if (doc == null || doc.getStatDate() == null) {
|
||||
continue;
|
||||
}
|
||||
OverviewAggRows.DailyRow row = byDay.computeIfAbsent(doc.getStatDate(), d -> emptyDaily(d));
|
||||
addDealRefundCost(row,
|
||||
doc.getDealAmount(), doc.getDealOrderCount(),
|
||||
doc.getRefundAmount(), doc.getRefundOrderCount(),
|
||||
doc.getProductCost(), doc.getFreightCost(), doc.getOtherCost());
|
||||
}
|
||||
return new ArrayList<>(byDay.values());
|
||||
}
|
||||
|
||||
/** SKU 日文档按日历日合并(单 SKU 趋势)。 */
|
||||
public List<OverviewAggRows.DailyRow> toDailyRowsFromSkuDocs(List<BiOrderStatDailySkuDoc> skuDocs) {
|
||||
Map<LocalDate, OverviewAggRows.DailyRow> byDay = new HashMap<>();
|
||||
for (BiOrderStatDailySkuDoc doc : skuDocs) {
|
||||
if (doc == null || doc.getStatDate() == null) {
|
||||
continue;
|
||||
}
|
||||
OverviewAggRows.DailyRow row = byDay.computeIfAbsent(doc.getStatDate(), d -> emptyDaily(d));
|
||||
addDealRefundCost(row,
|
||||
doc.getDealAmount(), doc.getDealOrderCount(),
|
||||
doc.getRefundAmount(), doc.getRefundOrderCount(),
|
||||
doc.getProductCost(), doc.getFreightCost(), doc.getOtherCost());
|
||||
}
|
||||
return new ArrayList<>(byDay.values());
|
||||
}
|
||||
|
||||
/** SKU 日文档按 productSkuId 合并区间。 */
|
||||
public List<SkuPeriodMetrics> sumSkuDocsBySku(List<BiOrderStatDailySkuDoc> skuDocs) {
|
||||
Map<Long, SkuPeriodMetrics> merged = new HashMap<>();
|
||||
for (BiOrderStatDailySkuDoc doc : skuDocs) {
|
||||
if (doc == null) {
|
||||
continue;
|
||||
}
|
||||
long skuId = doc.getProductSkuId() != null ? doc.getProductSkuId() : 0L;
|
||||
SkuPeriodMetrics cur = merged.get(skuId);
|
||||
BigDecimal deal = nz(doc.getDealAmount());
|
||||
BigDecimal refund = nz(doc.getRefundAmount());
|
||||
int dealOrders = nzInt(doc.getDealOrderCount());
|
||||
int refundOrders = nzInt(doc.getRefundOrderCount());
|
||||
int dealQty = nzInt(doc.getDealQuantitySum());
|
||||
int refundQty = nzInt(doc.getRefundQuantitySum());
|
||||
if (cur == null) {
|
||||
merged.put(skuId, new SkuPeriodMetrics(
|
||||
skuId,
|
||||
netAmount(deal, refund),
|
||||
refund,
|
||||
nz(doc.getProductCost()),
|
||||
nz(doc.getFreightCost()),
|
||||
nz(doc.getOtherCost()),
|
||||
netCount(dealOrders, refundOrders),
|
||||
netCount(dealQty, refundQty),
|
||||
deal, dealOrders, dealQty,
|
||||
refundOrders, refundQty));
|
||||
} else {
|
||||
BigDecimal nextDeal = cur.dealAmount().add(deal);
|
||||
BigDecimal nextRefund = cur.refundAmount().add(refund);
|
||||
int nextDealOrders = cur.dealOrderCount() + dealOrders;
|
||||
int nextRefundOrders = cur.refundOrderCount() + refundOrders;
|
||||
int nextDealQty = cur.dealQuantitySum() + dealQty;
|
||||
int nextRefundQty = cur.refundQuantitySum() + refundQty;
|
||||
merged.put(skuId, new SkuPeriodMetrics(
|
||||
skuId,
|
||||
netAmount(nextDeal, nextRefund),
|
||||
nextRefund,
|
||||
cur.productCost().add(nz(doc.getProductCost())),
|
||||
cur.freightCost().add(nz(doc.getFreightCost())),
|
||||
cur.otherCost().add(nz(doc.getOtherCost())),
|
||||
netCount(nextDealOrders, nextRefundOrders),
|
||||
netCount(nextDealQty, nextRefundQty),
|
||||
nextDeal, nextDealOrders, nextDealQty,
|
||||
nextRefundOrders, nextRefundQty));
|
||||
}
|
||||
}
|
||||
return new ArrayList<>(merged.values());
|
||||
}
|
||||
|
||||
/**
|
||||
* SKU 日文档按 (shopId, productSkuId) 合并区间,供工作台 SKU 汇总表。
|
||||
* 行上净销售三件套 = 成交 − 退款。
|
||||
*/
|
||||
public List<OverviewAggRows.ShopSkuRow> toShopSkuRows(List<BiOrderStatDailySkuDoc> docs) {
|
||||
Map<String, OverviewAggRows.ShopSkuRow> merged = new HashMap<>();
|
||||
for (BiOrderStatDailySkuDoc doc : docs) {
|
||||
if (doc == null || doc.getShopId() == null) {
|
||||
continue;
|
||||
}
|
||||
long skuId = doc.getProductSkuId() != null ? doc.getProductSkuId() : 0L;
|
||||
long productId = doc.getProductId() != null ? doc.getProductId() : 0L;
|
||||
String key = doc.getShopId() + ":" + skuId;
|
||||
OverviewAggRows.ShopSkuRow row = merged.computeIfAbsent(key, k -> {
|
||||
OverviewAggRows.ShopSkuRow r = new OverviewAggRows.ShopSkuRow();
|
||||
r.setShopId(doc.getShopId());
|
||||
r.setProductId(productId);
|
||||
r.setProductSkuId(skuId);
|
||||
r.setSalesAmount(BigDecimal.ZERO);
|
||||
r.setOrderCount(0L);
|
||||
r.setSalesQuantitySum(0L);
|
||||
r.setRefundAmount(BigDecimal.ZERO);
|
||||
r.setRefundOrderCount(0L);
|
||||
r.setRefundQuantitySum(0L);
|
||||
r.setProductCost(BigDecimal.ZERO);
|
||||
r.setFreightCost(BigDecimal.ZERO);
|
||||
r.setOtherCost(BigDecimal.ZERO);
|
||||
r.setDealAmount(BigDecimal.ZERO);
|
||||
r.setDealOrderCount(0L);
|
||||
r.setDealQuantitySum(0L);
|
||||
return r;
|
||||
});
|
||||
// 同一 SKU 跨店合并时保留非 0 的 productId
|
||||
if ((row.getProductId() == null || row.getProductId() <= 0) && productId > 0) {
|
||||
row.setProductId(productId);
|
||||
}
|
||||
row.setDealAmount(nz(row.getDealAmount()).add(nz(doc.getDealAmount())));
|
||||
row.setDealOrderCount(nzLong(row.getDealOrderCount()) + nzInt(doc.getDealOrderCount()));
|
||||
row.setDealQuantitySum(nzLong(row.getDealQuantitySum()) + nzInt(doc.getDealQuantitySum()));
|
||||
row.setRefundAmount(nz(row.getRefundAmount()).add(nz(doc.getRefundAmount())));
|
||||
row.setRefundOrderCount(nzLong(row.getRefundOrderCount()) + nzInt(doc.getRefundOrderCount()));
|
||||
row.setRefundQuantitySum(nzLong(row.getRefundQuantitySum()) + nzInt(doc.getRefundQuantitySum()));
|
||||
row.setProductCost(nz(row.getProductCost()).add(nz(doc.getProductCost())));
|
||||
row.setFreightCost(nz(row.getFreightCost()).add(nz(doc.getFreightCost())));
|
||||
row.setOtherCost(nz(row.getOtherCost()).add(nz(doc.getOtherCost())));
|
||||
fillNetSalesSku(row);
|
||||
}
|
||||
return new ArrayList<>(merged.values());
|
||||
}
|
||||
|
||||
/**
|
||||
* SKU 区间指标。{@code salesAmount}/{@code salesOrderCount}/{@code salesQuantitySum} 为净销售三件套(成交−退款)。
|
||||
*/
|
||||
public record SkuPeriodMetrics(
|
||||
long productSkuId,
|
||||
BigDecimal salesAmount,
|
||||
BigDecimal refundAmount,
|
||||
BigDecimal productCost,
|
||||
BigDecimal freightCost,
|
||||
BigDecimal otherCost,
|
||||
int salesOrderCount,
|
||||
int salesQuantitySum,
|
||||
BigDecimal dealAmount,
|
||||
int dealOrderCount,
|
||||
int dealQuantitySum,
|
||||
int refundOrderCount,
|
||||
int refundQuantitySum
|
||||
) {
|
||||
public BigDecimal orderCost() {
|
||||
return nz(productCost).add(nz(freightCost)).add(nz(otherCost));
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 商品日文档按 (shopId, productId) 合并区间后,转为工作台多维/四表所需行。
|
||||
* platformCode 由店铺主数据补齐;categoryId 按当前商品主数据实时解析。
|
||||
* 行上 salesAmount/orderCount/salesQuantitySum 为净销售三件套。
|
||||
*/
|
||||
public List<OverviewAggRows.ShopProductRow> toShopProductRows(
|
||||
List<BiOrderStatDailyProductDoc> docs, Map<Long, String> platformByShopId) {
|
||||
Map<Long, Long> liveCategoryByProduct = loadLiveCategoryByProductIds(docs);
|
||||
Map<String, OverviewAggRows.ShopProductRow> merged = new HashMap<>();
|
||||
for (BiOrderStatDailyProductDoc doc : docs) {
|
||||
if (doc == null || doc.getShopId() == null) {
|
||||
continue;
|
||||
}
|
||||
long productId = doc.getProductId() != null ? doc.getProductId() : 0L;
|
||||
long categoryId = productId > 0
|
||||
? liveCategoryByProduct.getOrDefault(productId, 0L)
|
||||
: 0L;
|
||||
String key = doc.getShopId() + ":" + productId;
|
||||
OverviewAggRows.ShopProductRow row = merged.computeIfAbsent(key, k -> {
|
||||
OverviewAggRows.ShopProductRow r = new OverviewAggRows.ShopProductRow();
|
||||
r.setShopId(doc.getShopId());
|
||||
r.setPlatformCode(platformByShopId != null ? platformByShopId.get(doc.getShopId()) : null);
|
||||
r.setProductId(productId);
|
||||
r.setCategoryId(categoryId);
|
||||
r.setSalesAmount(BigDecimal.ZERO);
|
||||
r.setOrderCount(0L);
|
||||
r.setSalesQuantitySum(0L);
|
||||
r.setRefundAmount(BigDecimal.ZERO);
|
||||
r.setRefundOrderCount(0L);
|
||||
r.setRefundQuantitySum(0L);
|
||||
r.setProductCost(BigDecimal.ZERO);
|
||||
r.setFreightCost(BigDecimal.ZERO);
|
||||
r.setOtherCost(BigDecimal.ZERO);
|
||||
r.setDealAmount(BigDecimal.ZERO);
|
||||
r.setDealOrderCount(0L);
|
||||
r.setDealQuantitySum(0L);
|
||||
return r;
|
||||
});
|
||||
row.setDealAmount(nz(row.getDealAmount()).add(nz(doc.getDealAmount())));
|
||||
row.setDealOrderCount(nzLong(row.getDealOrderCount()) + nzInt(doc.getDealOrderCount()));
|
||||
row.setDealQuantitySum(nzLong(row.getDealQuantitySum()) + nzInt(doc.getDealQuantitySum()));
|
||||
row.setRefundAmount(nz(row.getRefundAmount()).add(nz(doc.getRefundAmount())));
|
||||
row.setRefundOrderCount(nzLong(row.getRefundOrderCount()) + nzInt(doc.getRefundOrderCount()));
|
||||
row.setRefundQuantitySum(nzLong(row.getRefundQuantitySum()) + nzInt(doc.getRefundQuantitySum()));
|
||||
row.setProductCost(nz(row.getProductCost()).add(nz(doc.getProductCost())));
|
||||
row.setFreightCost(nz(row.getFreightCost()).add(nz(doc.getFreightCost())));
|
||||
row.setOtherCost(nz(row.getOtherCost()).add(nz(doc.getOtherCost())));
|
||||
fillNetSales(row);
|
||||
}
|
||||
return new ArrayList<>(merged.values());
|
||||
}
|
||||
|
||||
/** 批量读取商品当前类目;无主数据或未绑定类目时记为 0。 */
|
||||
private Map<Long, Long> loadLiveCategoryByProductIds(List<BiOrderStatDailyProductDoc> docs) {
|
||||
Set<Long> productIds = new HashSet<>();
|
||||
if (docs != null) {
|
||||
for (BiOrderStatDailyProductDoc doc : docs) {
|
||||
if (doc != null && doc.getProductId() != null && doc.getProductId() > 0) {
|
||||
productIds.add(doc.getProductId());
|
||||
}
|
||||
}
|
||||
}
|
||||
if (productIds.isEmpty()) {
|
||||
return Map.of();
|
||||
}
|
||||
Map<Long, Long> map = new HashMap<>();
|
||||
for (ProductPO p : productMapper.selectList(new LambdaQueryWrapper<ProductPO>()
|
||||
.in(ProductPO::getId, productIds)
|
||||
.select(ProductPO::getId, ProductPO::getCategoryId))) {
|
||||
if (p.getId() == null) {
|
||||
continue;
|
||||
}
|
||||
map.put(p.getId(), p.getCategoryId() != null ? p.getCategoryId() : 0L);
|
||||
}
|
||||
return map;
|
||||
}
|
||||
|
||||
/** 店铺日文档按日历日跨店求和,供趋势图。 */
|
||||
public List<OverviewAggRows.DailyRow> toDailyRows(List<BiOrderStatDailyShopDoc> shopDocs) {
|
||||
Map<LocalDate, OverviewAggRows.DailyRow> byDay = new HashMap<>();
|
||||
for (BiOrderStatDailyShopDoc doc : shopDocs) {
|
||||
if (doc == null || doc.getStatDate() == null) {
|
||||
continue;
|
||||
}
|
||||
OverviewAggRows.DailyRow row = byDay.computeIfAbsent(doc.getStatDate(), d -> emptyDaily(d));
|
||||
addDealRefundCost(row,
|
||||
doc.getDealAmount(), doc.getDealOrderCount(),
|
||||
doc.getRefundAmount(), doc.getRefundOrderCount(),
|
||||
doc.getProductCost(), doc.getFreightCost(), doc.getOtherCost());
|
||||
}
|
||||
return new ArrayList<>(byDay.values());
|
||||
}
|
||||
|
||||
/**
|
||||
* 店铺日文档区间合计(KPI 用:单量不跨商品重复计)。
|
||||
* {@code salesAmount}/{@code salesOrderCount}/{@code salesQuantitySum} 为净销售三件套。
|
||||
*/
|
||||
public ShopPeriodMetrics sumShopDocs(List<BiOrderStatDailyShopDoc> shopDocs) {
|
||||
BigDecimal dealAmount = BigDecimal.ZERO;
|
||||
BigDecimal refund = BigDecimal.ZERO;
|
||||
BigDecimal pc = BigDecimal.ZERO;
|
||||
BigDecimal fc = BigDecimal.ZERO;
|
||||
BigDecimal oc = BigDecimal.ZERO;
|
||||
int dealOrderCount = 0;
|
||||
int dealQuantitySum = 0;
|
||||
int refundOrderCount = 0;
|
||||
int refundQuantitySum = 0;
|
||||
for (BiOrderStatDailyShopDoc doc : shopDocs) {
|
||||
if (doc == null) {
|
||||
continue;
|
||||
}
|
||||
dealAmount = dealAmount.add(nz(doc.getDealAmount()));
|
||||
refund = refund.add(nz(doc.getRefundAmount()));
|
||||
pc = pc.add(nz(doc.getProductCost()));
|
||||
fc = fc.add(nz(doc.getFreightCost()));
|
||||
oc = oc.add(nz(doc.getOtherCost()));
|
||||
dealOrderCount += nzInt(doc.getDealOrderCount());
|
||||
dealQuantitySum += nzInt(doc.getDealQuantitySum());
|
||||
refundOrderCount += nzInt(doc.getRefundOrderCount());
|
||||
refundQuantitySum += nzInt(doc.getRefundQuantitySum());
|
||||
}
|
||||
return new ShopPeriodMetrics(
|
||||
netAmount(dealAmount, refund),
|
||||
refund,
|
||||
pc, fc, oc,
|
||||
dealAmount,
|
||||
netCount(dealOrderCount, refundOrderCount),
|
||||
netCount(dealQuantitySum, refundQuantitySum),
|
||||
dealOrderCount, dealQuantitySum,
|
||||
refundOrderCount, refundQuantitySum);
|
||||
}
|
||||
|
||||
public record ShopPeriodMetrics(
|
||||
BigDecimal salesAmount,
|
||||
BigDecimal refundAmount,
|
||||
BigDecimal productCost,
|
||||
BigDecimal freightCost,
|
||||
BigDecimal otherCost,
|
||||
BigDecimal dealAmount,
|
||||
int salesOrderCount,
|
||||
int salesQuantitySum,
|
||||
int dealOrderCount,
|
||||
int dealQuantitySum,
|
||||
int refundOrderCount,
|
||||
int refundQuantitySum
|
||||
) {
|
||||
}
|
||||
|
||||
private static OverviewAggRows.DailyRow emptyDaily(LocalDate d) {
|
||||
OverviewAggRows.DailyRow r = new OverviewAggRows.DailyRow();
|
||||
r.setStatDate(d);
|
||||
r.setSalesAmount(BigDecimal.ZERO);
|
||||
r.setDealAmount(BigDecimal.ZERO);
|
||||
r.setRefundAmount(BigDecimal.ZERO);
|
||||
r.setProductCost(BigDecimal.ZERO);
|
||||
r.setFreightCost(BigDecimal.ZERO);
|
||||
r.setOtherCost(BigDecimal.ZERO);
|
||||
r.setOrderCount(0L);
|
||||
r.setDealOrderCount(0L);
|
||||
r.setRefundOrderCount(0L);
|
||||
return r;
|
||||
}
|
||||
|
||||
private static void addDealRefundCost(OverviewAggRows.DailyRow row,
|
||||
BigDecimal dealAmount, Integer dealOrderCount,
|
||||
BigDecimal refundAmount, Integer refundOrderCount,
|
||||
BigDecimal productCost, BigDecimal freightCost, BigDecimal otherCost) {
|
||||
row.setDealAmount(nz(row.getDealAmount()).add(nz(dealAmount)));
|
||||
row.setDealOrderCount(nzLong(row.getDealOrderCount()) + nzInt(dealOrderCount));
|
||||
row.setRefundAmount(nz(row.getRefundAmount()).add(nz(refundAmount)));
|
||||
row.setRefundOrderCount(nzLong(row.getRefundOrderCount()) + nzInt(refundOrderCount));
|
||||
row.setProductCost(nz(row.getProductCost()).add(nz(productCost)));
|
||||
row.setFreightCost(nz(row.getFreightCost()).add(nz(freightCost)));
|
||||
row.setOtherCost(nz(row.getOtherCost()).add(nz(otherCost)));
|
||||
row.setSalesAmount(netAmount(row.getDealAmount(), row.getRefundAmount()));
|
||||
row.setOrderCount(netCountLong(
|
||||
nzLong(row.getDealOrderCount()),
|
||||
nzLong(row.getRefundOrderCount())));
|
||||
}
|
||||
|
||||
private static void fillNetSales(OverviewAggRows.ShopProductRow row) {
|
||||
row.setSalesAmount(netAmount(row.getDealAmount(), row.getRefundAmount()));
|
||||
row.setOrderCount(netCountLong(
|
||||
nzLong(row.getDealOrderCount()),
|
||||
nzLong(row.getRefundOrderCount())));
|
||||
row.setSalesQuantitySum(netCountLong(
|
||||
nzLong(row.getDealQuantitySum()),
|
||||
nzLong(row.getRefundQuantitySum())));
|
||||
}
|
||||
|
||||
private static void fillNetSalesSku(OverviewAggRows.ShopSkuRow row) {
|
||||
row.setSalesAmount(netAmount(row.getDealAmount(), row.getRefundAmount()));
|
||||
row.setOrderCount(netCountLong(
|
||||
nzLong(row.getDealOrderCount()),
|
||||
nzLong(row.getRefundOrderCount())));
|
||||
row.setSalesQuantitySum(netCountLong(
|
||||
nzLong(row.getDealQuantitySum()),
|
||||
nzLong(row.getRefundQuantitySum())));
|
||||
}
|
||||
|
||||
private static BigDecimal netAmount(BigDecimal deal, BigDecimal refund) {
|
||||
return nz(deal).subtract(nz(refund));
|
||||
}
|
||||
|
||||
private static int netCount(int deal, int refund) {
|
||||
return deal - refund;
|
||||
}
|
||||
|
||||
private static long netCountLong(long deal, long refund) {
|
||||
return deal - refund;
|
||||
}
|
||||
|
||||
private static BigDecimal nz(BigDecimal v) {
|
||||
return v != null ? v : BigDecimal.ZERO;
|
||||
}
|
||||
|
||||
private static long nzLong(Number v) {
|
||||
return v != null ? v.longValue() : 0L;
|
||||
}
|
||||
|
||||
private static int nzInt(Integer v) {
|
||||
return v != null ? v : 0;
|
||||
}
|
||||
}
|
||||
+325
@@ -0,0 +1,325 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.bi.orderstat.repository;
|
||||
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.bson.types.Decimal128;
|
||||
import org.springframework.data.mongodb.core.MongoTemplate;
|
||||
import org.springframework.data.mongodb.core.query.Criteria;
|
||||
import org.springframework.data.mongodb.core.query.Query;
|
||||
import org.springframework.data.mongodb.core.query.Update;
|
||||
import org.springframework.stereotype.Repository;
|
||||
import top.xyquan.ecomdmbbackend.modules.bi.messaging.BiProductStatDelta;
|
||||
import top.xyquan.ecomdmbbackend.modules.bi.messaging.BiSkuStatDelta;
|
||||
import top.xyquan.ecomdmbbackend.modules.bi.messaging.BiStatMetricDelta;
|
||||
import top.xyquan.ecomdmbbackend.modules.bi.orderstat.model.document.BiOrderStatDailyProductDoc;
|
||||
import top.xyquan.ecomdmbbackend.modules.bi.orderstat.model.document.BiOrderStatDailyShopDoc;
|
||||
import top.xyquan.ecomdmbbackend.modules.bi.orderstat.model.document.BiOrderStatDailySkuDoc;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.time.Instant;
|
||||
import java.time.LocalDate;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
|
||||
@Repository
|
||||
@RequiredArgsConstructor
|
||||
public class BiOrderStatDailyRepository {
|
||||
|
||||
private final MongoTemplate mongoTemplate;
|
||||
|
||||
public Optional<BiOrderStatDailyShopDoc> findShop(Long companyId, Long shopId, LocalDate statDate) {
|
||||
Query q = Query.query(Criteria.where("companyId").is(companyId)
|
||||
.and("shopId").is(shopId)
|
||||
.and("statDate").is(statDate));
|
||||
return Optional.ofNullable(mongoTemplate.findOne(q, BiOrderStatDailyShopDoc.class));
|
||||
}
|
||||
|
||||
/** 区间内店铺日文档(闭区间 [start, end])。shopIds 为空返回空列表。 */
|
||||
public List<BiOrderStatDailyShopDoc> listShopDocs(Long companyId, List<Long> shopIds,
|
||||
LocalDate start, LocalDate end) {
|
||||
if (companyId == null || shopIds == null || shopIds.isEmpty() || start == null || end == null) {
|
||||
return List.of();
|
||||
}
|
||||
Query q = Query.query(Criteria.where("companyId").is(companyId)
|
||||
.and("shopId").in(shopIds)
|
||||
.and("statDate").gte(start).lte(end));
|
||||
return mongoTemplate.find(q, BiOrderStatDailyShopDoc.class);
|
||||
}
|
||||
|
||||
/** 区间内商品日文档(闭区间)。shopIds 为空返回空列表。 */
|
||||
public List<BiOrderStatDailyProductDoc> listProductDocs(Long companyId, List<Long> shopIds,
|
||||
LocalDate start, LocalDate end) {
|
||||
return listProductDocs(companyId, shopIds, null, start, end);
|
||||
}
|
||||
|
||||
/**
|
||||
* 区间内商品日文档。{@code productId} 非空时仅该商品;
|
||||
* {@code shopIds} 为空时不按店过滤(商品概览未指定店铺时用)。
|
||||
*/
|
||||
public List<BiOrderStatDailyProductDoc> listProductDocs(Long companyId, List<Long> shopIds,
|
||||
Long productId,
|
||||
LocalDate start, LocalDate end) {
|
||||
if (companyId == null || start == null || end == null) {
|
||||
return List.of();
|
||||
}
|
||||
Criteria c = Criteria.where("companyId").is(companyId)
|
||||
.and("statDate").gte(start).lte(end);
|
||||
if (shopIds != null && !shopIds.isEmpty()) {
|
||||
c = c.and("shopId").in(shopIds);
|
||||
}
|
||||
if (productId != null) {
|
||||
c = c.and("productId").is(productId);
|
||||
}
|
||||
return mongoTemplate.find(Query.query(c), BiOrderStatDailyProductDoc.class);
|
||||
}
|
||||
|
||||
/**
|
||||
* 区间内 SKU 日文档。
|
||||
* {@code productId} 为空时不按商品过滤(公司/店铺级 SKU 汇总);
|
||||
* {@code shopIds} 为空时不按店过滤。
|
||||
*/
|
||||
public List<BiOrderStatDailySkuDoc> listSkuDocs(Long companyId, Long productId,
|
||||
List<Long> shopIds,
|
||||
LocalDate start, LocalDate end) {
|
||||
if (companyId == null || start == null || end == null) {
|
||||
return List.of();
|
||||
}
|
||||
Criteria c = Criteria.where("companyId").is(companyId)
|
||||
.and("statDate").gte(start).lte(end);
|
||||
if (productId != null) {
|
||||
c = c.and("productId").is(productId);
|
||||
}
|
||||
if (shopIds != null && !shopIds.isEmpty()) {
|
||||
c = c.and("shopId").in(shopIds);
|
||||
}
|
||||
return mongoTemplate.find(Query.query(c), BiOrderStatDailySkuDoc.class);
|
||||
}
|
||||
|
||||
/**
|
||||
* 按内部 SKU 主键拉区间日文档(SKU 概览)。
|
||||
* {@code shopIds} 为空时不按店过滤。
|
||||
*/
|
||||
public List<BiOrderStatDailySkuDoc> listSkuDocsBySkuId(Long companyId, Long productSkuId,
|
||||
List<Long> shopIds,
|
||||
LocalDate start, LocalDate end) {
|
||||
if (companyId == null || productSkuId == null || productSkuId <= 0
|
||||
|| start == null || end == null) {
|
||||
return List.of();
|
||||
}
|
||||
Criteria c = Criteria.where("companyId").is(companyId)
|
||||
.and("productSkuId").is(productSkuId)
|
||||
.and("statDate").gte(start).lte(end);
|
||||
if (shopIds != null && !shopIds.isEmpty()) {
|
||||
c = c.and("shopId").in(shopIds);
|
||||
}
|
||||
return mongoTemplate.find(Query.query(c), BiOrderStatDailySkuDoc.class);
|
||||
}
|
||||
|
||||
public void replaceShopDay(BiOrderStatDailyShopDoc shopDoc,
|
||||
List<BiOrderStatDailyProductDoc> products,
|
||||
List<BiOrderStatDailySkuDoc> skus) {
|
||||
Long companyId = shopDoc.getCompanyId();
|
||||
Long shopId = shopDoc.getShopId();
|
||||
LocalDate statDate = shopDoc.getStatDate();
|
||||
|
||||
Query dayQ = Query.query(Criteria.where("companyId").is(companyId)
|
||||
.and("shopId").is(shopId)
|
||||
.and("statDate").is(statDate));
|
||||
|
||||
findShop(companyId, shopId, statDate).ifPresentOrElse(existing -> {
|
||||
shopDoc.setId(existing.getId());
|
||||
if (!"FULL".equals(shopDoc.getComputeMode()) && existing.getDbSnapshotTime() != null) {
|
||||
shopDoc.setDbSnapshotTime(existing.getDbSnapshotTime());
|
||||
}
|
||||
mongoTemplate.save(shopDoc);
|
||||
}, () -> mongoTemplate.insert(shopDoc));
|
||||
|
||||
mongoTemplate.remove(dayQ, BiOrderStatDailyProductDoc.class);
|
||||
mongoTemplate.remove(dayQ, BiOrderStatDailySkuDoc.class);
|
||||
if (products != null && !products.isEmpty()) {
|
||||
mongoTemplate.insertAll(products);
|
||||
}
|
||||
if (skus != null && !skus.isEmpty()) {
|
||||
mongoTemplate.insertAll(skus);
|
||||
}
|
||||
}
|
||||
|
||||
/** 将转换侧算出的增量累加到日文档(无文档则按 delta 新建)。 */
|
||||
public void applyIncDeltas(Long companyId, Long shopId, String platformCode, LocalDate statDate,
|
||||
BiStatMetricDelta shopDelta,
|
||||
List<BiProductStatDelta> productDeltas,
|
||||
List<BiSkuStatDelta> skuDeltas) {
|
||||
Instant now = Instant.now();
|
||||
Optional<BiOrderStatDailyShopDoc> existing = findShop(companyId, shopId, statDate);
|
||||
if (existing.isEmpty()) {
|
||||
BiOrderStatDailyShopDoc shop = new BiOrderStatDailyShopDoc();
|
||||
shop.setCompanyId(companyId);
|
||||
shop.setShopId(shopId);
|
||||
shop.setPlatformCode(platformCode);
|
||||
shop.setStatDate(statDate);
|
||||
applyMetricToShop(shop, shopDelta);
|
||||
shop.setComputeMode("INC");
|
||||
shop.setComputedAt(now);
|
||||
mongoTemplate.insert(shop);
|
||||
} else {
|
||||
Query q = Query.query(Criteria.where("companyId").is(companyId)
|
||||
.and("shopId").is(shopId)
|
||||
.and("statDate").is(statDate));
|
||||
Update u = metricIncUpdate(shopDelta);
|
||||
u.set("computedAt", now).set("computeMode", "INC");
|
||||
if (platformCode != null) {
|
||||
u.set("platformCode", platformCode);
|
||||
}
|
||||
mongoTemplate.updateFirst(q, u, BiOrderStatDailyShopDoc.class);
|
||||
}
|
||||
|
||||
if (productDeltas != null) {
|
||||
for (BiProductStatDelta pd : productDeltas) {
|
||||
if (pd.getMetrics() == null || pd.getMetrics().isAllZero()) {
|
||||
continue;
|
||||
}
|
||||
long productId = pd.getProductId() != null ? pd.getProductId() : 0L;
|
||||
Query pq = Query.query(Criteria.where("companyId").is(companyId)
|
||||
.and("shopId").is(shopId)
|
||||
.and("productId").is(productId)
|
||||
.and("statDate").is(statDate));
|
||||
BiOrderStatDailyProductDoc found = mongoTemplate.findOne(pq, BiOrderStatDailyProductDoc.class);
|
||||
if (found == null) {
|
||||
BiOrderStatDailyProductDoc doc = new BiOrderStatDailyProductDoc();
|
||||
doc.setCompanyId(companyId);
|
||||
doc.setShopId(shopId);
|
||||
doc.setProductId(productId);
|
||||
doc.setStatDate(statDate);
|
||||
applyMetricToProduct(doc, pd.getMetrics());
|
||||
doc.setComputeMode("INC");
|
||||
doc.setComputedAt(now);
|
||||
mongoTemplate.insert(doc);
|
||||
} else {
|
||||
Update u = metricIncUpdate(pd.getMetrics());
|
||||
u.set("computedAt", now).set("computeMode", "INC");
|
||||
mongoTemplate.updateFirst(pq, u, BiOrderStatDailyProductDoc.class);
|
||||
}
|
||||
}
|
||||
}
|
||||
if (skuDeltas != null) {
|
||||
for (BiSkuStatDelta sd : skuDeltas) {
|
||||
if (sd.getMetrics() == null || sd.getMetrics().isAllZero()) {
|
||||
continue;
|
||||
}
|
||||
long productId = sd.getProductId() != null ? sd.getProductId() : 0L;
|
||||
long skuId = sd.getProductSkuId() != null ? sd.getProductSkuId() : 0L;
|
||||
Query sq = Query.query(Criteria.where("companyId").is(companyId)
|
||||
.and("shopId").is(shopId)
|
||||
.and("productSkuId").is(skuId)
|
||||
.and("statDate").is(statDate));
|
||||
BiOrderStatDailySkuDoc found = mongoTemplate.findOne(sq, BiOrderStatDailySkuDoc.class);
|
||||
if (found == null) {
|
||||
BiOrderStatDailySkuDoc doc = new BiOrderStatDailySkuDoc();
|
||||
doc.setCompanyId(companyId);
|
||||
doc.setShopId(shopId);
|
||||
doc.setProductId(productId);
|
||||
doc.setProductSkuId(skuId);
|
||||
doc.setStatDate(statDate);
|
||||
applyMetricToSku(doc, sd.getMetrics());
|
||||
doc.setComputeMode("INC");
|
||||
doc.setComputedAt(now);
|
||||
mongoTemplate.insert(doc);
|
||||
} else {
|
||||
Update u = metricIncUpdate(sd.getMetrics());
|
||||
u.set("computedAt", now).set("computeMode", "INC");
|
||||
mongoTemplate.updateFirst(sq, u, BiOrderStatDailySkuDoc.class);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private static Update metricIncUpdate(BiStatMetricDelta d) {
|
||||
Update u = new Update();
|
||||
if (d == null) {
|
||||
return u;
|
||||
}
|
||||
inc(u, "dealAmount", d.getDealAmount());
|
||||
inc(u, "dealOrderCount", d.getDealOrderCount());
|
||||
inc(u, "dealQuantitySum", d.getDealQuantitySum());
|
||||
inc(u, "refundAmount", d.getRefundAmount());
|
||||
inc(u, "refundOrderCount", d.getRefundOrderCount());
|
||||
inc(u, "refundQuantitySum", d.getRefundQuantitySum());
|
||||
inc(u, "serviceFee", d.getServiceFee());
|
||||
inc(u, "productCost", d.getProductCost());
|
||||
inc(u, "freightCost", d.getFreightCost());
|
||||
inc(u, "otherCost", d.getOtherCost());
|
||||
return u;
|
||||
}
|
||||
|
||||
private static void inc(Update u, String field, Number v) {
|
||||
if (v == null) {
|
||||
return;
|
||||
}
|
||||
if (v instanceof BigDecimal bd) {
|
||||
if (bd.signum() == 0) {
|
||||
return;
|
||||
}
|
||||
u.inc(field, new Decimal128(bd));
|
||||
return;
|
||||
}
|
||||
if (v instanceof Integer i && i == 0) {
|
||||
return;
|
||||
}
|
||||
u.inc(field, v);
|
||||
}
|
||||
|
||||
private static void applyMetricToShop(BiOrderStatDailyShopDoc doc, BiStatMetricDelta d) {
|
||||
if (d == null) {
|
||||
return;
|
||||
}
|
||||
doc.setDealAmount(nz(d.getDealAmount()));
|
||||
doc.setDealOrderCount(nzi(d.getDealOrderCount()));
|
||||
doc.setDealQuantitySum(nzi(d.getDealQuantitySum()));
|
||||
doc.setRefundAmount(nz(d.getRefundAmount()));
|
||||
doc.setRefundOrderCount(nzi(d.getRefundOrderCount()));
|
||||
doc.setRefundQuantitySum(nzi(d.getRefundQuantitySum()));
|
||||
doc.setServiceFee(nz(d.getServiceFee()));
|
||||
doc.setProductCost(nz(d.getProductCost()));
|
||||
doc.setFreightCost(nz(d.getFreightCost()));
|
||||
doc.setOtherCost(nz(d.getOtherCost()));
|
||||
}
|
||||
|
||||
private static void applyMetricToProduct(BiOrderStatDailyProductDoc doc, BiStatMetricDelta d) {
|
||||
if (d == null) {
|
||||
return;
|
||||
}
|
||||
doc.setDealAmount(nz(d.getDealAmount()));
|
||||
doc.setDealOrderCount(nzi(d.getDealOrderCount()));
|
||||
doc.setDealQuantitySum(nzi(d.getDealQuantitySum()));
|
||||
doc.setRefundAmount(nz(d.getRefundAmount()));
|
||||
doc.setRefundOrderCount(nzi(d.getRefundOrderCount()));
|
||||
doc.setRefundQuantitySum(nzi(d.getRefundQuantitySum()));
|
||||
doc.setServiceFee(nz(d.getServiceFee()));
|
||||
doc.setProductCost(nz(d.getProductCost()));
|
||||
doc.setFreightCost(nz(d.getFreightCost()));
|
||||
doc.setOtherCost(nz(d.getOtherCost()));
|
||||
}
|
||||
|
||||
private static void applyMetricToSku(BiOrderStatDailySkuDoc doc, BiStatMetricDelta d) {
|
||||
if (d == null) {
|
||||
return;
|
||||
}
|
||||
doc.setDealAmount(nz(d.getDealAmount()));
|
||||
doc.setDealOrderCount(nzi(d.getDealOrderCount()));
|
||||
doc.setDealQuantitySum(nzi(d.getDealQuantitySum()));
|
||||
doc.setRefundAmount(nz(d.getRefundAmount()));
|
||||
doc.setRefundOrderCount(nzi(d.getRefundOrderCount()));
|
||||
doc.setRefundQuantitySum(nzi(d.getRefundQuantitySum()));
|
||||
doc.setServiceFee(nz(d.getServiceFee()));
|
||||
doc.setProductCost(nz(d.getProductCost()));
|
||||
doc.setFreightCost(nz(d.getFreightCost()));
|
||||
doc.setOtherCost(nz(d.getOtherCost()));
|
||||
}
|
||||
|
||||
private static BigDecimal nz(BigDecimal v) {
|
||||
return v != null ? v : BigDecimal.ZERO;
|
||||
}
|
||||
|
||||
private static int nzi(Integer v) {
|
||||
return v != null ? v : 0;
|
||||
}
|
||||
}
|
||||
+685
@@ -0,0 +1,685 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.bi.orderstat.service;
|
||||
|
||||
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
|
||||
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.amqp.rabbit.core.RabbitTemplate;
|
||||
import org.springframework.dao.DuplicateKeyException;
|
||||
import org.springframework.data.redis.core.StringRedisTemplate;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.PlatformTransactionManager;
|
||||
import org.springframework.transaction.TransactionDefinition;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
import org.springframework.transaction.support.DefaultTransactionDefinition;
|
||||
import org.springframework.transaction.support.TransactionTemplate;
|
||||
import top.xyquan.ecomdmbbackend.common.exception.BusinessException;
|
||||
import top.xyquan.ecomdmbbackend.common.mq.OrderMqConstants;
|
||||
import top.xyquan.ecomdmbbackend.common.mq.TaskTriggerSource;
|
||||
import top.xyquan.ecomdmbbackend.modules.bi.infra.config.BiStatProperties;
|
||||
import top.xyquan.ecomdmbbackend.modules.bi.messaging.BiFullCalcMessage;
|
||||
import top.xyquan.ecomdmbbackend.modules.bi.orderstat.mapper.BiOrderStatFullCalcTaskDayMapper;
|
||||
import top.xyquan.ecomdmbbackend.modules.bi.orderstat.mapper.BiOrderStatFullCalcTaskMapper;
|
||||
import top.xyquan.ecomdmbbackend.modules.bi.orderstat.mapper.BiOrderStatIncCalcMapper;
|
||||
import top.xyquan.ecomdmbbackend.modules.bi.orderstat.model.po.BiOrderStatFullCalcTaskDayPO;
|
||||
import top.xyquan.ecomdmbbackend.modules.bi.orderstat.model.po.BiOrderStatFullCalcTaskPO;
|
||||
import top.xyquan.ecomdmbbackend.modules.bi.orderstat.model.po.BiOrderStatIncCalcPO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.platform.model.enums.PlatformCode;
|
||||
|
||||
import java.time.Duration;
|
||||
import java.time.LocalDate;
|
||||
import java.time.LocalDateTime;
|
||||
import java.time.OffsetDateTime;
|
||||
import java.time.ZoneId;
|
||||
import java.time.temporal.ChronoUnit;
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Objects;
|
||||
import java.util.UUID;
|
||||
|
||||
/**
|
||||
* BI 全量/增量计算控制面:懒建任务、投递 full、回写日态与 INC 店态(成功节流)。
|
||||
*/
|
||||
@Slf4j
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
public class BiOrderStatCalcTaskService {
|
||||
|
||||
private static final ZoneId ZONE = ZoneId.of("Asia/Shanghai");
|
||||
private static final String INC_FLUSH_KEY = "bi:stat:inc:flush:";
|
||||
/** 手动全量计算可选日历窗口(与同步/转换近 90 天对齐) */
|
||||
public static final int FULL_CALC_MAX_CALENDAR_DAYS = 90;
|
||||
|
||||
private final BiOrderStatFullCalcTaskMapper taskMapper;
|
||||
private final BiOrderStatFullCalcTaskDayMapper dayMapper;
|
||||
private final BiOrderStatIncCalcMapper incCalcMapper;
|
||||
private final RabbitTemplate rabbitTemplate;
|
||||
private final StringRedisTemplate stringRedisTemplate;
|
||||
private final BiStatProperties biStatProperties;
|
||||
private final PlatformTransactionManager transactionManager;
|
||||
|
||||
private TransactionTemplate newTxTemplate() {
|
||||
DefaultTransactionDefinition def = new DefaultTransactionDefinition();
|
||||
def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRES_NEW);
|
||||
return new TransactionTemplate(transactionManager, def);
|
||||
}
|
||||
|
||||
/**
|
||||
* 手动按区间创建全量计算(upstream 空):预建 day,提交后按日投递 bi.stat.full。
|
||||
*
|
||||
* @param companyId 公司
|
||||
* @param internalShopId ec_shop.id
|
||||
* @param platform 平台编码,空则 pdd
|
||||
*/
|
||||
@Transactional(rollbackFor = Exception.class)
|
||||
public BiOrderStatFullCalcTaskPO createManualTask(Long companyId, Long internalShopId,
|
||||
String platform, LocalDate dateFrom, LocalDate dateTo) {
|
||||
if (companyId == null || internalShopId == null || dateFrom == null || dateTo == null) {
|
||||
throw new BusinessException("参数不完整");
|
||||
}
|
||||
if (dateTo.isBefore(dateFrom)) {
|
||||
throw new BusinessException("结束日期不能早于开始日期");
|
||||
}
|
||||
LocalDate today = LocalDate.now(ZONE);
|
||||
if (dateTo.isAfter(today)) {
|
||||
throw new BusinessException("结束日期不能晚于今天");
|
||||
}
|
||||
int maxDays = FULL_CALC_MAX_CALENDAR_DAYS;
|
||||
LocalDate earliest = today.minusDays(maxDays - 1L);
|
||||
if (dateFrom.isBefore(earliest)) {
|
||||
throw new BusinessException("全量计算仅支持近 " + maxDays
|
||||
+ " 天(含今天):最早可选 " + earliest);
|
||||
}
|
||||
|
||||
BiOrderStatFullCalcTaskPO active = taskMapper.selectOne(new LambdaQueryWrapper<BiOrderStatFullCalcTaskPO>()
|
||||
.eq(BiOrderStatFullCalcTaskPO::getCompanyId, companyId)
|
||||
.eq(BiOrderStatFullCalcTaskPO::getShopId, internalShopId)
|
||||
.in(BiOrderStatFullCalcTaskPO::getStatus,
|
||||
BiOrderStatFullCalcTaskPO.STATUS_PENDING,
|
||||
BiOrderStatFullCalcTaskPO.STATUS_RUNNING)
|
||||
.orderByDesc(BiOrderStatFullCalcTaskPO::getId)
|
||||
.last("LIMIT 1"));
|
||||
if (active != null) {
|
||||
throw new BusinessException(String.format(
|
||||
"该店已有进行中的全量计算 #%d(%s~%s),请等待完成后再创建",
|
||||
active.getId(), active.getDateFrom(), active.getDateTo()));
|
||||
}
|
||||
|
||||
String platformCode = platform != null && !platform.isBlank()
|
||||
? platform : PlatformCode.PDD.getCode();
|
||||
int totalDays = (int) ChronoUnit.DAYS.between(dateFrom, dateTo) + 1;
|
||||
BiOrderStatFullCalcTaskPO task = new BiOrderStatFullCalcTaskPO();
|
||||
task.setCompanyId(companyId);
|
||||
task.setShopId(internalShopId);
|
||||
task.setPlatformCode(platformCode);
|
||||
task.setTriggerSource(TaskTriggerSource.MANUAL);
|
||||
task.setUpstreamTaskId(null);
|
||||
task.setDateFrom(dateFrom);
|
||||
task.setDateTo(dateTo);
|
||||
task.setTotalDays(totalDays);
|
||||
task.setDoneDays(0);
|
||||
task.setFailedDays(0);
|
||||
task.setSkippedDays(0);
|
||||
task.setStatus(BiOrderStatFullCalcTaskPO.STATUS_PENDING);
|
||||
BiOrderStatFullCalcTaskPO saved = newTxTemplate().execute(status -> {
|
||||
taskMapper.insert(task);
|
||||
insertDayRows(task);
|
||||
return task;
|
||||
});
|
||||
publishFullDateRange(saved.getId(), companyId, internalShopId, platformCode, dateFrom, dateTo);
|
||||
return saved;
|
||||
}
|
||||
|
||||
private void publishFullDateRange(Long taskId, Long companyId, Long shopId, String platform,
|
||||
LocalDate from, LocalDate to) {
|
||||
for (LocalDate d = from; !d.isAfter(to); d = d.plusDays(1)) {
|
||||
publishFull(companyId, shopId, platform, d,
|
||||
"bi:" + shopId + ":" + d, taskId, null);
|
||||
}
|
||||
log.info("BI 全量已投递全部日消息 calcTaskId={} {}~{}", taskId, from, to);
|
||||
}
|
||||
|
||||
private void publishFullDays(Long taskId, Long companyId, Long shopId, String platform,
|
||||
List<LocalDate> days) {
|
||||
for (LocalDate d : days) {
|
||||
publishFull(companyId, shopId, platform, d,
|
||||
"bi:" + shopId + ":" + d, taskId, null);
|
||||
}
|
||||
log.info("BI 全量已投递 {} 日消息 calcTaskId={}", days.size(), taskId);
|
||||
}
|
||||
|
||||
/**
|
||||
* 转换成功某日后:按 trigger_source=CONVERT + upstream_task_id 懒建 BI 任务并预建 days,再投递该日 full。
|
||||
*
|
||||
* @return calcTaskId
|
||||
*/
|
||||
public Long ensureAndPublishAfterConvertDay(Long convertTaskId, Long companyId, Long internalShopId,
|
||||
String platform, LocalDate dateFrom, LocalDate dateTo,
|
||||
LocalDate day, String syncBatchId) {
|
||||
if (convertTaskId == null || companyId == null || internalShopId == null
|
||||
|| dateFrom == null || dateTo == null || day == null) {
|
||||
return null;
|
||||
}
|
||||
BiOrderStatFullCalcTaskPO task = findByUpstream(TaskTriggerSource.CONVERT, convertTaskId);
|
||||
if (task == null) {
|
||||
task = createForConvert(convertTaskId, companyId, internalShopId, platform, dateFrom, dateTo);
|
||||
}
|
||||
publishFull(companyId, internalShopId, platform, day, syncBatchId, task.getId(), convertTaskId);
|
||||
return task.getId();
|
||||
}
|
||||
|
||||
public void markDayRunning(Long calcTaskId, LocalDate day) {
|
||||
if (calcTaskId == null || day == null) {
|
||||
return;
|
||||
}
|
||||
LocalDateTime now = LocalDateTime.now(ZONE);
|
||||
dayMapper.update(null, new LambdaUpdateWrapper<BiOrderStatFullCalcTaskDayPO>()
|
||||
.eq(BiOrderStatFullCalcTaskDayPO::getTaskId, calcTaskId)
|
||||
.eq(BiOrderStatFullCalcTaskDayPO::getDay, day)
|
||||
.in(BiOrderStatFullCalcTaskDayPO::getStatus,
|
||||
BiOrderStatFullCalcTaskDayPO.STATUS_PENDING,
|
||||
BiOrderStatFullCalcTaskDayPO.STATUS_RUNNING)
|
||||
.set(BiOrderStatFullCalcTaskDayPO::getStatus, BiOrderStatFullCalcTaskDayPO.STATUS_RUNNING)
|
||||
.set(BiOrderStatFullCalcTaskDayPO::getStartTime, now)
|
||||
.set(BiOrderStatFullCalcTaskDayPO::getLastError, null)
|
||||
.set(BiOrderStatFullCalcTaskDayPO::getFinishTime, null));
|
||||
taskMapper.update(null, new LambdaUpdateWrapper<BiOrderStatFullCalcTaskPO>()
|
||||
.eq(BiOrderStatFullCalcTaskPO::getId, calcTaskId)
|
||||
.in(BiOrderStatFullCalcTaskPO::getStatus,
|
||||
BiOrderStatFullCalcTaskPO.STATUS_PENDING,
|
||||
BiOrderStatFullCalcTaskPO.STATUS_RUNNING)
|
||||
.set(BiOrderStatFullCalcTaskPO::getStatus, BiOrderStatFullCalcTaskPO.STATUS_RUNNING)
|
||||
.set(BiOrderStatFullCalcTaskPO::getCurrentDate, day)
|
||||
.set(BiOrderStatFullCalcTaskPO::getFinishTime, null));
|
||||
}
|
||||
|
||||
public void markDaySuccess(Long calcTaskId, LocalDate day, LocalDateTime dbSnapshotTime) {
|
||||
if (calcTaskId == null || day == null) {
|
||||
return;
|
||||
}
|
||||
dayMapper.update(null, new LambdaUpdateWrapper<BiOrderStatFullCalcTaskDayPO>()
|
||||
.eq(BiOrderStatFullCalcTaskDayPO::getTaskId, calcTaskId)
|
||||
.eq(BiOrderStatFullCalcTaskDayPO::getDay, day)
|
||||
.set(BiOrderStatFullCalcTaskDayPO::getStatus, BiOrderStatFullCalcTaskDayPO.STATUS_SUCCESS)
|
||||
.set(BiOrderStatFullCalcTaskDayPO::getDbSnapshotTime, dbSnapshotTime)
|
||||
.set(BiOrderStatFullCalcTaskDayPO::getLastError, null)
|
||||
.set(BiOrderStatFullCalcTaskDayPO::getFinishTime, LocalDateTime.now(ZONE)));
|
||||
refreshParentAggregates(calcTaskId, day, null);
|
||||
}
|
||||
|
||||
public void markDayFailed(Long calcTaskId, LocalDate day, String error) {
|
||||
if (calcTaskId == null || day == null) {
|
||||
return;
|
||||
}
|
||||
String err = truncate(error, 512);
|
||||
dayMapper.update(null, new LambdaUpdateWrapper<BiOrderStatFullCalcTaskDayPO>()
|
||||
.eq(BiOrderStatFullCalcTaskDayPO::getTaskId, calcTaskId)
|
||||
.eq(BiOrderStatFullCalcTaskDayPO::getDay, day)
|
||||
.set(BiOrderStatFullCalcTaskDayPO::getStatus, BiOrderStatFullCalcTaskDayPO.STATUS_FAILED)
|
||||
.set(BiOrderStatFullCalcTaskDayPO::getLastError, err)
|
||||
.set(BiOrderStatFullCalcTaskDayPO::getFinishTime, LocalDateTime.now(ZONE)));
|
||||
refreshParentAggregates(calcTaskId, day, err);
|
||||
}
|
||||
|
||||
/**
|
||||
* 成功应用或快照跳过:默认 ≥30s 节流写店态。
|
||||
*/
|
||||
public void recordIncAppliedThrottled(Long companyId, Long internalShopId, LocalDate statDate,
|
||||
Long orderId, boolean skipped) {
|
||||
if (companyId == null || internalShopId == null) {
|
||||
return;
|
||||
}
|
||||
long flushSeconds = Math.max(biStatProperties.getIncStatusFlushSeconds(), 1L);
|
||||
Boolean acquired = stringRedisTemplate.opsForValue().setIfAbsent(
|
||||
INC_FLUSH_KEY + internalShopId, "1", Duration.ofSeconds(flushSeconds));
|
||||
if (!Boolean.TRUE.equals(acquired)) {
|
||||
return;
|
||||
}
|
||||
BiOrderStatIncCalcPO state = getOrCreateInc(companyId, internalShopId);
|
||||
state.setStatus(BiOrderStatIncCalcPO.STATUS_OK);
|
||||
state.setLastError(null);
|
||||
state.setLastSuccessTime(LocalDateTime.now(ZONE));
|
||||
if (statDate != null) {
|
||||
state.setLastStatDate(statDate);
|
||||
}
|
||||
if (orderId != null) {
|
||||
state.setLastAppliedOrderId(orderId);
|
||||
}
|
||||
state.setLastSkipped(skipped ? 1 : 0);
|
||||
state.setLastSummary(skipped
|
||||
? ("计算跳过(快照内),统计日 " + (statDate != null ? statDate : "-"))
|
||||
: ("计算已累加,统计日 " + (statDate != null ? statDate : "-")
|
||||
+ (orderId != null ? ",订单#" + orderId : "")));
|
||||
incCalcMapper.updateById(state);
|
||||
}
|
||||
|
||||
/** 失败立即写 PAUSED。 */
|
||||
public void recordIncFailureImmediate(Long companyId, Long internalShopId, String error) {
|
||||
if (companyId == null || internalShopId == null) {
|
||||
return;
|
||||
}
|
||||
BiOrderStatIncCalcPO state = getOrCreateInc(companyId, internalShopId);
|
||||
state.setStatus(BiOrderStatIncCalcPO.STATUS_PAUSED);
|
||||
String detail = truncate(error, 1000);
|
||||
state.setLastError(detail);
|
||||
state.setLastSummary(truncate("计算失败:" + (detail != null ? detail : "未知错误"), 500));
|
||||
incCalcMapper.updateById(state);
|
||||
}
|
||||
|
||||
/** 增量计算店态;shopId = ec_shop.id。 */
|
||||
public BiOrderStatIncCalcPO findIncState(Long internalShopId) {
|
||||
if (internalShopId == null) {
|
||||
return null;
|
||||
}
|
||||
return incCalcMapper.selectOne(new LambdaQueryWrapper<BiOrderStatIncCalcPO>()
|
||||
.eq(BiOrderStatIncCalcPO::getShopId, internalShopId)
|
||||
.last("LIMIT 1"));
|
||||
}
|
||||
|
||||
/** 出错暂停后人工恢复。 */
|
||||
public BiOrderStatIncCalcPO resumeInc(Long companyId, Long internalShopId) {
|
||||
BiOrderStatIncCalcPO state = getOrCreateInc(companyId, internalShopId);
|
||||
state.setStatus(BiOrderStatIncCalcPO.STATUS_OK);
|
||||
state.setLastError(null);
|
||||
state.setLastSummary("已恢复计算,等待后续消息");
|
||||
incCalcMapper.updateById(state);
|
||||
return state;
|
||||
}
|
||||
|
||||
/** 全量计算任务列表(内部店)。 */
|
||||
public List<BiOrderStatFullCalcTaskPO> listTasks(Long companyId, Long internalShopId, int limit) {
|
||||
if (companyId == null || internalShopId == null) {
|
||||
return List.of();
|
||||
}
|
||||
int lim = Math.min(Math.max(limit, 1), 50);
|
||||
return taskMapper.selectList(new LambdaQueryWrapper<BiOrderStatFullCalcTaskPO>()
|
||||
.eq(BiOrderStatFullCalcTaskPO::getCompanyId, companyId)
|
||||
.eq(BiOrderStatFullCalcTaskPO::getShopId, internalShopId)
|
||||
.orderByDesc(BiOrderStatFullCalcTaskPO::getId)
|
||||
.last("LIMIT " + lim));
|
||||
}
|
||||
|
||||
private void publishFull(Long companyId, Long shopId, String platform, LocalDate day,
|
||||
String syncBatchId, Long calcTaskId, Long convertTaskId) {
|
||||
BiFullCalcMessage msg = BiFullCalcMessage.builder()
|
||||
.messageId(UUID.randomUUID().toString())
|
||||
.companyId(companyId)
|
||||
.shopId(shopId)
|
||||
.platformCode(platform)
|
||||
.statDate(day.toString())
|
||||
.syncBatchId(syncBatchId != null ? syncBatchId : "bi:" + shopId + ":" + day)
|
||||
.calcTaskId(calcTaskId)
|
||||
.convertTaskId(convertTaskId)
|
||||
.occurredAt(OffsetDateTime.now(ZONE))
|
||||
.retryCount(0)
|
||||
.build();
|
||||
rabbitTemplate.convertAndSend(OrderMqConstants.EXCHANGE, OrderMqConstants.RK_BI_STAT_FULL, msg);
|
||||
log.info("已投递 BI full(控制面) shopId={} day={} calcTaskId={}", shopId, day, calcTaskId);
|
||||
}
|
||||
|
||||
private BiOrderStatFullCalcTaskPO createForConvert(Long convertTaskId, Long companyId, Long internalShopId,
|
||||
String platform, LocalDate dateFrom, LocalDate dateTo) {
|
||||
int totalDays = (int) ChronoUnit.DAYS.between(dateFrom, dateTo) + 1;
|
||||
BiOrderStatFullCalcTaskPO task = new BiOrderStatFullCalcTaskPO();
|
||||
task.setCompanyId(companyId);
|
||||
task.setShopId(internalShopId);
|
||||
task.setPlatformCode(platform);
|
||||
task.setTriggerSource(TaskTriggerSource.CONVERT);
|
||||
task.setUpstreamTaskId(convertTaskId);
|
||||
task.setDateFrom(dateFrom);
|
||||
task.setDateTo(dateTo);
|
||||
task.setTotalDays(totalDays);
|
||||
task.setDoneDays(0);
|
||||
task.setFailedDays(0);
|
||||
task.setSkippedDays(0);
|
||||
task.setStatus(BiOrderStatFullCalcTaskPO.STATUS_PENDING);
|
||||
try {
|
||||
taskMapper.insert(task);
|
||||
insertDayRows(task);
|
||||
return task;
|
||||
} catch (DuplicateKeyException e) {
|
||||
log.info("BI 全量任务并发创建,回读 CONVERT upstreamTaskId={}", convertTaskId);
|
||||
BiOrderStatFullCalcTaskPO existing = findByUpstream(TaskTriggerSource.CONVERT, convertTaskId);
|
||||
if (existing == null) {
|
||||
throw e;
|
||||
}
|
||||
return existing;
|
||||
}
|
||||
}
|
||||
|
||||
private void insertDayRows(BiOrderStatFullCalcTaskPO task) {
|
||||
for (LocalDate d = task.getDateFrom(); !d.isAfter(task.getDateTo()); d = d.plusDays(1)) {
|
||||
insertOneDayRow(task, d);
|
||||
}
|
||||
}
|
||||
|
||||
private void insertDayRows(BiOrderStatFullCalcTaskPO task, List<LocalDate> days) {
|
||||
for (LocalDate d : days) {
|
||||
insertOneDayRow(task, d);
|
||||
}
|
||||
}
|
||||
|
||||
private void insertOneDayRow(BiOrderStatFullCalcTaskPO task, LocalDate d) {
|
||||
BiOrderStatFullCalcTaskDayPO row = new BiOrderStatFullCalcTaskDayPO();
|
||||
row.setTaskId(task.getId());
|
||||
row.setCompanyId(task.getCompanyId());
|
||||
row.setShopId(task.getShopId());
|
||||
row.setDay(d);
|
||||
row.setStatus(BiOrderStatFullCalcTaskDayPO.STATUS_PENDING);
|
||||
try {
|
||||
dayMapper.insert(row);
|
||||
} catch (DuplicateKeyException ignore) {
|
||||
// 并发预建
|
||||
}
|
||||
}
|
||||
|
||||
private void refreshParentAggregates(Long calcTaskId, LocalDate activityDay, String lastError) {
|
||||
Long done = dayMapper.selectCount(new LambdaQueryWrapper<BiOrderStatFullCalcTaskDayPO>()
|
||||
.eq(BiOrderStatFullCalcTaskDayPO::getTaskId, calcTaskId)
|
||||
.eq(BiOrderStatFullCalcTaskDayPO::getStatus, BiOrderStatFullCalcTaskDayPO.STATUS_SUCCESS));
|
||||
Long failed = dayMapper.selectCount(new LambdaQueryWrapper<BiOrderStatFullCalcTaskDayPO>()
|
||||
.eq(BiOrderStatFullCalcTaskDayPO::getTaskId, calcTaskId)
|
||||
.eq(BiOrderStatFullCalcTaskDayPO::getStatus, BiOrderStatFullCalcTaskDayPO.STATUS_FAILED));
|
||||
Long skipped = dayMapper.selectCount(new LambdaQueryWrapper<BiOrderStatFullCalcTaskDayPO>()
|
||||
.eq(BiOrderStatFullCalcTaskDayPO::getTaskId, calcTaskId)
|
||||
.eq(BiOrderStatFullCalcTaskDayPO::getStatus, BiOrderStatFullCalcTaskDayPO.STATUS_SKIPPED));
|
||||
int doneN = done == null ? 0 : done.intValue();
|
||||
int failedN = failed == null ? 0 : failed.intValue();
|
||||
int skippedN = skipped == null ? 0 : skipped.intValue();
|
||||
|
||||
LambdaUpdateWrapper<BiOrderStatFullCalcTaskPO> uw = new LambdaUpdateWrapper<BiOrderStatFullCalcTaskPO>()
|
||||
.eq(BiOrderStatFullCalcTaskPO::getId, calcTaskId)
|
||||
.ne(BiOrderStatFullCalcTaskPO::getStatus, BiOrderStatFullCalcTaskPO.STATUS_CANCELLED)
|
||||
.set(BiOrderStatFullCalcTaskPO::getDoneDays, doneN)
|
||||
.set(BiOrderStatFullCalcTaskPO::getFailedDays, failedN)
|
||||
.set(BiOrderStatFullCalcTaskPO::getSkippedDays, skippedN);
|
||||
if (activityDay != null) {
|
||||
uw.set(BiOrderStatFullCalcTaskPO::getCurrentDate, activityDay);
|
||||
}
|
||||
if (lastError != null) {
|
||||
uw.set(BiOrderStatFullCalcTaskPO::getLastError, truncate(lastError, 512));
|
||||
}
|
||||
taskMapper.update(null, uw);
|
||||
maybeComplete(calcTaskId);
|
||||
}
|
||||
|
||||
private void maybeComplete(Long calcTaskId) {
|
||||
BiOrderStatFullCalcTaskPO task = taskMapper.selectById(calcTaskId);
|
||||
if (task == null
|
||||
|| BiOrderStatFullCalcTaskPO.STATUS_CANCELLED.equals(task.getStatus())
|
||||
|| BiOrderStatFullCalcTaskPO.STATUS_SUCCESS.equals(task.getStatus())) {
|
||||
return;
|
||||
}
|
||||
int total = task.getTotalDays() == null ? 0 : task.getTotalDays();
|
||||
int done = task.getDoneDays() == null ? 0 : task.getDoneDays();
|
||||
int failed = task.getFailedDays() == null ? 0 : task.getFailedDays();
|
||||
int skipped = task.getSkippedDays() == null ? 0 : task.getSkippedDays();
|
||||
if (total <= 0 || done + failed + skipped < total) {
|
||||
return;
|
||||
}
|
||||
if (failed > 0) {
|
||||
taskMapper.update(null, new LambdaUpdateWrapper<BiOrderStatFullCalcTaskPO>()
|
||||
.eq(BiOrderStatFullCalcTaskPO::getId, calcTaskId)
|
||||
.ne(BiOrderStatFullCalcTaskPO::getStatus, BiOrderStatFullCalcTaskPO.STATUS_CANCELLED)
|
||||
.set(BiOrderStatFullCalcTaskPO::getStatus, BiOrderStatFullCalcTaskPO.STATUS_FAILED)
|
||||
.set(BiOrderStatFullCalcTaskPO::getFinishTime, LocalDateTime.now(ZONE)));
|
||||
} else {
|
||||
taskMapper.update(null, new LambdaUpdateWrapper<BiOrderStatFullCalcTaskPO>()
|
||||
.eq(BiOrderStatFullCalcTaskPO::getId, calcTaskId)
|
||||
.ne(BiOrderStatFullCalcTaskPO::getStatus, BiOrderStatFullCalcTaskPO.STATUS_CANCELLED)
|
||||
.set(BiOrderStatFullCalcTaskPO::getStatus, BiOrderStatFullCalcTaskPO.STATUS_SUCCESS)
|
||||
.set(BiOrderStatFullCalcTaskPO::getLastError, null)
|
||||
.set(BiOrderStatFullCalcTaskPO::getFinishTime, LocalDateTime.now(ZONE)));
|
||||
}
|
||||
}
|
||||
|
||||
/** 脏日账本:建 BI 全量并同步投递(仅 statDates 列出的自然日)。 */
|
||||
public BiOrderStatFullCalcTaskPO createForDirtyDayAndPublish(Long companyId, Long internalShopId,
|
||||
String platform,
|
||||
List<LocalDate> statDates,
|
||||
String applyBatchId) {
|
||||
if (companyId == null || internalShopId == null || statDates == null || statDates.isEmpty()) {
|
||||
throw new BusinessException("创建脏日 BI 任务参数不完整");
|
||||
}
|
||||
List<LocalDate> days = statDates.stream()
|
||||
.filter(Objects::nonNull)
|
||||
.sorted()
|
||||
.distinct()
|
||||
.toList();
|
||||
if (days.isEmpty()) {
|
||||
throw new BusinessException("创建脏日 BI 任务参数不完整");
|
||||
}
|
||||
String platformCode = platform != null && !platform.isBlank()
|
||||
? platform : PlatformCode.PDD.getCode();
|
||||
LocalDate dateFrom = days.get(0);
|
||||
LocalDate dateTo = days.get(days.size() - 1);
|
||||
BiOrderStatFullCalcTaskPO task = new BiOrderStatFullCalcTaskPO();
|
||||
task.setCompanyId(companyId);
|
||||
task.setShopId(internalShopId);
|
||||
task.setPlatformCode(platformCode);
|
||||
task.setTriggerSource(TaskTriggerSource.DIRTY_DAY);
|
||||
task.setUpstreamTaskId(null);
|
||||
task.setDateFrom(dateFrom);
|
||||
task.setDateTo(dateTo);
|
||||
task.setTotalDays(days.size());
|
||||
task.setDoneDays(0);
|
||||
task.setFailedDays(0);
|
||||
task.setSkippedDays(0);
|
||||
task.setStatus(BiOrderStatFullCalcTaskPO.STATUS_PENDING);
|
||||
BiOrderStatFullCalcTaskPO saved = newTxTemplate().execute(status -> {
|
||||
taskMapper.insert(task);
|
||||
insertDayRows(task, days);
|
||||
return task;
|
||||
});
|
||||
publishFullDays(saved.getId(), companyId, internalShopId, platformCode, days);
|
||||
log.info("脏日 BI 任务已创建 calcTaskId={} shopId={} batch={} days={} {}~{}",
|
||||
saved.getId(), internalShopId, applyBatchId, days.size(), dateFrom, dateTo);
|
||||
return saved;
|
||||
}
|
||||
|
||||
/**
|
||||
* 卡住的全量任务重投:PENDING/RUNNING 任务上未完成的日(PENDING/RUNNING/FAILED)重置后补发 MQ。
|
||||
* 用于:afterCommit 未投递、消费中断、日锁延迟后消息丢失等。
|
||||
*
|
||||
* @return 实际补投的自然日条数
|
||||
*/
|
||||
public int tryRepublishStuckActiveTask(Long companyId, Long shopId) {
|
||||
if (companyId == null || shopId == null) {
|
||||
return 0;
|
||||
}
|
||||
List<BiOrderStatFullCalcTaskPO> tasks = taskMapper.selectList(new LambdaQueryWrapper<BiOrderStatFullCalcTaskPO>()
|
||||
.eq(BiOrderStatFullCalcTaskPO::getCompanyId, companyId)
|
||||
.eq(BiOrderStatFullCalcTaskPO::getShopId, shopId)
|
||||
.in(BiOrderStatFullCalcTaskPO::getStatus,
|
||||
BiOrderStatFullCalcTaskPO.STATUS_PENDING,
|
||||
BiOrderStatFullCalcTaskPO.STATUS_RUNNING)
|
||||
.orderByAsc(BiOrderStatFullCalcTaskPO::getId));
|
||||
int republishedDays = 0;
|
||||
for (BiOrderStatFullCalcTaskPO task : tasks) {
|
||||
republishedDays += republishUnfinishedDays(task, companyId, shopId);
|
||||
}
|
||||
return republishedDays;
|
||||
}
|
||||
|
||||
/**
|
||||
* 将该任务下未完成日打回 PENDING 并补投 MQ。
|
||||
* RUNNING 日若刚开始(<2 分钟)则跳过,避免与正在消费的 worker 打架。
|
||||
*/
|
||||
private int republishUnfinishedDays(BiOrderStatFullCalcTaskPO task, Long companyId, Long shopId) {
|
||||
if (task == null || task.getId() == null) {
|
||||
return 0;
|
||||
}
|
||||
List<BiOrderStatFullCalcTaskDayPO> unfinished = dayMapper.selectList(
|
||||
new LambdaQueryWrapper<BiOrderStatFullCalcTaskDayPO>()
|
||||
.eq(BiOrderStatFullCalcTaskDayPO::getTaskId, task.getId())
|
||||
.in(BiOrderStatFullCalcTaskDayPO::getStatus,
|
||||
BiOrderStatFullCalcTaskDayPO.STATUS_PENDING,
|
||||
BiOrderStatFullCalcTaskDayPO.STATUS_RUNNING,
|
||||
BiOrderStatFullCalcTaskDayPO.STATUS_FAILED)
|
||||
.orderByAsc(BiOrderStatFullCalcTaskDayPO::getDay));
|
||||
if (unfinished.isEmpty()) {
|
||||
return 0;
|
||||
}
|
||||
LocalDateTime freshCutoff = LocalDateTime.now(ZONE).minusMinutes(2);
|
||||
List<LocalDate> toRepublish = new ArrayList<>();
|
||||
for (BiOrderStatFullCalcTaskDayPO dayRow : unfinished) {
|
||||
if (BiOrderStatFullCalcTaskDayPO.STATUS_RUNNING.equals(dayRow.getStatus())
|
||||
&& dayRow.getStartTime() != null
|
||||
&& dayRow.getStartTime().isAfter(freshCutoff)) {
|
||||
continue;
|
||||
}
|
||||
toRepublish.add(dayRow.getDay());
|
||||
}
|
||||
if (toRepublish.isEmpty()) {
|
||||
return 0;
|
||||
}
|
||||
dayMapper.update(null, new LambdaUpdateWrapper<BiOrderStatFullCalcTaskDayPO>()
|
||||
.eq(BiOrderStatFullCalcTaskDayPO::getTaskId, task.getId())
|
||||
.in(BiOrderStatFullCalcTaskDayPO::getDay, toRepublish)
|
||||
.in(BiOrderStatFullCalcTaskDayPO::getStatus,
|
||||
BiOrderStatFullCalcTaskDayPO.STATUS_PENDING,
|
||||
BiOrderStatFullCalcTaskDayPO.STATUS_RUNNING,
|
||||
BiOrderStatFullCalcTaskDayPO.STATUS_FAILED)
|
||||
.set(BiOrderStatFullCalcTaskDayPO::getStatus, BiOrderStatFullCalcTaskDayPO.STATUS_PENDING)
|
||||
.set(BiOrderStatFullCalcTaskDayPO::getStartTime, null)
|
||||
.set(BiOrderStatFullCalcTaskDayPO::getFinishTime, null)
|
||||
.set(BiOrderStatFullCalcTaskDayPO::getLastError, null));
|
||||
publishFullDays(task.getId(), companyId, shopId, task.getPlatformCode(), toRepublish);
|
||||
log.info("已重投未完成全量日 calcTaskId={} shopId={} days={}", task.getId(), shopId, toRepublish.size());
|
||||
return toRepublish.size();
|
||||
}
|
||||
|
||||
/** 该店可补投的未完成自然日数(PENDING 任务未开跑 + RUNNING/FAILED 卡住日)。 */
|
||||
public long countStuckPendingTasks(Long companyId, Long shopId) {
|
||||
if (companyId == null || shopId == null) {
|
||||
return 0;
|
||||
}
|
||||
List<BiOrderStatFullCalcTaskPO> tasks = taskMapper.selectList(new LambdaQueryWrapper<BiOrderStatFullCalcTaskPO>()
|
||||
.eq(BiOrderStatFullCalcTaskPO::getCompanyId, companyId)
|
||||
.eq(BiOrderStatFullCalcTaskPO::getShopId, shopId)
|
||||
.in(BiOrderStatFullCalcTaskPO::getStatus,
|
||||
BiOrderStatFullCalcTaskPO.STATUS_PENDING,
|
||||
BiOrderStatFullCalcTaskPO.STATUS_RUNNING));
|
||||
long total = 0;
|
||||
LocalDateTime freshCutoff = LocalDateTime.now(ZONE).minusMinutes(2);
|
||||
for (BiOrderStatFullCalcTaskPO task : tasks) {
|
||||
List<BiOrderStatFullCalcTaskDayPO> unfinished = dayMapper.selectList(
|
||||
new LambdaQueryWrapper<BiOrderStatFullCalcTaskDayPO>()
|
||||
.eq(BiOrderStatFullCalcTaskDayPO::getTaskId, task.getId())
|
||||
.in(BiOrderStatFullCalcTaskDayPO::getStatus,
|
||||
BiOrderStatFullCalcTaskDayPO.STATUS_PENDING,
|
||||
BiOrderStatFullCalcTaskDayPO.STATUS_RUNNING,
|
||||
BiOrderStatFullCalcTaskDayPO.STATUS_FAILED));
|
||||
for (BiOrderStatFullCalcTaskDayPO dayRow : unfinished) {
|
||||
if (BiOrderStatFullCalcTaskDayPO.STATUS_RUNNING.equals(dayRow.getStatus())
|
||||
&& dayRow.getStartTime() != null
|
||||
&& dayRow.getStartTime().isAfter(freshCutoff)) {
|
||||
continue;
|
||||
}
|
||||
total++;
|
||||
}
|
||||
}
|
||||
return total;
|
||||
}
|
||||
|
||||
/** 该店是否已有进行中的全量计算任务。 */
|
||||
public boolean hasActiveFullTask(Long companyId, Long shopId) {
|
||||
if (companyId == null || shopId == null) {
|
||||
return false;
|
||||
}
|
||||
Long count = taskMapper.selectCount(new LambdaQueryWrapper<BiOrderStatFullCalcTaskPO>()
|
||||
.eq(BiOrderStatFullCalcTaskPO::getCompanyId, companyId)
|
||||
.eq(BiOrderStatFullCalcTaskPO::getShopId, shopId)
|
||||
.in(BiOrderStatFullCalcTaskPO::getStatus,
|
||||
BiOrderStatFullCalcTaskPO.STATUS_PENDING,
|
||||
BiOrderStatFullCalcTaskPO.STATUS_RUNNING));
|
||||
return count != null && count > 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* 某店某自然日是否已有不早于 since 的 SUCCESS/SKIPPED 全量日(对齐脏账本,避免误清调价后的 RUNNING)。
|
||||
*/
|
||||
public boolean hasSuccessfulFullDaySince(Long companyId, Long shopId, LocalDate day, LocalDateTime since) {
|
||||
if (companyId == null || shopId == null || day == null) {
|
||||
return false;
|
||||
}
|
||||
LambdaQueryWrapper<BiOrderStatFullCalcTaskDayPO> q = new LambdaQueryWrapper<BiOrderStatFullCalcTaskDayPO>()
|
||||
.eq(BiOrderStatFullCalcTaskDayPO::getCompanyId, companyId)
|
||||
.eq(BiOrderStatFullCalcTaskDayPO::getShopId, shopId)
|
||||
.eq(BiOrderStatFullCalcTaskDayPO::getDay, day)
|
||||
.in(BiOrderStatFullCalcTaskDayPO::getStatus,
|
||||
BiOrderStatFullCalcTaskDayPO.STATUS_SUCCESS,
|
||||
BiOrderStatFullCalcTaskDayPO.STATUS_SKIPPED);
|
||||
if (since != null) {
|
||||
q.and(w -> w.ge(BiOrderStatFullCalcTaskDayPO::getFinishTime, since)
|
||||
.or()
|
||||
.ge(BiOrderStatFullCalcTaskDayPO::getUpdateTime, since));
|
||||
}
|
||||
Long count = dayMapper.selectCount(q);
|
||||
return count != null && count > 0;
|
||||
}
|
||||
|
||||
/** 活跃全量任务上该店日是否仍有未完成行。 */
|
||||
public boolean hasUnfinishedActiveFullDay(Long companyId, Long shopId, LocalDate day) {
|
||||
if (companyId == null || shopId == null || day == null) {
|
||||
return false;
|
||||
}
|
||||
List<BiOrderStatFullCalcTaskPO> tasks = taskMapper.selectList(new LambdaQueryWrapper<BiOrderStatFullCalcTaskPO>()
|
||||
.eq(BiOrderStatFullCalcTaskPO::getCompanyId, companyId)
|
||||
.eq(BiOrderStatFullCalcTaskPO::getShopId, shopId)
|
||||
.in(BiOrderStatFullCalcTaskPO::getStatus,
|
||||
BiOrderStatFullCalcTaskPO.STATUS_PENDING,
|
||||
BiOrderStatFullCalcTaskPO.STATUS_RUNNING));
|
||||
if (tasks.isEmpty()) {
|
||||
return false;
|
||||
}
|
||||
List<Long> taskIds = tasks.stream().map(BiOrderStatFullCalcTaskPO::getId).filter(Objects::nonNull).toList();
|
||||
Long count = dayMapper.selectCount(new LambdaQueryWrapper<BiOrderStatFullCalcTaskDayPO>()
|
||||
.in(BiOrderStatFullCalcTaskDayPO::getTaskId, taskIds)
|
||||
.eq(BiOrderStatFullCalcTaskDayPO::getDay, day)
|
||||
.in(BiOrderStatFullCalcTaskDayPO::getStatus,
|
||||
BiOrderStatFullCalcTaskDayPO.STATUS_PENDING,
|
||||
BiOrderStatFullCalcTaskDayPO.STATUS_RUNNING,
|
||||
BiOrderStatFullCalcTaskDayPO.STATUS_FAILED));
|
||||
return count != null && count > 0;
|
||||
}
|
||||
|
||||
private BiOrderStatFullCalcTaskPO findByUpstream(String triggerSource, Long upstreamTaskId) {
|
||||
if (triggerSource == null || upstreamTaskId == null) {
|
||||
return null;
|
||||
}
|
||||
return taskMapper.selectOne(new LambdaQueryWrapper<BiOrderStatFullCalcTaskPO>()
|
||||
.eq(BiOrderStatFullCalcTaskPO::getTriggerSource, triggerSource)
|
||||
.eq(BiOrderStatFullCalcTaskPO::getUpstreamTaskId, upstreamTaskId)
|
||||
.last("LIMIT 1"));
|
||||
}
|
||||
|
||||
private BiOrderStatIncCalcPO getOrCreateInc(Long companyId, Long internalShopId) {
|
||||
BiOrderStatIncCalcPO existing = incCalcMapper.selectOne(new LambdaQueryWrapper<BiOrderStatIncCalcPO>()
|
||||
.eq(BiOrderStatIncCalcPO::getShopId, internalShopId)
|
||||
.last("LIMIT 1"));
|
||||
if (existing != null) {
|
||||
return existing;
|
||||
}
|
||||
BiOrderStatIncCalcPO state = new BiOrderStatIncCalcPO();
|
||||
state.setCompanyId(companyId);
|
||||
state.setShopId(internalShopId);
|
||||
state.setStatus(BiOrderStatIncCalcPO.STATUS_OK);
|
||||
state.setLastSkipped(0);
|
||||
try {
|
||||
incCalcMapper.insert(state);
|
||||
return state;
|
||||
} catch (DuplicateKeyException e) {
|
||||
return incCalcMapper.selectOne(new LambdaQueryWrapper<BiOrderStatIncCalcPO>()
|
||||
.eq(BiOrderStatIncCalcPO::getShopId, internalShopId)
|
||||
.last("LIMIT 1"));
|
||||
}
|
||||
}
|
||||
|
||||
private static String truncate(String s, int max) {
|
||||
if (s == null) {
|
||||
return null;
|
||||
}
|
||||
return s.length() > max ? s.substring(0, max) : s;
|
||||
}
|
||||
}
|
||||
+531
@@ -0,0 +1,531 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.bi.orderstat.service;
|
||||
|
||||
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
|
||||
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
|
||||
import com.fasterxml.jackson.core.JsonProcessingException;
|
||||
import com.fasterxml.jackson.core.type.TypeReference;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
import org.springframework.transaction.support.TransactionSynchronization;
|
||||
import org.springframework.transaction.support.TransactionSynchronizationManager;
|
||||
import top.xyquan.ecomdmbbackend.common.exception.BusinessException;
|
||||
import top.xyquan.ecomdmbbackend.modules.bi.orderstat.mapper.BiOrderStatDirtyDayMapper;
|
||||
import top.xyquan.ecomdmbbackend.modules.bi.orderstat.model.dto.ShopStatDateRow;
|
||||
import top.xyquan.ecomdmbbackend.modules.bi.orderstat.model.po.BiOrderStatDirtyDayPO;
|
||||
import top.xyquan.ecomdmbbackend.modules.bi.orderstat.model.po.BiOrderStatFullCalcTaskPO;
|
||||
import top.xyquan.ecomdmbbackend.modules.bi.orderstat.model.vo.BiOrderStatDirtyDayVO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.order.mapper.OrderMapper;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.platform.model.enums.PlatformCode;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.shop.mapper.ShopMapper;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.shop.model.po.ShopPO;
|
||||
|
||||
import java.time.LocalDate;
|
||||
import java.time.LocalDateTime;
|
||||
import java.time.ZoneId;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Comparator;
|
||||
import java.util.HashMap;
|
||||
import java.util.LinkedHashSet;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
import java.util.Set;
|
||||
import java.util.UUID;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
/**
|
||||
* BI 店日脏账本:mark / 部分自动 apply / 手动 apply / FULL 成功后标 CLEAN。
|
||||
*/
|
||||
@Slf4j
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
public class BiOrderStatDirtyDayService {
|
||||
|
||||
private static final ZoneId ZONE = ZoneId.of("Asia/Shanghai");
|
||||
private static final TypeReference<List<String>> REASON_LIST = new TypeReference<>() {};
|
||||
private static final TypeReference<List<Map<String, Object>>> SOURCE_REF_LIST = new TypeReference<>() {};
|
||||
|
||||
private final BiOrderStatDirtyDayMapper dirtyDayMapper;
|
||||
private final OrderMapper orderMapper;
|
||||
private final ShopMapper shopMapper;
|
||||
private final BiOrderStatCalcTaskService calcTaskService;
|
||||
private final ObjectMapper objectMapper;
|
||||
|
||||
/** 成本调价:effectiveFrom~today 涉及该 SKU 的 (shop, day)。 */
|
||||
@Transactional(rollbackFor = Exception.class)
|
||||
public void markAfterCostAdjust(Long companyId, Long skuId, LocalDate effectiveFrom, Long userId) {
|
||||
if (companyId == null || skuId == null || effectiveFrom == null) {
|
||||
return;
|
||||
}
|
||||
LocalDate today = LocalDate.now(ZONE);
|
||||
LocalDate dateFrom = effectiveFrom.isAfter(today) ? today : effectiveFrom;
|
||||
markForSkuDateRange(companyId, skuId, dateFrom, today,
|
||||
BiOrderStatDirtyDayPO.REASON_COST,
|
||||
Map.of("type", "COST_ADJUST", "skuId", skuId, "userId", userId != null ? userId : 0));
|
||||
}
|
||||
|
||||
/** SKU 迁品:effectiveFrom~today(最早下单日或 today)涉及该 SKU 的 (shop, day)。 */
|
||||
@Transactional(rollbackFor = Exception.class)
|
||||
public void markAfterSkuMigrate(Long companyId, Long skuId, Long userId) {
|
||||
if (companyId == null || skuId == null) {
|
||||
return;
|
||||
}
|
||||
LocalDate today = LocalDate.now(ZONE);
|
||||
LocalDate minOrder = orderMapper.selectMinOrderDateForSku(companyId, skuId);
|
||||
LocalDate dateFrom = minOrder != null ? minOrder : today;
|
||||
if (dateFrom.isAfter(today)) {
|
||||
dateFrom = today;
|
||||
}
|
||||
markForSkuDateRange(companyId, skuId, dateFrom, today,
|
||||
BiOrderStatDirtyDayPO.REASON_PRODUCT_DIM,
|
||||
Map.of("type", "SKU_MIGRATE", "skuId", skuId, "userId", userId != null ? userId : 0));
|
||||
}
|
||||
|
||||
public BiOrderStatDirtyDayVO.HealthSummary healthSummary(Long companyId) {
|
||||
List<BiOrderStatDirtyDayPO> outstanding = listOutstandingEntities(companyId);
|
||||
Set<Long> shops = outstanding.stream()
|
||||
.map(BiOrderStatDirtyDayPO::getShopId)
|
||||
.filter(Objects::nonNull)
|
||||
.collect(Collectors.toSet());
|
||||
LocalDate oldest = outstanding.stream()
|
||||
.map(BiOrderStatDirtyDayPO::getStatDate)
|
||||
.filter(Objects::nonNull)
|
||||
.min(Comparator.naturalOrder())
|
||||
.orElse(null);
|
||||
boolean hasRunning = outstanding.stream()
|
||||
.anyMatch(r -> BiOrderStatDirtyDayPO.STATUS_RUNNING.equals(r.getStatus()));
|
||||
return BiOrderStatDirtyDayVO.HealthSummary.builder()
|
||||
.pendingDayCount(outstanding.size())
|
||||
.pendingShopCount(shops.size())
|
||||
.oldestPendingDate(oldest)
|
||||
.hasRunning(hasRunning)
|
||||
.build();
|
||||
}
|
||||
|
||||
/** 未完成脏日:PENDING + RUNNING(APPLY 后已入队但未 CLEAN 的也在内)。 */
|
||||
public List<BiOrderStatDirtyDayVO.PendingRow> listPending(Long companyId, int limit) {
|
||||
int lim = Math.min(Math.max(limit, 1), 500);
|
||||
List<BiOrderStatDirtyDayPO> rows = dirtyDayMapper.selectList(new LambdaQueryWrapper<BiOrderStatDirtyDayPO>()
|
||||
.eq(BiOrderStatDirtyDayPO::getCompanyId, companyId)
|
||||
.in(BiOrderStatDirtyDayPO::getStatus,
|
||||
BiOrderStatDirtyDayPO.STATUS_PENDING,
|
||||
BiOrderStatDirtyDayPO.STATUS_RUNNING)
|
||||
.orderByAsc(BiOrderStatDirtyDayPO::getStatus)
|
||||
.orderByAsc(BiOrderStatDirtyDayPO::getStatDate)
|
||||
.orderByAsc(BiOrderStatDirtyDayPO::getShopId)
|
||||
.last("LIMIT " + lim));
|
||||
Map<Long, String> shopNames = loadShopNames(rows);
|
||||
return rows.stream().map(r -> BiOrderStatDirtyDayVO.PendingRow.builder()
|
||||
.id(r.getId())
|
||||
.shopId(r.getShopId())
|
||||
.shopName(shopNames.get(r.getShopId()))
|
||||
.statDate(r.getStatDate())
|
||||
.reasons(parseReasons(r.getReasons()))
|
||||
.status(r.getStatus())
|
||||
.updateTime(r.getUpdateTime())
|
||||
.build()).toList();
|
||||
}
|
||||
|
||||
/** 公司级一键:PENDING 投 FULL;无 PENDING 时回收孤儿 RUNNING / 对齐已成功日 / 补投卡住任务。 */
|
||||
@Transactional(rollbackFor = Exception.class)
|
||||
public BiOrderStatDirtyDayVO.ApplyResult applyAllPending(Long companyId) {
|
||||
if (companyId == null) {
|
||||
throw new BusinessException("公司不能为空");
|
||||
}
|
||||
// 1) 全量日已 SUCCESS 但脏日仍 RUNNING → 直接 CLEAN(投过且算完了但账本未更新)
|
||||
int reconciled = reconcileRunningDirtyAlreadyComputed(companyId);
|
||||
// 2) 无活跃全量任务的 RUNNING 脏日 → 打回 PENDING,便于重新建任务
|
||||
int reclaimed = reclaimOrphanRunningDirtyDays(companyId);
|
||||
|
||||
List<BiOrderStatDirtyDayPO> pendingOnly = listPendingEntities(companyId);
|
||||
if (!pendingOnly.isEmpty()) {
|
||||
String batchId = UUID.randomUUID().toString().replace("-", "");
|
||||
Map<Long, List<LocalDate>> datesByShop = groupDatesByShop(pendingOnly);
|
||||
List<BiOrderStatDirtyDayVO.TaskBrief> briefs = scheduleFullForShops(companyId, datesByShop, batchId);
|
||||
markRunning(companyId, pendingOnly.stream().map(BiOrderStatDirtyDayPO::getId).toList(), batchId);
|
||||
int recoveredDays = recoverStuckFullTasks(companyId);
|
||||
log.debug("apply-pending 主路径后补投未完成日 recoveredDays={}", recoveredDays);
|
||||
return BiOrderStatDirtyDayVO.ApplyResult.builder()
|
||||
.applyBatchId(batchId)
|
||||
.dirtyDayCount(pendingOnly.size())
|
||||
.taskCount(briefs.size())
|
||||
.tasks(briefs)
|
||||
.build();
|
||||
}
|
||||
|
||||
// 3) 仅剩 RUNNING:补投活跃任务上未完成的日
|
||||
int recoveredDays = recoverStuckFullTasks(companyId);
|
||||
if (recoveredDays > 0 || reconciled > 0) {
|
||||
long runningCount = dirtyDayMapper.selectCount(new LambdaQueryWrapper<BiOrderStatDirtyDayPO>()
|
||||
.eq(BiOrderStatDirtyDayPO::getCompanyId, companyId)
|
||||
.eq(BiOrderStatDirtyDayPO::getStatus, BiOrderStatDirtyDayPO.STATUS_RUNNING));
|
||||
return BiOrderStatDirtyDayVO.ApplyResult.builder()
|
||||
.applyBatchId("recover")
|
||||
.dirtyDayCount(runningCount > 0 ? (int) runningCount : recoveredDays)
|
||||
.taskCount(Math.max(recoveredDays, reconciled > 0 ? 1 : 0))
|
||||
.tasks(List.of())
|
||||
.build();
|
||||
}
|
||||
|
||||
long runningLeft = dirtyDayMapper.selectCount(new LambdaQueryWrapper<BiOrderStatDirtyDayPO>()
|
||||
.eq(BiOrderStatDirtyDayPO::getCompanyId, companyId)
|
||||
.eq(BiOrderStatDirtyDayPO::getStatus, BiOrderStatDirtyDayPO.STATUS_RUNNING));
|
||||
if (runningLeft > 0) {
|
||||
throw new BusinessException(
|
||||
"有 " + runningLeft + " 个脏日仍显示「重算中」,且对应全量任务日正在执行(开始未满 2 分钟)。"
|
||||
+ "请稍候刷新;若长时间不变,再点一次补投。已对齐成功日 "
|
||||
+ reconciled + "、回收孤儿 " + reclaimed);
|
||||
}
|
||||
throw new BusinessException("没有待重算的 BI 脏数据");
|
||||
}
|
||||
|
||||
/**
|
||||
* RUNNING 脏日若对应店日已有 SUCCESS/SKIPPED 全量日,则标 CLEAN。
|
||||
*
|
||||
* @return 对齐条数
|
||||
*/
|
||||
private int reconcileRunningDirtyAlreadyComputed(Long companyId) {
|
||||
List<BiOrderStatDirtyDayPO> running = dirtyDayMapper.selectList(new LambdaQueryWrapper<BiOrderStatDirtyDayPO>()
|
||||
.eq(BiOrderStatDirtyDayPO::getCompanyId, companyId)
|
||||
.eq(BiOrderStatDirtyDayPO::getStatus, BiOrderStatDirtyDayPO.STATUS_RUNNING));
|
||||
int n = 0;
|
||||
for (BiOrderStatDirtyDayPO row : running) {
|
||||
if (row.getShopId() == null || row.getStatDate() == null) {
|
||||
continue;
|
||||
}
|
||||
if (calcTaskService.hasUnfinishedActiveFullDay(companyId, row.getShopId(), row.getStatDate())) {
|
||||
continue;
|
||||
}
|
||||
if (calcTaskService.hasSuccessfulFullDaySince(
|
||||
companyId, row.getShopId(), row.getStatDate(), row.getUpdateTime())) {
|
||||
markClean(companyId, row.getShopId(), row.getStatDate());
|
||||
n++;
|
||||
}
|
||||
}
|
||||
if (n > 0) {
|
||||
log.info("脏日对齐 CLEAN companyId={} count={}", companyId, n);
|
||||
}
|
||||
return n;
|
||||
}
|
||||
|
||||
/**
|
||||
* 无 PENDING/RUNNING 全量任务时,将孤儿 RUNNING 脏日打回 PENDING。
|
||||
*
|
||||
* @return 回收条数
|
||||
*/
|
||||
private int reclaimOrphanRunningDirtyDays(Long companyId) {
|
||||
List<BiOrderStatDirtyDayPO> running = dirtyDayMapper.selectList(new LambdaQueryWrapper<BiOrderStatDirtyDayPO>()
|
||||
.eq(BiOrderStatDirtyDayPO::getCompanyId, companyId)
|
||||
.eq(BiOrderStatDirtyDayPO::getStatus, BiOrderStatDirtyDayPO.STATUS_RUNNING));
|
||||
Map<Long, List<Long>> idsByShop = new HashMap<>();
|
||||
for (BiOrderStatDirtyDayPO row : running) {
|
||||
if (row.getShopId() == null || row.getId() == null) {
|
||||
continue;
|
||||
}
|
||||
idsByShop.computeIfAbsent(row.getShopId(), k -> new ArrayList<>()).add(row.getId());
|
||||
}
|
||||
int reclaimed = 0;
|
||||
for (Map.Entry<Long, List<Long>> e : idsByShop.entrySet()) {
|
||||
if (calcTaskService.hasActiveFullTask(companyId, e.getKey())) {
|
||||
continue;
|
||||
}
|
||||
dirtyDayMapper.update(null, new LambdaUpdateWrapper<BiOrderStatDirtyDayPO>()
|
||||
.eq(BiOrderStatDirtyDayPO::getCompanyId, companyId)
|
||||
.in(BiOrderStatDirtyDayPO::getId, e.getValue())
|
||||
.eq(BiOrderStatDirtyDayPO::getStatus, BiOrderStatDirtyDayPO.STATUS_RUNNING)
|
||||
.set(BiOrderStatDirtyDayPO::getStatus, BiOrderStatDirtyDayPO.STATUS_PENDING)
|
||||
.set(BiOrderStatDirtyDayPO::getApplyBatchId, null));
|
||||
reclaimed += e.getValue().size();
|
||||
}
|
||||
if (reclaimed > 0) {
|
||||
log.info("回收孤儿 RUNNING 脏日 companyId={} count={}", companyId, reclaimed);
|
||||
}
|
||||
return reclaimed;
|
||||
}
|
||||
|
||||
/** FULL 成功:对应店日标 CLEAN。 */
|
||||
@Transactional(rollbackFor = Exception.class)
|
||||
public void markClean(Long companyId, Long shopId, LocalDate statDate) {
|
||||
if (companyId == null || shopId == null || statDate == null) {
|
||||
return;
|
||||
}
|
||||
dirtyDayMapper.update(null, new LambdaUpdateWrapper<BiOrderStatDirtyDayPO>()
|
||||
.eq(BiOrderStatDirtyDayPO::getCompanyId, companyId)
|
||||
.eq(BiOrderStatDirtyDayPO::getShopId, shopId)
|
||||
.eq(BiOrderStatDirtyDayPO::getStatDate, statDate)
|
||||
.in(BiOrderStatDirtyDayPO::getStatus,
|
||||
BiOrderStatDirtyDayPO.STATUS_PENDING,
|
||||
BiOrderStatDirtyDayPO.STATUS_RUNNING)
|
||||
.set(BiOrderStatDirtyDayPO::getStatus, BiOrderStatDirtyDayPO.STATUS_CLEAN)
|
||||
.set(BiOrderStatDirtyDayPO::getAppliedTime, LocalDateTime.now(ZONE)));
|
||||
}
|
||||
|
||||
private void markForSkuDateRange(Long companyId, Long skuId, LocalDate dateFrom, LocalDate dateTo,
|
||||
String reason, Map<String, Object> sourceRef) {
|
||||
LocalDateTime start = dateFrom.atStartOfDay();
|
||||
LocalDateTime end = dateTo.plusDays(1).atStartOfDay();
|
||||
List<ShopStatDateRow> rows = orderMapper.selectShopStatDatesForSku(companyId, skuId, start, end);
|
||||
if (rows == null || rows.isEmpty()) {
|
||||
log.info("脏标记无订单 skuId={} {}~{}", skuId, dateFrom, dateTo);
|
||||
return;
|
||||
}
|
||||
Set<Long> shopIds = new LinkedHashSet<>();
|
||||
for (ShopStatDateRow row : rows) {
|
||||
if (row.getShopId() == null || row.getStatDate() == null) {
|
||||
continue;
|
||||
}
|
||||
upsertDirty(companyId, row.getShopId(), row.getStatDate(), reason, sourceRef);
|
||||
shopIds.add(row.getShopId());
|
||||
}
|
||||
scheduleAutoApplyAfterCommit(companyId, shopIds);
|
||||
log.info("脏标记完成 reason={} skuId={} shops={} days={}", reason, skuId, shopIds.size(), rows.size());
|
||||
}
|
||||
|
||||
private void upsertDirty(Long companyId, Long shopId, LocalDate statDate,
|
||||
String reason, Map<String, Object> sourceRef) {
|
||||
BiOrderStatDirtyDayPO existing = dirtyDayMapper.selectOne(new LambdaQueryWrapper<BiOrderStatDirtyDayPO>()
|
||||
.eq(BiOrderStatDirtyDayPO::getCompanyId, companyId)
|
||||
.eq(BiOrderStatDirtyDayPO::getShopId, shopId)
|
||||
.eq(BiOrderStatDirtyDayPO::getStatDate, statDate)
|
||||
.last("LIMIT 1"));
|
||||
if (existing == null) {
|
||||
BiOrderStatDirtyDayPO row = new BiOrderStatDirtyDayPO();
|
||||
row.setCompanyId(companyId);
|
||||
row.setShopId(shopId);
|
||||
row.setStatDate(statDate);
|
||||
row.setReasons(writeJson(List.of(reason)));
|
||||
row.setStatus(BiOrderStatDirtyDayPO.STATUS_PENDING);
|
||||
row.setSourceRefs(writeJson(List.of(sourceRef)));
|
||||
dirtyDayMapper.insert(row);
|
||||
return;
|
||||
}
|
||||
if (BiOrderStatDirtyDayPO.STATUS_RUNNING.equals(existing.getStatus())) {
|
||||
mergeReasons(existing, reason, sourceRef);
|
||||
dirtyDayMapper.updateById(existing);
|
||||
return;
|
||||
}
|
||||
existing.setStatus(BiOrderStatDirtyDayPO.STATUS_PENDING);
|
||||
mergeReasons(existing, reason, sourceRef);
|
||||
dirtyDayMapper.updateById(existing);
|
||||
}
|
||||
|
||||
private void mergeReasons(BiOrderStatDirtyDayPO row, String reason, Map<String, Object> sourceRef) {
|
||||
Set<String> reasons = new LinkedHashSet<>(parseReasons(row.getReasons()));
|
||||
reasons.add(reason);
|
||||
row.setReasons(writeJson(new ArrayList<>(reasons)));
|
||||
List<Map<String, Object>> refs = parseSourceRefs(row.getSourceRefs());
|
||||
refs.add(sourceRef);
|
||||
row.setSourceRefs(writeJson(refs));
|
||||
}
|
||||
|
||||
private void scheduleAutoApplyAfterCommit(Long companyId, Set<Long> shopIds) {
|
||||
if (shopIds == null || shopIds.isEmpty()) {
|
||||
return;
|
||||
}
|
||||
Runnable job = () -> {
|
||||
for (Long shopId : shopIds) {
|
||||
try {
|
||||
tryAutoApplyShop(companyId, shopId);
|
||||
} catch (Exception e) {
|
||||
log.warn("脏日自动 apply 失败 companyId={} shopId={}: {}", companyId, shopId, e.getMessage());
|
||||
}
|
||||
}
|
||||
};
|
||||
if (!TransactionSynchronizationManager.isSynchronizationActive()) {
|
||||
job.run();
|
||||
return;
|
||||
}
|
||||
TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronization() {
|
||||
@Override
|
||||
public void afterCommit() {
|
||||
job.run();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/** 部分自动:单店 pending 聚合切段投 FULL(店已有进行中全量则尝试重投卡住任务)。 */
|
||||
public void tryAutoApplyShop(Long companyId, Long shopId) {
|
||||
if (companyId == null || shopId == null) {
|
||||
return;
|
||||
}
|
||||
if (calcTaskService.hasActiveFullTask(companyId, shopId)) {
|
||||
calcTaskService.tryRepublishStuckActiveTask(companyId, shopId);
|
||||
return;
|
||||
}
|
||||
List<BiOrderStatDirtyDayPO> pending = dirtyDayMapper.selectList(new LambdaQueryWrapper<BiOrderStatDirtyDayPO>()
|
||||
.eq(BiOrderStatDirtyDayPO::getCompanyId, companyId)
|
||||
.eq(BiOrderStatDirtyDayPO::getShopId, shopId)
|
||||
.eq(BiOrderStatDirtyDayPO::getStatus, BiOrderStatDirtyDayPO.STATUS_PENDING)
|
||||
.orderByAsc(BiOrderStatDirtyDayPO::getStatDate));
|
||||
if (pending.isEmpty()) {
|
||||
return;
|
||||
}
|
||||
String batchId = UUID.randomUUID().toString().replace("-", "");
|
||||
scheduleFullForShops(companyId,
|
||||
Map.of(shopId, pending.stream().map(BiOrderStatDirtyDayPO::getStatDate).toList()), batchId);
|
||||
markRunning(companyId, pending.stream().map(BiOrderStatDirtyDayPO::getId).toList(), batchId);
|
||||
}
|
||||
|
||||
private List<BiOrderStatDirtyDayVO.TaskBrief> scheduleFullForShops(Long companyId,
|
||||
Map<Long, List<LocalDate>> datesByShop,
|
||||
String batchId) {
|
||||
List<BiOrderStatDirtyDayVO.TaskBrief> briefs = new ArrayList<>();
|
||||
int maxDays = BiOrderStatCalcTaskService.FULL_CALC_MAX_CALENDAR_DAYS;
|
||||
for (Map.Entry<Long, List<LocalDate>> e : datesByShop.entrySet()) {
|
||||
Long shopId = e.getKey();
|
||||
if (shopId == null) {
|
||||
continue;
|
||||
}
|
||||
ShopPO shop = shopMapper.selectById(shopId);
|
||||
if (shop == null || !companyId.equals(shop.getCompanyId())) {
|
||||
continue;
|
||||
}
|
||||
List<LocalDate> dates = e.getValue().stream().filter(Objects::nonNull).sorted().distinct().toList();
|
||||
if (dates.isEmpty()) {
|
||||
continue;
|
||||
}
|
||||
String platform = shop.getPlatformCode() != null ? shop.getPlatformCode() : PlatformCode.PDD.getCode();
|
||||
for (List<LocalDate> chunk : chunkDirtyDates(dates, maxDays)) {
|
||||
BiOrderStatFullCalcTaskPO biTask = calcTaskService.createForDirtyDayAndPublish(
|
||||
companyId, shopId, platform, chunk, batchId);
|
||||
briefs.add(BiOrderStatDirtyDayVO.TaskBrief.builder()
|
||||
.biCalcTaskId(biTask.getId())
|
||||
.shopId(shopId)
|
||||
.dateFrom(chunk.get(0))
|
||||
.dateTo(chunk.get(chunk.size() - 1))
|
||||
.totalDays(chunk.size())
|
||||
.status(biTask.getStatus())
|
||||
.build());
|
||||
}
|
||||
}
|
||||
return briefs;
|
||||
}
|
||||
|
||||
/** 脏日切段:连续自然日一组,单组超过 maxDays 再切。 */
|
||||
private static List<List<LocalDate>> chunkDirtyDates(List<LocalDate> sortedDistinctDates, int maxDays) {
|
||||
List<List<LocalDate>> groups = new ArrayList<>();
|
||||
List<LocalDate> current = new ArrayList<>();
|
||||
for (LocalDate d : sortedDistinctDates) {
|
||||
if (current.isEmpty()) {
|
||||
current.add(d);
|
||||
continue;
|
||||
}
|
||||
LocalDate last = current.get(current.size() - 1);
|
||||
if (last.plusDays(1).equals(d)) {
|
||||
current.add(d);
|
||||
} else {
|
||||
groups.add(current);
|
||||
current = new ArrayList<>();
|
||||
current.add(d);
|
||||
}
|
||||
}
|
||||
if (!current.isEmpty()) {
|
||||
groups.add(current);
|
||||
}
|
||||
List<List<LocalDate>> chunks = new ArrayList<>();
|
||||
for (List<LocalDate> group : groups) {
|
||||
for (int i = 0; i < group.size(); i += maxDays) {
|
||||
chunks.add(group.subList(i, Math.min(i + maxDays, group.size())));
|
||||
}
|
||||
}
|
||||
return chunks;
|
||||
}
|
||||
|
||||
/** @return 补投的全量自然日条数 */
|
||||
private int recoverStuckFullTasks(Long companyId) {
|
||||
List<BiOrderStatDirtyDayPO> running = dirtyDayMapper.selectList(new LambdaQueryWrapper<BiOrderStatDirtyDayPO>()
|
||||
.eq(BiOrderStatDirtyDayPO::getCompanyId, companyId)
|
||||
.eq(BiOrderStatDirtyDayPO::getStatus, BiOrderStatDirtyDayPO.STATUS_RUNNING));
|
||||
Set<Long> shopIds = running.stream()
|
||||
.map(BiOrderStatDirtyDayPO::getShopId)
|
||||
.filter(Objects::nonNull)
|
||||
.collect(Collectors.toCollection(LinkedHashSet::new));
|
||||
// 无 RUNNING 脏日时,仍扫描公司级可能卡住的店:从 PENDING 脏日涉及店亦可——此处以 RUNNING 为主
|
||||
int republished = 0;
|
||||
for (Long shopId : shopIds) {
|
||||
republished += calcTaskService.tryRepublishStuckActiveTask(companyId, shopId);
|
||||
}
|
||||
return republished;
|
||||
}
|
||||
|
||||
private void markRunning(Long companyId, List<Long> ids, String batchId) {
|
||||
if (ids == null || ids.isEmpty()) {
|
||||
return;
|
||||
}
|
||||
dirtyDayMapper.update(null, new LambdaUpdateWrapper<BiOrderStatDirtyDayPO>()
|
||||
.eq(BiOrderStatDirtyDayPO::getCompanyId, companyId)
|
||||
.in(BiOrderStatDirtyDayPO::getId, ids)
|
||||
.eq(BiOrderStatDirtyDayPO::getStatus, BiOrderStatDirtyDayPO.STATUS_PENDING)
|
||||
.set(BiOrderStatDirtyDayPO::getStatus, BiOrderStatDirtyDayPO.STATUS_RUNNING)
|
||||
.set(BiOrderStatDirtyDayPO::getApplyBatchId, batchId));
|
||||
}
|
||||
|
||||
private List<BiOrderStatDirtyDayPO> listPendingEntities(Long companyId) {
|
||||
return dirtyDayMapper.selectList(new LambdaQueryWrapper<BiOrderStatDirtyDayPO>()
|
||||
.eq(BiOrderStatDirtyDayPO::getCompanyId, companyId)
|
||||
.eq(BiOrderStatDirtyDayPO::getStatus, BiOrderStatDirtyDayPO.STATUS_PENDING)
|
||||
.orderByAsc(BiOrderStatDirtyDayPO::getStatDate));
|
||||
}
|
||||
|
||||
private List<BiOrderStatDirtyDayPO> listOutstandingEntities(Long companyId) {
|
||||
return dirtyDayMapper.selectList(new LambdaQueryWrapper<BiOrderStatDirtyDayPO>()
|
||||
.eq(BiOrderStatDirtyDayPO::getCompanyId, companyId)
|
||||
.in(BiOrderStatDirtyDayPO::getStatus,
|
||||
BiOrderStatDirtyDayPO.STATUS_PENDING,
|
||||
BiOrderStatDirtyDayPO.STATUS_RUNNING)
|
||||
.orderByAsc(BiOrderStatDirtyDayPO::getStatDate));
|
||||
}
|
||||
|
||||
private static Map<Long, List<LocalDate>> groupDatesByShop(List<BiOrderStatDirtyDayPO> pending) {
|
||||
Map<Long, List<LocalDate>> map = new HashMap<>();
|
||||
for (BiOrderStatDirtyDayPO p : pending) {
|
||||
if (p.getShopId() == null || p.getStatDate() == null) {
|
||||
continue;
|
||||
}
|
||||
map.computeIfAbsent(p.getShopId(), k -> new ArrayList<>()).add(p.getStatDate());
|
||||
}
|
||||
return map;
|
||||
}
|
||||
|
||||
private Map<Long, String> loadShopNames(List<BiOrderStatDirtyDayPO> rows) {
|
||||
Set<Long> ids = rows.stream().map(BiOrderStatDirtyDayPO::getShopId).filter(Objects::nonNull).collect(Collectors.toSet());
|
||||
if (ids.isEmpty()) {
|
||||
return Map.of();
|
||||
}
|
||||
return shopMapper.selectByIds(ids).stream()
|
||||
.collect(Collectors.toMap(ShopPO::getId, s -> s.getName() != null ? s.getName() : "", (a, b) -> a));
|
||||
}
|
||||
|
||||
private List<String> parseReasons(String json) {
|
||||
if (json == null || json.isBlank()) {
|
||||
return List.of();
|
||||
}
|
||||
try {
|
||||
return objectMapper.readValue(json, REASON_LIST);
|
||||
} catch (JsonProcessingException e) {
|
||||
return List.of();
|
||||
}
|
||||
}
|
||||
|
||||
private List<Map<String, Object>> parseSourceRefs(String json) {
|
||||
if (json == null || json.isBlank()) {
|
||||
return new ArrayList<>();
|
||||
}
|
||||
try {
|
||||
return objectMapper.readValue(json, SOURCE_REF_LIST);
|
||||
} catch (JsonProcessingException e) {
|
||||
return new ArrayList<>();
|
||||
}
|
||||
}
|
||||
|
||||
private String writeJson(Object value) {
|
||||
try {
|
||||
return objectMapper.writeValueAsString(value);
|
||||
} catch (JsonProcessingException e) {
|
||||
throw new BusinessException("JSON 序列化失败");
|
||||
}
|
||||
}
|
||||
}
|
||||
+198
@@ -0,0 +1,198 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.bi.orderstat.service;
|
||||
|
||||
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.stereotype.Service;
|
||||
import top.xyquan.ecomdmbbackend.modules.bi.infra.config.BiStatProperties;
|
||||
import top.xyquan.ecomdmbbackend.modules.bi.orderstat.mapper.BiOrderStatIncCalcMapper;
|
||||
import top.xyquan.ecomdmbbackend.modules.bi.orderstat.model.po.BiOrderStatIncCalcPO;
|
||||
import top.xyquan.ecomdmbbackend.modules.bi.orderstat.model.vo.BiOrderStatIncHealthVO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.order.mapper.OrderMapper;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.shop.mapper.ShopMapper;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.shop.model.po.ShopPO;
|
||||
|
||||
import java.time.Duration;
|
||||
import java.time.LocalDateTime;
|
||||
import java.time.ZoneId;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Comparator;
|
||||
import java.util.HashSet;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
/**
|
||||
* BI 增量计算健康度:公司汇总 / 按店明细 / 批量恢复暂停。
|
||||
* 滞后仅评估「近活动窗有订单或有成功增量」的店,安静店标 IDLE。
|
||||
*/
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
public class BiOrderStatIncHealthService {
|
||||
|
||||
private static final ZoneId ZONE = ZoneId.of("Asia/Shanghai");
|
||||
|
||||
private final ShopMapper shopMapper;
|
||||
private final OrderMapper orderMapper;
|
||||
private final BiOrderStatIncCalcMapper incCalcMapper;
|
||||
private final BiOrderStatCalcTaskService calcTaskService;
|
||||
private final BiStatProperties biStatProperties;
|
||||
|
||||
public BiOrderStatIncHealthVO.HealthSummary healthSummary(Long companyId) {
|
||||
List<BiOrderStatIncHealthVO.ShopRow> rows = listShopRows(companyId);
|
||||
int ok = 0;
|
||||
int idle = 0;
|
||||
int lagged = 0;
|
||||
int paused = 0;
|
||||
Long worst = null;
|
||||
for (BiOrderStatIncHealthVO.ShopRow row : rows) {
|
||||
switch (row.getHealthKind()) {
|
||||
case BiOrderStatIncHealthVO.KIND_PAUSED -> paused++;
|
||||
case BiOrderStatIncHealthVO.KIND_LAGGED -> {
|
||||
lagged++;
|
||||
if (row.getLagMinutes() != null
|
||||
&& (worst == null || row.getLagMinutes() > worst)) {
|
||||
worst = row.getLagMinutes();
|
||||
}
|
||||
}
|
||||
case BiOrderStatIncHealthVO.KIND_IDLE -> idle++;
|
||||
default -> ok++;
|
||||
}
|
||||
}
|
||||
return BiOrderStatIncHealthVO.HealthSummary.builder()
|
||||
.shopCount(rows.size())
|
||||
.okCount(ok)
|
||||
.idleCount(idle)
|
||||
.laggedCount(lagged)
|
||||
.pausedCount(paused)
|
||||
.worstLagMinutes(worst)
|
||||
.lagThresholdMinutes(lagThresholdMinutes())
|
||||
.activityWindowHours(activityWindowHours())
|
||||
.healthy(paused == 0 && lagged == 0)
|
||||
.build();
|
||||
}
|
||||
|
||||
public List<BiOrderStatIncHealthVO.ShopRow> listShopRows(Long companyId) {
|
||||
if (companyId == null) {
|
||||
return List.of();
|
||||
}
|
||||
List<ShopPO> shops = shopMapper.selectList(new LambdaQueryWrapper<ShopPO>()
|
||||
.eq(ShopPO::getCompanyId, companyId)
|
||||
.orderByAsc(ShopPO::getId));
|
||||
if (shops.isEmpty()) {
|
||||
return List.of();
|
||||
}
|
||||
|
||||
LocalDateTime now = LocalDateTime.now(ZONE);
|
||||
LocalDateTime activitySince = now.minusHours(activityWindowHours());
|
||||
long lagThreshold = lagThresholdMinutes();
|
||||
|
||||
Set<Long> activeShopIds = new HashSet<>(
|
||||
orderMapper.selectShopIdsWithRecentActivity(companyId, activitySince));
|
||||
|
||||
Map<Long, BiOrderStatIncCalcPO> stateByShop = incCalcMapper.selectList(
|
||||
new LambdaQueryWrapper<BiOrderStatIncCalcPO>()
|
||||
.eq(BiOrderStatIncCalcPO::getCompanyId, companyId))
|
||||
.stream()
|
||||
.filter(s -> s.getShopId() != null)
|
||||
.collect(Collectors.toMap(BiOrderStatIncCalcPO::getShopId, s -> s, (a, b) -> a));
|
||||
|
||||
List<BiOrderStatIncHealthVO.ShopRow> rows = new ArrayList<>();
|
||||
for (ShopPO shop : shops) {
|
||||
BiOrderStatIncCalcPO state = stateByShop.get(shop.getId());
|
||||
boolean recentOrder = activeShopIds.contains(shop.getId());
|
||||
boolean recentInc = state != null
|
||||
&& state.getLastSuccessTime() != null
|
||||
&& !state.getLastSuccessTime().isBefore(activitySince);
|
||||
boolean eligible = recentOrder || recentInc;
|
||||
|
||||
Integer status = state != null ? state.getStatus() : null;
|
||||
boolean paused = status != null && status == BiOrderStatIncCalcPO.STATUS_PAUSED;
|
||||
|
||||
Long lagMinutes = null;
|
||||
if (state != null && state.getLastSuccessTime() != null) {
|
||||
lagMinutes = Math.max(0L,
|
||||
Duration.between(state.getLastSuccessTime(), now).toMinutes());
|
||||
}
|
||||
|
||||
String kind;
|
||||
if (paused) {
|
||||
kind = BiOrderStatIncHealthVO.KIND_PAUSED;
|
||||
} else if (!eligible) {
|
||||
kind = BiOrderStatIncHealthVO.KIND_IDLE;
|
||||
lagMinutes = null;
|
||||
} else if (state == null || state.getLastSuccessTime() == null
|
||||
|| lagMinutes == null || lagMinutes > lagThreshold) {
|
||||
kind = BiOrderStatIncHealthVO.KIND_LAGGED;
|
||||
if (state == null || state.getLastSuccessTime() == null) {
|
||||
lagMinutes = null;
|
||||
}
|
||||
} else {
|
||||
kind = BiOrderStatIncHealthVO.KIND_OK;
|
||||
}
|
||||
|
||||
rows.add(BiOrderStatIncHealthVO.ShopRow.builder()
|
||||
.shopId(shop.getId())
|
||||
.shopName(shop.getName())
|
||||
.platformCode(shop.getPlatformCode())
|
||||
.status(status)
|
||||
.healthKind(kind)
|
||||
.lagMinutes(lagMinutes)
|
||||
.lastSuccessTime(state != null ? state.getLastSuccessTime() : null)
|
||||
.lastStatDate(state != null ? state.getLastStatDate() : null)
|
||||
.lastSummary(state != null ? state.getLastSummary() : null)
|
||||
.lastError(state != null ? state.getLastError() : null)
|
||||
.recentOrderActivity(recentOrder)
|
||||
.recentIncSuccess(recentInc)
|
||||
.build());
|
||||
}
|
||||
|
||||
rows.sort(Comparator
|
||||
.comparingInt((BiOrderStatIncHealthVO.ShopRow r) -> kindRank(r.getHealthKind()))
|
||||
.thenComparing(r -> r.getLagMinutes() == null ? -1L : r.getLagMinutes(),
|
||||
Comparator.reverseOrder())
|
||||
.thenComparing(r -> r.getShopId() == null ? 0L : r.getShopId()));
|
||||
return rows;
|
||||
}
|
||||
|
||||
/** 恢复公司下全部暂停店。 */
|
||||
public BiOrderStatIncHealthVO.ResumePausedResult resumeAllPaused(Long companyId) {
|
||||
List<BiOrderStatIncCalcPO> paused = incCalcMapper.selectList(
|
||||
new LambdaQueryWrapper<BiOrderStatIncCalcPO>()
|
||||
.eq(BiOrderStatIncCalcPO::getCompanyId, companyId)
|
||||
.eq(BiOrderStatIncCalcPO::getStatus, BiOrderStatIncCalcPO.STATUS_PAUSED));
|
||||
List<Long> shopIds = new ArrayList<>();
|
||||
for (BiOrderStatIncCalcPO row : paused) {
|
||||
if (row.getShopId() == null) {
|
||||
continue;
|
||||
}
|
||||
calcTaskService.resumeInc(companyId, row.getShopId());
|
||||
shopIds.add(row.getShopId());
|
||||
}
|
||||
return BiOrderStatIncHealthVO.ResumePausedResult.builder()
|
||||
.resumedCount(shopIds.size())
|
||||
.shopIds(shopIds)
|
||||
.build();
|
||||
}
|
||||
|
||||
private int lagThresholdMinutes() {
|
||||
return Math.max(1, biStatProperties.getIncLagThresholdMinutes());
|
||||
}
|
||||
|
||||
private int activityWindowHours() {
|
||||
return Math.max(1, biStatProperties.getIncActivityWindowHours());
|
||||
}
|
||||
|
||||
private static int kindRank(String kind) {
|
||||
if (BiOrderStatIncHealthVO.KIND_PAUSED.equals(kind)) {
|
||||
return 0;
|
||||
}
|
||||
if (BiOrderStatIncHealthVO.KIND_LAGGED.equals(kind)) {
|
||||
return 1;
|
||||
}
|
||||
if (BiOrderStatIncHealthVO.KIND_IDLE.equals(kind)) {
|
||||
return 2;
|
||||
}
|
||||
return 3;
|
||||
}
|
||||
}
|
||||
+420
@@ -0,0 +1,420 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.bi.orderstat.service;
|
||||
|
||||
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.PlatformTransactionManager;
|
||||
import org.springframework.transaction.support.TransactionTemplate;
|
||||
import top.xyquan.ecomdmbbackend.modules.bi.infra.lock.BiStatComputeLock;
|
||||
import top.xyquan.ecomdmbbackend.modules.bi.orderstat.model.document.BiOrderStatDailyProductDoc;
|
||||
import top.xyquan.ecomdmbbackend.modules.bi.orderstat.model.document.BiOrderStatDailyShopDoc;
|
||||
import top.xyquan.ecomdmbbackend.modules.bi.orderstat.model.document.BiOrderStatDailySkuDoc;
|
||||
import top.xyquan.ecomdmbbackend.modules.bi.orderstat.repository.BiOrderStatDailyRepository;
|
||||
import top.xyquan.ecomdmbbackend.modules.bi.orderstat.support.OrderItemCostResolver;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.order.mapper.OrderItemMapper;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.order.mapper.OrderMapper;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.order.model.po.OrderItemPO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.order.model.po.OrderPO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.order.status.support.OrderStatusStatResolver;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.order.status.support.OrderStatusStatSets;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.product.sku.mapper.ProductSkuMapper;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.product.sku.model.po.ProductSkuPO;
|
||||
|
||||
import org.springframework.transaction.TransactionDefinition;
|
||||
import org.springframework.transaction.support.DefaultTransactionDefinition;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.time.Instant;
|
||||
import java.time.LocalDate;
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.HashSet;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.Set;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
@Slf4j
|
||||
@Service
|
||||
@RequiredArgsConstructor
|
||||
public class OrderDailyStatComputeService {
|
||||
|
||||
private final OrderMapper orderMapper;
|
||||
private final OrderItemMapper orderItemMapper;
|
||||
private final ProductSkuMapper productSkuMapper;
|
||||
private final OrderStatusStatResolver orderStatusStatResolver;
|
||||
private final OrderItemCostResolver orderItemCostResolver;
|
||||
private final BiOrderStatDailyRepository repository;
|
||||
private final BiStatComputeLock computeLock;
|
||||
private final PlatformTransactionManager transactionManager;
|
||||
|
||||
/**
|
||||
* 全量:店+日锁 + MySQL 事务一致读重算;
|
||||
* 将事务快照开启时间写入 Mongo 文档 dbSnapshotTime(该日最新全量计算快照时间)。
|
||||
*/
|
||||
public boolean tryComputeFull(Long companyId, Long shopId, LocalDate statDate, String platformCode) {
|
||||
// 快照时刻在抢锁时登记,供同日进行中的增量与会话快照比较
|
||||
Instant snapshotTime = Instant.now();
|
||||
Optional<BiStatComputeLock.Session> sessionOpt =
|
||||
computeLock.tryLock(companyId, shopId, statDate, snapshotTime);
|
||||
if (sessionOpt.isEmpty()) {
|
||||
return false;
|
||||
}
|
||||
BiStatComputeLock.Session session = sessionOpt.get();
|
||||
try {
|
||||
DefaultTransactionDefinition def = new DefaultTransactionDefinition();
|
||||
def.setIsolationLevel(TransactionDefinition.ISOLATION_REPEATABLE_READ);
|
||||
def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);
|
||||
TransactionTemplate tt = new TransactionTemplate(transactionManager, def);
|
||||
tt.executeWithoutResult(status -> {
|
||||
DayAgg agg = aggregateDay(companyId, shopId, statDate, platformCode);
|
||||
persist(agg, snapshotTime, "FULL");
|
||||
});
|
||||
return true;
|
||||
} finally {
|
||||
computeLock.unlock(session);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @deprecated 增量已改为消费端 $inc delta,不再按日重算。
|
||||
*/
|
||||
public boolean tryComputeInc(Long companyId, Long shopId, LocalDate statDate, String platformCode) {
|
||||
Optional<BiStatComputeLock.Session> sessionOpt =
|
||||
computeLock.tryLock(companyId, shopId, statDate, null);
|
||||
if (sessionOpt.isEmpty()) {
|
||||
return false;
|
||||
}
|
||||
BiStatComputeLock.Session session = sessionOpt.get();
|
||||
try {
|
||||
DayAgg agg = aggregateDay(companyId, shopId, statDate, platformCode);
|
||||
persist(agg, null, "INC");
|
||||
return true;
|
||||
} finally {
|
||||
computeLock.unlock(session);
|
||||
}
|
||||
}
|
||||
|
||||
/** @deprecated 使用 {@link #tryComputeFull} */
|
||||
public void computeFull(Long companyId, Long shopId, LocalDate statDate, String platformCode) {
|
||||
if (!tryComputeFull(companyId, shopId, statDate, platformCode)) {
|
||||
throw new IllegalStateException(
|
||||
"BI 店日计算锁占用中: " + companyId + "/" + shopId + "/" + statDate);
|
||||
}
|
||||
}
|
||||
|
||||
/** @deprecated 使用 {@link #tryComputeInc} */
|
||||
public void computeInc(Long companyId, Long shopId, LocalDate statDate, String platformCode) {
|
||||
if (!tryComputeInc(companyId, shopId, statDate, platformCode)) {
|
||||
throw new IllegalStateException(
|
||||
"BI 店日计算锁占用中: " + companyId + "/" + shopId + "/" + statDate);
|
||||
}
|
||||
}
|
||||
|
||||
private DayAgg aggregateDay(Long companyId, Long shopId, LocalDate statDate, String platformCode) {
|
||||
LocalDateTime start = statDate.atStartOfDay();
|
||||
LocalDateTime end = statDate.plusDays(1).atStartOfDay();
|
||||
List<OrderPO> orders = orderMapper.selectList(new LambdaQueryWrapper<OrderPO>()
|
||||
.eq(OrderPO::getCompanyId, companyId)
|
||||
.eq(OrderPO::getShopId, shopId)
|
||||
.ge(OrderPO::getOrderTime, start)
|
||||
.lt(OrderPO::getOrderTime, end));
|
||||
OrderStatusStatSets stat = orderStatusStatResolver.resolve(companyId);
|
||||
|
||||
Map<Long, List<OrderItemPO>> itemsByOrder = new HashMap<>();
|
||||
if (!orders.isEmpty()) {
|
||||
List<Long> orderIds = orders.stream().map(OrderPO::getId).toList();
|
||||
List<OrderItemPO> items = orderItemMapper.selectList(new LambdaQueryWrapper<OrderItemPO>()
|
||||
.in(OrderItemPO::getOrderId, orderIds));
|
||||
for (OrderItemPO item : items) {
|
||||
itemsByOrder.computeIfAbsent(item.getOrderId(), k -> new ArrayList<>()).add(item);
|
||||
}
|
||||
}
|
||||
|
||||
Set<Long> skuIds = itemsByOrder.values().stream()
|
||||
.flatMap(List::stream)
|
||||
.map(OrderItemPO::getProductSkuId)
|
||||
.filter(id -> id != null && id > 0)
|
||||
.collect(Collectors.toSet());
|
||||
Map<Long, Long> productBySku = new HashMap<>();
|
||||
if (!skuIds.isEmpty()) {
|
||||
for (ProductSkuPO sku : productSkuMapper.selectByIds(skuIds)) {
|
||||
productBySku.put(sku.getId(), sku.getProductId() != null ? sku.getProductId() : 0L);
|
||||
}
|
||||
}
|
||||
Map<Long, OrderItemCostResolver.UnitCosts> unitCostBySku =
|
||||
orderItemCostResolver.resolveUnitCostsForDay(skuIds, statDate);
|
||||
|
||||
Metric shop = new Metric();
|
||||
Map<String, Metric> productMap = new HashMap<>();
|
||||
Map<String, Metric> skuMap = new HashMap<>();
|
||||
Map<String, DimKey> productKeys = new HashMap<>();
|
||||
Map<String, DimKey> skuKeys = new HashMap<>();
|
||||
|
||||
for (OrderPO order : orders) {
|
||||
boolean deal = stat.includesDeal(order.getStatus());
|
||||
boolean refund = stat.includesRefund(order.getStatus());
|
||||
// 已取消/未知:不进成交、退款、服务费与成本
|
||||
if (!deal && !refund) {
|
||||
continue;
|
||||
}
|
||||
List<OrderItemPO> items = itemsByOrder.getOrDefault(order.getId(), List.of());
|
||||
int qtySum = OrderStatusStatSets.totalQuantity(items);
|
||||
if (qtySum <= 0 && items.isEmpty()) {
|
||||
qtySum = 1;
|
||||
}
|
||||
BigDecimal received = OrderStatusStatSets.receivedAmount(order);
|
||||
BigDecimal fee = deal ? nz(order.getServiceFee()) : BigDecimal.ZERO;
|
||||
|
||||
if (deal) {
|
||||
shop.dealAmount = shop.dealAmount.add(received);
|
||||
shop.dealOrderCount++;
|
||||
shop.dealQuantitySum += qtySum;
|
||||
shop.serviceFee = shop.serviceFee.add(fee);
|
||||
}
|
||||
if (refund) {
|
||||
shop.refundAmount = shop.refundAmount.add(received);
|
||||
shop.refundOrderCount++;
|
||||
shop.refundQuantitySum += qtySum;
|
||||
}
|
||||
|
||||
Set<String> countedProductDeal = new HashSet<>();
|
||||
Set<String> countedProductRefund = new HashSet<>();
|
||||
Set<String> countedSkuDeal = new HashSet<>();
|
||||
Set<String> countedSkuRefund = new HashSet<>();
|
||||
|
||||
if (items.isEmpty()) {
|
||||
continue;
|
||||
}
|
||||
for (OrderItemPO item : items) {
|
||||
long skuId = item.getProductSkuId() != null ? item.getProductSkuId() : 0L;
|
||||
long productId = productBySku.getOrDefault(skuId, 0L);
|
||||
int qty = OrderStatusStatSets.quantity(item);
|
||||
BigDecimal lineReceived = allocateLine(received, item, items);
|
||||
BigDecimal lineFee = deal ? allocateLine(fee, item, items) : BigDecimal.ZERO;
|
||||
|
||||
String pk = companyId + ":" + shopId + ":" + productId;
|
||||
Metric pm = productMap.computeIfAbsent(pk, k -> new Metric());
|
||||
productKeys.putIfAbsent(pk, new DimKey(productId, 0L));
|
||||
if (deal) {
|
||||
pm.dealAmount = pm.dealAmount.add(lineReceived);
|
||||
pm.dealQuantitySum += qty;
|
||||
pm.serviceFee = pm.serviceFee.add(lineFee);
|
||||
if (countedProductDeal.add(pk)) {
|
||||
pm.dealOrderCount++;
|
||||
}
|
||||
}
|
||||
if (refund) {
|
||||
pm.refundAmount = pm.refundAmount.add(lineReceived);
|
||||
pm.refundQuantitySum += qty;
|
||||
if (countedProductRefund.add(pk)) {
|
||||
pm.refundOrderCount++;
|
||||
}
|
||||
}
|
||||
pm.productCost = pm.productCost.add(lineProductCost(order, item, stat, unitCostBySku));
|
||||
pm.freightCost = pm.freightCost.add(lineFreightCost(order, item, stat, unitCostBySku));
|
||||
pm.otherCost = pm.otherCost.add(lineOtherCost(order, item, stat, unitCostBySku));
|
||||
|
||||
String sk = companyId + ":" + shopId + ":" + skuId;
|
||||
Metric sm = skuMap.computeIfAbsent(sk, k -> new Metric());
|
||||
skuKeys.putIfAbsent(sk, new DimKey(productId, skuId));
|
||||
if (deal) {
|
||||
sm.dealAmount = sm.dealAmount.add(lineReceived);
|
||||
sm.dealQuantitySum += qty;
|
||||
sm.serviceFee = sm.serviceFee.add(lineFee);
|
||||
if (countedSkuDeal.add(sk)) {
|
||||
sm.dealOrderCount++;
|
||||
}
|
||||
}
|
||||
if (refund) {
|
||||
sm.refundAmount = sm.refundAmount.add(lineReceived);
|
||||
sm.refundQuantitySum += qty;
|
||||
if (countedSkuRefund.add(sk)) {
|
||||
sm.refundOrderCount++;
|
||||
}
|
||||
}
|
||||
sm.productCost = sm.productCost.add(lineProductCost(order, item, stat, unitCostBySku));
|
||||
sm.freightCost = sm.freightCost.add(lineFreightCost(order, item, stat, unitCostBySku));
|
||||
sm.otherCost = sm.otherCost.add(lineOtherCost(order, item, stat, unitCostBySku));
|
||||
|
||||
shop.productCost = shop.productCost.add(lineProductCost(order, item, stat, unitCostBySku));
|
||||
shop.freightCost = shop.freightCost.add(lineFreightCost(order, item, stat, unitCostBySku));
|
||||
shop.otherCost = shop.otherCost.add(lineOtherCost(order, item, stat, unitCostBySku));
|
||||
}
|
||||
}
|
||||
|
||||
String platform = platformCode;
|
||||
if (platform == null && !orders.isEmpty()) {
|
||||
platform = orders.get(0).getPlatformCode();
|
||||
}
|
||||
|
||||
return new DayAgg(companyId, shopId, statDate, platform, shop, productMap, productKeys, skuMap, skuKeys);
|
||||
}
|
||||
|
||||
private void persist(DayAgg agg, Instant snapshotTime, String mode) {
|
||||
Instant now = Instant.now();
|
||||
BiOrderStatDailyShopDoc shopDoc = new BiOrderStatDailyShopDoc();
|
||||
shopDoc.setCompanyId(agg.companyId());
|
||||
shopDoc.setShopId(agg.shopId());
|
||||
shopDoc.setPlatformCode(agg.platformCode());
|
||||
shopDoc.setStatDate(agg.statDate());
|
||||
applyMetric(shopDoc, agg.shop());
|
||||
shopDoc.setDbSnapshotTime(snapshotTime);
|
||||
shopDoc.setComputedAt(now);
|
||||
shopDoc.setComputeMode(mode);
|
||||
|
||||
List<BiOrderStatDailyProductDoc> products = new ArrayList<>();
|
||||
for (Map.Entry<String, Metric> e : agg.productMap().entrySet()) {
|
||||
DimKey key = agg.productKeys().get(e.getKey());
|
||||
BiOrderStatDailyProductDoc doc = new BiOrderStatDailyProductDoc();
|
||||
doc.setCompanyId(agg.companyId());
|
||||
doc.setShopId(agg.shopId());
|
||||
doc.setProductId(key.productId());
|
||||
doc.setStatDate(agg.statDate());
|
||||
applyMetric(doc, e.getValue());
|
||||
doc.setDbSnapshotTime(snapshotTime);
|
||||
doc.setComputedAt(now);
|
||||
doc.setComputeMode(mode);
|
||||
products.add(doc);
|
||||
}
|
||||
|
||||
List<BiOrderStatDailySkuDoc> skus = new ArrayList<>();
|
||||
for (Map.Entry<String, Metric> e : agg.skuMap().entrySet()) {
|
||||
DimKey key = agg.skuKeys().get(e.getKey());
|
||||
BiOrderStatDailySkuDoc doc = new BiOrderStatDailySkuDoc();
|
||||
doc.setCompanyId(agg.companyId());
|
||||
doc.setShopId(agg.shopId());
|
||||
doc.setProductId(key.productId());
|
||||
doc.setProductSkuId(key.skuId());
|
||||
doc.setStatDate(agg.statDate());
|
||||
applyMetric(doc, e.getValue());
|
||||
doc.setDbSnapshotTime(snapshotTime);
|
||||
doc.setComputedAt(now);
|
||||
doc.setComputeMode(mode);
|
||||
skus.add(doc);
|
||||
}
|
||||
|
||||
repository.replaceShopDay(shopDoc, products, skus);
|
||||
log.info("BI 日汇聚完成 mode={} companyId={} shopId={} statDate={} ordersShopDeal={}",
|
||||
mode, agg.companyId(), agg.shopId(), agg.statDate(), agg.shop().dealOrderCount);
|
||||
}
|
||||
|
||||
private static void applyMetric(BiOrderStatDailyShopDoc doc, Metric m) {
|
||||
doc.setDealAmount(m.dealAmount);
|
||||
doc.setDealOrderCount(m.dealOrderCount);
|
||||
doc.setDealQuantitySum(m.dealQuantitySum);
|
||||
doc.setRefundAmount(m.refundAmount);
|
||||
doc.setRefundOrderCount(m.refundOrderCount);
|
||||
doc.setRefundQuantitySum(m.refundQuantitySum);
|
||||
doc.setServiceFee(m.serviceFee);
|
||||
doc.setProductCost(m.productCost);
|
||||
doc.setFreightCost(m.freightCost);
|
||||
doc.setOtherCost(m.otherCost);
|
||||
}
|
||||
|
||||
private static void applyMetric(BiOrderStatDailyProductDoc doc, Metric m) {
|
||||
doc.setDealAmount(m.dealAmount);
|
||||
doc.setDealOrderCount(m.dealOrderCount);
|
||||
doc.setDealQuantitySum(m.dealQuantitySum);
|
||||
doc.setRefundAmount(m.refundAmount);
|
||||
doc.setRefundOrderCount(m.refundOrderCount);
|
||||
doc.setRefundQuantitySum(m.refundQuantitySum);
|
||||
doc.setServiceFee(m.serviceFee);
|
||||
doc.setProductCost(m.productCost);
|
||||
doc.setFreightCost(m.freightCost);
|
||||
doc.setOtherCost(m.otherCost);
|
||||
}
|
||||
|
||||
private static void applyMetric(BiOrderStatDailySkuDoc doc, Metric m) {
|
||||
doc.setDealAmount(m.dealAmount);
|
||||
doc.setDealOrderCount(m.dealOrderCount);
|
||||
doc.setDealQuantitySum(m.dealQuantitySum);
|
||||
doc.setRefundAmount(m.refundAmount);
|
||||
doc.setRefundOrderCount(m.refundOrderCount);
|
||||
doc.setRefundQuantitySum(m.refundQuantitySum);
|
||||
doc.setServiceFee(m.serviceFee);
|
||||
doc.setProductCost(m.productCost);
|
||||
doc.setFreightCost(m.freightCost);
|
||||
doc.setOtherCost(m.otherCost);
|
||||
}
|
||||
|
||||
/** 按行金额占比分摊订单实收;无行金额则均分。 */
|
||||
private static BigDecimal allocateLine(BigDecimal orderPay, OrderItemPO item, List<OrderItemPO> items) {
|
||||
BigDecimal totalLine = BigDecimal.ZERO;
|
||||
for (OrderItemPO i : items) {
|
||||
totalLine = totalLine.add(nz(i.getLineAmount()));
|
||||
}
|
||||
if (totalLine.compareTo(BigDecimal.ZERO) > 0) {
|
||||
return orderPay.multiply(nz(item.getLineAmount())).divide(totalLine, 4, java.math.RoundingMode.HALF_UP);
|
||||
}
|
||||
if (items.isEmpty()) {
|
||||
return orderPay;
|
||||
}
|
||||
return orderPay.divide(BigDecimal.valueOf(items.size()), 4, java.math.RoundingMode.HALF_UP);
|
||||
}
|
||||
|
||||
private static BigDecimal nz(BigDecimal v) {
|
||||
return v != null ? v : BigDecimal.ZERO;
|
||||
}
|
||||
|
||||
private static BigDecimal lineProductCost(OrderPO order, OrderItemPO item, OrderStatusStatSets stat,
|
||||
Map<Long, OrderItemCostResolver.UnitCosts> unitCostBySku) {
|
||||
if (!stat.includesProductCost(order.getStatus())) {
|
||||
return BigDecimal.ZERO;
|
||||
}
|
||||
long skuId = item.getProductSkuId() != null ? item.getProductSkuId() : 0L;
|
||||
OrderItemCostResolver.UnitCosts uc = unitCostBySku.getOrDefault(skuId, OrderItemCostResolver.UnitCosts.ZERO);
|
||||
return uc.productCost().multiply(BigDecimal.valueOf(OrderStatusStatSets.quantity(item)));
|
||||
}
|
||||
|
||||
private static BigDecimal lineFreightCost(OrderPO order, OrderItemPO item, OrderStatusStatSets stat,
|
||||
Map<Long, OrderItemCostResolver.UnitCosts> unitCostBySku) {
|
||||
if (!stat.includesFreightCost(order.getStatus())) {
|
||||
return BigDecimal.ZERO;
|
||||
}
|
||||
long skuId = item.getProductSkuId() != null ? item.getProductSkuId() : 0L;
|
||||
OrderItemCostResolver.UnitCosts uc = unitCostBySku.getOrDefault(skuId, OrderItemCostResolver.UnitCosts.ZERO);
|
||||
return uc.shippingCost().multiply(BigDecimal.valueOf(OrderStatusStatSets.quantity(item)));
|
||||
}
|
||||
|
||||
private static BigDecimal lineOtherCost(OrderPO order, OrderItemPO item, OrderStatusStatSets stat,
|
||||
Map<Long, OrderItemCostResolver.UnitCosts> unitCostBySku) {
|
||||
if (!stat.includesOtherCost(order.getStatus())) {
|
||||
return BigDecimal.ZERO;
|
||||
}
|
||||
long skuId = item.getProductSkuId() != null ? item.getProductSkuId() : 0L;
|
||||
OrderItemCostResolver.UnitCosts uc = unitCostBySku.getOrDefault(skuId, OrderItemCostResolver.UnitCosts.ZERO);
|
||||
return uc.otherCost().multiply(BigDecimal.valueOf(OrderStatusStatSets.quantity(item)));
|
||||
}
|
||||
|
||||
private static final class Metric {
|
||||
BigDecimal dealAmount = BigDecimal.ZERO;
|
||||
int dealOrderCount;
|
||||
int dealQuantitySum;
|
||||
BigDecimal refundAmount = BigDecimal.ZERO;
|
||||
int refundOrderCount;
|
||||
int refundQuantitySum;
|
||||
BigDecimal serviceFee = BigDecimal.ZERO;
|
||||
BigDecimal productCost = BigDecimal.ZERO;
|
||||
BigDecimal freightCost = BigDecimal.ZERO;
|
||||
BigDecimal otherCost = BigDecimal.ZERO;
|
||||
}
|
||||
|
||||
private record DimKey(long productId, long skuId) {
|
||||
}
|
||||
|
||||
private record DayAgg(
|
||||
Long companyId,
|
||||
Long shopId,
|
||||
LocalDate statDate,
|
||||
String platformCode,
|
||||
Metric shop,
|
||||
Map<String, Metric> productMap,
|
||||
Map<String, DimKey> productKeys,
|
||||
Map<String, Metric> skuMap,
|
||||
Map<String, DimKey> skuKeys) {
|
||||
}
|
||||
}
|
||||
+96
@@ -0,0 +1,96 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.bi.orderstat.support;
|
||||
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.stereotype.Component;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.order.model.po.OrderItemPO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.order.model.po.OrderPO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.order.status.support.OrderStatusStatSets;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.product.sku.cost.model.po.ProductSkuCostPO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.product.sku.cost.service.ProductSkuCostService;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.time.LocalDate;
|
||||
import java.util.Collection;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* 订单明细成本:按 order_time 自然日从 SKU 成本主数据 as-of 解析,不读 ec_order_item 快照。
|
||||
*/
|
||||
@Component
|
||||
@RequiredArgsConstructor
|
||||
public class OrderItemCostResolver {
|
||||
|
||||
private final ProductSkuCostService productSkuCostService;
|
||||
|
||||
/** 单笔订单行:按订单日取 SKU 成本。 */
|
||||
public UnitCosts resolveUnitCosts(OrderPO order, OrderItemPO item) {
|
||||
LocalDate orderDate = order != null && order.getOrderTime() != null
|
||||
? order.getOrderTime().toLocalDate()
|
||||
: LocalDate.now();
|
||||
long skuId = item != null && item.getProductSkuId() != null ? item.getProductSkuId() : 0L;
|
||||
if (skuId <= 0) {
|
||||
return UnitCosts.ZERO;
|
||||
}
|
||||
ProductSkuCostPO cost = productSkuCostService.getCostAsOf(skuId, orderDate);
|
||||
return UnitCosts.from(cost);
|
||||
}
|
||||
|
||||
/** 店日批算:同一 statDate 下批量 as-of。 */
|
||||
public Map<Long, UnitCosts> resolveUnitCostsForDay(Collection<Long> skuIds, LocalDate statDate) {
|
||||
Map<Long, ProductSkuCostPO> raw = productSkuCostService.getCostsAsOf(skuIds, statDate);
|
||||
Map<Long, UnitCosts> map = new HashMap<>();
|
||||
if (skuIds == null) {
|
||||
return map;
|
||||
}
|
||||
for (Long skuId : skuIds) {
|
||||
if (skuId == null || skuId <= 0) {
|
||||
continue;
|
||||
}
|
||||
map.put(skuId, UnitCosts.from(raw.get(skuId)));
|
||||
}
|
||||
return map;
|
||||
}
|
||||
|
||||
public BigDecimal productCostForStats(OrderPO order, OrderItemPO item, OrderStatusStatSets stat) {
|
||||
if (!stat.includesProductCost(order.getStatus())) {
|
||||
return BigDecimal.ZERO;
|
||||
}
|
||||
UnitCosts c = resolveUnitCosts(order, item);
|
||||
return c.productCost().multiply(BigDecimal.valueOf(OrderStatusStatSets.quantity(item)));
|
||||
}
|
||||
|
||||
public BigDecimal freightCostForStats(OrderPO order, OrderItemPO item, OrderStatusStatSets stat) {
|
||||
if (!stat.includesFreightCost(order.getStatus())) {
|
||||
return BigDecimal.ZERO;
|
||||
}
|
||||
UnitCosts c = resolveUnitCosts(order, item);
|
||||
return c.shippingCost().multiply(BigDecimal.valueOf(OrderStatusStatSets.quantity(item)));
|
||||
}
|
||||
|
||||
public BigDecimal otherCostForStats(OrderPO order, OrderItemPO item, OrderStatusStatSets stat) {
|
||||
if (!stat.includesOtherCost(order.getStatus())) {
|
||||
return BigDecimal.ZERO;
|
||||
}
|
||||
UnitCosts c = resolveUnitCosts(order, item);
|
||||
return c.otherCost().multiply(BigDecimal.valueOf(OrderStatusStatSets.quantity(item)));
|
||||
}
|
||||
|
||||
public record UnitCosts(BigDecimal productCost, BigDecimal shippingCost, BigDecimal otherCost) {
|
||||
public static final UnitCosts ZERO = new UnitCosts(BigDecimal.ZERO, BigDecimal.ZERO, BigDecimal.ZERO);
|
||||
|
||||
static UnitCosts from(ProductSkuCostPO cost) {
|
||||
if (cost == null) {
|
||||
return ZERO;
|
||||
}
|
||||
return new UnitCosts(
|
||||
nz(cost.getProductCost()),
|
||||
nz(cost.getShippingCost()),
|
||||
nz(cost.getOtherCost()));
|
||||
}
|
||||
|
||||
private static BigDecimal nz(BigDecimal v) {
|
||||
return v != null ? v : BigDecimal.ZERO;
|
||||
}
|
||||
}
|
||||
}
|
||||
+216
@@ -0,0 +1,216 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.bi.orderstat.support;
|
||||
|
||||
import lombok.Builder;
|
||||
import lombok.Data;
|
||||
import top.xyquan.ecomdmbbackend.modules.bi.messaging.BiProductStatDelta;
|
||||
import top.xyquan.ecomdmbbackend.modules.bi.messaging.BiSkuStatDelta;
|
||||
import top.xyquan.ecomdmbbackend.modules.bi.messaging.BiStatMetricDelta;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.order.model.po.OrderItemPO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.order.model.po.OrderPO;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.order.status.support.OrderStatusStatSets;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.product.sku.mapper.ProductSkuMapper;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.product.sku.model.po.ProductSkuPO;
|
||||
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.math.RoundingMode;
|
||||
import java.time.LocalDate;
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* 单笔内部订单对日汇聚的贡献(转换侧算增量 delta 用)。
|
||||
*/
|
||||
@Component
|
||||
public class OrderStatContributionCalculator {
|
||||
|
||||
private final ProductSkuMapper productSkuMapper;
|
||||
private final OrderItemCostResolver orderItemCostResolver;
|
||||
|
||||
public OrderStatContributionCalculator(ProductSkuMapper productSkuMapper,
|
||||
OrderItemCostResolver orderItemCostResolver) {
|
||||
this.productSkuMapper = productSkuMapper;
|
||||
this.orderItemCostResolver = orderItemCostResolver;
|
||||
}
|
||||
|
||||
public OrderContribution contribute(OrderPO order, List<OrderItemPO> items, OrderStatusStatSets stat) {
|
||||
if (order == null || order.getOrderTime() == null) {
|
||||
return null;
|
||||
}
|
||||
LocalDate statDate = order.getOrderTime().toLocalDate();
|
||||
List<OrderItemPO> safeItems = items != null ? items : List.of();
|
||||
int qtySum = OrderStatusStatSets.totalQuantity(safeItems);
|
||||
if (qtySum <= 0 && safeItems.isEmpty()) {
|
||||
qtySum = 1;
|
||||
}
|
||||
BigDecimal received = OrderStatusStatSets.receivedAmount(order);
|
||||
boolean deal = stat.includesDeal(order.getStatus());
|
||||
boolean refund = stat.includesRefund(order.getStatus());
|
||||
if (!deal && !refund) {
|
||||
return null;
|
||||
}
|
||||
BigDecimal fee = deal ? nz(order.getServiceFee()) : BigDecimal.ZERO;
|
||||
|
||||
BiStatMetricDelta shop = BiStatMetricDelta.zeros();
|
||||
if (deal) {
|
||||
shop.setDealAmount(received);
|
||||
shop.setDealOrderCount(1);
|
||||
shop.setDealQuantitySum(qtySum);
|
||||
shop.setServiceFee(fee);
|
||||
}
|
||||
if (refund) {
|
||||
shop.setRefundAmount(received);
|
||||
shop.setRefundOrderCount(1);
|
||||
shop.setRefundQuantitySum(qtySum);
|
||||
}
|
||||
|
||||
Map<String, BiStatMetricDelta> productMap = new HashMap<>();
|
||||
Map<String, Long> productKeys = new HashMap<>();
|
||||
Map<String, BiStatMetricDelta> skuMap = new HashMap<>();
|
||||
Map<String, long[]> skuKeys = new HashMap<>();
|
||||
|
||||
Map<Long, Long> productBySku = loadProductBySku(safeItems);
|
||||
|
||||
for (OrderItemPO item : safeItems) {
|
||||
long skuId = item.getProductSkuId() != null ? item.getProductSkuId() : 0L;
|
||||
long productId = productBySku.getOrDefault(skuId, 0L);
|
||||
int qty = OrderStatusStatSets.quantity(item);
|
||||
BigDecimal lineReceived = allocateLine(received, item, safeItems);
|
||||
BigDecimal lineFee = deal ? allocateLine(fee, item, safeItems) : BigDecimal.ZERO;
|
||||
|
||||
String pk = String.valueOf(productId);
|
||||
BiStatMetricDelta pm = productMap.computeIfAbsent(pk, k -> BiStatMetricDelta.zeros());
|
||||
productKeys.putIfAbsent(pk, productId);
|
||||
if (deal) {
|
||||
pm.setDealAmount(nz(pm.getDealAmount()).add(lineReceived));
|
||||
pm.setDealQuantitySum(nzi(pm.getDealQuantitySum()) + qty);
|
||||
pm.setServiceFee(nz(pm.getServiceFee()).add(lineFee));
|
||||
}
|
||||
if (refund) {
|
||||
pm.setRefundAmount(nz(pm.getRefundAmount()).add(lineReceived));
|
||||
pm.setRefundQuantitySum(nzi(pm.getRefundQuantitySum()) + qty);
|
||||
}
|
||||
BigDecimal pc = orderItemCostResolver.productCostForStats(order, item, stat);
|
||||
BigDecimal fc = orderItemCostResolver.freightCostForStats(order, item, stat);
|
||||
BigDecimal oc = orderItemCostResolver.otherCostForStats(order, item, stat);
|
||||
pm.setProductCost(nz(pm.getProductCost()).add(pc));
|
||||
pm.setFreightCost(nz(pm.getFreightCost()).add(fc));
|
||||
pm.setOtherCost(nz(pm.getOtherCost()).add(oc));
|
||||
|
||||
String sk = String.valueOf(skuId);
|
||||
BiStatMetricDelta sm = skuMap.computeIfAbsent(sk, k -> BiStatMetricDelta.zeros());
|
||||
skuKeys.putIfAbsent(sk, new long[]{productId, skuId});
|
||||
if (deal) {
|
||||
sm.setDealAmount(nz(sm.getDealAmount()).add(lineReceived));
|
||||
sm.setDealQuantitySum(nzi(sm.getDealQuantitySum()) + qty);
|
||||
sm.setServiceFee(nz(sm.getServiceFee()).add(lineFee));
|
||||
}
|
||||
if (refund) {
|
||||
sm.setRefundAmount(nz(sm.getRefundAmount()).add(lineReceived));
|
||||
sm.setRefundQuantitySum(nzi(sm.getRefundQuantitySum()) + qty);
|
||||
}
|
||||
sm.setProductCost(nz(sm.getProductCost()).add(pc));
|
||||
sm.setFreightCost(nz(sm.getFreightCost()).add(fc));
|
||||
sm.setOtherCost(nz(sm.getOtherCost()).add(oc));
|
||||
|
||||
shop.setProductCost(nz(shop.getProductCost()).add(pc));
|
||||
shop.setFreightCost(nz(shop.getFreightCost()).add(fc));
|
||||
shop.setOtherCost(nz(shop.getOtherCost()).add(oc));
|
||||
}
|
||||
|
||||
// 订单计数:商品/SKU 维度每单计 1 次(有明细时)
|
||||
if (!safeItems.isEmpty()) {
|
||||
for (BiStatMetricDelta pm : productMap.values()) {
|
||||
if (deal) {
|
||||
pm.setDealOrderCount(1);
|
||||
}
|
||||
if (refund) {
|
||||
pm.setRefundOrderCount(1);
|
||||
}
|
||||
}
|
||||
for (BiStatMetricDelta sm : skuMap.values()) {
|
||||
if (deal) {
|
||||
sm.setDealOrderCount(1);
|
||||
}
|
||||
if (refund) {
|
||||
sm.setRefundOrderCount(1);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
List<BiProductStatDelta> products = new ArrayList<>();
|
||||
for (Map.Entry<String, BiStatMetricDelta> e : productMap.entrySet()) {
|
||||
products.add(BiProductStatDelta.builder()
|
||||
.productId(productKeys.get(e.getKey()))
|
||||
.metrics(e.getValue())
|
||||
.build());
|
||||
}
|
||||
List<BiSkuStatDelta> skus = new ArrayList<>();
|
||||
for (Map.Entry<String, BiStatMetricDelta> e : skuMap.entrySet()) {
|
||||
long[] k = skuKeys.get(e.getKey());
|
||||
skus.add(BiSkuStatDelta.builder()
|
||||
.productId(k[0])
|
||||
.productSkuId(k[1])
|
||||
.metrics(e.getValue())
|
||||
.build());
|
||||
}
|
||||
|
||||
return OrderContribution.builder()
|
||||
.statDate(statDate)
|
||||
.shop(shop)
|
||||
.products(products)
|
||||
.skus(skus)
|
||||
.build();
|
||||
}
|
||||
|
||||
/** skuId → productId(未绑定为 0) */
|
||||
private Map<Long, Long> loadProductBySku(List<OrderItemPO> items) {
|
||||
Map<Long, Long> map = new HashMap<>();
|
||||
List<Long> skuIds = items.stream()
|
||||
.map(OrderItemPO::getProductSkuId)
|
||||
.filter(id -> id != null && id > 0)
|
||||
.distinct()
|
||||
.toList();
|
||||
if (skuIds.isEmpty()) {
|
||||
return map;
|
||||
}
|
||||
for (ProductSkuPO sku : productSkuMapper.selectByIds(skuIds)) {
|
||||
map.put(sku.getId(), sku.getProductId() != null ? sku.getProductId() : 0L);
|
||||
}
|
||||
return map;
|
||||
}
|
||||
|
||||
private static BigDecimal allocateLine(BigDecimal orderPay, OrderItemPO item, List<OrderItemPO> items) {
|
||||
BigDecimal totalLine = BigDecimal.ZERO;
|
||||
for (OrderItemPO i : items) {
|
||||
totalLine = totalLine.add(nz(i.getLineAmount()));
|
||||
}
|
||||
if (totalLine.compareTo(BigDecimal.ZERO) > 0) {
|
||||
return orderPay.multiply(nz(item.getLineAmount())).divide(totalLine, 4, RoundingMode.HALF_UP);
|
||||
}
|
||||
if (items.isEmpty()) {
|
||||
return orderPay;
|
||||
}
|
||||
return orderPay.divide(BigDecimal.valueOf(items.size()), 4, RoundingMode.HALF_UP);
|
||||
}
|
||||
|
||||
private static BigDecimal nz(BigDecimal v) {
|
||||
return v != null ? v : BigDecimal.ZERO;
|
||||
}
|
||||
|
||||
private static int nzi(Integer v) {
|
||||
return v != null ? v : 0;
|
||||
}
|
||||
|
||||
@Data
|
||||
@Builder
|
||||
public static class OrderContribution {
|
||||
private LocalDate statDate;
|
||||
private BiStatMetricDelta shop;
|
||||
private List<BiProductStatDelta> products;
|
||||
private List<BiSkuStatDelta> skus;
|
||||
}
|
||||
}
|
||||
+97
@@ -0,0 +1,97 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.bi.overview.model.agg;
|
||||
|
||||
import lombok.Data;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.time.LocalDate;
|
||||
|
||||
/**
|
||||
* 概览/工作台 SQL 聚合行类型(原 OrderStatAggMapper 内嵌类,供 buildWorkbenchSummaryTablesFromAgg 等复用)。
|
||||
*/
|
||||
public final class OverviewAggRows {
|
||||
|
||||
private OverviewAggRows() {
|
||||
}
|
||||
|
||||
@Data
|
||||
public static class ShopProductRow {
|
||||
private Long shopId;
|
||||
private String platformCode;
|
||||
private Long productId;
|
||||
private Long categoryId;
|
||||
/** 净销售额 = dealAmount − refundAmount(读侧推导) */
|
||||
private BigDecimal salesAmount;
|
||||
/** 净销售单量 = dealOrderCount − refundOrderCount */
|
||||
private Long orderCount;
|
||||
/** 净销量 = dealQuantitySum − refundQuantitySum */
|
||||
private Long salesQuantitySum;
|
||||
private BigDecimal refundAmount;
|
||||
private Long refundOrderCount;
|
||||
private Long refundQuantitySum;
|
||||
private BigDecimal productCost;
|
||||
private BigDecimal freightCost;
|
||||
private BigDecimal otherCost;
|
||||
private BigDecimal dealAmount;
|
||||
private Long dealOrderCount;
|
||||
private Long dealQuantitySum;
|
||||
}
|
||||
|
||||
/**
|
||||
* 店铺×SKU 区间行(工作台 SKU 汇总表);净销售三件套同 {@link ShopProductRow}。
|
||||
*/
|
||||
@Data
|
||||
public static class ShopSkuRow {
|
||||
private Long shopId;
|
||||
private Long productId;
|
||||
private Long productSkuId;
|
||||
private BigDecimal salesAmount;
|
||||
private Long orderCount;
|
||||
private Long salesQuantitySum;
|
||||
private BigDecimal refundAmount;
|
||||
private Long refundOrderCount;
|
||||
private Long refundQuantitySum;
|
||||
private BigDecimal productCost;
|
||||
private BigDecimal freightCost;
|
||||
private BigDecimal otherCost;
|
||||
private BigDecimal dealAmount;
|
||||
private Long dealOrderCount;
|
||||
private Long dealQuantitySum;
|
||||
}
|
||||
|
||||
@Data
|
||||
public static class DailyRow {
|
||||
private LocalDate statDate;
|
||||
/** 净销售额 = dealAmount − refundAmount */
|
||||
private BigDecimal salesAmount;
|
||||
private BigDecimal dealAmount;
|
||||
private BigDecimal refundAmount;
|
||||
private BigDecimal productCost;
|
||||
private BigDecimal freightCost;
|
||||
private BigDecimal otherCost;
|
||||
/** 净销售单量 = dealOrderCount − refundOrderCount */
|
||||
private Long orderCount;
|
||||
private Long dealOrderCount;
|
||||
private Long refundOrderCount;
|
||||
}
|
||||
|
||||
@Data
|
||||
public static class FeeKpiRow {
|
||||
private BigDecimal curAmount;
|
||||
private BigDecimal prevAmount;
|
||||
private BigDecimal yoyAmount;
|
||||
}
|
||||
|
||||
@Data
|
||||
public static class PromotionRow {
|
||||
private Long shopId;
|
||||
private Long productId;
|
||||
private Long categoryId;
|
||||
private BigDecimal feeAmount;
|
||||
}
|
||||
|
||||
@Data
|
||||
public static class BrushRow {
|
||||
private Long shopId;
|
||||
private BigDecimal brushAmount;
|
||||
}
|
||||
}
|
||||
+29
@@ -0,0 +1,29 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.bi.overview.model.dto;
|
||||
|
||||
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
|
||||
import jakarta.validation.constraints.NotEmpty;
|
||||
import jakarta.validation.constraints.Size;
|
||||
import lombok.Data;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.time.LocalDate;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* 全店概览-按品类汇总导出参数
|
||||
*/
|
||||
@Data
|
||||
@JsonIgnoreProperties(ignoreUnknown = true)
|
||||
public class CategoryExportDTO {
|
||||
|
||||
@NotEmpty(message = "日期范围不能为空")
|
||||
@Size(min = 1, max = 2, message = "日期范围数组必须包含1-2个日期")
|
||||
private List<LocalDate> dateRange;
|
||||
|
||||
private List<Long> categoryIds;
|
||||
|
||||
private BigDecimal taxRate = new BigDecimal("0.04");
|
||||
|
||||
/** 店铺导出接口传入时用于下载文件名(店铺名_按品类汇总统计_日期.xlsx) */
|
||||
private Long shopId;
|
||||
}
|
||||
+28
@@ -0,0 +1,28 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.bi.overview.model.dto;
|
||||
|
||||
import jakarta.validation.constraints.NotEmpty;
|
||||
import jakarta.validation.constraints.Size;
|
||||
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
|
||||
import lombok.Data;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.time.LocalDate;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* 全店概览-按店铺汇总导出参数
|
||||
*/
|
||||
@Data
|
||||
@JsonIgnoreProperties(ignoreUnknown = true)
|
||||
public class CompanyExportDTO {
|
||||
|
||||
@NotEmpty(message = "日期范围不能为空")
|
||||
@Size(min = 1, max = 2, message = "日期范围数组必须包含1-2个日期")
|
||||
private List<LocalDate> dateRange;
|
||||
|
||||
private List<Long> shopIds;
|
||||
|
||||
private String exportType = "all";
|
||||
|
||||
private BigDecimal taxRate = new BigDecimal("0.04");
|
||||
}
|
||||
+26
@@ -0,0 +1,26 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.bi.overview.model.dto;
|
||||
|
||||
import jakarta.validation.constraints.NotEmpty;
|
||||
import jakarta.validation.constraints.Size;
|
||||
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
|
||||
import lombok.Data;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.time.LocalDate;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* 全店概览-按平台汇总导出参数
|
||||
*/
|
||||
@Data
|
||||
@JsonIgnoreProperties(ignoreUnknown = true)
|
||||
public class PlatformExportDTO {
|
||||
|
||||
@NotEmpty(message = "日期范围不能为空")
|
||||
@Size(min = 1, max = 2, message = "日期范围数组必须包含1-2个日期")
|
||||
private List<LocalDate> dateRange;
|
||||
|
||||
private List<String> platformCodes;
|
||||
|
||||
private BigDecimal taxRate = new BigDecimal("0.04");
|
||||
}
|
||||
+396
@@ -0,0 +1,396 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.bi.overview.model.vo;
|
||||
|
||||
import lombok.Data;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* 全店铺概览VO
|
||||
*/
|
||||
@Data
|
||||
public class CompanyOverviewVO {
|
||||
|
||||
/**
|
||||
* 全店总销售额
|
||||
*/
|
||||
private BigDecimal totalSalesAmount;
|
||||
|
||||
/**
|
||||
* 较上月同期增长百分比
|
||||
*/
|
||||
private BigDecimal monthOverMonthGrowth;
|
||||
|
||||
/**
|
||||
* 全店总单量
|
||||
*/
|
||||
private Integer totalOrderCount;
|
||||
|
||||
/**
|
||||
* 总推广费支出
|
||||
*/
|
||||
private BigDecimal totalPromotionFee;
|
||||
|
||||
/**
|
||||
* 平均费比(推广费/销售额)
|
||||
*/
|
||||
private BigDecimal averageFeeRatio;
|
||||
|
||||
/**
|
||||
* 全店总净利(税后)
|
||||
*/
|
||||
private BigDecimal totalNetProfitAfterTax;
|
||||
|
||||
/**
|
||||
* 扣除总税额
|
||||
*/
|
||||
private BigDecimal totalTaxAmount;
|
||||
|
||||
/**
|
||||
* 各店铺销售占比排行
|
||||
*/
|
||||
private List<ShopSalesRatio> shopSalesRatios;
|
||||
|
||||
/**
|
||||
* 店铺效率象限(ROI vs 净利)
|
||||
*/
|
||||
private List<ShopEfficiencyQuadrant> shopEfficiencyQuadrants;
|
||||
|
||||
/**
|
||||
* 多店铺数据横向汇总(包含合计行和店铺列表)
|
||||
*/
|
||||
private ShopOverview shopSummary;
|
||||
|
||||
/**
|
||||
* 多品类数据横向汇总(包含合计行和品类列表)
|
||||
*/
|
||||
private CategoryOverview categorySummary;
|
||||
|
||||
/**
|
||||
* 平台维度概览(包含合计行和平台列表)
|
||||
*/
|
||||
@Data
|
||||
public static class PlatformOverview {
|
||||
private PlatformSummary total;
|
||||
|
||||
private List<PlatformSummary> platforms;
|
||||
}
|
||||
|
||||
/**
|
||||
* 多店铺概览(包含合计行和店铺列表)
|
||||
*/
|
||||
@Data
|
||||
public static class ShopOverview {
|
||||
private ShopSummary total;
|
||||
|
||||
private List<ShopSummary> shops;
|
||||
}
|
||||
|
||||
/**
|
||||
* 多品类概览(包含合计行和品类列表)
|
||||
*/
|
||||
@Data
|
||||
public static class CategoryOverview {
|
||||
private CategorySummary total;
|
||||
|
||||
private List<CategorySummary> categories;
|
||||
}
|
||||
|
||||
/**
|
||||
* 工作台底部四张汇总表(与全店概览「店铺/平台/品类」及扩展「商品」表同源计算)
|
||||
*/
|
||||
@Data
|
||||
public static class WorkbenchTableBundle {
|
||||
private ShopOverview shopTable;
|
||||
private PlatformOverview platformTable;
|
||||
private CategoryOverview categoryTable;
|
||||
private CategoryOverview productTable;
|
||||
/** SKU 汇总(复用 CategoryOverview;categoryId=skuId,categoryName=商品名/规格名) */
|
||||
private CategoryOverview skuTable;
|
||||
}
|
||||
|
||||
/**
|
||||
* 平台维度汇总
|
||||
*/
|
||||
private PlatformOverview platformSummary;
|
||||
|
||||
/**
|
||||
* 汇总ROI
|
||||
*/
|
||||
private BigDecimal totalROI;
|
||||
|
||||
/**
|
||||
* 总税后盈亏
|
||||
*/
|
||||
private BigDecimal totalProfitAfterTax;
|
||||
|
||||
/**
|
||||
* 全店总销量目标(目标订单数)
|
||||
*/
|
||||
private Integer totalTargetOrderCount;
|
||||
|
||||
/**
|
||||
* 全店总销售额目标
|
||||
*/
|
||||
private BigDecimal totalTargetAmount;
|
||||
|
||||
/**
|
||||
* 销量目标达成率(实际订单数/目标订单数)
|
||||
*/
|
||||
private BigDecimal orderCountAchievementRate;
|
||||
|
||||
/**
|
||||
* 销售额目标达成率(净销售额/目标销售额)
|
||||
*/
|
||||
private BigDecimal salesAmountAchievementRate;
|
||||
|
||||
/**
|
||||
* 店铺销售占比
|
||||
*/
|
||||
@Data
|
||||
public static class ShopSalesRatio {
|
||||
private Long shopId;
|
||||
|
||||
private String shopName;
|
||||
|
||||
private BigDecimal salesAmount;
|
||||
|
||||
private BigDecimal ratio;
|
||||
}
|
||||
|
||||
/**
|
||||
* 店铺效率象限
|
||||
*/
|
||||
@Data
|
||||
public static class ShopEfficiencyQuadrant {
|
||||
private Long shopId;
|
||||
|
||||
private String shopName;
|
||||
|
||||
private BigDecimal roi;
|
||||
|
||||
private BigDecimal netProfit;
|
||||
|
||||
private Integer quadrant;
|
||||
}
|
||||
|
||||
/**
|
||||
* 店铺汇总数据
|
||||
*/
|
||||
@Data
|
||||
public static class ShopSummary {
|
||||
private Long shopId;
|
||||
|
||||
private String shopName;
|
||||
|
||||
private String platform;
|
||||
|
||||
private Integer targetOrderCount;
|
||||
|
||||
private BigDecimal orderCountAchievementRate;
|
||||
|
||||
private BigDecimal targetAmount;
|
||||
|
||||
private BigDecimal salesAmountAchievementRate;
|
||||
|
||||
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 Integer refundOrderCount;
|
||||
|
||||
/** 退款件数 */
|
||||
private Integer refundQuantitySum;
|
||||
|
||||
private BigDecimal totalPromotionFee;
|
||||
|
||||
private BigDecimal brushFee;
|
||||
|
||||
private BigDecimal feeRatio;
|
||||
|
||||
private BigDecimal grossProfit;
|
||||
|
||||
private BigDecimal totalProfitBeforeTax;
|
||||
|
||||
private BigDecimal salesTaxAmount;
|
||||
|
||||
private BigDecimal profitAfterTax;
|
||||
|
||||
private BigDecimal roi;
|
||||
}
|
||||
|
||||
/**
|
||||
* 品类汇总数据
|
||||
*/
|
||||
@Data
|
||||
public static class CategorySummary {
|
||||
private Long categoryId;
|
||||
|
||||
private String categoryName;
|
||||
|
||||
/** SKU 汇总行:所属商品名(展示用) */
|
||||
private String productName;
|
||||
|
||||
/** SKU 汇总行:规格编码(悬停展示) */
|
||||
private String skuCode;
|
||||
|
||||
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 Integer refundOrderCount;
|
||||
|
||||
/** 退款件数 */
|
||||
private Integer refundQuantitySum;
|
||||
|
||||
private BigDecimal totalPromotionFee;
|
||||
|
||||
private BigDecimal brushFee;
|
||||
|
||||
private BigDecimal feeRatio;
|
||||
|
||||
private BigDecimal grossProfit;
|
||||
|
||||
private BigDecimal totalProfitBeforeTax;
|
||||
|
||||
private BigDecimal salesTaxAmount;
|
||||
|
||||
private BigDecimal profitAfterTax;
|
||||
|
||||
private BigDecimal roi;
|
||||
}
|
||||
|
||||
/**
|
||||
* 平台维度汇总
|
||||
*/
|
||||
@Data
|
||||
public static class PlatformSummary {
|
||||
private String platformCode;
|
||||
|
||||
private String platformName;
|
||||
|
||||
private Integer targetOrderCount;
|
||||
|
||||
private BigDecimal orderCountAchievementRate;
|
||||
|
||||
private BigDecimal targetAmount;
|
||||
|
||||
private BigDecimal salesAmountAchievementRate;
|
||||
|
||||
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 Integer refundOrderCount;
|
||||
|
||||
/** 退款件数 */
|
||||
private Integer refundQuantitySum;
|
||||
|
||||
private BigDecimal totalPromotionFee;
|
||||
|
||||
private BigDecimal brushFee;
|
||||
|
||||
private BigDecimal feeRatio;
|
||||
|
||||
private BigDecimal grossProfit;
|
||||
|
||||
private BigDecimal totalProfitBeforeTax;
|
||||
|
||||
private BigDecimal salesTaxAmount;
|
||||
|
||||
private BigDecimal roi;
|
||||
|
||||
private BigDecimal profitAfterTax;
|
||||
}
|
||||
}
|
||||
|
||||
+24
@@ -0,0 +1,24 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.bi.overview.service;
|
||||
|
||||
import top.xyquan.ecomdmbbackend.modules.bi.overview.model.dto.CategoryExportDTO;
|
||||
import top.xyquan.ecomdmbbackend.modules.bi.overview.model.vo.CompanyOverviewVO;
|
||||
|
||||
/**
|
||||
* 按品类维度导出 Excel(店铺品类汇总、工作台品类/商品维表)。
|
||||
*/
|
||||
public interface CategoryExportExcelService {
|
||||
|
||||
/** 店铺维度:按店铺 ID 导出品类汇总。 */
|
||||
byte[] exportCategoryOverview(CategoryExportDTO dto);
|
||||
|
||||
/**
|
||||
* 多维度经营明细:品类/商品维度表已由调用方按筛选口径汇总,仅写「汇总」Sheet(无趋势表)。
|
||||
*
|
||||
* @param dimensionColumnHeader 首列表头,如「品类名称」「商品名称」
|
||||
*/
|
||||
byte[] exportCategoryDimensionsFromTable(
|
||||
CategoryExportDTO dto,
|
||||
CompanyOverviewVO.CategoryOverview overview,
|
||||
String summaryTitle,
|
||||
String dimensionColumnHeader);
|
||||
}
|
||||
+46
@@ -0,0 +1,46 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.bi.overview.service;
|
||||
|
||||
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.ec.shop.model.po.ShopPO;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.time.LocalDate;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* 工作台汇总表构建(原全店概览服务收口后仅保留聚合读路径)。
|
||||
*/
|
||||
public interface CompanyOverviewService {
|
||||
|
||||
/**
|
||||
* 基于 Mongo/SQL 聚合行构建工作台底部汇总表(不含 SKU 表)。
|
||||
*/
|
||||
default CompanyOverviewVO.WorkbenchTableBundle buildWorkbenchSummaryTablesFromAgg(
|
||||
BigDecimal taxRate,
|
||||
Long companyId,
|
||||
List<ShopPO> shops,
|
||||
List<OverviewAggRows.ShopProductRow> orderRows,
|
||||
List<OverviewAggRows.PromotionRow> promotionRows,
|
||||
List<OverviewAggRows.BrushRow> brushRows,
|
||||
LocalDate startDate,
|
||||
LocalDate endDate) {
|
||||
return buildWorkbenchSummaryTablesFromAgg(
|
||||
taxRate, companyId, shops, orderRows, promotionRows, brushRows,
|
||||
startDate, endDate, List.of());
|
||||
}
|
||||
|
||||
/**
|
||||
* 基于商品行 + 可选 SKU 行构建工作台底部汇总表(含 skuTable)。
|
||||
*/
|
||||
CompanyOverviewVO.WorkbenchTableBundle buildWorkbenchSummaryTablesFromAgg(
|
||||
BigDecimal taxRate,
|
||||
Long companyId,
|
||||
List<ShopPO> shops,
|
||||
List<OverviewAggRows.ShopProductRow> orderRows,
|
||||
List<OverviewAggRows.PromotionRow> promotionRows,
|
||||
List<OverviewAggRows.BrushRow> brushRows,
|
||||
LocalDate startDate,
|
||||
LocalDate endDate,
|
||||
List<OverviewAggRows.ShopSkuRow> skuRows);
|
||||
}
|
||||
+21
@@ -0,0 +1,21 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.bi.overview.service;
|
||||
|
||||
import top.xyquan.ecomdmbbackend.modules.bi.overview.model.dto.CompanyExportDTO;
|
||||
import top.xyquan.ecomdmbbackend.modules.bi.overview.model.dto.PlatformExportDTO;
|
||||
import top.xyquan.ecomdmbbackend.modules.bi.overview.model.vo.CompanyOverviewVO;
|
||||
|
||||
/**
|
||||
* 工作台等多维表导出(按已汇总好的表写入 Excel)。
|
||||
*/
|
||||
public interface ExportService {
|
||||
|
||||
/**
|
||||
* 多维度经营明细:已按筛选口径汇总好的「按店铺」表写入 Excel(不含趋势表)。
|
||||
*/
|
||||
byte[] exportShopOverviewFromTable(CompanyExportDTO dto, CompanyOverviewVO.ShopOverview shopOverview, String summaryTitle);
|
||||
|
||||
/**
|
||||
* 多维度经营明细:已按筛选口径汇总好的「按平台」表写入 Excel(不含趋势表)。
|
||||
*/
|
||||
byte[] exportPlatformOverviewFromTable(PlatformExportDTO dto, CompanyOverviewVO.PlatformOverview platformOverview, String summaryTitle);
|
||||
}
|
||||
+502
@@ -0,0 +1,502 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.bi.overview.service.impl;
|
||||
|
||||
import org.apache.poi.ss.usermodel.*;
|
||||
import org.apache.poi.ss.util.CellRangeAddress;
|
||||
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
|
||||
import org.springframework.stereotype.Service;
|
||||
import top.xyquan.ecomdmbbackend.common.exception.BusinessException;
|
||||
import top.xyquan.ecomdmbbackend.modules.bi.shopoverview.model.dto.ShopOverviewQueryDTO;
|
||||
import top.xyquan.ecomdmbbackend.modules.bi.shopoverview.model.vo.ShopOverviewStatisticsVO;
|
||||
import top.xyquan.ecomdmbbackend.modules.bi.shopoverview.service.BiShopOverviewService;
|
||||
import top.xyquan.ecomdmbbackend.modules.bi.overview.model.dto.CategoryExportDTO;
|
||||
import top.xyquan.ecomdmbbackend.modules.bi.overview.model.vo.CompanyOverviewVO;
|
||||
import top.xyquan.ecomdmbbackend.modules.bi.overview.service.CategoryExportExcelService;
|
||||
import top.xyquan.ecomdmbbackend.modules.bi.workbench.model.vo.WorkbenchTrendPointVO;
|
||||
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.math.BigDecimal;
|
||||
import java.math.RoundingMode;
|
||||
import java.time.LocalDate;
|
||||
import java.time.format.DateTimeFormatter;
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.HashSet;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
@Service
|
||||
public class CategoryExportExcelServiceImpl implements CategoryExportExcelService {
|
||||
|
||||
private static final BigDecimal DEFAULT_TAX_RATE = new BigDecimal("0.04");
|
||||
private static final DateTimeFormatter DATE_FMT = DateTimeFormatter.ofPattern("yyyy-MM-dd");
|
||||
|
||||
/** 税额 = 净销售额 × 税率 */
|
||||
private static BigDecimal salesTaxOnNetForCategoryExport(BigDecimal sales, BigDecimal taxRate) {
|
||||
BigDecimal s = sales != null ? sales : BigDecimal.ZERO;
|
||||
BigDecimal r = taxRate != null ? taxRate : DEFAULT_TAX_RATE;
|
||||
BigDecimal base = s.compareTo(BigDecimal.ZERO) < 0 ? BigDecimal.ZERO : s;
|
||||
return base.multiply(r).setScale(2, RoundingMode.HALF_UP);
|
||||
}
|
||||
|
||||
private final ExportStatusRangeHelper exportStatusRangeHelper;
|
||||
private final BiShopOverviewService biShopOverviewService;
|
||||
|
||||
public CategoryExportExcelServiceImpl(
|
||||
ExportStatusRangeHelper exportStatusRangeHelper,
|
||||
BiShopOverviewService biShopOverviewService) {
|
||||
this.exportStatusRangeHelper = exportStatusRangeHelper;
|
||||
this.biShopOverviewService = biShopOverviewService;
|
||||
}
|
||||
|
||||
@Override
|
||||
public byte[] exportCategoryOverview(CategoryExportDTO dto) {
|
||||
if (dto.getShopId() == null) {
|
||||
throw new BusinessException("按品类导出必须指定店铺");
|
||||
}
|
||||
return exportShopCategoryViaOverview(dto);
|
||||
}
|
||||
|
||||
@Override
|
||||
public byte[] exportCategoryDimensionsFromTable(
|
||||
CategoryExportDTO dto,
|
||||
CompanyOverviewVO.CategoryOverview co,
|
||||
String summaryTitle,
|
||||
String dimensionColumnHeader) {
|
||||
BigDecimal taxRate = dto.getTaxRate() != null ? dto.getTaxRate() : DEFAULT_TAX_RATE;
|
||||
LocalDate[] dateRange = exportStatusRangeHelper.parseDateRange(dto.getDateRange());
|
||||
LocalDate startDate = dateRange[0];
|
||||
LocalDate endDate = dateRange[1];
|
||||
String dateRangeLabel = startDate.format(DATE_FMT) + " 至 " + endDate.format(DATE_FMT);
|
||||
|
||||
List<CompanyOverviewVO.CategorySummary> catRows = (co != null && co.getCategories() != null)
|
||||
? new ArrayList<>(co.getCategories())
|
||||
: new ArrayList<>();
|
||||
|
||||
if (dto.getCategoryIds() != null && !dto.getCategoryIds().isEmpty()) {
|
||||
Set<Long> allowed = new HashSet<>(dto.getCategoryIds());
|
||||
catRows = catRows.stream()
|
||||
.filter(c -> allowed.contains(c.getCategoryId() != null ? c.getCategoryId() : 0L))
|
||||
.collect(Collectors.toList());
|
||||
}
|
||||
|
||||
List<ShopOverviewStatisticsVO.CategorySummary> shopRows = catRows.stream()
|
||||
.map(this::toShopCategorySummary)
|
||||
.collect(Collectors.toList());
|
||||
|
||||
boolean filtered = dto.getCategoryIds() != null && !dto.getCategoryIds().isEmpty();
|
||||
ShopOverviewStatisticsVO.CategorySummary totalRow = filtered
|
||||
? aggregateCategoryTotals(shopRows, taxRate)
|
||||
: (co != null && co.getTotal() != null
|
||||
? toShopCategorySummary(co.getTotal())
|
||||
: aggregateCategoryTotals(shopRows, taxRate));
|
||||
|
||||
try (Workbook workbook = new XSSFWorkbook()) {
|
||||
Sheet sheet = workbook.createSheet("汇总");
|
||||
writeCategoryMultidimensionalSheet(
|
||||
sheet, summaryTitle, dateRangeLabel, shopRows, totalRow, taxRate, dimensionColumnHeader);
|
||||
try (ByteArrayOutputStream out = new ByteArrayOutputStream()) {
|
||||
workbook.write(out);
|
||||
return out.toByteArray();
|
||||
}
|
||||
} catch (Exception e) {
|
||||
throw new BusinessException("导出Excel失败: " + e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 店铺侧导出:与 {@link BiShopOverviewService#getShopOverview} 同源,
|
||||
* 保证订单状态参与统计、推广费/刷单费分摊与前端「品类多维度损益汇总」一致。
|
||||
*/
|
||||
private byte[] exportShopCategoryViaOverview(CategoryExportDTO dto) {
|
||||
BigDecimal taxRate = dto.getTaxRate() != null ? dto.getTaxRate() : DEFAULT_TAX_RATE;
|
||||
LocalDate[] dateRange = exportStatusRangeHelper.parseDateRange(dto.getDateRange());
|
||||
LocalDate startDate = dateRange[0];
|
||||
LocalDate endDate = dateRange[1];
|
||||
String dateRangeLabel = startDate.format(DATE_FMT) + " 至 " + endDate.format(DATE_FMT);
|
||||
|
||||
ShopOverviewQueryDTO query = new ShopOverviewQueryDTO();
|
||||
query.setShopId(dto.getShopId());
|
||||
query.setDateRange(dto.getDateRange());
|
||||
query.setTaxRate(taxRate);
|
||||
|
||||
ShopOverviewStatisticsVO vo = biShopOverviewService.getShopOverview(query);
|
||||
ShopOverviewStatisticsVO.CategoryOverview co = vo.getCategoryOverview();
|
||||
|
||||
List<ShopOverviewStatisticsVO.CategorySummary> rows = (co != null && co.getCategories() != null)
|
||||
? new ArrayList<>(co.getCategories())
|
||||
: new ArrayList<>();
|
||||
ShopOverviewStatisticsVO.CategorySummary totalRow = (co != null && co.getTotal() != null)
|
||||
? co.getTotal()
|
||||
: aggregateCategoryTotals(rows, taxRate);
|
||||
|
||||
if (dto.getCategoryIds() != null && !dto.getCategoryIds().isEmpty()) {
|
||||
Set<Long> allowed = new HashSet<>(dto.getCategoryIds());
|
||||
rows = rows.stream()
|
||||
.filter(c -> allowed.contains(c.getCategoryId()))
|
||||
.collect(Collectors.toList());
|
||||
totalRow = aggregateCategoryTotals(rows, taxRate);
|
||||
}
|
||||
|
||||
String shopTitle = vo.getShopName() != null && !vo.getShopName().isBlank()
|
||||
? vo.getShopName() + " - 品类多维度损益汇总"
|
||||
: ("店铺" + dto.getShopId() + " - 品类多维度损益汇总");
|
||||
|
||||
try (Workbook workbook = new XSSFWorkbook()) {
|
||||
Sheet sheet = workbook.createSheet("品类汇总");
|
||||
writeCategoryMultidimensionalSheet(sheet, shopTitle, dateRangeLabel, rows, totalRow, taxRate, "品类名称");
|
||||
if (vo.getDealTrend() != null && !vo.getDealTrend().isEmpty()) {
|
||||
Sheet trendSheet = workbook.createSheet("销量趋势");
|
||||
writeShopSalesTrendSheet(trendSheet, shopTitle, dateRangeLabel, vo);
|
||||
}
|
||||
try (ByteArrayOutputStream out = new ByteArrayOutputStream()) {
|
||||
workbook.write(out);
|
||||
return out.toByteArray();
|
||||
}
|
||||
} catch (Exception e) {
|
||||
throw new BusinessException("导出品类Excel失败: " + e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
/** 与店铺概览销量趋势同源:从 {@link ShopOverviewStatisticsVO#getDealTrend()} 取日销售额/单量。 */
|
||||
private void writeShopSalesTrendSheet(
|
||||
Sheet sheet, String shopContextTitle, String dateRangeLabel, ShopOverviewStatisticsVO vo) {
|
||||
Workbook wb = sheet.getWorkbook();
|
||||
CellStyle headerStyle = createHeaderStyle(wb);
|
||||
CellStyle dataStyle = createDataStyle(wb);
|
||||
|
||||
Row titleRow = sheet.createRow(0);
|
||||
Cell titleCell = titleRow.createCell(0);
|
||||
titleCell.setCellValue(shopContextTitle + " - 销量趋势 | " + dateRangeLabel);
|
||||
titleCell.setCellStyle(createTitleStyle(wb));
|
||||
sheet.addMergedRegion(new CellRangeAddress(0, 0, 0, 2));
|
||||
|
||||
String[] headers = {"日期", "销售额", "单量"};
|
||||
Row headerRow = sheet.createRow(1);
|
||||
for (int i = 0; i < headers.length; i++) {
|
||||
Cell cell = headerRow.createCell(i);
|
||||
cell.setCellValue(headers[i]);
|
||||
cell.setCellStyle(headerStyle);
|
||||
}
|
||||
|
||||
List<WorkbenchTrendPointVO> dealTrend = vo.getDealTrend();
|
||||
if (dealTrend == null || dealTrend.isEmpty()) {
|
||||
sheet.setColumnWidth(0, 3200);
|
||||
sheet.setColumnWidth(1, 3200);
|
||||
sheet.setColumnWidth(2, 3200);
|
||||
return;
|
||||
}
|
||||
|
||||
Map<LocalDate, BigDecimal> salesMap = new HashMap<>();
|
||||
Map<LocalDate, BigDecimal> ordersMap = new HashMap<>();
|
||||
LocalDate startDate = null;
|
||||
LocalDate endDate = null;
|
||||
for (WorkbenchTrendPointVO p : dealTrend) {
|
||||
if (p == null || p.getDate() == null || p.getDate().isBlank()) {
|
||||
continue;
|
||||
}
|
||||
LocalDate d = LocalDate.parse(p.getDate());
|
||||
salesMap.put(d, p.getSalesYuan() != null ? p.getSalesYuan() : BigDecimal.ZERO);
|
||||
ordersMap.put(d, BigDecimal.valueOf(p.getSalesOrderCount() != null ? p.getSalesOrderCount() : 0));
|
||||
if (startDate == null || d.isBefore(startDate)) {
|
||||
startDate = d;
|
||||
}
|
||||
if (endDate == null || d.isAfter(endDate)) {
|
||||
endDate = d;
|
||||
}
|
||||
}
|
||||
|
||||
int rowIdx = 2;
|
||||
if (startDate != null && endDate != null) {
|
||||
LocalDate current = startDate;
|
||||
while (!current.isAfter(endDate)) {
|
||||
Row row = sheet.createRow(rowIdx++);
|
||||
BigDecimal sales = salesMap.getOrDefault(current, BigDecimal.ZERO);
|
||||
BigDecimal orders = ordersMap.getOrDefault(current, BigDecimal.ZERO);
|
||||
setCell(row, 0, current.format(DATE_FMT), dataStyle);
|
||||
setCell(row, 1, sales.setScale(2, RoundingMode.HALF_UP).doubleValue(), dataStyle);
|
||||
setCell(row, 2, orders.setScale(0, RoundingMode.HALF_UP).doubleValue(), dataStyle);
|
||||
current = current.plusDays(1);
|
||||
}
|
||||
}
|
||||
|
||||
sheet.setColumnWidth(0, 3200);
|
||||
sheet.setColumnWidth(1, 3200);
|
||||
sheet.setColumnWidth(2, 3200);
|
||||
}
|
||||
|
||||
private ShopOverviewStatisticsVO.CategorySummary toShopCategorySummary(CompanyOverviewVO.CategorySummary c) {
|
||||
ShopOverviewStatisticsVO.CategorySummary s = new ShopOverviewStatisticsVO.CategorySummary();
|
||||
s.setCategoryId(c.getCategoryId() != null ? c.getCategoryId() : 0L);
|
||||
s.setCategoryName(c.getCategoryName());
|
||||
s.setSalesAmount(c.getSalesAmount());
|
||||
s.setDealAmount(c.getDealAmount());
|
||||
s.setSalesOrderCount(c.getSalesOrderCount());
|
||||
s.setDealOrderCount(c.getDealOrderCount());
|
||||
s.setDealQuantitySum(c.getDealQuantitySum());
|
||||
s.setSalesQuantitySum(c.getSalesQuantitySum());
|
||||
s.setSalesAverageOrderValue(c.getSalesAverageOrderValue());
|
||||
s.setDealAverageOrderValue(c.getDealAverageOrderValue());
|
||||
s.setProductCost(c.getProductCost());
|
||||
s.setShippingCost(c.getShippingCost());
|
||||
s.setOtherCost(c.getOtherCost());
|
||||
s.setOrderCost(c.getOrderCost());
|
||||
s.setRefundAmount(c.getRefundAmount());
|
||||
s.setTotalPromotionFee(c.getTotalPromotionFee());
|
||||
s.setBrushFee(c.getBrushFee());
|
||||
s.setFeeRatio(c.getFeeRatio());
|
||||
s.setTotalProfitBeforeTax(c.getTotalProfitBeforeTax());
|
||||
s.setSalesTaxAmount(c.getSalesTaxAmount());
|
||||
s.setProfitAfterTax(c.getProfitAfterTax());
|
||||
s.setRoi(c.getRoi());
|
||||
return s;
|
||||
}
|
||||
|
||||
/** 与店铺概览品类「合计」行算法一致,用于按品类 ID 筛选导出后的合计行。 */
|
||||
private ShopOverviewStatisticsVO.CategorySummary aggregateCategoryTotals(
|
||||
List<ShopOverviewStatisticsVO.CategorySummary> categories, BigDecimal taxRate) {
|
||||
BigDecimal totalSales = BigDecimal.ZERO;
|
||||
BigDecimal totalDealAmount = BigDecimal.ZERO;
|
||||
int totalSalesOrders = 0;
|
||||
int totalDealOrders = 0;
|
||||
int totalDealQuantity = 0;
|
||||
int totalSalesQuantity = 0;
|
||||
BigDecimal totalProductCost = BigDecimal.ZERO;
|
||||
BigDecimal totalShippingCost = BigDecimal.ZERO;
|
||||
BigDecimal totalOtherCost = BigDecimal.ZERO;
|
||||
BigDecimal totalRefund = BigDecimal.ZERO;
|
||||
BigDecimal totalPromoFee = BigDecimal.ZERO;
|
||||
BigDecimal totalBrushFee = BigDecimal.ZERO;
|
||||
|
||||
for (ShopOverviewStatisticsVO.CategorySummary c : categories) {
|
||||
totalSales = totalSales.add(c.getSalesAmount() != null ? c.getSalesAmount() : BigDecimal.ZERO);
|
||||
totalDealAmount = totalDealAmount.add(c.getDealAmount() != null ? c.getDealAmount() : BigDecimal.ZERO);
|
||||
totalSalesOrders += c.getSalesOrderCount() != null ? c.getSalesOrderCount() : 0;
|
||||
totalDealOrders += c.getDealOrderCount() != null ? c.getDealOrderCount() : 0;
|
||||
totalDealQuantity += c.getDealQuantitySum() != null ? c.getDealQuantitySum() : 0;
|
||||
totalSalesQuantity += c.getSalesQuantitySum() != null ? c.getSalesQuantitySum() : 0;
|
||||
totalProductCost = totalProductCost.add(c.getProductCost() != null ? c.getProductCost() : BigDecimal.ZERO);
|
||||
totalShippingCost = totalShippingCost.add(c.getShippingCost() != null ? c.getShippingCost() : BigDecimal.ZERO);
|
||||
totalOtherCost = totalOtherCost.add(c.getOtherCost() != null ? c.getOtherCost() : BigDecimal.ZERO);
|
||||
totalRefund = totalRefund.add(c.getRefundAmount() != null ? c.getRefundAmount() : BigDecimal.ZERO);
|
||||
totalPromoFee = totalPromoFee.add(c.getTotalPromotionFee() != null ? c.getTotalPromotionFee() : BigDecimal.ZERO);
|
||||
totalBrushFee = totalBrushFee.add(c.getBrushFee() != null ? c.getBrushFee() : BigDecimal.ZERO);
|
||||
}
|
||||
|
||||
BigDecimal salesAvgOrderValue = totalSalesOrders > 0
|
||||
? totalSales.divide(new BigDecimal(totalSalesOrders), 2, RoundingMode.HALF_UP)
|
||||
: BigDecimal.ZERO;
|
||||
BigDecimal dealAvgOrderValue = totalDealOrders > 0
|
||||
? totalDealAmount.divide(new BigDecimal(totalDealOrders), 2, RoundingMode.HALF_UP)
|
||||
: BigDecimal.ZERO;
|
||||
BigDecimal totalCost = totalProductCost.add(totalShippingCost).add(totalOtherCost);
|
||||
BigDecimal profitBeforeTax = totalSales.subtract(totalCost)
|
||||
.subtract(totalPromoFee).subtract(totalBrushFee);
|
||||
BigDecimal salesTax = salesTaxOnNetForCategoryExport(totalSales, taxRate);
|
||||
BigDecimal profitAfterTax = profitBeforeTax.subtract(salesTax);
|
||||
BigDecimal roi = totalPromoFee.compareTo(BigDecimal.ZERO) > 0
|
||||
? totalSales.divide(totalPromoFee, 4, RoundingMode.HALF_UP)
|
||||
: BigDecimal.ZERO;
|
||||
BigDecimal feeRatio = totalSales.compareTo(BigDecimal.ZERO) > 0
|
||||
? totalPromoFee.add(totalBrushFee).divide(totalSales, 4, RoundingMode.HALF_UP)
|
||||
: BigDecimal.ZERO;
|
||||
|
||||
ShopOverviewStatisticsVO.CategorySummary total = new ShopOverviewStatisticsVO.CategorySummary();
|
||||
total.setCategoryId(0L);
|
||||
total.setCategoryName("合计");
|
||||
total.setSalesAmount(totalSales);
|
||||
total.setDealAmount(totalDealAmount);
|
||||
total.setSalesOrderCount(totalSalesOrders);
|
||||
total.setDealOrderCount(totalDealOrders);
|
||||
total.setDealQuantitySum(totalDealQuantity);
|
||||
total.setSalesQuantitySum(totalSalesQuantity);
|
||||
total.setSalesAverageOrderValue(salesAvgOrderValue);
|
||||
total.setDealAverageOrderValue(dealAvgOrderValue);
|
||||
total.setProductCost(totalProductCost);
|
||||
total.setShippingCost(totalShippingCost);
|
||||
total.setOtherCost(totalOtherCost);
|
||||
total.setOrderCost(totalCost);
|
||||
total.setRefundAmount(totalRefund);
|
||||
total.setTotalPromotionFee(totalPromoFee);
|
||||
total.setBrushFee(totalBrushFee);
|
||||
total.setFeeRatio(feeRatio);
|
||||
total.setTotalProfitBeforeTax(profitBeforeTax);
|
||||
total.setSalesTaxAmount(salesTax);
|
||||
total.setRoi(roi);
|
||||
total.setProfitAfterTax(profitAfterTax.setScale(2, RoundingMode.HALF_UP));
|
||||
return total;
|
||||
}
|
||||
|
||||
/**
|
||||
* 列顺序与工作台品类/商品汇总表一致:税额在订单成本后,费比在 ROI 前。
|
||||
*/
|
||||
private void writeCategoryMultidimensionalSheet(
|
||||
Sheet sheet,
|
||||
String title,
|
||||
String dateRangeLabel,
|
||||
List<ShopOverviewStatisticsVO.CategorySummary> rows,
|
||||
ShopOverviewStatisticsVO.CategorySummary totalRow,
|
||||
BigDecimal taxRate,
|
||||
String dimensionColumnHeader) {
|
||||
Workbook wb = sheet.getWorkbook();
|
||||
CellStyle titleStyle = createTitleStyle(wb);
|
||||
CellStyle headerStyle = createHeaderStyle(wb);
|
||||
CellStyle dataStyle = createDataStyle(wb);
|
||||
CellStyle totalStyle = createBoldDataStyle(wb);
|
||||
|
||||
String taxHeader = taxRate.multiply(new BigDecimal("100")).setScale(0, RoundingMode.HALF_UP).toPlainString()
|
||||
+ "%税额";
|
||||
String[] headers = {
|
||||
dimensionColumnHeader, "成交金额", "净销售额", "成交单量", "净销售单量", "成交量", "净销量",
|
||||
"成交客单价", "净销售客单价",
|
||||
"商品成本", "运费", "其他成本", "订单成本", "退款金额", taxHeader, "推广费", "刷单费",
|
||||
"税前盈亏", "费比 %", "ROI", "税后盈亏"
|
||||
};
|
||||
|
||||
Row titleRow = sheet.createRow(0);
|
||||
Cell titleCell = titleRow.createCell(0);
|
||||
titleCell.setCellValue(title + " | " + dateRangeLabel);
|
||||
titleCell.setCellStyle(titleStyle);
|
||||
sheet.addMergedRegion(new CellRangeAddress(0, 0, 0, headers.length - 1));
|
||||
|
||||
Row headerRow = sheet.createRow(1);
|
||||
for (int i = 0; i < headers.length; i++) {
|
||||
Cell cell = headerRow.createCell(i);
|
||||
cell.setCellValue(headers[i]);
|
||||
cell.setCellStyle(headerStyle);
|
||||
}
|
||||
|
||||
int r = 2;
|
||||
for (ShopOverviewStatisticsVO.CategorySummary rowData : rows) {
|
||||
fillCategoryDataRow(sheet.createRow(r++), rowData, dataStyle, taxRate);
|
||||
}
|
||||
if (totalRow != null) {
|
||||
fillCategoryDataRow(sheet.createRow(r), totalRow, totalStyle, taxRate);
|
||||
}
|
||||
|
||||
sheet.setColumnWidth(0, 5200);
|
||||
for (int i = 1; i < headers.length; i++) {
|
||||
sheet.setColumnWidth(i, 3400);
|
||||
}
|
||||
}
|
||||
|
||||
private void fillCategoryDataRow(
|
||||
Row row, ShopOverviewStatisticsVO.CategorySummary d, CellStyle style, BigDecimal taxRate) {
|
||||
setCell(row, 0, d.getCategoryName() != null ? d.getCategoryName() : "", style);
|
||||
setCell(row, 1, bd2Money(d.getDealAmount()), style);
|
||||
setCell(row, 2, bd2Money(d.getSalesAmount()), style);
|
||||
Cell dealOc = row.createCell(3);
|
||||
dealOc.setCellStyle(style);
|
||||
dealOc.setCellValue(d.getDealOrderCount() != null ? d.getDealOrderCount() : 0);
|
||||
Cell salesOc = row.createCell(4);
|
||||
salesOc.setCellStyle(style);
|
||||
salesOc.setCellValue(d.getSalesOrderCount() != null ? d.getSalesOrderCount() : 0);
|
||||
Cell dealQty = row.createCell(5);
|
||||
dealQty.setCellStyle(style);
|
||||
dealQty.setCellValue(d.getDealQuantitySum() != null ? d.getDealQuantitySum() : 0);
|
||||
Cell salesQty = row.createCell(6);
|
||||
salesQty.setCellStyle(style);
|
||||
salesQty.setCellValue(d.getSalesQuantitySum() != null ? d.getSalesQuantitySum() : 0);
|
||||
setCell(row, 7, bd2Money(d.getDealAverageOrderValue()), style);
|
||||
setCell(row, 8, bd2Money(d.getSalesAverageOrderValue()), style);
|
||||
setCell(row, 9, bd2Money(d.getProductCost()), style);
|
||||
setCell(row, 10, bd2Money(d.getShippingCost()), style);
|
||||
setCell(row, 11, bd2Money(d.getOtherCost()), style);
|
||||
setCell(row, 12, bd2Money(d.getOrderCost()), style);
|
||||
BigDecimal salesTax = salesTaxOnNetForCategoryExport(d.getSalesAmount(), taxRate);
|
||||
BigDecimal profitAfterTax = (d.getTotalProfitBeforeTax() != null ? d.getTotalProfitBeforeTax() : BigDecimal.ZERO)
|
||||
.subtract(salesTax)
|
||||
.setScale(2, RoundingMode.HALF_UP);
|
||||
setCell(row, 13, bd2Money(d.getRefundAmount()), style);
|
||||
setCell(row, 14, bd2Money(salesTax), style);
|
||||
setCell(row, 15, bd2Money(d.getTotalPromotionFee()), style);
|
||||
setCell(row, 16, bd2Money(d.getBrushFee()), style);
|
||||
setCell(row, 17, bd2Money(d.getTotalProfitBeforeTax()), style);
|
||||
setCell(row, 18, bd2FeeRatioPercent(d.getFeeRatio()), style);
|
||||
setCell(row, 19, bd2Roi(d.getRoi()), style);
|
||||
setCell(row, 20, bd2Money(profitAfterTax), style);
|
||||
}
|
||||
|
||||
private static double bd2Money(BigDecimal v) {
|
||||
if (v == null) {
|
||||
return 0.0;
|
||||
}
|
||||
return v.setScale(2, RoundingMode.HALF_UP).doubleValue();
|
||||
}
|
||||
|
||||
private static double bd2Roi(BigDecimal v) {
|
||||
if (v == null) {
|
||||
return 0.0;
|
||||
}
|
||||
return v.setScale(4, RoundingMode.HALF_UP).doubleValue();
|
||||
}
|
||||
|
||||
/** 费比小数(如 0.052)转为与前端一致的百分比数值(5.2) */
|
||||
private static double bd2FeeRatioPercent(BigDecimal ratio) {
|
||||
if (ratio == null) {
|
||||
return 0.0;
|
||||
}
|
||||
return ratio.multiply(new BigDecimal("100")).setScale(1, RoundingMode.HALF_UP).doubleValue();
|
||||
}
|
||||
|
||||
private CellStyle createTitleStyle(Workbook workbook) {
|
||||
CellStyle style = workbook.createCellStyle();
|
||||
Font font = workbook.createFont();
|
||||
font.setBold(true);
|
||||
font.setFontHeightInPoints((short) 14);
|
||||
style.setFont(font);
|
||||
style.setAlignment(HorizontalAlignment.CENTER);
|
||||
style.setVerticalAlignment(VerticalAlignment.CENTER);
|
||||
return style;
|
||||
}
|
||||
|
||||
private CellStyle createHeaderStyle(Workbook workbook) {
|
||||
CellStyle style = workbook.createCellStyle();
|
||||
Font font = workbook.createFont();
|
||||
font.setBold(true);
|
||||
style.setFont(font);
|
||||
style.setFillForegroundColor(IndexedColors.GREY_25_PERCENT.getIndex());
|
||||
style.setFillPattern(FillPatternType.SOLID_FOREGROUND);
|
||||
style.setBorderBottom(BorderStyle.THIN);
|
||||
style.setBorderTop(BorderStyle.THIN);
|
||||
style.setBorderLeft(BorderStyle.THIN);
|
||||
style.setBorderRight(BorderStyle.THIN);
|
||||
style.setAlignment(HorizontalAlignment.CENTER);
|
||||
style.setVerticalAlignment(VerticalAlignment.CENTER);
|
||||
return style;
|
||||
}
|
||||
|
||||
private CellStyle createDataStyle(Workbook workbook) {
|
||||
CellStyle style = workbook.createCellStyle();
|
||||
style.setBorderBottom(BorderStyle.THIN);
|
||||
style.setBorderTop(BorderStyle.THIN);
|
||||
style.setBorderLeft(BorderStyle.THIN);
|
||||
style.setBorderRight(BorderStyle.THIN);
|
||||
style.setAlignment(HorizontalAlignment.CENTER);
|
||||
style.setVerticalAlignment(VerticalAlignment.CENTER);
|
||||
DataFormat format = workbook.createDataFormat();
|
||||
style.setDataFormat(format.getFormat("#,##0.00"));
|
||||
return style;
|
||||
}
|
||||
|
||||
private CellStyle createBoldDataStyle(Workbook workbook) {
|
||||
CellStyle style = createDataStyle(workbook);
|
||||
Font font = workbook.createFont();
|
||||
font.setBold(true);
|
||||
style.setFont(font);
|
||||
return style;
|
||||
}
|
||||
|
||||
private void setCell(Row row, int col, String value, CellStyle style) {
|
||||
Cell cell = row.createCell(col);
|
||||
cell.setCellValue(value != null ? value : "");
|
||||
cell.setCellStyle(style);
|
||||
}
|
||||
|
||||
private void setCell(Row row, int col, double value, CellStyle style) {
|
||||
Cell cell = row.createCell(col);
|
||||
cell.setCellValue(value);
|
||||
cell.setCellStyle(style);
|
||||
}
|
||||
}
|
||||
+983
@@ -0,0 +1,983 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.bi.overview.service.impl;
|
||||
|
||||
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
|
||||
import org.springframework.stereotype.Service;
|
||||
import top.xyquan.ecomdmbbackend.modules.bi.overview.model.agg.OverviewAggRows;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.platform.model.enums.PlatformCode;
|
||||
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.bi.overview.model.vo.CompanyOverviewVO;
|
||||
import top.xyquan.ecomdmbbackend.modules.bi.overview.service.CompanyOverviewService;
|
||||
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.product.sku.mapper.ProductSkuMapper;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.product.sku.model.po.ProductSkuPO;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.math.RoundingMode;
|
||||
import java.time.LocalDate;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Comparator;
|
||||
import java.util.HashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Objects;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
/**
|
||||
* 工作台汇总表构建(聚合行读路径)。
|
||||
*/
|
||||
@Service
|
||||
public class CompanyOverviewServiceImpl implements CompanyOverviewService {
|
||||
|
||||
private static final BigDecimal DEFAULT_TAX_RATE = new BigDecimal("0.04");
|
||||
private BigDecimal taxRate = DEFAULT_TAX_RATE;
|
||||
|
||||
private final ShopMonthlyTargetMapper shopMonthlyTargetMapper;
|
||||
private final ProductMapper productMapper;
|
||||
private final ProductSkuMapper productSkuMapper;
|
||||
private final CategoryService categoryService;
|
||||
|
||||
public CompanyOverviewServiceImpl(
|
||||
ShopMonthlyTargetMapper shopMonthlyTargetMapper,
|
||||
ProductMapper productMapper,
|
||||
ProductSkuMapper productSkuMapper,
|
||||
CategoryService categoryService) {
|
||||
this.shopMonthlyTargetMapper = shopMonthlyTargetMapper;
|
||||
this.productMapper = productMapper;
|
||||
this.productSkuMapper = productSkuMapper;
|
||||
this.categoryService = categoryService;
|
||||
}
|
||||
|
||||
private BigDecimal salesTaxOnSales(BigDecimal salesAmount) {
|
||||
BigDecimal sales = salesAmount != null ? salesAmount : BigDecimal.ZERO;
|
||||
if (sales.compareTo(BigDecimal.ZERO) < 0) {
|
||||
sales = BigDecimal.ZERO;
|
||||
}
|
||||
BigDecimal rate = taxRate != null ? taxRate : DEFAULT_TAX_RATE;
|
||||
return sales.multiply(rate).setScale(2, RoundingMode.HALF_UP);
|
||||
}
|
||||
|
||||
/** 计算ROI:净销售额 / 推广费用 */
|
||||
private BigDecimal calculateSalesROI(BigDecimal salesAmount, BigDecimal promotionFee) {
|
||||
if (promotionFee == null || promotionFee.compareTo(BigDecimal.ZERO) <= 0) {
|
||||
return BigDecimal.ZERO;
|
||||
}
|
||||
return salesAmount.divide(promotionFee, 4, RoundingMode.HALF_UP);
|
||||
}
|
||||
|
||||
/** 计算店铺汇总的合计行 */
|
||||
private CompanyOverviewVO.ShopSummary computeShopTotal(List<CompanyOverviewVO.ShopSummary> shops) {
|
||||
BigDecimal totalSales = BigDecimal.ZERO;
|
||||
int totalSalesOrders = 0;
|
||||
int totalDealOrders = 0;
|
||||
int totalDealQuantity = 0;
|
||||
int totalSalesQuantity = 0;
|
||||
BigDecimal totalTargetAmount = BigDecimal.ZERO;
|
||||
int totalTargetOrders = 0;
|
||||
BigDecimal totalProductCost = BigDecimal.ZERO;
|
||||
BigDecimal totalShippingCost = BigDecimal.ZERO;
|
||||
BigDecimal totalOtherCost = BigDecimal.ZERO;
|
||||
BigDecimal totalRefund = BigDecimal.ZERO;
|
||||
BigDecimal totalPromoFee = BigDecimal.ZERO;
|
||||
BigDecimal totalBrushFee = BigDecimal.ZERO;
|
||||
BigDecimal totalDealAmount = BigDecimal.ZERO;
|
||||
BigDecimal totalGrossProfit = BigDecimal.ZERO;
|
||||
|
||||
for (CompanyOverviewVO.ShopSummary s : shops) {
|
||||
totalSales = totalSales.add(s.getSalesAmount() != null ? s.getSalesAmount() : BigDecimal.ZERO);
|
||||
totalDealAmount = totalDealAmount.add(s.getDealAmount() != null ? s.getDealAmount() : BigDecimal.ZERO);
|
||||
totalGrossProfit = totalGrossProfit.add(s.getGrossProfit() != null ? s.getGrossProfit() : BigDecimal.ZERO);
|
||||
totalSalesOrders += s.getSalesOrderCount() != null ? s.getSalesOrderCount() : 0;
|
||||
totalDealOrders += s.getDealOrderCount() != null ? s.getDealOrderCount() : 0;
|
||||
totalDealQuantity += s.getDealQuantitySum() != null ? s.getDealQuantitySum() : 0;
|
||||
totalSalesQuantity += s.getSalesQuantitySum() != null ? s.getSalesQuantitySum() : 0;
|
||||
totalTargetAmount = totalTargetAmount.add(s.getTargetAmount() != null ? s.getTargetAmount() : BigDecimal.ZERO);
|
||||
totalTargetOrders += s.getTargetOrderCount() != null ? s.getTargetOrderCount() : 0;
|
||||
totalProductCost = totalProductCost.add(s.getProductCost() != null ? s.getProductCost() : BigDecimal.ZERO);
|
||||
totalShippingCost = totalShippingCost.add(s.getShippingCost() != null ? s.getShippingCost() : BigDecimal.ZERO);
|
||||
totalOtherCost = totalOtherCost.add(s.getOtherCost() != null ? s.getOtherCost() : BigDecimal.ZERO);
|
||||
totalRefund = totalRefund.add(s.getRefundAmount() != null ? s.getRefundAmount() : BigDecimal.ZERO);
|
||||
totalPromoFee = totalPromoFee.add(s.getTotalPromotionFee() != null ? s.getTotalPromotionFee() : BigDecimal.ZERO);
|
||||
totalBrushFee = totalBrushFee.add(s.getBrushFee() != null ? s.getBrushFee() : BigDecimal.ZERO);
|
||||
}
|
||||
|
||||
BigDecimal salesAvgOrderValue = totalSalesOrders > 0
|
||||
? totalSales.divide(new BigDecimal(totalSalesOrders), 2, RoundingMode.HALF_UP)
|
||||
: BigDecimal.ZERO;
|
||||
BigDecimal dealAvgOrderValue = totalDealOrders > 0
|
||||
? totalDealAmount.divide(new BigDecimal(totalDealOrders), 2, RoundingMode.HALF_UP)
|
||||
: BigDecimal.ZERO;
|
||||
BigDecimal totalCost = totalProductCost.add(totalShippingCost).add(totalOtherCost);
|
||||
BigDecimal profitBeforeTax = totalSales.subtract(totalCost)
|
||||
.subtract(totalPromoFee).subtract(totalBrushFee);
|
||||
BigDecimal salesTax = salesTaxOnSales(totalSales);
|
||||
BigDecimal profitAfterTax = profitBeforeTax.subtract(salesTax);
|
||||
BigDecimal roi = totalPromoFee.compareTo(BigDecimal.ZERO) > 0
|
||||
? totalSales.divide(totalPromoFee, 4, RoundingMode.HALF_UP)
|
||||
: BigDecimal.ZERO;
|
||||
BigDecimal feeRatio = totalSales.compareTo(BigDecimal.ZERO) > 0
|
||||
? totalPromoFee.add(totalBrushFee).divide(totalSales, 4, RoundingMode.HALF_UP)
|
||||
: BigDecimal.ZERO;
|
||||
BigDecimal salesAchievementRate = totalTargetAmount.compareTo(BigDecimal.ZERO) > 0
|
||||
? totalSales.divide(totalTargetAmount, 4, RoundingMode.HALF_UP).multiply(new BigDecimal("100"))
|
||||
: totalSales.compareTo(BigDecimal.ZERO) > 0 ? new BigDecimal("100") : BigDecimal.ZERO;
|
||||
BigDecimal orderAchievementRate = totalTargetOrders > 0
|
||||
? new BigDecimal(totalSalesOrders).divide(new BigDecimal(totalTargetOrders), 4, RoundingMode.HALF_UP)
|
||||
.multiply(new BigDecimal("100"))
|
||||
: totalSalesOrders > 0 ? new BigDecimal("100") : BigDecimal.ZERO;
|
||||
|
||||
CompanyOverviewVO.ShopSummary total = new CompanyOverviewVO.ShopSummary();
|
||||
total.setShopId(0L);
|
||||
total.setShopName("合计");
|
||||
total.setSalesAmount(totalSales);
|
||||
total.setDealAmount(totalDealAmount);
|
||||
total.setGrossProfit(totalGrossProfit.setScale(2, RoundingMode.HALF_UP));
|
||||
total.setSalesOrderCount(totalSalesOrders);
|
||||
total.setDealOrderCount(totalDealOrders);
|
||||
total.setDealQuantitySum(totalDealQuantity);
|
||||
total.setSalesQuantitySum(totalSalesQuantity);
|
||||
total.setSalesAverageOrderValue(salesAvgOrderValue);
|
||||
total.setDealAverageOrderValue(dealAvgOrderValue);
|
||||
total.setTargetAmount(totalTargetAmount);
|
||||
total.setTargetOrderCount(totalTargetOrders);
|
||||
total.setSalesAmountAchievementRate(salesAchievementRate);
|
||||
total.setOrderCountAchievementRate(orderAchievementRate);
|
||||
total.setProductCost(totalProductCost);
|
||||
total.setShippingCost(totalShippingCost);
|
||||
total.setOtherCost(totalOtherCost);
|
||||
total.setOrderCost(totalCost);
|
||||
total.setRefundAmount(totalRefund);
|
||||
total.setTotalPromotionFee(totalPromoFee);
|
||||
total.setBrushFee(totalBrushFee);
|
||||
total.setFeeRatio(feeRatio);
|
||||
total.setTotalProfitBeforeTax(profitBeforeTax);
|
||||
total.setSalesTaxAmount(salesTax);
|
||||
total.setRoi(roi);
|
||||
total.setProfitAfterTax(profitAfterTax.setScale(2, RoundingMode.HALF_UP));
|
||||
return total;
|
||||
}
|
||||
|
||||
/** 计算品类汇总的合计行 */
|
||||
private CompanyOverviewVO.CategorySummary computeCategoryTotal(List<CompanyOverviewVO.CategorySummary> categories) {
|
||||
BigDecimal totalSales = BigDecimal.ZERO;
|
||||
int totalSalesOrders = 0;
|
||||
int totalDealOrders = 0;
|
||||
int totalDealQuantity = 0;
|
||||
int totalSalesQuantity = 0;
|
||||
BigDecimal totalProductCost = BigDecimal.ZERO;
|
||||
BigDecimal totalShippingCost = BigDecimal.ZERO;
|
||||
BigDecimal totalOtherCost = BigDecimal.ZERO;
|
||||
BigDecimal totalRefund = BigDecimal.ZERO;
|
||||
BigDecimal totalPromoFee = BigDecimal.ZERO;
|
||||
BigDecimal totalBrushFee = BigDecimal.ZERO;
|
||||
BigDecimal totalDealAmount = BigDecimal.ZERO;
|
||||
BigDecimal totalGrossProfit = BigDecimal.ZERO;
|
||||
|
||||
for (CompanyOverviewVO.CategorySummary c : categories) {
|
||||
totalSales = totalSales.add(c.getSalesAmount() != null ? c.getSalesAmount() : BigDecimal.ZERO);
|
||||
totalDealAmount = totalDealAmount.add(c.getDealAmount() != null ? c.getDealAmount() : BigDecimal.ZERO);
|
||||
totalGrossProfit = totalGrossProfit.add(c.getGrossProfit() != null ? c.getGrossProfit() : BigDecimal.ZERO);
|
||||
totalSalesOrders += c.getSalesOrderCount() != null ? c.getSalesOrderCount() : 0;
|
||||
totalDealOrders += c.getDealOrderCount() != null ? c.getDealOrderCount() : 0;
|
||||
totalDealQuantity += c.getDealQuantitySum() != null ? c.getDealQuantitySum() : 0;
|
||||
totalSalesQuantity += c.getSalesQuantitySum() != null ? c.getSalesQuantitySum() : 0;
|
||||
totalProductCost = totalProductCost.add(c.getProductCost() != null ? c.getProductCost() : BigDecimal.ZERO);
|
||||
totalShippingCost = totalShippingCost.add(c.getShippingCost() != null ? c.getShippingCost() : BigDecimal.ZERO);
|
||||
totalOtherCost = totalOtherCost.add(c.getOtherCost() != null ? c.getOtherCost() : BigDecimal.ZERO);
|
||||
totalRefund = totalRefund.add(c.getRefundAmount() != null ? c.getRefundAmount() : BigDecimal.ZERO);
|
||||
totalPromoFee = totalPromoFee.add(c.getTotalPromotionFee() != null ? c.getTotalPromotionFee() : BigDecimal.ZERO);
|
||||
totalBrushFee = totalBrushFee.add(c.getBrushFee() != null ? c.getBrushFee() : BigDecimal.ZERO);
|
||||
}
|
||||
|
||||
BigDecimal salesAvgOrderValue = totalSalesOrders > 0
|
||||
? totalSales.divide(new BigDecimal(totalSalesOrders), 2, RoundingMode.HALF_UP)
|
||||
: BigDecimal.ZERO;
|
||||
BigDecimal dealAvgOrderValue = totalDealOrders > 0
|
||||
? totalDealAmount.divide(new BigDecimal(totalDealOrders), 2, RoundingMode.HALF_UP)
|
||||
: BigDecimal.ZERO;
|
||||
BigDecimal totalCost = totalProductCost.add(totalShippingCost).add(totalOtherCost);
|
||||
BigDecimal profitBeforeTax = totalSales.subtract(totalCost)
|
||||
.subtract(totalPromoFee).subtract(totalBrushFee);
|
||||
BigDecimal salesTax = salesTaxOnSales(totalSales);
|
||||
BigDecimal profitAfterTax = profitBeforeTax.subtract(salesTax);
|
||||
BigDecimal roi = totalPromoFee.compareTo(BigDecimal.ZERO) > 0
|
||||
? totalSales.divide(totalPromoFee, 4, RoundingMode.HALF_UP)
|
||||
: BigDecimal.ZERO;
|
||||
BigDecimal feeRatio = totalSales.compareTo(BigDecimal.ZERO) > 0
|
||||
? totalPromoFee.add(totalBrushFee).divide(totalSales, 4, RoundingMode.HALF_UP)
|
||||
: BigDecimal.ZERO;
|
||||
|
||||
CompanyOverviewVO.CategorySummary total = new CompanyOverviewVO.CategorySummary();
|
||||
total.setCategoryId(0L);
|
||||
total.setCategoryName("合计");
|
||||
total.setSalesAmount(totalSales);
|
||||
total.setDealAmount(totalDealAmount);
|
||||
total.setGrossProfit(totalGrossProfit.setScale(2, RoundingMode.HALF_UP));
|
||||
total.setSalesOrderCount(totalSalesOrders);
|
||||
total.setDealOrderCount(totalDealOrders);
|
||||
total.setDealQuantitySum(totalDealQuantity);
|
||||
total.setSalesQuantitySum(totalSalesQuantity);
|
||||
total.setSalesAverageOrderValue(salesAvgOrderValue);
|
||||
total.setDealAverageOrderValue(dealAvgOrderValue);
|
||||
total.setProductCost(totalProductCost);
|
||||
total.setShippingCost(totalShippingCost);
|
||||
total.setOtherCost(totalOtherCost);
|
||||
total.setOrderCost(totalCost);
|
||||
total.setRefundAmount(totalRefund);
|
||||
total.setTotalPromotionFee(totalPromoFee);
|
||||
total.setBrushFee(totalBrushFee);
|
||||
total.setFeeRatio(feeRatio);
|
||||
total.setTotalProfitBeforeTax(profitBeforeTax);
|
||||
total.setSalesTaxAmount(salesTax);
|
||||
total.setRoi(roi);
|
||||
total.setProfitAfterTax(profitAfterTax.setScale(2, RoundingMode.HALF_UP));
|
||||
return total;
|
||||
}
|
||||
|
||||
/** 计算平台汇总的合计行 */
|
||||
private CompanyOverviewVO.PlatformSummary computePlatformTotal(List<CompanyOverviewVO.PlatformSummary> platforms) {
|
||||
BigDecimal totalSalesAmount = BigDecimal.ZERO;
|
||||
int totalSalesOrders = 0;
|
||||
int totalDealOrders = 0;
|
||||
int totalDealQuantity = 0;
|
||||
int totalSalesQuantity = 0;
|
||||
BigDecimal totalTargetAmount = BigDecimal.ZERO;
|
||||
int totalTargetOrderCount = 0;
|
||||
BigDecimal totalProductCost = BigDecimal.ZERO;
|
||||
BigDecimal totalShippingCost = BigDecimal.ZERO;
|
||||
BigDecimal totalOtherCost = BigDecimal.ZERO;
|
||||
BigDecimal totalRefundAmount = BigDecimal.ZERO;
|
||||
BigDecimal totalPromotionFee = BigDecimal.ZERO;
|
||||
BigDecimal totalBrushFee = BigDecimal.ZERO;
|
||||
BigDecimal totalDealAmount = BigDecimal.ZERO;
|
||||
BigDecimal totalGrossProfit = BigDecimal.ZERO;
|
||||
|
||||
for (CompanyOverviewVO.PlatformSummary p : platforms) {
|
||||
totalSalesAmount = totalSalesAmount.add(p.getSalesAmount() != null ? p.getSalesAmount() : BigDecimal.ZERO);
|
||||
totalDealAmount = totalDealAmount.add(p.getDealAmount() != null ? p.getDealAmount() : BigDecimal.ZERO);
|
||||
totalGrossProfit = totalGrossProfit.add(p.getGrossProfit() != null ? p.getGrossProfit() : BigDecimal.ZERO);
|
||||
totalSalesOrders += p.getSalesOrderCount() != null ? p.getSalesOrderCount() : 0;
|
||||
totalDealOrders += p.getDealOrderCount() != null ? p.getDealOrderCount() : 0;
|
||||
totalDealQuantity += p.getDealQuantitySum() != null ? p.getDealQuantitySum() : 0;
|
||||
totalSalesQuantity += p.getSalesQuantitySum() != null ? p.getSalesQuantitySum() : 0;
|
||||
totalTargetAmount = totalTargetAmount.add(p.getTargetAmount() != null ? p.getTargetAmount() : BigDecimal.ZERO);
|
||||
totalTargetOrderCount += p.getTargetOrderCount() != null ? p.getTargetOrderCount() : 0;
|
||||
totalProductCost = totalProductCost.add(p.getProductCost() != null ? p.getProductCost() : BigDecimal.ZERO);
|
||||
totalShippingCost = totalShippingCost.add(p.getShippingCost() != null ? p.getShippingCost() : BigDecimal.ZERO);
|
||||
totalOtherCost = totalOtherCost.add(p.getOtherCost() != null ? p.getOtherCost() : BigDecimal.ZERO);
|
||||
totalRefundAmount = totalRefundAmount.add(p.getRefundAmount() != null ? p.getRefundAmount() : BigDecimal.ZERO);
|
||||
totalPromotionFee = totalPromotionFee.add(p.getTotalPromotionFee() != null ? p.getTotalPromotionFee() : BigDecimal.ZERO);
|
||||
totalBrushFee = totalBrushFee.add(p.getBrushFee() != null ? p.getBrushFee() : BigDecimal.ZERO);
|
||||
}
|
||||
|
||||
BigDecimal salesAvgOrderValue = totalSalesOrders > 0
|
||||
? totalSalesAmount.divide(new BigDecimal(totalSalesOrders), 2, RoundingMode.HALF_UP)
|
||||
: BigDecimal.ZERO;
|
||||
BigDecimal dealAvgOrderValue = totalDealOrders > 0
|
||||
? totalDealAmount.divide(new BigDecimal(totalDealOrders), 2, RoundingMode.HALF_UP)
|
||||
: BigDecimal.ZERO;
|
||||
BigDecimal totalCost = totalProductCost.add(totalShippingCost).add(totalOtherCost);
|
||||
BigDecimal profitBeforeTax = totalSalesAmount.subtract(totalCost)
|
||||
.subtract(totalPromotionFee).subtract(totalBrushFee);
|
||||
BigDecimal salesTax = salesTaxOnSales(totalSalesAmount);
|
||||
BigDecimal profitAfterTax = profitBeforeTax.subtract(salesTax);
|
||||
BigDecimal roi = totalPromotionFee.compareTo(BigDecimal.ZERO) > 0
|
||||
? totalSalesAmount.divide(totalPromotionFee, 4, RoundingMode.HALF_UP)
|
||||
: BigDecimal.ZERO;
|
||||
BigDecimal feeRatio = totalSalesAmount.compareTo(BigDecimal.ZERO) > 0
|
||||
? totalPromotionFee.add(totalBrushFee).divide(totalSalesAmount, 4, RoundingMode.HALF_UP)
|
||||
: BigDecimal.ZERO;
|
||||
BigDecimal salesAchievementRate = totalTargetAmount.compareTo(BigDecimal.ZERO) > 0
|
||||
? totalSalesAmount.divide(totalTargetAmount, 4, RoundingMode.HALF_UP).multiply(new BigDecimal("100"))
|
||||
: totalSalesAmount.compareTo(BigDecimal.ZERO) > 0 ? new BigDecimal("100") : BigDecimal.ZERO;
|
||||
BigDecimal orderAchievementRate = totalTargetOrderCount > 0
|
||||
? new BigDecimal(totalSalesOrders).divide(new BigDecimal(totalTargetOrderCount), 4, RoundingMode.HALF_UP)
|
||||
.multiply(new BigDecimal("100"))
|
||||
: totalSalesOrders > 0 ? new BigDecimal("100") : BigDecimal.ZERO;
|
||||
|
||||
CompanyOverviewVO.PlatformSummary total = new CompanyOverviewVO.PlatformSummary();
|
||||
total.setPlatformCode(null);
|
||||
total.setPlatformName("合计");
|
||||
total.setSalesAmount(totalSalesAmount);
|
||||
total.setDealAmount(totalDealAmount);
|
||||
total.setGrossProfit(totalGrossProfit.setScale(2, RoundingMode.HALF_UP));
|
||||
total.setSalesOrderCount(totalSalesOrders);
|
||||
total.setDealOrderCount(totalDealOrders);
|
||||
total.setDealQuantitySum(totalDealQuantity);
|
||||
total.setSalesQuantitySum(totalSalesQuantity);
|
||||
total.setSalesAverageOrderValue(salesAvgOrderValue);
|
||||
total.setDealAverageOrderValue(dealAvgOrderValue);
|
||||
total.setTargetAmount(totalTargetAmount);
|
||||
total.setTargetOrderCount(totalTargetOrderCount);
|
||||
total.setSalesAmountAchievementRate(salesAchievementRate);
|
||||
total.setOrderCountAchievementRate(orderAchievementRate);
|
||||
total.setProductCost(totalProductCost);
|
||||
total.setShippingCost(totalShippingCost);
|
||||
total.setOtherCost(totalOtherCost);
|
||||
total.setOrderCost(totalCost);
|
||||
total.setRefundAmount(totalRefundAmount);
|
||||
total.setTotalPromotionFee(totalPromotionFee);
|
||||
total.setBrushFee(totalBrushFee);
|
||||
total.setFeeRatio(feeRatio);
|
||||
total.setTotalProfitBeforeTax(profitBeforeTax);
|
||||
total.setSalesTaxAmount(salesTax);
|
||||
total.setRoi(roi);
|
||||
total.setProfitAfterTax(profitAfterTax.setScale(2, RoundingMode.HALF_UP));
|
||||
return total;
|
||||
}
|
||||
|
||||
@Override
|
||||
public CompanyOverviewVO.WorkbenchTableBundle buildWorkbenchSummaryTablesFromAgg(
|
||||
BigDecimal taxRate,
|
||||
Long companyId,
|
||||
List<ShopPO> shops,
|
||||
List<OverviewAggRows.ShopProductRow> orderRows,
|
||||
List<OverviewAggRows.PromotionRow> promotionRows,
|
||||
List<OverviewAggRows.BrushRow> brushRows,
|
||||
LocalDate startDate,
|
||||
LocalDate endDate,
|
||||
List<OverviewAggRows.ShopSkuRow> skuRows) {
|
||||
synchronized (this) {
|
||||
BigDecimal saved = this.taxRate;
|
||||
try {
|
||||
this.taxRate = taxRate != null ? taxRate : DEFAULT_TAX_RATE;
|
||||
return buildWorkbenchTablesFromAggInternal(
|
||||
companyId, shops, orderRows, promotionRows, brushRows,
|
||||
startDate, endDate, skuRows != null ? skuRows : List.of());
|
||||
} finally {
|
||||
this.taxRate = saved;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/** 聚合行 → 五表(推广/刷单分摊规则与明细版一致) */
|
||||
private CompanyOverviewVO.WorkbenchTableBundle buildWorkbenchTablesFromAggInternal(
|
||||
Long companyId,
|
||||
List<ShopPO> shops,
|
||||
List<OverviewAggRows.ShopProductRow> orderRows,
|
||||
List<OverviewAggRows.PromotionRow> promotionRows,
|
||||
List<OverviewAggRows.BrushRow> brushRows,
|
||||
LocalDate startDate,
|
||||
LocalDate endDate,
|
||||
List<OverviewAggRows.ShopSkuRow> skuRows) {
|
||||
|
||||
Map<Long, AggMetrics> byShop = new HashMap<>();
|
||||
Map<Long, AggMetrics> byCategory = new HashMap<>();
|
||||
Map<Long, AggMetrics> byProduct = new HashMap<>();
|
||||
Map<Long, Map<Long, BigDecimal>> categorySalesByShop = new HashMap<>();
|
||||
Map<Long, Map<Long, BigDecimal>> productSalesByShop = new HashMap<>();
|
||||
Map<Long, Long> productCategoryMap = new HashMap<>();
|
||||
|
||||
for (OverviewAggRows.ShopProductRow row : orderRows) {
|
||||
long shopId = row.getShopId() != null ? row.getShopId() : 0L;
|
||||
long productId = row.getProductId() != null && row.getProductId() > 0 ? row.getProductId() : -1L;
|
||||
long categoryKey = productId <= 0 ? -1L
|
||||
: (row.getCategoryId() == null || row.getCategoryId() == 0 ? 0L : row.getCategoryId());
|
||||
if (productId > 0) {
|
||||
productCategoryMap.put(productId, categoryKey <= 0 ? null : categoryKey);
|
||||
}
|
||||
mergeAgg(byShop, shopId, row);
|
||||
mergeAgg(byCategory, categoryKey, row);
|
||||
mergeAgg(byProduct, productId, row);
|
||||
BigDecimal sales = nz(row.getSalesAmount());
|
||||
categorySalesByShop.computeIfAbsent(categoryKey, k -> new HashMap<>()).merge(shopId, sales, BigDecimal::add);
|
||||
productSalesByShop.computeIfAbsent(productId, k -> new HashMap<>()).merge(shopId, sales, BigDecimal::add);
|
||||
}
|
||||
|
||||
Map<Long, BigDecimal> promoByShop = new HashMap<>();
|
||||
Map<Long, BigDecimal> directPromoByProduct = new HashMap<>();
|
||||
Map<Long, BigDecimal> directPromoByCategory = new HashMap<>();
|
||||
BigDecimal ratioPool = BigDecimal.ZERO;
|
||||
for (OverviewAggRows.PromotionRow fee : promotionRows) {
|
||||
BigDecimal amt = nz(fee.getFeeAmount());
|
||||
promoByShop.merge(fee.getShopId(), amt, BigDecimal::add);
|
||||
if (fee.getProductId() != null) {
|
||||
directPromoByProduct.merge(fee.getProductId(), amt, BigDecimal::add);
|
||||
} else if (fee.getCategoryId() != null) {
|
||||
directPromoByCategory.merge(fee.getCategoryId(), amt, BigDecimal::add);
|
||||
} else {
|
||||
ratioPool = ratioPool.add(amt);
|
||||
}
|
||||
}
|
||||
Map<Long, BigDecimal> brushByShop = new HashMap<>();
|
||||
for (OverviewAggRows.BrushRow b : brushRows) {
|
||||
brushByShop.merge(b.getShopId(), nz(b.getBrushAmount()), BigDecimal::add);
|
||||
}
|
||||
BigDecimal totalSalesPool = orderRows.stream().map(r -> nz(r.getSalesAmount())).reduce(BigDecimal.ZERO, BigDecimal::add);
|
||||
|
||||
Map<Long, List<ShopMonthlyTargetPO>> targetsByShop = loadTargetsByShop(companyId, startDate, endDate);
|
||||
|
||||
CompanyOverviewVO.WorkbenchTableBundle bundle = new CompanyOverviewVO.WorkbenchTableBundle();
|
||||
bundle.setShopTable(buildShopOverviewFromAgg(shops, byShop, promoByShop, brushByShop, targetsByShop));
|
||||
bundle.setPlatformTable(buildPlatformOverviewFromAgg(shops, byShop, promoByShop, brushByShop, targetsByShop));
|
||||
bundle.setCategoryTable(buildCategoryOverviewFromAgg(byCategory, categorySalesByShop, brushByShop,
|
||||
directPromoByProduct, directPromoByCategory, ratioPool, totalSalesPool, productCategoryMap, companyId));
|
||||
bundle.setProductTable(buildProductOverviewFromAgg(byProduct, productSalesByShop, brushByShop,
|
||||
directPromoByProduct, directPromoByCategory, ratioPool, totalSalesPool, productCategoryMap, companyId));
|
||||
bundle.setSkuTable(buildSkuOverviewFromAgg(skuRows, bundle.getProductTable(), brushByShop));
|
||||
return bundle;
|
||||
}
|
||||
|
||||
/**
|
||||
* SKU 汇总:订单指标来自 SKU 日汇聚;推广按父商品推广×SKU 净销占比分摊;刷单按店净销占比。
|
||||
*/
|
||||
private CompanyOverviewVO.CategoryOverview buildSkuOverviewFromAgg(
|
||||
List<OverviewAggRows.ShopSkuRow> skuRows,
|
||||
CompanyOverviewVO.CategoryOverview productTable,
|
||||
Map<Long, BigDecimal> brushByShop) {
|
||||
if (skuRows == null || skuRows.isEmpty()) {
|
||||
CompanyOverviewVO.CategoryOverview empty = new CompanyOverviewVO.CategoryOverview();
|
||||
empty.setCategories(List.of());
|
||||
empty.setTotal(computeCategoryTotal(List.of()));
|
||||
return empty;
|
||||
}
|
||||
|
||||
Map<Long, BigDecimal> productPromoById = new HashMap<>();
|
||||
if (productTable != null && productTable.getCategories() != null) {
|
||||
for (CompanyOverviewVO.CategorySummary p : productTable.getCategories()) {
|
||||
if (p.getCategoryId() == null || p.getCategoryId() <= 0) {
|
||||
continue;
|
||||
}
|
||||
productPromoById.put(p.getCategoryId(), nz(p.getTotalPromotionFee()));
|
||||
}
|
||||
}
|
||||
|
||||
Map<Long, AggMetrics> bySku = new HashMap<>();
|
||||
Map<Long, Long> skuProductId = new HashMap<>();
|
||||
Map<Long, Map<Long, BigDecimal>> skuSalesByShop = new HashMap<>();
|
||||
for (OverviewAggRows.ShopSkuRow row : skuRows) {
|
||||
long skuId = row.getProductSkuId() != null ? row.getProductSkuId() : 0L;
|
||||
long shopId = row.getShopId() != null ? row.getShopId() : 0L;
|
||||
long productId = row.getProductId() != null && row.getProductId() > 0 ? row.getProductId() : 0L;
|
||||
bySku.merge(skuId, AggMetrics.from(row), AggMetrics::merge);
|
||||
if (productId > 0) {
|
||||
skuProductId.putIfAbsent(skuId, productId);
|
||||
} else if (!skuProductId.containsKey(skuId)) {
|
||||
skuProductId.put(skuId, 0L);
|
||||
}
|
||||
BigDecimal sales = nz(row.getSalesAmount());
|
||||
skuSalesByShop.computeIfAbsent(skuId, k -> new HashMap<>()).merge(shopId, sales, BigDecimal::add);
|
||||
}
|
||||
|
||||
// 同商品下 SKU 净销合计,用于推广二次分摊
|
||||
Map<Long, BigDecimal> salesByProductFromSku = new HashMap<>();
|
||||
for (Map.Entry<Long, AggMetrics> e : bySku.entrySet()) {
|
||||
Long pid = skuProductId.getOrDefault(e.getKey(), 0L);
|
||||
if (pid != null && pid > 0) {
|
||||
salesByProductFromSku.merge(pid, e.getValue().sales, BigDecimal::add);
|
||||
}
|
||||
}
|
||||
|
||||
Map<Long, SkuLabel> skuLabels = loadSkuLabelMap(bySku.keySet());
|
||||
Map<Long, String> productNames = loadProductNameMap(new java.util.HashSet<>(skuProductId.values()));
|
||||
List<CompanyOverviewVO.CategorySummary> list = new ArrayList<>();
|
||||
for (Map.Entry<Long, AggMetrics> e : bySku.entrySet()) {
|
||||
Long skuId = e.getKey();
|
||||
AggMetrics m = e.getValue();
|
||||
Long productId = skuProductId.getOrDefault(skuId, 0L);
|
||||
BigDecimal productPromo = productPromoById.getOrDefault(productId, BigDecimal.ZERO);
|
||||
BigDecimal productSkuSalesPool = salesByProductFromSku.getOrDefault(productId, BigDecimal.ZERO);
|
||||
BigDecimal promo = productSkuSalesPool.compareTo(BigDecimal.ZERO) > 0
|
||||
? productPromo.multiply(m.sales).divide(productSkuSalesPool, 4, RoundingMode.HALF_UP)
|
||||
: BigDecimal.ZERO;
|
||||
BigDecimal brush = allocBrushShare(skuSalesByShop.get(skuId), brushByShop);
|
||||
SkuLabel label = skuId != null && skuId > 0 ? skuLabels.get(skuId) : null;
|
||||
String skuName = skuId == null || skuId <= 0
|
||||
? "未绑定规格"
|
||||
: (label != null && label.name() != null && !label.name().isBlank()
|
||||
? label.name()
|
||||
: "规格" + skuId);
|
||||
String productName = productId != null && productId > 0
|
||||
? productNames.getOrDefault(productId, "商品" + productId)
|
||||
: null;
|
||||
String displayName = productName != null ? productName + "/" + skuName : skuName;
|
||||
CompanyOverviewVO.CategorySummary row = toCategorySummaryFromAgg(skuId, displayName, m, promo, brush);
|
||||
row.setProductName(productName);
|
||||
if (label != null && label.code() != null && !label.code().isBlank()) {
|
||||
row.setSkuCode(label.code());
|
||||
}
|
||||
list.add(row);
|
||||
}
|
||||
list.sort(Comparator.comparing(CompanyOverviewVO.CategorySummary::getSalesAmount,
|
||||
Comparator.nullsFirst(BigDecimal::compareTo)).reversed());
|
||||
CompanyOverviewVO.CategoryOverview o = new CompanyOverviewVO.CategoryOverview();
|
||||
o.setCategories(list);
|
||||
o.setTotal(computeCategoryTotal(list));
|
||||
return o;
|
||||
}
|
||||
|
||||
private CompanyOverviewVO.ShopOverview buildShopOverviewFromAgg(
|
||||
List<ShopPO> shops, Map<Long, AggMetrics> byShop, Map<Long, BigDecimal> promoByShop,
|
||||
Map<Long, BigDecimal> brushByShop, Map<Long, List<ShopMonthlyTargetPO>> targetsByShop) {
|
||||
List<CompanyOverviewVO.ShopSummary> list = new ArrayList<>();
|
||||
for (ShopPO shop : shops) {
|
||||
AggMetrics m = byShop.getOrDefault(shop.getId(), AggMetrics.EMPTY);
|
||||
list.add(toShopSummaryFromAgg(shop, m, promoByShop.getOrDefault(shop.getId(), BigDecimal.ZERO),
|
||||
brushByShop.getOrDefault(shop.getId(), BigDecimal.ZERO),
|
||||
targetsByShop.getOrDefault(shop.getId(), List.of())));
|
||||
}
|
||||
list.sort(Comparator.comparing(CompanyOverviewVO.ShopSummary::getSalesAmount,
|
||||
Comparator.nullsFirst(BigDecimal::compareTo)).reversed());
|
||||
CompanyOverviewVO.ShopOverview o = new CompanyOverviewVO.ShopOverview();
|
||||
o.setShops(list);
|
||||
o.setTotal(computeShopTotal(list));
|
||||
return o;
|
||||
}
|
||||
|
||||
private CompanyOverviewVO.PlatformOverview buildPlatformOverviewFromAgg(
|
||||
List<ShopPO> shops, Map<Long, AggMetrics> byShop, Map<Long, BigDecimal> promoByShop,
|
||||
Map<Long, BigDecimal> brushByShop, Map<Long, List<ShopMonthlyTargetPO>> targetsByShop) {
|
||||
Map<String, List<ShopPO>> byPlatform = shops.stream()
|
||||
.filter(s -> s.getPlatformCode() != null && !s.getPlatformCode().isBlank())
|
||||
.collect(Collectors.groupingBy(ShopPO::getPlatformCode));
|
||||
List<CompanyOverviewVO.PlatformSummary> list = new ArrayList<>();
|
||||
for (Map.Entry<String, List<ShopPO>> e : byPlatform.entrySet()) {
|
||||
list.add(rollupPlatformFromAgg(e.getKey(), PlatformCode.labelOf(e.getKey()),
|
||||
e.getValue(), byShop, promoByShop, brushByShop, targetsByShop));
|
||||
}
|
||||
list.sort(Comparator.comparing(CompanyOverviewVO.PlatformSummary::getSalesAmount,
|
||||
Comparator.nullsFirst(BigDecimal::compareTo)).reversed());
|
||||
CompanyOverviewVO.PlatformOverview o = new CompanyOverviewVO.PlatformOverview();
|
||||
o.setPlatforms(list);
|
||||
o.setTotal(computePlatformTotal(list));
|
||||
return o;
|
||||
}
|
||||
|
||||
private CompanyOverviewVO.CategoryOverview buildCategoryOverviewFromAgg(
|
||||
Map<Long, AggMetrics> byCategory, Map<Long, Map<Long, BigDecimal>> categorySalesByShop,
|
||||
Map<Long, BigDecimal> brushByShop, Map<Long, BigDecimal> directPromoByProduct,
|
||||
Map<Long, BigDecimal> directPromoByCategory, BigDecimal ratioPool, BigDecimal totalSalesPool,
|
||||
Map<Long, Long> productCategoryMap, Long companyId) {
|
||||
Map<Long, String> categoryNames = loadCategoryNameMap(companyId);
|
||||
Map<Long, BigDecimal> salesByCategory = byCategory.entrySet().stream()
|
||||
.collect(Collectors.toMap(Map.Entry::getKey, e -> e.getValue().sales));
|
||||
List<CompanyOverviewVO.CategorySummary> list = new ArrayList<>();
|
||||
for (Map.Entry<Long, AggMetrics> e : byCategory.entrySet()) {
|
||||
Long key = e.getKey();
|
||||
AggMetrics m = e.getValue();
|
||||
BigDecimal promo = resolveCategoryPromo(key, m.sales, salesByCategory, productCategoryMap,
|
||||
directPromoByProduct, directPromoByCategory, ratioPool, totalSalesPool);
|
||||
BigDecimal brush = allocBrushShare(categorySalesByShop.get(key), brushByShop);
|
||||
list.add(toCategorySummaryFromAgg(key, categoryAggName(key, categoryNames), m, promo, brush));
|
||||
}
|
||||
list.sort(Comparator.comparing(CompanyOverviewVO.CategorySummary::getSalesAmount,
|
||||
Comparator.nullsFirst(BigDecimal::compareTo)).reversed());
|
||||
CompanyOverviewVO.CategoryOverview o = new CompanyOverviewVO.CategoryOverview();
|
||||
o.setCategories(list);
|
||||
o.setTotal(computeCategoryTotal(list));
|
||||
return o;
|
||||
}
|
||||
|
||||
private CompanyOverviewVO.CategoryOverview buildProductOverviewFromAgg(
|
||||
Map<Long, AggMetrics> byProduct, Map<Long, Map<Long, BigDecimal>> productSalesByShop,
|
||||
Map<Long, BigDecimal> brushByShop, Map<Long, BigDecimal> directPromoByProduct,
|
||||
Map<Long, BigDecimal> directPromoByCategory, BigDecimal ratioPool, BigDecimal totalSalesPool,
|
||||
Map<Long, Long> productCategoryMap, Long companyId) {
|
||||
Map<Long, BigDecimal> salesByCategory = new HashMap<>();
|
||||
for (Map.Entry<Long, AggMetrics> e : byProduct.entrySet()) {
|
||||
if (e.getKey() > 0) {
|
||||
Long cid = productCategoryMap.get(e.getKey());
|
||||
if (cid != null && cid > 0) {
|
||||
salesByCategory.merge(cid, e.getValue().sales, BigDecimal::add);
|
||||
}
|
||||
}
|
||||
}
|
||||
Map<Long, String> productNames = loadProductNameMap(byProduct.keySet());
|
||||
List<CompanyOverviewVO.CategorySummary> list = new ArrayList<>();
|
||||
for (Map.Entry<Long, AggMetrics> e : byProduct.entrySet()) {
|
||||
Long pid = e.getKey();
|
||||
AggMetrics m = e.getValue();
|
||||
BigDecimal promo = resolveProductPromo(pid, m.sales, productCategoryMap, salesByCategory,
|
||||
directPromoByProduct, directPromoByCategory, ratioPool, totalSalesPool);
|
||||
BigDecimal brush = allocBrushShare(productSalesByShop.get(pid), brushByShop);
|
||||
String name = pid <= 0 ? "未匹配商品" : productNames.getOrDefault(pid, "商品" + pid);
|
||||
list.add(toCategorySummaryFromAgg(pid, name, m, promo, brush));
|
||||
}
|
||||
list.sort(Comparator.comparing(CompanyOverviewVO.CategorySummary::getSalesAmount,
|
||||
Comparator.nullsFirst(BigDecimal::compareTo)).reversed());
|
||||
CompanyOverviewVO.CategoryOverview o = new CompanyOverviewVO.CategoryOverview();
|
||||
o.setCategories(list);
|
||||
o.setTotal(computeCategoryTotal(list));
|
||||
return o;
|
||||
}
|
||||
|
||||
private CompanyOverviewVO.PlatformSummary rollupPlatformFromAgg(
|
||||
String platformCode, String platformName, List<ShopPO> platformShops,
|
||||
Map<Long, AggMetrics> byShop, Map<Long, BigDecimal> promoByShop, Map<Long, BigDecimal> brushByShop,
|
||||
Map<Long, List<ShopMonthlyTargetPO>> targetsByShop) {
|
||||
AggMetrics merged = AggMetrics.EMPTY;
|
||||
BigDecimal promo = BigDecimal.ZERO;
|
||||
BigDecimal brush = BigDecimal.ZERO;
|
||||
BigDecimal targetAmt = BigDecimal.ZERO;
|
||||
int targetOrders = 0;
|
||||
for (ShopPO shop : platformShops) {
|
||||
merged = merged.merge(byShop.getOrDefault(shop.getId(), AggMetrics.EMPTY));
|
||||
promo = promo.add(promoByShop.getOrDefault(shop.getId(), BigDecimal.ZERO));
|
||||
brush = brush.add(brushByShop.getOrDefault(shop.getId(), BigDecimal.ZERO));
|
||||
for (ShopMonthlyTargetPO t : targetsByShop.getOrDefault(shop.getId(), List.of())) {
|
||||
targetAmt = targetAmt.add(nz(t.getTargetAmount()));
|
||||
targetOrders += t.getTargetOrderCount() != null ? t.getTargetOrderCount() : 0;
|
||||
}
|
||||
}
|
||||
return toPlatformSummaryFromAgg(platformCode, platformName, merged, promo, brush, targetAmt, targetOrders);
|
||||
}
|
||||
|
||||
private CompanyOverviewVO.ShopSummary toShopSummaryFromAgg(
|
||||
ShopPO shop, AggMetrics m, BigDecimal promo, BigDecimal brush,
|
||||
List<ShopMonthlyTargetPO> targets) {
|
||||
BigDecimal targetAmt = targets.stream().map(t -> nz(t.getTargetAmount())).reduce(BigDecimal.ZERO, BigDecimal::add);
|
||||
int targetOrders = targets.stream().mapToInt(t -> t.getTargetOrderCount() != null ? t.getTargetOrderCount() : 0).sum();
|
||||
CompanyOverviewVO.ShopSummary s = new CompanyOverviewVO.ShopSummary();
|
||||
s.setShopId(shop.getId());
|
||||
s.setShopName(shop.getName());
|
||||
s.setPlatform(shop.getPlatformCode() != null ? PlatformCode.labelOf(shop.getPlatformCode()) : null);
|
||||
fillSummaryMetrics(s, m, promo, brush, targetAmt, targetOrders);
|
||||
return s;
|
||||
}
|
||||
|
||||
private CompanyOverviewVO.PlatformSummary toPlatformSummaryFromAgg(
|
||||
String platformCode, String name, AggMetrics m, BigDecimal promo, BigDecimal brush,
|
||||
BigDecimal targetAmt, int targetOrders) {
|
||||
CompanyOverviewVO.PlatformSummary s = new CompanyOverviewVO.PlatformSummary();
|
||||
s.setPlatformCode(platformCode != null && !platformCode.isBlank() ? platformCode : null);
|
||||
s.setPlatformName(name);
|
||||
fillPlatformLikeMetrics(s, m, promo, brush, targetAmt, targetOrders);
|
||||
return s;
|
||||
}
|
||||
|
||||
private CompanyOverviewVO.CategorySummary toCategorySummaryFromAgg(
|
||||
Long key, String name, AggMetrics m, BigDecimal promo, BigDecimal brush) {
|
||||
CompanyOverviewVO.CategorySummary s = new CompanyOverviewVO.CategorySummary();
|
||||
s.setCategoryId(key != null && key > 0 ? key : null);
|
||||
s.setCategoryName(name);
|
||||
fillCategoryLikeMetrics(s, m, promo, brush);
|
||||
return s;
|
||||
}
|
||||
|
||||
private void fillSummaryMetrics(CompanyOverviewVO.ShopSummary s, AggMetrics m, BigDecimal promo,
|
||||
BigDecimal brush, BigDecimal targetAmt, int targetOrders) {
|
||||
s.setSalesAmount(m.sales);
|
||||
s.setDealAmount(m.dealAmount);
|
||||
s.setSalesOrderCount(m.salesOrderCount);
|
||||
s.setDealOrderCount(m.dealOrderCount);
|
||||
s.setDealQuantitySum(m.dealQuantitySum);
|
||||
s.setSalesQuantitySum(m.salesQuantitySum);
|
||||
s.setSalesAverageOrderValue(aov(m.sales, m.salesOrderCount));
|
||||
s.setDealAverageOrderValue(aov(m.dealAmount, m.dealOrderCount));
|
||||
s.setProductCost(m.productCost);
|
||||
s.setShippingCost(m.freightCost);
|
||||
s.setOtherCost(m.otherCost);
|
||||
s.setOrderCost(m.orderCost());
|
||||
s.setRefundAmount(m.refund);
|
||||
s.setRefundOrderCount(m.refundOrderCount);
|
||||
s.setRefundQuantitySum(m.refundQuantitySum);
|
||||
s.setTotalPromotionFee(promo);
|
||||
s.setBrushFee(brush);
|
||||
s.setFeeRatio(safeDivide(promo, m.sales));
|
||||
s.setGrossProfit(m.grossProfit().setScale(2, RoundingMode.HALF_UP));
|
||||
BigDecimal pbt = m.grossProfit().subtract(promo).subtract(brush);
|
||||
s.setTotalProfitBeforeTax(pbt);
|
||||
s.setSalesTaxAmount(salesTaxOnSales(m.sales));
|
||||
s.setProfitAfterTax(pbt.subtract(s.getSalesTaxAmount()).setScale(2, RoundingMode.HALF_UP));
|
||||
s.setRoi(calculateSalesROI(m.sales, promo));
|
||||
s.setTargetAmount(targetAmt);
|
||||
s.setTargetOrderCount(targetOrders);
|
||||
s.setSalesAmountAchievementRate(achievementRate(m.sales, targetAmt));
|
||||
s.setOrderCountAchievementRate(achievementRate(BigDecimal.valueOf(m.salesOrderCount), BigDecimal.valueOf(targetOrders)));
|
||||
}
|
||||
|
||||
/** 品类/商品/平台汇总行:填充成交金额、毛利与净利字段 */
|
||||
private void fillCategoryLikeMetrics(CompanyOverviewVO.CategorySummary s, AggMetrics m,
|
||||
BigDecimal promo, BigDecimal brush) {
|
||||
s.setSalesAmount(m.sales);
|
||||
s.setDealAmount(m.dealAmount);
|
||||
s.setSalesOrderCount(m.salesOrderCount);
|
||||
s.setDealOrderCount(m.dealOrderCount);
|
||||
s.setDealQuantitySum(m.dealQuantitySum);
|
||||
s.setSalesQuantitySum(m.salesQuantitySum);
|
||||
s.setSalesAverageOrderValue(aov(m.sales, m.salesOrderCount));
|
||||
s.setDealAverageOrderValue(aov(m.dealAmount, m.dealOrderCount));
|
||||
s.setProductCost(m.productCost);
|
||||
s.setShippingCost(m.freightCost);
|
||||
s.setOtherCost(m.otherCost);
|
||||
s.setOrderCost(m.orderCost());
|
||||
s.setRefundAmount(m.refund);
|
||||
s.setRefundOrderCount(m.refundOrderCount);
|
||||
s.setRefundQuantitySum(m.refundQuantitySum);
|
||||
s.setTotalPromotionFee(promo);
|
||||
s.setBrushFee(brush);
|
||||
s.setFeeRatio(safeDivide(promo, m.sales));
|
||||
s.setGrossProfit(m.grossProfit().setScale(2, RoundingMode.HALF_UP));
|
||||
BigDecimal pbt = m.grossProfit().subtract(promo).subtract(brush);
|
||||
s.setTotalProfitBeforeTax(pbt);
|
||||
s.setSalesTaxAmount(salesTaxOnSales(m.sales));
|
||||
s.setProfitAfterTax(pbt.subtract(s.getSalesTaxAmount()).setScale(2, RoundingMode.HALF_UP));
|
||||
s.setRoi(calculateSalesROI(m.sales, promo));
|
||||
}
|
||||
|
||||
private void fillPlatformLikeMetrics(CompanyOverviewVO.PlatformSummary s, AggMetrics m,
|
||||
BigDecimal promo, BigDecimal brush,
|
||||
BigDecimal targetAmt, int targetOrders) {
|
||||
s.setSalesAmount(m.sales);
|
||||
s.setDealAmount(m.dealAmount);
|
||||
s.setSalesOrderCount(m.salesOrderCount);
|
||||
s.setDealOrderCount(m.dealOrderCount);
|
||||
s.setDealQuantitySum(m.dealQuantitySum);
|
||||
s.setSalesQuantitySum(m.salesQuantitySum);
|
||||
s.setSalesAverageOrderValue(aov(m.sales, m.salesOrderCount));
|
||||
s.setDealAverageOrderValue(aov(m.dealAmount, m.dealOrderCount));
|
||||
s.setProductCost(m.productCost);
|
||||
s.setShippingCost(m.freightCost);
|
||||
s.setOtherCost(m.otherCost);
|
||||
s.setOrderCost(m.orderCost());
|
||||
s.setRefundAmount(m.refund);
|
||||
s.setRefundOrderCount(m.refundOrderCount);
|
||||
s.setRefundQuantitySum(m.refundQuantitySum);
|
||||
s.setTotalPromotionFee(promo);
|
||||
s.setBrushFee(brush);
|
||||
s.setFeeRatio(safeDivide(promo.add(brush), m.sales));
|
||||
s.setGrossProfit(m.grossProfit().setScale(2, RoundingMode.HALF_UP));
|
||||
BigDecimal pbt = m.grossProfit().subtract(promo).subtract(brush);
|
||||
s.setTotalProfitBeforeTax(pbt);
|
||||
s.setSalesTaxAmount(salesTaxOnSales(m.sales));
|
||||
s.setProfitAfterTax(pbt.subtract(s.getSalesTaxAmount()).setScale(2, RoundingMode.HALF_UP));
|
||||
s.setRoi(calculateSalesROI(m.sales, promo));
|
||||
s.setTargetAmount(targetAmt);
|
||||
s.setTargetOrderCount(targetOrders);
|
||||
s.setSalesAmountAchievementRate(achievementRate(m.sales, targetAmt));
|
||||
s.setOrderCountAchievementRate(achievementRate(BigDecimal.valueOf(m.salesOrderCount), BigDecimal.valueOf(targetOrders)));
|
||||
}
|
||||
|
||||
private static void mergeAgg(Map<Long, AggMetrics> map, long key, OverviewAggRows.ShopProductRow row) {
|
||||
map.merge(key, AggMetrics.from(row), AggMetrics::merge);
|
||||
}
|
||||
|
||||
private static BigDecimal resolveCategoryPromo(Long categoryKey, BigDecimal sales,
|
||||
Map<Long, BigDecimal> salesByCategory, Map<Long, Long> productCategoryMap,
|
||||
Map<Long, BigDecimal> directByProduct, Map<Long, BigDecimal> directByCategory,
|
||||
BigDecimal ratioPool, BigDecimal totalPool) {
|
||||
BigDecimal direct = BigDecimal.ZERO;
|
||||
for (Map.Entry<Long, Long> e : productCategoryMap.entrySet()) {
|
||||
if (matchesCategory(categoryKey, e.getValue())) {
|
||||
direct = direct.add(directByProduct.getOrDefault(e.getKey(), BigDecimal.ZERO));
|
||||
}
|
||||
}
|
||||
if (categoryKey != null && categoryKey > 0) {
|
||||
direct = direct.add(directByCategory.getOrDefault(categoryKey, BigDecimal.ZERO));
|
||||
}
|
||||
return addPoolShare(direct, sales, ratioPool, totalPool);
|
||||
}
|
||||
|
||||
private static BigDecimal resolveProductPromo(Long productId, BigDecimal sales,
|
||||
Map<Long, Long> productCategoryMap, Map<Long, BigDecimal> salesByCategory,
|
||||
Map<Long, BigDecimal> directByProduct, Map<Long, BigDecimal> directByCategory,
|
||||
BigDecimal ratioPool, BigDecimal totalPool) {
|
||||
if (productId == null || productId <= 0) {
|
||||
return addPoolShare(BigDecimal.ZERO, sales, ratioPool, totalPool);
|
||||
}
|
||||
BigDecimal direct = directByProduct.getOrDefault(productId, BigDecimal.ZERO);
|
||||
Long cid = productCategoryMap.get(productId);
|
||||
if (cid != null && cid > 0) {
|
||||
BigDecimal catSales = salesByCategory.getOrDefault(cid, BigDecimal.ZERO);
|
||||
if (catSales.compareTo(BigDecimal.ZERO) > 0) {
|
||||
direct = direct.add(directByCategory.getOrDefault(cid, BigDecimal.ZERO)
|
||||
.multiply(sales).divide(catSales, 4, RoundingMode.HALF_UP));
|
||||
}
|
||||
}
|
||||
return addPoolShare(direct, sales, ratioPool, totalPool);
|
||||
}
|
||||
|
||||
private static boolean matchesCategory(Long categoryKey, Long productCat) {
|
||||
if (categoryKey == -1L) {
|
||||
return productCat == null;
|
||||
}
|
||||
return Objects.equals(categoryKey, productCat);
|
||||
}
|
||||
|
||||
private static BigDecimal addPoolShare(BigDecimal base, BigDecimal sales, BigDecimal pool, BigDecimal total) {
|
||||
if (pool.compareTo(BigDecimal.ZERO) > 0 && total.compareTo(BigDecimal.ZERO) > 0) {
|
||||
return base.add(pool.multiply(sales).divide(total, 4, RoundingMode.HALF_UP));
|
||||
}
|
||||
return base;
|
||||
}
|
||||
|
||||
private static BigDecimal allocBrushShare(Map<Long, BigDecimal> salesByShop, Map<Long, BigDecimal> brushByShop) {
|
||||
if (salesByShop == null || salesByShop.isEmpty()) {
|
||||
return BigDecimal.ZERO;
|
||||
}
|
||||
BigDecimal total = salesByShop.values().stream().reduce(BigDecimal.ZERO, BigDecimal::add);
|
||||
if (total.compareTo(BigDecimal.ZERO) <= 0) {
|
||||
return BigDecimal.ZERO;
|
||||
}
|
||||
BigDecimal brush = BigDecimal.ZERO;
|
||||
for (Map.Entry<Long, BigDecimal> e : salesByShop.entrySet()) {
|
||||
brush = brush.add(brushByShop.getOrDefault(e.getKey(), BigDecimal.ZERO)
|
||||
.multiply(e.getValue()).divide(total, 6, RoundingMode.HALF_UP));
|
||||
}
|
||||
return brush;
|
||||
}
|
||||
|
||||
private Map<Long, String> loadCategoryNameMap(Long companyId) {
|
||||
return categoryService.list(new LambdaQueryWrapper<CategoryPO>().eq(CategoryPO::getCompanyId, companyId))
|
||||
.stream().collect(Collectors.toMap(CategoryPO::getId, CategoryPO::getName, (a, b) -> a));
|
||||
}
|
||||
|
||||
private Map<Long, String> loadProductNameMap(java.util.Set<Long> productKeys) {
|
||||
List<Long> ids = productKeys.stream().filter(id -> id != null && id > 0).distinct().toList();
|
||||
if (ids.isEmpty()) {
|
||||
return Map.of();
|
||||
}
|
||||
return productMapper.selectList(new LambdaQueryWrapper<ProductPO>().in(ProductPO::getId, ids))
|
||||
.stream().collect(Collectors.toMap(ProductPO::getId, ProductPO::getName, (a, b) -> a));
|
||||
}
|
||||
|
||||
/** SKU 展示标签:规格名 + 编码 */
|
||||
private Map<Long, SkuLabel> loadSkuLabelMap(java.util.Set<Long> skuKeys) {
|
||||
List<Long> ids = skuKeys.stream().filter(id -> id != null && id > 0).distinct().toList();
|
||||
if (ids.isEmpty()) {
|
||||
return Map.of();
|
||||
}
|
||||
Map<Long, SkuLabel> map = new HashMap<>();
|
||||
for (ProductSkuPO sku : productSkuMapper.selectList(
|
||||
new LambdaQueryWrapper<ProductSkuPO>().in(ProductSkuPO::getId, ids))) {
|
||||
if (sku.getId() == null) {
|
||||
continue;
|
||||
}
|
||||
map.put(sku.getId(), new SkuLabel(
|
||||
sku.getName() != null ? sku.getName() : ("规格" + sku.getId()),
|
||||
sku.getSkuCode()));
|
||||
}
|
||||
return map;
|
||||
}
|
||||
|
||||
private record SkuLabel(String name, String code) {
|
||||
}
|
||||
|
||||
private Map<Long, List<ShopMonthlyTargetPO>> loadTargetsByShop(Long companyId, LocalDate start, LocalDate end) {
|
||||
List<LocalDate> months = new ArrayList<>();
|
||||
LocalDate cur = start.withDayOfMonth(1);
|
||||
LocalDate endMonth = end.withDayOfMonth(1);
|
||||
while (!cur.isAfter(endMonth)) {
|
||||
months.add(cur);
|
||||
cur = cur.plusMonths(1);
|
||||
}
|
||||
if (months.isEmpty()) {
|
||||
return Map.of();
|
||||
}
|
||||
LambdaQueryWrapper<ShopMonthlyTargetPO> w = new LambdaQueryWrapper<>();
|
||||
w.eq(ShopMonthlyTargetPO::getCompanyId, companyId).in(ShopMonthlyTargetPO::getTargetMonth, months);
|
||||
return shopMonthlyTargetMapper.selectList(w).stream()
|
||||
.collect(Collectors.groupingBy(ShopMonthlyTargetPO::getShopId));
|
||||
}
|
||||
|
||||
private static String categoryAggName(Long key, Map<Long, String> names) {
|
||||
if (key == null || key == -1L) {
|
||||
return "其他品类";
|
||||
}
|
||||
if (key == 0L) {
|
||||
return "未分类";
|
||||
}
|
||||
return names.getOrDefault(key, "类目" + key);
|
||||
}
|
||||
|
||||
private static BigDecimal aov(BigDecimal sales, int count) {
|
||||
return count > 0 ? sales.divide(BigDecimal.valueOf(count), 2, RoundingMode.HALF_UP) : BigDecimal.ZERO;
|
||||
}
|
||||
|
||||
private static BigDecimal safeDivide(BigDecimal a, BigDecimal b) {
|
||||
return b.compareTo(BigDecimal.ZERO) > 0 ? a.divide(b, 4, RoundingMode.HALF_UP) : BigDecimal.ZERO;
|
||||
}
|
||||
|
||||
private static BigDecimal achievementRate(BigDecimal actual, BigDecimal target) {
|
||||
if (target.compareTo(BigDecimal.ZERO) > 0) {
|
||||
return actual.divide(target, 4, RoundingMode.HALF_UP).multiply(new BigDecimal("100"));
|
||||
}
|
||||
return actual.compareTo(BigDecimal.ZERO) > 0 ? new BigDecimal("100") : BigDecimal.ZERO;
|
||||
}
|
||||
|
||||
private static BigDecimal nz(BigDecimal v) {
|
||||
return v != null ? v : BigDecimal.ZERO;
|
||||
}
|
||||
|
||||
private static final class AggMetrics {
|
||||
static final AggMetrics EMPTY = new AggMetrics();
|
||||
BigDecimal sales = BigDecimal.ZERO;
|
||||
/** 成交金额(全订单状态商家实收合计) */
|
||||
BigDecimal dealAmount = BigDecimal.ZERO;
|
||||
int salesOrderCount;
|
||||
int dealOrderCount;
|
||||
int dealQuantitySum;
|
||||
int salesQuantitySum;
|
||||
BigDecimal refund = BigDecimal.ZERO;
|
||||
int refundOrderCount;
|
||||
int refundQuantitySum;
|
||||
BigDecimal productCost = BigDecimal.ZERO;
|
||||
BigDecimal freightCost = BigDecimal.ZERO;
|
||||
BigDecimal otherCost = BigDecimal.ZERO;
|
||||
|
||||
/** 订单成本合计(商品+运费+其他,不含推广/刷单) */
|
||||
BigDecimal orderCost() {
|
||||
return productCost.add(freightCost).add(otherCost);
|
||||
}
|
||||
|
||||
/** 订单维度毛利:净销售额 − 订单成本(净销售额已含成交−退款,不再二次减退款) */
|
||||
BigDecimal grossProfit() {
|
||||
return sales.subtract(orderCost());
|
||||
}
|
||||
|
||||
static AggMetrics from(OverviewAggRows.ShopProductRow row) {
|
||||
AggMetrics a = new AggMetrics();
|
||||
a.sales = nz(row.getSalesAmount());
|
||||
a.dealAmount = nz(row.getDealAmount());
|
||||
a.salesOrderCount = row.getOrderCount() != null ? row.getOrderCount().intValue() : 0;
|
||||
a.dealOrderCount = row.getDealOrderCount() != null ? row.getDealOrderCount().intValue() : 0;
|
||||
a.dealQuantitySum = row.getDealQuantitySum() != null ? row.getDealQuantitySum().intValue() : 0;
|
||||
a.salesQuantitySum = row.getSalesQuantitySum() != null ? row.getSalesQuantitySum().intValue() : 0;
|
||||
a.refund = nz(row.getRefundAmount());
|
||||
a.refundOrderCount = row.getRefundOrderCount() != null ? row.getRefundOrderCount().intValue() : 0;
|
||||
a.refundQuantitySum = row.getRefundQuantitySum() != null ? row.getRefundQuantitySum().intValue() : 0;
|
||||
a.productCost = nz(row.getProductCost());
|
||||
a.freightCost = nz(row.getFreightCost());
|
||||
a.otherCost = nz(row.getOtherCost());
|
||||
return a;
|
||||
}
|
||||
|
||||
static AggMetrics from(OverviewAggRows.ShopSkuRow row) {
|
||||
AggMetrics a = new AggMetrics();
|
||||
a.sales = nz(row.getSalesAmount());
|
||||
a.dealAmount = nz(row.getDealAmount());
|
||||
a.salesOrderCount = row.getOrderCount() != null ? row.getOrderCount().intValue() : 0;
|
||||
a.dealOrderCount = row.getDealOrderCount() != null ? row.getDealOrderCount().intValue() : 0;
|
||||
a.dealQuantitySum = row.getDealQuantitySum() != null ? row.getDealQuantitySum().intValue() : 0;
|
||||
a.salesQuantitySum = row.getSalesQuantitySum() != null ? row.getSalesQuantitySum().intValue() : 0;
|
||||
a.refund = nz(row.getRefundAmount());
|
||||
a.refundOrderCount = row.getRefundOrderCount() != null ? row.getRefundOrderCount().intValue() : 0;
|
||||
a.refundQuantitySum = row.getRefundQuantitySum() != null ? row.getRefundQuantitySum().intValue() : 0;
|
||||
a.productCost = nz(row.getProductCost());
|
||||
a.freightCost = nz(row.getFreightCost());
|
||||
a.otherCost = nz(row.getOtherCost());
|
||||
return a;
|
||||
}
|
||||
|
||||
AggMetrics merge(AggMetrics o) {
|
||||
AggMetrics a = new AggMetrics();
|
||||
a.sales = sales.add(o.sales);
|
||||
a.dealAmount = dealAmount.add(o.dealAmount);
|
||||
a.salesOrderCount = salesOrderCount + o.salesOrderCount;
|
||||
a.dealOrderCount = dealOrderCount + o.dealOrderCount;
|
||||
a.dealQuantitySum = dealQuantitySum + o.dealQuantitySum;
|
||||
a.salesQuantitySum = salesQuantitySum + o.salesQuantitySum;
|
||||
a.refund = refund.add(o.refund);
|
||||
a.refundOrderCount = refundOrderCount + o.refundOrderCount;
|
||||
a.refundQuantitySum = refundQuantitySum + o.refundQuantitySum;
|
||||
a.productCost = productCost.add(o.productCost);
|
||||
a.freightCost = freightCost.add(o.freightCost);
|
||||
a.otherCost = otherCost.add(o.otherCost);
|
||||
return a;
|
||||
}
|
||||
}
|
||||
}
|
||||
+586
@@ -0,0 +1,586 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.bi.overview.service.impl;
|
||||
|
||||
import org.apache.poi.ss.usermodel.*;
|
||||
import org.apache.poi.ss.util.CellRangeAddress;
|
||||
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
|
||||
import org.springframework.stereotype.Service;
|
||||
import top.xyquan.ecomdmbbackend.common.exception.BusinessException;
|
||||
import top.xyquan.ecomdmbbackend.modules.bi.overview.model.dto.CompanyExportDTO;
|
||||
import top.xyquan.ecomdmbbackend.modules.bi.overview.model.dto.PlatformExportDTO;
|
||||
import top.xyquan.ecomdmbbackend.modules.bi.overview.model.vo.CompanyOverviewVO;
|
||||
import top.xyquan.ecomdmbbackend.modules.bi.overview.service.ExportService;
|
||||
|
||||
import java.io.ByteArrayOutputStream;
|
||||
import java.math.BigDecimal;
|
||||
import java.math.RoundingMode;
|
||||
import java.time.LocalDate;
|
||||
import java.time.format.DateTimeFormatter;
|
||||
import java.util.*;
|
||||
import java.util.function.Function;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
/**
|
||||
* 工作台等多维表导出(按已汇总好的表写入 Excel)。
|
||||
*/
|
||||
@Service
|
||||
public class ExportServiceImpl implements ExportService {
|
||||
|
||||
private static final BigDecimal DEFAULT_TAX_RATE = new BigDecimal("0.04");
|
||||
private static final DateTimeFormatter DATE_FMT = DateTimeFormatter.ofPattern("yyyy-MM-dd");
|
||||
|
||||
private final ExportStatusRangeHelper exportStatusRangeHelper;
|
||||
|
||||
public ExportServiceImpl(ExportStatusRangeHelper exportStatusRangeHelper) {
|
||||
this.exportStatusRangeHelper = exportStatusRangeHelper;
|
||||
}
|
||||
|
||||
@Override
|
||||
public byte[] exportShopOverviewFromTable(CompanyExportDTO dto, CompanyOverviewVO.ShopOverview shopOverview, String summaryTitle) {
|
||||
return buildShopOverviewExcelBytes(dto, shopOverview, summaryTitle);
|
||||
}
|
||||
|
||||
private byte[] buildShopOverviewExcelBytes(
|
||||
CompanyExportDTO dto,
|
||||
CompanyOverviewVO.ShopOverview shopOv,
|
||||
String summarySheetTitle) {
|
||||
BigDecimal taxRate = dto.getTaxRate() != null ? dto.getTaxRate() : DEFAULT_TAX_RATE;
|
||||
|
||||
List<CompanyOverviewVO.ShopSummary> shops = (shopOv != null && shopOv.getShops() != null)
|
||||
? new ArrayList<>(shopOv.getShops())
|
||||
: new ArrayList<>();
|
||||
if (dto.getShopIds() != null && !dto.getShopIds().isEmpty()) {
|
||||
Set<Long> allowed = new HashSet<>(dto.getShopIds());
|
||||
shops = shops.stream()
|
||||
.filter(s -> s.getShopId() != null && allowed.contains(s.getShopId()))
|
||||
.collect(Collectors.toList());
|
||||
}
|
||||
|
||||
List<Map<String, Object>> shopRows = shops.stream().map(this::shopSummaryToRowMap).collect(Collectors.toList());
|
||||
boolean shopFiltered = dto.getShopIds() != null && !dto.getShopIds().isEmpty();
|
||||
CompanyOverviewVO.ShopSummary totalShop = shopFiltered
|
||||
? aggregateShopSummariesForExport(shops, taxRate)
|
||||
: (shopOv != null && shopOv.getTotal() != null ? shopOv.getTotal() : aggregateShopSummariesForExport(shops, taxRate));
|
||||
Map<String, Object> totalRowMap = shopSummaryToRowMap(totalShop);
|
||||
|
||||
LocalDate[] dateRange = exportStatusRangeHelper.parseDateRange(dto.getDateRange());
|
||||
String dateRangeLabel = dateRange[0].format(DATE_FMT) + " 至 " + dateRange[1].format(DATE_FMT);
|
||||
|
||||
try (Workbook workbook = new XSSFWorkbook()) {
|
||||
Sheet summarySheet = workbook.createSheet("汇总");
|
||||
createCompanyDetailSheet(
|
||||
summarySheet, summarySheetTitle, dateRangeLabel, shopRows, taxRate, totalRowMap);
|
||||
try (ByteArrayOutputStream out = new ByteArrayOutputStream()) {
|
||||
workbook.write(out);
|
||||
return out.toByteArray();
|
||||
}
|
||||
} catch (Exception e) {
|
||||
throw new BusinessException("导出Excel失败: " + e.getMessage());
|
||||
}
|
||||
}
|
||||
|
||||
private void createCompanyDetailSheet(
|
||||
Sheet sheet,
|
||||
String summaryTitle,
|
||||
String dateRangeLabel,
|
||||
List<Map<String, Object>> shopDataList,
|
||||
BigDecimal taxRate,
|
||||
Map<String, Object> totalRowMap) {
|
||||
createOverviewDimensionSheet(
|
||||
sheet,
|
||||
summaryTitle,
|
||||
dateRangeLabel,
|
||||
shopDataList,
|
||||
taxRate,
|
||||
totalRowMap,
|
||||
"店铺名称",
|
||||
m -> m.get("shopName") != null ? m.get("shopName").toString() : "");
|
||||
}
|
||||
|
||||
private void createPlatformSummarySheet(
|
||||
Sheet sheet,
|
||||
String summaryTitle,
|
||||
String dateRangeLabel,
|
||||
List<Map<String, Object>> platformRows,
|
||||
BigDecimal taxRate,
|
||||
Map<String, Object> totalRowMap) {
|
||||
createOverviewDimensionSheet(
|
||||
sheet,
|
||||
summaryTitle,
|
||||
dateRangeLabel,
|
||||
platformRows,
|
||||
taxRate,
|
||||
totalRowMap,
|
||||
"平台名称",
|
||||
m -> m.get("platformName") != null ? m.get("platformName").toString() : "");
|
||||
}
|
||||
|
||||
private void createOverviewDimensionSheet(
|
||||
Sheet sheet,
|
||||
String summaryTitle,
|
||||
String dateRangeLabel,
|
||||
List<Map<String, Object>> dataList,
|
||||
BigDecimal taxRate,
|
||||
Map<String, Object> totalRowMap,
|
||||
String firstColumnHeader,
|
||||
Function<Map<String, Object>, String> firstColumnValue) {
|
||||
Workbook wb = sheet.getWorkbook();
|
||||
Row titleRow = sheet.createRow(0);
|
||||
Cell titleCell = titleRow.createCell(0);
|
||||
titleCell.setCellValue(summaryTitle + " | " + dateRangeLabel);
|
||||
titleCell.setCellStyle(createTitleStyle(wb));
|
||||
String taxLabel = (taxRate.multiply(new BigDecimal("100")).setScale(0, RoundingMode.HALF_UP)).toPlainString() + "%税额";
|
||||
String[] headers = {
|
||||
firstColumnHeader, "目标单量", "单量达成率(%)", "目标额", "销售达成率(%)",
|
||||
"成交金额", "净销售额", "成交单量", "净销售单量", "成交量", "净销量", "成交客单价", "净销售客单价",
|
||||
"商品成本", "运费", "其他成本", "订单成本", "退款金额", taxLabel, "推广费", "刷单费",
|
||||
"毛利", "税前净利", "费比", "ROI", "税后净利"
|
||||
};
|
||||
sheet.addMergedRegion(new CellRangeAddress(0, 0, 0, headers.length - 1));
|
||||
CellStyle headerStyle = createHeaderStyle(wb);
|
||||
CellStyle dataStyle = createDataStyle(wb);
|
||||
CellStyle boldStyle = createBoldDataStyle(wb);
|
||||
|
||||
Row headerRow = sheet.createRow(1);
|
||||
for (int i = 0; i < headers.length; i++) {
|
||||
Cell cell = headerRow.createCell(i);
|
||||
cell.setCellValue(headers[i]);
|
||||
cell.setCellStyle(headerStyle);
|
||||
}
|
||||
|
||||
int rowIdx = 2;
|
||||
for (Map<String, Object> data : dataList) {
|
||||
Row row = sheet.createRow(rowIdx++);
|
||||
writeOverviewDetailRow(row, data, dataStyle, firstColumnValue.apply(data), taxRate);
|
||||
}
|
||||
if (totalRowMap != null) {
|
||||
Row row = sheet.createRow(rowIdx);
|
||||
writeOverviewDetailRow(row, totalRowMap, boldStyle, firstColumnValue.apply(totalRowMap), taxRate);
|
||||
}
|
||||
|
||||
for (int i = 0; i < headers.length; i++) {
|
||||
sheet.setColumnWidth(i, 3200);
|
||||
}
|
||||
}
|
||||
|
||||
private void writeOverviewDetailRow(
|
||||
Row row, Map<String, Object> data, CellStyle style, String firstColumnText, BigDecimal taxRate) {
|
||||
setCell(row, 0, firstColumnText, style);
|
||||
setCell(row, 1, objToDouble(data.get("targetOrderCount")), style);
|
||||
setCell(row, 2, objToPct(data.get("orderCountAchievementRate")), style);
|
||||
setCell(row, 3, objToDouble(data.get("targetAmount")), style);
|
||||
setCell(row, 4, objToPct(data.get("salesAchievementRate")), style);
|
||||
setCell(row, 5, objToDouble(data.get("dealAmount")), style);
|
||||
setCell(row, 6, objToDouble(data.get("salesAmount")), style);
|
||||
setCell(row, 7, objToDouble(data.get("dealOrderCount")), style);
|
||||
setCell(row, 8, objToDouble(data.get("salesOrderCount")), style);
|
||||
setCell(row, 9, objToDouble(data.get("dealQuantitySum")), style);
|
||||
setCell(row, 10, objToDouble(data.get("salesQuantitySum")), style);
|
||||
setCell(row, 11, objToDouble(data.get("dealAvgOrderValue")), style);
|
||||
setCell(row, 12, objToDouble(data.get("salesAvgOrderValue")), style);
|
||||
setCell(row, 13, objToDouble(data.get("productCost")), style);
|
||||
setCell(row, 14, objToDouble(data.get("shippingCost")), style);
|
||||
setCell(row, 15, objToDouble(data.get("otherCost")), style);
|
||||
setCell(row, 16, objToDouble(data.get("orderCost")), style);
|
||||
BigDecimal salesTax = salesTaxOnNetForExport(
|
||||
mapToBigDecimal(data.get("salesAmount")),
|
||||
taxRate);
|
||||
BigDecimal profitAfterTax = mapToBigDecimal(data.get("totalProfitBeforeTax"))
|
||||
.subtract(salesTax)
|
||||
.setScale(2, RoundingMode.HALF_UP);
|
||||
setCell(row, 17, objToDouble(data.get("refundAmount")), style);
|
||||
setCell(row, 18, salesTax.doubleValue(), style);
|
||||
setCell(row, 19, objToDouble(data.get("totalPromotionFee")), style);
|
||||
setCell(row, 20, objToDouble(data.get("brushFee")), style);
|
||||
setCell(row, 21, objToDouble(data.get("grossProfit")), style);
|
||||
setCell(row, 22, objToDouble(data.get("totalProfitBeforeTax")), style);
|
||||
setCell(row, 23, objToDouble(data.get("feeRatio")), style);
|
||||
setCell(row, 24, objToDouble(data.get("roi")), style);
|
||||
setCell(row, 25, profitAfterTax.doubleValue(), style);
|
||||
}
|
||||
|
||||
private static BigDecimal mapToBigDecimal(Object val) {
|
||||
if (val == null) {
|
||||
return BigDecimal.ZERO;
|
||||
}
|
||||
if (val instanceof BigDecimal) {
|
||||
return (BigDecimal) val;
|
||||
}
|
||||
if (val instanceof Integer) {
|
||||
return BigDecimal.valueOf((Integer) val);
|
||||
}
|
||||
if (val instanceof Long) {
|
||||
return BigDecimal.valueOf((Long) val);
|
||||
}
|
||||
return BigDecimal.ZERO;
|
||||
}
|
||||
|
||||
private Map<String, Object> shopSummaryToRowMap(CompanyOverviewVO.ShopSummary s) {
|
||||
Map<String, Object> data = new HashMap<>();
|
||||
data.put("shopName", s.getShopName());
|
||||
data.put("targetOrderCount", s.getTargetOrderCount());
|
||||
data.put("orderCountAchievementRate", s.getOrderCountAchievementRate());
|
||||
data.put("targetAmount", s.getTargetAmount());
|
||||
data.put("salesAchievementRate", s.getSalesAmountAchievementRate());
|
||||
data.put("dealAmount", s.getDealAmount());
|
||||
data.put("salesAmount", s.getSalesAmount());
|
||||
data.put("dealOrderCount", s.getDealOrderCount());
|
||||
data.put("salesOrderCount", s.getSalesOrderCount());
|
||||
data.put("dealQuantitySum", s.getDealQuantitySum());
|
||||
data.put("salesQuantitySum", s.getSalesQuantitySum());
|
||||
data.put("dealAvgOrderValue", s.getDealAverageOrderValue());
|
||||
data.put("salesAvgOrderValue", s.getSalesAverageOrderValue());
|
||||
data.put("productCost", s.getProductCost());
|
||||
data.put("shippingCost", s.getShippingCost());
|
||||
data.put("otherCost", s.getOtherCost());
|
||||
data.put("orderCost", s.getOrderCost());
|
||||
data.put("refundAmount", s.getRefundAmount());
|
||||
data.put("totalPromotionFee", s.getTotalPromotionFee());
|
||||
data.put("brushFee", s.getBrushFee());
|
||||
data.put("feeRatio", s.getFeeRatio());
|
||||
data.put("grossProfit", s.getGrossProfit());
|
||||
data.put("totalProfitBeforeTax", s.getTotalProfitBeforeTax());
|
||||
data.put("salesTaxAmount", s.getSalesTaxAmount());
|
||||
data.put("roi", s.getRoi());
|
||||
data.put("profitAfterTax", s.getProfitAfterTax());
|
||||
return data;
|
||||
}
|
||||
|
||||
/** 税额 = 净销售额 × 税率 */
|
||||
private static BigDecimal salesTaxOnNetForExport(BigDecimal sales, BigDecimal taxRate) {
|
||||
BigDecimal base = sales != null ? sales : BigDecimal.ZERO;
|
||||
if (base.compareTo(BigDecimal.ZERO) < 0) {
|
||||
base = BigDecimal.ZERO;
|
||||
}
|
||||
BigDecimal r = taxRate != null ? taxRate : BigDecimal.ZERO;
|
||||
return base.multiply(r).setScale(2, RoundingMode.HALF_UP);
|
||||
}
|
||||
|
||||
private CompanyOverviewVO.ShopSummary aggregateShopSummariesForExport(
|
||||
List<CompanyOverviewVO.ShopSummary> shops, BigDecimal taxRate) {
|
||||
BigDecimal totalSales = BigDecimal.ZERO;
|
||||
BigDecimal totalDealAmount = BigDecimal.ZERO;
|
||||
int totalSalesOrders = 0;
|
||||
int totalDealOrders = 0;
|
||||
int totalDealQuantity = 0;
|
||||
int totalSalesQuantity = 0;
|
||||
BigDecimal totalTargetAmount = BigDecimal.ZERO;
|
||||
int totalTargetOrders = 0;
|
||||
BigDecimal totalProductCost = BigDecimal.ZERO;
|
||||
BigDecimal totalShippingCost = BigDecimal.ZERO;
|
||||
BigDecimal totalOtherCost = BigDecimal.ZERO;
|
||||
BigDecimal totalRefund = BigDecimal.ZERO;
|
||||
BigDecimal totalPromoFee = BigDecimal.ZERO;
|
||||
BigDecimal totalBrushFee = BigDecimal.ZERO;
|
||||
|
||||
for (CompanyOverviewVO.ShopSummary s : shops) {
|
||||
totalSales = totalSales.add(s.getSalesAmount() != null ? s.getSalesAmount() : BigDecimal.ZERO);
|
||||
totalDealAmount = totalDealAmount.add(s.getDealAmount() != null ? s.getDealAmount() : BigDecimal.ZERO);
|
||||
totalSalesOrders += s.getSalesOrderCount() != null ? s.getSalesOrderCount() : 0;
|
||||
totalDealOrders += s.getDealOrderCount() != null ? s.getDealOrderCount() : 0;
|
||||
totalDealQuantity += s.getDealQuantitySum() != null ? s.getDealQuantitySum() : 0;
|
||||
totalSalesQuantity += s.getSalesQuantitySum() != null ? s.getSalesQuantitySum() : 0;
|
||||
totalTargetAmount = totalTargetAmount.add(s.getTargetAmount() != null ? s.getTargetAmount() : BigDecimal.ZERO);
|
||||
totalTargetOrders += s.getTargetOrderCount() != null ? s.getTargetOrderCount() : 0;
|
||||
totalProductCost = totalProductCost.add(s.getProductCost() != null ? s.getProductCost() : BigDecimal.ZERO);
|
||||
totalShippingCost = totalShippingCost.add(s.getShippingCost() != null ? s.getShippingCost() : BigDecimal.ZERO);
|
||||
totalOtherCost = totalOtherCost.add(s.getOtherCost() != null ? s.getOtherCost() : BigDecimal.ZERO);
|
||||
totalRefund = totalRefund.add(s.getRefundAmount() != null ? s.getRefundAmount() : BigDecimal.ZERO);
|
||||
totalPromoFee = totalPromoFee.add(s.getTotalPromotionFee() != null ? s.getTotalPromotionFee() : BigDecimal.ZERO);
|
||||
totalBrushFee = totalBrushFee.add(s.getBrushFee() != null ? s.getBrushFee() : BigDecimal.ZERO);
|
||||
}
|
||||
|
||||
BigDecimal salesAvgOrderValue = totalSalesOrders > 0
|
||||
? totalSales.divide(new BigDecimal(totalSalesOrders), 2, RoundingMode.HALF_UP)
|
||||
: BigDecimal.ZERO;
|
||||
BigDecimal dealAvgOrderValue = totalDealOrders > 0
|
||||
? totalDealAmount.divide(new BigDecimal(totalDealOrders), 2, RoundingMode.HALF_UP)
|
||||
: BigDecimal.ZERO;
|
||||
BigDecimal totalCost = totalProductCost.add(totalShippingCost).add(totalOtherCost);
|
||||
BigDecimal profitBeforeTax = totalSales.subtract(totalCost)
|
||||
.subtract(totalPromoFee).subtract(totalBrushFee);
|
||||
BigDecimal salesTax = salesTaxOnNetForExport(totalSales, taxRate);
|
||||
BigDecimal profitAfterTax = profitBeforeTax.subtract(salesTax);
|
||||
BigDecimal roi = totalPromoFee.compareTo(BigDecimal.ZERO) > 0
|
||||
? totalSales.divide(totalPromoFee, 4, RoundingMode.HALF_UP)
|
||||
: BigDecimal.ZERO;
|
||||
BigDecimal feeRatio = totalSales.compareTo(BigDecimal.ZERO) > 0
|
||||
? totalPromoFee.add(totalBrushFee).divide(totalSales, 4, RoundingMode.HALF_UP)
|
||||
: BigDecimal.ZERO;
|
||||
BigDecimal salesAchievementRate = totalTargetAmount.compareTo(BigDecimal.ZERO) > 0
|
||||
? totalSales.divide(totalTargetAmount, 4, RoundingMode.HALF_UP).multiply(new BigDecimal("100"))
|
||||
: totalSales.compareTo(BigDecimal.ZERO) > 0 ? new BigDecimal("100") : BigDecimal.ZERO;
|
||||
BigDecimal orderAchievementRate = totalTargetOrders > 0
|
||||
? new BigDecimal(totalSalesOrders).divide(new BigDecimal(totalTargetOrders), 4, RoundingMode.HALF_UP)
|
||||
.multiply(new BigDecimal("100"))
|
||||
: totalSalesOrders > 0 ? new BigDecimal("100") : BigDecimal.ZERO;
|
||||
|
||||
CompanyOverviewVO.ShopSummary total = new CompanyOverviewVO.ShopSummary();
|
||||
total.setShopId(0L);
|
||||
total.setShopName("合计");
|
||||
total.setSalesAmount(totalSales);
|
||||
total.setDealAmount(totalDealAmount);
|
||||
total.setSalesOrderCount(totalSalesOrders);
|
||||
total.setDealOrderCount(totalDealOrders);
|
||||
total.setDealQuantitySum(totalDealQuantity);
|
||||
total.setSalesQuantitySum(totalSalesQuantity);
|
||||
total.setSalesAverageOrderValue(salesAvgOrderValue);
|
||||
total.setDealAverageOrderValue(dealAvgOrderValue);
|
||||
total.setTargetAmount(totalTargetAmount);
|
||||
total.setTargetOrderCount(totalTargetOrders);
|
||||
total.setSalesAmountAchievementRate(salesAchievementRate);
|
||||
total.setOrderCountAchievementRate(orderAchievementRate);
|
||||
total.setProductCost(totalProductCost);
|
||||
total.setShippingCost(totalShippingCost);
|
||||
total.setOtherCost(totalOtherCost);
|
||||
total.setOrderCost(totalCost);
|
||||
total.setRefundAmount(totalRefund);
|
||||
total.setTotalPromotionFee(totalPromoFee);
|
||||
total.setBrushFee(totalBrushFee);
|
||||
total.setFeeRatio(feeRatio);
|
||||
total.setTotalProfitBeforeTax(profitBeforeTax);
|
||||
total.setSalesTaxAmount(salesTax);
|
||||
total.setRoi(roi);
|
||||
total.setProfitAfterTax(profitAfterTax.setScale(2, RoundingMode.HALF_UP));
|
||||
return total;
|
||||
}
|
||||
|
||||
private Map<String, Object> platformSummaryToRowMap(CompanyOverviewVO.PlatformSummary s) {
|
||||
Map<String, Object> data = new HashMap<>();
|
||||
data.put("platformName", s.getPlatformName());
|
||||
data.put("targetOrderCount", s.getTargetOrderCount());
|
||||
data.put("orderCountAchievementRate", s.getOrderCountAchievementRate());
|
||||
data.put("targetAmount", s.getTargetAmount());
|
||||
data.put("salesAchievementRate", s.getSalesAmountAchievementRate());
|
||||
data.put("dealAmount", s.getDealAmount());
|
||||
data.put("salesAmount", s.getSalesAmount());
|
||||
data.put("dealOrderCount", s.getDealOrderCount());
|
||||
data.put("salesOrderCount", s.getSalesOrderCount());
|
||||
data.put("dealQuantitySum", s.getDealQuantitySum());
|
||||
data.put("salesQuantitySum", s.getSalesQuantitySum());
|
||||
data.put("dealAvgOrderValue", s.getDealAverageOrderValue());
|
||||
data.put("salesAvgOrderValue", s.getSalesAverageOrderValue());
|
||||
data.put("productCost", s.getProductCost());
|
||||
data.put("shippingCost", s.getShippingCost());
|
||||
data.put("otherCost", s.getOtherCost());
|
||||
data.put("orderCost", s.getOrderCost());
|
||||
data.put("refundAmount", s.getRefundAmount());
|
||||
data.put("totalPromotionFee", s.getTotalPromotionFee());
|
||||
data.put("brushFee", s.getBrushFee());
|
||||
data.put("feeRatio", s.getFeeRatio());
|
||||
data.put("grossProfit", s.getGrossProfit());
|
||||
data.put("totalProfitBeforeTax", s.getTotalProfitBeforeTax());
|
||||
data.put("salesTaxAmount", s.getSalesTaxAmount());
|
||||
data.put("roi", s.getRoi());
|
||||
data.put("profitAfterTax", s.getProfitAfterTax());
|
||||
return data;
|
||||
}
|
||||
|
||||
private CompanyOverviewVO.PlatformSummary aggregatePlatformSummariesForExport(
|
||||
List<CompanyOverviewVO.PlatformSummary> platforms, BigDecimal taxRate) {
|
||||
BigDecimal totalSales = BigDecimal.ZERO;
|
||||
BigDecimal totalDealAmount = BigDecimal.ZERO;
|
||||
int totalSalesOrders = 0;
|
||||
int totalDealOrders = 0;
|
||||
int totalDealQuantity = 0;
|
||||
int totalSalesQuantity = 0;
|
||||
BigDecimal totalTargetAmount = BigDecimal.ZERO;
|
||||
int totalTargetOrders = 0;
|
||||
BigDecimal totalProductCost = BigDecimal.ZERO;
|
||||
BigDecimal totalShippingCost = BigDecimal.ZERO;
|
||||
BigDecimal totalOtherCost = BigDecimal.ZERO;
|
||||
BigDecimal totalRefund = BigDecimal.ZERO;
|
||||
BigDecimal totalPromoFee = BigDecimal.ZERO;
|
||||
BigDecimal totalBrushFee = BigDecimal.ZERO;
|
||||
|
||||
for (CompanyOverviewVO.PlatformSummary s : platforms) {
|
||||
totalSales = totalSales.add(s.getSalesAmount() != null ? s.getSalesAmount() : BigDecimal.ZERO);
|
||||
totalDealAmount = totalDealAmount.add(s.getDealAmount() != null ? s.getDealAmount() : BigDecimal.ZERO);
|
||||
totalSalesOrders += s.getSalesOrderCount() != null ? s.getSalesOrderCount() : 0;
|
||||
totalDealOrders += s.getDealOrderCount() != null ? s.getDealOrderCount() : 0;
|
||||
totalDealQuantity += s.getDealQuantitySum() != null ? s.getDealQuantitySum() : 0;
|
||||
totalSalesQuantity += s.getSalesQuantitySum() != null ? s.getSalesQuantitySum() : 0;
|
||||
totalTargetAmount = totalTargetAmount.add(s.getTargetAmount() != null ? s.getTargetAmount() : BigDecimal.ZERO);
|
||||
totalTargetOrders += s.getTargetOrderCount() != null ? s.getTargetOrderCount() : 0;
|
||||
totalProductCost = totalProductCost.add(s.getProductCost() != null ? s.getProductCost() : BigDecimal.ZERO);
|
||||
totalShippingCost = totalShippingCost.add(s.getShippingCost() != null ? s.getShippingCost() : BigDecimal.ZERO);
|
||||
totalOtherCost = totalOtherCost.add(s.getOtherCost() != null ? s.getOtherCost() : BigDecimal.ZERO);
|
||||
totalRefund = totalRefund.add(s.getRefundAmount() != null ? s.getRefundAmount() : BigDecimal.ZERO);
|
||||
totalPromoFee = totalPromoFee.add(s.getTotalPromotionFee() != null ? s.getTotalPromotionFee() : BigDecimal.ZERO);
|
||||
totalBrushFee = totalBrushFee.add(s.getBrushFee() != null ? s.getBrushFee() : BigDecimal.ZERO);
|
||||
}
|
||||
|
||||
BigDecimal salesAvgOrderValue = totalSalesOrders > 0
|
||||
? totalSales.divide(new BigDecimal(totalSalesOrders), 2, RoundingMode.HALF_UP)
|
||||
: BigDecimal.ZERO;
|
||||
BigDecimal dealAvgOrderValue = totalDealOrders > 0
|
||||
? totalDealAmount.divide(new BigDecimal(totalDealOrders), 2, RoundingMode.HALF_UP)
|
||||
: BigDecimal.ZERO;
|
||||
BigDecimal totalCost = totalProductCost.add(totalShippingCost).add(totalOtherCost);
|
||||
BigDecimal profitBeforeTax = totalSales.subtract(totalCost)
|
||||
.subtract(totalPromoFee).subtract(totalBrushFee);
|
||||
BigDecimal salesTax = salesTaxOnNetForExport(totalSales, taxRate);
|
||||
BigDecimal profitAfterTax = profitBeforeTax.subtract(salesTax);
|
||||
BigDecimal roi = totalPromoFee.compareTo(BigDecimal.ZERO) > 0
|
||||
? totalSales.divide(totalPromoFee, 4, RoundingMode.HALF_UP)
|
||||
: BigDecimal.ZERO;
|
||||
BigDecimal feeRatio = totalSales.compareTo(BigDecimal.ZERO) > 0
|
||||
? totalPromoFee.add(totalBrushFee).divide(totalSales, 4, RoundingMode.HALF_UP)
|
||||
: BigDecimal.ZERO;
|
||||
BigDecimal salesAchievementRate = totalTargetAmount.compareTo(BigDecimal.ZERO) > 0
|
||||
? totalSales.divide(totalTargetAmount, 4, RoundingMode.HALF_UP).multiply(new BigDecimal("100"))
|
||||
: totalSales.compareTo(BigDecimal.ZERO) > 0 ? new BigDecimal("100") : BigDecimal.ZERO;
|
||||
BigDecimal orderAchievementRate = totalTargetOrders > 0
|
||||
? new BigDecimal(totalSalesOrders).divide(new BigDecimal(totalTargetOrders), 4, RoundingMode.HALF_UP)
|
||||
.multiply(new BigDecimal("100"))
|
||||
: totalSalesOrders > 0 ? new BigDecimal("100") : BigDecimal.ZERO;
|
||||
|
||||
CompanyOverviewVO.PlatformSummary total = new CompanyOverviewVO.PlatformSummary();
|
||||
total.setPlatformCode(null);
|
||||
total.setPlatformName("合计");
|
||||
total.setSalesAmount(totalSales);
|
||||
total.setDealAmount(totalDealAmount);
|
||||
total.setSalesOrderCount(totalSalesOrders);
|
||||
total.setDealOrderCount(totalDealOrders);
|
||||
total.setDealQuantitySum(totalDealQuantity);
|
||||
total.setSalesQuantitySum(totalSalesQuantity);
|
||||
total.setSalesAverageOrderValue(salesAvgOrderValue);
|
||||
total.setDealAverageOrderValue(dealAvgOrderValue);
|
||||
total.setTargetAmount(totalTargetAmount);
|
||||
total.setTargetOrderCount(totalTargetOrders);
|
||||
total.setSalesAmountAchievementRate(salesAchievementRate);
|
||||
total.setOrderCountAchievementRate(orderAchievementRate);
|
||||
total.setProductCost(totalProductCost);
|
||||
total.setShippingCost(totalShippingCost);
|
||||
total.setOtherCost(totalOtherCost);
|
||||
total.setOrderCost(totalCost);
|
||||
total.setRefundAmount(totalRefund);
|
||||
total.setTotalPromotionFee(totalPromoFee);
|
||||
total.setBrushFee(totalBrushFee);
|
||||
total.setFeeRatio(feeRatio);
|
||||
total.setTotalProfitBeforeTax(profitBeforeTax);
|
||||
total.setSalesTaxAmount(salesTax);
|
||||
total.setRoi(roi);
|
||||
total.setProfitAfterTax(profitAfterTax.setScale(2, RoundingMode.HALF_UP));
|
||||
return total;
|
||||
}
|
||||
|
||||
private double objToDouble(Object val) {
|
||||
if (val == null) {
|
||||
return 0;
|
||||
}
|
||||
if (val instanceof Number) {
|
||||
return ((Number) val).doubleValue();
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
private double objToPct(Object val) {
|
||||
if (val == null) {
|
||||
return 0;
|
||||
}
|
||||
if (val instanceof Number) {
|
||||
return ((Number) val).doubleValue();
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
private CellStyle createTitleStyle(Workbook workbook) {
|
||||
CellStyle style = workbook.createCellStyle();
|
||||
Font font = workbook.createFont();
|
||||
font.setBold(true);
|
||||
font.setFontHeightInPoints((short) 14);
|
||||
style.setFont(font);
|
||||
return style;
|
||||
}
|
||||
|
||||
private CellStyle createHeaderStyle(Workbook workbook) {
|
||||
CellStyle style = workbook.createCellStyle();
|
||||
Font font = workbook.createFont();
|
||||
font.setBold(true);
|
||||
style.setFont(font);
|
||||
style.setFillForegroundColor(IndexedColors.GREY_25_PERCENT.getIndex());
|
||||
style.setFillPattern(FillPatternType.SOLID_FOREGROUND);
|
||||
style.setBorderBottom(BorderStyle.THIN);
|
||||
style.setBorderTop(BorderStyle.THIN);
|
||||
style.setBorderLeft(BorderStyle.THIN);
|
||||
style.setBorderRight(BorderStyle.THIN);
|
||||
return style;
|
||||
}
|
||||
|
||||
private CellStyle createDataStyle(Workbook workbook) {
|
||||
CellStyle style = workbook.createCellStyle();
|
||||
style.setBorderBottom(BorderStyle.THIN);
|
||||
style.setBorderTop(BorderStyle.THIN);
|
||||
style.setBorderLeft(BorderStyle.THIN);
|
||||
style.setBorderRight(BorderStyle.THIN);
|
||||
return style;
|
||||
}
|
||||
|
||||
private CellStyle createBoldDataStyle(Workbook workbook) {
|
||||
CellStyle style = createDataStyle(workbook);
|
||||
Font font = workbook.createFont();
|
||||
font.setBold(true);
|
||||
style.setFont(font);
|
||||
return style;
|
||||
}
|
||||
|
||||
private void setCell(Row row, int col, String value, CellStyle style) {
|
||||
Cell cell = row.createCell(col);
|
||||
cell.setCellValue(value != null ? value : "");
|
||||
cell.setCellStyle(style);
|
||||
}
|
||||
|
||||
private void setCell(Row row, int col, double value, CellStyle style) {
|
||||
Cell cell = row.createCell(col);
|
||||
cell.setCellValue(value);
|
||||
cell.setCellStyle(style);
|
||||
}
|
||||
|
||||
@Override
|
||||
public byte[] exportPlatformOverviewFromTable(PlatformExportDTO dto, CompanyOverviewVO.PlatformOverview platformOverview, String summaryTitle) {
|
||||
return buildPlatformOverviewExcelBytes(dto, platformOverview, summaryTitle);
|
||||
}
|
||||
|
||||
private byte[] buildPlatformOverviewExcelBytes(
|
||||
PlatformExportDTO dto,
|
||||
CompanyOverviewVO.PlatformOverview platformOv,
|
||||
String summarySheetTitle) {
|
||||
BigDecimal taxRate = dto.getTaxRate() != null ? dto.getTaxRate() : DEFAULT_TAX_RATE;
|
||||
|
||||
List<CompanyOverviewVO.PlatformSummary> platforms = (platformOv != null && platformOv.getPlatforms() != null)
|
||||
? new ArrayList<>(platformOv.getPlatforms())
|
||||
: new ArrayList<>();
|
||||
if (dto.getPlatformCodes() != null && !dto.getPlatformCodes().isEmpty()) {
|
||||
Set<String> allowed = new HashSet<>(dto.getPlatformCodes());
|
||||
platforms = platforms.stream()
|
||||
.filter(p -> p.getPlatformCode() != null && allowed.contains(p.getPlatformCode()))
|
||||
.collect(Collectors.toList());
|
||||
}
|
||||
|
||||
List<Map<String, Object>> platformRows = platforms.stream()
|
||||
.map(this::platformSummaryToRowMap)
|
||||
.collect(Collectors.toList());
|
||||
boolean platformFiltered = dto.getPlatformCodes() != null && !dto.getPlatformCodes().isEmpty();
|
||||
CompanyOverviewVO.PlatformSummary totalPlatform = platformFiltered
|
||||
? aggregatePlatformSummariesForExport(platforms, taxRate)
|
||||
: (platformOv != null && platformOv.getTotal() != null
|
||||
? platformOv.getTotal()
|
||||
: aggregatePlatformSummariesForExport(platforms, taxRate));
|
||||
Map<String, Object> totalRowMap = platformSummaryToRowMap(totalPlatform);
|
||||
|
||||
LocalDate[] dateRange = exportStatusRangeHelper.parseDateRange(dto.getDateRange());
|
||||
String dateRangeLabel = dateRange[0].format(DATE_FMT) + " 至 " + dateRange[1].format(DATE_FMT);
|
||||
|
||||
try (Workbook workbook = new XSSFWorkbook()) {
|
||||
Sheet summarySheet = workbook.createSheet("汇总");
|
||||
createPlatformSummarySheet(
|
||||
summarySheet, summarySheetTitle, dateRangeLabel, platformRows, taxRate, totalRowMap);
|
||||
try (ByteArrayOutputStream out = new ByteArrayOutputStream()) {
|
||||
workbook.write(out);
|
||||
return out.toByteArray();
|
||||
}
|
||||
} catch (Exception e) {
|
||||
throw new BusinessException("导出平台Excel失败: " + e.getMessage());
|
||||
}
|
||||
}
|
||||
}
|
||||
+49
@@ -0,0 +1,49 @@
|
||||
package top.xyquan.ecomdmbbackend.modules.bi.overview.service.impl;
|
||||
|
||||
import org.springframework.stereotype.Component;
|
||||
import top.xyquan.ecomdmbbackend.common.exception.BusinessException;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.order.status.support.OrderStatusStatResolver;
|
||||
import top.xyquan.ecomdmbbackend.modules.ec.order.status.support.OrderStatusStatSets;
|
||||
|
||||
import java.time.LocalDate;
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* 导出共用的日期区间与订单状态 ID 解析
|
||||
*/
|
||||
@Component
|
||||
public class ExportStatusRangeHelper {
|
||||
|
||||
private final OrderStatusStatResolver orderStatusStatResolver;
|
||||
|
||||
public ExportStatusRangeHelper(OrderStatusStatResolver orderStatusStatResolver) {
|
||||
this.orderStatusStatResolver = orderStatusStatResolver;
|
||||
}
|
||||
|
||||
public LocalDate[] parseDateRange(List<LocalDate> dateRange) {
|
||||
if (dateRange.size() == 1) {
|
||||
return new LocalDate[]{dateRange.get(0), dateRange.get(0)};
|
||||
}
|
||||
LocalDate start = dateRange.get(0);
|
||||
LocalDate end = dateRange.get(1);
|
||||
if (start.isAfter(end)) {
|
||||
throw new BusinessException("开始日期不能晚于结束日期");
|
||||
}
|
||||
return new LocalDate[]{start, end};
|
||||
}
|
||||
|
||||
/**
|
||||
* 任一会参与统计的订单状态码(用于拉取订单并集)
|
||||
*/
|
||||
public List<String> getAutoStatusCodes(Long companyId) {
|
||||
return orderStatusStatResolver.resolve(companyId).getUnionStatusCodes();
|
||||
}
|
||||
|
||||
public List<String> getRefundStatusCodes(Long companyId) {
|
||||
return orderStatusStatResolver.resolve(companyId).getRefundStatusCodes();
|
||||
}
|
||||
|
||||
public OrderStatusStatSets resolveStat(Long companyId) {
|
||||
return orderStatusStatResolver.resolve(companyId);
|
||||
}
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user