feat: 促销系统完善、发票页重构、前端中文化、订单表迁移及多项优化
前端: - 发票页完整重构:智能按钮状态、防重复开票、空态引导、订单多选 - 全局中文化:Ant Design Vue locale配置、清除残留英文UI文本 - 新增关于我们、联系我们页面 - 首页活动专区、搜索页、Skill详情等多处优化 后端: - 订单模块:新增original_amount/promotion_deduct_amount字段及DB迁移 - 促销系统:完善促销规则、过期任务、批量查询等 - 新增RateLimit注解及拦截器、CORS过滤器、Health检查接口 - Logback日志配置、points枚举修复等
This commit is contained in:
13
openclaw-backend/openclaw-backend/.gitignore
vendored
Normal file
13
openclaw-backend/openclaw-backend/.gitignore
vendored
Normal file
@@ -0,0 +1,13 @@
|
||||
target/
|
||||
*.class
|
||||
*.jar
|
||||
*.war
|
||||
*.log
|
||||
.idea/
|
||||
*.iml
|
||||
.vscode/
|
||||
.settings/
|
||||
.project
|
||||
.classpath
|
||||
# 本地密钥配置(不提交)
|
||||
application-local.yml
|
||||
@@ -3,9 +3,10 @@ package com.openclaw;
|
||||
import org.mybatis.spring.annotation.MapperScan;
|
||||
import org.springframework.boot.SpringApplication;
|
||||
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||
import org.springframework.boot.autoconfigure.security.servlet.UserDetailsServiceAutoConfiguration;
|
||||
import org.springframework.scheduling.annotation.EnableScheduling;
|
||||
|
||||
@SpringBootApplication
|
||||
@SpringBootApplication(exclude = { UserDetailsServiceAutoConfiguration.class })
|
||||
@EnableScheduling
|
||||
@MapperScan({"com.openclaw.module.**.repository", "com.openclaw.common.leaf", "com.openclaw.common.compensation"})
|
||||
public class OpenclawApplication {
|
||||
|
||||
@@ -0,0 +1,24 @@
|
||||
package com.openclaw.annotation;
|
||||
|
||||
import java.lang.annotation.*;
|
||||
|
||||
/**
|
||||
* 接口限流注解,基于Redis滑动窗口实现
|
||||
* 可标注在Controller方法上,限制单个IP或用户的请求频率
|
||||
*/
|
||||
@Target(ElementType.METHOD)
|
||||
@Retention(RetentionPolicy.RUNTIME)
|
||||
@Documented
|
||||
public @interface RateLimit {
|
||||
/** 时间窗口(秒) */
|
||||
int window() default 60;
|
||||
|
||||
/** 窗口内最大请求数 */
|
||||
int maxRequests() default 10;
|
||||
|
||||
/** 限流维度:ip / user / ip+uri(默认按IP+URI) */
|
||||
String key() default "ip+uri";
|
||||
|
||||
/** 被限流时的提示消息 */
|
||||
String message() default "请求过于频繁,请稍后再试";
|
||||
}
|
||||
@@ -30,6 +30,14 @@ public class InviteEventConsumer {
|
||||
log.info("[MQ] 邀请绑定成功: inviterId={}, inviteeId={}, code={}",
|
||||
event.getInviterId(), event.getInviteeId(), event.getInviteCode());
|
||||
|
||||
// 幂等:检查奖励是否已发放,防止MQ重试导致重复发积分
|
||||
InviteRecord record = inviteRecordRepo.selectById(event.getInviteRecordId());
|
||||
if (record != null && Boolean.TRUE.equals(record.getRewardGiven())) {
|
||||
log.info("[MQ] 邀请奖励已发放,跳过: recordId={}", event.getInviteRecordId());
|
||||
channel.basicAck(tag, false);
|
||||
return;
|
||||
}
|
||||
|
||||
// 发放邀请人积分
|
||||
if (event.getInviterPoints() != null && event.getInviterPoints() > 0) {
|
||||
inviteService.addPointsDirectly(event.getInviterId(), event.getInviterPoints(),
|
||||
@@ -43,7 +51,6 @@ public class InviteEventConsumer {
|
||||
}
|
||||
|
||||
// 标记奖励已发放
|
||||
InviteRecord record = inviteRecordRepo.selectById(event.getInviteRecordId());
|
||||
if (record != null) {
|
||||
record.setRewardGiven(true);
|
||||
record.setRewardedAt(java.time.LocalDateTime.now());
|
||||
@@ -54,7 +61,8 @@ public class InviteEventConsumer {
|
||||
} catch (Exception e) {
|
||||
log.error("[MQ] 处理邀请积分发放失败: inviterId={}, inviteeId={}",
|
||||
event.getInviterId(), event.getInviteeId(), e);
|
||||
channel.basicNack(tag, false, false);
|
||||
boolean redelivered = message.getMessageProperties().getRedelivered();
|
||||
channel.basicNack(tag, false, !redelivered);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -70,7 +78,8 @@ public class InviteEventConsumer {
|
||||
channel.basicAck(tag, false);
|
||||
} catch (Exception e) {
|
||||
log.error("[MQ] 处理邀请码过期失败: inviterId={}", event.getInviterId(), e);
|
||||
channel.basicNack(tag, false, false);
|
||||
boolean redelivered = message.getMessageProperties().getRedelivered();
|
||||
channel.basicNack(tag, false, !redelivered);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -59,7 +59,14 @@ public class OrderEventConsumer {
|
||||
channel.basicAck(tag, false);
|
||||
} catch (Exception e) {
|
||||
log.error("[MQ] 处理订单支付失败: orderId={}", event.getOrderId(), e);
|
||||
channel.basicNack(tag, false, false);
|
||||
boolean redelivered = message.getMessageProperties().getRedelivered();
|
||||
if (!redelivered) {
|
||||
log.warn("[MQ] 订单支付消息将重入队重试: orderId={}", event.getOrderId());
|
||||
channel.basicNack(tag, false, true);
|
||||
} else {
|
||||
log.error("[MQ] 订单支付消息重试仍失败,放弃: orderId={}", event.getOrderId());
|
||||
channel.basicNack(tag, false, false);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -75,7 +82,8 @@ public class OrderEventConsumer {
|
||||
channel.basicAck(tag, false);
|
||||
} catch (Exception e) {
|
||||
log.error("[MQ] 处理订单超时失败: orderId={}", event.getOrderId(), e);
|
||||
channel.basicNack(tag, false, false);
|
||||
boolean redelivered = message.getMessageProperties().getRedelivered();
|
||||
channel.basicNack(tag, false, !redelivered);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -92,7 +100,8 @@ public class OrderEventConsumer {
|
||||
channel.basicAck(tag, false);
|
||||
} catch (Exception e) {
|
||||
log.error("[MQ] 处理订单取消失败: orderNo={}", orderNo, e);
|
||||
channel.basicNack(tag, false, false);
|
||||
boolean redelivered = message.getMessageProperties().getRedelivered();
|
||||
channel.basicNack(tag, false, !redelivered);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -47,7 +47,8 @@ public class PaymentEventConsumer {
|
||||
channel.basicAck(tag, false);
|
||||
} catch (Exception e) {
|
||||
log.error("[MQ] 处理充值积分发放失败: rechargeOrderId={}", event.getRechargeOrderId(), e);
|
||||
channel.basicNack(tag, false, false);
|
||||
boolean redelivered = message.getMessageProperties().getRedelivered();
|
||||
channel.basicNack(tag, false, !redelivered);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -69,7 +70,8 @@ public class PaymentEventConsumer {
|
||||
channel.basicAck(tag, false);
|
||||
} catch (Exception e) {
|
||||
log.error("[MQ] 处理充值超时失败: rechargeOrderNo={}", rechargeOrderNo, e);
|
||||
channel.basicNack(tag, false, false);
|
||||
boolean redelivered = message.getMessageProperties().getRedelivered();
|
||||
channel.basicNack(tag, false, !redelivered);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -121,7 +123,8 @@ public class PaymentEventConsumer {
|
||||
channel.basicAck(tag, false);
|
||||
} catch (Exception e) {
|
||||
log.error("[MQ] 处理退款失败: refundId={}", event.getRefundId(), e);
|
||||
channel.basicNack(tag, false, false);
|
||||
boolean redelivered = message.getMessageProperties().getRedelivered();
|
||||
channel.basicNack(tag, false, !redelivered);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -137,7 +140,8 @@ public class PaymentEventConsumer {
|
||||
channel.basicAck(tag, false);
|
||||
} catch (Exception e) {
|
||||
log.error("[MQ] 处理退款超时提醒失败: refundId={}", refundIdStr, e);
|
||||
channel.basicNack(tag, false, false);
|
||||
boolean redelivered = message.getMessageProperties().getRedelivered();
|
||||
channel.basicNack(tag, false, !redelivered);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -45,7 +45,15 @@ public class UserEventConsumer {
|
||||
channel.basicAck(tag, false);
|
||||
} catch (Exception e) {
|
||||
log.error("[MQ] 处理用户注册失败: userId={}", event.getUserId(), e);
|
||||
channel.basicNack(tag, false, false);
|
||||
// 首次失败允许重入队重试,重试仍失败则放弃(进死信队列)
|
||||
boolean redelivered = message.getMessageProperties().getRedelivered();
|
||||
if (!redelivered) {
|
||||
log.warn("[MQ] 用户注册消息将重入队重试: userId={}", event.getUserId());
|
||||
channel.basicNack(tag, false, true);
|
||||
} else {
|
||||
log.error("[MQ] 用户注册消息重试仍失败,放弃处理: userId={}", event.getUserId());
|
||||
channel.basicNack(tag, false, false);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,39 @@
|
||||
package com.openclaw.config;
|
||||
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.web.cors.CorsConfiguration;
|
||||
import org.springframework.web.cors.CorsConfigurationSource;
|
||||
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
/**
|
||||
* CORS 配置源(由 Spring Security 的 CorsFilter 统一处理)
|
||||
* 解决 OPTIONS 预检请求被拦截导致跨域失败的问题
|
||||
*/
|
||||
@Configuration
|
||||
public class CorsFilterConfig {
|
||||
|
||||
@Bean
|
||||
public CorsConfigurationSource corsConfigurationSource() {
|
||||
CorsConfiguration config = new CorsConfiguration();
|
||||
config.setAllowedOriginPatterns(List.of(
|
||||
"http://localhost:*",
|
||||
"http://127.0.0.1:*",
|
||||
"http://192.168.*.*:*",
|
||||
"http://10.*.*.*:*",
|
||||
"http://172.16.*.*:*",
|
||||
"https://*.openclaw.com"
|
||||
));
|
||||
config.setAllowedMethods(List.of("GET", "POST", "PUT", "DELETE", "OPTIONS", "PATCH"));
|
||||
config.setAllowedHeaders(List.of("*"));
|
||||
config.setExposedHeaders(List.of("Authorization", "Content-Disposition"));
|
||||
config.setAllowCredentials(true);
|
||||
config.setMaxAge(3600L);
|
||||
|
||||
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
|
||||
source.registerCorsConfiguration("/**", config);
|
||||
return source;
|
||||
}
|
||||
}
|
||||
@@ -3,9 +3,12 @@ package com.openclaw.config;
|
||||
import io.swagger.v3.oas.models.OpenAPI;
|
||||
import io.swagger.v3.oas.models.info.Contact;
|
||||
import io.swagger.v3.oas.models.info.Info;
|
||||
import io.swagger.v3.oas.models.info.License;
|
||||
import io.swagger.v3.oas.models.security.SecurityRequirement;
|
||||
import io.swagger.v3.oas.models.security.SecurityScheme;
|
||||
import io.swagger.v3.oas.models.Components;
|
||||
import io.swagger.v3.oas.models.ExternalDocumentation;
|
||||
import org.springdoc.core.models.GroupedOpenApi;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
|
||||
@@ -16,12 +19,23 @@ public class OpenApiConfig {
|
||||
public OpenAPI openAPI() {
|
||||
return new OpenAPI()
|
||||
.info(new Info()
|
||||
.title("OpenClaw Skills Platform API")
|
||||
.description("数字员工交易平台后端接口文档")
|
||||
.title("OpenClaw Skills 数字员工平台 API")
|
||||
.description("OpenClaw 数字员工交易平台完整后端接口文档。\n\n"
|
||||
+ "## 认证方式\n"
|
||||
+ "- 用户端接口:登录后获取 JWT Token,在请求头中添加 `Authorization: Bearer {token}`\n"
|
||||
+ "- 管理端接口:管理员登录后获取 Admin Token,同样使用 Bearer 认证\n"
|
||||
+ "- 公开接口:无需认证,如技能列表、分类、注册登录等\n\n"
|
||||
+ "## 通用响应格式\n"
|
||||
+ "```json\n{\"code\": 200, \"message\": \"success\", \"data\": {}}\n```")
|
||||
.version("1.0.0")
|
||||
.contact(new Contact()
|
||||
.name("OpenClaw Team")
|
||||
.email("dev@openclaw.com")))
|
||||
.email("dev@openclaw.com"))
|
||||
.license(new License()
|
||||
.name("MIT")))
|
||||
.externalDocs(new ExternalDocumentation()
|
||||
.description("OpenClaw Skills 平台文档")
|
||||
.url("https://docs.openclaw.com"))
|
||||
.addSecurityItem(new SecurityRequirement().addList("Bearer Token"))
|
||||
.components(new Components()
|
||||
.addSecuritySchemes("Bearer Token",
|
||||
@@ -29,6 +43,32 @@ public class OpenApiConfig {
|
||||
.type(SecurityScheme.Type.HTTP)
|
||||
.scheme("bearer")
|
||||
.bearerFormat("JWT")
|
||||
.description("JWT 认证令牌,登录后获取")));
|
||||
.description("JWT 认证令牌。用户调用 POST /api/v1/users/login 获取,"
|
||||
+ "管理员调用 POST /api/v1/admin/login 获取。")));
|
||||
}
|
||||
|
||||
@Bean
|
||||
public GroupedOpenApi userApi() {
|
||||
return GroupedOpenApi.builder()
|
||||
.group("1-用户端接口")
|
||||
.pathsToMatch("/api/v1/**")
|
||||
.pathsToExclude("/api/v1/admin/**")
|
||||
.build();
|
||||
}
|
||||
|
||||
@Bean
|
||||
public GroupedOpenApi adminApi() {
|
||||
return GroupedOpenApi.builder()
|
||||
.group("2-管理端接口")
|
||||
.pathsToMatch("/api/v1/admin/**")
|
||||
.build();
|
||||
}
|
||||
|
||||
@Bean
|
||||
public GroupedOpenApi allApi() {
|
||||
return GroupedOpenApi.builder()
|
||||
.group("0-全部接口")
|
||||
.pathsToMatch("/api/**")
|
||||
.build();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,6 +2,7 @@ package com.openclaw.config;
|
||||
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.security.config.Customizer;
|
||||
import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity;
|
||||
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
|
||||
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
|
||||
@@ -23,6 +24,7 @@ public class SecurityConfig {
|
||||
@Bean
|
||||
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
|
||||
http
|
||||
.cors(Customizer.withDefaults())
|
||||
.csrf(csrf -> csrf.disable())
|
||||
.sessionManagement(sm -> sm.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
|
||||
.authorizeHttpRequests(auth -> auth
|
||||
|
||||
@@ -3,6 +3,7 @@ package com.openclaw.config;
|
||||
import com.openclaw.interceptor.AuthInterceptor;
|
||||
import com.openclaw.interceptor.OptionalAuthInterceptor;
|
||||
import com.openclaw.interceptor.PermissionCheckInterceptor;
|
||||
import com.openclaw.interceptor.RateLimitInterceptor;
|
||||
import com.openclaw.interceptor.RoleCheckInterceptor;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
@@ -15,6 +16,7 @@ import java.nio.file.Paths;
|
||||
@RequiredArgsConstructor
|
||||
public class WebMvcConfig implements WebMvcConfigurer {
|
||||
|
||||
private final RateLimitInterceptor rateLimitInterceptor;
|
||||
private final OptionalAuthInterceptor optionalAuthInterceptor;
|
||||
private final AuthInterceptor authInterceptor;
|
||||
private final RoleCheckInterceptor roleCheckInterceptor;
|
||||
@@ -30,22 +32,15 @@ public class WebMvcConfig implements WebMvcConfigurer {
|
||||
.addResourceLocations(absolutePath);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void addCorsMappings(CorsRegistry registry) {
|
||||
registry.addMapping("/api/**")
|
||||
.allowedOriginPatterns("http://localhost:*", "https://*.openclaw.com")
|
||||
.allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS")
|
||||
.allowedHeaders("*")
|
||||
.allowCredentials(true)
|
||||
.maxAge(3600);
|
||||
registry.addMapping("/uploads/**")
|
||||
.allowedOriginPatterns("http://localhost:*", "https://*.openclaw.com")
|
||||
.allowedMethods("GET")
|
||||
.maxAge(3600);
|
||||
}
|
||||
// CORS 已移至 CorsFilterConfig(Servlet Filter 层级),避免被 Interceptor 拦截 OPTIONS 预检请求
|
||||
|
||||
@Override
|
||||
public void addInterceptors(InterceptorRegistry registry) {
|
||||
// 限流拦截器:最先执行,防止暴力攻击
|
||||
registry.addInterceptor(rateLimitInterceptor)
|
||||
.addPathPatterns("/api/**")
|
||||
.order(-1);
|
||||
|
||||
// 可选认证:公开接口中尝试提取用户身份(不阻断请求)
|
||||
registry.addInterceptor(optionalAuthInterceptor)
|
||||
.addPathPatterns("/api/**")
|
||||
@@ -75,7 +70,9 @@ public class WebMvcConfig implements WebMvcConfigurer {
|
||||
"/api/v1/config/**", // 系统配置(充值档位、积分规则)
|
||||
"/api/v1/share/**", // 分享JS-SDK配置(公开)
|
||||
"/api/v1/activities", // 活动列表(公开)
|
||||
"/api/v1/activities/*" // 活动详情(公开)
|
||||
"/api/v1/activities/*", // 活动详情(公开)
|
||||
"/api/v1/health", // 健康检查(存活探针)
|
||||
"/api/v1/health/**" // 健康检查(就绪探针)
|
||||
);
|
||||
|
||||
// 角色权限拦截器,在认证之后执行
|
||||
|
||||
@@ -18,6 +18,8 @@ public interface ErrorCode {
|
||||
BusinessError SKILL_NOT_FOUND = new BusinessError(2001, "Skill不存在");
|
||||
BusinessError SKILL_OFFLINE = new BusinessError(2002, "Skill已下架");
|
||||
BusinessError SKILL_ALREADY_OWNED = new BusinessError(2003, "已拥有该Skill");
|
||||
BusinessError REVIEW_NOT_ALLOWED = new BusinessError(2004, "您尚未获取此Skill,无法评价");
|
||||
BusinessError REVIEW_DUPLICATE = new BusinessError(2005, "您已经评价过此Skill");
|
||||
|
||||
// 积分模块 3xxx
|
||||
BusinessError POINTS_NOT_ENOUGH = new BusinessError(3001, "积分不足");
|
||||
|
||||
@@ -6,6 +6,7 @@ import com.openclaw.util.JwtUtil;
|
||||
import com.openclaw.util.UserContext;
|
||||
import jakarta.servlet.http.*;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.data.redis.core.StringRedisTemplate;
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.springframework.web.servlet.HandlerInterceptor;
|
||||
|
||||
@@ -14,6 +15,7 @@ import org.springframework.web.servlet.HandlerInterceptor;
|
||||
public class AuthInterceptor implements HandlerInterceptor {
|
||||
|
||||
private final JwtUtil jwtUtil;
|
||||
private final StringRedisTemplate redisTemplate;
|
||||
|
||||
@Override
|
||||
public boolean preHandle(HttpServletRequest req,
|
||||
@@ -24,9 +26,24 @@ public class AuthInterceptor implements HandlerInterceptor {
|
||||
throw new BusinessException(ErrorCode.UNAUTHORIZED);
|
||||
try {
|
||||
String token = auth.substring(7);
|
||||
// 检查 token 是否已被登出(Redis 黑名单)
|
||||
if (Boolean.TRUE.equals(redisTemplate.hasKey("user:token:" + token))) {
|
||||
throw new BusinessException(ErrorCode.UNAUTHORIZED);
|
||||
}
|
||||
Long userId = jwtUtil.getUserId(token);
|
||||
String role = jwtUtil.getRole(token);
|
||||
// 检查用户是否已换号(换号后所有旧 token 失效)
|
||||
String phoneChanged = redisTemplate.opsForValue().get("user:phone_changed:" + userId);
|
||||
if (phoneChanged != null) {
|
||||
long changedAt = Long.parseLong(phoneChanged);
|
||||
long tokenIssuedAt = jwtUtil.parse(token).getIssuedAt().getTime();
|
||||
if (tokenIssuedAt < changedAt) {
|
||||
throw new BusinessException(ErrorCode.UNAUTHORIZED);
|
||||
}
|
||||
}
|
||||
UserContext.set(userId, role);
|
||||
} catch (BusinessException e) {
|
||||
throw e;
|
||||
} catch (Exception e) {
|
||||
throw new BusinessException(ErrorCode.UNAUTHORIZED);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,71 @@
|
||||
package com.openclaw.interceptor;
|
||||
|
||||
import com.openclaw.annotation.RateLimit;
|
||||
import com.openclaw.exception.BusinessException;
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import jakarta.servlet.http.HttpServletResponse;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.data.redis.core.StringRedisTemplate;
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.springframework.web.method.HandlerMethod;
|
||||
import org.springframework.web.servlet.HandlerInterceptor;
|
||||
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
@Slf4j
|
||||
@Component
|
||||
@RequiredArgsConstructor
|
||||
public class RateLimitInterceptor implements HandlerInterceptor {
|
||||
|
||||
private final StringRedisTemplate redisTemplate;
|
||||
|
||||
@Override
|
||||
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
|
||||
if (!(handler instanceof HandlerMethod handlerMethod)) {
|
||||
return true;
|
||||
}
|
||||
RateLimit rateLimit = handlerMethod.getMethodAnnotation(RateLimit.class);
|
||||
if (rateLimit == null) {
|
||||
return true;
|
||||
}
|
||||
|
||||
String key = buildKey(request, rateLimit);
|
||||
int window = rateLimit.window();
|
||||
int maxRequests = rateLimit.maxRequests();
|
||||
|
||||
Long count = redisTemplate.opsForValue().increment(key);
|
||||
if (count != null && count == 1) {
|
||||
redisTemplate.expire(key, window, TimeUnit.SECONDS);
|
||||
}
|
||||
if (count != null && count > maxRequests) {
|
||||
log.warn("限流触发: key={}, count={}, max={}", key, count, maxRequests);
|
||||
throw new BusinessException(429, rateLimit.message());
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
private String buildKey(HttpServletRequest request, RateLimit rateLimit) {
|
||||
String ip = getClientIp(request);
|
||||
String uri = request.getRequestURI();
|
||||
return switch (rateLimit.key()) {
|
||||
case "ip" -> "rate_limit:" + ip;
|
||||
case "user" -> "rate_limit:user:" + request.getAttribute("userId");
|
||||
default -> "rate_limit:" + ip + ":" + uri;
|
||||
};
|
||||
}
|
||||
|
||||
private String getClientIp(HttpServletRequest request) {
|
||||
String ip = request.getHeader("X-Forwarded-For");
|
||||
if (ip != null && !ip.isEmpty()) {
|
||||
ip = ip.split(",")[0].trim();
|
||||
}
|
||||
if (ip == null || ip.isEmpty()) {
|
||||
ip = request.getHeader("X-Real-IP");
|
||||
}
|
||||
if (ip == null || ip.isEmpty()) {
|
||||
ip = request.getRemoteAddr();
|
||||
}
|
||||
return ip;
|
||||
}
|
||||
}
|
||||
@@ -3,11 +3,13 @@ package com.openclaw.module.activity.controller;
|
||||
import com.openclaw.common.Result;
|
||||
import com.openclaw.module.activity.service.ActivityService;
|
||||
import com.openclaw.module.activity.vo.ActivityVO;
|
||||
import io.swagger.v3.oas.annotations.tags.Tag;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
@Tag(name = "活动", description = "查询进行中的活动")
|
||||
@RestController
|
||||
@RequestMapping("/api/v1/activities")
|
||||
@RequiredArgsConstructor
|
||||
|
||||
@@ -8,9 +8,11 @@ import com.openclaw.module.activity.service.ActivityService;
|
||||
import com.openclaw.module.activity.vo.ActivityVO;
|
||||
import jakarta.validation.Valid;
|
||||
import com.openclaw.annotation.RequiresRole;
|
||||
import io.swagger.v3.oas.annotations.tags.Tag;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
|
||||
@Tag(name = "[管理] 活动管理", description = "管理端-创建/编辑/删除/查询活动")
|
||||
@RestController
|
||||
@RequestMapping("/api/v1/admin/activities")
|
||||
@RequiresRole({"admin", "super_admin"})
|
||||
|
||||
@@ -1,11 +1,13 @@
|
||||
package com.openclaw.module.admin.controller;
|
||||
|
||||
import com.baomidou.mybatisplus.core.metadata.IPage;
|
||||
import com.openclaw.annotation.RateLimit;
|
||||
import com.openclaw.annotation.RequiresRole;
|
||||
import com.openclaw.module.log.annotation.OpLog;
|
||||
import com.openclaw.common.Result;
|
||||
import com.openclaw.module.admin.dto.AdminLoginDTO;
|
||||
import com.openclaw.module.admin.dto.AdminSkillCreateDTO;
|
||||
import com.openclaw.module.admin.dto.AdminSkillUpdateDTO;
|
||||
import com.openclaw.module.admin.service.AdminService;
|
||||
import com.openclaw.module.admin.vo.*;
|
||||
import com.openclaw.module.customization.entity.CustomizationRequest;
|
||||
@@ -14,9 +16,11 @@ import com.openclaw.module.developer.entity.DeveloperApplication;
|
||||
import com.openclaw.module.developer.service.DeveloperApplicationService;
|
||||
import com.openclaw.util.UserContext;
|
||||
import jakarta.validation.Valid;
|
||||
import io.swagger.v3.oas.annotations.tags.Tag;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
|
||||
@Tag(name = "[管理] 后台总控", description = "管理员登录、用户/技能/订单/退款/开发者/定制需求管理")
|
||||
@RestController
|
||||
@RequestMapping("/api/v1/admin")
|
||||
@RequiredArgsConstructor
|
||||
@@ -28,6 +32,7 @@ public class AdminController {
|
||||
|
||||
// ==================== 登录(无需权限) ====================
|
||||
|
||||
@RateLimit(window = 60, maxRequests = 5, message = "登录请求过于频繁,请稍后再试")
|
||||
@PostMapping("/login")
|
||||
public Result<AdminLoginVO> login(@Valid @RequestBody AdminLoginDTO dto) {
|
||||
return Result.ok(adminService.login(dto));
|
||||
@@ -152,6 +157,15 @@ public class AdminController {
|
||||
return Result.ok(adminService.createSkill(UserContext.getUserId(), dto));
|
||||
}
|
||||
|
||||
@PutMapping("/skills/{skillId}")
|
||||
@RequiresRole("super_admin")
|
||||
@OpLog(module = "skill", action = "update", description = "后台编辑Skill", targetType = "skill")
|
||||
public Result<AdminSkillVO> updateSkill(
|
||||
@PathVariable Long skillId,
|
||||
@RequestBody AdminSkillUpdateDTO dto) {
|
||||
return Result.ok(adminService.updateSkill(skillId, dto));
|
||||
}
|
||||
|
||||
// ==================== 订单管理 ====================
|
||||
|
||||
@GetMapping("/orders")
|
||||
|
||||
@@ -0,0 +1,17 @@
|
||||
package com.openclaw.module.admin.dto;
|
||||
|
||||
import lombok.Data;
|
||||
import java.math.BigDecimal;
|
||||
|
||||
@Data
|
||||
public class AdminSkillUpdateDTO {
|
||||
private String name;
|
||||
private String description;
|
||||
private String coverImageUrl;
|
||||
private Integer categoryId;
|
||||
private BigDecimal price;
|
||||
private Boolean isFree;
|
||||
private String version;
|
||||
private String fileUrl;
|
||||
private String status;
|
||||
}
|
||||
@@ -3,6 +3,7 @@ package com.openclaw.module.admin.service;
|
||||
import com.baomidou.mybatisplus.core.metadata.IPage;
|
||||
import com.openclaw.module.admin.dto.AdminLoginDTO;
|
||||
import com.openclaw.module.admin.dto.AdminSkillCreateDTO;
|
||||
import com.openclaw.module.admin.dto.AdminSkillUpdateDTO;
|
||||
import com.openclaw.module.admin.vo.*;
|
||||
|
||||
public interface AdminService {
|
||||
@@ -27,6 +28,7 @@ public interface AdminService {
|
||||
void offlineSkill(Long skillId);
|
||||
void toggleFeatured(Long skillId);
|
||||
AdminSkillVO createSkill(Long adminUserId, AdminSkillCreateDTO dto);
|
||||
AdminSkillVO updateSkill(Long skillId, AdminSkillUpdateDTO dto);
|
||||
|
||||
// 订单管理
|
||||
IPage<AdminOrderVO> listOrders(String keyword, String status, int pageNum, int pageSize);
|
||||
|
||||
@@ -7,6 +7,7 @@ import com.openclaw.constant.ErrorCode;
|
||||
import com.openclaw.exception.BusinessException;
|
||||
import com.openclaw.module.admin.dto.AdminLoginDTO;
|
||||
import com.openclaw.module.admin.dto.AdminSkillCreateDTO;
|
||||
import com.openclaw.module.admin.dto.AdminSkillUpdateDTO;
|
||||
import com.openclaw.module.admin.service.AdminService;
|
||||
import com.openclaw.module.admin.vo.*;
|
||||
import com.openclaw.common.event.RefundApprovedEvent;
|
||||
@@ -236,9 +237,14 @@ public class AdminServiceImpl implements AdminService {
|
||||
log.info("[Admin] 解封用户: userId={}", userId);
|
||||
}
|
||||
|
||||
private static final java.util.Set<String> VALID_ROLES = java.util.Set.of("user", "creator", "admin", "super_admin");
|
||||
|
||||
@Override
|
||||
@Transactional
|
||||
public void changeUserRole(Long userId, String role) {
|
||||
if (!VALID_ROLES.contains(role)) {
|
||||
throw new BusinessException(ErrorCode.PARAM_ERROR.code(), "非法角色值: " + role);
|
||||
}
|
||||
User user = userRepo.selectById(userId);
|
||||
if (user == null) throw new BusinessException(ErrorCode.USER_NOT_FOUND);
|
||||
user.setRole(role);
|
||||
@@ -348,6 +354,32 @@ public class AdminServiceImpl implements AdminService {
|
||||
return toAdminSkillVO(skill);
|
||||
}
|
||||
|
||||
@Override
|
||||
@Transactional
|
||||
public AdminSkillVO updateSkill(Long skillId, AdminSkillUpdateDTO dto) {
|
||||
Skill skill = skillRepo.selectById(skillId);
|
||||
if (skill == null) throw new BusinessException(ErrorCode.SKILL_NOT_FOUND);
|
||||
|
||||
if (dto.getName() != null) skill.setName(dto.getName());
|
||||
if (dto.getDescription() != null) skill.setDescription(dto.getDescription());
|
||||
if (dto.getCoverImageUrl() != null) skill.setCoverImageUrl(dto.getCoverImageUrl());
|
||||
if (dto.getCategoryId() != null) skill.setCategoryId(dto.getCategoryId());
|
||||
if (dto.getPrice() != null) skill.setPrice(dto.getPrice());
|
||||
if (dto.getIsFree() != null) skill.setIsFree(dto.getIsFree());
|
||||
if (dto.getVersion() != null) skill.setVersion(dto.getVersion());
|
||||
if (dto.getFileUrl() != null) skill.setFileUrl(dto.getFileUrl());
|
||||
if (dto.getStatus() != null) {
|
||||
if (!java.util.Set.of("draft", "pending", "approved", "rejected", "offline").contains(dto.getStatus())) {
|
||||
throw new BusinessException(ErrorCode.PARAM_ERROR.code(), "非法Skill状态值: " + dto.getStatus());
|
||||
}
|
||||
skill.setStatus(dto.getStatus());
|
||||
}
|
||||
|
||||
skillRepo.updateById(skill);
|
||||
log.info("[Admin] 管理员编辑Skill: skillId={}, name={}", skill.getId(), skill.getName());
|
||||
return toAdminSkillVO(skill);
|
||||
}
|
||||
|
||||
// ==================== 订单管理 ====================
|
||||
|
||||
@Override
|
||||
|
||||
@@ -4,6 +4,7 @@ import com.openclaw.common.Result;
|
||||
import com.openclaw.module.payment.config.RechargeConfig;
|
||||
import com.openclaw.module.points.entity.PointsRule;
|
||||
import com.openclaw.module.points.repository.PointsRuleRepository;
|
||||
import io.swagger.v3.oas.annotations.tags.Tag;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
@@ -14,6 +15,7 @@ import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
@Tag(name = "公共配置", description = "充值选项、积分规则等公共配置")
|
||||
@RestController
|
||||
@RequestMapping("/api/v1/config")
|
||||
@RequiredArgsConstructor
|
||||
|
||||
@@ -7,6 +7,7 @@ import com.openclaw.util.UserContext;
|
||||
import com.qcloud.cos.COSClient;
|
||||
import com.qcloud.cos.model.ObjectMetadata;
|
||||
import com.qcloud.cos.model.PutObjectRequest;
|
||||
import io.swagger.v3.oas.annotations.tags.Tag;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
@@ -23,6 +24,7 @@ import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.UUID;
|
||||
|
||||
@Tag(name = "文件上传", description = "图片/文件上传到COS")
|
||||
@Slf4j
|
||||
@RestController
|
||||
@RequestMapping("/api/v1/upload")
|
||||
|
||||
@@ -0,0 +1,70 @@
|
||||
package com.openclaw.module.common.controller;
|
||||
|
||||
import com.openclaw.common.Result;
|
||||
import io.swagger.v3.oas.annotations.tags.Tag;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.data.redis.core.StringRedisTemplate;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
import javax.sql.DataSource;
|
||||
import java.sql.Connection;
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.Map;
|
||||
|
||||
@Tag(name = "健康检查", description = "服务健康状态、数据库/Redis连通性检查")
|
||||
@RestController
|
||||
@RequestMapping("/api/v1/health")
|
||||
@RequiredArgsConstructor
|
||||
public class HealthController {
|
||||
|
||||
private final DataSource dataSource;
|
||||
private final StringRedisTemplate redisTemplate;
|
||||
|
||||
@Value("${spring.application.name:openclaw-backend}")
|
||||
private String appName;
|
||||
|
||||
/** 基础存活探针(无依赖检查) */
|
||||
@GetMapping
|
||||
public Result<Map<String, Object>> health() {
|
||||
Map<String, Object> info = new LinkedHashMap<>();
|
||||
info.put("status", "UP");
|
||||
info.put("app", appName);
|
||||
info.put("time", LocalDateTime.now().toString());
|
||||
return Result.ok(info);
|
||||
}
|
||||
|
||||
/** 深度就绪探针(检查 DB + Redis) */
|
||||
@GetMapping("/ready")
|
||||
public Result<Map<String, Object>> readiness() {
|
||||
Map<String, Object> info = new LinkedHashMap<>();
|
||||
info.put("app", appName);
|
||||
info.put("time", LocalDateTime.now().toString());
|
||||
|
||||
// DB check
|
||||
try (Connection conn = dataSource.getConnection()) {
|
||||
conn.createStatement().execute("SELECT 1");
|
||||
info.put("db", "UP");
|
||||
} catch (Exception e) {
|
||||
info.put("db", "DOWN: " + e.getMessage());
|
||||
}
|
||||
|
||||
// Redis check
|
||||
try {
|
||||
var factory = redisTemplate.getConnectionFactory();
|
||||
if (factory == null) throw new IllegalStateException("Redis ConnectionFactory is null");
|
||||
String pong = factory.getConnection().ping();
|
||||
info.put("redis", pong != null ? "UP" : "DOWN");
|
||||
} catch (Exception e) {
|
||||
info.put("redis", "DOWN: " + e.getMessage());
|
||||
}
|
||||
|
||||
boolean allUp = "UP".equals(info.get("db")) && "UP".equals(info.get("redis"));
|
||||
info.put("status", allUp ? "UP" : "DEGRADED");
|
||||
|
||||
return Result.ok(info);
|
||||
}
|
||||
}
|
||||
@@ -5,6 +5,7 @@ import com.openclaw.common.Result;
|
||||
import com.openclaw.module.order.repository.OrderRepository;
|
||||
import com.openclaw.module.skill.repository.SkillRepository;
|
||||
import com.openclaw.module.user.repository.UserRepository;
|
||||
import io.swagger.v3.oas.annotations.tags.Tag;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
@@ -13,6 +14,7 @@ import org.springframework.web.bind.annotation.RestController;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
@Tag(name = "统计数据", description = "平台概览统计")
|
||||
@RestController
|
||||
@RequestMapping("/api/v1/stats")
|
||||
@RequiredArgsConstructor
|
||||
|
||||
@@ -10,6 +10,7 @@ import com.openclaw.module.community.repository.CommunityJoinRequestRepository;
|
||||
import com.openclaw.module.coupon.dto.CouponIssueDTO;
|
||||
import com.openclaw.module.coupon.service.CouponService;
|
||||
import com.openclaw.util.UserContext;
|
||||
import io.swagger.v3.oas.annotations.tags.Tag;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
@@ -18,6 +19,7 @@ import java.time.LocalDateTime;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
@Tag(name = "[管理] 社区管理", description = "管理端-社群申请审核、批量发券")
|
||||
@Slf4j
|
||||
@RestController
|
||||
@RequestMapping("/api/v1/admin/community")
|
||||
|
||||
@@ -5,12 +5,14 @@ import com.openclaw.common.Result;
|
||||
import com.openclaw.module.community.entity.CommunityJoinRequest;
|
||||
import com.openclaw.module.community.repository.CommunityJoinRequestRepository;
|
||||
import com.openclaw.util.UserContext;
|
||||
import io.swagger.v3.oas.annotations.tags.Tag;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
import java.util.Map;
|
||||
|
||||
@Tag(name = "社区", description = "社群加入申请")
|
||||
@RestController
|
||||
@RequestMapping("/api/v1/community")
|
||||
@RequiredArgsConstructor
|
||||
|
||||
@@ -9,11 +9,13 @@ import com.openclaw.module.content.service.AnnouncementService;
|
||||
import com.openclaw.module.content.vo.AnnouncementVO;
|
||||
import com.openclaw.util.UserContext;
|
||||
import jakarta.validation.Valid;
|
||||
import io.swagger.v3.oas.annotations.tags.Tag;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
@Tag(name = "公告管理", description = "公告列表、创建/编辑/删除公告")
|
||||
@RestController
|
||||
@RequiredArgsConstructor
|
||||
public class AnnouncementController {
|
||||
|
||||
@@ -9,11 +9,13 @@ import com.openclaw.module.content.service.BannerService;
|
||||
import com.openclaw.module.content.vo.BannerVO;
|
||||
import com.openclaw.util.UserContext;
|
||||
import jakarta.validation.Valid;
|
||||
import io.swagger.v3.oas.annotations.tags.Tag;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
@Tag(name = "Banner管理", description = "轮播图列表、创建/编辑/删除")
|
||||
@RestController
|
||||
@RequiredArgsConstructor
|
||||
public class BannerController {
|
||||
|
||||
@@ -9,9 +9,11 @@ import com.openclaw.module.coupon.dto.CouponTemplateUpdateDTO;
|
||||
import com.openclaw.module.coupon.service.CouponService;
|
||||
import com.openclaw.module.coupon.vo.CouponTemplateVO;
|
||||
import jakarta.validation.Valid;
|
||||
import io.swagger.v3.oas.annotations.tags.Tag;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
|
||||
@Tag(name = "[管理] 优惠券管理", description = "管理端-券模板创建/编辑、手动发券")
|
||||
@RestController
|
||||
@RequestMapping("/api/v1/admin/coupons")
|
||||
@RequiresRole({"admin", "super_admin"})
|
||||
|
||||
@@ -6,13 +6,15 @@ import com.openclaw.module.coupon.service.CouponService;
|
||||
import com.openclaw.module.coupon.vo.CouponCalcResultVO;
|
||||
import com.openclaw.module.coupon.vo.CouponTemplateVO;
|
||||
import com.openclaw.module.coupon.vo.UserCouponVO;
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import com.openclaw.util.UserContext;
|
||||
import io.swagger.v3.oas.annotations.tags.Tag;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.util.List;
|
||||
|
||||
@Tag(name = "优惠券", description = "领取、查询、使用优惠券")
|
||||
@RestController
|
||||
@RequestMapping("/api/v1/coupons")
|
||||
@RequiredArgsConstructor
|
||||
@@ -22,45 +24,41 @@ public class CouponController {
|
||||
|
||||
/** 可领取的优惠券列表 */
|
||||
@GetMapping("/available")
|
||||
public Result<List<CouponTemplateVO>> getAvailableTemplates(HttpServletRequest request) {
|
||||
Long userId = (Long) request.getAttribute("userId");
|
||||
public Result<List<CouponTemplateVO>> getAvailableTemplates() {
|
||||
Long userId = UserContext.getUserId();
|
||||
return Result.ok(couponService.getAvailableTemplates(userId));
|
||||
}
|
||||
|
||||
/** 领取优惠券 */
|
||||
@PostMapping("/receive/{templateId}")
|
||||
public Result<UserCouponVO> receiveCoupon(HttpServletRequest request,
|
||||
@PathVariable Long templateId) {
|
||||
Long userId = (Long) request.getAttribute("userId");
|
||||
public Result<UserCouponVO> receiveCoupon(@PathVariable Long templateId) {
|
||||
Long userId = UserContext.getUserId();
|
||||
return Result.ok(couponService.receiveCoupon(userId, templateId));
|
||||
}
|
||||
|
||||
/** 我的优惠券列表 */
|
||||
@GetMapping("/mine")
|
||||
public Result<IPage<UserCouponVO>> getMyCoupons(HttpServletRequest request,
|
||||
@RequestParam(required = false) String status,
|
||||
public Result<IPage<UserCouponVO>> getMyCoupons(@RequestParam(required = false) String status,
|
||||
@RequestParam(defaultValue = "1") int pageNum,
|
||||
@RequestParam(defaultValue = "10") int pageSize) {
|
||||
Long userId = (Long) request.getAttribute("userId");
|
||||
Long userId = UserContext.getUserId();
|
||||
pageSize = Math.min(pageSize, 50);
|
||||
return Result.ok(couponService.getMyCoupons(userId, status, pageNum, pageSize));
|
||||
}
|
||||
|
||||
/** 下单时查询可用优惠券 */
|
||||
@GetMapping("/usable")
|
||||
public Result<List<UserCouponVO>> getUsableCoupons(HttpServletRequest request,
|
||||
@RequestParam List<Long> skillIds,
|
||||
public Result<List<UserCouponVO>> getUsableCoupons(@RequestParam List<Long> skillIds,
|
||||
@RequestParam BigDecimal orderAmount) {
|
||||
Long userId = (Long) request.getAttribute("userId");
|
||||
Long userId = UserContext.getUserId();
|
||||
return Result.ok(couponService.getUsableCoupons(userId, skillIds, orderAmount));
|
||||
}
|
||||
|
||||
/** 计算优惠券抵扣金额(预览) */
|
||||
@GetMapping("/calc")
|
||||
public Result<CouponCalcResultVO> calcDiscount(HttpServletRequest request,
|
||||
@RequestParam Long couponId,
|
||||
public Result<CouponCalcResultVO> calcDiscount(@RequestParam Long couponId,
|
||||
@RequestParam BigDecimal orderAmount) {
|
||||
Long userId = (Long) request.getAttribute("userId");
|
||||
Long userId = UserContext.getUserId();
|
||||
return Result.ok(couponService.calcDiscount(userId, couponId, orderAmount));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -360,6 +360,12 @@ public class CouponServiceImpl implements CouponService {
|
||||
if (template == null) {
|
||||
throw new BusinessException(ErrorCode.COUPON_TEMPLATE_NOT_FOUND);
|
||||
}
|
||||
// 管理员发券时,自动激活草稿状态的模板
|
||||
if ("draft".equals(template.getStatus())) {
|
||||
template.setStatus("active");
|
||||
templateRepo.updateById(template);
|
||||
log.info("管理员发券时自动激活优惠券模板[{}]", template.getId());
|
||||
}
|
||||
|
||||
int issued = 0;
|
||||
for (Long userId : dto.getUserIds()) {
|
||||
|
||||
@@ -4,10 +4,12 @@ import com.openclaw.common.Result;
|
||||
import com.openclaw.module.customization.dto.CustomizationRequestDTO;
|
||||
import com.openclaw.module.customization.service.CustomizationRequestService;
|
||||
import com.openclaw.util.UserContext;
|
||||
import io.swagger.v3.oas.annotations.tags.Tag;
|
||||
import jakarta.validation.Valid;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
|
||||
@Tag(name = "定制需求", description = "提交定制需求")
|
||||
@RestController
|
||||
@RequestMapping("/api/v1/customization")
|
||||
@RequiredArgsConstructor
|
||||
|
||||
@@ -4,9 +4,11 @@ import com.openclaw.common.Result;
|
||||
import com.openclaw.module.developer.dto.DeveloperApplicationDTO;
|
||||
import com.openclaw.module.developer.service.DeveloperApplicationService;
|
||||
import com.openclaw.util.UserContext;
|
||||
import io.swagger.v3.oas.annotations.tags.Tag;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
|
||||
@Tag(name = "开发者申请", description = "提交/查询开发者申请")
|
||||
@RestController
|
||||
@RequestMapping("/api/v1/developer")
|
||||
@RequiredArgsConstructor
|
||||
@@ -18,7 +20,7 @@ public class DeveloperController {
|
||||
* 提交开发者申请
|
||||
*/
|
||||
@PostMapping("/application")
|
||||
public Result<Void> submitApplication(@RequestBody DeveloperApplicationDTO dto) {
|
||||
public Result<Void> submitApplication(@jakarta.validation.Valid @RequestBody DeveloperApplicationDTO dto) {
|
||||
Long userId = UserContext.getUserId();
|
||||
applicationService.submitApplication(userId, dto);
|
||||
return Result.ok();
|
||||
|
||||
@@ -8,10 +8,12 @@ import com.openclaw.module.feedback.dto.FeedbackReplyDTO;
|
||||
import com.openclaw.module.feedback.service.FeedbackService;
|
||||
import com.openclaw.module.feedback.vo.FeedbackVO;
|
||||
import com.openclaw.util.UserContext;
|
||||
import io.swagger.v3.oas.annotations.tags.Tag;
|
||||
import jakarta.validation.Valid;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
|
||||
@Tag(name = "用户反馈", description = "提交反馈、查询反馈、管理端回复")
|
||||
@RestController
|
||||
@RequiredArgsConstructor
|
||||
public class FeedbackController {
|
||||
|
||||
@@ -159,6 +159,9 @@ public class FeedbackServiceImpl implements FeedbackService {
|
||||
|
||||
@Override
|
||||
public void changeStatus(Long id, String status) {
|
||||
if (!STATUS_LABELS.containsKey(status)) {
|
||||
throw new BusinessException(400, "无效的状态值: " + status);
|
||||
}
|
||||
Feedback feedback = feedbackRepository.selectById(id);
|
||||
if (feedback == null) {
|
||||
throw new BusinessException(ErrorCode.NOT_FOUND);
|
||||
|
||||
@@ -10,11 +10,13 @@ import com.openclaw.module.help.vo.HelpArticleVO;
|
||||
import com.openclaw.module.help.vo.HelpCategoryVO;
|
||||
import com.openclaw.annotation.RequiresRole;
|
||||
import jakarta.validation.Valid;
|
||||
import io.swagger.v3.oas.annotations.tags.Tag;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
@Tag(name = "[管理] 帮助中心", description = "管理端-帮助分类和文章CRUD")
|
||||
@RestController
|
||||
@RequestMapping("/api/v1/admin/help")
|
||||
@RequiresRole({"admin", "super_admin"})
|
||||
|
||||
@@ -5,11 +5,13 @@ import com.openclaw.module.help.service.HelpService;
|
||||
import com.openclaw.module.help.vo.HelpArticleListVO;
|
||||
import com.openclaw.module.help.vo.HelpArticleVO;
|
||||
import com.openclaw.module.help.vo.HelpCategoryVO;
|
||||
import io.swagger.v3.oas.annotations.tags.Tag;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
@Tag(name = "帮助中心", description = "帮助分类、文章列表、文章详情")
|
||||
@RestController
|
||||
@RequestMapping("/api/v1/help")
|
||||
@RequiredArgsConstructor
|
||||
|
||||
@@ -6,10 +6,12 @@ import com.openclaw.module.invite.dto.BindInviteDTO;
|
||||
import com.openclaw.module.invite.service.InviteService;
|
||||
import com.openclaw.util.UserContext;
|
||||
import com.openclaw.module.invite.vo.*;
|
||||
import io.swagger.v3.oas.annotations.tags.Tag;
|
||||
import jakarta.validation.Valid;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
|
||||
@Tag(name = "邀请管理", description = "邀请码、邀请记录、绑定邀请码")
|
||||
@RestController
|
||||
@RequestMapping("/api/v1/invites")
|
||||
@RequiredArgsConstructor
|
||||
|
||||
@@ -8,10 +8,12 @@ import com.openclaw.module.invoice.dto.InvoiceReviewDTO;
|
||||
import com.openclaw.module.invoice.service.InvoiceService;
|
||||
import com.openclaw.module.invoice.vo.InvoiceVO;
|
||||
import com.openclaw.util.UserContext;
|
||||
import io.swagger.v3.oas.annotations.tags.Tag;
|
||||
import jakarta.validation.Valid;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
|
||||
@Tag(name = "发票管理", description = "申请发票、查询发票、审核发票")
|
||||
@RestController
|
||||
@RequiredArgsConstructor
|
||||
public class InvoiceController {
|
||||
|
||||
@@ -5,9 +5,11 @@ import com.openclaw.annotation.RequiresRole;
|
||||
import com.openclaw.common.Result;
|
||||
import com.openclaw.module.log.service.OperationLogService;
|
||||
import com.openclaw.module.log.vo.OperationLogVO;
|
||||
import io.swagger.v3.oas.annotations.tags.Tag;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
|
||||
@Tag(name = "[管理] 操作日志", description = "管理端-操作日志查询")
|
||||
@RestController
|
||||
@RequestMapping("/api/v1/admin/logs")
|
||||
@RequiredArgsConstructor
|
||||
|
||||
@@ -4,11 +4,13 @@ import com.openclaw.annotation.RequiresRole;
|
||||
import com.openclaw.common.Result;
|
||||
import com.openclaw.module.member.entity.MemberLevelConfig;
|
||||
import com.openclaw.module.member.repository.MemberLevelConfigRepository;
|
||||
import io.swagger.v3.oas.annotations.tags.Tag;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
@Tag(name = "[管理] 会员等级", description = "管理端-会员等级配置CRUD")
|
||||
@RestController
|
||||
@RequestMapping("/api/v1/admin/member-levels")
|
||||
@RequiresRole({"admin", "super_admin"})
|
||||
|
||||
@@ -8,12 +8,14 @@ import com.openclaw.module.member.entity.GrowthRecord;
|
||||
import com.openclaw.module.member.service.MemberService;
|
||||
import com.openclaw.module.member.vo.MemberLevelVO;
|
||||
import com.openclaw.util.UserContext;
|
||||
import io.swagger.v3.oas.annotations.tags.Tag;
|
||||
import jakarta.validation.Valid;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
@Tag(name = "会员等级", description = "等级详情、成长值记录")
|
||||
@RestController
|
||||
@RequestMapping("/api/v1/member")
|
||||
@RequiredArgsConstructor
|
||||
|
||||
@@ -5,9 +5,11 @@ import com.openclaw.common.Result;
|
||||
import com.openclaw.util.UserContext;
|
||||
import com.openclaw.module.notification.entity.Notification;
|
||||
import com.openclaw.module.notification.service.NotificationService;
|
||||
import io.swagger.v3.oas.annotations.tags.Tag;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
|
||||
@Tag(name = "消息通知", description = "用户消息列表、读取、标记")
|
||||
@RestController
|
||||
@RequestMapping("/api/v1/notifications")
|
||||
@RequiredArgsConstructor
|
||||
@@ -19,6 +21,7 @@ public class NotificationController {
|
||||
public Result<IPage<Notification>> list(
|
||||
@RequestParam(defaultValue = "1") int pageNum,
|
||||
@RequestParam(defaultValue = "20") int pageSize) {
|
||||
pageSize = Math.min(Math.max(pageSize, 1), 50);
|
||||
Long userId = UserContext.getUserId();
|
||||
return Result.ok(notificationService.getUserNotifications(userId, pageNum, pageSize));
|
||||
}
|
||||
|
||||
@@ -7,11 +7,14 @@ import com.openclaw.module.order.service.OrderService;
|
||||
import com.openclaw.annotation.RequiresRole;
|
||||
import com.openclaw.util.UserContext;
|
||||
import com.openclaw.module.order.vo.*;
|
||||
import io.swagger.v3.oas.annotations.Operation;
|
||||
import io.swagger.v3.oas.annotations.tags.Tag;
|
||||
import java.util.List;
|
||||
import jakarta.validation.Valid;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
|
||||
@Tag(name = "订单管理", description = "创建订单、支付、取消、退款")
|
||||
@RestController
|
||||
@RequestMapping("/api/v1/orders")
|
||||
@RequiredArgsConstructor
|
||||
@@ -20,7 +23,7 @@ public class OrderController {
|
||||
|
||||
private final OrderService orderService;
|
||||
|
||||
/** 订单预览(不创建订单,仅计算金额) */
|
||||
@Operation(summary = "订单预览", description = "计算金额、优惠、积分抵扣,不创建订单")
|
||||
@GetMapping("/preview")
|
||||
public Result<OrderPreviewVO> previewOrder(
|
||||
@RequestParam List<Long> skillIds,
|
||||
@@ -29,26 +32,28 @@ public class OrderController {
|
||||
return Result.ok(orderService.previewOrder(UserContext.getUserId(), skillIds, pointsToUse, couponId));
|
||||
}
|
||||
|
||||
@Operation(summary = "创建订单")
|
||||
@PostMapping
|
||||
public Result<OrderVO> createOrder(@Valid @RequestBody OrderCreateDTO dto) {
|
||||
return Result.ok(orderService.createOrder(UserContext.getUserId(), dto));
|
||||
}
|
||||
|
||||
/** 获取订单详情 */
|
||||
@Operation(summary = "获取订单详情")
|
||||
@GetMapping("/{id}")
|
||||
public Result<OrderVO> getOrder(@PathVariable Long id) {
|
||||
return Result.ok(orderService.getOrderDetail(UserContext.getUserId(), id));
|
||||
}
|
||||
|
||||
/** 获取我的订单列表 */
|
||||
@Operation(summary = "我的订单列表", description = "分页查询")
|
||||
@GetMapping
|
||||
public Result<IPage<OrderVO>> listOrders(
|
||||
@RequestParam(defaultValue = "1") int pageNum,
|
||||
@RequestParam(defaultValue = "10") int pageSize) {
|
||||
pageSize = Math.min(Math.max(pageSize, 1), 50);
|
||||
return Result.ok(orderService.listMyOrders(UserContext.getUserId(), pageNum, pageSize));
|
||||
}
|
||||
|
||||
/** 支付订单 */
|
||||
@Operation(summary = "支付订单")
|
||||
@PostMapping("/{id}/pay")
|
||||
public Result<Void> payOrder(
|
||||
@PathVariable Long id,
|
||||
@@ -57,7 +62,7 @@ public class OrderController {
|
||||
return Result.ok();
|
||||
}
|
||||
|
||||
/** 取消订单 */
|
||||
@Operation(summary = "取消订单")
|
||||
@PostMapping("/{id}/cancel")
|
||||
public Result<Void> cancelOrder(
|
||||
@PathVariable Long id,
|
||||
@@ -66,7 +71,7 @@ public class OrderController {
|
||||
return Result.ok();
|
||||
}
|
||||
|
||||
/** 申请退款 */
|
||||
@Operation(summary = "申请退款")
|
||||
@PostMapping("/{id}/refund")
|
||||
public Result<Void> applyRefund(
|
||||
@PathVariable Long id,
|
||||
|
||||
@@ -12,7 +12,9 @@ public class Order {
|
||||
private Long id;
|
||||
private String orderNo;
|
||||
private Long userId;
|
||||
private BigDecimal totalAmount;
|
||||
private BigDecimal originalAmount; // 原价总额(促销前)
|
||||
private BigDecimal totalAmount; // 促销后总额
|
||||
private BigDecimal promotionDeductAmount; // 促销优惠金额
|
||||
private BigDecimal cashAmount;
|
||||
private Integer pointsUsed;
|
||||
private BigDecimal pointsDeductAmount;
|
||||
|
||||
@@ -13,9 +13,11 @@ public class OrderItem {
|
||||
private Long skillId;
|
||||
private String skillName; // 下单时快照
|
||||
private String skillCover; // 下单时快照
|
||||
private BigDecimal unitPrice;
|
||||
private BigDecimal originalPrice; // 原价(促销前)
|
||||
private BigDecimal unitPrice; // 实际单价(促销后)
|
||||
private Integer quantity;
|
||||
private BigDecimal totalPrice;
|
||||
private Long promotionId; // 关联的促销活动ID(NULL=无促销)
|
||||
@TableLogic(value = "0", delval = "1")
|
||||
private Integer deleted;
|
||||
}
|
||||
|
||||
@@ -24,4 +24,12 @@ public interface OrderRepository extends BaseMapper<Order> {
|
||||
/** CAS方式更新订单状态(幂等性保护),返回受影响行数 */
|
||||
@Update("UPDATE orders SET status = #{newStatus}, paid_at = #{paidAt}, updated_at = NOW() WHERE id = #{orderId} AND status = #{expectedStatus} AND deleted = 0")
|
||||
int casUpdateStatus(@Param("orderId") Long orderId, @Param("expectedStatus") String expectedStatus, @Param("newStatus") String newStatus, @Param("paidAt") LocalDateTime paidAt);
|
||||
|
||||
/** CAS方式更新订单状态(不更新paidAt),用于取消等操作防止并发竞态 */
|
||||
@Update("UPDATE orders SET status = #{newStatus}, cancel_reason = #{cancelReason}, updated_at = NOW() WHERE id = #{orderId} AND status = #{expectedStatus} AND deleted = 0")
|
||||
int casCancel(@Param("orderId") Long orderId, @Param("expectedStatus") String expectedStatus, @Param("newStatus") String newStatus, @Param("cancelReason") String cancelReason);
|
||||
|
||||
/** CAS方式更新订单状态(通用),用于退款申请等场景防止并发竞态 */
|
||||
@Update("UPDATE orders SET status = #{newStatus}, updated_at = NOW() WHERE id = #{orderId} AND status = #{expectedStatus} AND deleted = 0")
|
||||
int casStatus(@Param("orderId") Long orderId, @Param("expectedStatus") String expectedStatus, @Param("newStatus") String newStatus);
|
||||
}
|
||||
|
||||
@@ -22,6 +22,8 @@ import com.openclaw.common.compensation.CompensationService;
|
||||
import com.openclaw.module.coupon.service.CouponService;
|
||||
import com.openclaw.module.coupon.vo.CouponCalcResultVO;
|
||||
import com.openclaw.module.notification.service.NotificationService;
|
||||
import com.openclaw.module.promotion.service.PromotionService;
|
||||
import com.openclaw.module.promotion.vo.SkillPromotionVO;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.amqp.rabbit.core.RabbitTemplate;
|
||||
@@ -55,6 +57,7 @@ public class OrderServiceImpl implements OrderService {
|
||||
private final CompensationService compensationService;
|
||||
private final CouponService couponService;
|
||||
private final NotificationService notificationService;
|
||||
private final PromotionService promotionService;
|
||||
|
||||
@Override
|
||||
public OrderPreviewVO previewOrder(Long userId, List<Long> skillIds, Integer pointsToUse) {
|
||||
@@ -67,14 +70,33 @@ public class OrderServiceImpl implements OrderService {
|
||||
List<Skill> skills = skillRepo.selectBatchIds(skillIds);
|
||||
if (skills.isEmpty()) throw new BusinessException(ErrorCode.SKILL_NOT_FOUND);
|
||||
|
||||
BigDecimal totalAmount = skills.stream()
|
||||
// 1b. 批量查询促销信息
|
||||
List<SkillPromotionVO> promotions = promotionService.batchGetSkillPromotions(skillIds);
|
||||
Map<Long, SkillPromotionVO> promoMap = promotions.stream()
|
||||
.filter(p -> p.getSkillId() != null)
|
||||
.collect(Collectors.toMap(SkillPromotionVO::getSkillId, p -> p, (a, b) -> a));
|
||||
|
||||
// 1c. 计算原价总额和促销后总额
|
||||
BigDecimal originalAmount = skills.stream()
|
||||
.map(Skill::getPrice)
|
||||
.reduce(BigDecimal.ZERO, BigDecimal::add);
|
||||
|
||||
BigDecimal totalAmount = BigDecimal.ZERO;
|
||||
for (Skill s : skills) {
|
||||
SkillPromotionVO promo = promoMap.get(s.getId());
|
||||
if (promo != null) {
|
||||
BigDecimal promoPrice = promotionService.calculatePromotionPrice(s.getId(), s.getPrice());
|
||||
totalAmount = totalAmount.add(promoPrice);
|
||||
} else {
|
||||
totalAmount = totalAmount.add(s.getPrice());
|
||||
}
|
||||
}
|
||||
BigDecimal promotionDeductAmount = originalAmount.subtract(totalAmount).max(BigDecimal.ZERO);
|
||||
|
||||
// 2. 查询用户积分余额
|
||||
int availablePoints = pointsService.getBalance(userId).getAvailablePoints();
|
||||
|
||||
// 3. 计算最大可用积分
|
||||
// 3. 计算最大可用积分(基于促销后总额)
|
||||
int maxPoints = totalAmount.multiply(BigDecimal.valueOf(POINTS_RATE)).intValue();
|
||||
maxPoints = Math.min(maxPoints, availablePoints);
|
||||
|
||||
@@ -108,11 +130,22 @@ public class OrderServiceImpl implements OrderService {
|
||||
item.setSkillId(s.getId());
|
||||
item.setSkillName(s.getName());
|
||||
item.setSkillCover(s.getCoverImageUrl());
|
||||
item.setUnitPrice(s.getPrice());
|
||||
SkillPromotionVO promo = promoMap.get(s.getId());
|
||||
if (promo != null) {
|
||||
BigDecimal promoPrice = promotionService.calculatePromotionPrice(s.getId(), s.getPrice());
|
||||
item.setOriginalPrice(s.getPrice());
|
||||
item.setUnitPrice(promoPrice);
|
||||
item.setTotalPrice(promoPrice);
|
||||
item.setPromotionTag(promo.getTagText());
|
||||
} else {
|
||||
item.setUnitPrice(s.getPrice());
|
||||
item.setTotalPrice(s.getPrice());
|
||||
}
|
||||
item.setQuantity(1);
|
||||
item.setTotalPrice(s.getPrice());
|
||||
return item;
|
||||
}).collect(Collectors.toList()));
|
||||
vo.setOriginalAmount(originalAmount);
|
||||
vo.setPromotionDeductAmount(promotionDeductAmount);
|
||||
vo.setTotalAmount(totalAmount);
|
||||
vo.setPointsToUse(pointsToUse);
|
||||
vo.setPointsDeductAmount(deduct);
|
||||
@@ -140,11 +173,38 @@ public class OrderServiceImpl implements OrderService {
|
||||
}
|
||||
}
|
||||
|
||||
// 2. 计算总金额
|
||||
BigDecimal totalAmount = skills.stream()
|
||||
// 1b. 批量查询促销信息 & 校验用户限购
|
||||
List<Long> skillIds = skills.stream().map(Skill::getId).collect(Collectors.toList());
|
||||
List<SkillPromotionVO> promotions = promotionService.batchGetSkillPromotions(skillIds);
|
||||
Map<Long, SkillPromotionVO> promoMap = promotions.stream()
|
||||
.filter(p -> p.getSkillId() != null)
|
||||
.collect(Collectors.toMap(SkillPromotionVO::getSkillId, p -> p, (a, b) -> a));
|
||||
|
||||
java.util.Iterator<Map.Entry<Long, SkillPromotionVO>> it = promoMap.entrySet().iterator();
|
||||
while (it.hasNext()) {
|
||||
SkillPromotionVO promo = it.next().getValue();
|
||||
if (!promotionService.checkUserLimit(promo.getPromotionId(), userId)) {
|
||||
log.warn("用户超出促销限购: userId={}, promotionId={}", userId, promo.getPromotionId());
|
||||
it.remove();
|
||||
}
|
||||
}
|
||||
|
||||
// 2. 计算原价总额和促销后总额
|
||||
BigDecimal originalAmount = skills.stream()
|
||||
.map(Skill::getPrice)
|
||||
.reduce(BigDecimal.ZERO, BigDecimal::add);
|
||||
|
||||
BigDecimal totalAmount = BigDecimal.ZERO;
|
||||
for (Skill s : skills) {
|
||||
SkillPromotionVO promo = promoMap.get(s.getId());
|
||||
if (promo != null) {
|
||||
totalAmount = totalAmount.add(promotionService.calculatePromotionPrice(s.getId(), s.getPrice()));
|
||||
} else {
|
||||
totalAmount = totalAmount.add(s.getPrice());
|
||||
}
|
||||
}
|
||||
BigDecimal promotionDeductAmount = originalAmount.subtract(totalAmount).max(BigDecimal.ZERO);
|
||||
|
||||
// 3. 处理积分抵扣(校正上限,防止超额消耗)
|
||||
int pointsToUse = dto.getPointsToUse() != null ? dto.getPointsToUse() : 0;
|
||||
if (pointsToUse > 0) {
|
||||
@@ -187,7 +247,9 @@ public class OrderServiceImpl implements OrderService {
|
||||
Order order = new Order();
|
||||
order.setOrderNo(idGenerator.generateOrderNo());
|
||||
order.setUserId(userId);
|
||||
order.setOriginalAmount(originalAmount);
|
||||
order.setTotalAmount(totalAmount);
|
||||
order.setPromotionDeductAmount(promotionDeductAmount);
|
||||
order.setCashAmount(cashAmount);
|
||||
order.setPointsUsed(pointsToUse);
|
||||
order.setPointsDeductAmount(pointsDeductAmount);
|
||||
@@ -198,16 +260,25 @@ public class OrderServiceImpl implements OrderService {
|
||||
order.setExpiredAt(LocalDateTime.now().plusHours(1));
|
||||
orderRepo.insert(order);
|
||||
|
||||
// 6. 创建订单项
|
||||
// 6. 创建订单项(含促销快照)
|
||||
for (Skill skill : skills) {
|
||||
OrderItem item = new OrderItem();
|
||||
item.setOrderId(order.getId());
|
||||
item.setSkillId(skill.getId());
|
||||
item.setSkillName(skill.getName());
|
||||
item.setSkillCover(skill.getCoverImageUrl());
|
||||
item.setUnitPrice(skill.getPrice());
|
||||
item.setOriginalPrice(skill.getPrice());
|
||||
SkillPromotionVO promo = promoMap.get(skill.getId());
|
||||
if (promo != null) {
|
||||
BigDecimal promoPrice = promotionService.calculatePromotionPrice(skill.getId(), skill.getPrice());
|
||||
item.setUnitPrice(promoPrice);
|
||||
item.setTotalPrice(promoPrice);
|
||||
item.setPromotionId(promo.getPromotionId());
|
||||
} else {
|
||||
item.setUnitPrice(skill.getPrice());
|
||||
item.setTotalPrice(skill.getPrice());
|
||||
}
|
||||
item.setQuantity(1);
|
||||
item.setTotalPrice(skill.getPrice());
|
||||
orderItemRepo.insert(item);
|
||||
}
|
||||
|
||||
@@ -221,6 +292,16 @@ public class OrderServiceImpl implements OrderService {
|
||||
couponService.useCoupon(userId, couponId, order.getId());
|
||||
}
|
||||
|
||||
// 7c. 记录促销使用
|
||||
for (Skill skill : skills) {
|
||||
SkillPromotionVO promo = promoMap.get(skill.getId());
|
||||
if (promo != null) {
|
||||
BigDecimal promoPrice = promotionService.calculatePromotionPrice(skill.getId(), skill.getPrice());
|
||||
BigDecimal discount = skill.getPrice().subtract(promoPrice).max(BigDecimal.ZERO);
|
||||
promotionService.recordPromotionUsage(promo.getPromotionId(), userId, order.getId(), skill.getId(), discount);
|
||||
}
|
||||
}
|
||||
|
||||
// 8. 免现金支付(纯积分 或 优惠券全额抵扣):直接完成订单
|
||||
if (cashAmount.compareTo(BigDecimal.ZERO) == 0) {
|
||||
if (pointsToUse > 0) {
|
||||
@@ -229,13 +310,21 @@ public class OrderServiceImpl implements OrderService {
|
||||
order.setStatus("completed");
|
||||
order.setPaidAt(LocalDateTime.now());
|
||||
orderRepo.updateById(order);
|
||||
// 发放 Skill 访问权限
|
||||
String grantSource = pointsToUse > 0 ? "points" : "coupon";
|
||||
// 发放 Skill 访问权限(download_type ENUM: free/paid/points)
|
||||
String grantSource;
|
||||
if (totalAmount.compareTo(BigDecimal.ZERO) == 0) {
|
||||
grantSource = "free";
|
||||
} else if (pointsToUse > 0) {
|
||||
grantSource = "points";
|
||||
} else {
|
||||
grantSource = "paid";
|
||||
}
|
||||
for (Skill skill : skills) {
|
||||
skillService.grantAccess(userId, skill.getId(), order.getId(), grantSource);
|
||||
}
|
||||
log.info("免现金订单直接完成: orderId={}, points={}, couponId={}", order.getId(), pointsToUse, couponId);
|
||||
return toVO(order, skills);
|
||||
log.info("免现金订单直接完成: orderId={}, points={}, couponId={}, promoDeduct={}",
|
||||
order.getId(), pointsToUse, couponId, promotionDeductAmount);
|
||||
return toVO(order, skills, promoMap);
|
||||
}
|
||||
|
||||
// 9. 非纯积分:事务提交后发送订单超时延迟消息(1小时后自动取消)
|
||||
@@ -256,7 +345,7 @@ public class OrderServiceImpl implements OrderService {
|
||||
}
|
||||
});
|
||||
|
||||
return toVO(order, skills);
|
||||
return toVO(order, skills, promoMap);
|
||||
}
|
||||
|
||||
@Override
|
||||
@@ -303,6 +392,11 @@ public class OrderServiceImpl implements OrderService {
|
||||
if (order == null || !order.getUserId().equals(userId)) {
|
||||
throw new BusinessException(ErrorCode.ORDER_NOT_FOUND);
|
||||
}
|
||||
// 幂等处理:已支付/已完成的订单直接返回成功(免费订单创建时已自动完成)
|
||||
if ("paid".equals(order.getStatus()) || "completed".equals(order.getStatus())) {
|
||||
log.info("订单已完成,跳过重复支付: orderId={}, status={}", orderId, order.getStatus());
|
||||
return;
|
||||
}
|
||||
if (!"pending".equals(order.getStatus())) {
|
||||
throw new BusinessException(ErrorCode.ORDER_STATUS_ERROR);
|
||||
}
|
||||
@@ -352,9 +446,11 @@ public class OrderServiceImpl implements OrderService {
|
||||
if (!"pending".equals(order.getStatus())) {
|
||||
throw new BusinessException(ErrorCode.ORDER_STATUS_ERROR);
|
||||
}
|
||||
order.setStatus("cancelled");
|
||||
order.setCancelReason(reason);
|
||||
orderRepo.updateById(order);
|
||||
// CAS更新:防止并发重复取消(用户手动取消 + 超时自动取消 竞态)
|
||||
int rows = orderRepo.casCancel(orderId, "pending", "cancelled", reason);
|
||||
if (rows == 0) {
|
||||
throw new BusinessException(ErrorCode.ORDER_STATUS_ERROR);
|
||||
}
|
||||
|
||||
// 解冻积分
|
||||
if (order.getPointsUsed() != null && order.getPointsUsed() > 0) {
|
||||
@@ -391,16 +487,15 @@ public class OrderServiceImpl implements OrderService {
|
||||
if (order == null || !order.getUserId().equals(userId)) {
|
||||
throw new BusinessException(ErrorCode.ORDER_NOT_FOUND);
|
||||
}
|
||||
if (!"paid".equals(order.getStatus()) && !"completed".equals(order.getStatus())) {
|
||||
String currentStatus = order.getStatus();
|
||||
if (!"paid".equals(currentStatus) && !"completed".equals(currentStatus)) {
|
||||
throw new BusinessException(ErrorCode.ORDER_STATUS_ERROR);
|
||||
}
|
||||
Long refundCount = refundRepo.selectCount(
|
||||
new LambdaQueryWrapper<OrderRefund>()
|
||||
.eq(OrderRefund::getOrderId, orderId)
|
||||
.in(OrderRefund::getStatus, "pending", "approved", "completed")
|
||||
);
|
||||
if (refundCount != null && refundCount > 0) {
|
||||
throw new BusinessException(409, "该订单已有退款申请,请勿重复提交");
|
||||
|
||||
// CAS原子更新订单状态为refunding,防止并发重复申请退款
|
||||
int rows = orderRepo.casStatus(orderId, currentStatus, "refunding");
|
||||
if (rows == 0) {
|
||||
throw new BusinessException(409, "订单状态已变更或已有退款申请,请勿重复提交");
|
||||
}
|
||||
|
||||
OrderRefund refund = new OrderRefund();
|
||||
@@ -417,17 +512,16 @@ public class OrderServiceImpl implements OrderService {
|
||||
}
|
||||
}
|
||||
refund.setStatus("pending");
|
||||
refund.setPreviousOrderStatus(order.getStatus());
|
||||
refund.setPreviousOrderStatus(currentStatus);
|
||||
refundRepo.insert(refund);
|
||||
|
||||
order.setStatus("refunding");
|
||||
orderRepo.updateById(order);
|
||||
}
|
||||
|
||||
private OrderVO toVO(Order order, List<Skill> skills) {
|
||||
private OrderVO toVO(Order order, List<Skill> skills, Map<Long, SkillPromotionVO> promoMap) {
|
||||
OrderVO vo = new OrderVO();
|
||||
vo.setId(order.getId());
|
||||
vo.setOrderNo(order.getOrderNo());
|
||||
vo.setOriginalAmount(order.getOriginalAmount());
|
||||
vo.setPromotionDeductAmount(order.getPromotionDeductAmount());
|
||||
vo.setTotalAmount(order.getTotalAmount());
|
||||
vo.setCashAmount(order.getCashAmount());
|
||||
vo.setPointsUsed(order.getPointsUsed());
|
||||
@@ -444,9 +538,18 @@ public class OrderServiceImpl implements OrderService {
|
||||
item.setSkillId(s.getId());
|
||||
item.setSkillName(s.getName());
|
||||
item.setSkillCover(s.getCoverImageUrl());
|
||||
item.setUnitPrice(s.getPrice());
|
||||
SkillPromotionVO promo = promoMap != null ? promoMap.get(s.getId()) : null;
|
||||
if (promo != null) {
|
||||
BigDecimal promoPrice = promotionService.calculatePromotionPrice(s.getId(), s.getPrice());
|
||||
item.setOriginalPrice(s.getPrice());
|
||||
item.setUnitPrice(promoPrice);
|
||||
item.setTotalPrice(promoPrice);
|
||||
item.setPromotionTag(promo.getTagText());
|
||||
} else {
|
||||
item.setUnitPrice(s.getPrice());
|
||||
item.setTotalPrice(s.getPrice());
|
||||
}
|
||||
item.setQuantity(1);
|
||||
item.setTotalPrice(s.getPrice());
|
||||
return item;
|
||||
}).collect(Collectors.toList()));
|
||||
return vo;
|
||||
@@ -457,6 +560,8 @@ public class OrderServiceImpl implements OrderService {
|
||||
OrderVO vo = new OrderVO();
|
||||
vo.setId(order.getId());
|
||||
vo.setOrderNo(order.getOrderNo());
|
||||
vo.setOriginalAmount(order.getOriginalAmount());
|
||||
vo.setPromotionDeductAmount(order.getPromotionDeductAmount());
|
||||
vo.setTotalAmount(order.getTotalAmount());
|
||||
vo.setCashAmount(order.getCashAmount());
|
||||
vo.setPointsUsed(order.getPointsUsed());
|
||||
@@ -473,9 +578,11 @@ public class OrderServiceImpl implements OrderService {
|
||||
item.setSkillId(oi.getSkillId());
|
||||
item.setSkillName(oi.getSkillName());
|
||||
item.setSkillCover(oi.getSkillCover());
|
||||
item.setOriginalPrice(oi.getOriginalPrice());
|
||||
item.setUnitPrice(oi.getUnitPrice());
|
||||
item.setQuantity(oi.getQuantity());
|
||||
item.setTotalPrice(oi.getTotalPrice());
|
||||
item.setPromotionId(oi.getPromotionId());
|
||||
return item;
|
||||
}).collect(Collectors.toList()));
|
||||
return vo;
|
||||
|
||||
@@ -8,7 +8,10 @@ public class OrderItemVO {
|
||||
private Long skillId;
|
||||
private String skillName;
|
||||
private String skillCover;
|
||||
private BigDecimal unitPrice;
|
||||
private BigDecimal originalPrice; // 原价(促销前,NULL=无促销)
|
||||
private BigDecimal unitPrice; // 实际单价
|
||||
private Integer quantity;
|
||||
private BigDecimal totalPrice;
|
||||
private String promotionTag; // 促销标签(如"限时8折")
|
||||
private Long promotionId; // 促销活动ID
|
||||
}
|
||||
|
||||
@@ -7,7 +7,9 @@ import java.util.List;
|
||||
@Data
|
||||
public class OrderPreviewVO {
|
||||
private List<OrderItemVO> items;
|
||||
private BigDecimal totalAmount;
|
||||
private BigDecimal originalAmount; // 原价总额(促销前)
|
||||
private BigDecimal promotionDeductAmount; // 促销优惠金额
|
||||
private BigDecimal totalAmount; // 促销后总额
|
||||
private Integer pointsToUse;
|
||||
private BigDecimal pointsDeductAmount;
|
||||
private Long couponId;
|
||||
|
||||
@@ -9,6 +9,8 @@ import java.util.List;
|
||||
public class OrderVO {
|
||||
private Long id;
|
||||
private String orderNo;
|
||||
private BigDecimal originalAmount;
|
||||
private BigDecimal promotionDeductAmount;
|
||||
private BigDecimal totalAmount;
|
||||
private BigDecimal cashAmount;
|
||||
private Integer pointsUsed;
|
||||
|
||||
@@ -6,6 +6,7 @@ import com.openclaw.module.payment.service.PaymentService;
|
||||
import com.openclaw.module.order.service.OrderService;
|
||||
import com.openclaw.util.UserContext;
|
||||
import com.openclaw.annotation.RequiresRole;
|
||||
import io.swagger.v3.oas.annotations.tags.Tag;
|
||||
import lombok.Data;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
@@ -18,6 +19,7 @@ import java.util.Map;
|
||||
* 仅在微信支付未启用时(wechat.pay.enabled=false)生效
|
||||
* 用于开发/测试环境模拟完整支付流程
|
||||
*/
|
||||
@Tag(name = "模拟支付", description = "开发/测试环境模拟支付网关")
|
||||
@Slf4j
|
||||
@RestController
|
||||
@RequestMapping("/api/v1/mock-pay")
|
||||
|
||||
@@ -7,6 +7,8 @@ import com.openclaw.module.payment.service.PaymentService;
|
||||
import com.openclaw.annotation.RequiresRole;
|
||||
import com.openclaw.util.UserContext;
|
||||
import com.openclaw.module.payment.vo.*;
|
||||
import io.swagger.v3.oas.annotations.Operation;
|
||||
import io.swagger.v3.oas.annotations.tags.Tag;
|
||||
import jakarta.validation.Valid;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
@@ -16,6 +18,7 @@ import org.springframework.web.bind.annotation.*;
|
||||
import java.util.HashMap;
|
||||
import java.util.Map;
|
||||
|
||||
@Tag(name = "支付与充值", description = "积分充值、支付记录、微信回调")
|
||||
@Slf4j
|
||||
@RestController
|
||||
@RequestMapping("/api/v1/payments")
|
||||
@@ -24,14 +27,14 @@ public class PaymentController {
|
||||
|
||||
private final PaymentService paymentService;
|
||||
|
||||
/** 发起充值 */
|
||||
@Operation(summary = "发起充值", description = "创建积分充值订单")
|
||||
@RequiresRole("user")
|
||||
@PostMapping("/recharge")
|
||||
public Result<RechargeVO> createRecharge(@Valid @RequestBody RechargeDTO dto) {
|
||||
return Result.ok(paymentService.createRecharge(UserContext.getUserId(), dto));
|
||||
}
|
||||
|
||||
/** 获取支付记录 */
|
||||
@Operation(summary = "支付记录列表", description = "分页查询")
|
||||
@RequiresRole("user")
|
||||
@GetMapping("/records")
|
||||
public Result<IPage<PaymentRecordVO>> listRecords(
|
||||
@@ -40,13 +43,14 @@ public class PaymentController {
|
||||
return Result.ok(paymentService.listPaymentRecords(UserContext.getUserId(), pageNum, pageSize));
|
||||
}
|
||||
|
||||
/** 查询充值订单状态 */
|
||||
@Operation(summary = "查询充值状态")
|
||||
@RequiresRole("user")
|
||||
@GetMapping("/recharge/{id}")
|
||||
public Result<RechargeVO> getRechargeStatus(@PathVariable Long id) {
|
||||
return Result.ok(paymentService.getRechargeStatus(UserContext.getUserId(), id));
|
||||
}
|
||||
|
||||
@Operation(summary = "微信支付回调", description = "微信V3回调通知,无需登录")
|
||||
/**
|
||||
* 微信支付V3回调(无需登录)
|
||||
* 微信V3使用JSON格式 + HTTP请求头传递签名信息
|
||||
|
||||
@@ -5,9 +5,11 @@ import com.openclaw.common.Result;
|
||||
import com.openclaw.module.points.service.PointsService;
|
||||
import com.openclaw.util.UserContext;
|
||||
import com.openclaw.module.points.vo.*;
|
||||
import io.swagger.v3.oas.annotations.tags.Tag;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
|
||||
@Tag(name = "积分管理", description = "积分余额、积分流水")
|
||||
@RestController
|
||||
@RequestMapping("/api/v1/points")
|
||||
@RequiredArgsConstructor
|
||||
@@ -26,6 +28,7 @@ public class PointsController {
|
||||
public Result<IPage<PointsRecordVO>> getRecords(
|
||||
@RequestParam(defaultValue = "1") int pageNum,
|
||||
@RequestParam(defaultValue = "20") int pageSize) {
|
||||
pageSize = Math.min(Math.max(pageSize, 1), 50);
|
||||
return Result.ok(pointsService.getRecords(UserContext.getUserId(), pageNum, pageSize));
|
||||
}
|
||||
|
||||
|
||||
@@ -41,6 +41,10 @@ public class PointsServiceImpl implements PointsService {
|
||||
@Override
|
||||
@Transactional
|
||||
public void initUserPoints(Long userId) {
|
||||
// 幂等:已存在则跳过,防止MQ重试导致唯一约束冲突
|
||||
if (userPointsRepo.findByUserId(userId) != null) {
|
||||
return;
|
||||
}
|
||||
UserPoints up = new UserPoints();
|
||||
up.setUserId(userId);
|
||||
up.setAvailablePoints(0);
|
||||
@@ -132,12 +136,31 @@ public class PointsServiceImpl implements PointsService {
|
||||
return points;
|
||||
}
|
||||
|
||||
/** 一次性来源:每个用户只能领取一次积分,防止重复刷取 */
|
||||
private static final java.util.Set<String> ONE_TIME_SOURCES = java.util.Set.of(
|
||||
"register", "join_community", "invited"
|
||||
);
|
||||
|
||||
@Override
|
||||
@Transactional
|
||||
public void earnPoints(Long userId, String source, Long relatedId, String relatedType) {
|
||||
PointsRule rule = ruleRepo.findBySource(source);
|
||||
if (rule == null || !rule.getEnabled()) return;
|
||||
|
||||
// 幂等:一次性来源检查是否已领取过,防止重复刷积分
|
||||
if (ONE_TIME_SOURCES.contains(source)) {
|
||||
Long existCount = recordRepo.selectCount(
|
||||
new LambdaQueryWrapper<PointsRecord>()
|
||||
.eq(PointsRecord::getUserId, userId)
|
||||
.eq(PointsRecord::getSource, source)
|
||||
.eq(PointsRecord::getPointsType, "earn")
|
||||
);
|
||||
if (existCount != null && existCount > 0) {
|
||||
log.info("一次性积分已领取,跳过: userId={}, source={}", userId, source);
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
UserPoints up = userPointsRepo.findByUserId(userId);
|
||||
if (up == null) {
|
||||
initUserPoints(userId);
|
||||
|
||||
@@ -7,12 +7,14 @@ import com.openclaw.module.promotion.dto.PromotionCreateDTO;
|
||||
import com.openclaw.module.promotion.dto.PromotionUpdateDTO;
|
||||
import com.openclaw.module.promotion.service.PromotionService;
|
||||
import com.openclaw.module.promotion.vo.*;
|
||||
import io.swagger.v3.oas.annotations.tags.Tag;
|
||||
import jakarta.validation.Valid;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
@Tag(name = "促销活动", description = "促销活动管理与用户端查询")
|
||||
@RestController
|
||||
@RequestMapping("/api/v1/promotions")
|
||||
@RequiredArgsConstructor
|
||||
|
||||
@@ -20,8 +20,7 @@ public class PromotionCreateDTO {
|
||||
@NotNull
|
||||
private LocalDateTime endTime;
|
||||
|
||||
@NotBlank
|
||||
private String rules; // JSON
|
||||
private PromotionRules rules;
|
||||
|
||||
private String scopeType; // all / category / skill
|
||||
private String scopeValues; // JSON
|
||||
|
||||
@@ -0,0 +1,17 @@
|
||||
package com.openclaw.module.promotion.dto;
|
||||
|
||||
import lombok.Data;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
|
||||
@Data
|
||||
public class PromotionRules {
|
||||
/** 固定促销价 */
|
||||
private BigDecimal promotionPrice;
|
||||
/** 折扣率 (0.8 = 八折, 0.5 = 五折) */
|
||||
private BigDecimal discountRate;
|
||||
/** 直减金额 */
|
||||
private BigDecimal discountAmount;
|
||||
/** 最低消费金额(满减门槛,可选) */
|
||||
private BigDecimal minOrderAmount;
|
||||
}
|
||||
@@ -11,7 +11,7 @@ public class PromotionUpdateDTO {
|
||||
private String type;
|
||||
private LocalDateTime startTime;
|
||||
private LocalDateTime endTime;
|
||||
private String rules;
|
||||
private PromotionRules rules;
|
||||
private String scopeType;
|
||||
private String scopeValues;
|
||||
private String exclusiveGroup;
|
||||
|
||||
@@ -16,4 +16,8 @@ public interface PromotionRepository extends BaseMapper<Promotion> {
|
||||
@Update("UPDATE promotion SET sold_count = GREATEST(sold_count - 1, 0) " +
|
||||
"WHERE id = #{id}")
|
||||
int decrementSoldCount(@Param("id") Long id);
|
||||
|
||||
@Update("UPDATE promotion SET status = 'ended', updated_at = NOW() " +
|
||||
"WHERE status = 'active' AND end_time < NOW()")
|
||||
int batchExpirePromotions();
|
||||
}
|
||||
|
||||
@@ -51,4 +51,7 @@ public interface PromotionService {
|
||||
|
||||
/** 检查用户是否超出活动限购 */
|
||||
boolean checkUserLimit(Long promotionId, Long userId);
|
||||
|
||||
/** 批量过期已结束的促销活动,返回影响行数 */
|
||||
int batchExpirePromotions();
|
||||
}
|
||||
|
||||
@@ -23,6 +23,9 @@ import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import com.openclaw.module.promotion.dto.PromotionRules;
|
||||
|
||||
import java.math.BigDecimal;
|
||||
import java.math.RoundingMode;
|
||||
import java.time.LocalDateTime;
|
||||
@@ -37,6 +40,8 @@ import java.util.stream.Collectors;
|
||||
@RequiredArgsConstructor
|
||||
public class PromotionServiceImpl implements PromotionService {
|
||||
|
||||
private static final ObjectMapper MAPPER = new ObjectMapper();
|
||||
|
||||
private final PromotionRepository promotionRepository;
|
||||
private final PromotionSkillRepository promotionSkillRepository;
|
||||
private final PromotionRecordRepository promotionRecordRepository;
|
||||
@@ -51,7 +56,7 @@ public class PromotionServiceImpl implements PromotionService {
|
||||
promotion.setStatus("draft");
|
||||
promotion.setStartTime(dto.getStartTime());
|
||||
promotion.setEndTime(dto.getEndTime());
|
||||
promotion.setRules(dto.getRules());
|
||||
promotion.setRules(serializeRules(dto.getRules()));
|
||||
promotion.setScopeType(dto.getScopeType() != null ? dto.getScopeType() : "all");
|
||||
promotion.setScopeValues(dto.getScopeValues());
|
||||
promotion.setExclusiveGroup(dto.getExclusiveGroup());
|
||||
@@ -95,7 +100,7 @@ public class PromotionServiceImpl implements PromotionService {
|
||||
if (dto.getType() != null) promotion.setType(dto.getType());
|
||||
if (dto.getStartTime() != null) promotion.setStartTime(dto.getStartTime());
|
||||
if (dto.getEndTime() != null) promotion.setEndTime(dto.getEndTime());
|
||||
if (dto.getRules() != null) promotion.setRules(dto.getRules());
|
||||
if (dto.getRules() != null) promotion.setRules(serializeRules(dto.getRules()));
|
||||
if (dto.getScopeType() != null) promotion.setScopeType(dto.getScopeType());
|
||||
if (dto.getScopeValues() != null) promotion.setScopeValues(dto.getScopeValues());
|
||||
if (dto.getExclusiveGroup() != null) promotion.setExclusiveGroup(dto.getExclusiveGroup());
|
||||
@@ -251,7 +256,7 @@ public class PromotionServiceImpl implements PromotionService {
|
||||
vo.setStatus(promotion.getStatus());
|
||||
vo.setStartTime(promotion.getStartTime());
|
||||
vo.setEndTime(promotion.getEndTime());
|
||||
vo.setRules(promotion.getRules());
|
||||
vo.setRules(parseRules(promotion.getRules()));
|
||||
vo.setScopeType(promotion.getScopeType());
|
||||
vo.setScopeValues(promotion.getScopeValues());
|
||||
vo.setExclusiveGroup(promotion.getExclusiveGroup());
|
||||
@@ -312,48 +317,112 @@ public class PromotionServiceImpl implements PromotionService {
|
||||
@Override
|
||||
public SkillPromotionVO getSkillPromotion(Long skillId) {
|
||||
LocalDateTime now = LocalDateTime.now();
|
||||
Skill skill = skillRepository.selectById(skillId);
|
||||
if (skill == null) return null;
|
||||
|
||||
Promotion bestPromotion = null;
|
||||
PromotionSkill bestPromotionSkill = null;
|
||||
int bestPriority = Integer.MIN_VALUE;
|
||||
|
||||
// 1. 直接指定skill的促销 (via promotion_skills table)
|
||||
List<PromotionSkill> promotionSkills = promotionSkillRepository.selectList(
|
||||
new LambdaQueryWrapper<PromotionSkill>().eq(PromotionSkill::getSkillId, skillId));
|
||||
if (!promotionSkills.isEmpty()) {
|
||||
List<Long> promotionIds = promotionSkills.stream()
|
||||
.map(PromotionSkill::getPromotionId).collect(Collectors.toList());
|
||||
List<Promotion> directPromotions = promotionRepository.selectList(
|
||||
new LambdaQueryWrapper<Promotion>()
|
||||
.in(Promotion::getId, promotionIds)
|
||||
.eq(Promotion::getStatus, "active")
|
||||
.le(Promotion::getStartTime, now)
|
||||
.ge(Promotion::getEndTime, now)
|
||||
.orderByDesc(Promotion::getPriority));
|
||||
if (!directPromotions.isEmpty()) {
|
||||
Promotion dp = directPromotions.get(0);
|
||||
int dpPriority = dp.getPriority() != null ? dp.getPriority() : 0;
|
||||
bestPromotion = dp;
|
||||
bestPriority = dpPriority;
|
||||
final Long dpId = dp.getId();
|
||||
bestPromotionSkill = promotionSkills.stream()
|
||||
.filter(ps -> ps.getPromotionId().equals(dpId))
|
||||
.findFirst().orElse(null);
|
||||
}
|
||||
}
|
||||
|
||||
if (promotionSkills.isEmpty()) return null;
|
||||
|
||||
List<Long> promotionIds = promotionSkills.stream()
|
||||
.map(PromotionSkill::getPromotionId).collect(Collectors.toList());
|
||||
|
||||
List<Promotion> activePromotions = promotionRepository.selectList(
|
||||
// 2. scopeType=all 全场促销
|
||||
List<Promotion> allPromotions = promotionRepository.selectList(
|
||||
new LambdaQueryWrapper<Promotion>()
|
||||
.in(Promotion::getId, promotionIds)
|
||||
.eq(Promotion::getScopeType, "all")
|
||||
.eq(Promotion::getStatus, "active")
|
||||
.le(Promotion::getStartTime, now)
|
||||
.ge(Promotion::getEndTime, now)
|
||||
.orderByDesc(Promotion::getPriority));
|
||||
if (!allPromotions.isEmpty()) {
|
||||
Promotion ap = allPromotions.get(0);
|
||||
int apPriority = ap.getPriority() != null ? ap.getPriority() : 0;
|
||||
if (apPriority > bestPriority) {
|
||||
bestPromotion = ap;
|
||||
bestPromotionSkill = null;
|
||||
bestPriority = apPriority;
|
||||
}
|
||||
}
|
||||
|
||||
if (activePromotions.isEmpty()) return null;
|
||||
// 3. scopeType=category 分类促销
|
||||
if (skill.getCategoryId() != null) {
|
||||
List<Promotion> catPromotions = promotionRepository.selectList(
|
||||
new LambdaQueryWrapper<Promotion>()
|
||||
.eq(Promotion::getScopeType, "category")
|
||||
.eq(Promotion::getStatus, "active")
|
||||
.le(Promotion::getStartTime, now)
|
||||
.ge(Promotion::getEndTime, now)
|
||||
.orderByDesc(Promotion::getPriority));
|
||||
for (Promotion cp : catPromotions) {
|
||||
int cpPriority = cp.getPriority() != null ? cp.getPriority() : 0;
|
||||
if (cpPriority <= bestPriority) break;
|
||||
if (matchesCategory(cp.getScopeValues(), skill.getCategoryId())) {
|
||||
bestPromotion = cp;
|
||||
bestPromotionSkill = null;
|
||||
bestPriority = cpPriority;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Promotion bestPromotion = activePromotions.get(0);
|
||||
PromotionSkill matchedSkill = promotionSkills.stream()
|
||||
.filter(ps -> ps.getPromotionId().equals(bestPromotion.getId()))
|
||||
.findFirst().orElse(null);
|
||||
if (bestPromotion == null) return null;
|
||||
|
||||
if (matchedSkill == null) return null;
|
||||
|
||||
Skill skill = skillRepository.selectById(skillId);
|
||||
// 检查 all/category 促销是否有针对此skill的PromotionSkill覆盖
|
||||
if (bestPromotionSkill == null && !promotionSkills.isEmpty()) {
|
||||
final Long bpId = bestPromotion.getId();
|
||||
bestPromotionSkill = promotionSkills.stream()
|
||||
.filter(ps -> ps.getPromotionId().equals(bpId))
|
||||
.findFirst().orElse(null);
|
||||
}
|
||||
|
||||
// 构建VO
|
||||
SkillPromotionVO vo = new SkillPromotionVO();
|
||||
vo.setSkillId(skillId);
|
||||
vo.setPromotionId(bestPromotion.getId());
|
||||
vo.setPromotionName(bestPromotion.getName());
|
||||
vo.setPromotionType(bestPromotion.getType());
|
||||
vo.setPromotionPrice(matchedSkill.getPromotionPrice());
|
||||
vo.setDiscountRate(matchedSkill.getDiscountRate());
|
||||
vo.setTagText(bestPromotion.getTagText());
|
||||
vo.setEndTime(bestPromotion.getEndTime());
|
||||
vo.setStockLimit(matchedSkill.getStockLimit());
|
||||
vo.setSoldCount(matchedSkill.getSoldCount());
|
||||
|
||||
if (skill != null && skill.getPrice() != null) {
|
||||
BigDecimal originalPrice = skill.getPrice();
|
||||
BigDecimal finalPrice = calculateFinalPrice(matchedSkill, originalPrice);
|
||||
BigDecimal originalPrice = skill.getPrice();
|
||||
BigDecimal finalPrice = originalPrice;
|
||||
|
||||
if (bestPromotionSkill != null) {
|
||||
vo.setPromotionPrice(bestPromotionSkill.getPromotionPrice());
|
||||
vo.setDiscountRate(bestPromotionSkill.getDiscountRate());
|
||||
vo.setStockLimit(bestPromotionSkill.getStockLimit());
|
||||
vo.setSoldCount(bestPromotionSkill.getSoldCount());
|
||||
if (originalPrice != null) {
|
||||
finalPrice = calculateFinalPrice(bestPromotionSkill, originalPrice);
|
||||
}
|
||||
} else if (originalPrice != null) {
|
||||
finalPrice = calculatePriceFromRules(bestPromotion.getRules(), originalPrice);
|
||||
}
|
||||
|
||||
if (originalPrice != null && finalPrice != null) {
|
||||
vo.setDiscountAmount(originalPrice.subtract(finalPrice));
|
||||
}
|
||||
|
||||
@@ -363,11 +432,135 @@ public class PromotionServiceImpl implements PromotionService {
|
||||
@Override
|
||||
public List<SkillPromotionVO> batchGetSkillPromotions(List<Long> skillIds) {
|
||||
if (skillIds == null || skillIds.isEmpty()) return Collections.emptyList();
|
||||
LocalDateTime now = LocalDateTime.now();
|
||||
|
||||
// 1. 批量加载Skill
|
||||
List<Skill> skills = skillRepository.selectBatchIds(skillIds);
|
||||
Map<Long, Skill> skillMap = skills.stream().collect(Collectors.toMap(Skill::getId, s -> s));
|
||||
|
||||
// 2. 批量加载所有相关的PromotionSkill
|
||||
List<PromotionSkill> allPromotionSkills = promotionSkillRepository.selectList(
|
||||
new LambdaQueryWrapper<PromotionSkill>().in(PromotionSkill::getSkillId, skillIds));
|
||||
Map<Long, List<PromotionSkill>> psMap = allPromotionSkills.stream()
|
||||
.collect(Collectors.groupingBy(PromotionSkill::getSkillId));
|
||||
|
||||
// 3. 收集所有关联的promotionId,一次性加载活跃促销
|
||||
List<Long> directPromotionIds = allPromotionSkills.stream()
|
||||
.map(PromotionSkill::getPromotionId).distinct().collect(Collectors.toList());
|
||||
|
||||
// 查询所有活跃促销(含direct/all/category三种scopeType)
|
||||
LambdaQueryWrapper<Promotion> activeWrapper = new LambdaQueryWrapper<Promotion>()
|
||||
.eq(Promotion::getStatus, "active")
|
||||
.le(Promotion::getStartTime, now)
|
||||
.ge(Promotion::getEndTime, now);
|
||||
if (!directPromotionIds.isEmpty()) {
|
||||
activeWrapper.and(w -> w
|
||||
.in(Promotion::getId, directPromotionIds)
|
||||
.or().eq(Promotion::getScopeType, "all")
|
||||
.or().eq(Promotion::getScopeType, "category"));
|
||||
} else {
|
||||
activeWrapper.and(w -> w
|
||||
.eq(Promotion::getScopeType, "all")
|
||||
.or().eq(Promotion::getScopeType, "category"));
|
||||
}
|
||||
activeWrapper.orderByDesc(Promotion::getPriority);
|
||||
List<Promotion> activePromotions = promotionRepository.selectList(activeWrapper);
|
||||
|
||||
// 按ID索引 & 按scopeType分组
|
||||
Map<Long, Promotion> promotionMap = activePromotions.stream()
|
||||
.collect(Collectors.toMap(Promotion::getId, p -> p, (a, b) -> a));
|
||||
List<Promotion> allScopePromotions = activePromotions.stream()
|
||||
.filter(p -> "all".equals(p.getScopeType())).collect(Collectors.toList());
|
||||
List<Promotion> catScopePromotions = activePromotions.stream()
|
||||
.filter(p -> "category".equals(p.getScopeType())).collect(Collectors.toList());
|
||||
|
||||
// 4. 为每个skillId匹配最优促销
|
||||
List<SkillPromotionVO> result = new ArrayList<>();
|
||||
for (Long skillId : skillIds) {
|
||||
SkillPromotionVO vo = getSkillPromotion(skillId);
|
||||
if (vo != null) result.add(vo);
|
||||
Skill skill = skillMap.get(skillId);
|
||||
if (skill == null) continue;
|
||||
|
||||
Promotion bestPromotion = null;
|
||||
PromotionSkill bestPs = null;
|
||||
int bestPriority = Integer.MIN_VALUE;
|
||||
|
||||
// 4a. direct skill promotions
|
||||
List<PromotionSkill> directPs = psMap.getOrDefault(skillId, Collections.emptyList());
|
||||
for (PromotionSkill ps : directPs) {
|
||||
Promotion p = promotionMap.get(ps.getPromotionId());
|
||||
if (p == null) continue;
|
||||
int pri = p.getPriority() != null ? p.getPriority() : 0;
|
||||
if (pri > bestPriority) {
|
||||
bestPromotion = p;
|
||||
bestPs = ps;
|
||||
bestPriority = pri;
|
||||
}
|
||||
}
|
||||
|
||||
// 4b. all scope
|
||||
if (!allScopePromotions.isEmpty()) {
|
||||
Promotion ap = allScopePromotions.get(0); // already sorted by priority desc
|
||||
int apPri = ap.getPriority() != null ? ap.getPriority() : 0;
|
||||
if (apPri > bestPriority) {
|
||||
bestPromotion = ap;
|
||||
bestPs = null;
|
||||
bestPriority = apPri;
|
||||
}
|
||||
}
|
||||
|
||||
// 4c. category scope
|
||||
if (skill.getCategoryId() != null) {
|
||||
for (Promotion cp : catScopePromotions) {
|
||||
int cpPri = cp.getPriority() != null ? cp.getPriority() : 0;
|
||||
if (cpPri <= bestPriority) break;
|
||||
if (matchesCategory(cp.getScopeValues(), skill.getCategoryId())) {
|
||||
bestPromotion = cp;
|
||||
bestPs = null;
|
||||
bestPriority = cpPri;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (bestPromotion == null) continue;
|
||||
|
||||
// 检查PromotionSkill覆盖
|
||||
if (bestPs == null && !directPs.isEmpty()) {
|
||||
final Long bpId = bestPromotion.getId();
|
||||
bestPs = directPs.stream()
|
||||
.filter(ps -> ps.getPromotionId().equals(bpId))
|
||||
.findFirst().orElse(null);
|
||||
}
|
||||
|
||||
// 构建VO
|
||||
SkillPromotionVO vo = new SkillPromotionVO();
|
||||
vo.setSkillId(skillId);
|
||||
vo.setPromotionId(bestPromotion.getId());
|
||||
vo.setPromotionName(bestPromotion.getName());
|
||||
vo.setPromotionType(bestPromotion.getType());
|
||||
vo.setTagText(bestPromotion.getTagText());
|
||||
vo.setEndTime(bestPromotion.getEndTime());
|
||||
|
||||
BigDecimal originalPrice = skill.getPrice();
|
||||
BigDecimal finalPrice = originalPrice;
|
||||
|
||||
if (bestPs != null) {
|
||||
vo.setPromotionPrice(bestPs.getPromotionPrice());
|
||||
vo.setDiscountRate(bestPs.getDiscountRate());
|
||||
vo.setStockLimit(bestPs.getStockLimit());
|
||||
vo.setSoldCount(bestPs.getSoldCount());
|
||||
if (originalPrice != null) {
|
||||
finalPrice = calculateFinalPrice(bestPs, originalPrice);
|
||||
}
|
||||
} else if (originalPrice != null) {
|
||||
finalPrice = calculatePriceFromRules(bestPromotion.getRules(), originalPrice);
|
||||
}
|
||||
|
||||
if (originalPrice != null && finalPrice != null) {
|
||||
vo.setDiscountAmount(originalPrice.subtract(finalPrice));
|
||||
}
|
||||
|
||||
result.add(vo);
|
||||
}
|
||||
return result;
|
||||
}
|
||||
@@ -424,6 +617,75 @@ public class PromotionServiceImpl implements PromotionService {
|
||||
return usedCount < promotion.getUserLimit();
|
||||
}
|
||||
|
||||
/** 判断分类ID是否在scopeValues JSON数组中 */
|
||||
private boolean matchesCategory(String scopeValues, Integer categoryId) {
|
||||
if (scopeValues == null || scopeValues.isBlank() || categoryId == null) return false;
|
||||
try {
|
||||
List<?> ids = MAPPER.readValue(scopeValues, List.class);
|
||||
return ids.stream().anyMatch(id -> {
|
||||
if (id instanceof Number) return ((Number) id).intValue() == categoryId;
|
||||
return String.valueOf(id).equals(String.valueOf(categoryId));
|
||||
});
|
||||
} catch (Exception e) {
|
||||
log.warn("[Promotion] 解析scopeValues失败: {}", scopeValues, e);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/** PromotionRules -> JSON字符串 */
|
||||
private String serializeRules(PromotionRules rules) {
|
||||
if (rules == null) return null;
|
||||
try {
|
||||
return MAPPER.writeValueAsString(rules);
|
||||
} catch (Exception e) {
|
||||
log.warn("[Promotion] 序列化rules失败", e);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/** JSON字符串 -> PromotionRules */
|
||||
private PromotionRules parseRules(String rulesJson) {
|
||||
if (rulesJson == null || rulesJson.isBlank()) return null;
|
||||
try {
|
||||
return MAPPER.readValue(rulesJson, PromotionRules.class);
|
||||
} catch (Exception e) {
|
||||
log.warn("[Promotion] 反序列化rules失败: {}", rulesJson, e);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/** 从rules JSON解析折扣规则计算最终价格 */
|
||||
@SuppressWarnings("unchecked")
|
||||
private BigDecimal calculatePriceFromRules(String rulesJson, BigDecimal originalPrice) {
|
||||
if (rulesJson == null || rulesJson.isBlank() || originalPrice == null) return originalPrice;
|
||||
try {
|
||||
Map<String, Object> rules = MAPPER.readValue(rulesJson, Map.class);
|
||||
// 固定促销价
|
||||
if (rules.containsKey("promotionPrice")) {
|
||||
return new BigDecimal(String.valueOf(rules.get("promotionPrice")));
|
||||
}
|
||||
// 折扣率 (0.8 = 八折)
|
||||
if (rules.containsKey("discountRate")) {
|
||||
BigDecimal rate = new BigDecimal(String.valueOf(rules.get("discountRate")));
|
||||
return originalPrice.multiply(rate).setScale(2, RoundingMode.HALF_UP);
|
||||
}
|
||||
// 直减金额
|
||||
if (rules.containsKey("discountAmount")) {
|
||||
BigDecimal amount = new BigDecimal(String.valueOf(rules.get("discountAmount")));
|
||||
BigDecimal result = originalPrice.subtract(amount);
|
||||
return result.compareTo(BigDecimal.ZERO) > 0 ? result : BigDecimal.ZERO;
|
||||
}
|
||||
} catch (Exception e) {
|
||||
log.warn("[Promotion] 解析促销规则失败: {}", rulesJson, e);
|
||||
}
|
||||
return originalPrice;
|
||||
}
|
||||
|
||||
@Override
|
||||
public int batchExpirePromotions() {
|
||||
return promotionRepository.batchExpirePromotions();
|
||||
}
|
||||
|
||||
private BigDecimal calculateFinalPrice(PromotionSkill ps, BigDecimal originalPrice) {
|
||||
if (ps.getPromotionPrice() != null) {
|
||||
return ps.getPromotionPrice();
|
||||
|
||||
@@ -0,0 +1,28 @@
|
||||
package com.openclaw.module.promotion.task;
|
||||
|
||||
import com.openclaw.module.promotion.service.PromotionService;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import lombok.extern.slf4j.Slf4j;
|
||||
import org.springframework.scheduling.annotation.Scheduled;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
@Slf4j
|
||||
@Component
|
||||
@RequiredArgsConstructor
|
||||
public class PromotionExpireTask {
|
||||
|
||||
private final PromotionService promotionService;
|
||||
|
||||
/** 每10分钟执行一次: 批量结束已过期的促销活动 */
|
||||
@Scheduled(cron = "0 */10 * * * ?")
|
||||
public void expirePromotions() {
|
||||
try {
|
||||
int count = promotionService.batchExpirePromotions();
|
||||
if (count > 0) {
|
||||
log.info("[PromotionExpireTask] 本次过期促销活动: {}个", count);
|
||||
}
|
||||
} catch (Exception e) {
|
||||
log.error("[PromotionExpireTask] 执行失败", e);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,6 @@
|
||||
package com.openclaw.module.promotion.vo;
|
||||
|
||||
import com.openclaw.module.promotion.dto.PromotionRules;
|
||||
import lombok.Data;
|
||||
|
||||
import java.time.LocalDateTime;
|
||||
@@ -13,7 +14,7 @@ public class PromotionDetailVO {
|
||||
private String status;
|
||||
private LocalDateTime startTime;
|
||||
private LocalDateTime endTime;
|
||||
private String rules;
|
||||
private PromotionRules rules;
|
||||
private String scopeType;
|
||||
private String scopeValues;
|
||||
private String exclusiveGroup;
|
||||
|
||||
@@ -7,6 +7,7 @@ import java.time.LocalDateTime;
|
||||
|
||||
@Data
|
||||
public class SkillPromotionVO {
|
||||
private Long skillId;
|
||||
private Long promotionId;
|
||||
private String promotionName;
|
||||
private String promotionType;
|
||||
|
||||
@@ -5,6 +5,8 @@ import com.openclaw.common.Result;
|
||||
import com.openclaw.module.skill.entity.SkillCategory;
|
||||
import com.openclaw.module.skill.repository.SkillCategoryRepository;
|
||||
import com.openclaw.module.skill.vo.CategoryVO;
|
||||
import io.swagger.v3.oas.annotations.Operation;
|
||||
import io.swagger.v3.oas.annotations.tags.Tag;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
|
||||
@@ -13,6 +15,7 @@ import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
@Tag(name = "分类管理", description = "技能分类树查询")
|
||||
@RestController
|
||||
@RequestMapping("/api/v1/categories")
|
||||
@RequiredArgsConstructor
|
||||
@@ -20,7 +23,7 @@ public class CategoryController {
|
||||
|
||||
private final SkillCategoryRepository categoryRepository;
|
||||
|
||||
/** 获取分类树(公开) */
|
||||
@Operation(summary = "获取分类树", description = "公开接口,返回树形结构")
|
||||
@GetMapping
|
||||
public Result<List<CategoryVO>> listCategories() {
|
||||
List<SkillCategory> all = categoryRepository.selectList(
|
||||
@@ -29,7 +32,7 @@ public class CategoryController {
|
||||
return Result.ok(buildTree(all));
|
||||
}
|
||||
|
||||
/** 获取单个分类 */
|
||||
@Operation(summary = "获取单个分类")
|
||||
@GetMapping("/{id}")
|
||||
public Result<CategoryVO> getCategory(@PathVariable Integer id) {
|
||||
SkillCategory cat = categoryRepository.selectById(id);
|
||||
|
||||
@@ -7,11 +7,14 @@ import com.openclaw.module.skill.service.SkillService;
|
||||
import com.openclaw.annotation.RequiresRole;
|
||||
import com.openclaw.util.UserContext;
|
||||
import com.openclaw.module.skill.vo.*;
|
||||
import io.swagger.v3.oas.annotations.Operation;
|
||||
import io.swagger.v3.oas.annotations.tags.Tag;
|
||||
import jakarta.validation.Valid;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
import java.util.List;
|
||||
|
||||
@Tag(name = "技能商城", description = "Skill列表、详情、评价、榜单、CRUD")
|
||||
@RestController
|
||||
@RequestMapping("/api/v1/skills")
|
||||
@RequiredArgsConstructor
|
||||
@@ -19,27 +22,27 @@ public class SkillController {
|
||||
|
||||
private final SkillService skillService;
|
||||
|
||||
/** Skill列表(公开,支持分页/筛选/排序) */
|
||||
@Operation(summary = "Skill列表", description = "公开接口,支持分页/分类/价格/排序筛选")
|
||||
@GetMapping
|
||||
public Result<IPage<SkillVO>> listSkills(SkillQueryDTO query) {
|
||||
Long userId = UserContext.getUserId(); // 未登录为null
|
||||
return Result.ok(skillService.listSkills(query, userId));
|
||||
}
|
||||
|
||||
/** Skill详情(公开) */
|
||||
@Operation(summary = "Skill详情", description = "公开接口,获取单个Skill完整信息")
|
||||
@GetMapping("/{id}")
|
||||
public Result<SkillVO> getDetail(@PathVariable Long id) {
|
||||
return Result.ok(skillService.getSkillDetail(id, UserContext.getUserId()));
|
||||
}
|
||||
|
||||
/** 上传Skill(需登录,creator及以上) */
|
||||
@Operation(summary = "创建Skill", description = "需creator及以上角色")
|
||||
@RequiresRole({"creator", "admin", "super_admin"})
|
||||
@PostMapping
|
||||
public Result<SkillVO> createSkill(@Valid @RequestBody SkillCreateDTO dto) {
|
||||
return Result.ok(skillService.createSkill(UserContext.getUserId(), dto));
|
||||
}
|
||||
|
||||
/** 更新Skill(创建者本人) */
|
||||
@Operation(summary = "更新Skill")
|
||||
@RequiresRole({"creator", "admin", "super_admin"})
|
||||
@PutMapping("/{id}")
|
||||
public Result<SkillVO> updateSkill(
|
||||
@@ -48,7 +51,7 @@ public class SkillController {
|
||||
return Result.ok(skillService.updateSkill(UserContext.getUserId(), id, dto));
|
||||
}
|
||||
|
||||
/** 删除Skill(创建者本人) */
|
||||
@Operation(summary = "删除Skill")
|
||||
@RequiresRole({"creator", "admin", "super_admin"})
|
||||
@DeleteMapping("/{id}")
|
||||
public Result<Void> deleteSkill(@PathVariable Long id) {
|
||||
@@ -56,7 +59,7 @@ public class SkillController {
|
||||
return Result.ok();
|
||||
}
|
||||
|
||||
/** 获取Skill评论列表(公开) */
|
||||
@Operation(summary = "获取评论列表", description = "公开接口,分页")
|
||||
@GetMapping("/{id}/reviews")
|
||||
public Result<IPage<SkillReviewVO>> getReviews(
|
||||
@PathVariable Long id,
|
||||
@@ -65,7 +68,7 @@ public class SkillController {
|
||||
return Result.ok(skillService.getReviews(id, UserContext.getUserId(), pageNum, pageSize));
|
||||
}
|
||||
|
||||
/** 发表评价(需登录且已拥有) */
|
||||
@Operation(summary = "发表评价", description = "需登录且已购买")
|
||||
@RequiresRole("user")
|
||||
@PostMapping("/{id}/reviews")
|
||||
public Result<Void> submitReview(
|
||||
@@ -75,7 +78,7 @@ public class SkillController {
|
||||
return Result.ok();
|
||||
}
|
||||
|
||||
/** 点赞评论 */
|
||||
@Operation(summary = "点赞评论")
|
||||
@RequiresRole("user")
|
||||
@PostMapping("/reviews/{reviewId}/like")
|
||||
public Result<Void> likeReview(@PathVariable Long reviewId) {
|
||||
@@ -83,7 +86,7 @@ public class SkillController {
|
||||
return Result.ok();
|
||||
}
|
||||
|
||||
/** 删除自己的评论 */
|
||||
@Operation(summary = "删除评论")
|
||||
@RequiresRole("user")
|
||||
@DeleteMapping("/reviews/{reviewId}")
|
||||
public Result<Void> deleteReview(@PathVariable Long reviewId) {
|
||||
@@ -91,7 +94,7 @@ public class SkillController {
|
||||
return Result.ok();
|
||||
}
|
||||
|
||||
/** 热门榜单(公开) */
|
||||
@Operation(summary = "热门榜单", description = "公开接口,按下载/评分/最新排序")
|
||||
@GetMapping("/ranking")
|
||||
public Result<List<SkillVO>> getRanking(
|
||||
@RequestParam(defaultValue = "downloads") String sortBy,
|
||||
|
||||
@@ -5,6 +5,8 @@ import com.openclaw.common.Result;
|
||||
import com.openclaw.module.skill.entity.SkillFavorite;
|
||||
import com.openclaw.module.skill.repository.SkillFavoriteRepository;
|
||||
import com.openclaw.util.UserContext;
|
||||
import io.swagger.v3.oas.annotations.Operation;
|
||||
import io.swagger.v3.oas.annotations.tags.Tag;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
|
||||
@@ -13,6 +15,7 @@ import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
@Tag(name = "收藏管理", description = "收藏/取消收藏Skill")
|
||||
@RestController
|
||||
@RequestMapping("/api/v1/favorites")
|
||||
@RequiredArgsConstructor
|
||||
@@ -20,9 +23,7 @@ public class SkillFavoriteController {
|
||||
|
||||
private final SkillFavoriteRepository favoriteRepository;
|
||||
|
||||
/**
|
||||
* 收藏/取消收藏
|
||||
*/
|
||||
@Operation(summary = "收藏/取消收藏", description = "切换收藏状态")
|
||||
@PostMapping("/{skillId}")
|
||||
public Result<Map<String, Object>> toggleFavorite(@PathVariable Long skillId) {
|
||||
Long userId = UserContext.getUserId();
|
||||
@@ -48,9 +49,7 @@ public class SkillFavoriteController {
|
||||
return Result.ok(result);
|
||||
}
|
||||
|
||||
/**
|
||||
* 查询是否已收藏
|
||||
*/
|
||||
@Operation(summary = "查询是否已收藏")
|
||||
@GetMapping("/{skillId}")
|
||||
public Result<Map<String, Object>> checkFavorite(@PathVariable Long skillId) {
|
||||
Long userId = UserContext.getUserId();
|
||||
@@ -60,9 +59,7 @@ public class SkillFavoriteController {
|
||||
return Result.ok(result);
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取我的收藏列表
|
||||
*/
|
||||
@Operation(summary = "获取我的收藏列表", description = "返回收藏Skill ID列表")
|
||||
@GetMapping
|
||||
public Result<List<Long>> getMyFavorites() {
|
||||
Long userId = UserContext.getUserId();
|
||||
|
||||
@@ -13,6 +13,7 @@ import com.openclaw.module.user.entity.User;
|
||||
import com.openclaw.module.user.repository.UserRepository;
|
||||
import com.openclaw.module.skill.vo.*;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.data.redis.core.StringRedisTemplate;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
@@ -25,6 +26,7 @@ public class SkillServiceImpl implements SkillService {
|
||||
private final SkillReviewRepository reviewRepository;
|
||||
private final SkillDownloadRepository downloadRepository;
|
||||
private final UserRepository userRepository;
|
||||
private final StringRedisTemplate redisTemplate;
|
||||
|
||||
@Override
|
||||
public IPage<SkillVO> listSkills(SkillQueryDTO query, Long currentUserId) {
|
||||
@@ -81,8 +83,14 @@ public class SkillServiceImpl implements SkillService {
|
||||
@Override
|
||||
@Transactional
|
||||
public void submitReview(Long skillId, Long userId, SkillReviewDTO dto) {
|
||||
// 检查是否已购买
|
||||
if (!hasOwned(userId, skillId)) throw new BusinessException(ErrorCode.SKILL_NOT_FOUND);
|
||||
// 检查是否已获取
|
||||
if (!hasOwned(userId, skillId)) throw new BusinessException(ErrorCode.REVIEW_NOT_ALLOWED);
|
||||
// 检查是否已评价过
|
||||
Long existCount = reviewRepository.selectCount(
|
||||
new LambdaQueryWrapper<SkillReview>()
|
||||
.eq(SkillReview::getSkillId, skillId)
|
||||
.eq(SkillReview::getUserId, userId));
|
||||
if (existCount > 0) throw new BusinessException(ErrorCode.REVIEW_DUPLICATE);
|
||||
|
||||
SkillReview review = new SkillReview();
|
||||
review.setSkillId(skillId);
|
||||
@@ -111,6 +119,10 @@ public class SkillServiceImpl implements SkillService {
|
||||
@Override
|
||||
@Transactional
|
||||
public void grantAccess(Long userId, Long skillId, Long orderId, String type) {
|
||||
// 幂等:已拥有则跳过,防止唯一约束 uk_user_skill 冲突
|
||||
if (hasOwned(userId, skillId)) {
|
||||
return;
|
||||
}
|
||||
SkillDownload d = new SkillDownload();
|
||||
d.setUserId(userId);
|
||||
d.setSkillId(skillId);
|
||||
@@ -166,6 +178,14 @@ public class SkillServiceImpl implements SkillService {
|
||||
public void likeReview(Long reviewId, Long userId) {
|
||||
SkillReview review = reviewRepository.selectById(reviewId);
|
||||
if (review == null) throw new BusinessException(400, "评论不存在");
|
||||
// 防刷:Redis Set 去重,每个用户对同一评论只能点赞一次
|
||||
String key = "review:like:" + reviewId;
|
||||
Boolean added = redisTemplate.opsForSet().add(key, String.valueOf(userId)) == 1;
|
||||
if (Boolean.FALSE.equals(added)) {
|
||||
throw new BusinessException(400, "您已点赞过该评论");
|
||||
}
|
||||
// 设置30天过期,避免Redis无限膨胀
|
||||
redisTemplate.expire(key, 30, java.util.concurrent.TimeUnit.DAYS);
|
||||
review.setHelpfulCount(review.getHelpfulCount() == null ? 1 : review.getHelpfulCount() + 1);
|
||||
reviewRepository.updateById(review);
|
||||
}
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
package com.openclaw.module.user.controller;
|
||||
|
||||
import com.openclaw.annotation.RateLimit;
|
||||
import com.openclaw.common.Result;
|
||||
import com.openclaw.module.log.annotation.OpLog;
|
||||
import com.openclaw.module.user.dto.*;
|
||||
@@ -7,6 +8,8 @@ import com.openclaw.module.user.service.UserService;
|
||||
import com.openclaw.annotation.RequiresRole;
|
||||
import com.openclaw.util.UserContext;
|
||||
import com.openclaw.module.user.vo.*;
|
||||
import io.swagger.v3.oas.annotations.Operation;
|
||||
import io.swagger.v3.oas.annotations.tags.Tag;
|
||||
import jakarta.servlet.http.HttpServletRequest;
|
||||
import jakarta.validation.Valid;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
@@ -14,6 +17,7 @@ import org.springframework.web.bind.annotation.*;
|
||||
|
||||
import java.util.Map;
|
||||
|
||||
@Tag(name = "用户账户", description = "注册、登录、个人信息、密码管理、换号")
|
||||
@RestController
|
||||
@RequestMapping("/api/v1/users")
|
||||
@RequiredArgsConstructor
|
||||
@@ -21,7 +25,8 @@ public class UserController {
|
||||
|
||||
private final UserService userService;
|
||||
|
||||
/** 发送短信验证码(注册/找回密码用) */
|
||||
@Operation(summary = "发送短信验证码", description = "注册/找回密码时发送短信验证码,60秒内限1次")
|
||||
@RateLimit(window = 60, maxRequests = 1, message = "短信发送过于频繁,请60秒后再试")
|
||||
@PostMapping("/sms/code")
|
||||
public Result<Void> sendSmsCode(@Valid @RequestBody SmsCodeDTO dto, HttpServletRequest request) {
|
||||
String ip = getClientIp(request);
|
||||
@@ -46,19 +51,21 @@ public class UserController {
|
||||
return ip;
|
||||
}
|
||||
|
||||
/** 用户注册 */
|
||||
@Operation(summary = "用户注册", description = "手机号+短信验证码注册,返回JWT令牌")
|
||||
@RateLimit(window = 60, maxRequests = 5, message = "注册请求过于频繁,请稍后再试")
|
||||
@PostMapping("/register")
|
||||
public Result<LoginVO> register(@Valid @RequestBody UserRegisterDTO dto) {
|
||||
return Result.ok(userService.register(dto));
|
||||
}
|
||||
|
||||
/** 用户登录 */
|
||||
@Operation(summary = "用户登录", description = "手机号+密码登录,返回JWT令牌")
|
||||
@RateLimit(window = 60, maxRequests = 10, message = "登录请求过于频繁,请稍后再试")
|
||||
@PostMapping("/login")
|
||||
public Result<LoginVO> login(@Valid @RequestBody UserLoginDTO dto) {
|
||||
return Result.ok(userService.login(dto));
|
||||
}
|
||||
|
||||
/** 退出登录 */
|
||||
@Operation(summary = "退出登录")
|
||||
@RequiresRole("user")
|
||||
@PostMapping("/logout")
|
||||
public Result<Void> logout(@RequestHeader("Authorization") String authorization) {
|
||||
@@ -67,14 +74,14 @@ public class UserController {
|
||||
return Result.ok();
|
||||
}
|
||||
|
||||
/** 获取当前用户信息 */
|
||||
@Operation(summary = "获取当前用户信息")
|
||||
@RequiresRole("user")
|
||||
@GetMapping("/profile")
|
||||
public Result<UserVO> getProfile() {
|
||||
return Result.ok(userService.getCurrentUser(UserContext.getUserId()));
|
||||
}
|
||||
|
||||
/** 更新个人信息 */
|
||||
@Operation(summary = "更新个人信息", description = "修改昵称、头像、邮箱、简介等")
|
||||
@RequiresRole("user")
|
||||
@PutMapping("/profile")
|
||||
public Result<UserVO> updateProfile(@Valid @RequestBody UserUpdateDTO dto) {
|
||||
@@ -90,7 +97,7 @@ public class UserController {
|
||||
return Result.ok();
|
||||
}
|
||||
|
||||
/** 获取当前用户脱敏手机号(换号页面初始化用) */
|
||||
@Operation(summary = "获取脱敏手机号", description = "换号页面初始化用")
|
||||
@RequiresRole("user")
|
||||
@GetMapping("/phone/masked")
|
||||
public Result<Map<String, String>> getMaskedPhone() {
|
||||
@@ -98,7 +105,7 @@ public class UserController {
|
||||
return Result.ok(Map.of("maskedPhone", masked));
|
||||
}
|
||||
|
||||
/** 换号 Step1:验证原手机号短信码 */
|
||||
@Operation(summary = "换号Step1-验证原手机号", description = "验证原手机号短信码,返回ticket")
|
||||
@RequiresRole("user")
|
||||
@PostMapping("/phone/verify")
|
||||
@OpLog(module = "user", action = "update", description = "换号Step1-验证原手机号", targetType = "user")
|
||||
@@ -106,7 +113,7 @@ public class UserController {
|
||||
return Result.ok(userService.verifyOldPhone(UserContext.getUserId(), dto));
|
||||
}
|
||||
|
||||
/** 换号 Step2:凭 ticket 绑定新手机号 */
|
||||
@Operation(summary = "换号Step2-绑定新手机号", description = "凭ticket绑定新手机号")
|
||||
@RequiresRole("user")
|
||||
@PostMapping("/phone/bind")
|
||||
@OpLog(module = "user", action = "update", description = "换号Step2-绑定新手机号", targetType = "user")
|
||||
@@ -115,7 +122,7 @@ public class UserController {
|
||||
return Result.ok();
|
||||
}
|
||||
|
||||
/** 修改密码 */
|
||||
@Operation(summary = "修改密码", description = "需提供旧密码验证")
|
||||
@RequiresRole("user")
|
||||
@PutMapping("/password")
|
||||
public Result<Void> changePassword(@Valid @RequestBody ChangePasswordDTO dto) {
|
||||
@@ -123,7 +130,8 @@ public class UserController {
|
||||
return Result.ok();
|
||||
}
|
||||
|
||||
/** 忘记密码 - 重置 */
|
||||
@Operation(summary = "忘记密码-重置", description = "通过手机号+短信验证码重置密码")
|
||||
@RateLimit(window = 60, maxRequests = 5, message = "密码重置请求过于频繁,请稍后再试")
|
||||
@PostMapping("/password/reset")
|
||||
public Result<Void> resetPassword(@Valid @RequestBody ResetPasswordDTO dto) {
|
||||
userService.resetPassword(dto.getPhone(), dto.getSmsCode(), dto.getNewPassword());
|
||||
|
||||
@@ -6,12 +6,15 @@ import com.openclaw.module.user.dto.WechatBindPhoneDTO;
|
||||
import com.openclaw.module.user.dto.WechatLoginDTO;
|
||||
import com.openclaw.module.user.service.WechatAuthService;
|
||||
import com.openclaw.module.user.vo.WechatLoginVO;
|
||||
import io.swagger.v3.oas.annotations.Operation;
|
||||
import io.swagger.v3.oas.annotations.tags.Tag;
|
||||
import jakarta.validation.Valid;
|
||||
import lombok.RequiredArgsConstructor;
|
||||
import org.springframework.web.bind.annotation.*;
|
||||
|
||||
import java.util.Map;
|
||||
|
||||
@Tag(name = "微信认证", description = "微信扫码登录、绑定/解绑微信")
|
||||
@RestController
|
||||
@RequestMapping("/api/v1/wechat")
|
||||
@RequiredArgsConstructor
|
||||
@@ -19,28 +22,28 @@ public class WechatAuthController {
|
||||
|
||||
private final WechatAuthService wechatAuthService;
|
||||
|
||||
/** 获取微信扫码登录授权URL(无需登录) */
|
||||
@Operation(summary = "获取微信扫码授权URL")
|
||||
@GetMapping("/authorize-url")
|
||||
public Result<Map<String, String>> getAuthorizeUrl() {
|
||||
String url = wechatAuthService.getAuthorizeUrl();
|
||||
return Result.ok(Map.of("authorizeUrl", url));
|
||||
}
|
||||
|
||||
/** 微信扫码回调登录(无需登录) */
|
||||
@Operation(summary = "微信扫码登录", description = "凭code换取用户信息并登录")
|
||||
@PostMapping("/login")
|
||||
public Result<WechatLoginVO> login(@RequestBody @Valid WechatLoginDTO dto) {
|
||||
WechatLoginVO vo = wechatAuthService.loginByCode(dto.getCode(), dto.getState());
|
||||
return Result.ok(vo);
|
||||
}
|
||||
|
||||
/** 绑定手机号(无需登录,用bindTicket) */
|
||||
@Operation(summary = "微信用户绑定手机号")
|
||||
@PostMapping("/bind-phone")
|
||||
public Result<WechatLoginVO> bindPhone(@RequestBody @Valid WechatBindPhoneDTO dto) {
|
||||
WechatLoginVO vo = wechatAuthService.bindPhone(dto);
|
||||
return Result.ok(vo);
|
||||
}
|
||||
|
||||
/** 已登录用户绑定微信(需登录) */
|
||||
@Operation(summary = "已登录用户绑定微信")
|
||||
@PostMapping("/bind")
|
||||
public Result<Void> bindWechat(@RequestBody @Valid WechatLoginDTO dto) {
|
||||
Long userId = UserContext.getUserId();
|
||||
@@ -48,7 +51,7 @@ public class WechatAuthController {
|
||||
return Result.ok();
|
||||
}
|
||||
|
||||
/** 已登录用户解绑微信(需登录) */
|
||||
@Operation(summary = "解绑微信")
|
||||
@PostMapping("/unbind")
|
||||
public Result<Void> unbindWechat() {
|
||||
Long userId = UserContext.getUserId();
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
package com.openclaw.module.user.entity;
|
||||
|
||||
import com.baomidou.mybatisplus.annotation.*;
|
||||
import com.fasterxml.jackson.annotation.JsonIgnore;
|
||||
import lombok.Data;
|
||||
import java.time.LocalDateTime;
|
||||
|
||||
@@ -10,6 +11,7 @@ public class User {
|
||||
@TableId(type = IdType.AUTO)
|
||||
private Long id;
|
||||
private String phone;
|
||||
@JsonIgnore
|
||||
private String passwordHash;
|
||||
private String nickname;
|
||||
private String avatarUrl;
|
||||
|
||||
@@ -23,6 +23,8 @@ import org.springframework.data.redis.core.StringRedisTemplate;
|
||||
import org.springframework.security.crypto.password.PasswordEncoder;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
import org.springframework.transaction.support.TransactionSynchronization;
|
||||
import org.springframework.transaction.support.TransactionSynchronizationManager;
|
||||
import java.util.UUID;
|
||||
import java.util.concurrent.TimeUnit;
|
||||
|
||||
@@ -105,20 +107,31 @@ public class UserServiceImpl implements UserService {
|
||||
profile.setAuthStatus("none");
|
||||
userProfileRepository.insert(profile);
|
||||
|
||||
// 5. 发布用户注册事件(异步处理:初始化积分、注册奖励、邀请码生成、邀请绑定)
|
||||
try {
|
||||
UserRegisteredEvent event = new UserRegisteredEvent(user.getId(), dto.getInviteCode());
|
||||
rabbitTemplate.convertAndSend(MQConstants.EXCHANGE_TOPIC, MQConstants.RK_USER_REGISTERED, event);
|
||||
log.info("[MQ] 发布用户注册事件: userId={}", user.getId());
|
||||
} catch (Exception e) {
|
||||
log.error("[MQ] 发布用户注册事件失败,降级同步处理: userId={}", user.getId(), e);
|
||||
pointsService.initUserPoints(user.getId());
|
||||
pointsService.earnPoints(user.getId(), "register", user.getId(), "user");
|
||||
inviteService.generateInviteCode(user.getId());
|
||||
if (dto.getInviteCode() != null) {
|
||||
inviteService.handleInviteRegister(dto.getInviteCode(), user.getId());
|
||||
// 5. 事务提交后再发布MQ事件,避免消费者在用户记录未入库时处理消息
|
||||
final Long newUserId = user.getId();
|
||||
final String invCode = dto.getInviteCode();
|
||||
TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronization() {
|
||||
@Override
|
||||
public void afterCommit() {
|
||||
try {
|
||||
UserRegisteredEvent event = new UserRegisteredEvent(newUserId, invCode);
|
||||
rabbitTemplate.convertAndSend(MQConstants.EXCHANGE_TOPIC, MQConstants.RK_USER_REGISTERED, event);
|
||||
log.info("[MQ] 发布用户注册事件: userId={}", newUserId);
|
||||
} catch (Exception e) {
|
||||
log.error("[MQ] 发布用户注册事件失败,降级同步处理: userId={}", newUserId, e);
|
||||
try {
|
||||
pointsService.initUserPoints(newUserId);
|
||||
pointsService.earnPoints(newUserId, "register", newUserId, "user");
|
||||
inviteService.generateInviteCode(newUserId);
|
||||
if (invCode != null && !invCode.isBlank()) {
|
||||
inviteService.handleInviteRegister(invCode, newUserId);
|
||||
}
|
||||
} catch (Exception ex) {
|
||||
log.error("[Sync] 同步降级处理也失败: userId={}", newUserId, ex);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
// 8. 清除验证码
|
||||
redisTemplate.delete("captcha:sms:" + dto.getPhone());
|
||||
@@ -223,6 +236,7 @@ public class UserServiceImpl implements UserService {
|
||||
@Override
|
||||
public void changePassword(Long userId, String oldPwd, String newPwd) {
|
||||
User user = userRepository.selectById(userId);
|
||||
if (user == null) throw new BusinessException(ErrorCode.USER_NOT_FOUND);
|
||||
if (!passwordEncoder.matches(oldPwd, user.getPasswordHash()))
|
||||
throw new BusinessException(ErrorCode.PASSWORD_ERROR);
|
||||
user.setPasswordHash(passwordEncoder.encode(newPwd));
|
||||
|
||||
@@ -1,7 +1,10 @@
|
||||
server:
|
||||
port: 8080
|
||||
address: 0.0.0.0
|
||||
|
||||
spring:
|
||||
config:
|
||||
import: optional:classpath:application-local.yml
|
||||
servlet:
|
||||
multipart:
|
||||
max-file-size: 100MB
|
||||
@@ -42,10 +45,28 @@ spring:
|
||||
max-idle: 10
|
||||
min-idle: 2
|
||||
|
||||
logging:
|
||||
level:
|
||||
root: INFO
|
||||
com.openclaw: INFO
|
||||
com.openclaw.module.log.aspect: WARN
|
||||
org.springframework: WARN
|
||||
org.springframework.web: WARN
|
||||
org.springframework.security: WARN
|
||||
org.springframework.amqp: WARN
|
||||
org.mybatis: WARN
|
||||
com.baomidou.mybatisplus: WARN
|
||||
org.apache.ibatis: WARN
|
||||
com.zaxxer.hikari: WARN
|
||||
io.lettuce: WARN
|
||||
io.netty: WARN
|
||||
org.hibernate: WARN
|
||||
springdoc: WARN
|
||||
org.springdoc: WARN
|
||||
|
||||
mybatis-plus:
|
||||
configuration:
|
||||
map-underscore-to-camel-case: true
|
||||
log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
|
||||
global-config:
|
||||
db-config:
|
||||
logic-delete-field: deleted
|
||||
@@ -109,15 +130,15 @@ info:
|
||||
# 腾讯云短信配置
|
||||
tencent:
|
||||
sms:
|
||||
secret-id: ${SMS_SECRET_ID:AKIDlW1GEwPcZGhx1d4HFyRggQu88tPgiWwI}
|
||||
secret-key: ${SMS_SECRET_KEY:AKJ3XljSv85mEUXLtDJ9j3JK5appZ3HF}
|
||||
secret-id: ${SMS_SECRET_ID:${COS_SECRET_ID:}}
|
||||
secret-key: ${SMS_SECRET_KEY:${COS_SECRET_KEY:}}
|
||||
sdk-app-id: "1401097910"
|
||||
sign-name: 星洋智慧杭州科技
|
||||
template-id: "2457549"
|
||||
enabled: ${SMS_ENABLED:true} # 已启用真实短信发送
|
||||
cos:
|
||||
secret-id: ${COS_SECRET_ID:AKIDlW1GEwPcZGhx1d4HFyRggQu88tPgiWwI}
|
||||
secret-key: ${COS_SECRET_KEY:AKJ3XljSv85mEUXLtDJ9j3JK5appZ3HF}
|
||||
secret-id: ${COS_SECRET_ID:}
|
||||
secret-key: ${COS_SECRET_KEY:}
|
||||
region: ap-guangzhou
|
||||
bucket: openclaw-1302947942
|
||||
base-url: https://openclaw-1302947942.cos.ap-guangzhou.myqcloud.com
|
||||
|
||||
@@ -189,11 +189,12 @@ CREATE TABLE user_points (
|
||||
CREATE TABLE points_records (
|
||||
id BIGINT PRIMARY KEY AUTO_INCREMENT,
|
||||
user_id BIGINT NOT NULL,
|
||||
points_type ENUM('earn','consume','freeze','unfreeze','admin_correct') NOT NULL COMMENT '变动类型',
|
||||
points_type ENUM('earn','consume','freeze','unfreeze','admin_correct','expire') NOT NULL COMMENT '变动类型',
|
||||
source ENUM(
|
||||
'register','sign_in','invite','invited','join_community',
|
||||
'recharge','skill_purchase','review','activity',
|
||||
'admin_add','admin_deduct','admin_correct','refund'
|
||||
'admin_add','admin_deduct','admin_correct','refund',
|
||||
'expire','activity_freeze','activity_unfreeze'
|
||||
) NOT NULL COMMENT '来源',
|
||||
amount INT NOT NULL COMMENT '变动量(正:获得 负:消耗)',
|
||||
balance INT NOT NULL COMMENT '变动后余额',
|
||||
|
||||
@@ -0,0 +1,14 @@
|
||||
-- 修复 points_records 表 ENUM 值缺失问题
|
||||
-- points_type 缺少 'expire'
|
||||
-- source 缺少 'expire', 'activity_freeze', 'activity_unfreeze'
|
||||
|
||||
ALTER TABLE points_records
|
||||
MODIFY COLUMN points_type ENUM('earn','consume','freeze','unfreeze','admin_correct','expire') NOT NULL COMMENT '变动类型';
|
||||
|
||||
ALTER TABLE points_records
|
||||
MODIFY COLUMN source ENUM(
|
||||
'register','sign_in','invite','invited','join_community',
|
||||
'recharge','skill_purchase','review','activity',
|
||||
'admin_add','admin_deduct','admin_correct','refund',
|
||||
'expire','activity_freeze','activity_unfreeze'
|
||||
) NOT NULL COMMENT '来源';
|
||||
@@ -0,0 +1,9 @@
|
||||
-- 订单表新增促销相关字段(与 Order 实体对齐)
|
||||
ALTER TABLE orders
|
||||
ADD COLUMN original_amount DECIMAL(10,2) DEFAULT 0.00 COMMENT '原价总额(促销前)' AFTER user_id,
|
||||
ADD COLUMN promotion_deduct_amount DECIMAL(10,2) DEFAULT 0.00 COMMENT '促销优惠金额' AFTER total_amount;
|
||||
|
||||
-- 订单项表新增促销快照字段(与 OrderItem 实体对齐)
|
||||
ALTER TABLE order_items
|
||||
ADD COLUMN original_price DECIMAL(10,2) DEFAULT NULL COMMENT '原价(促销前)' AFTER skill_cover,
|
||||
ADD COLUMN promotion_id BIGINT DEFAULT NULL COMMENT '关联的促销活动ID' AFTER total_price;
|
||||
@@ -0,0 +1,85 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<configuration>
|
||||
<!-- 控制台输出:精简格式 -->
|
||||
<appender name="CONSOLE" class="ch.qos.logback.core.ConsoleAppender">
|
||||
<encoder>
|
||||
<pattern>%d{HH:mm:ss.SSS} %highlight(%-5level) %cyan(%-30.30logger{30}) : %msg%n</pattern>
|
||||
</encoder>
|
||||
</appender>
|
||||
|
||||
<!-- 文件输出:按天滚动,保留30天 -->
|
||||
<appender name="FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
|
||||
<file>logs/openclaw.log</file>
|
||||
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
|
||||
<fileNamePattern>logs/openclaw.%d{yyyy-MM-dd}.log</fileNamePattern>
|
||||
<maxHistory>30</maxHistory>
|
||||
<totalSizeCap>1GB</totalSizeCap>
|
||||
</rollingPolicy>
|
||||
<encoder>
|
||||
<pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} %-5level [%thread] %logger{36} : %msg%n</pattern>
|
||||
</encoder>
|
||||
</appender>
|
||||
|
||||
<!-- 错误日志单独文件 -->
|
||||
<appender name="ERROR_FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
|
||||
<file>logs/error.log</file>
|
||||
<filter class="ch.qos.logback.classic.filter.ThresholdFilter">
|
||||
<level>ERROR</level>
|
||||
</filter>
|
||||
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
|
||||
<fileNamePattern>logs/error.%d{yyyy-MM-dd}.log</fileNamePattern>
|
||||
<maxHistory>60</maxHistory>
|
||||
<totalSizeCap>500MB</totalSizeCap>
|
||||
</rollingPolicy>
|
||||
<encoder>
|
||||
<pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} %-5level [%thread] %logger{50} : %msg%n%ex</pattern>
|
||||
</encoder>
|
||||
</appender>
|
||||
|
||||
<!-- ==================== 开发环境 ==================== -->
|
||||
<springProfile name="default,dev">
|
||||
<!-- 业务代码:INFO -->
|
||||
<logger name="com.openclaw" level="INFO" />
|
||||
<!-- 操作日志切面:WARN(避免刷屏) -->
|
||||
<logger name="com.openclaw.module.log.aspect" level="WARN" />
|
||||
<!-- MQ消费者:INFO(关键流转需要看到) -->
|
||||
<logger name="com.openclaw.common.mq" level="INFO" />
|
||||
|
||||
<!-- 框架噪音:WARN -->
|
||||
<logger name="org.springframework" level="WARN" />
|
||||
<logger name="org.springframework.amqp" level="WARN" />
|
||||
<logger name="org.apache.ibatis" level="WARN" />
|
||||
<logger name="com.baomidou" level="WARN" />
|
||||
<logger name="com.zaxxer.hikari" level="WARN" />
|
||||
<logger name="io.lettuce" level="WARN" />
|
||||
<logger name="io.netty" level="WARN" />
|
||||
<logger name="org.hibernate" level="WARN" />
|
||||
<logger name="org.springdoc" level="WARN" />
|
||||
<logger name="springdoc" level="WARN" />
|
||||
<logger name="org.apache.catalina" level="WARN" />
|
||||
<logger name="org.apache.coyote" level="WARN" />
|
||||
<logger name="org.apache.tomcat" level="WARN" />
|
||||
<logger name="sun.rmi" level="WARN" />
|
||||
|
||||
<root level="INFO">
|
||||
<appender-ref ref="CONSOLE" />
|
||||
</root>
|
||||
</springProfile>
|
||||
|
||||
<!-- ==================== 生产环境 ==================== -->
|
||||
<springProfile name="prod">
|
||||
<logger name="com.openclaw" level="INFO" />
|
||||
<logger name="com.openclaw.module.log.aspect" level="WARN" />
|
||||
<logger name="org.springframework" level="WARN" />
|
||||
<logger name="org.apache.ibatis" level="WARN" />
|
||||
<logger name="com.baomidou" level="WARN" />
|
||||
<logger name="com.zaxxer.hikari" level="WARN" />
|
||||
<logger name="io.lettuce" level="WARN" />
|
||||
<logger name="io.netty" level="WARN" />
|
||||
|
||||
<root level="WARN">
|
||||
<appender-ref ref="FILE" />
|
||||
<appender-ref ref="ERROR_FILE" />
|
||||
</root>
|
||||
</springProfile>
|
||||
</configuration>
|
||||
Reference in New Issue
Block a user