Compare commits

...

4 Commits

Author SHA1 Message Date
qingfeng1121
c5f631d043 refactor: 重构项目结构,将Result类及相关工具类移动到dto和util包
将Result类从common包移动到dto包,ResultUtils类从common包移动到util包
调整所有相关文件的import语句以匹配新的包结构
新增CorsConfig配置类处理跨域请求
优化AuthController的登录接口返回统一响应格式
2025-12-09 10:58:12 +08:00
qingfeng1121
20f8a9d132 feat(security): 实现JWT认证与授权功能
重构用户登录服务,引入Spring Security和JWT认证机制
- 新增JwtUtils工具类处理JWT生成与验证
- 添加JwtAuthenticationFilter拦截请求验证token
- 实现UserDetailsService从数据库加载用户信息
- 创建AuthController处理登录请求返回JWT
- 重构用户角色权限相关接口,支持基于角色的访问控制
- 移除旧的安全配置,启用新的SecurityConfig
- 新增LoginResponse DTO替代旧的LoginUser
- 优化用户密码加密存储,使用BCryptPasswordEncoder
2025-12-04 14:03:29 +08:00
qingfeng1121
d99580f0c9 feat(登录): 实现用户登录功能及相关模块
- 添加LoginController处理登录请求
- 实现UserLoginService登录逻辑,包括角色和权限验证
- 新增LoginRequest和LoginUser DTO
- 在UsersService中添加登录方法
- 添加RoleInitializer初始化系统角色
- 更新项目结构文档
- 临时禁用Spring Security配置
2025-12-02 14:55:30 +08:00
qingfeng1121
51086db30e feat: 添加用户登录服务及JWT认证功能
refactor: 重构实体类并添加Lombok注解

docs: 更新数据库表结构文档

style: 清理无用代码并优化格式

fix: 修复用户详情服务中的联系方式更新方法

build: 更新pom.xml配置并添加Lombok插件

test: 添加用户登录测试用例

chore: 添加开发和生产环境配置文件
2025-11-28 14:14:38 +08:00
109 changed files with 9608 additions and 603 deletions

1
build.log Normal file
View File

@@ -0,0 +1 @@
[DEBUG] Shutting down 'noop' factory

View File

@@ -36,12 +36,16 @@
| userId | BIGINT | 用户ID | 外键关联users表 |
| realName | VARCHAR | 真实姓名 | |
| idCard | VARCHAR | 身份证号 | |
| gender | INTEGER | 性别 | |
| gender | VARCHAR | 性别 | 男、女、保密 |
| birthday | DATE | 生日 | |
| address | VARCHAR | 地址 | |
| province | VARCHAR | 省份 | |
| city | VARCHAR | 城市 | |
| district | VARCHAR | 区县 | |
| createdAt | DATE | 创建时间 | |
| updatedAt | DATE | 更新时间 | |
## 权限相关表
### roles表
@@ -97,10 +101,18 @@
| shopName | VARCHAR | 店铺名称 | |
| userId | BIGINT | 店主用户ID | 外键关联users表 |
| categoryId | BIGINT | 店铺分类ID | 外键关联shop_categories表 |
| logo | VARCHAR | 店铺Logo | |
| shopLogo | VARCHAR | 店铺Logo | |
| coverImage | VARCHAR | 店铺封面图 | |
| description | VARCHAR | 店铺描述 | |
| status | INTEGER | 状态 | 0:待审核, 1:正常, 2:封禁 |
| address | VARCHAR | 店铺地址 | |
| contactPhone | VARCHAR | 联系电话 | |
| contactPerson | VARCHAR | 联系人 | |
| rating | DECIMAL | 店铺评分 | |
| salesVolume | INTEGER | 销量 | |
| status | INTEGER | 状态 | 0: 未审核, 1: 已审核, 2: 已关闭, 3: 审核失败 |
| businessLicense | VARCHAR | 营业执照 | |
| businessStartTime | DATE | 营业时间开始 | |
| businessEndTime | DATE | 营业时间结束 | |
| createdAt | DATE | 创建时间 | |
| updatedAt | DATE | 更新时间 | |
@@ -110,8 +122,9 @@
| :--- | :--- | :--- | :--- |
| id | BIGINT | 分类ID | 主键,自增 |
| categoryName | VARCHAR | 分类名称 | |
| parentId | BIGINT | 父分类ID | |
| parentId | BIGINT | 父分类ID | 顶级分类为0 |
| level | INTEGER | 分类级别 | |
| icon | VARCHAR | 分类图标 | |
| sort | INTEGER | 排序 | |
| status | INTEGER | 状态 | 0:禁用, 1:启用 |
| createdAt | DATE | 创建时间 | |
@@ -127,14 +140,13 @@
| productName | VARCHAR | 商品名称 | |
| shopId | BIGINT | 店铺ID | 外键关联shops表 |
| categoryId | BIGINT | 商品分类ID | 外键关联product_categories表 |
| brand | VARCHAR | 品牌 | |
| description | VARCHAR | 商品描述 | |
| mainImage | VARCHAR | 主图URL | |
| price | DECIMAL | 价格 | |
| originalPrice | DECIMAL | 原价 | |
| stock | INTEGER | 库存 | |
| sales | INTEGER | 销量 | |
| currentPrice | DECIMAL | 当前价格 | |
| salesVolume | INTEGER | 销量 | |
| status | INTEGER | 状态 | 0:下架, 1:上架 |
| isDeleted | INTEGER | 是否删除 | 0: 未删除, 1: 已删除 |
| createdAt | DATE | 创建时间 | |
| updatedAt | DATE | 更新时间 | |
@@ -144,8 +156,10 @@
| :--- | :--- | :--- | :--- |
| id | BIGINT | 分类ID | 主键,自增 |
| categoryName | VARCHAR | 分类名称 | |
| parentId | BIGINT | 父分类ID | |
| level | INTEGER | 分类级别 | |
| parentId | BIGINT | 父分类ID | 顶级分类为0 |
| level | INTEGER | 分类级别 | 1、2、3 |
| icon | VARCHAR | 分类图标 | |
| banner | VARCHAR | 分类横幅 | |
| sort | INTEGER | 排序 | |
| status | INTEGER | 状态 | 0:禁用, 1:启用 |
| createdAt | DATE | 创建时间 | |
@@ -158,9 +172,8 @@
| id | BIGINT | 属性ID | 主键,自增 |
| attributeName | VARCHAR | 属性名称 | |
| categoryId | BIGINT | 分类ID | 外键关联product_categories表 |
| attributeType | INTEGER | 属性类型 | 0:普通属性, 1:规格属性 |
| attributeType | INTEGER | 属性类型 | 0: 规格属性, 1: 销售属性 |
| sort | INTEGER | 排序 | |
| status | INTEGER | 状态 | 0:禁用, 1:启用 |
| createdAt | DATE | 创建时间 | |
| updatedAt | DATE | 更新时间 | |

81
doc/项目结构.md Normal file
View File

@@ -0,0 +1,81 @@
e:\TaoTaoWang\backend\
├── pom.xml # Maven依赖配置
├── src/main/java/com/taotaowang/
│ ├── TaotaoWangApplication.java # 应用主启动类
│ ├── config/ # 配置类
│ │ ├── SecurityConfig.java # 安全配置
│ │ ├── MyBatisPlusConfig.java # MyBatis-Plus配置
│ │ ├── RedisConfig.java # Redis配置
│ │ ├── SwaggerConfig.java # Swagger文档配置
│ │ └── WebConfig.java # Web配置
│ ├── controller/ # 控制器层
│ │ ├── AuthController.java # 认证相关接口
│ │ ├── UserController.java # 用户管理接口
│ │ ├── RoleController.java # 角色管理接口
│ │ ├── PermissionController.java # 权限管理接口
│ │ ├── ProductController.java # 商品管理接口
│ │ ├── OrderController.java # 订单管理接口
│ │ ├── ShopController.java # 店铺管理接口
│ │ └── MarketingController.java # 营销活动接口
│ ├── service/ # 业务层
│ │ ├── impl/ # 业务实现类
│ │ │ ├── AuthServiceImpl.java
│ │ │ ├── UserServiceImpl.java
│ │ │ ├── RoleServiceImpl.java
│ │ │ ├── PermissionServiceImpl.java
│ │ │ ├── ProductServiceImpl.java
│ │ │ ├── OrderServiceImpl.java
│ │ │ ├── ShopServiceImpl.java
│ │ │ └── MarketingServiceImpl.java
│ │ ├── AuthService.java # 认证服务接口
│ │ ├── UserService.java # 用户服务接口
│ │ ├── RoleService.java # 角色服务接口
│ │ ├── PermissionService.java # 权限服务接口
│ │ ├── ProductService.java # 商品服务接口
│ │ ├── OrderService.java # 订单服务接口
│ │ ├── ShopService.java # 店铺服务接口
│ │ └── MarketingService.java # 营销服务接口
│ ├── mapper/ # 数据访问层
│ │ ├── UserMapper.java
│ │ ├── RoleMapper.java
│ │ ├── PermissionMapper.java
│ │ ├── ProductMapper.java
│ │ ├── OrderMapper.java
│ │ └── ShopMapper.java
│ ├── entity/ # 实体层
│ │ ├── User.java
│ │ ├── Role.java
│ │ ├── Permission.java
│ │ ├── Product.java
│ │ ├── Order.java
│ │ ├── Shop.java
│ │ └── Marketing.java
│ ├── dto/ # 数据传输对象
│ │ ├── request/ # 请求DTO
│ │ │ ├── LoginRequest.java
│ │ │ ├── RegisterRequest.java
│ │ │ ├── ProductRequest.java
│ │ │ └── OrderRequest.java
│ │ └── response/ # 响应DTO
│ │ ├── LoginResponse.java
│ │ ├── UserResponse.java
│ │ ├── ProductResponse.java
│ │ └── OrderResponse.java
│ ├── exception/ # 异常处理
│ │ ├── GlobalExceptionHandler.java # 全局异常处理器
│ │ ├── BusinessException.java # 业务异常
│ │ └── ErrorCode.java # 错误码定义
│ ├── util/ # 工具类
│ │ ├── JwtUtil.java # JWT工具
│ │ ├── SecurityUtil.java # 安全工具
│ │ └── ResponseUtil.java # 响应工具
│ └── interceptor/ # 拦截器
│ ├── JwtInterceptor.java # JWT拦截器
│ └── LogInterceptor.java # 日志拦截器
└── src/main/resources/
├── application.yml # 主配置文件
├── application-dev.yml # 开发环境配置
├── application-test.yml # 测试环境配置
├── application-prod.yml # 生产环境配置
├── mapper/ # MyBatis映射文件
└── static/ # 静态资源目录

18
pom.xml
View File

@@ -125,7 +125,6 @@
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<!-- Fastjson JSON处理 -->
@@ -181,6 +180,23 @@
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.14.1</version>
<configuration>
<source>${java.version}</source>
<target>${java.version}</target>
<encoding>UTF-8</encoding>
<annotationProcessorPaths>
<path>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.42</version>
</path>
</annotationProcessorPaths>
</configuration>
</plugin>
</plugins>
</build>

View File

@@ -0,0 +1,50 @@
package com.qf.backend.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.filter.CorsFilter;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
@Configuration
public class CorsConfig {
/**
* 跨域配置
*/
@Bean
public CorsFilter corsFilter(){
// 创建跨域配置对象
CorsConfiguration configuration = new CorsConfiguration();
// 允许的来源使用通配符,允许所有来源
configuration.addAllowedOriginPattern("*");
// 允许携带cookie
configuration.setAllowCredentials(true);
// 明确列出允许的HTTP方法比使用通配符更安全
configuration.addAllowedMethod("GET");
configuration.addAllowedMethod("POST");
configuration.addAllowedMethod("PUT");
configuration.addAllowedMethod("DELETE");
configuration.addAllowedMethod("OPTIONS");
configuration.addAllowedMethod("PATCH");
// 允许所有请求头(新增)
configuration.addAllowedHeader("*");
// 明确暴露的响应头对于JWT认证很重要
configuration.addExposedHeader("Authorization");
configuration.addExposedHeader("Content-Type");
configuration.addExposedHeader("X-Requested-With");
configuration.addExposedHeader("Accept");
configuration.addExposedHeader("Access-Control-Allow-Origin");
// 设置最大缓存时间为1小时减少预检请求次数
configuration.setMaxAge(3600L);
// 创建基于URL的CORS配置源
UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
// 为所有路径应用CORS配置
source.registerCorsConfiguration("/**", configuration);
// 返回配置好的CORS过滤器
return new CorsFilter(source);
}
}

View File

@@ -0,0 +1,80 @@
package com.qf.backend.config;
import java.io.IOException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;
import com.qf.backend.util.JwtUtils;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
/**
* JWT认证过滤器用于解析和验证JWT
* 拦截所有请求检查Authorization头中的Bearer token
*/
@Component
public class JwtAuthenticationFilter extends OncePerRequestFilter {
private static final Logger logger = LoggerFactory.getLogger(JwtAuthenticationFilter.class);
@Autowired
private JwtUtils jwtUtils;
@Autowired
private UserDetailsService userDetailsService;
/**
* 过滤请求检查JWT并设置认证信息
*/
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
throws ServletException, IOException {
try {
// 1. 从请求头中获取Authorization
String authorizationHeader = request.getHeader("Authorization");
String token = null;
String username = null;
// 2. 检查Authorization头格式
if (authorizationHeader != null && authorizationHeader.startsWith(jwtUtils.getTokenPrefix() + " ")) {
token = authorizationHeader.substring(jwtUtils.getTokenPrefix().length() + 1);
username = jwtUtils.getUsernameFromToken(token);
}
// 3. 如果token有效且用户未认证设置认证信息
if (username != null && SecurityContextHolder.getContext().getAuthentication() == null) {
UserDetails userDetails = this.userDetailsService.loadUserByUsername(username);
// 4. 验证token
if (jwtUtils.validateToken(token, userDetails)) {
// 5. 创建认证对象
UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(
userDetails, null, userDetails.getAuthorities());
// 6. 设置认证细节
authenticationToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
// 7. 设置认证信息到SecurityContext
SecurityContextHolder.getContext().setAuthentication(authenticationToken);
}
}
} catch (Exception e) {
logger.error("JWT认证失败: {}", e.getMessage());
}
// 8. 继续过滤链
filterChain.doFilter(request, response);
}
}

View File

@@ -0,0 +1,114 @@
/*
* Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license
* Click nbfs://nbhost/SystemFileSystem/Templates/Classes/Class.java to edit this template
*/
package com.qf.backend.config;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.configuration.AuthenticationConfiguration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
/**
* 安全配置类使用JWT认证
* 该类是Spring Security的核心配置类负责配置安全策略、认证机制和授权规则
* 与AuthController.java的关系
* 1. AuthController处理登录请求调用AuthenticationManager进行认证
* 2. SecurityConfig配置AuthenticationManager和相关组件
* 3. SecurityConfig配置JWT过滤器用于拦截后续请求并验证JWT
* 4. 两者协同工作,完成完整的认证授权流程
*/
@Configuration
@EnableWebSecurity // 启用Spring Security
public class SecurityConfig {
/**
* 注入JWT认证过滤器
* 该过滤器会拦截所有请求检查Authorization头中的Bearer token
*/
@Autowired
private JwtAuthenticationFilter jwtAuthenticationFilter;
/**
* 配置SecurityFilterChain
* SecurityFilterChain是Spring Security 3.x的新特性替代了旧版的WebSecurityConfigurerAdapter
* 该方法配置了安全策略,包括:
* 1. 禁用CSRF保护适合API服务因为API通常使用JWT而不是Session
* 2. 配置会话管理为无状态适合RESTful API不使用Session
* 3. 配置请求授权规则
* 4. 禁用默认的登录和注销功能使用自定义的AuthController
* 5. 添加JWT过滤器
*
* @param http HttpSecurity对象用于配置安全策略
* @return SecurityFilterChain对象
* @throws Exception 配置过程中可能抛出的异常
*/
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
http
// 1. 禁用CSRF保护
// CSRF跨站请求伪造保护主要用于Web应用防止第三方网站伪造请求
// API服务通常使用JWT认证不需要CSRF保护
.csrf(csrf -> csrf.disable())
// 2. 配置会话管理:无状态
// 无状态意味着服务器不存储用户会话信息,每个请求都需要携带完整的认证信息
// 这是RESTful API的最佳实践提高了系统的可扩展性和安全性
.sessionManagement(session -> session.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
// 3. 配置请求授权规则
// 使用Lambda DSL配置请求匹配规则和授权要求
.authorizeHttpRequests(auth -> auth
// 登录接口公开访问,不需要认证
.requestMatchers("/api/auth/login").permitAll()
// 其他所有请求都需要认证
.anyRequest().authenticated()
)
// 4. 禁用默认的登录和注销功能
// 因为我们使用自定义的AuthController处理登录请求
.formLogin(form -> form.disable())
.logout(logout -> logout.disable());
// 5. 添加JWT过滤器
// 在UsernamePasswordAuthenticationFilter之前添加JWT过滤器
// 这样所有请求都会先经过JWT过滤器验证token的有效性
http.addFilterBefore(jwtAuthenticationFilter, UsernamePasswordAuthenticationFilter.class);
return http.build();
}
/**
* 配置PasswordEncoder
* PasswordEncoder用于加密和验证密码
* BCryptPasswordEncoder是Spring Security推荐的密码编码器使用随机盐值
*
* @return PasswordEncoder对象
*/
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
/**
* 配置AuthenticationManager
* AuthenticationManager是Spring Security的核心组件负责处理认证请求
* 该方法从AuthenticationConfiguration中获取AuthenticationManager实例
*
* @param authenticationConfiguration AuthenticationConfiguration对象
* @return AuthenticationManager对象
* @throws Exception 配置过程中可能抛出的异常
*/
@Bean
public AuthenticationManager authenticationManager(AuthenticationConfiguration authenticationConfiguration) throws Exception {
return authenticationConfiguration.getAuthenticationManager();
}
}

View File

@@ -0,0 +1,92 @@
package com.qf.backend.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.qf.backend.dto.LoginRequest;
import com.qf.backend.dto.LoginResponse;
import com.qf.backend.dto.Result;
import com.qf.backend.exception.ErrorCode;
import com.qf.backend.util.JwtUtils;
import com.qf.backend.util.ResultUtils;
/**
* 认证控制器,用于处理用户登录请求
* 该控制器接收前端发送的用户名和密码通过Spring Security进行认证认证成功后生成JWT返回给前端
*/
@RestController
@RequestMapping("/api/auth")
public class AuthController {
/**
* 注入AuthenticationManager用于处理认证请求
* AuthenticationManager是Spring Security的核心组件负责协调认证过程
*/
@Autowired
private AuthenticationManager authenticationManager;
/**
* 注入JWT工具类用于生成和验证JWT
*/
@Autowired
private JwtUtils jwtUtils;
/**
* 用户登录接口
* @param loginRequest 登录请求体,包含用户名和密码
* @return ResponseEntity 包含JWT令牌的响应
*
* 登录流程:
* 1. 前端发送POST请求到/api/auth/login携带用户名和密码
* 2. 该方法被调用创建UsernamePasswordAuthenticationToken对象
* 3. 调用AuthenticationManager.authenticate()方法进行认证
* 4. 认证成功后从Authentication对象中获取UserDetails
* 5. 使用JwtUtils生成JWT令牌
* 6. 返回包含JWT令牌的响应
*/
@PostMapping("/login")
public Result<ResponseEntity<LoginResponse>> login(@RequestBody LoginRequest loginRequest) {
try {
// 1. 创建认证令牌将用户名和密码封装到UsernamePasswordAuthenticationToken中
// 这里的令牌是未认证状态的,因为还没有验证密码是否正确
UsernamePasswordAuthenticationToken authenticationToken =
new UsernamePasswordAuthenticationToken(loginRequest.getUsername(), loginRequest.getPassword());
// 2. 调用AuthenticationManager.authenticate()方法进行认证
// 这个方法会触发以下流程:
// a. 调用UserDetailsService.loadUserByUsername()方法,从数据库加载用户信息
// b. 使用PasswordEncoder验证密码是否匹配
// c. 认证成功后返回一个已认证的Authentication对象
Authentication authentication = authenticationManager.authenticate(authenticationToken);
// 3. 从已认证的Authentication对象中获取UserDetails
// UserDetails包含了用户的基本信息和权限列表
UserDetails userDetails = (UserDetails) authentication.getPrincipal();
// 4. 使用JwtUtils生成JWT令牌
// 令牌中包含了用户名、权限等信息,以及过期时间
String jwt = jwtUtils.generateToken(userDetails);
// 5. 创建LoginResponse对象封装JWT令牌和令牌类型
LoginResponse loginResponse = new LoginResponse();
loginResponse.setToken(jwt);
loginResponse.setTokenType(jwtUtils.getTokenPrefix());
// 5. 返回包含JWT令牌的响应
// 响应格式为:{"token": "xxx", "tokenType": "Bearer"}
return ResultUtils.success(ResponseEntity.ok(loginResponse));
} catch (BadCredentialsException e) {
// 认证失败,通常是用户名不存在或密码错误
// 返回401 Unauthorized响应
return ResultUtils.fail(ErrorCode.PASSWORD_ERROR, "用户名或密码错误");
}
}
}

View File

@@ -0,0 +1,147 @@
package com.qf.backend.controller;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.security.access.prepost.PreAuthorize;
import com.qf.backend.dto.Result;
import com.qf.backend.entity.OrderItems;
import com.qf.backend.service.OrderItemsService;
import java.util.List;
/**
* 订单项控制器
* 处理订单项相关的HTTP请求
* 遵循RESTful API设计规范
*/
@RequestMapping("/api/order-items")
@RestController
public class OrderItemsController {
private static final Logger logger = LoggerFactory.getLogger(OrderItemsController.class);
@Autowired
private OrderItemsService orderItemsService;
/**
* 根据订单ID查询订单项
* @param orderId 订单ID
* @return 订单项列表
*/
@GetMapping("/order/{orderId}")
public Result<List<OrderItems>> getOrderItemsByOrderId(@PathVariable Long orderId) {
logger.info("根据订单ID查询订单项订单ID{}", orderId);
return orderItemsService.getOrderItemsByOrderId(orderId);
}
/**
* 根据商品ID查询订单项
* @param productId 商品ID
* @return 订单项列表
*/
@GetMapping("/product/{productId}")
public Result<List<OrderItems>> getOrderItemsByProductId(@PathVariable Long productId) {
logger.info("根据商品ID查询订单项商品ID{}", productId);
return orderItemsService.getOrderItemsByProductId(productId);
}
/**
* 创建订单项
* @param orderItems 订单项信息
* @return 是否成功
*/
@PostMapping("/create")
@PreAuthorize("hasRole('ROLE_ADMIN') or hasRole('ROLE_USER')")
public Result<Boolean> createOrderItem(@RequestBody OrderItems orderItems) {
logger.info("创建订单项,订单项信息:{}", orderItems);
return orderItemsService.createOrderItem(orderItems);
}
/**
* 更新订单项信息
* @param orderItems 订单项信息
* @return 是否成功
*/
@PutMapping("/update")
@PreAuthorize("hasRole('ROLE_ADMIN')")
public Result<Boolean> updateOrderItem(@RequestBody OrderItems orderItems) {
logger.info("更新订单项信息,订单项信息:{}", orderItems);
return orderItemsService.updateOrderItem(orderItems);
}
/**
* 删除订单项
* @param id 订单项ID
* @return 是否成功
*/
@DeleteMapping("/delete/{id}")
@PreAuthorize("hasRole('ROLE_ADMIN')")
public Result<Boolean> deleteOrderItem(@PathVariable Long id) {
logger.info("删除订单项订单项ID{}", id);
return orderItemsService.deleteOrderItem(id);
}
/**
* 根据订单项ID查询订单项
* @param id 订单项ID
* @return 订单项信息
*/
@GetMapping("/{id}")
public Result<OrderItems> getOrderItemById(@PathVariable Long id) {
logger.info("根据订单项ID查询订单项订单项ID{}", id);
return orderItemsService.getOrderItemById(id);
}
/**
* 批量创建订单项
* @param orderItemsList 订单项列表
* @return 是否成功
*/
@PostMapping("/batch-create")
@PreAuthorize("hasRole('ROLE_ADMIN') or hasRole('ROLE_USER')")
public Result<Boolean> batchCreateOrderItems(@RequestBody List<OrderItems> orderItemsList) {
logger.info("批量创建订单项,订单项数量:{}", orderItemsList.size());
return orderItemsService.batchCreateOrderItems(orderItemsList);
}
/**
* 根据订单ID删除所有订单项
* @param orderId 订单ID
* @return 是否成功
*/
@DeleteMapping("/delete-by-order/{orderId}")
@PreAuthorize("hasRole('ROLE_ADMIN')")
public Result<Boolean> deleteOrderItemsByOrderId(@PathVariable Long orderId) {
logger.info("根据订单ID删除所有订单项订单ID{}", orderId);
return orderItemsService.deleteOrderItemsByOrderId(orderId);
}
/**
* 计算订单总金额
* @param orderId 订单ID
* @return 订单总金额
*/
@GetMapping("/calculate-total/{orderId}")
public Result<Double> calculateOrderTotal(@PathVariable Long orderId) {
logger.info("计算订单总金额订单ID{}", orderId);
return orderItemsService.calculateOrderTotal(orderId);
}
/**
* 根据SKU ID查询订单项
* @param skuId SKU ID
* @return 订单项列表
*/
@GetMapping("/sku/{skuId}")
public Result<List<OrderItems>> getOrderItemsBySkuId(@PathVariable Long skuId) {
logger.info("根据SKU ID查询订单项SKU ID{}", skuId);
return orderItemsService.getOrderItemsBySkuId(skuId);
}
}

View File

@@ -0,0 +1,137 @@
package com.qf.backend.controller;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.security.access.prepost.PreAuthorize;
import com.qf.backend.dto.Result;
import com.qf.backend.entity.OrderStatusHistory;
import com.qf.backend.service.OrderStatusHistoryService;
import java.util.List;
/**
* 订单状态历史控制器
* 处理订单状态历史相关的HTTP请求
* 遵循RESTful API设计规范
*/
@RequestMapping("/api/order-status-history")
@RestController
public class OrderStatusHistoryController {
private static final Logger logger = LoggerFactory.getLogger(OrderStatusHistoryController.class);
@Autowired
private OrderStatusHistoryService orderStatusHistoryService;
/**
* 根据订单ID查询状态历史
* @param orderId 订单ID
* @return 订单状态历史列表
*/
@GetMapping("/order/{orderId}")
public Result<List<OrderStatusHistory>> getHistoryByOrderId(@PathVariable Long orderId) {
logger.info("根据订单ID查询状态历史订单ID{}", orderId);
return orderStatusHistoryService.getHistoryByOrderId(orderId);
}
/**
* 创建订单状态历史记录
* @param orderStatusHistory 订单状态历史信息
* @return 是否成功
*/
@PostMapping("/create")
@PreAuthorize("hasRole('ROLE_ADMIN') or hasRole('ROLE_USER')")
public Result<Boolean> createStatusHistory(@RequestBody OrderStatusHistory orderStatusHistory) {
logger.info("创建订单状态历史记录,订单状态历史信息:{}", orderStatusHistory);
return orderStatusHistoryService.createStatusHistory(orderStatusHistory);
}
/**
* 更新订单状态历史信息
* @param orderStatusHistory 订单状态历史信息
* @return 是否成功
*/
@PutMapping("/update")
@PreAuthorize("hasRole('ROLE_ADMIN')")
public Result<Boolean> updateStatusHistory(@RequestBody OrderStatusHistory orderStatusHistory) {
logger.info("更新订单状态历史信息,订单状态历史信息:{}", orderStatusHistory);
return orderStatusHistoryService.updateStatusHistory(orderStatusHistory);
}
/**
* 删除订单状态历史记录
* @param id 记录ID
* @return 是否成功
*/
@DeleteMapping("/delete/{id}")
@PreAuthorize("hasRole('ROLE_ADMIN')")
public Result<Boolean> deleteStatusHistory(@PathVariable Long id) {
logger.info("删除订单状态历史记录记录ID{}", id);
return orderStatusHistoryService.deleteStatusHistory(id);
}
/**
* 根据记录ID查询订单状态历史
* @param id 记录ID
* @return 订单状态历史信息
*/
@GetMapping("/{id}")
public Result<OrderStatusHistory> getStatusHistoryById(@PathVariable Long id) {
logger.info("根据记录ID查询订单状态历史记录ID{}", id);
return orderStatusHistoryService.getStatusHistoryById(id);
}
/**
* 批量创建订单状态历史记录
* @param historyList 订单状态历史列表
* @return 是否成功
*/
@PostMapping("/batch-create")
@PreAuthorize("hasRole('ROLE_ADMIN')")
public Result<Boolean> batchCreateStatusHistory(@RequestBody List<OrderStatusHistory> historyList) {
logger.info("批量创建订单状态历史记录,记录数量:{}", historyList.size());
return orderStatusHistoryService.batchCreateStatusHistory(historyList);
}
/**
* 根据订单ID和状态查询历史记录
* @param orderId 订单ID
* @param status 订单状态
* @return 订单状态历史列表
*/
@GetMapping("/order/{orderId}/status/{status}")
public Result<List<OrderStatusHistory>> getHistoryByOrderIdAndStatus(@PathVariable Long orderId, @PathVariable Integer status) {
logger.info("根据订单ID和状态查询历史记录订单ID{},状态:{}", orderId, status);
return orderStatusHistoryService.getHistoryByOrderIdAndStatus(orderId, status);
}
/**
* 获取订单最新状态
* @param orderId 订单ID
* @return 最新订单状态历史信息
*/
@GetMapping("/order/{orderId}/latest")
public Result<OrderStatusHistory> getLatestStatusHistory(@PathVariable Long orderId) {
logger.info("获取订单最新状态订单ID{}", orderId);
return orderStatusHistoryService.getLatestStatusHistory(orderId);
}
/**
* 根据订单ID删除所有状态历史
* @param orderId 订单ID
* @return 是否成功
*/
@DeleteMapping("/delete-by-order/{orderId}")
@PreAuthorize("hasRole('ROLE_ADMIN')")
public Result<Boolean> deleteHistoryByOrderId(@PathVariable Long orderId) {
logger.info("根据订单ID删除所有状态历史订单ID{}", orderId);
return orderStatusHistoryService.deleteHistoryByOrderId(orderId);
}
}

View File

@@ -0,0 +1,149 @@
package com.qf.backend.controller;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.security.access.prepost.PreAuthorize;
import com.qf.backend.dto.Result;
import com.qf.backend.entity.Orders;
import com.qf.backend.service.OrdersService;
import java.util.List;
/**
* 订单控制器
* 处理订单相关的HTTP请求
* 遵循RESTful API设计规范
*/
@RequestMapping("/api/orders")
@RestController
public class OrdersController {
private static final Logger logger = LoggerFactory.getLogger(OrdersController.class);
@Autowired
private OrdersService ordersService;
/**
* 根据订单号查询订单
* @param orderNumber 订单号
* @return 订单信息
*/
@GetMapping("/number/{orderNumber}")
public Result<Orders> getOrderByNumber(@PathVariable String orderNumber) {
logger.info("根据订单号查询订单,订单号:{}", orderNumber);
return ordersService.getOrderByNumber(orderNumber);
}
/**
* 根据用户ID查询订单列表
* @param userId 用户ID
* @return 订单列表
*/
@GetMapping("/user/{userId}")
public Result<List<Orders>> getOrdersByUserId(@PathVariable Long userId) {
logger.info("根据用户ID查询订单列表用户ID{}", userId);
return ordersService.getOrdersByUserId(userId);
}
/**
* 创建订单
* @param orders 订单信息
* @return 是否成功
*/
@PostMapping("/create")
@PreAuthorize("hasRole('ROLE_ADMIN') or hasRole('ROLE_USER')")
public Result<Boolean> createOrder(@RequestBody Orders orders) {
logger.info("创建订单,订单信息:{}", orders);
return ordersService.createOrder(orders);
}
/**
* 更新订单信息
* @param orders 订单信息
* @return 是否成功
*/
@PutMapping("/update")
@PreAuthorize("hasRole('ROLE_ADMIN')")
public Result<Boolean> updateOrder(@RequestBody Orders orders) {
logger.info("更新订单信息,订单信息:{}", orders);
return ordersService.updateOrder(orders);
}
/**
* 删除订单
* @param id 订单ID
* @return 是否成功
*/
@DeleteMapping("/delete/{id}")
@PreAuthorize("hasRole('ROLE_ADMIN')")
public Result<Boolean> deleteOrder(@PathVariable Long id) {
logger.info("删除订单订单ID{}", id);
return ordersService.deleteOrder(id);
}
/**
* 根据订单ID查询订单
* @param id 订单ID
* @return 订单信息
*/
@GetMapping("/{id}")
public Result<Orders> getOrderById(@PathVariable Long id) {
logger.info("根据订单ID查询订单订单ID{}", id);
return ordersService.getOrderById(id);
}
/**
* 分页查询订单
* @param page 当前页码
* @param size 每页数量
* @return 订单列表
*/
@GetMapping("/page/{page}/{size}")
public Result<List<Orders>> listOrdersByPage(@PathVariable int page, @PathVariable int size) {
logger.info("分页查询订单,页码:{},每页数量:{}", page, size);
return ordersService.listOrdersByPage(page, size);
}
/**
* 根据店铺ID查询订单
* @param shopId 店铺ID
* @return 订单列表
*/
@GetMapping("/shop/{shopId}")
public Result<List<Orders>> getOrdersByShopId(@PathVariable Long shopId) {
logger.info("根据店铺ID查询订单店铺ID{}", shopId);
return ordersService.getOrdersByShopId(shopId);
}
/**
* 更新订单状态
* @param orderId 订单ID
* @param status 订单状态
* @return 是否成功
*/
@PutMapping("/update-status/{orderId}/{status}")
@PreAuthorize("hasRole('ROLE_ADMIN') or hasRole('ROLE_USER')")
public Result<Boolean> updateOrderStatus(@PathVariable Long orderId, @PathVariable Integer status) {
logger.info("更新订单状态订单ID{},状态:{}", orderId, status);
return ordersService.updateOrderStatus(orderId, status);
}
/**
* 根据订单状态查询订单
* @param status 订单状态
* @return 订单列表
*/
@GetMapping("/status/{status}")
public Result<List<Orders>> getOrdersByStatus(@PathVariable Integer status) {
logger.info("根据订单状态查询订单,状态:{}", status);
return ordersService.getOrdersByStatus(status);
}
}

View File

@@ -0,0 +1,158 @@
package com.qf.backend.controller;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.security.access.prepost.PreAuthorize;
import com.qf.backend.dto.Result;
import com.qf.backend.entity.Payments;
import com.qf.backend.service.PaymentsService;
import java.util.List;
/**
* 支付控制器
* 处理支付相关的HTTP请求
* 遵循RESTful API设计规范
*/
@RequestMapping("/api/payments")
@RestController
public class PaymentsController {
private static final Logger logger = LoggerFactory.getLogger(PaymentsController.class);
@Autowired
private PaymentsService paymentsService;
/**
* 根据订单ID查询支付记录
* @param orderId 订单ID
* @return 支付记录
*/
@GetMapping("/order/{orderId}")
public Result<Payments> getPaymentByOrderId(@PathVariable Long orderId) {
logger.info("根据订单ID查询支付记录订单ID{}", orderId);
Payments payment = paymentsService.getPaymentByOrderId(orderId);
return Result.success(payment);
}
/**
* 根据支付流水号查询支付记录
* @param transactionId 支付流水号
* @return 支付记录
*/
@GetMapping("/transaction/{transactionId}")
public Result<Payments> getPaymentByTransactionId(@PathVariable String transactionId) {
logger.info("根据支付流水号查询支付记录,支付流水号:{}", transactionId);
Payments payment = paymentsService.getPaymentByTransactionId(transactionId);
return Result.success(payment);
}
/**
* 创建支付记录
* @param payments 支付信息
* @return 是否成功
*/
@PostMapping("/create")
@PreAuthorize("hasRole('ROLE_ADMIN') or hasRole('ROLE_USER')")
public Result<Boolean> createPayment(@RequestBody Payments payments) {
logger.info("创建支付记录,支付信息:{}", payments);
boolean result = paymentsService.createPayment(payments);
return Result.success(result);
}
/**
* 更新支付信息
* @param payments 支付信息
* @return 是否成功
*/
@PutMapping("/update")
@PreAuthorize("hasRole('ROLE_ADMIN')")
public Result<Boolean> updatePayment(@RequestBody Payments payments) {
logger.info("更新支付信息,支付信息:{}", payments);
boolean result = paymentsService.updatePayment(payments);
return Result.success(result);
}
/**
* 删除支付记录
* @param id 支付ID
* @return 是否成功
*/
@DeleteMapping("/delete/{id}")
@PreAuthorize("hasRole('ROLE_ADMIN')")
public Result<Boolean> deletePayment(@PathVariable Long id) {
logger.info("删除支付记录支付ID{}", id);
boolean result = paymentsService.deletePayment(id);
return Result.success(result);
}
/**
* 根据支付ID查询支付记录
* @param id 支付ID
* @return 支付记录
*/
@GetMapping("/{id}")
public Result<Payments> getPaymentById(@PathVariable Long id) {
logger.info("根据支付ID查询支付记录支付ID{}", id);
Payments payment = paymentsService.getPaymentById(id);
return Result.success(payment);
}
/**
* 根据用户ID查询支付记录
* @param userId 用户ID
* @return 支付记录列表
*/
@GetMapping("/user/{userId}")
public Result<List<Payments>> getPaymentsByUserId(@PathVariable Long userId) {
logger.info("根据用户ID查询支付记录用户ID{}", userId);
List<Payments> payments = paymentsService.getPaymentsByUserId(userId);
return Result.success(payments);
}
/**
* 根据支付状态查询支付记录
* @param status 支付状态
* @return 支付记录列表
*/
@GetMapping("/status/{status}")
public Result<List<Payments>> getPaymentsByStatus(@PathVariable Integer status) {
logger.info("根据支付状态查询支付记录,状态:{}", status);
List<Payments> payments = paymentsService.getPaymentsByStatus(status);
return Result.success(payments);
}
/**
* 更新支付状态
* @param paymentId 支付ID
* @param status 支付状态
* @return 是否成功
*/
@PutMapping("/update-status/{paymentId}/{status}")
@PreAuthorize("hasRole('ROLE_ADMIN')")
public Result<Boolean> updatePaymentStatus(@PathVariable Long paymentId, @PathVariable Integer status) {
logger.info("更新支付状态支付ID{},状态:{}", paymentId, status);
boolean result = paymentsService.updatePaymentStatus(paymentId, status);
return Result.success(result);
}
/**
* 分页查询支付记录
* @param page 当前页码
* @param size 每页数量
* @return 支付记录列表
*/
@GetMapping("/page/{page}/{size}")
public Result<List<Payments>> listPaymentsByPage(@PathVariable int page, @PathVariable int size) {
logger.info("分页查询支付记录,页码:{},每页数量:{}", page, size);
List<Payments> payments = paymentsService.listPaymentsByPage(page, size);
return Result.success(payments);
}
}

View File

@@ -0,0 +1,145 @@
/*
* Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license
* Click nbfs://nbhost/SystemFileSystem/Templates/Classes/Class.java to edit this template
*/
package com.qf.backend.controller;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.security.access.prepost.PreAuthorize;
import com.qf.backend.dto.Result;
import com.qf.backend.entity.Permissions;
import com.qf.backend.service.PermissionsService;
import java.util.List;
/**
* 权限管理控制器
* 处理权限相关的HTTP请求
* 遵循RESTful API设计规范
* @author 30803
*/
@RequestMapping("/api/permissions")
@RestController
public class PermissionsController {
private static final Logger logger = LoggerFactory.getLogger(PermissionsController.class);
@Autowired
private PermissionsService permissionsService;
/**
* 查询所有权限
* @return 权限列表
*/
@GetMapping
@PreAuthorize("hasRole('ROLE_ADMIN')")
public Result<List<Permissions>> listAllPermissions() {
logger.info("管理员查询所有权限");
return permissionsService.listAllPermissions();
}
/**
* 根据权限ID查询权限
* @param id 权限ID
* @return 权限信息
*/
@GetMapping("/{id}")
@PreAuthorize("hasRole('ROLE_ADMIN')")
public Result<Permissions> getPermissionById(@PathVariable Long id) {
logger.info("管理员根据ID查询权限ID{}", id);
return permissionsService.getPermissionById(id);
}
/**
* 根据权限编码查询权限
* @param permissionCode 权限编码
* @return 权限信息
*/
@GetMapping("/code/{permissionCode}")
@PreAuthorize("hasRole('ROLE_ADMIN')")
public Result<Permissions> getPermissionByCode(@PathVariable String permissionCode) {
logger.info("管理员根据权限编码查询权限,权限编码:{}", permissionCode);
return permissionsService.getPermissionByCode(permissionCode);
}
/**
* 创建权限
* @param permissions 权限信息
* @return 是否成功
*/
@PostMapping
@PreAuthorize("hasRole('ROLE_ADMIN')")
public Result<Boolean> createPermission(@RequestBody Permissions permissions) {
logger.info("管理员创建权限:{}", permissions);
return permissionsService.createPermission(permissions);
}
/**
* 更新权限信息
* @param permissions 权限信息
* @return 是否成功
*/
@PutMapping
@PreAuthorize("hasRole('ROLE_ADMIN')")
public Result<Boolean> updatePermission(@RequestBody Permissions permissions) {
logger.info("管理员更新权限:{}", permissions);
return permissionsService.updatePermission(permissions);
}
/**
* 删除权限
* @param id 权限ID
* @return 是否成功
*/
@DeleteMapping("/{id}")
@PreAuthorize("hasRole('ROLE_ADMIN')")
public Result<Boolean> deletePermission(@PathVariable Long id) {
logger.info("管理员删除权限ID{}", id);
return permissionsService.deletePermission(id);
}
/**
* 批量删除权限
* @param ids 权限ID列表
* @return 是否成功
*/
@DeleteMapping("/batch")
@PreAuthorize("hasRole('ROLE_ADMIN')")
public Result<Boolean> batchDeletePermissions(@RequestBody List<Long> ids) {
logger.info("管理员批量删除权限IDs{}", ids);
return permissionsService.batchDeletePermissions(ids);
}
/**
* 根据菜单ID查询权限
* @param menuId 菜单ID
* @return 权限列表
*/
@GetMapping("/menu/{menuId}")
@PreAuthorize("hasRole('ROLE_ADMIN')")
public Result<List<Permissions>> listPermissionsByMenuId(@PathVariable Long menuId) {
logger.info("管理员根据菜单ID查询权限菜单ID{}", menuId);
return permissionsService.listPermissionsByMenuId(menuId);
}
/**
* 根据权限类型查询权限
* @param permissionType 权限类型
* @return 权限列表
*/
@GetMapping("/type/{permissionType}")
@PreAuthorize("hasRole('ROLE_ADMIN')")
public Result<List<Permissions>> listPermissionsByType(@PathVariable String permissionType) {
logger.info("管理员根据权限类型查询权限,权限类型:{}", permissionType);
return permissionsService.listPermissionsByType(permissionType);
}
}

View File

@@ -0,0 +1,137 @@
package com.qf.backend.controller;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.security.access.prepost.PreAuthorize;
import com.qf.backend.dto.Result;
import com.qf.backend.entity.ProductAttributeValues;
import com.qf.backend.service.ProductAttributeValuesService;
import java.util.List;
/**
* 商品属性值控制器
* 处理商品属性值相关的HTTP请求
* 遵循RESTful API设计规范
*/
@RequestMapping("/api/product-attribute-values")
@RestController
public class ProductAttributeValuesController {
private static final Logger logger = LoggerFactory.getLogger(ProductAttributeValuesController.class);
@Autowired
private ProductAttributeValuesService productAttributeValuesService;
/**
* 根据商品ID查询属性值
* @param productId 商品ID
* @return 属性值列表
*/
@GetMapping("/product/{productId}")
public Result<List<ProductAttributeValues>> getAttributeValuesByProductId(@PathVariable Long productId) {
logger.info("根据商品ID查询属性值商品ID{}", productId);
return productAttributeValuesService.getAttributeValuesByProductId(productId);
}
/**
* 根据属性ID查询属性值
* @param attributeId 属性ID
* @return 属性值列表
*/
@GetMapping("/attribute/{attributeId}")
public Result<List<ProductAttributeValues>> getAttributeValuesByAttributeId(@PathVariable Long attributeId) {
logger.info("根据属性ID查询属性值属性ID{}", attributeId);
return productAttributeValuesService.getAttributeValuesByAttributeId(attributeId);
}
/**
* 创建属性值
* @param productAttributeValues 属性值信息
* @return 是否成功
*/
@PostMapping("/create")
@PreAuthorize("hasRole('ROLE_ADMIN')")
public Result<Boolean> createAttributeValue(@RequestBody ProductAttributeValues productAttributeValues) {
logger.info("创建属性值,属性值信息:{}", productAttributeValues);
return productAttributeValuesService.createAttributeValue(productAttributeValues);
}
/**
* 更新属性值信息
* @param productAttributeValues 属性值信息
* @return 是否成功
*/
@PutMapping("/update")
@PreAuthorize("hasRole('ROLE_ADMIN')")
public Result<Boolean> updateAttributeValue(@RequestBody ProductAttributeValues productAttributeValues) {
logger.info("更新属性值信息,属性值信息:{}", productAttributeValues);
return productAttributeValuesService.updateAttributeValue(productAttributeValues);
}
/**
* 删除属性值
* @param id 属性值ID
* @return 是否成功
*/
@DeleteMapping("/delete/{id}")
@PreAuthorize("hasRole('ROLE_ADMIN')")
public Result<Boolean> deleteAttributeValue(@PathVariable Long id) {
logger.info("删除属性值属性值ID{}", id);
return productAttributeValuesService.deleteAttributeValue(id);
}
/**
* 根据属性值ID查询属性值
* @param id 属性值ID
* @return 属性值信息
*/
@GetMapping("/{id}")
public Result<ProductAttributeValues> getAttributeValueById(@PathVariable Long id) {
logger.info("根据属性值ID查询属性值属性值ID{}", id);
return productAttributeValuesService.getAttributeValueById(id);
}
/**
* 批量创建商品属性值
* @param attributeValues 属性值列表
* @return 是否成功
*/
@PostMapping("/batch-create")
@PreAuthorize("hasRole('ROLE_ADMIN')")
public Result<Boolean> batchCreateAttributeValues(@RequestBody List<ProductAttributeValues> attributeValues) {
logger.info("批量创建商品属性值,属性值数量:{}", attributeValues.size());
return productAttributeValuesService.batchCreateAttributeValues(attributeValues);
}
/**
* 根据商品ID和属性ID查询属性值
* @param productId 商品ID
* @param attributeId 属性ID
* @return 属性值信息
*/
@GetMapping("/product/{productId}/attribute/{attributeId}")
public Result<ProductAttributeValues> getAttributeValueByProductAndAttribute(@PathVariable Long productId, @PathVariable Long attributeId) {
logger.info("根据商品ID和属性ID查询属性值商品ID{}属性ID{}", productId, attributeId);
return productAttributeValuesService.getAttributeValueByProductAndAttribute(productId, attributeId);
}
/**
* 根据商品ID删除所有属性值
* @param productId 商品ID
* @return 是否成功
*/
@DeleteMapping("/delete-by-product/{productId}")
@PreAuthorize("hasRole('ROLE_ADMIN')")
public Result<Boolean> deleteAttributeValuesByProductId(@PathVariable Long productId) {
logger.info("根据商品ID删除所有属性值商品ID{}", productId);
return productAttributeValuesService.deleteAttributeValuesByProductId(productId);
}
}

View File

@@ -0,0 +1,136 @@
package com.qf.backend.controller;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.security.access.prepost.PreAuthorize;
import com.qf.backend.dto.Result;
import com.qf.backend.entity.ProductAttributes;
import com.qf.backend.service.ProductAttributesService;
import java.util.List;
/**
* 商品属性控制器
* 处理商品属性相关的HTTP请求
* 遵循RESTful API设计规范
*/
@RequestMapping("/api/product-attributes")
@RestController
public class ProductAttributesController {
private static final Logger logger = LoggerFactory.getLogger(ProductAttributesController.class);
@Autowired
private ProductAttributesService productAttributesService;
/**
* 根据分类ID查询属性
* @param categoryId 分类ID
* @return 属性列表
*/
@GetMapping("/category/{categoryId}")
public Result<List<ProductAttributes>> getAttributesByCategoryId(@PathVariable Long categoryId) {
logger.info("根据分类ID查询属性分类ID{}", categoryId);
return productAttributesService.getAttributesByCategoryId(categoryId);
}
/**
* 根据属性名称查询属性
* @param attributeName 属性名称
* @return 属性列表
*/
@GetMapping("/name/{attributeName}")
public Result<List<ProductAttributes>> getAttributesByName(@PathVariable String attributeName) {
logger.info("根据属性名称查询属性,属性名称:{}", attributeName);
return productAttributesService.getAttributesByName(attributeName);
}
/**
* 创建属性
* @param productAttributes 属性信息
* @return 是否成功
*/
@PostMapping("/create")
@PreAuthorize("hasRole('ROLE_ADMIN')")
public Result<Boolean> createAttribute(@RequestBody ProductAttributes productAttributes) {
logger.info("创建属性,属性信息:{}", productAttributes);
return productAttributesService.createAttribute(productAttributes);
}
/**
* 更新属性信息
* @param productAttributes 属性信息
* @return 是否成功
*/
@PutMapping("/update")
@PreAuthorize("hasRole('ROLE_ADMIN')")
public Result<Boolean> updateAttribute(@RequestBody ProductAttributes productAttributes) {
logger.info("更新属性信息,属性信息:{}", productAttributes);
return productAttributesService.updateAttribute(productAttributes);
}
/**
* 删除属性
* @param id 属性ID
* @return 是否成功
*/
@DeleteMapping("/delete/{id}")
@PreAuthorize("hasRole('ROLE_ADMIN')")
public Result<Boolean> deleteAttribute(@PathVariable Long id) {
logger.info("删除属性属性ID{}", id);
return productAttributesService.deleteAttribute(id);
}
/**
* 根据属性ID查询属性
* @param id 属性ID
* @return 属性信息
*/
@GetMapping("/{id}")
public Result<ProductAttributes> getAttributeById(@PathVariable Long id) {
logger.info("根据属性ID查询属性属性ID{}", id);
return productAttributesService.getAttributeById(id);
}
/**
* 批量删除属性
* @param ids 属性ID列表
* @return 是否成功
*/
@DeleteMapping("/batch-delete")
@PreAuthorize("hasRole('ROLE_ADMIN')")
public Result<Boolean> batchDeleteAttributes(@RequestBody List<Long> ids) {
logger.info("批量删除属性属性ID数量{}", ids.size());
return productAttributesService.batchDeleteAttributes(ids);
}
/**
* 根据属性类型查询属性
* @param attributeType 属性类型
* @return 属性列表
*/
@GetMapping("/type/{attributeType}")
public Result<List<ProductAttributes>> getAttributesByType(@PathVariable String attributeType) {
logger.info("根据属性类型查询属性,属性类型:{}", attributeType);
return productAttributesService.getAttributesByType(attributeType);
}
/**
* 查询是否可搜索的属性
* @param searchable 是否可搜索
* @return 属性列表
*/
@GetMapping("/searchable")
public Result<List<ProductAttributes>> getAttributesBySearchable(@RequestParam Boolean searchable) {
logger.info("查询是否可搜索的属性,可搜索:{}", searchable);
return productAttributesService.getAttributesBySearchable(searchable);
}
}

View File

@@ -0,0 +1,133 @@
package com.qf.backend.controller;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.security.access.prepost.PreAuthorize;
import com.qf.backend.dto.Result;
import com.qf.backend.entity.ProductCategories;
import com.qf.backend.service.ProductCategoriesService;
import java.util.List;
/**
* 商品分类控制器
* 处理商品分类相关的HTTP请求
* 遵循RESTful API设计规范
*/
@RequestMapping("/api/product-categories")
@RestController
public class ProductCategoriesController {
private static final Logger logger = LoggerFactory.getLogger(ProductCategoriesController.class);
@Autowired
private ProductCategoriesService productCategoriesService;
/**
* 根据分类名称查询分类
* @param categoryName 分类名称
* @return 分类信息
*/
@GetMapping("/name/{categoryName}")
public Result<ProductCategories> getCategoryByName(@PathVariable String categoryName) {
logger.info("根据分类名称查询分类,分类名称:{}", categoryName);
return productCategoriesService.getCategoryByName(categoryName);
}
/**
* 根据父分类ID查询子分类
* @param parentId 父分类ID
* @return 子分类列表
*/
@GetMapping("/parent/{parentId}")
public Result<List<ProductCategories>> getSubCategoriesByParentId(@PathVariable Long parentId) {
logger.info("根据父分类ID查询子分类父分类ID{}", parentId);
return productCategoriesService.getSubCategoriesByParentId(parentId);
}
/**
* 创建分类
* @param productCategories 分类信息
* @return 是否成功
*/
@PostMapping("/create")
@PreAuthorize("hasRole('ROLE_ADMIN')")
public Result<Boolean> createCategory(@RequestBody ProductCategories productCategories) {
logger.info("创建分类,分类信息:{}", productCategories);
return productCategoriesService.createCategory(productCategories);
}
/**
* 更新分类信息
* @param productCategories 分类信息
* @return 是否成功
*/
@PutMapping("/update")
@PreAuthorize("hasRole('ROLE_ADMIN')")
public Result<Boolean> updateCategory(@RequestBody ProductCategories productCategories) {
logger.info("更新分类信息,分类信息:{}", productCategories);
return productCategoriesService.updateCategory(productCategories);
}
/**
* 删除分类
* @param id 分类ID
* @return 是否成功
*/
@DeleteMapping("/delete/{id}")
@PreAuthorize("hasRole('ROLE_ADMIN')")
public Result<Boolean> deleteCategory(@PathVariable Long id) {
logger.info("删除分类分类ID{}", id);
return productCategoriesService.deleteCategory(id);
}
/**
* 查询所有根分类父分类ID为0或null的分类
* @return 根分类列表
*/
@GetMapping("/root")
public Result<List<ProductCategories>> listRootCategories() {
logger.info("查询所有根分类");
return productCategoriesService.listRootCategories();
}
/**
* 根据分类ID查询分类
* @param id 分类ID
* @return 分类信息
*/
@GetMapping("/{id}")
public Result<ProductCategories> getCategoryById(@PathVariable Long id) {
logger.info("根据分类ID查询分类分类ID{}", id);
return productCategoriesService.getCategoryById(id);
}
/**
* 批量删除分类
* @param ids 分类ID列表
* @return 是否成功
*/
@DeleteMapping("/batch-delete")
@PreAuthorize("hasRole('ROLE_ADMIN')")
public Result<Boolean> batchDeleteCategories(@RequestBody List<Long> ids) {
logger.info("批量删除分类分类ID数量{}", ids.size());
return productCategoriesService.batchDeleteCategories(ids);
}
/**
* 查询所有分类(树形结构)
* @return 分类树形列表
*/
@GetMapping("/tree")
public Result<List<ProductCategories>> listAllCategoriesWithTree() {
logger.info("查询所有分类(树形结构)");
return productCategoriesService.listAllCategoriesWithTree();
}
}

View File

@@ -0,0 +1,138 @@
package com.qf.backend.controller;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.security.access.prepost.PreAuthorize;
import com.qf.backend.dto.Result;
import com.qf.backend.entity.ProductImages;
import com.qf.backend.service.ProductImagesService;
import java.util.List;
/**
* 商品图片控制器
* 处理商品图片相关的HTTP请求
* 遵循RESTful API设计规范
*/
@RequestMapping("/api/product-images")
@RestController
public class ProductImagesController {
private static final Logger logger = LoggerFactory.getLogger(ProductImagesController.class);
@Autowired
private ProductImagesService productImagesService;
/**
* 根据商品ID查询图片
* @param productId 商品ID
* @return 图片列表
*/
@GetMapping("/product/{productId}")
public Result<List<ProductImages>> getImagesByProductId(@PathVariable Long productId) {
logger.info("根据商品ID查询图片商品ID{}", productId);
return productImagesService.getImagesByProductId(productId);
}
/**
* 根据商品ID查询主图
* @param productId 商品ID
* @return 主图信息
*/
@GetMapping("/product/{productId}/main")
public Result<ProductImages> getMainImageByProductId(@PathVariable Long productId) {
logger.info("根据商品ID查询主图商品ID{}", productId);
return productImagesService.getMainImageByProductId(productId);
}
/**
* 创建商品图片
* @param productImages 图片信息
* @return 是否成功
*/
@PostMapping("/create")
@PreAuthorize("hasRole('ROLE_ADMIN')")
public Result<Boolean> createImage(@RequestBody ProductImages productImages) {
logger.info("创建商品图片,图片信息:{}", productImages);
return productImagesService.createImage(productImages);
}
/**
* 更新图片信息
* @param productImages 图片信息
* @return 是否成功
*/
@PutMapping("/update")
@PreAuthorize("hasRole('ROLE_ADMIN')")
public Result<Boolean> updateImage(@RequestBody ProductImages productImages) {
logger.info("更新图片信息,图片信息:{}", productImages);
return productImagesService.updateImage(productImages);
}
/**
* 删除图片
* @param id 图片ID
* @return 是否成功
*/
@DeleteMapping("/delete/{id}")
@PreAuthorize("hasRole('ROLE_ADMIN')")
public Result<Boolean> deleteImage(@PathVariable Long id) {
logger.info("删除图片图片ID{}", id);
return productImagesService.deleteImage(id);
}
/**
* 根据图片ID查询图片
* @param id 图片ID
* @return 图片信息
*/
@GetMapping("/{id}")
public Result<ProductImages> getImageById(@PathVariable Long id) {
logger.info("根据图片ID查询图片图片ID{}", id);
return productImagesService.getImageById(id);
}
/**
* 批量创建商品图片
* @param images 图片列表
* @return 是否成功
*/
@PostMapping("/batch-create")
@PreAuthorize("hasRole('ROLE_ADMIN')")
public Result<Boolean> batchCreateImages(@RequestBody List<ProductImages> images) {
logger.info("批量创建商品图片,图片数量:{}", images.size());
return productImagesService.batchCreateImages(images);
}
/**
* 根据商品ID删除所有图片
* @param productId 商品ID
* @return 是否成功
*/
@DeleteMapping("/delete-by-product/{productId}")
@PreAuthorize("hasRole('ROLE_ADMIN')")
public Result<Boolean> deleteImagesByProductId(@PathVariable Long productId) {
logger.info("根据商品ID删除所有图片商品ID{}", productId);
return productImagesService.deleteImagesByProductId(productId);
}
/**
* 设置主图
* @param productId 商品ID
* @param imageId 图片ID
* @return 是否成功
*/
@PutMapping("/set-main/{productId}/{imageId}")
@PreAuthorize("hasRole('ROLE_ADMIN')")
public Result<Boolean> setMainImage(@PathVariable Long productId, @PathVariable Long imageId) {
logger.info("设置主图商品ID{}图片ID{}", productId, imageId);
return productImagesService.setMainImage(productId, imageId);
}
}

View File

@@ -0,0 +1,151 @@
package com.qf.backend.controller;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.security.access.prepost.PreAuthorize;
import com.qf.backend.dto.Result;
import com.qf.backend.entity.ProductInventories;
import com.qf.backend.service.ProductInventoriesService;
import java.util.List;
/**
* 商品库存控制器
* 处理商品库存相关的HTTP请求
* 遵循RESTful API设计规范
*/
@RequestMapping("/api/product-inventories")
@RestController
public class ProductInventoriesController {
private static final Logger logger = LoggerFactory.getLogger(ProductInventoriesController.class);
@Autowired
private ProductInventoriesService productInventoriesService;
/**
* 根据商品ID查询库存
* @param productId 商品ID
* @return 库存列表
*/
@GetMapping("/product/{productId}")
public Result<List<ProductInventories>> getInventoriesByProductId(@PathVariable Long productId) {
logger.info("根据商品ID查询库存商品ID{}", productId);
return productInventoriesService.getInventoriesByProductId(productId);
}
/**
* 根据SKU ID查询库存
* @param skuId SKU ID
* @return 库存信息
*/
@GetMapping("/sku/{skuId}")
public Result<ProductInventories> getInventoryBySkuId(@PathVariable Long skuId) {
logger.info("根据SKU ID查询库存SKU ID{}", skuId);
return productInventoriesService.getInventoryBySkuId(skuId);
}
/**
* 创建库存记录
* @param productInventories 库存信息
* @return 是否成功
*/
@PostMapping("/create")
@PreAuthorize("hasRole('ROLE_ADMIN')")
public Result<Boolean> createInventory(@RequestBody ProductInventories productInventories) {
logger.info("创建库存记录,库存信息:{}", productInventories);
return productInventoriesService.createInventory(productInventories);
}
/**
* 更新库存信息
* @param productInventories 库存信息
* @return 是否成功
*/
@PutMapping("/update")
@PreAuthorize("hasRole('ROLE_ADMIN')")
public Result<Boolean> updateInventory(@RequestBody ProductInventories productInventories) {
logger.info("更新库存信息,库存信息:{}", productInventories);
return productInventoriesService.updateInventory(productInventories);
}
/**
* 删除库存记录
* @param id 库存ID
* @return 是否成功
*/
@DeleteMapping("/delete/{id}")
@PreAuthorize("hasRole('ROLE_ADMIN')")
public Result<Boolean> deleteInventory(@PathVariable Long id) {
logger.info("删除库存记录库存ID{}", id);
return productInventoriesService.deleteInventory(id);
}
/**
* 根据库存ID查询库存
* @param id 库存ID
* @return 库存信息
*/
@GetMapping("/{id}")
public Result<ProductInventories> getInventoryById(@PathVariable Long id) {
logger.info("根据库存ID查询库存库存ID{}", id);
return productInventoriesService.getInventoryById(id);
}
/**
* 增加库存
* @param skuId SKU ID
* @param quantity 增加数量
* @return 是否成功
*/
@PutMapping("/increase/{skuId}/{quantity}")
@PreAuthorize("hasRole('ROLE_ADMIN')")
public Result<Boolean> increaseInventory(@PathVariable Long skuId, @PathVariable Integer quantity) {
logger.info("增加库存SKU ID{},增加数量:{}", skuId, quantity);
return productInventoriesService.increaseInventory(skuId, quantity);
}
/**
* 减少库存
* @param skuId SKU ID
* @param quantity 减少数量
* @return 是否成功
*/
@PutMapping("/decrease/{skuId}/{quantity}")
@PreAuthorize("hasRole('ROLE_ADMIN') or hasRole('ROLE_USER')")
public Result<Boolean> decreaseInventory(@PathVariable Long skuId, @PathVariable Integer quantity) {
logger.info("减少库存SKU ID{},减少数量:{}", skuId, quantity);
return productInventoriesService.decreaseInventory(skuId, quantity);
}
/**
* 检查库存是否充足
* @param skuId SKU ID
* @param quantity 需要的数量
* @return 是否充足
*/
@GetMapping("/check/{skuId}/{quantity}")
public Result<Boolean> checkInventorySufficient(@PathVariable Long skuId, @PathVariable Integer quantity) {
logger.info("检查库存是否充足SKU ID{},需要数量:{}", skuId, quantity);
return productInventoriesService.checkInventorySufficient(skuId, quantity);
}
/**
* 批量更新库存
* @param inventoryUpdates 库存更新列表
* @return 是否成功
*/
@PutMapping("/batch-update")
@PreAuthorize("hasRole('ROLE_ADMIN')")
public Result<Boolean> batchUpdateInventory(@RequestBody List<ProductInventories> inventoryUpdates) {
logger.info("批量更新库存,更新数量:{}", inventoryUpdates.size());
return productInventoriesService.batchUpdateInventory(inventoryUpdates);
}
}

View File

@@ -0,0 +1,149 @@
package com.qf.backend.controller;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.security.access.prepost.PreAuthorize;
import com.qf.backend.dto.Result;
import com.qf.backend.entity.ProductSkus;
import com.qf.backend.service.ProductSkusService;
import java.util.List;
/**
* 商品SKU控制器
* 处理商品SKU相关的HTTP请求
* 遵循RESTful API设计规范
*/
@RequestMapping("/api/product-skus")
@RestController
public class ProductSkusController {
private static final Logger logger = LoggerFactory.getLogger(ProductSkusController.class);
@Autowired
private ProductSkusService productSkusService;
/**
* 根据商品ID查询SKU
* @param productId 商品ID
* @return SKU列表
*/
@GetMapping("/product/{productId}")
public Result<List<ProductSkus>> getSkusByProductId(@PathVariable Long productId) {
logger.info("根据商品ID查询SKU商品ID{}", productId);
return productSkusService.getSkusByProductId(productId);
}
/**
* 根据SKU编码查询SKU
* @param skuCode SKU编码
* @return SKU信息
*/
@GetMapping("/code/{skuCode}")
public Result<ProductSkus> getSkuByCode(@PathVariable String skuCode) {
logger.info("根据SKU编码查询SKUSKU编码{}", skuCode);
return productSkusService.getSkuByCode(skuCode);
}
/**
* 创建SKU
* @param productSkus SKU信息
* @return 是否成功
*/
@PostMapping("/create")
@PreAuthorize("hasRole('ROLE_ADMIN')")
public Result<Boolean> createSku(@RequestBody ProductSkus productSkus) {
logger.info("创建SKUSKU信息{}", productSkus);
return productSkusService.createSku(productSkus);
}
/**
* 更新SKU信息
* @param productSkus SKU信息
* @return 是否成功
*/
@PutMapping("/update")
@PreAuthorize("hasRole('ROLE_ADMIN')")
public Result<Boolean> updateSku(@RequestBody ProductSkus productSkus) {
logger.info("更新SKU信息SKU信息{}", productSkus);
return productSkusService.updateSku(productSkus);
}
/**
* 删除SKU
* @param id SKU ID
* @return 是否成功
*/
@DeleteMapping("/delete/{id}")
@PreAuthorize("hasRole('ROLE_ADMIN')")
public Result<Boolean> deleteSku(@PathVariable Long id) {
logger.info("删除SKUSKU ID{}", id);
return productSkusService.deleteSku(id);
}
/**
* 根据SKU ID查询SKU
* @param id SKU ID
* @return SKU信息
*/
@GetMapping("/{id}")
public Result<ProductSkus> getSkuById(@PathVariable Long id) {
logger.info("根据SKU ID查询SKUSKU ID{}", id);
return productSkusService.getSkuById(id);
}
/**
* 批量创建SKU
* @param skus SKU列表
* @return 是否成功
*/
@PostMapping("/batch-create")
@PreAuthorize("hasRole('ROLE_ADMIN')")
public Result<Boolean> batchCreateSkus(@RequestBody List<ProductSkus> skus) {
logger.info("批量创建SKUSKU数量{}", skus.size());
return productSkusService.batchCreateSkus(skus);
}
/**
* 根据商品ID删除所有SKU
* @param productId 商品ID
* @return 是否成功
*/
@DeleteMapping("/delete-by-product/{productId}")
@PreAuthorize("hasRole('ROLE_ADMIN')")
public Result<Boolean> deleteSkusByProductId(@PathVariable Long productId) {
logger.info("根据商品ID删除所有SKU商品ID{}", productId);
return productSkusService.deleteSkusByProductId(productId);
}
/**
* 更新SKU库存
* @param skuId SKU ID
* @param quantity 库存数量
* @return 是否成功
*/
@PutMapping("/update-stock/{skuId}/{quantity}")
@PreAuthorize("hasRole('ROLE_ADMIN')")
public Result<Boolean> updateSkuStock(@PathVariable Long skuId, @PathVariable Integer quantity) {
logger.info("更新SKU库存SKU ID{},库存数量:{}", skuId, quantity);
return productSkusService.updateSkuStock(skuId, quantity);
}
/**
* 批量查询SKU
* @param skuIds SKU ID列表
* @return SKU列表
*/
@PostMapping("/batch-get")
public Result<List<ProductSkus>> batchGetSkus(@RequestBody List<Long> skuIds) {
logger.info("批量查询SKUSKU ID数量{}", skuIds.size());
return productSkusService.batchGetSkus(skuIds);
}
}

View File

@@ -0,0 +1,151 @@
package com.qf.backend.controller;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.security.access.prepost.PreAuthorize;
import com.qf.backend.dto.Result;
import com.qf.backend.entity.Products;
import com.qf.backend.service.ProductsService;
import java.util.List;
/**
* 商品控制器
* 处理商品相关的HTTP请求
* 遵循RESTful API设计规范
*/
@RequestMapping("/api/products")
@RestController
public class ProductsController {
private static final Logger logger = LoggerFactory.getLogger(ProductsController.class);
@Autowired
private ProductsService productsService;
/**
* 根据商品名称查询商品
* @param productName 商品名称
* @return 商品列表
*/
@GetMapping("/name/{productName}")
public Result<List<Products>> getProductsByName(@PathVariable String productName) {
logger.info("根据商品名称查询商品,商品名称:{}", productName);
return productsService.getProductsByName(productName);
}
/**
* 根据分类ID查询商品
* @param categoryId 分类ID
* @return 商品列表
*/
@GetMapping("/category/{categoryId}")
public Result<List<Products>> getProductsByCategoryId(@PathVariable Long categoryId) {
logger.info("根据分类ID查询商品分类ID{}", categoryId);
return productsService.getProductsByCategoryId(categoryId);
}
/**
* 创建商品
* @param products 商品信息
* @return 是否成功
*/
@PostMapping("/create")
@PreAuthorize("hasRole('ROLE_ADMIN')")
public Result<Boolean> createProduct(@RequestBody Products products) {
logger.info("创建商品,商品信息:{}", products);
return productsService.createProduct(products);
}
/**
* 更新商品信息
* @param products 商品信息
* @return 是否成功
*/
@PutMapping("/update")
@PreAuthorize("hasRole('ROLE_ADMIN')")
public Result<Boolean> updateProduct(@RequestBody Products products) {
logger.info("更新商品信息,商品信息:{}", products);
return productsService.updateProduct(products);
}
/**
* 删除商品
* @param id 商品ID
* @return 是否成功
*/
@DeleteMapping("/delete/{id}")
@PreAuthorize("hasRole('ROLE_ADMIN')")
public Result<Boolean> deleteProduct(@PathVariable Long id) {
logger.info("删除商品商品ID{}", id);
return productsService.deleteProduct(id);
}
/**
* 根据商品ID查询商品
* @param id 商品ID
* @return 商品信息
*/
@GetMapping("/{id}")
public Result<Products> getProductById(@PathVariable Long id) {
logger.info("根据商品ID查询商品商品ID{}", id);
return productsService.getProductById(id);
}
/**
* 分页查询商品
* @param page 当前页码
* @param size 每页数量
* @return 商品列表
*/
@GetMapping("/page/{page}/{size}")
public Result<List<Products>> listProductsByPage(@PathVariable int page, @PathVariable int size) {
logger.info("分页查询商品,页码:{},每页数量:{}", page, size);
return productsService.listProductsByPage(page, size);
}
/**
* 根据店铺ID查询商品
* @param shopId 店铺ID
* @return 商品列表
*/
@GetMapping("/shop/{shopId}")
public Result<List<Products>> getProductsByShopId(@PathVariable Long shopId) {
logger.info("根据店铺ID查询商品店铺ID{}", shopId);
return productsService.getProductsByShopId(shopId);
}
/**
* 批量上下架商品
* @param ids 商品ID列表
* @param status 状态(上架/下架)
* @return 是否成功
*/
@PutMapping("/batch-status")
@PreAuthorize("hasRole('ROLE_ADMIN')")
public Result<Boolean> batchUpdateProductStatus(@RequestBody List<Long> ids, @RequestParam Integer status) {
logger.info("批量上下架商品商品ID数量{},状态:{}", ids.size(), status);
return productsService.batchUpdateProductStatus(ids, status);
}
/**
* 搜索商品
* @param keyword 关键词
* @param page 当前页码
* @param size 每页数量
* @return 商品列表
*/
@GetMapping("/search")
public Result<List<Products>> searchProducts(@RequestParam String keyword, @RequestParam int page, @RequestParam int size) {
logger.info("搜索商品,关键词:{},页码:{},每页数量:{}", keyword, page, size);
return productsService.searchProducts(keyword, page, size);
}
}

View File

@@ -0,0 +1,158 @@
package com.qf.backend.controller;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.security.access.prepost.PreAuthorize;
import com.qf.backend.dto.Result;
import com.qf.backend.entity.Refunds;
import com.qf.backend.service.RefundsService;
import java.util.List;
/**
* 退款控制器
* 处理退款相关的HTTP请求
* 遵循RESTful API设计规范
*/
@RequestMapping("/api/refunds")
@RestController
public class RefundsController {
private static final Logger logger = LoggerFactory.getLogger(RefundsController.class);
@Autowired
private RefundsService refundsService;
/**
* 根据订单ID查询退款记录
* @param orderId 订单ID
* @return 退款记录列表
*/
@GetMapping("/order/{orderId}")
public Result<List<Refunds>> getRefundsByOrderId(@PathVariable Long orderId) {
logger.info("根据订单ID查询退款记录订单ID{}", orderId);
List<Refunds> refunds = refundsService.getRefundsByOrderId(orderId);
return Result.success(refunds);
}
/**
* 根据退款单号查询退款记录
* @param refundNumber 退款单号
* @return 退款记录
*/
@GetMapping("/number/{refundNumber}")
public Result<Refunds> getRefundByNumber(@PathVariable String refundNumber) {
logger.info("根据退款单号查询退款记录,退款单号:{}", refundNumber);
Refunds refund = refundsService.getRefundByNumber(refundNumber);
return Result.success(refund);
}
/**
* 创建退款记录
* @param refunds 退款信息
* @return 是否成功
*/
@PostMapping("/create")
@PreAuthorize("hasRole('ROLE_ADMIN') or hasRole('ROLE_USER')")
public Result<Boolean> createRefund(@RequestBody Refunds refunds) {
logger.info("创建退款记录,退款信息:{}", refunds);
boolean result = refundsService.createRefund(refunds);
return Result.success(result);
}
/**
* 更新退款信息
* @param refunds 退款信息
* @return 是否成功
*/
@PutMapping("/update")
@PreAuthorize("hasRole('ROLE_ADMIN')")
public Result<Boolean> updateRefund(@RequestBody Refunds refunds) {
logger.info("更新退款信息,退款信息:{}", refunds);
boolean result = refundsService.updateRefund(refunds);
return Result.success(result);
}
/**
* 删除退款记录
* @param id 退款ID
* @return 是否成功
*/
@DeleteMapping("/delete/{id}")
@PreAuthorize("hasRole('ROLE_ADMIN')")
public Result<Boolean> deleteRefund(@PathVariable Long id) {
logger.info("删除退款记录退款ID{}", id);
boolean result = refundsService.deleteRefund(id);
return Result.success(result);
}
/**
* 根据退款ID查询退款记录
* @param id 退款ID
* @return 退款记录
*/
@GetMapping("/{id}")
public Result<Refunds> getRefundById(@PathVariable Long id) {
logger.info("根据退款ID查询退款记录退款ID{}", id);
Refunds refund = refundsService.getRefundById(id);
return Result.success(refund);
}
/**
* 根据用户ID查询退款记录
* @param userId 用户ID
* @return 退款记录列表
*/
@GetMapping("/user/{userId}")
public Result<List<Refunds>> getRefundsByUserId(@PathVariable Long userId) {
logger.info("根据用户ID查询退款记录用户ID{}", userId);
List<Refunds> refunds = refundsService.getRefundsByUserId(userId);
return Result.success(refunds);
}
/**
* 根据退款状态查询退款记录
* @param status 退款状态
* @return 退款记录列表
*/
@GetMapping("/status/{status}")
public Result<List<Refunds>> getRefundsByStatus(@PathVariable Integer status) {
logger.info("根据退款状态查询退款记录,状态:{}", status);
List<Refunds> refunds = refundsService.getRefundsByStatus(status);
return Result.success(refunds);
}
/**
* 更新退款状态
* @param refundId 退款ID
* @param status 退款状态
* @return 是否成功
*/
@PutMapping("/update-status/{refundId}/{status}")
@PreAuthorize("hasRole('ROLE_ADMIN')")
public Result<Boolean> updateRefundStatus(@PathVariable Long refundId, @PathVariable Integer status) {
logger.info("更新退款状态退款ID{},状态:{}", refundId, status);
boolean result = refundsService.updateRefundStatus(refundId, status);
return Result.success(result);
}
/**
* 分页查询退款记录
* @param page 当前页码
* @param size 每页数量
* @return 退款记录列表
*/
@GetMapping("/page/{page}/{size}")
public Result<List<Refunds>> listRefundsByPage(@PathVariable int page, @PathVariable int size) {
logger.info("分页查询退款记录,页码:{},每页数量:{}", page, size);
List<Refunds> refunds = refundsService.listRefundsByPage(page, size);
return Result.success(refunds);
}
}

View File

@@ -0,0 +1,180 @@
package com.qf.backend.controller;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.security.access.prepost.PreAuthorize;
import com.qf.backend.dto.Result;
import com.qf.backend.entity.RolePermissions;
import com.qf.backend.service.RolePermissionsService;
import java.util.List;
/**
* 角色权限关联控制器
* 处理角色与权限关联相关的HTTP请求
* 遵循RESTful API设计规范
*/
@RequestMapping("/api/role-permissions")
@RestController
public class RolePermissionsController {
private static final Logger logger = LoggerFactory.getLogger(RolePermissionsController.class);
@Autowired
private RolePermissionsService rolePermissionsService;
/**
* 根据角色ID查询角色权限关联
* @param roleId 角色ID
* @return 角色权限关联列表
*/
@GetMapping("/role/{roleId}")
@PreAuthorize("hasRole('ROLE_ADMIN')")
public Result<List<RolePermissions>> getRolePermissionsByRoleId(@PathVariable Long roleId) {
logger.info("管理员根据角色ID查询角色权限关联角色ID{}", roleId);
List<RolePermissions> rolePermissions = rolePermissionsService.getRolePermissionsByRoleId(roleId);
return Result.success(rolePermissions);
}
/**
* 根据权限ID查询角色权限关联
* @param permissionId 权限ID
* @return 角色权限关联列表
*/
@GetMapping("/permission/{permissionId}")
@PreAuthorize("hasRole('ROLE_ADMIN')")
public Result<List<RolePermissions>> getRolePermissionsByPermissionId(@PathVariable Long permissionId) {
logger.info("管理员根据权限ID查询角色权限关联权限ID{}", permissionId);
List<RolePermissions> rolePermissions = rolePermissionsService.getRolePermissionsByPermissionId(permissionId);
return Result.success(rolePermissions);
}
/**
* 为角色添加权限
* @param request 角色权限关联请求体
* @return 是否成功
*/
@PostMapping("/add")
@PreAuthorize("hasRole('ROLE_ADMIN')")
public Result<Boolean> addPermissionToRole(@RequestBody RolePermissionRequest request) {
logger.info("管理员为角色添加权限角色ID{}权限ID{}", request.getRoleId(), request.getPermissionId());
boolean result = rolePermissionsService.addPermissionToRole(request.getRoleId(), request.getPermissionId());
return Result.success(result);
}
/**
* 从角色移除权限
* @param request 角色权限关联请求体
* @return 是否成功
*/
@DeleteMapping("/remove")
@PreAuthorize("hasRole('ROLE_ADMIN')")
public Result<Boolean> removePermissionFromRole(@RequestBody RolePermissionRequest request) {
logger.info("管理员从角色移除权限角色ID{}权限ID{}", request.getRoleId(), request.getPermissionId());
boolean result = rolePermissionsService.removePermissionFromRole(request.getRoleId(), request.getPermissionId());
return Result.success(result);
}
/**
* 批量为角色添加权限
* @param request 批量角色权限关联请求体
* @return 是否成功
*/
@PostMapping("/batch-add")
@PreAuthorize("hasRole('ROLE_ADMIN')")
public Result<Boolean> batchAddPermissionsToRole(@RequestBody BatchRolePermissionRequest request) {
logger.info("管理员批量为角色添加权限角色ID{}权限ID列表{}", request.getRoleId(), request.getPermissionIds());
boolean result = rolePermissionsService.batchAddPermissionsToRole(request.getRoleId(), request.getPermissionIds());
return Result.success(result);
}
/**
* 清空角色的所有权限
* @param roleId 角色ID
* @return 是否成功
*/
@DeleteMapping("/clear/{roleId}")
@PreAuthorize("hasRole('ROLE_ADMIN')")
public Result<Boolean> clearRolePermissions(@PathVariable Long roleId) {
logger.info("管理员清空角色的所有权限角色ID{}", roleId);
boolean result = rolePermissionsService.clearRolePermissions(roleId);
return Result.success(result);
}
/**
* 检查角色是否拥有指定权限
* @param roleId 角色ID
* @param permissionId 权限ID
* @return 是否拥有
*/
@GetMapping("/check")
@PreAuthorize("hasRole('ROLE_ADMIN')")
public Result<Boolean> checkRoleHasPermission(Long roleId, Long permissionId) {
logger.info("管理员检查角色是否拥有指定权限角色ID{}权限ID{}", roleId, permissionId);
boolean result = rolePermissionsService.checkRoleHasPermission(roleId, permissionId);
return Result.success(result);
}
/**
* 根据角色ID查询其拥有的权限ID列表
* @param roleId 角色ID
* @return 权限ID列表
*/
@GetMapping("/permission-ids/{roleId}")
@PreAuthorize("hasRole('ROLE_ADMIN')")
public Result<List<Long>> listPermissionIdsByRoleId(@PathVariable Long roleId) {
logger.info("管理员根据角色ID查询其拥有的权限ID列表角色ID{}", roleId);
List<Long> permissionIds = rolePermissionsService.listPermissionIdsByRoleId(roleId);
return Result.success(permissionIds);
}
/**
* 角色权限关联请求体
*/
public static class RolePermissionRequest {
private Long roleId;
private Long permissionId;
// getter和setter
public Long getRoleId() {
return roleId;
}
public void setRoleId(Long roleId) {
this.roleId = roleId;
}
public Long getPermissionId() {
return permissionId;
}
public void setPermissionId(Long permissionId) {
this.permissionId = permissionId;
}
}
/**
* 批量角色权限关联请求体
*/
public static class BatchRolePermissionRequest {
private Long roleId;
private List<Long> permissionIds;
// getter和setter
public Long getRoleId() {
return roleId;
}
public void setRoleId(Long roleId) {
this.roleId = roleId;
}
public List<Long> getPermissionIds() {
return permissionIds;
}
public void setPermissionIds(List<Long> permissionIds) {
this.permissionIds = permissionIds;
}
}
}

View File

@@ -0,0 +1,133 @@
/*
* Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license
* Click nbfs://nbhost/SystemFileSystem/Templates/Classes/Class.java to edit this template
*/
package com.qf.backend.controller;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.security.access.prepost.PreAuthorize;
import com.qf.backend.dto.Result;
import com.qf.backend.entity.Roles;
import com.qf.backend.service.RolesService;
import java.util.List;
/**
* 角色管理控制器
* 处理角色相关的HTTP请求
* 遵循RESTful API设计规范
* @author 30803
*/
@RequestMapping("/api/roles")
@RestController
public class RolesController {
private static final Logger logger = LoggerFactory.getLogger(RolesController.class);
@Autowired
private RolesService rolesService;
/**
* 查询所有角色
* @return 角色列表
*/
@GetMapping
@PreAuthorize("hasRole('ROLE_ADMIN')")
public Result<List<Roles>> listAllRoles() {
logger.info("管理员查询所有角色");
return rolesService.listAllRoles();
}
/**
* 根据角色ID查询角色
* @param id 角色ID
* @return 角色信息
*/
@GetMapping("/{id}")
@PreAuthorize("hasRole('ROLE_ADMIN')")
public Result<Roles> getRoleById(@PathVariable Long id) {
logger.info("管理员根据ID查询角色ID{}", id);
return rolesService.getRoleById(id);
}
/**
* 根据角色名称查询角色
* @param roleName 角色名称
* @return 角色信息
*/
@GetMapping("/name/{roleName}")
@PreAuthorize("hasRole('ROLE_ADMIN')")
public Result<Roles> getRoleByName(@PathVariable String roleName) {
logger.info("管理员根据名称查询角色,名称:{}", roleName);
return rolesService.getRoleByName(roleName);
}
/**
* 根据用户ID查询其拥有的角色列表
* @param userId 用户ID
* @return 角色列表
*/
@GetMapping("/user/{userId}")
@PreAuthorize("hasRole('ROLE_ADMIN')")
public Result<List<Roles>> listRolesByUserId(@PathVariable Long userId) {
logger.info("管理员根据用户ID查询角色列表用户ID{}", userId);
return rolesService.listRolesByUserId(userId);
}
/**
* 创建角色
* @param roles 角色信息
* @return 是否成功
*/
@PostMapping
@PreAuthorize("hasRole('ROLE_ADMIN')")
public Result<Boolean> createRole(@RequestBody Roles roles) {
logger.info("管理员创建角色:{}", roles);
return rolesService.createRole(roles);
}
/**
* 更新角色信息
* @param roles 角色信息
* @return 是否成功
*/
@PutMapping
@PreAuthorize("hasRole('ROLE_ADMIN')")
public Result<Boolean> updateRole(@RequestBody Roles roles) {
logger.info("管理员更新角色:{}", roles);
return rolesService.updateRole(roles);
}
/**
* 删除角色
* @param id 角色ID
* @return 是否成功
*/
@DeleteMapping("/{id}")
@PreAuthorize("hasRole('ROLE_ADMIN')")
public Result<Boolean> deleteRole(@PathVariable Long id) {
logger.info("管理员删除角色ID{}", id);
return rolesService.deleteRole(id);
}
/**
* 批量删除角色
* @param ids 角色ID列表
* @return 是否成功
*/
@DeleteMapping("/batch")
@PreAuthorize("hasRole('ROLE_ADMIN')")
public Result<Boolean> batchDeleteRoles(@RequestBody List<Long> ids) {
logger.info("管理员批量删除角色IDs{}", ids);
return rolesService.batchDeleteRoles(ids);
}
}

View File

@@ -0,0 +1,133 @@
package com.qf.backend.controller;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.security.access.prepost.PreAuthorize;
import com.qf.backend.dto.Result;
import com.qf.backend.entity.ShopCategories;
import com.qf.backend.service.ShopCategoriesService;
import java.util.List;
/**
* 店铺分类控制器
* 处理店铺分类相关的HTTP请求
* 遵循RESTful API设计规范
*/
@RequestMapping("/api/shop-categories")
@RestController
public class ShopCategoriesController {
private static final Logger logger = LoggerFactory.getLogger(ShopCategoriesController.class);
@Autowired
private ShopCategoriesService shopCategoriesService;
/**
* 根据分类名称查询分类
* @param categoryName 分类名称
* @return 分类信息
*/
@GetMapping("/name/{categoryName}")
public Result<ShopCategories> getCategoryByName(@PathVariable String categoryName) {
logger.info("根据分类名称查询分类,分类名称:{}", categoryName);
return shopCategoriesService.getCategoryByName(categoryName);
}
/**
* 根据父分类ID查询子分类
* @param parentId 父分类ID
* @return 子分类列表
*/
@GetMapping("/parent/{parentId}")
public Result<List<ShopCategories>> getSubCategoriesByParentId(@PathVariable Long parentId) {
logger.info("根据父分类ID查询子分类父分类ID{}", parentId);
return shopCategoriesService.getSubCategoriesByParentId(parentId);
}
/**
* 创建分类
* @param shopCategories 分类信息
* @return 是否成功
*/
@PostMapping("/create")
@PreAuthorize("hasRole('ROLE_ADMIN')")
public Result<Boolean> createCategory(@RequestBody ShopCategories shopCategories) {
logger.info("创建分类,分类信息:{}", shopCategories);
return shopCategoriesService.createCategory(shopCategories);
}
/**
* 更新分类信息
* @param shopCategories 分类信息
* @return 是否成功
*/
@PutMapping("/update")
@PreAuthorize("hasRole('ROLE_ADMIN')")
public Result<Boolean> updateCategory(@RequestBody ShopCategories shopCategories) {
logger.info("更新分类信息,分类信息:{}", shopCategories);
return shopCategoriesService.updateCategory(shopCategories);
}
/**
* 删除分类
* @param id 分类ID
* @return 是否成功
*/
@DeleteMapping("/delete/{id}")
@PreAuthorize("hasRole('ROLE_ADMIN')")
public Result<Boolean> deleteCategory(@PathVariable Long id) {
logger.info("删除分类分类ID{}", id);
return shopCategoriesService.deleteCategory(id);
}
/**
* 查询所有根分类父分类ID为0或null的分类
* @return 根分类列表
*/
@GetMapping("/root")
public Result<List<ShopCategories>> listRootCategories() {
logger.info("查询所有根分类");
return shopCategoriesService.listRootCategories();
}
/**
* 根据分类ID查询分类
* @param id 分类ID
* @return 分类信息
*/
@GetMapping("/{id}")
public Result<ShopCategories> getCategoryById(@PathVariable Long id) {
logger.info("根据分类ID查询分类分类ID{}", id);
return shopCategoriesService.getCategoryById(id);
}
/**
* 批量删除分类
* @param ids 分类ID列表
* @return 是否成功
*/
@DeleteMapping("/batch-delete")
@PreAuthorize("hasRole('ROLE_ADMIN')")
public Result<Boolean> batchDeleteCategories(@RequestBody List<Long> ids) {
logger.info("批量删除分类分类ID数量{}", ids.size());
return shopCategoriesService.batchDeleteCategories(ids);
}
/**
* 查询所有分类(树形结构)
* @return 分类树形列表
*/
@GetMapping("/tree")
public Result<List<ShopCategories>> listAllCategoriesWithTree() {
logger.info("查询所有分类(树形结构)");
return shopCategoriesService.listAllCategoriesWithTree();
}
}

View File

@@ -0,0 +1,161 @@
package com.qf.backend.controller;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.security.access.prepost.PreAuthorize;
import com.qf.backend.dto.Result;
import com.qf.backend.entity.ShopRatings;
import com.qf.backend.service.ShopRatingsService;
import java.util.List;
/**
* 店铺评分控制器
* 处理店铺评分相关的HTTP请求
* 遵循RESTful API设计规范
*/
@RequestMapping("/api/shop-ratings")
@RestController
public class ShopRatingsController {
private static final Logger logger = LoggerFactory.getLogger(ShopRatingsController.class);
@Autowired
private ShopRatingsService shopRatingsService;
/**
* 根据店铺ID查询评分
* @param shopId 店铺ID
* @return 评分列表
*/
@GetMapping("/shop/{shopId}")
public Result<List<ShopRatings>> getRatingsByShopId(@PathVariable Long shopId) {
logger.info("根据店铺ID查询评分店铺ID{}", shopId);
return shopRatingsService.getRatingsByShopId(shopId);
}
/**
* 根据用户ID查询评分
* @param userId 用户ID
* @return 评分列表
*/
@GetMapping("/user/{userId}")
public Result<List<ShopRatings>> getRatingsByUserId(@PathVariable Long userId) {
logger.info("根据用户ID查询评分用户ID{}", userId);
return shopRatingsService.getRatingsByUserId(userId);
}
/**
* 创建评分
* @param shopRatings 评分信息
* @return 是否成功
*/
@PostMapping("/create")
@PreAuthorize("hasRole('ROLE_ADMIN') or hasRole('ROLE_USER')")
public Result<Boolean> createRating(@RequestBody ShopRatings shopRatings) {
logger.info("创建评分,评分信息:{}", shopRatings);
return shopRatingsService.createRating(shopRatings);
}
/**
* 更新评分信息
* @param shopRatings 评分信息
* @return 是否成功
*/
@PutMapping("/update")
@PreAuthorize("hasRole('ROLE_ADMIN') or hasRole('ROLE_USER')")
public Result<Boolean> updateRating(@RequestBody ShopRatings shopRatings) {
logger.info("更新评分信息,评分信息:{}", shopRatings);
return shopRatingsService.updateRating(shopRatings);
}
/**
* 删除评分
* @param id 评分ID
* @return 是否成功
*/
@DeleteMapping("/delete/{id}")
@PreAuthorize("hasRole('ROLE_ADMIN')")
public Result<Boolean> deleteRating(@PathVariable Long id) {
logger.info("删除评分评分ID{}", id);
return shopRatingsService.deleteRating(id);
}
/**
* 根据评分ID查询评分
* @param id 评分ID
* @return 评分信息
*/
@GetMapping("/{id}")
public Result<ShopRatings> getRatingById(@PathVariable Long id) {
logger.info("根据评分ID查询评分评分ID{}", id);
return shopRatingsService.getRatingById(id);
}
/**
* 获取店铺平均评分
* @param shopId 店铺ID
* @return 平均评分
*/
@GetMapping("/shop/{shopId}/average")
public Result<Double> getAverageRatingByShopId(@PathVariable Long shopId) {
logger.info("获取店铺平均评分店铺ID{}", shopId);
return shopRatingsService.getAverageRatingByShopId(shopId);
}
/**
* 获取店铺评分数量
* @param shopId 店铺ID
* @return 评分数量
*/
@GetMapping("/shop/{shopId}/count")
public Result<Integer> getRatingCountByShopId(@PathVariable Long shopId) {
logger.info("获取店铺评分数量店铺ID{}", shopId);
return shopRatingsService.getRatingCountByShopId(shopId);
}
/**
* 根据评分星级查询店铺评分
* @param shopId 店铺ID
* @param rating 评分星级
* @return 评分列表
*/
@GetMapping("/shop/{shopId}/rating/{rating}")
public Result<List<ShopRatings>> getRatingsByShopIdAndRating(@PathVariable Long shopId, @PathVariable Integer rating) {
logger.info("根据评分星级查询店铺评分店铺ID{},评分星级:{}", shopId, rating);
return shopRatingsService.getRatingsByShopIdAndRating(shopId, rating);
}
/**
* 检查用户是否已对店铺评分
* @param shopId 店铺ID
* @param userId 用户ID
* @return 是否已评分
*/
@GetMapping("/check")
public Result<Boolean> checkUserHasRated(@RequestParam Long shopId, @RequestParam Long userId) {
logger.info("检查用户是否已对店铺评分店铺ID{}用户ID{}", shopId, userId);
return shopRatingsService.checkUserHasRated(shopId, userId);
}
/**
* 分页查询店铺评分
* @param shopId 店铺ID
* @param page 当前页码
* @param size 每页数量
* @return 评分列表
*/
@GetMapping("/shop/{shopId}/page/{page}/{size}")
public Result<List<ShopRatings>> listRatingsByShopIdAndPage(@PathVariable Long shopId, @PathVariable int page, @PathVariable int size) {
logger.info("分页查询店铺评分店铺ID{},页码:{},每页数量:{}", shopId, page, size);
return shopRatingsService.listRatingsByShopIdAndPage(shopId, page, size);
}
}

View File

@@ -0,0 +1,151 @@
package com.qf.backend.controller;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.security.access.prepost.PreAuthorize;
import com.qf.backend.dto.Result;
import com.qf.backend.entity.Shops;
import com.qf.backend.service.ShopsService;
import java.util.List;
/**
* 店铺控制器
* 处理店铺相关的HTTP请求
* 遵循RESTful API设计规范
*/
@RequestMapping("/api/shops")
@RestController
public class ShopsController {
private static final Logger logger = LoggerFactory.getLogger(ShopsController.class);
@Autowired
private ShopsService shopsService;
/**
* 根据店铺名称查询店铺
* @param shopName 店铺名称
* @return 店铺列表
*/
@GetMapping("/name/{shopName}")
public Result<List<Shops>> getShopsByName(@PathVariable String shopName) {
logger.info("根据店铺名称查询店铺,店铺名称:{}", shopName);
return shopsService.getShopsByName(shopName);
}
/**
* 根据用户ID查询店铺
* @param userId 用户ID
* @return 店铺信息
*/
@GetMapping("/user/{userId}")
public Result<Shops> getShopByUserId(@PathVariable Long userId) {
logger.info("根据用户ID查询店铺用户ID{}", userId);
return shopsService.getShopByUserId(userId);
}
/**
* 创建店铺
* @param shops 店铺信息
* @return 是否成功
*/
@PostMapping("/create")
@PreAuthorize("hasRole('ROLE_ADMIN') or hasRole('ROLE_USER')")
public Result<Boolean> createShop(@RequestBody Shops shops) {
logger.info("创建店铺,店铺信息:{}", shops);
return shopsService.createShop(shops);
}
/**
* 更新店铺信息
* @param shops 店铺信息
* @return 是否成功
*/
@PutMapping("/update")
@PreAuthorize("hasRole('ROLE_ADMIN') or hasRole('ROLE_USER')")
public Result<Boolean> updateShop(@RequestBody Shops shops) {
logger.info("更新店铺信息,店铺信息:{}", shops);
return shopsService.updateShop(shops);
}
/**
* 删除店铺
* @param id 店铺ID
* @return 是否成功
*/
@DeleteMapping("/delete/{id}")
@PreAuthorize("hasRole('ROLE_ADMIN')")
public Result<Boolean> deleteShop(@PathVariable Long id) {
logger.info("删除店铺店铺ID{}", id);
return shopsService.deleteShop(id);
}
/**
* 根据店铺ID查询店铺
* @param id 店铺ID
* @return 店铺信息
*/
@GetMapping("/{id}")
public Result<Shops> getShopById(@PathVariable Long id) {
logger.info("根据店铺ID查询店铺店铺ID{}", id);
return shopsService.getShopById(id);
}
/**
* 分页查询店铺
* @param page 当前页码
* @param size 每页数量
* @return 店铺列表
*/
@GetMapping("/page/{page}/{size}")
public Result<List<Shops>> listShopsByPage(@PathVariable int page, @PathVariable int size) {
logger.info("分页查询店铺,页码:{},每页数量:{}", page, size);
return shopsService.listShopsByPage(page, size);
}
/**
* 根据店铺分类ID查询店铺
* @param categoryId 分类ID
* @return 店铺列表
*/
@GetMapping("/category/{categoryId}")
public Result<List<Shops>> getShopsByCategoryId(@PathVariable Long categoryId) {
logger.info("根据店铺分类ID查询店铺分类ID{}", categoryId);
return shopsService.getShopsByCategoryId(categoryId);
}
/**
* 更新店铺状态
* @param shopId 店铺ID
* @param status 店铺状态
* @return 是否成功
*/
@PutMapping("/update-status/{shopId}/{status}")
@PreAuthorize("hasRole('ROLE_ADMIN')")
public Result<Boolean> updateShopStatus(@PathVariable Long shopId, @PathVariable Integer status) {
logger.info("更新店铺状态店铺ID{},状态:{}", shopId, status);
return shopsService.updateShopStatus(shopId, status);
}
/**
* 搜索店铺
* @param keyword 关键词
* @param page 当前页码
* @param size 每页数量
* @return 店铺列表
*/
@GetMapping("/search")
public Result<List<Shops>> searchShops(@RequestParam String keyword, @RequestParam int page, @RequestParam int size) {
logger.info("搜索店铺,关键词:{},页码:{},每页数量:{}", keyword, page, size);
return shopsService.searchShops(keyword, page, size);
}
}

View File

@@ -0,0 +1,169 @@
/*
* Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license
* Click nbfs://nbhost/SystemFileSystem/Templates/Classes/Class.java to edit this template
*/
package com.qf.backend.controller;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.security.access.prepost.PreAuthorize;
import com.qf.backend.dto.Result;
import com.qf.backend.entity.UserRoles;
import com.qf.backend.service.UserRolesService;
import java.util.List;
/**
* 用户角色关联控制器
* 处理用户与角色关联相关的HTTP请求
* 遵循RESTful API设计规范
* @author 30803
*/
@RequestMapping("/api/user-roles")
@RestController
public class UserRolesController {
private static final Logger logger = LoggerFactory.getLogger(UserRolesController.class);
@Autowired
private UserRolesService userRolesService;
/**
* 根据用户ID查询角色关联
* @param userId 用户ID
* @return 用户角色关联列表
*/
@GetMapping("/user/{userId}")
@PreAuthorize("hasRole('ROLE_ADMIN')")
public Result<List<UserRoles>> getUserRolesByUserId(@PathVariable Long userId) {
logger.info("管理员根据用户ID查询角色关联用户ID{}", userId);
return userRolesService.getUserRolesByUserId(userId);
}
/**
* 根据角色ID查询用户关联
* @param roleId 角色ID
* @return 用户角色关联列表
*/
@GetMapping("/role/{roleId}")
@PreAuthorize("hasRole('ROLE_ADMIN')")
public Result<List<UserRoles>> getUserRolesByRoleId(@PathVariable Long roleId) {
logger.info("管理员根据角色ID查询用户关联角色ID{}", roleId);
return userRolesService.getUserRolesByRoleId(roleId);
}
/**
* 为用户添加角色
* @param userId 用户ID
* @param roleId 角色ID
* @return 是否成功
*/
@PostMapping("/add")
@PreAuthorize("hasRole('ROLE_ADMIN')")
public Result<Boolean> addRoleToUser(@RequestBody UserRolesRequest request) {
logger.info("管理员为用户添加角色用户ID{}角色ID{}", request.getUserId(), request.getRoleId());
return userRolesService.addRoleToUser(request.getUserId(), request.getRoleId());
}
/**
* 从用户移除角色
* @param userId 用户ID
* @param roleId 角色ID
* @return 是否成功
*/
@DeleteMapping("/remove")
@PreAuthorize("hasRole('ROLE_ADMIN')")
public Result<Boolean> removeRoleFromUser(@RequestBody UserRolesRequest request) {
logger.info("管理员从用户移除角色用户ID{}角色ID{}", request.getUserId(), request.getRoleId());
return userRolesService.removeRoleFromUser(request.getUserId(), request.getRoleId());
}
/**
* 批量为用户添加角色
* @param userId 用户ID
* @param roleIds 角色ID列表
* @return 是否成功
*/
@PostMapping("/batch-add")
@PreAuthorize("hasRole('ROLE_ADMIN')")
public Result<Boolean> batchAddRolesToUser(@RequestBody BatchUserRolesRequest request) {
logger.info("管理员批量为用户添加角色用户ID{}角色ID列表{}", request.getUserId(), request.getRoleIds());
return userRolesService.batchAddRolesToUser(request.getUserId(), request.getRoleIds());
}
/**
* 清空用户的所有角色
* @param userId 用户ID
* @return 是否成功
*/
@DeleteMapping("/clear/{userId}")
@PreAuthorize("hasRole('ROLE_ADMIN')")
public Result<Boolean> clearUserRoles(@PathVariable Long userId) {
logger.info("管理员清空用户的所有角色用户ID{}", userId);
return userRolesService.clearUserRoles(userId);
}
/**
* 检查用户是否拥有指定角色
* @param userId 用户ID
* @param roleId 角色ID
* @return 是否拥有
*/
@GetMapping("/check")
@PreAuthorize("hasRole('ROLE_ADMIN')")
public Result<Boolean> checkUserHasRole(Long userId, Long roleId) {
logger.info("管理员检查用户是否拥有指定角色用户ID{}角色ID{}", userId, roleId);
return userRolesService.checkUserHasRole(userId, roleId);
}
/**
* 用户角色关联请求体
*/
public static class UserRolesRequest {
private Long userId;
private Long roleId;
// getter和setter
public Long getUserId() {
return userId;
}
public void setUserId(Long userId) {
this.userId = userId;
}
public Long getRoleId() {
return roleId;
}
public void setRoleId(Long roleId) {
this.roleId = roleId;
}
}
/**
* 批量用户角色关联请求体
*/
public static class BatchUserRolesRequest {
private Long userId;
private List<Long> roleIds;
// getter和setter
public Long getUserId() {
return userId;
}
public void setUserId(Long userId) {
this.userId = userId;
}
public List<Long> getRoleIds() {
return roleIds;
}
public void setRoleIds(List<Long> roleIds) {
this.roleIds = roleIds;
}
}
}

View File

@@ -0,0 +1,94 @@
/*
* Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license
* Click nbfs://nbhost/SystemFileSystem/Templates/Classes/Class.java to edit this template
*/
package com.qf.backend.controller;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.security.access.prepost.PreAuthorize;
import com.qf.backend.dto.Result;
import com.qf.backend.entity.Users;
import com.qf.backend.service.UsersService;
import java.util.List;
/**
* 用户管理控制器
* 处理用户相关的HTTP请求
* 遵循RESTful API设计规范
* @author 30803
*/
@RequestMapping("/api/users")
@RestController
public class UsersController {
private static final Logger logger = LoggerFactory.getLogger(UsersController.class);
@Autowired
private UsersService usersService;
/**
* 分页获取用户列表 仅管理员角色
* @param pageNum 页码
* @param pageSize 每页数量
* @return 用户列表
*/
@GetMapping("/page")
@PreAuthorize("hasRole('ROLE_ADMIN')")
public Result<List<Users>> listUsersByPage(int pageNum, int pageSize) {
logger.info("管理员获取用户列表,页码:{},每页数量:{}", pageNum, pageSize);
return usersService.listUsersByPage(pageNum, pageSize);
}
/**
* 根据id查询用户 仅管理员角色
* @param id 用户ID
* @return 用户信息
*/
@GetMapping("/{id}")
@PreAuthorize("hasRole('ROLE_ADMIN')")
public Result<Users> getUserById(@PathVariable Long id) {
logger.info("管理员根据id查询用户id{}", id);
return usersService.getUserById(id);
}
/**
* 根据用户名查询用户 用户可以查询自己的信息
* @param username 用户名
* @return 用户信息
*/
@GetMapping("/username/{username}")
// @PreAuthorize("hasRole('ROLE_ADMIN')")
public Result<Users> getUserByUsername(@PathVariable String username) {
logger.info("管理员根据用户名查询用户,用户名:{}", username);
return usersService.getUserByUsername(username);
}
/**
* 根据邮箱查询用户 仅管理员角色
* @param email 邮箱
* @return 用户信息
*/
@GetMapping("/email/{email}")
@PreAuthorize("hasRole('ROLE_ADMIN')")
public Result<Users> getUserByEmail(@PathVariable String email) {
logger.info("管理员根据邮箱查询用户,邮箱:{}", email);
return usersService.getUserByEmail(email);
}
/**
* 查询所有用户 仅管理员角色
* @return 用户列表
*/
@GetMapping
@PreAuthorize("hasRole('ROLE_ADMIN')")
public Result<List<Users>> listAllUsers() {
logger.info("管理员查询所有用户");
return usersService.listAllUsers();
}
}

View File

@@ -0,0 +1,24 @@
/*
* Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license
* Click nbfs://nbhost/SystemFileSystem/Templates/Classes/Class.java to edit this template
*/
package com.qf.backend.dto;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
/**
* 登录请求参数
* @author 30803
*/
@Data
@AllArgsConstructor
@NoArgsConstructor
public class LoginRequest {
private String username;
private String password;
}

View File

@@ -0,0 +1,32 @@
/*
* Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license
* Click nbfs://nbhost/SystemFileSystem/Templates/Classes/Class.java to edit this template
*/
package com.qf.backend.dto;
import java.util.List;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
/**
* (登录时返回的用户信息DTO)
* @param username 用户名
* @param password 密码
* @param roles 角色列表
* @param permissions 权限列表
* @author 30803
*/
@Data
@Builder
@NoArgsConstructor
@AllArgsConstructor
public class LoginResponse {
private String username; // 用户名
private List<String> roles; // 角色列表 暂时无用
private List<String> permissions; // 权限列表 暂时无用
private String token; // JWT令牌
private String tokenType; // 令牌类型通常为Bearer
}

View File

@@ -1,4 +1,4 @@
package com.qf.backend.common;
package com.qf.backend.dto;
import lombok.Data;

View File

@@ -7,30 +7,34 @@ import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
/**
* 订单商品项表
*/
@Data
@Builder
@Data // 自动生成getter、setter、toString、equals、hashCode方法
@Builder // 自动生成builder模式的构造器
@NoArgsConstructor // 自动生成无参构造器
@AllArgsConstructor // 自动生成全参构造器
@TableName("order_items")
public class OrderItems {
@TableId(type = IdType.AUTO)
private Long id;
private Long id; // 订单项ID主键自增
private Long orderId;
private Long productId;
private Long skuId;
private String productName;
private String skuSpecs;
private String productImage;
private BigDecimal price;
private Integer quantity;
private BigDecimal subtotal;
private Integer itemStatus; // 0: 正常, 1: 已退款, 2: 退款中
private Date createdAt;
private Date updatedAt;
private Long orderId; // 订单ID外键关联orders表
private Long productId; // 商品ID外键关联products表
private Long skuId; // SKU ID外键关联product_skus表
private String productName; // 商品名称
private String skuSpecs; // SKU规格
private String productImage; // 商品图片
private BigDecimal price; // 价格
private Integer quantity; // 数量
private BigDecimal subtotal; // 小计
private Integer itemStatus; // 商品状态:0:正常, 1:已退款, 2:退款中
private Date createdAt; // 创建时间
private Date updatedAt; // 更新时间
}

View File

@@ -6,25 +6,29 @@ import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
/**
* 订单状态历史表
*/
@Data
@Builder
@Data // 自动生成getter、setter、toString、equals、hashCode方法
@Builder // 自动生成builder模式的构造器
@NoArgsConstructor // 自动生成无参构造器
@AllArgsConstructor // 自动生成全参构造器
@TableName("order_status_history")
public class OrderStatusHistory {
@TableId(type = IdType.AUTO)
private Long id;
private Long id; // 历史ID主键自增
private Long orderId;
private Integer previousStatus;
private Integer currentStatus;
private String changeReason;
private String operator;
private Date changeTime;
private Date createdAt;
private Long orderId; // 订单ID外键关联orders表
private Integer previousStatus; // 之前状态
private Integer currentStatus; // 当前状态
private String changeReason; // 变更原因
private String operator; // 操作人
private Date changeTime; // 变更时间
private Date createdAt; // 创建时间
}

View File

@@ -7,36 +7,40 @@ import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
/**
* 订单主表
*/
@Data
@Builder
@Data // 自动生成getter、setter、toString、equals、hashCode方法
@Builder // 自动生成builder模式的构造器
@NoArgsConstructor // 自动生成无参构造器
@AllArgsConstructor // 自动生成全参构造器
@TableName("orders")
public class Orders {
@TableId(type = IdType.AUTO)
private Long id;
private Long id; // 订单ID主键自增
private String orderNo;
private Long userId;
private Long shopId;
private BigDecimal totalAmount;
private BigDecimal actualAmount;
private BigDecimal shippingFee;
private Integer orderStatus; // 0: 待付款, 1: 待发货, 2: 待收货, 3: 已完成, 4: 已取消, 5: 已退款
private String shippingAddress;
private String receiverName;
private String receiverPhone;
private String orderNo; // 订单号
private Long userId; // 用户ID外键关联users表
private Long shopId; // 店铺ID外键关联shops表
private BigDecimal totalAmount; // 总金额
private BigDecimal actualAmount; // 实际支付金额
private BigDecimal shippingFee; // 运费
private Integer orderStatus; // 订单状态:0:待付款, 1:待发货, 2:待收货, 3:已完成, 4:已取消, 5:已退款
private String shippingAddress; // 收货地址
private String receiverName; // 收件人姓名
private String receiverPhone; // 收件人电话
private String paymentMethod; // 支付方式
private Date paymentTime;
private Date shippingTime;
private Date deliveryTime;
private Date completeTime;
private String remark;
private Date createdAt;
private Date updatedAt;
private Date paymentTime; // 支付时间
private Date shippingTime; // 发货时间
private Date deliveryTime; // 送达时间
private Date completeTime; // 完成时间
private String remark; // 备注
private Date createdAt; // 创建时间
private Date updatedAt; // 更新时间
}

View File

@@ -7,30 +7,34 @@ import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
/**
* 支付信息表
*/
@Data
@Builder
@Data // 自动生成getter、setter、toString、equals、hashCode方法
@Builder // 自动生成builder模式的构造器
@NoArgsConstructor // 自动生成无参构造器
@AllArgsConstructor // 自动生成全参构造器
@TableName("payments")
public class Payments {
@TableId(type = IdType.AUTO)
private Long id;
private Long id; // 支付ID主键自增
private String paymentNo;
private Long orderId;
private Long userId;
private BigDecimal amount;
private String paymentNo; // 支付单号
private Long orderId; // 订单ID外键关联orders表
private Long userId; // 用户ID外键关联users表
private BigDecimal amount; // 支付金额
private String paymentMethod; // 支付方式
private String transactionId; // 第三方交易流水号
private Integer paymentStatus; // 0: 待支付, 1: 支付成功, 2: 支付失败, 3: 已退款
private Integer paymentStatus; // 支付状态:0:待支付, 1:支付成功, 2:支付失败, 3:已退款
private String paymentUrl; // 支付链接
private Date expireTime;
private Date paymentTime;
private Date createdAt;
private Date updatedAt;
private Date expireTime; // 过期时间
private Date paymentTime; // 支付时间
private Date createdAt; // 创建时间
private Date updatedAt; // 更新时间
}

View File

@@ -6,25 +6,29 @@ import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
/**
* 权限信息表
*/
@Data
@Builder
@Data // 自动生成getter、setter、toString、equals、hashCode方法
@Builder // 自动生成builder模式的构造器
@NoArgsConstructor // 自动生成无参构造器
@AllArgsConstructor // 自动生成全参构造器
@TableName("permissions")
public class Permissions {
@TableId(type = IdType.AUTO)
private Long id;
private Long id; // 权限ID主键自增
private String permissionName;
private String permissionCode;
private String description;
private String module;
private Integer status; // 0: 禁用, 1: 启用
private Date createdAt;
private Date updatedAt;
private String permissionName; // 权限名称
private String permissionCode; // 权限编码
private String description; // 权限描述
private String module; // 所属模块
private Integer status; // 状态:0:禁用, 1:启用
private Date createdAt; // 创建时间
private Date updatedAt; // 更新时间
}

View File

@@ -6,25 +6,28 @@ import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
/**
* 商品属性值表
*/
@Data
@Builder
@Data // 自动生成getter、setter、toString、equals、hashCode方法
@Builder // 自动生成builder模式的构造器
@NoArgsConstructor // 自动生成无参构造器
@AllArgsConstructor // 自动生成全参构造器
@TableName("product_attribute_values")
public class ProductAttributeValues {
@TableId(type = IdType.AUTO)
private Long id;
private Long id; // 属性值ID主键自增
private Long productId;
private Long attributeId;
private String attributeValue;
private Integer sort;
private Date createdAt;
private Date updatedAt;
private Long productId; // 商品ID外键关联products表
private Long attributeId; // 属性ID外键关联product_attributes表
private String attributeValue; // 属性值
private Integer sort; // 排序
private Date createdAt; // 创建时间
private Date updatedAt; // 更新时间
}

View File

@@ -6,24 +6,28 @@ import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
/**
* 商品属性表
*/
@Data
@Builder
@Data // 自动生成getter、setter、toString、equals、hashCode方法
@Builder // 自动生成builder模式的构造器
@NoArgsConstructor // 自动生成无参构造器
@AllArgsConstructor // 自动生成全参构造器
@TableName("product_attributes")
public class ProductAttributes {
@TableId(type = IdType.AUTO)
private Long id;
private Long id; // 属性ID主键自增
private String attributeName;
private Long categoryId;
private Integer attributeType; // 0: 规格属性, 1: 销售属性
private Integer sort;
private Date createdAt;
private Date updatedAt;
private String attributeName; // 属性名称
private Long categoryId; // 分类ID外键关联product_categories表
private Integer attributeType; // 属性类型:0: 规格属性, 1: 销售属性
private Integer sort; // 排序
private Date createdAt; // 创建时间
private Date updatedAt; // 更新时间
}

View File

@@ -1,32 +1,40 @@
package com.qf.backend.entity;
import java.util.Date;
import java.util.List;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import java.util.Date;
import lombok.NoArgsConstructor;
/**
* 商品分类表
*/
@Data
@Builder
@AllArgsConstructor
@NoArgsConstructor
@TableName("product_categories")
public class ProductCategories {
@TableId(type = IdType.AUTO)
private Long id;
private Long id; // 分类ID主键自增
private String categoryName;
private String categoryName; // 分类名称
private Long parentId; // 父分类ID顶级分类为0
private Integer level; // 分类级别1、2、3
private String icon;
private String banner;
private Integer sort;
private Integer status; // 0: 禁用, 1: 启用
private Date createdAt;
private Date updatedAt;
private String icon; // 分类图标
private String banner; // 分类横幅
private Integer sort; // 排序
private Integer status; // 状态:0:禁用, 1:启用
private Date createdAt; // 创建时间
private Date updatedAt; // 更新时间
@TableField(exist = false) // 非数据库字段,用于构建树形结构
private List<ProductCategories> children; // 子分类列表
}

View File

@@ -4,25 +4,29 @@ import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.util.Date;
/**
* 商品图片表
*/
@Data
@Builder
@Data // 自动生成getter、setter、toString、equals、hashCode方法
@Builder // 自动生成builder模式的构造器
@NoArgsConstructor // 自动生成无参构造器
@AllArgsConstructor // 自动生成全参构造器
@TableName("product_images")
public class ProductImages {
@TableId(type = IdType.AUTO)
private Long id;
private Long id; // 图片ID主键自增
private Long productId;
private String imageUrl;
private Integer sort;
private Integer isMain; // 0: 非主图, 1: 主图
private Date createdAt;
private Long productId; // 商品ID外键关联products表
private String imageUrl; // 图片URL
private Integer sort; // 排序
private Integer isMain; // 是否主图:0:非主图, 1:主图
private Date createdAt; // 创建时间
}

View File

@@ -6,26 +6,29 @@ import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
/**
* 库存信息表
*/
@Data
@Builder
@Data // 自动生成getter、setter、toString、equals、hashCode方法
@Builder // 自动生成builder模式的构造器
@NoArgsConstructor // 自动生成无参构造器
@AllArgsConstructor // 自动生成全参构造器
@TableName("product_inventories")
public class ProductInventories {
@TableId(type = IdType.AUTO)
private Long id;
private Long id; // 库存ID主键自增
private Long skuId;
private Integer currentStock;
private Integer safetyStock;
private Long skuId; // SKU ID外键关联product_skus表
private Integer currentStock; // 当前库存
private Integer safetyStock; // 安全库存
private Integer lockStock; // 锁定库存
private Date lastUpdateTime;
private Date createdAt;
private Date updatedAt;
private Date lastUpdateTime; // 最后更新时间
private Date createdAt; // 创建时间
private Date updatedAt; // 更新时间
}

View File

@@ -7,28 +7,31 @@ import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
/**
* 商品SKU表
*/
@Data
@Builder
@Data // 自动生成getter、setter、toString、equals、hashCode方法
@Builder // 自动生成builder模式的构造器
@NoArgsConstructor // 自动生成无参构造器
@AllArgsConstructor // 自动生成全参构造器
@TableName("product_skus")
public class ProductSkus {
@TableId(type = IdType.AUTO)
private Long id;
private Long id; // SKU ID主键自增
private Long productId;
private String skuCode;
private Long productId; // 商品ID外键关联products表
private String skuCode; // SKU编码
private String skuSpecs; // SKU规格信息JSON格式存储
private BigDecimal price;
private Integer stock;
private String image;
private Integer status; // 0: 禁用, 1: 启用
private Date createdAt;
private Date updatedAt;
private BigDecimal price; // 价格
private Integer stock; // 库存
private String image; // 图片
private Integer status; // 状态:0:禁用, 1:启用
private Date createdAt; // 创建时间
private Date updatedAt; // 更新时间
}

View File

@@ -7,31 +7,34 @@ import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
/**
* 商品基本信息表
*/
@Data
@Builder
@Data // 自动生成getter、setter、toString、equals、hashCode方法
@Builder // 自动生成builder模式的构造器
@NoArgsConstructor // 自动生成无参构造器
@AllArgsConstructor // 自动生成全参构造器
@TableName("products")
public class Products {
@TableId(type = IdType.AUTO)
private Long id;
private Long id; // 商品ID主键自增
private String productName;
private Long shopId;
private Long categoryId;
private String description;
private BigDecimal originalPrice;
private BigDecimal currentPrice;
private Integer salesVolume;
private Integer status; // 0: 下架, 1: 上架
private String mainImage;
private Integer isDeleted; // 0: 未删除, 1: 已删除
private Date createdAt;
private Date updatedAt;
private String productName; // 商品名称
private Long shopId; // 店铺ID外键关联shops表
private Long categoryId; // 商品分类ID外键关联product_categories表
private String description; // 商品描述
private BigDecimal originalPrice; // 原价 不能为空
private BigDecimal currentPrice; // 当前价格 为空时表示原价 ,否则表示折扣价
private Integer salesVolume; // 销量
private Integer status; // 状态:0:下架, 1:上架
private String mainImage; // 主图URL
private Integer isDeleted; // 是否删除:0: 未删除, 1: 已删除
private Date createdAt; // 创建时间
private Date updatedAt; // 更新时间
}

View File

@@ -7,35 +7,38 @@ import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
/**
* 退款信息表
*/
@Data
@Builder
@Data // 自动生成getter、setter、toString、equals、hashCode方法
@Builder // 自动生成builder模式的构造器
@NoArgsConstructor // 自动生成无参构造器
@AllArgsConstructor // 自动生成全参构造器
@TableName("refunds")
public class Refunds {
@TableId(type = IdType.AUTO)
private Long id;
private Long id; // 退款ID主键自增
private String refundNo;
private Long orderId;
private Long orderItemId;
private Long userId;
private Long shopId;
private BigDecimal refundAmount;
private String refundReason;
private String refundNo; // 退款单号
private Long orderId; // 订单ID外键关联orders表
private Long orderItemId; // 订单项ID外键关联order_items表
private Long userId; // 用户ID外键关联users表
private Long shopId; // 店铺ID外键关联shops表
private BigDecimal refundAmount; // 退款金额
private String refundReason; // 退款原因
private String refundType; // 退款类型
private Integer refundStatus; // 0: 申请中, 1: 退款成功, 2: 退款失败, 3: 已拒绝
private String refundAccount;
private String transactionId;
private Date applyTime;
private Date processTime;
private String processRemark;
private Date createdAt;
private Date updatedAt;
private Integer refundStatus; // 退款状态:0:申请中, 1:退款成功, 2:退款失败, 3:已拒绝
private String refundAccount; // 退款账户
private String transactionId; // 交易ID
private Date applyTime; // 申请时间
private Date processTime; // 处理时间
private String processRemark; // 处理备注
private Date createdAt; // 创建时间
private Date updatedAt; // 更新时间
}

View File

@@ -6,22 +6,24 @@ import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
/**
* 角色-权限关联表
*/
@Data
@Builder
@Data // 自动生成getter、setter、toString、equals、hashCode方法
@Builder // 自动生成builder模式的构造器
@NoArgsConstructor // 自动生成无参构造器
@AllArgsConstructor // 自动生成全参构造器
@TableName("role_permissions")
public class RolePermissions {
@TableId(type = IdType.AUTO)
private Long id;
private Long roleId;
private Long permissionId;
private Date createdAt;
private Long id; // 关联ID主键自增
private Long roleId; // 角色ID外键关联roles表
private Long permissionId; // 权限ID外键关联permissions表
private Date createdAt; // 创建时间
}

View File

@@ -6,25 +6,28 @@ import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
/**
* 角色信息表
*/
@Data
@Builder
@Data // 自动生成getter、setter、toString、equals、hashCode方法
@Builder // 自动生成builder模式的构造器
@NoArgsConstructor // 自动生成无参构造器
@AllArgsConstructor // 自动生成全参构造器
@TableName("roles")
public class Roles {
@TableId(type = IdType.AUTO)
private Long id;
private Long id; // 角色ID主键自增
private String roleName;
private String description;
private Integer roleType; // 0: 默认用户, 1: 店主, 2: 管理员
private Integer status; // 0: 禁用, 1: 启用
private Date createdAt;
private Date updatedAt;
private String roleName; // 角色名称
private String description; // 角色描述
private Integer roleType; // 角色类型:0:默认用户,1:店主,2:管理员
private Integer status; // 状态:0:禁用, 1:启用
private Date createdAt; // 创建时间
private Date updatedAt; // 更新时间
}

View File

@@ -6,27 +6,30 @@ import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
/**
* 店铺分类表
*/
@Data
@Builder
@Data // 自动生成getter、setter、toString、equals、hashCode方法
@Builder // 自动生成builder模式的构造器
@NoArgsConstructor // 自动生成无参构造器
@AllArgsConstructor // 自动生成全参构造器
@TableName("shop_categories")
public class ShopCategories {
@TableId(type = IdType.AUTO)
private Long id;
private Long id; // 分类ID主键自增
private String categoryName;
private String categoryName; // 分类名称
private Long parentId; // 父分类ID顶级分类为0
private Integer level; // 分类级别
private String icon;
private Integer sort;
private Integer status; // 0: 禁用, 1: 启用
private Date createdAt;
private Date updatedAt;
private String icon; // 分类图标
private Integer sort; // 排序
private Integer status; // 状态:0:禁用, 1:启用
private Date createdAt; // 创建时间
private Date updatedAt; // 更新时间
}

View File

@@ -6,28 +6,31 @@ import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
/**
* 店铺评分表
*/
@Data
@Builder
@Data // 自动生成getter、setter、toString、equals、hashCode方法
@Builder // 自动生成builder模式的构造器
@NoArgsConstructor // 自动生成无参构造器
@AllArgsConstructor // 自动生成全参构造器
@TableName("shop_ratings")
public class ShopRatings {
@TableId(type = IdType.AUTO)
private Long id;
private Long id; // 评价ID主键自增
private Long shopId;
private Long userId;
private Long orderId;
private Long shopId; // 店铺ID外键关联shops表
private Long userId; // 用户ID外键关联users表
private Long orderId; // 订单ID外键关联orders表
private Integer rating; // 评分1-5星
private String content;
private String content; // 评价内容
private String images; // 评价图片JSON格式存储
private Integer status; // 0: 待审核, 1: 已审核, 2: 已删除
private Date createdAt;
private Date updatedAt;
private Integer status; // 状态:0:待审核, 1:已审核, 2:已删除
private Date createdAt; // 创建时间
private Date updatedAt; // 更新时间
}

View File

@@ -7,35 +7,39 @@ import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
/**
* 店铺信息表
*/
@Data
@Builder
@Data // 自动生成getter、setter、toString、equals、hashCode方法
@Builder // 自动生成builder模式的构造器
@NoArgsConstructor // 自动生成无参构造器
@AllArgsConstructor // 自动生成全参构造器
@TableName("shops")
public class Shops {
@TableId(type = IdType.AUTO)
private Long id;
private Long id; // 店铺ID主键自增
private String shopName;
private Long userId; // 店主用户ID
private Long categoryId;
private String shopLogo;
private String coverImage;
private String description;
private String address;
private String contactPhone;
private String contactPerson;
private String shopName; // 店铺名称
private Long userId; // 店主用户ID外键关联users表
private Long categoryId; // 店铺分类ID外键关联shop_categories表
private String shopLogo; // 店铺Logo
private String coverImage; // 店铺封面图
private String description; // 店铺描述
private String address; // 店铺地址
private String contactPhone; // 联系电话
private String contactPerson; // 联系人
private BigDecimal rating; // 店铺评分
private Integer salesVolume;
private Integer status; // 0: 未审核, 1: 已审核, 2: 已关闭, 3: 审核失败
private String businessLicense;
private Date businessStartTime;
private Date businessEndTime;
private Date createdAt;
private Date updatedAt;
private Integer salesVolume; // 销量
private Integer status; // 状态:0: 未审核, 1: 已审核, 2: 已关闭, 3: 审核失败
private String businessLicense; // 营业执照
private Date businessStartTime; // 营业时间开始
private Date businessEndTime; // 营业时间结束
private Date createdAt; // 创建时间
private Date updatedAt; // 更新时间
}

View File

@@ -6,29 +6,33 @@ import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
/**
* 用户详细信息表
*/
@Data
@Builder
@Data // 自动生成getter、setter、toString、equals、hashCode方法
@Builder // 自动生成builder模式的构造器
@NoArgsConstructor // 自动生成无参构造器
@AllArgsConstructor // 自动生成全参构造器
@TableName("user_details")
public class UserDetails {
@TableId(type = IdType.AUTO)
private Long id;
private Long id; // 详情ID主键自增
private Long userId;
private String realName;
private String idCard;
private String gender; //男、女、保密
private Date birthday;
private String address;
private String province;
private String city;
private String district;
private Date createdAt;
private Date updatedAt;
private Long userId; // 用户ID外键关联users表
private String realName; // 真实姓名
private String idCard; // 身份证号
private String gender; // 性别:男、女、保密
private Date birthday; // 生日
private String address; // 地址
private String province; // 省份
private String city; // 城市
private String district; // 区县
private Date createdAt; // 创建时间
private Date updatedAt; // 更新时间
}

View File

@@ -6,21 +6,24 @@ import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
/**
* 用户-角色关联表
*/
@Data
@Builder
@Data // 自动生成getter、setter、toString、equals、hashCode方法
@Builder // 自动生成builder模式的构造器
@NoArgsConstructor // 自动生成无参构造器
@AllArgsConstructor // 自动生成全参构造器
@TableName("user_roles")
public class UserRoles {
@TableId(type = IdType.AUTO)
private Long id;
private Long userId;
private Long roleId;
private Date createdAt;
private Long id; // 关联ID主键自增
private Long userId; // 用户ID外键关联users表
private Long roleId; // 角色ID外键关联roles表
private Date createdAt; // 创建时间
}

View File

@@ -3,29 +3,35 @@ package com.qf.backend.entity;
import java.util.Date;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
/**
* 用户基本信息表
*/
@Data
@Builder
@Data // 自动生成getter、setter、toString、equals、hashCode方法
@Builder // 自动生成builder模式的构造器
@NoArgsConstructor // 自动生成无参构造器
@AllArgsConstructor // 自动生成全参构造器
@TableName("users")
public class Users {
@TableId(type = IdType.AUTO)
private Long id;
private String username;
private String password;
private String email;
private String phone;
private String nickname;
private String avatar;
private Integer status; // 0: 禁用, 1: 启用
private Date createdAt;
private Date updatedAt;
private Long id; // 用户ID主键自增
private String username; // 用户名,唯一
private String password; // 密码,加密存储
private String email; // 邮箱,唯一
private String phone; // 手机号,唯一
private String avatar; // 头像URL
@TableField(exist = false) // 标记该字段在数据库中不存在
private Date lastLoginTime; // 最后登录时间
private Integer status; // 状态0:禁用, 1:启用
private Date createdAt; // 创建时间
private Date updatedAt; // 更新时间
}

View File

@@ -38,7 +38,8 @@ public enum ErrorCode {
PRODUCT_OFF_SHELF(4092, "商品已下架"),
INSUFFICIENT_STOCK(4093, "库存不足"),
ORDER_CANCELLED(4094, "订单已取消"),
ROLE_NOT_FOUND(4095, "角色不存在"),
PASSWORD_ERROR(4096, "密码错误"),
// 服务器错误
SYSTEM_ERROR(500, "服务器内部错误"),
DATABASE_ERROR(5001, "数据库操作错误"),

View File

@@ -1,7 +1,7 @@
package com.qf.backend.exception;
import com.qf.backend.common.Result;
import com.qf.backend.common.ResultUtils;
import com.qf.backend.dto.Result;
import com.qf.backend.util.ResultUtils;
/**
* 异常处理使用示例

View File

@@ -4,8 +4,6 @@ import java.sql.SQLException;
import java.util.Objects;
import java.util.StringJoiner;
import javax.servlet.http.HttpServletRequest;
import org.springframework.http.HttpStatus;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.security.access.AccessDeniedException;
@@ -17,7 +15,7 @@ import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.HttpMediaTypeNotSupportedException;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.MissingPathVariableException;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
@@ -25,9 +23,10 @@ import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.method.annotation.MethodArgumentTypeMismatchException;
import org.springframework.web.servlet.NoHandlerFoundException;
import com.qf.backend.common.Result;
import com.qf.backend.common.ResultUtils;
import com.qf.backend.dto.Result;
import com.qf.backend.util.ResultUtils;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
/**
@@ -46,24 +45,17 @@ public class GlobalExceptionHandler {
log.warn("BusinessException: {} - Request: {}", e.getMessage(), request.getRequestURI());
return ResultUtils.fail(e.getCode(), e.getMessage());
}
/**
* 处理参数验证异常(@Valid
* 处理缺少路径变量异常
*/
@ExceptionHandler(MethodArgumentNotValidException.class)
@ExceptionHandler(MissingPathVariableException.class)
@ResponseStatus(HttpStatus.BAD_REQUEST)
public Result<?> handleMethodArgumentNotValidException(MethodArgumentNotValidException e, HttpServletRequest request) {
BindingResult bindingResult = e.getBindingResult();
StringJoiner joiner = new StringJoiner(", ");
for (FieldError fieldError : bindingResult.getFieldErrors()) {
joiner.add(fieldError.getField() + ": " + fieldError.getDefaultMessage());
}
String errorMsg = joiner.toString();
log.warn("MethodArgumentNotValidException: {} - Request: {}", errorMsg, request.getRequestURI());
public Result<?> handleMissingPathVariableException(MissingPathVariableException e, HttpServletRequest request) {
String errorMsg = "缺少路径变量: " + e.getVariableName();
log.warn("MissingPathVariableException: {} - Request: {}", errorMsg, request.getRequestURI());
return ResultUtils.paramError(errorMsg);
}
/**
/**
* 处理参数绑定异常(@RequestParam
*/
@ExceptionHandler(BindException.class)

View File

@@ -0,0 +1,60 @@
package com.qf.backend.inti;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.qf.backend.entity.Roles;
import com.qf.backend.service.RolesService;
/**
* 角色初始化配置类,用于在系统启动时创建内置角色
* @author 30803
*/
@Component
public class RoleInitializer {
private static final Logger logger = LoggerFactory.getLogger(RoleInitializer.class);
@Autowired
private RolesService rolesService;
/**
* 系统启动时初始化内置角色
*/
// @PostConstruct
public void initRoles() {
logger.info("开始初始化内置角色...");
// 定义内置角色信息
String[][] roleInfos = {
{"User", "默认用户角色", "0"}, // roleType: 0-默认用户
{"Shopkeeper", "店铺管理员角色", "1"}, // roleType: 1-店主
{"Admin", "系统管理员角色", "2"} // roleType: 2-管理员
};
for (String[] roleInfo : roleInfos) {
String roleName = roleInfo[0];
String description = roleInfo[1];
Integer roleType = Integer.parseInt(roleInfo[2]);
// 检查角色是否已存在
Roles existingRole = rolesService.getOne(new QueryWrapper<Roles>().eq("role_name", roleName));
if (existingRole == null) {
// 创建新角色
Roles role = new Roles();
role.setRoleName(roleName);
role.setDescription(description);
role.setRoleType(roleType);
role.setStatus(1); // 启用状态
rolesService.save(role);
logger.info("成功创建内置角色: {}", roleName);
} else {
logger.info("内置角色 {} 已存在,跳过创建", roleName);
}
}
logger.info("内置角色初始化完成");
}
}

View File

@@ -0,0 +1,66 @@
package com.qf.backend.inti;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.qf.backend.entity.Users;
import com.qf.backend.service.UsersService;
/**
* 用户初始化配置类,用于在系统启动时创建内置用户
* @author 30803
*/
@Component
public class UserInitializer {
private static final Logger logger = LoggerFactory.getLogger(UserInitializer.class);
@Autowired
private UsersService usersService;
/**
* 系统启动时初始化内置用户
*/
// @PostConstruct
public void initUsers() {
logger.info("开始初始化内置用户...");
// 定义内置用户信息
String[][] userInfos = {
// 用户名,密码,手机号,邮箱,状态
{"admin", "admin123", "13800000000", "admin@qq.com", "1"}, // 管理员用户
{"shopkeeper", "123456", "13800000001", "shopkeeper@qq.com", "1"}, // 店主用户
{"user", "123456", "13800000002", "user@qq.com", "1"} // 普通用户
};
for (String[] userInfo : userInfos) {
String username = userInfo[0];
String password = userInfo[1];
String phone = userInfo[2];
String email = userInfo[3];
Integer status = Integer.parseInt(userInfo[4]);
// 检查用户是否已存在
Users existingUser = usersService.getOne(new QueryWrapper<Users>().eq("username", username));
if (existingUser == null) {
// 创建新用户
Users user = new Users();
user.setUsername(username);
user.setPassword(password);
user.setPhone(phone);
user.setEmail(email);
user.setStatus(status);
// 注意不设置last_login_time字段因为数据库中可能不存在该字段
usersService.createUser(user);
logger.info("成功创建内置用户: {}", username);
} else {
logger.info("内置用户 {} 已存在,跳过创建", username);
}
}
logger.info("内置用户初始化完成");
}
}

View File

@@ -9,6 +9,7 @@ import com.qf.backend.entity.UserRoles;
* 用户角色关联表 Mapper 接口
*/
public interface UserRolesMapper extends BaseMapper<UserRoles> {
/**
* 查询用户角色关联信息
* @param userRoles 用户角色关联对象

View File

@@ -11,6 +11,14 @@ import com.qf.backend.entity.Users;
* 用户基本信息表 Mapper 接口
*/
public interface UsersMapper extends BaseMapper<Users> {
/**
* 登录
* @param username 用户名
* @param password 密码
* @return 用户对象
*/
@Select("select * from users where username = #{username} and password = #{password}")
Users login(String username, String password);
/**
* 根据用户名查询用户
* @param username 用户名
@@ -40,7 +48,6 @@ public interface UsersMapper extends BaseMapper<Users> {
* @return 用户对象
*/
Users selectInfo(Users users, QueryWrapper<Users> queryWrapper);
/**
* 更新用户信息
* @param users 用户信息

View File

@@ -3,7 +3,7 @@ package com.qf.backend.service;
import java.util.List;
import com.baomidou.mybatisplus.extension.service.IService;
import com.qf.backend.common.Result;
import com.qf.backend.dto.Result;
import com.qf.backend.entity.OrderItems;
/**

View File

@@ -1,7 +1,7 @@
package com.qf.backend.service;
import com.baomidou.mybatisplus.extension.service.IService;
import com.qf.backend.common.Result;
import com.qf.backend.dto.Result;
import com.qf.backend.entity.OrderStatusHistory;
import java.util.List;

View File

@@ -1,7 +1,7 @@
package com.qf.backend.service;
import com.baomidou.mybatisplus.extension.service.IService;
import com.qf.backend.common.Result;
import com.qf.backend.dto.Result;
import com.qf.backend.entity.Orders;
import java.util.List;

View File

@@ -1,6 +1,7 @@
package com.qf.backend.service;
import com.baomidou.mybatisplus.extension.service.IService;
import com.qf.backend.dto.Result;
import com.qf.backend.entity.Permissions;
import java.util.List;
@@ -15,60 +16,60 @@ public interface PermissionsService extends IService<Permissions> {
* @param permissionCode 权限编码
* @return 权限信息
*/
Permissions getPermissionByCode(String permissionCode);
Result<Permissions> getPermissionByCode(String permissionCode);
/**
* 创建权限
* @param permissions 权限信息
* @return 是否成功
*/
boolean createPermission(Permissions permissions);
Result<Boolean> createPermission(Permissions permissions);
/**
* 更新权限信息
* @param permissions 权限信息
* @return 是否成功
*/
boolean updatePermission(Permissions permissions);
Result<Boolean> updatePermission(Permissions permissions);
/**
* 删除权限
* @param id 权限ID
* @return 是否成功
*/
boolean deletePermission(Long id);
Result<Boolean> deletePermission(Long id);
/**
* 查询所有权限
* @return 权限列表
*/
List<Permissions> listAllPermissions();
Result<List<Permissions>> listAllPermissions();
/**
* 根据权限ID查询权限
* @param id 权限ID
* @return 权限信息
*/
Permissions getPermissionById(Long id);
Result<Permissions> getPermissionById(Long id);
/**
* 批量删除权限
* @param ids 权限ID列表
* @return 是否成功
*/
boolean batchDeletePermissions(List<Long> ids);
Result<Boolean> batchDeletePermissions(List<Long> ids);
/**
* 根据菜单ID查询权限
* @param menuId 菜单ID
* @return 权限列表
*/
List<Permissions> listPermissionsByMenuId(Long menuId);
Result<List<Permissions>> listPermissionsByMenuId(Long menuId);
/**
* 根据权限类型查询权限
* @param permissionType 权限类型
* @return 权限列表
*/
List<Permissions> listPermissionsByType(String permissionType);
Result<List<Permissions>> listPermissionsByType(String permissionType);
}

View File

@@ -1,7 +1,7 @@
package com.qf.backend.service;
import com.baomidou.mybatisplus.extension.service.IService;
import com.qf.backend.common.Result;
import com.qf.backend.dto.Result;
import com.qf.backend.entity.ProductAttributeValues;
import java.util.List;

View File

@@ -1,7 +1,7 @@
package com.qf.backend.service;
import com.baomidou.mybatisplus.extension.service.IService;
import com.qf.backend.common.Result;
import com.qf.backend.dto.Result;
import com.qf.backend.entity.ProductAttributes;
import java.util.List;

View File

@@ -1,7 +1,7 @@
package com.qf.backend.service;
import com.baomidou.mybatisplus.extension.service.IService;
import com.qf.backend.common.Result;
import com.qf.backend.dto.Result;
import com.qf.backend.entity.ProductCategories;
import java.util.List;

View File

@@ -1,7 +1,7 @@
package com.qf.backend.service;
import com.baomidou.mybatisplus.extension.service.IService;
import com.qf.backend.common.Result;
import com.qf.backend.dto.Result;
import com.qf.backend.entity.ProductImages;
import java.util.List;

View File

@@ -1,7 +1,7 @@
package com.qf.backend.service;
import com.baomidou.mybatisplus.extension.service.IService;
import com.qf.backend.common.Result;
import com.qf.backend.dto.Result;
import com.qf.backend.entity.ProductInventories;
import java.util.List;

View File

@@ -1,7 +1,7 @@
package com.qf.backend.service;
import com.baomidou.mybatisplus.extension.service.IService;
import com.qf.backend.common.Result;
import com.qf.backend.dto.Result;
import com.qf.backend.entity.ProductSkus;
import java.util.List;

View File

@@ -1,7 +1,7 @@
package com.qf.backend.service;
import com.baomidou.mybatisplus.extension.service.IService;
import com.qf.backend.common.Result;
import com.qf.backend.dto.Result;
import com.qf.backend.entity.Products;
import java.util.List;

View File

@@ -3,6 +3,7 @@ package com.qf.backend.service;
import java.util.List;
import com.baomidou.mybatisplus.extension.service.IService;
import com.qf.backend.dto.Result;
import com.qf.backend.entity.Roles;
/**
@@ -15,53 +16,53 @@ public interface RolesService extends IService<Roles> {
* @param roleName 角色名称
* @return 角色信息
*/
Roles getRoleByName(String roleName);
Result<Roles> getRoleByName(String roleName);
/**
* 创建角色
* @param roles 角色信息
* @return 是否成功
*/
boolean createRole(Roles roles);
Result<Boolean> createRole(Roles roles);
/**
* 更新角色信息
* @param roles 角色信息
* @return 是否成功
*/
boolean updateRole(Roles roles);
Result<Boolean> updateRole(Roles roles);
/**
* 删除角色
* @param id 角色ID
* @return 是否成功
*/
boolean deleteRole(Long id);
Result<Boolean> deleteRole(Long id);
/**
* 查询所有角色
* @return 角色列表
*/
List<Roles> listAllRoles();
Result<List<Roles>> listAllRoles();
/**
* 根据角色ID查询角色
* @param id 角色ID
* @return 角色信息
*/
Roles getRoleById(Long id);
Result<Roles> getRoleById(Long id);
/**
* 批量删除角色
* @param ids 角色ID列表
* @return 是否成功
*/
boolean batchDeleteRoles(List<Long> ids);
Result<Boolean> batchDeleteRoles(List<Long> ids);
/**
* 根据用户ID查询其拥有的角色列表
* @param userId 用户ID
* @return 角色列表
*/
List<Roles> listRolesByUserId(Long userId);
Result<List<Roles>> listRolesByUserId(Long userId);
}

View File

@@ -1,7 +1,7 @@
package com.qf.backend.service;
import com.baomidou.mybatisplus.extension.service.IService;
import com.qf.backend.common.Result;
import com.qf.backend.dto.Result;
import com.qf.backend.entity.ShopCategories;
import java.util.List;

View File

@@ -1,7 +1,7 @@
package com.qf.backend.service;
import com.baomidou.mybatisplus.extension.service.IService;
import com.qf.backend.common.Result;
import com.qf.backend.dto.Result;
import com.qf.backend.entity.ShopRatings;
import java.util.List;

View File

@@ -3,7 +3,7 @@ package com.qf.backend.service;
import java.util.List;
import com.baomidou.mybatisplus.extension.service.IService;
import com.qf.backend.common.Result;
import com.qf.backend.dto.Result;
import com.qf.backend.entity.Shops;
/**

View File

@@ -1,7 +1,7 @@
package com.qf.backend.service;
import com.baomidou.mybatisplus.extension.service.IService;
import com.qf.backend.common.Result;
import com.qf.backend.dto.Result;
import com.qf.backend.entity.UserDetails;
/**
@@ -44,12 +44,4 @@ public interface UserDetailsService extends IService<UserDetails> {
*/
Result<UserDetails> getUserDetailsById(Long id);
/**
* 更新用户联系方式
* @param userId 用户ID
* @param phone 手机号
* @param email 邮箱
* @return 是否成功
*/
Result<Boolean> updateContactInfo(Long userId, String phone, String email);
}

View File

@@ -0,0 +1,22 @@
/*
* Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license
* Click nbfs://nbhost/SystemFileSystem/Templates/Classes/Interface.java to edit this template
*/
package com.qf.backend.service;
import com.qf.backend.dto.LoginResponse;
import com.qf.backend.dto.Result;
/**
* 用户登录服务接口
*/
public interface UserLoginService {
/**
* 用户登录
* @param username 用户名
* @param password 密码
* @return 登录结果包含登录状态、token等信息
*/
Result<LoginResponse> login(String username, String password);
}

View File

@@ -1,11 +1,11 @@
package com.qf.backend.service;
import com.baomidou.mybatisplus.extension.service.IService;
import com.qf.backend.common.Result;
import com.qf.backend.entity.UserRoles;
import java.util.List;
import com.baomidou.mybatisplus.extension.service.IService;
import com.qf.backend.dto.Result;
import com.qf.backend.entity.UserRoles;
/**
* 用户角色关联服务接口
*/

View File

@@ -1,11 +1,11 @@
package com.qf.backend.service;
import com.baomidou.mybatisplus.extension.service.IService;
import com.qf.backend.common.Result;
import com.qf.backend.entity.Users;
import java.util.List;
import com.baomidou.mybatisplus.extension.service.IService;
import com.qf.backend.dto.Result;
import com.qf.backend.entity.Users;
/**
* 用户服务接口
*/
@@ -25,6 +25,14 @@ public interface UsersService extends IService<Users> {
*/
Result<Users> getUserByEmail(String email);
/**
* 登录
* @param username 用户名
* @param password 密码
* @return 用户信息
*/
Result<Users> login(String username, String password);
/**
* 创建用户
* @param users 用户信息

View File

@@ -1,5 +1,6 @@
package com.qf.backend.service.impl;
import java.math.BigDecimal;
import java.util.Collection;
import java.util.List;
import java.util.Map;
@@ -10,13 +11,15 @@ import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.qf.backend.common.Result;
import com.qf.backend.common.ResultUtils;
import com.qf.backend.dto.Result;
import com.qf.backend.entity.OrderItems;
import com.qf.backend.exception.BusinessException;
import com.qf.backend.exception.ErrorCode;
import com.qf.backend.mapper.OrderItemsMapper;
import com.qf.backend.service.OrderItemsService;
import com.qf.backend.util.ResultUtils;
@Service
public class OrderItemsServiceImpl implements OrderItemsService {
@@ -26,117 +29,398 @@ public class OrderItemsServiceImpl implements OrderItemsService {
@Override
public Result<List<OrderItems>> getOrderItemsByOrderId(Long orderId) {
// 参数校验
if (orderId == null) {
throw new BusinessException(ErrorCode.MISSING_PARAM, "订单ID不能为空");
}
try {
List<OrderItems> orderItems = orderItemsMapper.selectByOrderId(orderId);
if (orderItems == null || orderItems.isEmpty()) {
return ResultUtils.fail(ErrorCode.ORDER_NOT_FOUND);
throw new BusinessException(ErrorCode.NOT_FOUND, "订单商品不存在");
}
return ResultUtils.success(orderItems);
} catch (BusinessException e) {
throw e;
} catch (Exception e) {
return ResultUtils.fail(ErrorCode.ORDER_NOT_FOUND);
throw new BusinessException(ErrorCode.DATABASE_ERROR, "查询订单商品失败: " + e.getMessage(), e);
}
}
@Override
public Result<List<OrderItems>> getOrderItemsByProductId(Long productId) {
// 参数校验
if (productId == null) {
throw new BusinessException(ErrorCode.MISSING_PARAM, "商品ID不能为空");
}
try {
List<OrderItems> orderItems = orderItemsMapper.selectByProductId(productId);
if (orderItems == null || orderItems.isEmpty()) {
return ResultUtils.fail(ErrorCode.ORDER_NOT_FOUND);
throw new BusinessException(ErrorCode.NOT_FOUND, "订单商品不存在");
}
return ResultUtils.success(orderItems);
} catch (BusinessException e) {
throw e;
} catch (Exception e) {
return ResultUtils.fail(ErrorCode.ORDER_NOT_FOUND);
throw new BusinessException(ErrorCode.DATABASE_ERROR, "查询订单商品失败: " + e.getMessage(), e);
}
}
@Override
public BaseMapper<OrderItems> getBaseMapper() {
// TODO Auto-generated method stub
throw new UnsupportedOperationException("Unimplemented method 'getBaseMapper'");
return orderItemsMapper;
}
@Override
public Class<OrderItems> getEntityClass() {
// TODO Auto-generated method stub
throw new UnsupportedOperationException("Unimplemented method 'getEntityClass'");
return OrderItems.class;
}
@Override
public Map<String, Object> getMap(Wrapper<OrderItems> queryWrapper) {
// TODO Auto-generated method stub
throw new UnsupportedOperationException("Unimplemented method 'getMap'");
try {
return orderItemsMapper.selectMaps(queryWrapper).get(0);
} catch (Exception e) {
throw new BusinessException(ErrorCode.DATABASE_ERROR, "获取Map数据失败: " + e.getMessage(), e);
}
}
@Override
public <V> V getObj(Wrapper<OrderItems> queryWrapper, Function<? super Object, V> mapper) {
// TODO Auto-generated method stub
throw new UnsupportedOperationException("Unimplemented method 'getObj'");
try {
OrderItems orderItem = orderItemsMapper.selectOne(queryWrapper);
if (orderItem == null) {
throw new BusinessException(ErrorCode.NOT_FOUND, "订单商品不存在");
}
return mapper.apply(orderItem);
} catch (BusinessException e) {
throw e;
} catch (Exception e) {
throw new BusinessException(ErrorCode.DATABASE_ERROR, "获取对象数据失败: " + e.getMessage(), e);
}
}
@Override
public OrderItems getOne(Wrapper<OrderItems> queryWrapper, boolean throwEx) {
// TODO Auto-generated method stub
throw new UnsupportedOperationException("Unimplemented method 'getOne'");
try {
OrderItems orderItem = orderItemsMapper.selectOne(queryWrapper);
if (orderItem == null && throwEx) {
throw new BusinessException(ErrorCode.NOT_FOUND, "订单商品不存在");
}
return orderItem;
} catch (BusinessException e) {
throw e;
} catch (Exception e) {
throw new BusinessException(ErrorCode.DATABASE_ERROR, "获取单个对象失败: " + e.getMessage(), e);
}
}
@Override
public Optional<OrderItems> getOneOpt(Wrapper<OrderItems> queryWrapper, boolean throwEx) {
// TODO Auto-generated method stub
throw new UnsupportedOperationException("Unimplemented method 'getOneOpt'");
try {
OrderItems orderItem = orderItemsMapper.selectOne(queryWrapper);
if (orderItem == null && throwEx) {
throw new BusinessException(ErrorCode.NOT_FOUND, "订单商品不存在");
}
return Optional.ofNullable(orderItem);
} catch (BusinessException e) {
throw e;
} catch (Exception e) {
throw new BusinessException(ErrorCode.DATABASE_ERROR, "获取Optional对象失败: " + e.getMessage(), e);
}
}
@Override
public boolean saveBatch(Collection<OrderItems> entityList, int batchSize) {
// TODO Auto-generated method stub
throw new UnsupportedOperationException("Unimplemented method 'saveBatch'");
try {
if (entityList == null || entityList.isEmpty()) {
throw new BusinessException(ErrorCode.MISSING_PARAM, "实体列表不能为空");
}
if (batchSize <= 0) {
throw new BusinessException(ErrorCode.INVALID_PARAM, "批处理大小必须大于0");
}
// 简单的批量保存实现
for (OrderItems entity : entityList) {
orderItemsMapper.insert(entity);
}
return true;
} catch (BusinessException e) {
throw e;
} catch (Exception e) {
throw new BusinessException(ErrorCode.DATABASE_ERROR, "批量保存失败: " + e.getMessage(), e);
}
}
@Override
public boolean saveOrUpdate(OrderItems entity) {
// TODO Auto-generated method stub
throw new UnsupportedOperationException("Unimplemented method 'saveOrUpdate'");
try {
if (entity == null) {
throw new BusinessException(ErrorCode.MISSING_PARAM, "实体不能为空");
}
if (entity.getId() == null) {
// 新增
return orderItemsMapper.insert(entity) > 0;
} else {
// 更新
return orderItemsMapper.updateById(entity) > 0;
}
} catch (BusinessException e) {
throw e;
} catch (Exception e) {
throw new BusinessException(ErrorCode.DATABASE_ERROR, "保存或更新失败: " + e.getMessage(), e);
}
}
@Override
public boolean saveOrUpdateBatch(Collection<OrderItems> entityList, int batchSize) {
// TODO Auto-generated method stub
throw new UnsupportedOperationException("Unimplemented method 'saveOrUpdateBatch'");
try {
if (entityList == null || entityList.isEmpty()) {
throw new BusinessException(ErrorCode.MISSING_PARAM, "实体列表不能为空");
}
if (batchSize <= 0) {
throw new BusinessException(ErrorCode.INVALID_PARAM, "批处理大小必须大于0");
}
for (OrderItems entity : entityList) {
saveOrUpdate(entity);
}
return true;
} catch (BusinessException e) {
throw e;
} catch (Exception e) {
throw new BusinessException(ErrorCode.DATABASE_ERROR, "批量保存或更新失败: " + e.getMessage(), e);
}
}
@Override
public boolean updateBatchById(Collection<OrderItems> entityList, int batchSize) {
// TODO Auto-generated method stub
throw new UnsupportedOperationException("Unimplemented method 'updateBatchById'");
try {
if (entityList == null || entityList.isEmpty()) {
throw new BusinessException(ErrorCode.MISSING_PARAM, "实体列表不能为空");
}
if (batchSize <= 0) {
throw new BusinessException(ErrorCode.INVALID_PARAM, "批处理大小必须大于0");
}
for (OrderItems entity : entityList) {
if (entity.getId() == null) {
throw new BusinessException(ErrorCode.MISSING_PARAM, "实体ID不能为空");
}
orderItemsMapper.updateById(entity);
}
return true;
} catch (BusinessException e) {
throw e;
} catch (Exception e) {
throw new BusinessException(ErrorCode.DATABASE_ERROR, "批量更新失败: " + e.getMessage(), e);
}
}
@Override
public Result<Boolean> createOrderItem(OrderItems orderItems) {
// TODO Auto-generated method stub
throw new UnsupportedOperationException("Unimplemented method 'createOrderItem'");
// 参数校验
if (orderItems == null) {
throw new BusinessException(ErrorCode.MISSING_PARAM, "订单商品信息不能为空");
}
if (orderItems.getOrderId() == null) {
throw new BusinessException(ErrorCode.MISSING_PARAM, "订单ID不能为空");
}
if (orderItems.getProductId() == null) {
throw new BusinessException(ErrorCode.MISSING_PARAM, "商品ID不能为空");
}
if (orderItems.getQuantity() == null || orderItems.getQuantity() <= 0) {
throw new BusinessException(ErrorCode.INVALID_PARAM, "商品数量必须大于0");
}
if (orderItems.getPrice() == null || orderItems.getPrice().compareTo(BigDecimal.ZERO) < 0) {
throw new BusinessException(ErrorCode.INVALID_PARAM, "商品价格不能为负数");
}
try {
int result = orderItemsMapper.insert(orderItems);
if (result <= 0) {
throw new BusinessException(ErrorCode.BUSINESS_ERROR, "创建订单商品失败");
}
return ResultUtils.success(true);
} catch (BusinessException e) {
throw e;
} catch (Exception e) {
throw new BusinessException(ErrorCode.DATABASE_ERROR, "创建订单商品失败: " + e.getMessage(), e);
}
}
@Override
public Result<Boolean> updateOrderItem(OrderItems orderItems) {
// TODO Auto-generated method stub
throw new UnsupportedOperationException("Unimplemented method 'updateOrderItem'");
// 参数校验
if (orderItems == null) {
throw new BusinessException(ErrorCode.MISSING_PARAM, "订单商品信息不能为空");
}
if (orderItems.getId() == null) {
throw new BusinessException(ErrorCode.MISSING_PARAM, "订单商品ID不能为空");
}
try {
// 检查是否存在
OrderItems existingItem = orderItemsMapper.selectById(orderItems.getId());
if (existingItem == null) {
throw new BusinessException(ErrorCode.NOT_FOUND, "订单商品不存在");
}
int result = orderItemsMapper.updateById(orderItems);
if (result <= 0) {
throw new BusinessException(ErrorCode.BUSINESS_ERROR, "更新订单商品失败");
}
return ResultUtils.success(true);
} catch (BusinessException e) {
throw e;
} catch (Exception e) {
throw new BusinessException(ErrorCode.DATABASE_ERROR, "更新订单商品失败: " + e.getMessage(), e);
}
}
@Override
public Result<Boolean> deleteOrderItem(Long id) {
// TODO Auto-generated method stub
throw new UnsupportedOperationException("Unimplemented method 'deleteOrderItem'");
// 参数校验
if (id == null) {
throw new BusinessException(ErrorCode.MISSING_PARAM, "订单商品ID不能为空");
}
try {
// 检查是否存在
OrderItems orderItem = orderItemsMapper.selectById(id);
if (orderItem == null) {
throw new BusinessException(ErrorCode.NOT_FOUND, "订单商品不存在");
}
int result = orderItemsMapper.deleteById(id);
if (result <= 0) {
throw new BusinessException(ErrorCode.BUSINESS_ERROR, "删除订单商品失败");
}
return ResultUtils.success(true);
} catch (BusinessException e) {
throw e;
} catch (Exception e) {
throw new BusinessException(ErrorCode.DATABASE_ERROR, "删除订单商品失败: " + e.getMessage(), e);
}
}
@Override
public Result<OrderItems> getOrderItemById(Long id) {
// TODO Auto-generated method stub
throw new UnsupportedOperationException("Unimplemented method 'getOrderItemById'");
// 参数校验
if (id == null) {
throw new BusinessException(ErrorCode.MISSING_PARAM, "订单商品ID不能为空");
}
try {
OrderItems orderItem = orderItemsMapper.selectById(id);
if (orderItem == null) {
throw new BusinessException(ErrorCode.NOT_FOUND, "订单商品不存在");
}
return ResultUtils.success(orderItem);
} catch (BusinessException e) {
throw e;
} catch (Exception e) {
throw new BusinessException(ErrorCode.DATABASE_ERROR, "查询订单商品失败: " + e.getMessage(), e);
}
}
@Override
public Result<Boolean> batchCreateOrderItems(List<OrderItems> orderItemsList) {
// TODO Auto-generated method stub
throw new UnsupportedOperationException("Unimplemented method 'batchCreateOrderItems'");
// 参数校验
if (orderItemsList == null || orderItemsList.isEmpty()) {
throw new BusinessException(ErrorCode.MISSING_PARAM, "订单商品列表不能为空");
}
if (orderItemsList.size() > 100) {
throw new BusinessException(ErrorCode.INVALID_PARAM, "批量创建数量不能超过100个");
}
try {
// 逐个创建订单商品
for (OrderItems orderItem : orderItemsList) {
// 验证每个订单商品
if (orderItem.getOrderId() == null || orderItem.getProductId() == null ||
orderItem.getQuantity() == null || orderItem.getQuantity() <= 0 ||
orderItem.getPrice() == null || orderItem.getPrice().compareTo(BigDecimal.ZERO) < 0) {
throw new BusinessException(ErrorCode.INVALID_PARAM, "订单商品信息不完整或无效");
}
int result = orderItemsMapper.insert(orderItem);
if (result <= 0) {
throw new BusinessException(ErrorCode.BUSINESS_ERROR, "批量创建订单商品失败");
}
}
return ResultUtils.success(true);
} catch (BusinessException e) {
throw e;
} catch (Exception e) {
throw new BusinessException(ErrorCode.DATABASE_ERROR, "批量创建订单商品失败: " + e.getMessage(), e);
}
}
@Override
public Result<Boolean> deleteOrderItemsByOrderId(Long orderId) {
// TODO Auto-generated method stub
throw new UnsupportedOperationException("Unimplemented method 'deleteOrderItemsByOrderId'");
// 参数校验
if (orderId == null) {
throw new BusinessException(ErrorCode.MISSING_PARAM, "订单ID不能为空");
}
try {
int result = orderItemsMapper.delete(
new QueryWrapper<OrderItems>().eq("order_id", orderId)
);
return ResultUtils.success(true);
} catch (BusinessException e) {
throw e;
} catch (Exception e) {
throw new BusinessException(ErrorCode.DATABASE_ERROR, "删除订单下所有商品失败: " + e.getMessage(), e);
}
}
@Override
public Result<Double> calculateOrderTotal(Long orderId) {
// TODO Auto-generated method stub
throw new UnsupportedOperationException("Unimplemented method 'calculateOrderTotal'");
// 参数校验
if (orderId == null) {
throw new BusinessException(ErrorCode.MISSING_PARAM, "订单ID不能为空");
}
try {
List<OrderItems> orderItems = orderItemsMapper.selectByOrderId(orderId);
if (orderItems == null || orderItems.isEmpty()) {
throw new BusinessException(ErrorCode.NOT_FOUND, "订单商品不存在");
}
double totalAmount = 0.0;
for (OrderItems item : orderItems) {
totalAmount += item.getPrice().multiply(new BigDecimal(item.getQuantity())).doubleValue();
}
return ResultUtils.success(totalAmount);
} catch (BusinessException e) {
throw e;
} catch (Exception e) {
throw new BusinessException(ErrorCode.DATABASE_ERROR, "计算订单总金额失败: " + e.getMessage(), e);
}
}
@Override
public Result<List<OrderItems>> getOrderItemsBySkuId(Long skuId) {
// TODO Auto-generated method stub
throw new UnsupportedOperationException("Unimplemented method 'getOrderItemsBySkuId'");
// 参数校验
if (skuId == null) {
throw new BusinessException(ErrorCode.MISSING_PARAM, "SKU ID不能为空");
}
try {
List<OrderItems> orderItems = orderItemsMapper.selectList(
new QueryWrapper<OrderItems>().eq("sku_id", skuId)
);
if (orderItems == null || orderItems.isEmpty()) {
throw new BusinessException(ErrorCode.NOT_FOUND, "该SKU的订单商品不存在");
}
return ResultUtils.success(orderItems);
} catch (BusinessException e) {
throw e;
} catch (Exception e) {
throw new BusinessException(ErrorCode.DATABASE_ERROR, "查询SKU订单商品失败: " + e.getMessage(), e);
}
}
}

View File

@@ -0,0 +1,166 @@
package com.qf.backend.service.impl;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qf.backend.dto.Result;
import com.qf.backend.entity.OrderStatusHistory;
import com.qf.backend.exception.BusinessException;
import com.qf.backend.exception.ErrorCode;
import com.qf.backend.mapper.OrderStatusHistoryMapper;
import com.qf.backend.service.OrderStatusHistoryService;
import com.qf.backend.util.ValidateUtil;
@Service
public class OrderStatusHistoryServiceImpl extends ServiceImpl<OrderStatusHistoryMapper, OrderStatusHistory> implements OrderStatusHistoryService {
private static final Logger logger = LoggerFactory.getLogger(OrderStatusHistoryServiceImpl.class);
@Autowired
private OrderStatusHistoryMapper orderStatusHistoryMapper;
@Override
public Result<List<OrderStatusHistory>> getHistoryByOrderId(Long orderId) {
logger.info("根据订单ID查询订单状态历史记录订单ID{}", orderId);
if (ValidateUtil.isEmpty(orderId)) {
throw new BusinessException(ErrorCode.MISSING_PARAM, "订单ID不能为空");
}
try {
List<OrderStatusHistory> historyList = orderStatusHistoryMapper.selectList( new QueryWrapper<OrderStatusHistory>().eq("order_id", orderId));
return Result.success(historyList);
} catch (BusinessException e) {
throw e;
} catch (Exception e) {
throw new BusinessException(ErrorCode.DATABASE_ERROR, "查询订单状态历史记录失败", e);
}
}
@Override
public Result<Boolean> createStatusHistory(OrderStatusHistory orderStatusHistory) {
logger.info("创建订单状态历史记录订单ID{}", orderStatusHistory.getOrderId());
if (ValidateUtil.isEmpty(orderStatusHistory.getOrderId())) {
throw new BusinessException(ErrorCode.MISSING_PARAM, "订单ID不能为空");
}
try {
int result = orderStatusHistoryMapper.insert(orderStatusHistory);
if (result > 0) {
throw new BusinessException(ErrorCode.DATABASE_ERROR, "创建订单状态历史记录失败");
}
return Result.success(true);
} catch (Exception e) {
throw new BusinessException(ErrorCode.DATABASE_ERROR, "创建订单状态历史记录失败", e);
}
}
@Override
public Result<Boolean> updateStatusHistory(OrderStatusHistory orderStatusHistory) {
logger.info("更新订单状态历史记录订单ID{}", orderStatusHistory.getOrderId());
if (ValidateUtil.isEmpty(orderStatusHistory.getOrderId())) {
throw new BusinessException(ErrorCode.MISSING_PARAM, "订单ID不能为空");
}
try {
boolean result = orderStatusHistoryMapper.updateById(orderStatusHistory) > 0;
return Result.success(result);
} catch (Exception e) {
throw new BusinessException(ErrorCode.DATABASE_ERROR, "更新订单状态历史记录失败", e);
}
}
@Override
public Result<Boolean> deleteStatusHistory(Long id) {
logger.info("删除订单状态历史记录ID{}", id);
if (ValidateUtil.isEmpty(id)) {
throw new BusinessException(ErrorCode.MISSING_PARAM, "ID不能为空");
}
try {
boolean result = orderStatusHistoryMapper.deleteById(id) > 0;
return Result.success(result);
} catch (Exception e) {
throw new BusinessException(ErrorCode.DATABASE_ERROR, "删除订单状态历史记录失败", e);
}
}
@Override
public Result<OrderStatusHistory> getStatusHistoryById(Long id) {
logger.info("根据ID查询订单状态历史记录ID{}", id);
if (ValidateUtil.isEmpty(id)) {
throw new BusinessException(ErrorCode.MISSING_PARAM, "ID不能为空");
}
try {
OrderStatusHistory history = orderStatusHistoryMapper.selectById(id);
return Result.success(history);
} catch (Exception e) {
throw new BusinessException(ErrorCode.DATABASE_ERROR, "查询订单状态历史记录失败", e);
}
}
@Override
public Result<Boolean> batchCreateStatusHistory(List<OrderStatusHistory> historyList) {
logger.info("批量创建订单状态历史记录,数量:{}", historyList.size());
if (ValidateUtil.isEmpty(historyList)) {
throw new BusinessException(ErrorCode.MISSING_PARAM, "订单状态历史记录列表不能为空");
}
try {
for (OrderStatusHistory history : historyList) {
int result = orderStatusHistoryMapper.insert(history);
if (result > 0) {
throw new BusinessException(ErrorCode.DATABASE_ERROR, "批量创建订单状态历史记录失败");
}
}
return Result.success(true);
} catch (Exception e) {
throw new BusinessException(ErrorCode.DATABASE_ERROR, "批量创建订单状态历史记录失败", e);
}
}
@Override
public Result<List<OrderStatusHistory>> getHistoryByOrderIdAndStatus(Long orderId, Integer status) {
logger.info("根据订单ID和状态查询订单状态历史记录订单ID{},状态:{}", orderId, status);
if (ValidateUtil.isEmpty(orderId)) {
throw new BusinessException(ErrorCode.MISSING_PARAM, "订单ID不能为空");
}
try {
List<OrderStatusHistory> historyList = orderStatusHistoryMapper.selectList( new QueryWrapper<OrderStatusHistory>().eq("order_id", orderId).eq("status", status));
return Result.success(historyList);
} catch (Exception e) {
throw new BusinessException(ErrorCode.DATABASE_ERROR, "查询订单状态历史记录失败", e);
}
}
@Override
public Result<OrderStatusHistory> getLatestStatusHistory(Long orderId) {
logger.info("根据订单ID查询最新订单状态历史记录订单ID{}", orderId);
if (ValidateUtil.isEmpty(orderId)) {
throw new BusinessException(ErrorCode.MISSING_PARAM, "订单ID不能为空");
}
try {
OrderStatusHistory history = orderStatusHistoryMapper.selectOne( new QueryWrapper<OrderStatusHistory>().eq("order_id", orderId).orderByDesc("id").last("limit 1"));
return Result.success(history);
} catch (Exception e) {
throw new BusinessException(ErrorCode.DATABASE_ERROR, "查询最新订单状态历史记录失败", e);
}
}
@Override
public Result<Boolean> deleteHistoryByOrderId(Long orderId) {
logger.info("根据订单ID删除订单状态历史记录订单ID{}", orderId);
if (ValidateUtil.isEmpty(orderId)) {
throw new BusinessException(ErrorCode.MISSING_PARAM, "订单ID不能为空");
}
try {
boolean result = orderStatusHistoryMapper.delete( new QueryWrapper<OrderStatusHistory>().eq("order_id", orderId)) > 0;
return Result.success(result);
} catch (Exception e) {
throw new BusinessException(ErrorCode.DATABASE_ERROR, "删除订单状态历史记录失败", e);
}
}
}

View File

@@ -1,5 +1,7 @@
package com.qf.backend.service.impl;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import org.slf4j.Logger;
@@ -7,86 +9,293 @@ import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qf.backend.common.Result;
import com.qf.backend.common.ResultUtils;
import com.qf.backend.dto.Result;
import com.qf.backend.entity.Orders;
import com.qf.backend.exception.BusinessException;
import com.qf.backend.exception.ErrorCode;
import com.qf.backend.mapper.OrdersMapper;
import com.qf.backend.service.OrdersService;
import com.qf.backend.util.ResultUtils;
@Service
public class OrdersServiceImpl extends ServiceImpl<OrdersMapper, Orders> implements OrdersService {
private final Logger logger = LoggerFactory.getLogger(OrdersServiceImpl.class);
@Autowired
private OrdersMapper ordersMapper;
private Logger logger = LoggerFactory.getLogger(OrdersServiceImpl.class);
@Override
public Result<Orders> getOrderByNumber(String orderNumber) {
logger.info("根据订单号查询订单: {}", orderNumber);
// 参数校验
if (orderNumber == null || orderNumber.trim().isEmpty()) {
throw new BusinessException(ErrorCode.MISSING_PARAM, "订单编号不能为空");
}
try {
Orders orders = ordersMapper.selectByOrderNumber(orderNumber);
if (orders == null) {
logger.warn("订单号 {} 不存在", orderNumber);
return ResultUtils.fail(ErrorCode.ORDER_NOT_FOUND);
throw new BusinessException(ErrorCode.ORDER_NOT_FOUND, "订单不存在: " + orderNumber);
}
return ResultUtils.success(orders);
} catch (BusinessException e) {
throw e;
} catch (Exception e) {
return ResultUtils.fail(ErrorCode.ORDER_NOT_FOUND);
logger.error("查询订单失败: {}", e.getMessage(), e);
throw new BusinessException(ErrorCode.DATABASE_ERROR, "查询订单失败: " + e.getMessage(), e);
}
}
@Override
public Result<List<Orders>> getOrdersByUserId(Long userId) {
// TODO Auto-generated method stub
throw new UnsupportedOperationException("Unimplemented method 'getOrdersByUserId'");
// 参数校验
if (userId == null) {
throw new BusinessException(ErrorCode.MISSING_PARAM, "用户ID不能为空");
}
try {
List<Orders> ordersList = ordersMapper.selectList(
new QueryWrapper<Orders>().eq("user_id", userId).orderByDesc("create_time")
);
return ResultUtils.success(ordersList);
} catch (BusinessException e) {
throw e;
} catch (Exception e) {
logger.error("查询用户订单失败: {}", e.getMessage(), e);
throw new BusinessException(ErrorCode.DATABASE_ERROR, "查询用户订单失败: " + e.getMessage(), e);
}
}
@Override
public Result<Boolean> createOrder(Orders orders) {
// TODO Auto-generated method stub
throw new UnsupportedOperationException("Unimplemented method 'createOrder'");
// 参数校验
if (orders == null) {
throw new BusinessException(ErrorCode.MISSING_PARAM, "订单信息不能为空");
}
if (orders.getUserId() == null) {
throw new BusinessException(ErrorCode.MISSING_PARAM, "用户ID不能为空");
}
if (orders.getOrderNo() == null || orders.getOrderNo().trim().isEmpty()) {
throw new BusinessException(ErrorCode.MISSING_PARAM, "订单编号不能为空");
}
if (orders.getTotalAmount() == null || orders.getTotalAmount().compareTo(BigDecimal.ZERO) < 0) {
throw new BusinessException(ErrorCode.INVALID_PARAM, "订单金额不能为负数");
}
try {
// 检查订单编号是否已存在
Orders existingOrder = ordersMapper.selectByOrderNumber(orders.getOrderNo());
if (existingOrder != null) {
throw new BusinessException(ErrorCode.BUSINESS_ERROR, "订单编号已存在: " + orders.getOrderNo());
}
// 设置默认值
if (orders.getOrderStatus() == null) {
orders.setOrderStatus(0); // 默认为待支付状态
}
if (orders.getCreatedAt() == null) {
orders.setCreatedAt(new Date());
}
int result = ordersMapper.insert(orders);
if (result <= 0) {
throw new BusinessException(ErrorCode.BUSINESS_ERROR, "创建订单失败");
}
return ResultUtils.success(true);
} catch (BusinessException e) {
throw e;
} catch (Exception e) {
logger.error("创建订单失败: {}", e.getMessage(), e);
throw new BusinessException(ErrorCode.DATABASE_ERROR, "创建订单失败: " + e.getMessage(), e);
}
}
@Override
public Result<Boolean> updateOrder(Orders orders) {
// TODO Auto-generated method stub
throw new UnsupportedOperationException("Unimplemented method 'updateOrder'");
// 参数校验
if (orders == null) {
throw new BusinessException(ErrorCode.MISSING_PARAM, "订单信息不能为空");
}
if (orders.getId() == null) {
throw new BusinessException(ErrorCode.MISSING_PARAM, "订单ID不能为空");
}
try {
// 检查订单是否存在
Orders existingOrder = ordersMapper.selectById(orders.getId());
if (existingOrder == null) {
throw new BusinessException(ErrorCode.ORDER_NOT_FOUND, "订单不存在");
}
// 更新时间戳
orders.setUpdatedAt(new Date());
int result = ordersMapper.updateById(orders);
if (result <= 0) {
throw new BusinessException(ErrorCode.BUSINESS_ERROR, "更新订单失败");
}
return ResultUtils.success(true);
} catch (BusinessException e) {
throw e;
} catch (Exception e) {
logger.error("更新订单失败: {}", e.getMessage(), e);
throw new BusinessException(ErrorCode.DATABASE_ERROR, "更新订单失败: " + e.getMessage(), e);
}
}
@Override
public Result<Boolean> deleteOrder(Long id) {
// TODO Auto-generated method stub
throw new UnsupportedOperationException("Unimplemented method 'deleteOrder'");
// 参数校验
if (id == null) {
throw new BusinessException(ErrorCode.MISSING_PARAM, "订单ID不能为空");
}
try {
// 检查订单是否存在
Orders orders = ordersMapper.selectById(id);
if (orders == null) {
throw new BusinessException(ErrorCode.ORDER_NOT_FOUND, "订单不存在");
}
int result = ordersMapper.deleteById(id);
if (result <= 0) {
throw new BusinessException(ErrorCode.BUSINESS_ERROR, "删除订单失败");
}
return ResultUtils.success(true);
} catch (BusinessException e) {
throw e;
} catch (Exception e) {
logger.error("删除订单失败: {}", e.getMessage(), e);
throw new BusinessException(ErrorCode.DATABASE_ERROR, "删除订单失败: " + e.getMessage(), e);
}
}
@Override
public Result<Orders> getOrderById(Long id) {
// TODO Auto-generated method stub
throw new UnsupportedOperationException("Unimplemented method 'getOrderById'");
// 参数校验
if (id == null) {
throw new BusinessException(ErrorCode.MISSING_PARAM, "订单ID不能为空");
}
try {
Orders orders = ordersMapper.selectById(id);
if (orders == null) {
throw new BusinessException(ErrorCode.ORDER_NOT_FOUND, "订单不存在");
}
return ResultUtils.success(orders);
} catch (BusinessException e) {
throw e;
} catch (Exception e) {
logger.error("查询订单失败: {}", e.getMessage(), e);
throw new BusinessException(ErrorCode.DATABASE_ERROR, "查询订单失败: " + e.getMessage(), e);
}
}
@Override
public Result<List<Orders>> listOrdersByPage(int page, int size) {
// TODO Auto-generated method stub
throw new UnsupportedOperationException("Unimplemented method 'listOrdersByPage'");
// 参数校验
if (page < 1) {
throw new BusinessException(ErrorCode.INVALID_PARAM, "页码不能小于1");
}
if (size < 1 || size > 100) {
throw new BusinessException(ErrorCode.INVALID_PARAM, "每页大小必须在1-100之间");
}
try {
// 简单分页实现
int offset = (page - 1) * size;
List<Orders> ordersList = ordersMapper.selectList(
new QueryWrapper<Orders>().last("LIMIT " + offset + ", " + size).orderByDesc("create_time")
);
return ResultUtils.success(ordersList);
} catch (BusinessException e) {
throw e;
} catch (Exception e) {
logger.error("分页查询订单失败: {}", e.getMessage(), e);
throw new BusinessException(ErrorCode.DATABASE_ERROR, "分页查询订单失败: " + e.getMessage(), e);
}
}
@Override
public Result<List<Orders>> getOrdersByShopId(Long shopId) {
// TODO Auto-generated method stub
throw new UnsupportedOperationException("Unimplemented method 'getOrdersByShopId'");
// 参数校验
if (shopId == null) {
throw new BusinessException(ErrorCode.MISSING_PARAM, "店铺ID不能为空");
}
try {
List<Orders> ordersList = ordersMapper.selectList(
new QueryWrapper<Orders>().eq("shop_id", shopId).orderByDesc("create_time")
);
return ResultUtils.success(ordersList);
} catch (BusinessException e) {
throw e;
} catch (Exception e) {
logger.error("查询店铺订单失败: {}", e.getMessage(), e);
throw new BusinessException(ErrorCode.DATABASE_ERROR, "查询店铺订单失败: " + e.getMessage(), e);
}
}
@Override
public Result<Boolean> updateOrderStatus(Long orderId, Integer status) {
// TODO Auto-generated method stub
throw new UnsupportedOperationException("Unimplemented method 'updateOrderStatus'");
// 参数校验
if (orderId == null) {
throw new BusinessException(ErrorCode.MISSING_PARAM, "订单ID不能为空");
}
if (status == null) {
throw new BusinessException(ErrorCode.MISSING_PARAM, "订单状态不能为空");
}
try {
// 检查订单是否存在
Orders orders = ordersMapper.selectById(orderId);
if (orders == null) {
throw new BusinessException(ErrorCode.ORDER_NOT_FOUND, "订单不存在");
}
// 检查状态是否合法假设状态值为0-5
if (status < 0 || status > 5) {
throw new BusinessException(ErrorCode.INVALID_PARAM, "无效的订单状态值");
}
// 更新状态
Orders updateOrder = new Orders();
updateOrder.setId(orderId);
updateOrder.setOrderStatus(status);
updateOrder.setUpdatedAt(new Date());
int result = ordersMapper.updateById(updateOrder);
if (result <= 0) {
throw new BusinessException(ErrorCode.BUSINESS_ERROR, "更新订单状态失败");
}
return ResultUtils.success(true);
} catch (BusinessException e) {
throw e;
} catch (Exception e) {
logger.error("更新订单状态失败: {}", e.getMessage(), e);
throw new BusinessException(ErrorCode.DATABASE_ERROR, "更新订单状态失败: " + e.getMessage(), e);
}
}
@Override
public Result<List<Orders>> getOrdersByStatus(Integer status) {
// TODO Auto-generated method stub
throw new UnsupportedOperationException("Unimplemented method 'getOrdersByStatus'");
// 参数校验
if (status == null) {
throw new BusinessException(ErrorCode.MISSING_PARAM, "订单状态不能为空");
}
try {
List<Orders> ordersList = ordersMapper.selectList(
new QueryWrapper<Orders>().eq("status", status).orderByDesc("create_time")
);
return ResultUtils.success(ordersList);
} catch (BusinessException e) {
throw e;
} catch (Exception e) {
logger.error("查询订单失败: {}", e.getMessage(), e);
throw new BusinessException(ErrorCode.DATABASE_ERROR, "查询订单失败: " + e.getMessage(), e);
}
}
}

View File

@@ -0,0 +1,215 @@
package com.qf.backend.service.impl;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qf.backend.entity.Payments;
import com.qf.backend.exception.BusinessException;
import com.qf.backend.exception.ErrorCode;
import com.qf.backend.mapper.PaymentsMapper;
import com.qf.backend.service.PaymentsService;
import com.qf.backend.util.ValidateUtil;
/**
* 支付服务实现类
*/
@Service
public class PaymentsServiceImpl extends ServiceImpl<PaymentsMapper, Payments> implements PaymentsService {
@Autowired
private PaymentsMapper paymentsMapper;
@Override
public Payments getPaymentByOrderId(Long orderId) {
if (ValidateUtil.isEmpty(orderId)) {
throw new BusinessException(ErrorCode.MISSING_PARAM, "订单ID不能为空");
}
try {
return paymentsMapper.selectOne(
new QueryWrapper<Payments>().eq("order_id", orderId));
} catch (BusinessException e) {
throw e;
} catch (Exception e) {
throw new BusinessException(ErrorCode.DATABASE_ERROR, "查询支付记录失败", e);
}
}
@Override
public Payments getPaymentByTransactionId(String transactionId) {
if (ValidateUtil.isEmpty(transactionId)) {
throw new BusinessException(ErrorCode.MISSING_PARAM, "支付流水号不能为空");
}
try {
return paymentsMapper.selectOne(
new QueryWrapper<Payments>().eq("transaction_id", transactionId));
} catch (BusinessException e) {
throw e;
} catch (Exception e) {
throw new BusinessException(ErrorCode.DATABASE_ERROR, "查询支付记录失败", e);
}
}
@Override
public boolean createPayment(Payments payments) {
if (ValidateUtil.isEmpty(payments)) {
throw new BusinessException(ErrorCode.MISSING_PARAM, "支付信息不能为空");
}
if (ValidateUtil.isEmpty(payments.getOrderId())) {
throw new BusinessException(ErrorCode.MISSING_PARAM, "订单ID不能为空");
}
if (payments.getAmount() == null) {
throw new BusinessException(ErrorCode.MISSING_PARAM, "支付金额不能为空");
}
if (ValidateUtil.isEmpty(payments.getPaymentMethod())) {
throw new BusinessException(ErrorCode.MISSING_PARAM, "支付方式不能为空");
}
try {
int result = paymentsMapper.insert(payments);
return result > 0;
} catch (BusinessException e) {
throw e;
} catch (Exception e) {
throw new BusinessException(ErrorCode.DATABASE_ERROR, "创建支付记录失败", e);
}
}
@Override
public boolean updatePayment(Payments payments) {
if (ValidateUtil.isEmpty(payments)) {
throw new BusinessException(ErrorCode.MISSING_PARAM, "支付信息不能为空");
}
if (ValidateUtil.isEmpty(payments.getId())) {
throw new BusinessException(ErrorCode.MISSING_PARAM, "支付ID不能为空");
}
try {
// 检查支付记录是否存在
Payments existing = paymentsMapper.selectById(payments.getId());
if (existing == null) {
throw new BusinessException(ErrorCode.NOT_FOUND, "支付记录不存在");
}
int result = paymentsMapper.updateById(payments);
return result > 0;
} catch (BusinessException e) {
throw e;
} catch (Exception e) {
throw new BusinessException(ErrorCode.DATABASE_ERROR, "更新支付记录失败", e);
}
}
@Override
public boolean deletePayment(Long id) {
if (ValidateUtil.isEmpty(id)) {
throw new BusinessException(ErrorCode.MISSING_PARAM, "支付ID不能为空");
}
try {
// 检查支付记录是否存在
Payments existing = paymentsMapper.selectById(id);
if (existing == null) {
throw new BusinessException(ErrorCode.NOT_FOUND, "支付记录不存在");
}
int result = paymentsMapper.deleteById(id);
return result > 0;
} catch (BusinessException e) {
throw e;
} catch (Exception e) {
throw new BusinessException(ErrorCode.DATABASE_ERROR, "删除支付记录失败", e);
}
}
@Override
public Payments getPaymentById(Long id) {
if (ValidateUtil.isEmpty(id)) {
throw new BusinessException(ErrorCode.MISSING_PARAM, "支付ID不能为空");
}
try {
Payments payment = paymentsMapper.selectById(id);
if (payment == null) {
throw new BusinessException(ErrorCode.NOT_FOUND, "支付记录不存在");
}
return payment;
} catch (BusinessException e) {
throw e;
} catch (Exception e) {
throw new BusinessException(ErrorCode.DATABASE_ERROR, "查询支付记录失败", e);
}
}
@Override
public List<Payments> getPaymentsByUserId(Long userId) {
if (ValidateUtil.isEmpty(userId)) {
throw new BusinessException(ErrorCode.MISSING_PARAM, "用户ID不能为空");
}
try {
return paymentsMapper.selectList(
new QueryWrapper<Payments>().eq("user_id", userId));
} catch (BusinessException e) {
throw e;
} catch (Exception e) {
throw new BusinessException(ErrorCode.DATABASE_ERROR, "查询支付记录失败", e);
}
}
@Override
public List<Payments> getPaymentsByStatus(Integer status) {
if (ValidateUtil.isEmpty(status)) {
throw new BusinessException(ErrorCode.MISSING_PARAM, "支付状态不能为空");
}
try {
return paymentsMapper.selectList(
new QueryWrapper<Payments>().eq("status", status));
} catch (BusinessException e) {
throw e;
} catch (Exception e) {
throw new BusinessException(ErrorCode.DATABASE_ERROR, "查询支付记录失败", e);
}
}
@Override
public boolean updatePaymentStatus(Long paymentId, Integer status) {
if (ValidateUtil.isEmpty(paymentId)) {
throw new BusinessException(ErrorCode.MISSING_PARAM, "支付ID不能为空");
}
if (ValidateUtil.isEmpty(status)) {
throw new BusinessException(ErrorCode.MISSING_PARAM, "支付状态不能为空");
}
try {
// 检查支付记录是否存在
Payments existing = paymentsMapper.selectById(paymentId);
if (existing == null) {
throw new BusinessException(ErrorCode.NOT_FOUND, "支付记录不存在");
}
// 更新状态
existing.setPaymentStatus(status);
int result = paymentsMapper.updateById(existing);
return result > 0;
} catch (BusinessException e) {
throw e;
} catch (Exception e) {
throw new BusinessException(ErrorCode.DATABASE_ERROR, "更新支付状态失败", e);
}
}
@Override
public List<Payments> listPaymentsByPage(int page, int size) {
if (page < 1) {
throw new BusinessException(ErrorCode.INVALID_PARAM, "页码不能小于1");
}
if (size < 1 || size > 100) {
throw new BusinessException(ErrorCode.INVALID_PARAM, "每页数量必须在1-100之间");
}
try {
Page<Payments> paymentPage = new Page<>(page, size);
Page<Payments> resultPage = paymentsMapper.selectPage(paymentPage, null);
return resultPage.getRecords();
} catch (BusinessException e) {
throw e;
} catch (Exception e) {
throw new BusinessException(ErrorCode.DATABASE_ERROR, "分页查询支付记录失败", e);
}
}
}

View File

@@ -0,0 +1,275 @@
package com.qf.backend.service.impl;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qf.backend.dto.Result;
import com.qf.backend.entity.Permissions;
import com.qf.backend.exception.BusinessException;
import com.qf.backend.exception.ErrorCode;
import com.qf.backend.mapper.PermissionsMapper;
import com.qf.backend.service.PermissionsService;
import com.qf.backend.util.ResultUtils;
import com.qf.backend.util.ValidateUtil;
@Service
public class PermissionsServiceImpl extends ServiceImpl<PermissionsMapper, Permissions> implements PermissionsService {
private static final Logger logger = LoggerFactory.getLogger(PermissionsServiceImpl.class);
@Autowired
private PermissionsMapper permissionsMapper;
// 根据权限编码查询权限
@Override
public Result<Permissions> getPermissionByCode(String permissionCode) {
logger.info("根据权限编码查询权限: {}", permissionCode);
try {
if (ValidateUtil.isEmpty(permissionCode)) {
throw new BusinessException(ErrorCode.INVALID_PARAM, "权限编码不能为空");
}
QueryWrapper<Permissions> queryWrapper = new QueryWrapper<Permissions>().eq("permission_code", permissionCode);
Permissions permission = permissionsMapper.selectOne(queryWrapper);
if (permission == null) {
throw new BusinessException(ErrorCode.NOT_FOUND, "权限不存在: " + permissionCode);
}
return ResultUtils.success(permission);
} catch (BusinessException e) {
throw e;
} catch (Exception e) {
logger.error("查询权限失败: {}", e.getMessage(), e);
throw new BusinessException(ErrorCode.DATABASE_ERROR, "查询权限失败: " + e.getMessage(), e);
}
}
// 创建权限
@Override
public Result<Boolean> createPermission(Permissions permissions) {
logger.info("创建权限: 权限对象");
try {
// 使用ValidateUtil进行实体验证
ValidateUtil.validateEntity(permissions, "permissionCode", "permissionName", "permissionType");
int result = permissionsMapper.insert(permissions);
if (result <= 0) {
throw new BusinessException(ErrorCode.BUSINESS_ERROR, "创建权限失败");
}
logger.info("权限创建成功");
return ResultUtils.success(true);
} catch (IllegalArgumentException e) {
// 转换为业务异常
throw new BusinessException(ErrorCode.INVALID_PARAM, e.getMessage());
} catch (IllegalAccessException e) {
logger.error("验证权限信息失败: {}", e.getMessage(), e);
throw new BusinessException(ErrorCode.BUSINESS_ERROR, "验证权限信息失败: " + e.getMessage(), e);
} catch (BusinessException e) {
throw e;
} catch (Exception e) {
logger.error("创建权限失败: {}", e.getMessage(), e);
throw new BusinessException(ErrorCode.DATABASE_ERROR, "创建权限失败: " + e.getMessage(), e);
}
}
// 更新权限信息
@Override
public Result<Boolean> updatePermission(Permissions permissions) {
logger.info("更新权限信息: 权限ID = {}", permissions.getId());
try {
if (permissions == null || permissions.getId() == null) {
throw new BusinessException(ErrorCode.MISSING_PARAM, "权限信息或权限ID不能为空");
}
// 检查权限是否存在
Permissions existingPermission = getPermissionByIdAndCheckExist(permissions.getId());
if (existingPermission == null) {
throw new BusinessException(ErrorCode.NOT_FOUND, "权限不存在");
}
// 使用ValidateUtil进行实体验证
ValidateUtil.validateEntity(permissions, "permissionCode", "permissionName", "permissionType");
// 更新权限信息
int result = permissionsMapper.updateById(permissions);
if (result <= 0) {
throw new BusinessException(ErrorCode.BUSINESS_ERROR, "更新权限信息失败");
}
logger.info("权限信息更新成功: 权限ID = {}", permissions.getId());
return ResultUtils.success(true);
} catch (IllegalArgumentException e) {
// 转换为业务异常
throw new BusinessException(ErrorCode.INVALID_PARAM, e.getMessage());
} catch (IllegalAccessException e) {
logger.error("验证权限信息失败: {}", e.getMessage(), e);
throw new BusinessException(ErrorCode.BUSINESS_ERROR, "验证权限信息失败: " + e.getMessage(), e);
} catch (BusinessException e) {
throw e;
} catch (Exception e) {
logger.error("更新权限信息失败: {}", e.getMessage(), e);
throw new BusinessException(ErrorCode.DATABASE_ERROR, "更新权限信息失败: " + e.getMessage(), e);
}
}
// 删除权限
@Override
public Result<Boolean> deletePermission(Long id) {
logger.info("删除权限: 权限ID = {}", id);
try {
if (id == null) {
throw new BusinessException(ErrorCode.MISSING_PARAM, "权限ID不能为空");
}
// 检查权限是否存在
Permissions permission = getPermissionByIdAndCheckExist(id);
if (permission == null) {
throw new BusinessException(ErrorCode.NOT_FOUND, "权限不存在");
}
int result = permissionsMapper.deleteById(id);
if (result <= 0) {
throw new BusinessException(ErrorCode.BUSINESS_ERROR, "删除权限失败");
}
logger.info("权限删除成功: 权限ID = {}", id);
return ResultUtils.success(true);
} catch (BusinessException e) {
throw e;
} catch (Exception e) {
logger.error("删除权限失败: {}", e.getMessage(), e);
throw new BusinessException(ErrorCode.DATABASE_ERROR, "删除权限失败: " + e.getMessage(), e);
}
}
// 查询所有权限
@Override
public Result<List<Permissions>> listAllPermissions() {
logger.info("查询所有权限列表");
try {
List<Permissions> permissionsList = permissionsMapper.selectList(null);
logger.info("查询到 {} 个权限", permissionsList.size());
return ResultUtils.success(permissionsList);
} catch (Exception e) {
logger.error("查询权限列表失败: {}", e.getMessage(), e);
throw new BusinessException(ErrorCode.DATABASE_ERROR, "查询权限列表失败: " + e.getMessage(), e);
}
}
// 根据权限ID查询权限
@Override
public Result<Permissions> getPermissionById(Long id) {
logger.info("根据ID查询权限: 权限ID = {}", id);
try {
if (id == null) {
throw new BusinessException(ErrorCode.MISSING_PARAM, "权限ID不能为空");
}
Permissions permission = getPermissionByIdAndCheckExist(id);
if (permission == null) {
throw new BusinessException(ErrorCode.NOT_FOUND, "权限不存在");
}
return ResultUtils.success(permission);
} catch (BusinessException e) {
throw e;
} catch (Exception e) {
logger.error("查询权限失败: {}", e.getMessage(), e);
throw new BusinessException(ErrorCode.DATABASE_ERROR, "查询权限失败: " + e.getMessage(), e);
}
}
// 批量删除权限
@Override
public Result<Boolean> batchDeletePermissions(List<Long> ids) {
logger.info("批量删除权限: 权限ID列表 = {}", ids);
try {
if (ids == null || ids.isEmpty()) {
throw new BusinessException(ErrorCode.MISSING_PARAM, "权限ID列表不能为空");
}
int result = permissionsMapper.deleteBatchIds(ids);
if (result <= 0) {
throw new BusinessException(ErrorCode.BUSINESS_ERROR, "批量删除权限失败");
}
logger.info("批量删除权限成功: 删除了 {} 个权限", result);
return ResultUtils.success(true);
} catch (BusinessException e) {
throw e;
} catch (Exception e) {
logger.error("批量删除权限失败: {}", e.getMessage(), e);
throw new BusinessException(ErrorCode.DATABASE_ERROR, "批量删除权限失败: " + e.getMessage(), e);
}
}
// 根据菜单ID查询权限
@Override
public Result<List<Permissions>> listPermissionsByMenuId(Long menuId) {
logger.info("根据菜单ID查询权限: 菜单ID = {}", menuId);
try {
if (menuId == null) {
throw new BusinessException(ErrorCode.MISSING_PARAM, "菜单ID不能为空");
}
QueryWrapper<Permissions> queryWrapper = new QueryWrapper<Permissions>().eq("menu_id", menuId);
List<Permissions> permissionsList = permissionsMapper.selectList(queryWrapper);
logger.info("查询到 {} 个权限", permissionsList.size());
return ResultUtils.success(permissionsList);
} catch (BusinessException e) {
throw e;
} catch (Exception e) {
logger.error("根据菜单ID查询权限失败: {}", e.getMessage(), e);
throw new BusinessException(ErrorCode.DATABASE_ERROR, "根据菜单ID查询权限失败: " + e.getMessage(), e);
}
}
// 根据权限类型查询权限
@Override
public Result<List<Permissions>> listPermissionsByType(String permissionType) {
logger.info("根据权限类型查询权限: 权限类型 = {}", permissionType);
try {
if (ValidateUtil.isEmpty(permissionType)) {
throw new BusinessException(ErrorCode.MISSING_PARAM, "权限类型不能为空");
}
QueryWrapper<Permissions> queryWrapper = new QueryWrapper<Permissions>().eq("permission_type", permissionType);
List<Permissions> permissionsList = permissionsMapper.selectList(queryWrapper);
logger.info("查询到 {} 个权限", permissionsList.size());
return ResultUtils.success(permissionsList);
} catch (BusinessException e) {
throw e;
} catch (Exception e) {
logger.error("根据权限类型查询权限失败: {}", e.getMessage(), e);
throw new BusinessException(ErrorCode.DATABASE_ERROR, "根据权限类型查询权限失败: " + e.getMessage(), e);
}
}
/**
* 根据权限ID查询权限并检查是否存在
* @param id 权限ID
* @return 权限对象如果权限不存在则返回null
*/
private Permissions getPermissionByIdAndCheckExist(Long id) {
if (id == null) {
return null;
}
QueryWrapper<Permissions> queryWrapper = new QueryWrapper<Permissions>().eq("id", id);
return permissionsMapper.selectOne(queryWrapper);
}
}

View File

@@ -0,0 +1,213 @@
package com.qf.backend.service.impl;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qf.backend.dto.Result;
import com.qf.backend.entity.ProductAttributeValues;
import com.qf.backend.exception.BusinessException;
import com.qf.backend.exception.ErrorCode;
import com.qf.backend.mapper.ProductAttributeValuesMapper;
import com.qf.backend.service.ProductAttributeValuesService;
import com.qf.backend.util.ResultUtils;
import com.qf.backend.util.ValidateUtil;
/**
* 商品属性值服务实现类
*/
@Service
public class ProductAttributeValuesServiceImpl extends ServiceImpl<ProductAttributeValuesMapper, ProductAttributeValues> implements ProductAttributeValuesService {
@Autowired
private ProductAttributeValuesMapper productAttributeValuesMapper;
@Override
public Result<List<ProductAttributeValues>> getAttributeValuesByProductId(Long productId) {
if (ValidateUtil.isEmpty(productId)) {
throw new BusinessException(ErrorCode.MISSING_PARAM, "商品ID不能为空");
}
try {
List<ProductAttributeValues> attributeValues = productAttributeValuesMapper.selectList(
new QueryWrapper<ProductAttributeValues>().eq("product_id", productId));
return ResultUtils.success(attributeValues);
} catch (BusinessException e) {
throw e;
} catch (Exception e) {
throw new BusinessException(ErrorCode.DATABASE_ERROR, "查询商品属性值失败", e);
}
}
@Override
public Result<List<ProductAttributeValues>> getAttributeValuesByAttributeId(Long attributeId) {
if (ValidateUtil.isEmpty(attributeId)) {
throw new BusinessException(ErrorCode.MISSING_PARAM, "属性ID不能为空");
}
try {
List<ProductAttributeValues> attributeValues = productAttributeValuesMapper.selectList(
new QueryWrapper<ProductAttributeValues>().eq("attribute_id", attributeId));
return ResultUtils.success(attributeValues);
} catch (BusinessException e) {
throw e;
} catch (Exception e) {
throw new BusinessException(ErrorCode.DATABASE_ERROR, "查询属性值失败", e);
}
}
@Override
public Result<Boolean> createAttributeValue(ProductAttributeValues productAttributeValues) {
if (ValidateUtil.isEmpty(productAttributeValues)) {
throw new BusinessException(ErrorCode.MISSING_PARAM, "属性值信息不能为空");
}
if (ValidateUtil.isEmpty(productAttributeValues.getProductId())) {
throw new BusinessException(ErrorCode.MISSING_PARAM, "商品ID不能为空");
}
if (ValidateUtil.isEmpty(productAttributeValues.getAttributeId())) {
throw new BusinessException(ErrorCode.MISSING_PARAM, "属性ID不能为空");
}
if (ValidateUtil.isEmpty(productAttributeValues.getAttributeValue())) {
throw new BusinessException(ErrorCode.MISSING_PARAM, "属性值不能为空");
}
try {
int result = productAttributeValuesMapper.insert(productAttributeValues);
return ResultUtils.success(result > 0);
} catch (BusinessException e) {
throw e;
} catch (Exception e) {
throw new BusinessException(ErrorCode.DATABASE_ERROR, "创建属性值失败", e);
}
}
@Override
public Result<Boolean> updateAttributeValue(ProductAttributeValues productAttributeValues) {
if (ValidateUtil.isEmpty(productAttributeValues)) {
throw new BusinessException(ErrorCode.MISSING_PARAM, "属性值信息不能为空");
}
if (ValidateUtil.isEmpty(productAttributeValues.getId())) {
throw new BusinessException(ErrorCode.MISSING_PARAM, "属性值ID不能为空");
}
if (ValidateUtil.isEmpty(productAttributeValues.getAttributeValue())) {
throw new BusinessException(ErrorCode.MISSING_PARAM, "属性值不能为空");
}
try {
// 检查属性值是否存在
ProductAttributeValues existing = productAttributeValuesMapper.selectById(productAttributeValues.getId());
if (existing == null) {
throw new BusinessException(ErrorCode.NOT_FOUND, "属性值不存在");
}
int result = productAttributeValuesMapper.updateById(productAttributeValues);
return ResultUtils.success(result > 0);
} catch (BusinessException e) {
throw e;
} catch (Exception e) {
throw new BusinessException(ErrorCode.DATABASE_ERROR, "更新属性值失败", e);
}
}
@Override
public Result<Boolean> deleteAttributeValue(Long id) {
if (ValidateUtil.isEmpty(id)) {
throw new BusinessException(ErrorCode.MISSING_PARAM, "属性值ID不能为空");
}
try {
// 检查属性值是否存在
ProductAttributeValues existing = productAttributeValuesMapper.selectById(id);
if (existing == null) {
throw new BusinessException(ErrorCode.NOT_FOUND, "属性值不存在");
}
int result = productAttributeValuesMapper.deleteById(id);
return ResultUtils.success(result > 0);
} catch (BusinessException e) {
throw e;
} catch (Exception e) {
throw new BusinessException(ErrorCode.DATABASE_ERROR, "删除属性值失败", e);
}
}
@Override
public Result<ProductAttributeValues> getAttributeValueById(Long id) {
if (ValidateUtil.isEmpty(id)) {
throw new BusinessException(ErrorCode.MISSING_PARAM, "属性值ID不能为空");
}
try {
ProductAttributeValues attributeValue = productAttributeValuesMapper.selectById(id);
if (attributeValue == null) {
throw new BusinessException(ErrorCode.NOT_FOUND, "属性值不存在");
}
return ResultUtils.success(attributeValue);
} catch (BusinessException e) {
throw e;
} catch (Exception e) {
throw new BusinessException(ErrorCode.DATABASE_ERROR, "查询属性值失败", e);
}
}
@Override
public Result<Boolean> batchCreateAttributeValues(List<ProductAttributeValues> attributeValues) {
if (ValidateUtil.isEmpty(attributeValues)) {
throw new BusinessException(ErrorCode.MISSING_PARAM, "属性值列表不能为空");
}
if (attributeValues.isEmpty()) {
throw new BusinessException(ErrorCode.MISSING_PARAM, "属性值列表不能为空");
}
try {
for (ProductAttributeValues attributeValue : attributeValues) {
if (ValidateUtil.isEmpty(attributeValue.getProductId())) {
throw new BusinessException(ErrorCode.INVALID_PARAM, "属性值列表中存在商品ID为空的记录");
}
if (ValidateUtil.isEmpty(attributeValue.getAttributeId())) {
throw new BusinessException(ErrorCode.INVALID_PARAM, "属性值列表中存在属性ID为空的记录");
}
if (ValidateUtil.isEmpty(attributeValue.getAttributeValue())) {
throw new BusinessException(ErrorCode.INVALID_PARAM, "属性值列表中存在属性值为空的记录");
}
productAttributeValuesMapper.insert(attributeValue);
}
return ResultUtils.success(true);
} catch (BusinessException e) {
throw e;
} catch (Exception e) {
throw new BusinessException(ErrorCode.DATABASE_ERROR, "批量创建属性值失败", e);
}
}
@Override
public Result<ProductAttributeValues> getAttributeValueByProductAndAttribute(Long productId, Long attributeId) {
if (ValidateUtil.isEmpty(productId)) {
throw new BusinessException(ErrorCode.MISSING_PARAM, "商品ID不能为空");
}
if (ValidateUtil.isEmpty(attributeId)) {
throw new BusinessException(ErrorCode.MISSING_PARAM, "属性ID不能为空");
}
try {
ProductAttributeValues attributeValue = productAttributeValuesMapper.selectOne(
new QueryWrapper<ProductAttributeValues>()
.eq("product_id", productId)
.eq("attribute_id", attributeId));
return ResultUtils.success(attributeValue);
} catch (BusinessException e) {
throw e;
} catch (Exception e) {
throw new BusinessException(ErrorCode.DATABASE_ERROR, "查询商品属性值失败", e);
}
}
@Override
public Result<Boolean> deleteAttributeValuesByProductId(Long productId) {
if (ValidateUtil.isEmpty(productId)) {
throw new BusinessException(ErrorCode.MISSING_PARAM, "商品ID不能为空");
}
try {
int result = productAttributeValuesMapper.delete(
new QueryWrapper<ProductAttributeValues>().eq("product_id", productId));
return ResultUtils.success(result >= 0);
} catch (BusinessException e) {
throw e;
} catch (Exception e) {
throw new BusinessException(ErrorCode.DATABASE_ERROR, "删除商品属性值失败", e);
}
}
}

View File

@@ -0,0 +1,200 @@
package com.qf.backend.service.impl;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qf.backend.dto.Result;
import com.qf.backend.entity.ProductAttributes;
import com.qf.backend.exception.BusinessException;
import com.qf.backend.exception.ErrorCode;
import com.qf.backend.mapper.ProductAttributesMapper;
import com.qf.backend.service.ProductAttributesService;
import com.qf.backend.util.ResultUtils;
import com.qf.backend.util.ValidateUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
/**
* 商品属性服务实现类
*/
@Service
public class ProductAttributesServiceImpl extends ServiceImpl<ProductAttributesMapper, ProductAttributes> implements ProductAttributesService {
@Autowired
private ProductAttributesMapper productAttributesMapper;
@Override
public Result<List<ProductAttributes>> getAttributesByCategoryId(Long categoryId) {
if (ValidateUtil.isEmpty(categoryId)) {
throw new BusinessException(ErrorCode.MISSING_PARAM, "分类ID不能为空");
}
try {
List<ProductAttributes> attributes = productAttributesMapper.selectList(
new QueryWrapper<ProductAttributes>().eq("category_id", categoryId));
return ResultUtils.success(attributes);
} catch (BusinessException e) {
throw e;
} catch (Exception e) {
throw new BusinessException(ErrorCode.DATABASE_ERROR, "查询商品属性失败", e);
}
}
@Override
public Result<List<ProductAttributes>> getAttributesByName(String attributeName) {
if (ValidateUtil.isEmpty(attributeName)) {
throw new BusinessException(ErrorCode.MISSING_PARAM, "属性名称不能为空");
}
try {
List<ProductAttributes> attributes = productAttributesMapper.selectList(
new QueryWrapper<ProductAttributes>().like("attribute_name", attributeName));
return ResultUtils.success(attributes);
} catch (BusinessException e) {
throw e;
} catch (Exception e) {
throw new BusinessException(ErrorCode.DATABASE_ERROR, "查询商品属性失败", e);
}
}
@Override
public Result<Boolean> createAttribute(ProductAttributes productAttributes) {
if (ValidateUtil.isEmpty(productAttributes)) {
throw new BusinessException(ErrorCode.MISSING_PARAM, "属性信息不能为空");
}
if (ValidateUtil.isEmpty(productAttributes.getAttributeName())) {
throw new BusinessException(ErrorCode.MISSING_PARAM, "属性名称不能为空");
}
if (ValidateUtil.isEmpty(productAttributes.getCategoryId())) {
throw new BusinessException(ErrorCode.MISSING_PARAM, "分类ID不能为空");
}
try {
int result = productAttributesMapper.insert(productAttributes);
return ResultUtils.success(result > 0);
} catch (BusinessException e) {
throw e;
} catch (Exception e) {
throw new BusinessException(ErrorCode.DATABASE_ERROR, "创建商品属性失败", e);
}
}
@Override
public Result<Boolean> updateAttribute(ProductAttributes productAttributes) {
if (ValidateUtil.isEmpty(productAttributes)) {
throw new BusinessException(ErrorCode.MISSING_PARAM, "属性信息不能为空");
}
if (ValidateUtil.isEmpty(productAttributes.getId())) {
throw new BusinessException(ErrorCode.MISSING_PARAM, "属性ID不能为空");
}
if (ValidateUtil.isEmpty(productAttributes.getAttributeName())) {
throw new BusinessException(ErrorCode.MISSING_PARAM, "属性名称不能为空");
}
try {
// 检查属性是否存在
ProductAttributes existing = productAttributesMapper.selectById(productAttributes.getId());
if (existing == null) {
throw new BusinessException(ErrorCode.NOT_FOUND, "属性不存在");
}
int result = productAttributesMapper.updateById(productAttributes);
return ResultUtils.success(result > 0);
} catch (BusinessException e) {
throw e;
} catch (Exception e) {
throw new BusinessException(ErrorCode.DATABASE_ERROR, "更新商品属性失败", e);
}
}
@Override
public Result<Boolean> deleteAttribute(Long id) {
if (ValidateUtil.isEmpty(id)) {
throw new BusinessException(ErrorCode.MISSING_PARAM, "属性ID不能为空");
}
try {
// 检查属性是否存在
ProductAttributes existing = productAttributesMapper.selectById(id);
if (existing == null) {
throw new BusinessException(ErrorCode.NOT_FOUND, "属性不存在");
}
int result = productAttributesMapper.deleteById(id);
return ResultUtils.success(result > 0);
} catch (BusinessException e) {
throw e;
} catch (Exception e) {
throw new BusinessException(ErrorCode.DATABASE_ERROR, "删除商品属性失败", e);
}
}
@Override
public Result<ProductAttributes> getAttributeById(Long id) {
if (ValidateUtil.isEmpty(id)) {
throw new BusinessException(ErrorCode.MISSING_PARAM, "属性ID不能为空");
}
try {
ProductAttributes attribute = productAttributesMapper.selectById(id);
if (attribute == null) {
throw new BusinessException(ErrorCode.NOT_FOUND, "属性不存在");
}
return ResultUtils.success(attribute);
} catch (BusinessException e) {
throw e;
} catch (Exception e) {
throw new BusinessException(ErrorCode.DATABASE_ERROR, "查询商品属性失败", e);
}
}
@Override
public Result<Boolean> batchDeleteAttributes(List<Long> ids) {
if (ValidateUtil.isEmpty(ids)) {
throw new BusinessException(ErrorCode.MISSING_PARAM, "属性ID列表不能为空");
}
if (ids.isEmpty()) {
throw new BusinessException(ErrorCode.MISSING_PARAM, "属性ID列表不能为空");
}
try {
// 检查所有属性是否存在
for (Long id : ids) {
if (ValidateUtil.isEmpty(id)) {
throw new BusinessException(ErrorCode.INVALID_PARAM, "属性ID列表中存在空值");
}
ProductAttributes existing = productAttributesMapper.selectById(id);
if (existing == null) {
throw new BusinessException(ErrorCode.NOT_FOUND, "属性ID为" + id + "的属性不存在");
}
}
int result = productAttributesMapper.deleteBatchIds(ids);
return ResultUtils.success(result > 0);
} catch (BusinessException e) {
throw e;
} catch (Exception e) {
throw new BusinessException(ErrorCode.DATABASE_ERROR, "批量删除商品属性失败", e);
}
}
@Override
public Result<List<ProductAttributes>> getAttributesByType(String attributeType) {
if (ValidateUtil.isEmpty(attributeType)) {
throw new BusinessException(ErrorCode.MISSING_PARAM, "属性类型不能为空");
}
try {
List<ProductAttributes> attributes = productAttributesMapper.selectList(
new QueryWrapper<ProductAttributes>().eq("attribute_type", attributeType));
return ResultUtils.success(attributes);
} catch (BusinessException e) {
throw e;
} catch (Exception e) {
throw new BusinessException(ErrorCode.DATABASE_ERROR, "查询商品属性失败", e);
}
}
@Override
public Result<List<ProductAttributes>> getAttributesBySearchable(Boolean searchable) {
try {
List<ProductAttributes> attributes = productAttributesMapper.selectList(
new QueryWrapper<ProductAttributes>().eq("searchable", searchable));
return ResultUtils.success(attributes);
} catch (BusinessException e) {
throw e;
} catch (Exception e) {
throw new BusinessException(ErrorCode.DATABASE_ERROR, "查询商品属性失败", e);
}
}
}

View File

@@ -0,0 +1,240 @@
package com.qf.backend.service.impl;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qf.backend.dto.Result;
import com.qf.backend.entity.ProductCategories;
import com.qf.backend.exception.BusinessException;
import com.qf.backend.exception.ErrorCode;
import com.qf.backend.mapper.ProductCategoriesMapper;
import com.qf.backend.service.ProductCategoriesService;
import com.qf.backend.util.ResultUtils;
import com.qf.backend.util.ValidateUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.List;
/**
* 商品分类服务实现类
*/
@Service
public class ProductCategoriesServiceImpl extends ServiceImpl<ProductCategoriesMapper, ProductCategories> implements ProductCategoriesService {
@Autowired
private ProductCategoriesMapper productCategoriesMapper;
@Override
public Result<ProductCategories> getCategoryByName(String categoryName) {
if (ValidateUtil.isEmpty(categoryName)) {
throw new BusinessException(ErrorCode.MISSING_PARAM, "分类名称不能为空");
}
try {
ProductCategories category = productCategoriesMapper.selectOne(
new QueryWrapper<ProductCategories>().eq("category_name", categoryName));
return ResultUtils.success(category);
} catch (BusinessException e) {
throw e;
} catch (Exception e) {
throw new BusinessException(ErrorCode.DATABASE_ERROR, "查询商品分类失败", e);
}
}
@Override
public Result<List<ProductCategories>> getSubCategoriesByParentId(Long parentId) {
try {
List<ProductCategories> categories = productCategoriesMapper.selectList(
new QueryWrapper<ProductCategories>().eq("parent_id", parentId));
return ResultUtils.success(categories);
} catch (BusinessException e) {
throw e;
} catch (Exception e) {
throw new BusinessException(ErrorCode.DATABASE_ERROR, "查询子分类失败", e);
}
}
@Override
public Result<Boolean> createCategory(ProductCategories productCategories) {
if (ValidateUtil.isEmpty(productCategories)) {
throw new BusinessException(ErrorCode.MISSING_PARAM, "分类信息不能为空");
}
if (ValidateUtil.isEmpty(productCategories.getCategoryName())) {
throw new BusinessException(ErrorCode.MISSING_PARAM, "分类名称不能为空");
}
try {
// 检查分类名称是否已存在
ProductCategories existing = productCategoriesMapper.selectOne(
new QueryWrapper<ProductCategories>().eq("category_name", productCategories.getCategoryName()));
if (existing != null) {
throw new BusinessException(ErrorCode.BUSINESS_ERROR, "分类名称已存在");
}
int result = productCategoriesMapper.insert(productCategories);
return ResultUtils.success(result > 0);
} catch (BusinessException e) {
throw e;
} catch (Exception e) {
throw new BusinessException(ErrorCode.DATABASE_ERROR, "创建商品分类失败", e);
}
}
@Override
public Result<Boolean> updateCategory(ProductCategories productCategories) {
if (ValidateUtil.isEmpty(productCategories)) {
throw new BusinessException(ErrorCode.MISSING_PARAM, "分类信息不能为空");
}
if (ValidateUtil.isEmpty(productCategories.getId())) {
throw new BusinessException(ErrorCode.MISSING_PARAM, "分类ID不能为空");
}
if (ValidateUtil.isEmpty(productCategories.getCategoryName())) {
throw new BusinessException(ErrorCode.MISSING_PARAM, "分类名称不能为空");
}
try {
// 检查分类是否存在
ProductCategories existing = productCategoriesMapper.selectById(productCategories.getId());
if (existing == null) {
throw new BusinessException(ErrorCode.NOT_FOUND, "分类不存在");
}
// 检查分类名称是否已存在(排除当前分类)
ProductCategories nameExists = productCategoriesMapper.selectOne(
new QueryWrapper<ProductCategories>()
.eq("category_name", productCategories.getCategoryName())
.ne("id", productCategories.getId()));
if (nameExists != null) {
throw new BusinessException(ErrorCode.BUSINESS_ERROR, "分类名称已存在");
}
int result = productCategoriesMapper.updateById(productCategories);
return ResultUtils.success(result > 0);
} catch (BusinessException e) {
throw e;
} catch (Exception e) {
throw new BusinessException(ErrorCode.DATABASE_ERROR, "更新商品分类失败", e);
}
}
@Override
public Result<Boolean> deleteCategory(Long id) {
if (ValidateUtil.isEmpty(id)) {
throw new BusinessException(ErrorCode.MISSING_PARAM, "分类ID不能为空");
}
try {
// 检查分类是否存在
ProductCategories existing = productCategoriesMapper.selectById(id);
if (existing == null) {
throw new BusinessException(ErrorCode.NOT_FOUND, "分类不存在");
}
// 检查是否有子分类
List<ProductCategories> subCategories = productCategoriesMapper.selectList(
new QueryWrapper<ProductCategories>().eq("parent_id", id));
if (!subCategories.isEmpty()) {
throw new BusinessException(ErrorCode.BUSINESS_ERROR, "该分类下存在子分类,无法删除");
}
int result = productCategoriesMapper.deleteById(id);
return ResultUtils.success(result > 0);
} catch (BusinessException e) {
throw e;
} catch (Exception e) {
throw new BusinessException(ErrorCode.DATABASE_ERROR, "删除商品分类失败", e);
}
}
@Override
public Result<List<ProductCategories>> listRootCategories() {
try {
List<ProductCategories> rootCategories = productCategoriesMapper.selectList(
new QueryWrapper<ProductCategories>().isNull("parent_id").or().eq("parent_id", 0));
return ResultUtils.success(rootCategories);
} catch (BusinessException e) {
throw e;
} catch (Exception e) {
throw new BusinessException(ErrorCode.DATABASE_ERROR, "查询根分类失败", e);
}
}
@Override
public Result<ProductCategories> getCategoryById(Long id) {
if (ValidateUtil.isEmpty(id)) {
throw new BusinessException(ErrorCode.MISSING_PARAM, "分类ID不能为空");
}
try {
ProductCategories category = productCategoriesMapper.selectById(id);
if (category == null) {
throw new BusinessException(ErrorCode.NOT_FOUND, "分类不存在");
}
return ResultUtils.success(category);
} catch (BusinessException e) {
throw e;
} catch (Exception e) {
throw new BusinessException(ErrorCode.DATABASE_ERROR, "查询商品分类失败", e);
}
}
@Override
public Result<Boolean> batchDeleteCategories(List<Long> ids) {
if (ValidateUtil.isEmpty(ids)) {
throw new BusinessException(ErrorCode.MISSING_PARAM, "分类ID列表不能为空");
}
if (ids.isEmpty()) {
throw new BusinessException(ErrorCode.MISSING_PARAM, "分类ID列表不能为空");
}
try {
// 检查所有分类是否存在以及是否有子分类
for (Long id : ids) {
if (ValidateUtil.isEmpty(id)) {
throw new BusinessException(ErrorCode.INVALID_PARAM, "分类ID列表中存在空值");
}
ProductCategories existing = productCategoriesMapper.selectById(id);
if (existing == null) {
throw new BusinessException(ErrorCode.NOT_FOUND, "分类ID为" + id + "的分类不存在");
}
// 检查是否有子分类
List<ProductCategories> subCategories = productCategoriesMapper.selectList(
new QueryWrapper<ProductCategories>().eq("parent_id", id));
if (!subCategories.isEmpty()) {
throw new BusinessException(ErrorCode.BUSINESS_ERROR, "分类ID为" + id + "的分类下存在子分类,无法删除");
}
}
int result = productCategoriesMapper.deleteBatchIds(ids);
return ResultUtils.success(result > 0);
} catch (BusinessException e) {
throw e;
} catch (Exception e) {
throw new BusinessException(ErrorCode.DATABASE_ERROR, "批量删除商品分类失败", e);
}
}
@Override
public Result<List<ProductCategories>> listAllCategoriesWithTree() {
try {
// 查询所有分类
List<ProductCategories> allCategories = productCategoriesMapper.selectList(null);
// 构建树形结构
List<ProductCategories> treeCategories = buildCategoryTree(allCategories, null);
return ResultUtils.success(treeCategories);
} catch (BusinessException e) {
throw e;
} catch (Exception e) {
throw new BusinessException(ErrorCode.DATABASE_ERROR, "查询商品分类树失败", e);
}
}
/**
* 构建分类树形结构
* @param allCategories 所有分类列表
* @param parentId 父分类ID
* @return 树形分类列表
*/
private List<ProductCategories> buildCategoryTree(List<ProductCategories> allCategories, Long parentId) {
List<ProductCategories> tree = new ArrayList<>();
for (ProductCategories category : allCategories) {
Long categoryParentId = category.getParentId();
if ((parentId == null && (categoryParentId == null || categoryParentId == 0)) || (parentId != null && parentId.equals(categoryParentId))) {
// 递归查找子分类
List<ProductCategories> children = buildCategoryTree(allCategories, category.getId());
category.setChildren(children);
tree.add(category);
}
}
return tree;
}
}

View File

@@ -0,0 +1,319 @@
package com.qf.backend.service.impl;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qf.backend.dto.Result;
import com.qf.backend.entity.ProductImages;
import com.qf.backend.exception.BusinessException;
import com.qf.backend.exception.ErrorCode;
import com.qf.backend.mapper.ProductImagesMapper;
import com.qf.backend.service.ProductImagesService;
import com.qf.backend.util.ResultUtils;
import com.qf.backend.util.ValidateUtil;
@Service
public class ProductImagesServiceImpl extends ServiceImpl<ProductImagesMapper, ProductImages> implements ProductImagesService {
private static final Logger logger = LoggerFactory.getLogger(ProductImagesServiceImpl.class);
@Autowired
private ProductImagesMapper productImagesMapper;
@Override
public Result<List<ProductImages>> getImagesByProductId(Long productId) {
logger.info("根据商品ID查询图片: {}", productId);
try {
if (productId == null) {
throw new BusinessException(ErrorCode.MISSING_PARAM, "商品ID不能为空");
}
List<ProductImages> images = productImagesMapper.selectList(new QueryWrapper<ProductImages>().eq("product_id", productId).orderByAsc("sort"));
logger.info("查询到 {} 张图片", images.size());
return ResultUtils.success(images);
} catch (BusinessException e) {
throw e;
} catch (Exception e) {
logger.error("查询图片失败: {}", e.getMessage(), e);
throw new BusinessException(ErrorCode.DATABASE_ERROR, "查询图片失败: " + e.getMessage(), e);
}
}
@Override
public Result<ProductImages> getMainImageByProductId(Long productId) {
logger.info("根据商品ID查询主图: {}", productId);
try {
if (productId == null) {
throw new BusinessException(ErrorCode.MISSING_PARAM, "商品ID不能为空");
}
ProductImages mainImage = productImagesMapper.selectOne(new QueryWrapper<ProductImages>().eq("product_id", productId).eq("is_main", 1));
if (mainImage == null) {
logger.warn("商品 {} 没有设置主图", productId);
return ResultUtils.success(null);
}
return ResultUtils.success(mainImage);
} catch (BusinessException e) {
throw e;
} catch (Exception e) {
logger.error("查询主图失败: {}", e.getMessage(), e);
throw new BusinessException(ErrorCode.DATABASE_ERROR, "查询主图失败: " + e.getMessage(), e);
}
}
@Override
public Result<Boolean> createImage(ProductImages productImages) {
logger.info("创建商品图片: 商品ID = {}", productImages.getProductId());
try {
// 使用ValidateUtil进行实体验证
ValidateUtil.validateEntity(productImages, "productId", "imageUrl");
// 检查是否设置了主图,如果设置了主图,则将其他图片设置为非主图
if (productImages.getIsMain() != null && productImages.getIsMain() == 1) {
// 将该商品的所有图片设置为非主图
productImagesMapper.update(null, new UpdateWrapper<ProductImages>().eq("product_id", productImages.getProductId()).set("is_main", 0));
}
int result = productImagesMapper.insert(productImages);
if (result <= 0) {
throw new BusinessException(ErrorCode.BUSINESS_ERROR, "创建商品图片失败");
}
logger.info("商品图片创建成功");
return ResultUtils.success(true);
} catch (IllegalArgumentException e) {
// 转换为业务异常
throw new BusinessException(ErrorCode.INVALID_PARAM, e.getMessage());
} catch (IllegalAccessException e) {
logger.error("验证图片信息失败: {}", e.getMessage(), e);
throw new BusinessException(ErrorCode.BUSINESS_ERROR, "验证图片信息失败: " + e.getMessage(), e);
} catch (BusinessException e) {
throw e;
} catch (Exception e) {
logger.error("创建商品图片失败: {}", e.getMessage(), e);
throw new BusinessException(ErrorCode.DATABASE_ERROR, "创建商品图片失败: " + e.getMessage(), e);
}
}
@Override
public Result<Boolean> updateImage(ProductImages productImages) {
logger.info("更新图片信息: 图片ID = {}", productImages.getId());
try {
if (productImages == null || productImages.getId() == null) {
throw new BusinessException(ErrorCode.MISSING_PARAM, "图片信息或图片ID不能为空");
}
// 检查图片是否存在
ProductImages existingImage = getImageByIdAndCheckExist(productImages.getId());
if (existingImage == null) {
throw new BusinessException(ErrorCode.NOT_FOUND, "图片不存在");
}
// 使用ValidateUtil进行实体验证
ValidateUtil.validateEntity(productImages, "productId", "imageUrl");
// 检查是否设置了主图,如果设置了主图,则将其他图片设置为非主图
if (productImages.getIsMain() != null && productImages.getIsMain() == 1) {
// 将该商品的所有图片设置为非主图
productImagesMapper.update(null, new UpdateWrapper<ProductImages>().eq("product_id", productImages.getProductId()).set("is_main", 0));
}
// 更新图片信息
int result = productImagesMapper.updateById(productImages);
if (result <= 0) {
throw new BusinessException(ErrorCode.BUSINESS_ERROR, "更新图片信息失败");
}
logger.info("图片信息更新成功: 图片ID = {}", productImages.getId());
return ResultUtils.success(true);
} catch (IllegalArgumentException e) {
// 转换为业务异常
throw new BusinessException(ErrorCode.INVALID_PARAM, e.getMessage());
} catch (IllegalAccessException e) {
logger.error("验证图片信息失败: {}", e.getMessage(), e);
throw new BusinessException(ErrorCode.BUSINESS_ERROR, "验证图片信息失败: " + e.getMessage(), e);
} catch (BusinessException e) {
throw e;
} catch (Exception e) {
logger.error("更新图片信息失败: {}", e.getMessage(), e);
throw new BusinessException(ErrorCode.DATABASE_ERROR, "更新图片信息失败: " + e.getMessage(), e);
}
}
@Override
public Result<Boolean> deleteImage(Long id) {
logger.info("删除图片: 图片ID = {}", id);
try {
if (id == null) {
throw new BusinessException(ErrorCode.MISSING_PARAM, "图片ID不能为空");
}
// 检查图片是否存在
ProductImages image = getImageByIdAndCheckExist(id);
if (image == null) {
throw new BusinessException(ErrorCode.NOT_FOUND, "图片不存在");
}
int result = productImagesMapper.deleteById(id);
if (result <= 0) {
throw new BusinessException(ErrorCode.BUSINESS_ERROR, "删除图片失败");
}
logger.info("图片删除成功: 图片ID = {}", id);
return ResultUtils.success(true);
} catch (BusinessException e) {
throw e;
} catch (Exception e) {
logger.error("删除图片失败: {}", e.getMessage(), e);
throw new BusinessException(ErrorCode.DATABASE_ERROR, "删除图片失败: " + e.getMessage(), e);
}
}
@Override
public Result<ProductImages> getImageById(Long id) {
logger.info("根据ID查询图片: 图片ID = {}", id);
try {
if (id == null) {
throw new BusinessException(ErrorCode.MISSING_PARAM, "图片ID不能为空");
}
ProductImages image = getImageByIdAndCheckExist(id);
if (image == null) {
throw new BusinessException(ErrorCode.NOT_FOUND, "图片不存在");
}
return ResultUtils.success(image);
} catch (BusinessException e) {
throw e;
} catch (Exception e) {
logger.error("查询图片失败: {}", e.getMessage(), e);
throw new BusinessException(ErrorCode.DATABASE_ERROR, "查询图片失败: " + e.getMessage(), e);
}
}
@Override
public Result<Boolean> batchCreateImages(List<ProductImages> images) {
logger.info("批量创建商品图片: 图片数量 = {}", images.size());
try {
if (images == null || images.isEmpty()) {
throw new BusinessException(ErrorCode.MISSING_PARAM, "图片列表不能为空");
}
// 批量创建图片
for (ProductImages image : images) {
// 使用ValidateUtil进行实体验证
ValidateUtil.validateEntity(image, "productId", "imageUrl");
// 检查是否设置了主图,如果设置了主图,则将其他图片设置为非主图
if (image.getIsMain() != null && image.getIsMain() == 1) {
// 将该商品的所有图片设置为非主图
productImagesMapper.update(null, new UpdateWrapper<ProductImages>().eq("product_id", image.getProductId()).set("is_main", 0));
}
productImagesMapper.insert(image);
}
logger.info("批量创建商品图片成功: 图片数量 = {}", images.size());
return ResultUtils.success(true);
} catch (IllegalArgumentException e) {
// 转换为业务异常
throw new BusinessException(ErrorCode.INVALID_PARAM, e.getMessage());
} catch (IllegalAccessException e) {
logger.error("验证图片信息失败: {}", e.getMessage(), e);
throw new BusinessException(ErrorCode.BUSINESS_ERROR, "验证图片信息失败: " + e.getMessage(), e);
} catch (BusinessException e) {
throw e;
} catch (Exception e) {
logger.error("批量创建商品图片失败: {}", e.getMessage(), e);
throw new BusinessException(ErrorCode.DATABASE_ERROR, "批量创建商品图片失败: " + e.getMessage(), e);
}
}
@Override
public Result<Boolean> deleteImagesByProductId(Long productId) {
logger.info("根据商品ID删除所有图片: {}", productId);
try {
if (productId == null) {
throw new BusinessException(ErrorCode.MISSING_PARAM, "商品ID不能为空");
}
int result = productImagesMapper.delete(new QueryWrapper<ProductImages>().eq("product_id", productId));
logger.info("删除了 {} 张图片", result);
return ResultUtils.success(true);
} catch (BusinessException e) {
throw e;
} catch (Exception e) {
logger.error("根据商品ID删除所有图片失败: {}", e.getMessage(), e);
throw new BusinessException(ErrorCode.DATABASE_ERROR, "根据商品ID删除所有图片失败: " + e.getMessage(), e);
}
}
@Override
public Result<Boolean> setMainImage(Long productId, Long imageId) {
logger.info("设置主图: 商品ID = {}, 图片ID = {}", productId, imageId);
try {
if (productId == null || imageId == null) {
throw new BusinessException(ErrorCode.MISSING_PARAM, "商品ID和图片ID不能为空");
}
// 检查图片是否存在
ProductImages image = getImageByIdAndCheckExist(imageId);
if (image == null) {
throw new BusinessException(ErrorCode.NOT_FOUND, "图片不存在");
}
// 检查图片是否属于该商品
if (!image.getProductId().equals(productId)) {
throw new BusinessException(ErrorCode.INVALID_PARAM, "图片不属于该商品");
}
// 将该商品的所有图片设置为非主图
productImagesMapper.update(null, new UpdateWrapper<ProductImages>().eq("product_id", productId).set("is_main", 0));
// 将指定图片设置为主图
ProductImages mainImage = new ProductImages();
mainImage.setId(imageId);
mainImage.setIsMain(1);
int result = productImagesMapper.updateById(mainImage);
if (result <= 0) {
throw new BusinessException(ErrorCode.BUSINESS_ERROR, "设置主图失败");
}
logger.info("主图设置成功: 商品ID = {}, 图片ID = {}", productId, imageId);
return ResultUtils.success(true);
} catch (BusinessException e) {
throw e;
} catch (Exception e) {
logger.error("设置主图失败: {}", e.getMessage(), e);
throw new BusinessException(ErrorCode.DATABASE_ERROR, "设置主图失败: " + e.getMessage(), e);
}
}
/**
* 根据图片ID查询图片并检查是否存在
* @param id 图片ID
* @return 图片对象如果图片不存在则返回null
*/
private ProductImages getImageByIdAndCheckExist(Long id) {
if (id == null) {
return null;
}
QueryWrapper<ProductImages> queryWrapper = new QueryWrapper<ProductImages>().eq("id", id);
return productImagesMapper.selectOne(queryWrapper);
}
}

View File

@@ -0,0 +1,371 @@
package com.qf.backend.service.impl;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qf.backend.dto.Result;
import com.qf.backend.entity.ProductInventories;
import com.qf.backend.exception.BusinessException;
import com.qf.backend.exception.ErrorCode;
import com.qf.backend.mapper.ProductInventoriesMapper;
import com.qf.backend.service.ProductInventoriesService;
import com.qf.backend.util.ResultUtils;
import com.qf.backend.util.ValidateUtil;
@Service
public class ProductInventoriesServiceImpl extends ServiceImpl<ProductInventoriesMapper, ProductInventories> implements ProductInventoriesService {
private static final Logger logger = LoggerFactory.getLogger(ProductInventoriesServiceImpl.class);
@Autowired
private ProductInventoriesMapper productInventoriesMapper;
@Override
public Result<List<ProductInventories>> getInventoriesByProductId(Long productId) {
logger.info("根据商品ID查询库存: {}", productId);
try {
if (productId == null) {
throw new BusinessException(ErrorCode.MISSING_PARAM, "商品ID不能为空");
}
List<ProductInventories> inventories = productInventoriesMapper.selectList(new QueryWrapper<ProductInventories>().eq("product_id", productId));
logger.info("查询到 {} 条库存记录", inventories.size());
return ResultUtils.success(inventories);
} catch (BusinessException e) {
throw e;
} catch (Exception e) {
logger.error("查询库存失败: {}", e.getMessage(), e);
throw new BusinessException(ErrorCode.DATABASE_ERROR, "查询库存失败: " + e.getMessage(), e);
}
}
@Override
public Result<ProductInventories> getInventoryBySkuId(Long skuId) {
logger.info("根据SKU ID查询库存: {}", skuId);
try {
if (skuId == null) {
throw new BusinessException(ErrorCode.MISSING_PARAM, "SKU ID不能为空");
}
ProductInventories inventory = productInventoriesMapper.selectOne(new QueryWrapper<ProductInventories>().eq("sku_id", skuId));
if (inventory == null) {
throw new BusinessException(ErrorCode.NOT_FOUND, "库存不存在: SKU ID = " + skuId);
}
return ResultUtils.success(inventory);
} catch (BusinessException e) {
throw e;
} catch (Exception e) {
logger.error("查询库存失败: {}", e.getMessage(), e);
throw new BusinessException(ErrorCode.DATABASE_ERROR, "查询库存失败: " + e.getMessage(), e);
}
}
@Override
public Result<Boolean> createInventory(ProductInventories productInventories) {
logger.info("创建库存记录: SKU ID = {}", productInventories.getSkuId());
try {
// 使用ValidateUtil进行实体验证
ValidateUtil.validateEntity(productInventories, "skuId", "currentStock");
// 检查库存数量是否合法
if (productInventories.getCurrentStock() < 0) {
throw new BusinessException(ErrorCode.INVALID_PARAM, "库存数量不能为负数");
}
// 检查是否已存在该SKU的库存记录
ProductInventories existingInventory = productInventoriesMapper.selectOne(new QueryWrapper<ProductInventories>().eq("sku_id", productInventories.getSkuId()));
if (existingInventory != null) {
throw new BusinessException(ErrorCode.BUSINESS_ERROR, "该SKU的库存记录已存在");
}
int result = productInventoriesMapper.insert(productInventories);
if (result <= 0) {
throw new BusinessException(ErrorCode.BUSINESS_ERROR, "创建库存记录失败");
}
logger.info("库存记录创建成功");
return ResultUtils.success(true);
} catch (IllegalArgumentException e) {
// 转换为业务异常
throw new BusinessException(ErrorCode.INVALID_PARAM, e.getMessage());
} catch (IllegalAccessException e) {
logger.error("验证库存信息失败: {}", e.getMessage(), e);
throw new BusinessException(ErrorCode.BUSINESS_ERROR, "验证库存信息失败: " + e.getMessage(), e);
} catch (BusinessException e) {
throw e;
} catch (Exception e) {
logger.error("创建库存记录失败: {}", e.getMessage(), e);
throw new BusinessException(ErrorCode.DATABASE_ERROR, "创建库存记录失败: " + e.getMessage(), e);
}
}
@Override
public Result<Boolean> updateInventory(ProductInventories productInventories) {
logger.info("更新库存信息: 库存ID = {}", productInventories.getId());
try {
if (productInventories == null || productInventories.getId() == null) {
throw new BusinessException(ErrorCode.MISSING_PARAM, "库存信息或库存ID不能为空");
}
// 检查库存是否存在
ProductInventories existingInventory = getInventoryByIdAndCheckExist(productInventories.getId());
if (existingInventory == null) {
throw new BusinessException(ErrorCode.NOT_FOUND, "库存不存在");
}
// 使用ValidateUtil进行实体验证
ValidateUtil.validateEntity(productInventories, "skuId", "currentStock");
// 检查库存数量是否合法
if (productInventories.getCurrentStock() < 0) {
throw new BusinessException(ErrorCode.INVALID_PARAM, "库存数量不能为负数");
}
// 更新库存信息
int result = productInventoriesMapper.updateById(productInventories);
if (result <= 0) {
throw new BusinessException(ErrorCode.BUSINESS_ERROR, "更新库存信息失败");
}
logger.info("库存信息更新成功: 库存ID = {}", productInventories.getId());
return ResultUtils.success(true);
} catch (IllegalArgumentException e) {
// 转换为业务异常
throw new BusinessException(ErrorCode.INVALID_PARAM, e.getMessage());
} catch (IllegalAccessException e) {
logger.error("验证库存信息失败: {}", e.getMessage(), e);
throw new BusinessException(ErrorCode.BUSINESS_ERROR, "验证库存信息失败: " + e.getMessage(), e);
} catch (BusinessException e) {
throw e;
} catch (Exception e) {
logger.error("更新库存信息失败: {}", e.getMessage(), e);
throw new BusinessException(ErrorCode.DATABASE_ERROR, "更新库存信息失败: " + e.getMessage(), e);
}
}
@Override
public Result<Boolean> deleteInventory(Long id) {
logger.info("删除库存记录: 库存ID = {}", id);
try {
if (id == null) {
throw new BusinessException(ErrorCode.MISSING_PARAM, "库存ID不能为空");
}
// 检查库存是否存在
ProductInventories inventory = getInventoryByIdAndCheckExist(id);
if (inventory == null) {
throw new BusinessException(ErrorCode.NOT_FOUND, "库存不存在");
}
int result = productInventoriesMapper.deleteById(id);
if (result <= 0) {
throw new BusinessException(ErrorCode.BUSINESS_ERROR, "删除库存记录失败");
}
logger.info("库存记录删除成功: 库存ID = {}", id);
return ResultUtils.success(true);
} catch (BusinessException e) {
throw e;
} catch (Exception e) {
logger.error("删除库存记录失败: {}", e.getMessage(), e);
throw new BusinessException(ErrorCode.DATABASE_ERROR, "删除库存记录失败: " + e.getMessage(), e);
}
}
@Override
public Result<ProductInventories> getInventoryById(Long id) {
logger.info("根据ID查询库存: 库存ID = {}", id);
try {
if (id == null) {
throw new BusinessException(ErrorCode.MISSING_PARAM, "库存ID不能为空");
}
ProductInventories inventory = getInventoryByIdAndCheckExist(id);
if (inventory == null) {
throw new BusinessException(ErrorCode.NOT_FOUND, "库存不存在");
}
return ResultUtils.success(inventory);
} catch (BusinessException e) {
throw e;
} catch (Exception e) {
logger.error("查询库存失败: {}", e.getMessage(), e);
throw new BusinessException(ErrorCode.DATABASE_ERROR, "查询库存失败: " + e.getMessage(), e);
}
}
@Override
public Result<Boolean> increaseInventory(Long skuId, Integer quantity) {
logger.info("增加库存: SKU ID = {}, 数量 = {}", skuId, quantity);
try {
if (skuId == null) {
throw new BusinessException(ErrorCode.MISSING_PARAM, "SKU ID不能为空");
}
if (quantity == null || quantity <= 0) {
throw new BusinessException(ErrorCode.INVALID_PARAM, "增加数量必须大于0");
}
// 检查库存是否存在
ProductInventories inventory = productInventoriesMapper.selectOne(new QueryWrapper<ProductInventories>().eq("sku_id", skuId));
if (inventory == null) {
throw new BusinessException(ErrorCode.NOT_FOUND, "库存不存在: SKU ID = " + skuId);
}
// 增加库存
inventory.setCurrentStock(inventory.getCurrentStock() + quantity);
int result = productInventoriesMapper.updateById(inventory);
if (result <= 0) {
throw new BusinessException(ErrorCode.BUSINESS_ERROR, "增加库存失败");
}
logger.info("库存增加成功: SKU ID = {}, 新库存 = {}", skuId, inventory.getCurrentStock());
return ResultUtils.success(true);
} catch (BusinessException e) {
throw e;
} catch (Exception e) {
logger.error("增加库存失败: {}", e.getMessage(), e);
throw new BusinessException(ErrorCode.DATABASE_ERROR, "增加库存失败: " + e.getMessage(), e);
}
}
@Override
public Result<Boolean> decreaseInventory(Long skuId, Integer quantity) {
logger.info("减少库存: SKU ID = {}, 数量 = {}", skuId, quantity);
try {
if (skuId == null) {
throw new BusinessException(ErrorCode.MISSING_PARAM, "SKU ID不能为空");
}
if (quantity == null || quantity <= 0) {
throw new BusinessException(ErrorCode.INVALID_PARAM, "减少数量必须大于0");
}
// 检查库存是否存在
ProductInventories inventory = productInventoriesMapper.selectOne(new QueryWrapper<ProductInventories>().eq("sku_id", skuId));
if (inventory == null) {
throw new BusinessException(ErrorCode.NOT_FOUND, "库存不存在: SKU ID = " + skuId);
}
// 检查库存是否充足
if (inventory.getCurrentStock() < quantity) {
throw new BusinessException(ErrorCode.INVALID_PARAM, "库存不足: 当前库存 = " + inventory.getCurrentStock() + ", 需要 = " + quantity);
}
// 减少库存
inventory.setCurrentStock(inventory.getCurrentStock() - quantity);
int result = productInventoriesMapper.updateById(inventory);
if (result <= 0) {
throw new BusinessException(ErrorCode.BUSINESS_ERROR, "减少库存失败");
}
logger.info("库存减少成功: SKU ID = {}, 新库存 = {}", skuId, inventory.getCurrentStock());
return ResultUtils.success(true);
} catch (BusinessException e) {
throw e;
} catch (Exception e) {
logger.error("减少库存失败: {}", e.getMessage(), e);
throw new BusinessException(ErrorCode.DATABASE_ERROR, "减少库存失败: " + e.getMessage(), e);
}
}
@Override
public Result<Boolean> checkInventorySufficient(Long skuId, Integer quantity) {
logger.info("检查库存是否充足: SKU ID = {}, 需要数量 = {}", skuId, quantity);
try {
if (skuId == null) {
throw new BusinessException(ErrorCode.MISSING_PARAM, "SKU ID不能为空");
}
if (quantity == null || quantity <= 0) {
throw new BusinessException(ErrorCode.INVALID_PARAM, "需要数量必须大于0");
}
// 检查库存是否存在
ProductInventories inventory = productInventoriesMapper.selectOne(new QueryWrapper<ProductInventories>().eq("sku_id", skuId));
if (inventory == null) {
logger.warn("库存不存在: SKU ID = {}", skuId);
return ResultUtils.success(false);
}
boolean isSufficient = inventory.getCurrentStock() >= quantity;
logger.info("库存检查结果: SKU ID = {}, 当前库存 = {}, 需要数量 = {}, 是否充足 = {}", skuId, inventory.getCurrentStock(), quantity, isSufficient);
return ResultUtils.success(isSufficient);
} catch (BusinessException e) {
throw e;
} catch (Exception e) {
logger.error("检查库存是否充足失败: {}", e.getMessage(), e);
throw new BusinessException(ErrorCode.DATABASE_ERROR, "检查库存是否充足失败: " + e.getMessage(), e);
}
}
@Override
public Result<Boolean> batchUpdateInventory(List<ProductInventories> inventoryUpdates) {
logger.info("批量更新库存: 更新数量 = {}", inventoryUpdates.size());
try {
if (inventoryUpdates == null || inventoryUpdates.isEmpty()) {
throw new BusinessException(ErrorCode.MISSING_PARAM, "库存更新列表不能为空");
}
// 批量更新库存
for (ProductInventories inventory : inventoryUpdates) {
// 使用ValidateUtil进行实体验证
ValidateUtil.validateEntity(inventory, "id", "currentStock");
// 检查库存数量是否合法
if (inventory.getCurrentStock() < 0) {
throw new BusinessException(ErrorCode.INVALID_PARAM, "库存数量不能为负数");
}
// 检查库存是否存在
ProductInventories existingInventory = getInventoryByIdAndCheckExist(inventory.getId());
if (existingInventory == null) {
throw new BusinessException(ErrorCode.NOT_FOUND, "库存不存在: 库存ID = " + inventory.getId());
}
// 更新库存
productInventoriesMapper.updateById(inventory);
}
logger.info("批量更新库存成功: 更新数量 = {}", inventoryUpdates.size());
return ResultUtils.success(true);
} catch (IllegalArgumentException e) {
// 转换为业务异常
throw new BusinessException(ErrorCode.INVALID_PARAM, e.getMessage());
} catch (IllegalAccessException e) {
logger.error("验证库存信息失败: {}", e.getMessage(), e);
throw new BusinessException(ErrorCode.BUSINESS_ERROR, "验证库存信息失败: " + e.getMessage(), e);
} catch (BusinessException e) {
throw e;
} catch (Exception e) {
logger.error("批量更新库存失败: {}", e.getMessage(), e);
throw new BusinessException(ErrorCode.DATABASE_ERROR, "批量更新库存失败: " + e.getMessage(), e);
}
}
/**
* 根据库存ID查询库存并检查是否存在
* @param id 库存ID
* @return 库存对象如果库存不存在则返回null
*/
private ProductInventories getInventoryByIdAndCheckExist(Long id) {
if (id == null) {
return null;
}
QueryWrapper<ProductInventories> queryWrapper = new QueryWrapper<ProductInventories>().eq("id", id);
return productInventoriesMapper.selectOne(queryWrapper);
}
}

View File

@@ -0,0 +1,332 @@
package com.qf.backend.service.impl;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qf.backend.dto.Result;
import com.qf.backend.entity.ProductSkus;
import com.qf.backend.exception.BusinessException;
import com.qf.backend.exception.ErrorCode;
import com.qf.backend.mapper.ProductSkusMapper;
import com.qf.backend.service.ProductSkusService;
import com.qf.backend.util.ResultUtils;
import com.qf.backend.util.ValidateUtil;
@Service
public class ProductSkusServiceImpl extends ServiceImpl<ProductSkusMapper, ProductSkus> implements ProductSkusService {
private static final Logger logger = LoggerFactory.getLogger(ProductSkusServiceImpl.class);
@Autowired
private ProductSkusMapper productSkusMapper;
@Override
public Result<List<ProductSkus>> getSkusByProductId(Long productId) {
logger.info("根据商品ID查询SKU: {}", productId);
try {
if (productId == null) {
throw new BusinessException(ErrorCode.MISSING_PARAM, "商品ID不能为空");
}
List<ProductSkus> skus = productSkusMapper.selectList(new QueryWrapper<ProductSkus>().eq("product_id", productId));
logger.info("查询到 {} 个SKU", skus.size());
return ResultUtils.success(skus);
} catch (BusinessException e) {
throw e;
} catch (Exception e) {
logger.error("查询SKU失败: {}", e.getMessage(), e);
throw new BusinessException(ErrorCode.DATABASE_ERROR, "查询SKU失败: " + e.getMessage(), e);
}
}
@Override
public Result<ProductSkus> getSkuByCode(String skuCode) {
logger.info("根据SKU编码查询SKU: {}", skuCode);
try {
if (ValidateUtil.isEmpty(skuCode)) {
throw new BusinessException(ErrorCode.MISSING_PARAM, "SKU编码不能为空");
}
ProductSkus sku = productSkusMapper.selectOne(new QueryWrapper<ProductSkus>().eq("sku_code", skuCode));
if (sku == null) {
throw new BusinessException(ErrorCode.NOT_FOUND, "SKU不存在: " + skuCode);
}
return ResultUtils.success(sku);
} catch (BusinessException e) {
throw e;
} catch (Exception e) {
logger.error("查询SKU失败: {}", e.getMessage(), e);
throw new BusinessException(ErrorCode.DATABASE_ERROR, "查询SKU失败: " + e.getMessage(), e);
}
}
@Override
public Result<Boolean> createSku(ProductSkus productSkus) {
logger.info("创建SKU: SKU编码 = {}", productSkus.getSkuCode());
try {
// 使用ValidateUtil进行实体验证
ValidateUtil.validateEntity(productSkus, "productId", "skuCode", "skuSpecs", "price", "stock");
// 检查SKU编码是否已存在
ProductSkus existingSku = productSkusMapper.selectOne(new QueryWrapper<ProductSkus>().eq("sku_code", productSkus.getSkuCode()));
if (existingSku != null) {
throw new BusinessException(ErrorCode.BUSINESS_ERROR, "SKU编码已存在");
}
int result = productSkusMapper.insert(productSkus);
if (result <= 0) {
throw new BusinessException(ErrorCode.BUSINESS_ERROR, "创建SKU失败");
}
logger.info("SKU创建成功");
return ResultUtils.success(true);
} catch (IllegalArgumentException e) {
// 转换为业务异常
throw new BusinessException(ErrorCode.INVALID_PARAM, e.getMessage());
} catch (IllegalAccessException e) {
logger.error("验证SKU信息失败: {}", e.getMessage(), e);
throw new BusinessException(ErrorCode.BUSINESS_ERROR, "验证SKU信息失败: " + e.getMessage(), e);
} catch (BusinessException e) {
throw e;
} catch (Exception e) {
logger.error("创建SKU失败: {}", e.getMessage(), e);
throw new BusinessException(ErrorCode.DATABASE_ERROR, "创建SKU失败: " + e.getMessage(), e);
}
}
@Override
public Result<Boolean> updateSku(ProductSkus productSkus) {
logger.info("更新SKU信息: SKU ID = {}", productSkus.getId());
try {
if (productSkus == null || productSkus.getId() == null) {
throw new BusinessException(ErrorCode.MISSING_PARAM, "SKU信息或SKU ID不能为空");
}
// 检查SKU是否存在
ProductSkus existingSku = getSkuByIdAndCheckExist(productSkus.getId());
if (existingSku == null) {
throw new BusinessException(ErrorCode.NOT_FOUND, "SKU不存在");
}
// 使用ValidateUtil进行实体验证
ValidateUtil.validateEntity(productSkus, "productId", "skuCode", "skuSpecs", "price", "stock");
// 检查SKU编码是否已存在排除当前SKU
ProductSkus skuWithSameCode = productSkusMapper.selectOne(new QueryWrapper<ProductSkus>().eq("sku_code", productSkus.getSkuCode()).ne("id", productSkus.getId()));
if (skuWithSameCode != null) {
throw new BusinessException(ErrorCode.BUSINESS_ERROR, "SKU编码已存在");
}
// 更新SKU信息
int result = productSkusMapper.updateById(productSkus);
if (result <= 0) {
throw new BusinessException(ErrorCode.BUSINESS_ERROR, "更新SKU信息失败");
}
logger.info("SKU信息更新成功: SKU ID = {}", productSkus.getId());
return ResultUtils.success(true);
} catch (IllegalArgumentException e) {
// 转换为业务异常
throw new BusinessException(ErrorCode.INVALID_PARAM, e.getMessage());
} catch (IllegalAccessException e) {
logger.error("验证SKU信息失败: {}", e.getMessage(), e);
throw new BusinessException(ErrorCode.BUSINESS_ERROR, "验证SKU信息失败: " + e.getMessage(), e);
} catch (BusinessException e) {
throw e;
} catch (Exception e) {
logger.error("更新SKU信息失败: {}", e.getMessage(), e);
throw new BusinessException(ErrorCode.DATABASE_ERROR, "更新SKU信息失败: " + e.getMessage(), e);
}
}
@Override
public Result<Boolean> deleteSku(Long id) {
logger.info("删除SKU: SKU ID = {}", id);
try {
if (id == null) {
throw new BusinessException(ErrorCode.MISSING_PARAM, "SKU ID不能为空");
}
// 检查SKU是否存在
ProductSkus sku = getSkuByIdAndCheckExist(id);
if (sku == null) {
throw new BusinessException(ErrorCode.NOT_FOUND, "SKU不存在");
}
int result = productSkusMapper.deleteById(id);
if (result <= 0) {
throw new BusinessException(ErrorCode.BUSINESS_ERROR, "删除SKU失败");
}
logger.info("SKU删除成功: SKU ID = {}", id);
return ResultUtils.success(true);
} catch (BusinessException e) {
throw e;
} catch (Exception e) {
logger.error("删除SKU失败: {}", e.getMessage(), e);
throw new BusinessException(ErrorCode.DATABASE_ERROR, "删除SKU失败: " + e.getMessage(), e);
}
}
@Override
public Result<ProductSkus> getSkuById(Long id) {
logger.info("根据ID查询SKU: SKU ID = {}", id);
try {
if (id == null) {
throw new BusinessException(ErrorCode.MISSING_PARAM, "SKU ID不能为空");
}
ProductSkus sku = getSkuByIdAndCheckExist(id);
if (sku == null) {
throw new BusinessException(ErrorCode.NOT_FOUND, "SKU不存在");
}
return ResultUtils.success(sku);
} catch (BusinessException e) {
throw e;
} catch (Exception e) {
logger.error("查询SKU失败: {}", e.getMessage(), e);
throw new BusinessException(ErrorCode.DATABASE_ERROR, "查询SKU失败: " + e.getMessage(), e);
}
}
@Override
public Result<Boolean> batchCreateSkus(List<ProductSkus> skus) {
logger.info("批量创建SKU: SKU数量 = {}", skus.size());
try {
if (skus == null || skus.isEmpty()) {
throw new BusinessException(ErrorCode.MISSING_PARAM, "SKU列表不能为空");
}
// 批量创建SKU
for (ProductSkus sku : skus) {
// 使用ValidateUtil进行实体验证
ValidateUtil.validateEntity(sku, "productId", "skuCode", "skuSpecs", "price", "stock");
// 检查SKU编码是否已存在
ProductSkus existingSku = productSkusMapper.selectOne(new QueryWrapper<ProductSkus>().eq("sku_code", sku.getSkuCode()));
if (existingSku != null) {
throw new BusinessException(ErrorCode.BUSINESS_ERROR, "SKU编码已存在: " + sku.getSkuCode());
}
productSkusMapper.insert(sku);
}
logger.info("批量创建SKU成功: SKU数量 = {}", skus.size());
return ResultUtils.success(true);
} catch (IllegalArgumentException e) {
// 转换为业务异常
throw new BusinessException(ErrorCode.INVALID_PARAM, e.getMessage());
} catch (IllegalAccessException e) {
logger.error("验证SKU信息失败: {}", e.getMessage(), e);
throw new BusinessException(ErrorCode.BUSINESS_ERROR, "验证SKU信息失败: " + e.getMessage(), e);
} catch (BusinessException e) {
throw e;
} catch (Exception e) {
logger.error("批量创建SKU失败: {}", e.getMessage(), e);
throw new BusinessException(ErrorCode.DATABASE_ERROR, "批量创建SKU失败: " + e.getMessage(), e);
}
}
@Override
public Result<Boolean> deleteSkusByProductId(Long productId) {
logger.info("根据商品ID删除所有SKU: {}", productId);
try {
if (productId == null) {
throw new BusinessException(ErrorCode.MISSING_PARAM, "商品ID不能为空");
}
int result = productSkusMapper.delete(new QueryWrapper<ProductSkus>().eq("product_id", productId));
logger.info("删除了 {} 个SKU", result);
return ResultUtils.success(true);
} catch (BusinessException e) {
throw e;
} catch (Exception e) {
logger.error("根据商品ID删除所有SKU失败: {}", e.getMessage(), e);
throw new BusinessException(ErrorCode.DATABASE_ERROR, "根据商品ID删除所有SKU失败: " + e.getMessage(), e);
}
}
@Override
public Result<Boolean> updateSkuStock(Long skuId, Integer quantity) {
logger.info("更新SKU库存: SKU ID = {}, 库存数量 = {}", skuId, quantity);
try {
if (skuId == null || quantity == null) {
throw new BusinessException(ErrorCode.MISSING_PARAM, "SKU ID和库存数量不能为空");
}
// 检查库存数量是否合法
if (quantity < 0) {
throw new BusinessException(ErrorCode.INVALID_PARAM, "库存数量不能为负数");
}
// 检查SKU是否存在
ProductSkus sku = getSkuByIdAndCheckExist(skuId);
if (sku == null) {
throw new BusinessException(ErrorCode.NOT_FOUND, "SKU不存在");
}
// 更新库存
sku.setStock(quantity);
int result = productSkusMapper.updateById(sku);
if (result <= 0) {
throw new BusinessException(ErrorCode.BUSINESS_ERROR, "更新SKU库存失败");
}
logger.info("SKU库存更新成功: SKU ID = {}, 新库存 = {}", skuId, quantity);
return ResultUtils.success(true);
} catch (BusinessException e) {
throw e;
} catch (Exception e) {
logger.error("更新SKU库存失败: {}", e.getMessage(), e);
throw new BusinessException(ErrorCode.DATABASE_ERROR, "更新SKU库存失败: " + e.getMessage(), e);
}
}
@Override
public Result<List<ProductSkus>> batchGetSkus(List<Long> skuIds) {
logger.info("批量查询SKU: SKU ID列表 = {}", skuIds);
try {
if (skuIds == null || skuIds.isEmpty()) {
throw new BusinessException(ErrorCode.MISSING_PARAM, "SKU ID列表不能为空");
}
List<ProductSkus> skus = productSkusMapper.selectBatchIds(skuIds);
logger.info("查询到 {} 个SKU", skus.size());
return ResultUtils.success(skus);
} catch (BusinessException e) {
throw e;
} catch (Exception e) {
logger.error("批量查询SKU失败: {}", e.getMessage(), e);
throw new BusinessException(ErrorCode.DATABASE_ERROR, "批量查询SKU失败: " + e.getMessage(), e);
}
}
/**
* 根据SKU ID查询SKU并检查是否存在
* @param id SKU ID
* @return SKU对象如果SKU不存在则返回null
*/
private ProductSkus getSkuByIdAndCheckExist(Long id) {
if (id == null) {
return null;
}
QueryWrapper<ProductSkus> queryWrapper = new QueryWrapper<ProductSkus>().eq("id", id);
return productSkusMapper.selectOne(queryWrapper);
}
}

View File

@@ -0,0 +1,248 @@
package com.qf.backend.service.impl;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qf.backend.dto.Result;
import com.qf.backend.entity.Products;
import com.qf.backend.exception.BusinessException;
import com.qf.backend.exception.ErrorCode;
import com.qf.backend.mapper.ProductsMapper;
import com.qf.backend.service.ProductsService;
import com.qf.backend.util.ResultUtils;
import com.qf.backend.util.ValidateUtil;
/**
* 商品服务实现类
*/
@Service
public class ProductsServiceImpl extends ServiceImpl<ProductsMapper, Products> implements ProductsService {
@Autowired
private ProductsMapper productsMapper;
@Override
public Result<List<Products>> getProductsByName(String productName) {
if (ValidateUtil.isEmpty(productName)) {
throw new BusinessException(ErrorCode.MISSING_PARAM, "商品名称不能为空");
}
try {
List<Products> products = productsMapper.selectList(
new QueryWrapper<Products>().like("product_name", productName));
return ResultUtils.success(products);
} catch (BusinessException e) {
throw e;
} catch (Exception e) {
throw new BusinessException(ErrorCode.DATABASE_ERROR, "查询商品失败", e);
}
}
@Override
public Result<List<Products>> getProductsByCategoryId(Long categoryId) {
if (ValidateUtil.isEmpty(categoryId)) {
throw new BusinessException(ErrorCode.MISSING_PARAM, "分类ID不能为空");
}
try {
List<Products> products = productsMapper.selectList(
new QueryWrapper<Products>().eq("category_id", categoryId));
return ResultUtils.success(products);
} catch (BusinessException e) {
throw e;
} catch (Exception e) {
throw new BusinessException(ErrorCode.DATABASE_ERROR, "查询商品失败", e);
}
}
@Override
public Result<Boolean> createProduct(Products products) {
if (ValidateUtil.isEmpty(products)) {
throw new BusinessException(ErrorCode.MISSING_PARAM, "商品信息不能为空");
}
if (ValidateUtil.isEmpty(products.getProductName())) {
throw new BusinessException(ErrorCode.MISSING_PARAM, "商品名称不能为空");
}
if (products.getShopId() == null) {
throw new BusinessException(ErrorCode.MISSING_PARAM, "店铺ID不能为空");
}
if (products.getCategoryId() == null) {
throw new BusinessException(ErrorCode.MISSING_PARAM, "分类ID不能为空");
}
if (products.getOriginalPrice() == null) {
throw new BusinessException(ErrorCode.MISSING_PARAM, "商品原价不能为空");
}
try {
int result = productsMapper.insert(products);
return ResultUtils.success(result > 0);
} catch (BusinessException e) {
throw e;
} catch (Exception e) {
throw new BusinessException(ErrorCode.DATABASE_ERROR, "创建商品失败", e);
}
}
@Override
public Result<Boolean> updateProduct(Products products) {
if (ValidateUtil.isEmpty(products)) {
throw new BusinessException(ErrorCode.MISSING_PARAM, "商品信息不能为空");
}
if (products.getId() == null) {
throw new BusinessException(ErrorCode.MISSING_PARAM, "商品ID不能为空");
}
if (ValidateUtil.isEmpty(products.getProductName())) {
throw new BusinessException(ErrorCode.MISSING_PARAM, "商品名称不能为空");
}
try {
// 检查商品是否存在
Products existing = productsMapper.selectById(products.getId());
if (existing == null) {
throw new BusinessException(ErrorCode.NOT_FOUND, "商品不存在");
}
int result = productsMapper.updateById(products);
return ResultUtils.success(result > 0);
} catch (BusinessException e) {
throw e;
} catch (Exception e) {
throw new BusinessException(ErrorCode.DATABASE_ERROR, "更新商品失败", e);
}
}
@Override
public Result<Boolean> deleteProduct(Long id) {
if (ValidateUtil.isEmpty(id)) {
throw new BusinessException(ErrorCode.MISSING_PARAM, "商品ID不能为空");
}
try {
// 检查商品是否存在
Products existing = productsMapper.selectById(id);
if (existing == null) {
throw new BusinessException(ErrorCode.NOT_FOUND, "商品不存在");
}
int result = productsMapper.deleteById(id);
return ResultUtils.success(result > 0);
} catch (BusinessException e) {
throw e;
} catch (Exception e) {
throw new BusinessException(ErrorCode.DATABASE_ERROR, "删除商品失败", e);
}
}
@Override
public Result<Products> getProductById(Long id) {
if (ValidateUtil.isEmpty(id)) {
throw new BusinessException(ErrorCode.MISSING_PARAM, "商品ID不能为空");
}
try {
Products product = productsMapper.selectById(id);
if (product == null) {
throw new BusinessException(ErrorCode.NOT_FOUND, "商品不存在");
}
return ResultUtils.success(product);
} catch (BusinessException e) {
throw e;
} catch (Exception e) {
throw new BusinessException(ErrorCode.DATABASE_ERROR, "查询商品失败", e);
}
}
@Override
public Result<List<Products>> listProductsByPage(int page, int size) {
if (page < 1) {
throw new BusinessException(ErrorCode.INVALID_PARAM, "页码不能小于1");
}
if (size < 1 || size > 100) {
throw new BusinessException(ErrorCode.INVALID_PARAM, "每页数量必须在1-100之间");
}
try {
Page<Products> productPage = new Page<>(page, size);
Page<Products> resultPage = productsMapper.selectPage(productPage, null);
return ResultUtils.success(resultPage.getRecords());
} catch (BusinessException e) {
throw e;
} catch (Exception e) {
throw new BusinessException(ErrorCode.DATABASE_ERROR, "分页查询商品失败", e);
}
}
@Override
public Result<List<Products>> getProductsByShopId(Long shopId) {
if (ValidateUtil.isEmpty(shopId)) {
throw new BusinessException(ErrorCode.MISSING_PARAM, "店铺ID不能为空");
}
try {
List<Products> products = productsMapper.selectList(
new QueryWrapper<Products>().eq("shop_id", shopId));
return ResultUtils.success(products);
} catch (BusinessException e) {
throw e;
} catch (Exception e) {
throw new BusinessException(ErrorCode.DATABASE_ERROR, "查询商品失败", e);
}
}
@Override
public Result<Boolean> batchUpdateProductStatus(List<Long> ids, Integer status) {
if (ValidateUtil.isEmpty(ids)) {
throw new BusinessException(ErrorCode.MISSING_PARAM, "商品ID列表不能为空");
}
if (ids.isEmpty()) {
throw new BusinessException(ErrorCode.MISSING_PARAM, "商品ID列表不能为空");
}
if (ValidateUtil.isEmpty(status)) {
throw new BusinessException(ErrorCode.MISSING_PARAM, "商品状态不能为空");
}
try {
// 检查所有商品是否存在
for (Long id : ids) {
if (ValidateUtil.isEmpty(id)) {
throw new BusinessException(ErrorCode.INVALID_PARAM, "商品ID列表中存在空值");
}
Products existing = productsMapper.selectById(id);
if (existing == null) {
throw new BusinessException(ErrorCode.NOT_FOUND, "商品ID为" + id + "的商品不存在");
}
}
// 批量更新状态
for (Long id : ids) {
Products product = new Products();
product.setId(id);
product.setStatus(status);
productsMapper.updateById(product);
}
return ResultUtils.success(true);
} catch (BusinessException e) {
throw e;
} catch (Exception e) {
throw new BusinessException(ErrorCode.DATABASE_ERROR, "批量更新商品状态失败", e);
}
}
@Override
public Result<List<Products>> searchProducts(String keyword, int page, int size) {
if (ValidateUtil.isEmpty(keyword)) {
throw new BusinessException(ErrorCode.MISSING_PARAM, "搜索关键词不能为空");
}
if (page < 1) {
throw new BusinessException(ErrorCode.INVALID_PARAM, "页码不能小于1");
}
if (size < 1 || size > 100) {
throw new BusinessException(ErrorCode.INVALID_PARAM, "每页数量必须在1-100之间");
}
try {
Page<Products> productPage = new Page<>(page, size);
QueryWrapper<Products> queryWrapper = new QueryWrapper<>();
queryWrapper.like("product_name", keyword)
.or().like("description", keyword);
Page<Products> resultPage = productsMapper.selectPage(productPage, queryWrapper);
return ResultUtils.success(resultPage.getRecords());
} catch (BusinessException e) {
throw e;
} catch (Exception e) {
throw new BusinessException(ErrorCode.DATABASE_ERROR, "搜索商品失败", e);
}
}
}

View File

@@ -0,0 +1,215 @@
package com.qf.backend.service.impl;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qf.backend.entity.Refunds;
import com.qf.backend.exception.BusinessException;
import com.qf.backend.exception.ErrorCode;
import com.qf.backend.mapper.RefundsMapper;
import com.qf.backend.service.RefundsService;
import com.qf.backend.util.RefundNumberFenerator;
import com.qf.backend.util.ValidateUtil;
/**
* 退款服务实现类
*/
@Service
public class RefundsServiceImpl extends ServiceImpl<RefundsMapper, Refunds> implements RefundsService {
@Autowired
private RefundsMapper refundsMapper;
@Override
public List<Refunds> getRefundsByOrderId(Long orderId) {
if (ValidateUtil.isEmpty(orderId)) {
throw new BusinessException(ErrorCode.MISSING_PARAM, "订单ID不能为空");
}
try {
return refundsMapper.selectList(
new QueryWrapper<Refunds>().eq("order_id", orderId));
} catch (BusinessException e) {
throw e;
} catch (Exception e) {
throw new BusinessException(ErrorCode.DATABASE_ERROR, "查询退款记录失败", e);
}
}
@Override
public Refunds getRefundByNumber(String refundNumber) {
if (ValidateUtil.isEmpty(refundNumber)) {
throw new BusinessException(ErrorCode.MISSING_PARAM, "退款单号不能为空");
}
try {
return refundsMapper.selectOne(
new QueryWrapper<Refunds>().eq("refund_number", refundNumber));
} catch (BusinessException e) {
throw e;
} catch (Exception e) {
throw new BusinessException(ErrorCode.DATABASE_ERROR, "查询退款记录失败", e);
}
}
@Override
public boolean createRefund(Refunds refunds) {
if (ValidateUtil.isEmpty(refunds)) {
throw new BusinessException(ErrorCode.MISSING_PARAM, "退款信息不能为空");
}
if (ValidateUtil.isEmpty(refunds.getOrderId())) {
throw new BusinessException(ErrorCode.MISSING_PARAM, "订单ID不能为空");
}
if (refunds.getRefundAmount() == null) {
throw new BusinessException(ErrorCode.MISSING_PARAM, "退款金额不能为空");
}
// 生成退款单号 基于时间戳 + 随机数 / 序列号(最常用)
refunds.setRefundNo(RefundNumberFenerator.generateRefundNumber());
try {
int result = refundsMapper.insert(refunds);
return result > 0;
} catch (BusinessException e) {
throw e;
} catch (Exception e) {
throw new BusinessException(ErrorCode.DATABASE_ERROR, "创建退款记录失败", e);
}
}
@Override
public boolean updateRefund(Refunds refunds) {
if (ValidateUtil.isEmpty(refunds)) {
throw new BusinessException(ErrorCode.MISSING_PARAM, "退款信息不能为空");
}
if (ValidateUtil.isEmpty(refunds.getId())) {
throw new BusinessException(ErrorCode.MISSING_PARAM, "退款ID不能为空");
}
try {
// 检查退款记录是否存在
Refunds existing = refundsMapper.selectById(refunds.getId());
if (existing == null) {
throw new BusinessException(ErrorCode.NOT_FOUND, "退款记录不存在");
}
int result = refundsMapper.updateById(refunds);
return result > 0;
} catch (BusinessException e) {
throw e;
} catch (Exception e) {
throw new BusinessException(ErrorCode.DATABASE_ERROR, "更新退款记录失败", e);
}
}
@Override
public boolean deleteRefund(Long id) {
if (ValidateUtil.isEmpty(id)) {
throw new BusinessException(ErrorCode.MISSING_PARAM, "退款ID不能为空");
}
try {
// 检查退款记录是否存在
Refunds existing = refundsMapper.selectById(id);
if (existing == null) {
throw new BusinessException(ErrorCode.NOT_FOUND, "退款记录不存在");
}
int result = refundsMapper.deleteById(id);
return result > 0;
} catch (BusinessException e) {
throw e;
} catch (Exception e) {
throw new BusinessException(ErrorCode.DATABASE_ERROR, "删除退款记录失败", e);
}
}
@Override
public Refunds getRefundById(Long id) {
if (ValidateUtil.isEmpty(id)) {
throw new BusinessException(ErrorCode.MISSING_PARAM, "退款ID不能为空");
}
try {
Refunds refund = refundsMapper.selectById(id);
if (refund == null) {
throw new BusinessException(ErrorCode.NOT_FOUND, "退款记录不存在");
}
return refund;
} catch (BusinessException e) {
throw e;
} catch (Exception e) {
throw new BusinessException(ErrorCode.DATABASE_ERROR, "查询退款记录失败", e);
}
}
@Override
public List<Refunds> getRefundsByUserId(Long userId) {
if (ValidateUtil.isEmpty(userId)) {
throw new BusinessException(ErrorCode.MISSING_PARAM, "用户ID不能为空");
}
try {
return refundsMapper.selectList(
new QueryWrapper<Refunds>().eq("user_id", userId));
} catch (BusinessException e) {
throw e;
} catch (Exception e) {
throw new BusinessException(ErrorCode.DATABASE_ERROR, "查询退款记录失败", e);
}
}
@Override
public List<Refunds> getRefundsByStatus(Integer status) {
if (ValidateUtil.isEmpty(status)) {
throw new BusinessException(ErrorCode.MISSING_PARAM, "退款状态不能为空");
}
try {
return refundsMapper.selectList(
new QueryWrapper<Refunds>().eq("status", status));
} catch (BusinessException e) {
throw e;
} catch (Exception e) {
throw new BusinessException(ErrorCode.DATABASE_ERROR, "查询退款记录失败", e);
}
}
@Override
public boolean updateRefundStatus(Long refundId, Integer status) {
if (ValidateUtil.isEmpty(refundId)) {
throw new BusinessException(ErrorCode.MISSING_PARAM, "退款ID不能为空");
}
if (ValidateUtil.isEmpty(status)) {
throw new BusinessException(ErrorCode.MISSING_PARAM, "退款状态不能为空");
}
try {
// 检查退款记录是否存在
Refunds existing = refundsMapper.selectById(refundId);
if (existing == null) {
throw new BusinessException(ErrorCode.NOT_FOUND, "退款记录不存在");
}
// 更新状态
existing.setRefundStatus(status);
int result = refundsMapper.updateById(existing);
return result > 0;
} catch (BusinessException e) {
throw e;
} catch (Exception e) {
throw new BusinessException(ErrorCode.DATABASE_ERROR, "更新退款状态失败", e);
}
}
@Override
public List<Refunds> listRefundsByPage(int page, int size) {
if (page < 1) {
throw new BusinessException(ErrorCode.INVALID_PARAM, "页码不能小于1");
}
if (size < 1 || size > 100) {
throw new BusinessException(ErrorCode.INVALID_PARAM, "每页数量必须在1-100之间");
}
try {
Page<Refunds> refundPage = new Page<>(page, size);
Page<Refunds> resultPage = refundsMapper.selectPage(refundPage, null);
return resultPage.getRecords();
} catch (BusinessException e) {
throw e;
} catch (Exception e) {
throw new BusinessException(ErrorCode.DATABASE_ERROR, "分页查询退款记录失败", e);
}
}
}

View File

@@ -0,0 +1,212 @@
package com.qf.backend.service.impl;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qf.backend.entity.RolePermissions;
import com.qf.backend.exception.BusinessException;
import com.qf.backend.exception.ErrorCode;
import com.qf.backend.mapper.RolePermissionsMapper;
import com.qf.backend.service.RolePermissionsService;
import com.qf.backend.util.ValidateUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.List;
/**
* 角色权限关联服务实现类
*/
@Service
public class RolePermissionsServiceImpl extends ServiceImpl<RolePermissionsMapper, RolePermissions> implements RolePermissionsService {
@Autowired
private RolePermissionsMapper rolePermissionsMapper;
@Override
public List<RolePermissions> getRolePermissionsByRoleId(Long roleId) {
if (ValidateUtil.isEmpty(roleId)) {
throw new BusinessException(ErrorCode.MISSING_PARAM, "角色ID不能为空");
}
try {
return rolePermissionsMapper.selectList(
new QueryWrapper<RolePermissions>().eq("role_id", roleId));
} catch (BusinessException e) {
throw e;
} catch (Exception e) {
throw new BusinessException(ErrorCode.DATABASE_ERROR, "查询角色权限关联失败", e);
}
}
@Override
public List<RolePermissions> getRolePermissionsByPermissionId(Long permissionId) {
if (ValidateUtil.isEmpty(permissionId)) {
throw new BusinessException(ErrorCode.MISSING_PARAM, "权限ID不能为空");
}
try {
return rolePermissionsMapper.selectList(
new QueryWrapper<RolePermissions>().eq("permission_id", permissionId));
} catch (BusinessException e) {
throw e;
} catch (Exception e) {
throw new BusinessException(ErrorCode.DATABASE_ERROR, "查询角色权限关联失败", e);
}
}
@Override
public boolean addPermissionToRole(Long roleId, Long permissionId) {
if (ValidateUtil.isEmpty(roleId)) {
throw new BusinessException(ErrorCode.MISSING_PARAM, "角色ID不能为空");
}
if (ValidateUtil.isEmpty(permissionId)) {
throw new BusinessException(ErrorCode.MISSING_PARAM, "权限ID不能为空");
}
try {
// 检查是否已经存在该关联关系
RolePermissions existing = rolePermissionsMapper.selectOne(
new QueryWrapper<RolePermissions>()
.eq("role_id", roleId)
.eq("permission_id", permissionId));
if (existing != null) {
throw new BusinessException(ErrorCode.BUSINESS_ERROR, "该角色已拥有此权限");
}
RolePermissions rolePermission = new RolePermissions();
rolePermission.setRoleId(roleId);
rolePermission.setPermissionId(permissionId);
int result = rolePermissionsMapper.insert(rolePermission);
return result > 0;
} catch (BusinessException e) {
throw e;
} catch (Exception e) {
throw new BusinessException(ErrorCode.DATABASE_ERROR, "添加角色权限关联失败", e);
}
}
@Override
public boolean removePermissionFromRole(Long roleId, Long permissionId) {
if (ValidateUtil.isEmpty(roleId)) {
throw new BusinessException(ErrorCode.MISSING_PARAM, "角色ID不能为空");
}
if (ValidateUtil.isEmpty(permissionId)) {
throw new BusinessException(ErrorCode.MISSING_PARAM, "权限ID不能为空");
}
try {
// 检查关联关系是否存在
RolePermissions existing = rolePermissionsMapper.selectOne(
new QueryWrapper<RolePermissions>()
.eq("role_id", roleId)
.eq("permission_id", permissionId));
if (existing == null) {
throw new BusinessException(ErrorCode.BUSINESS_ERROR, "角色与权限的关联关系不存在");
}
int result = rolePermissionsMapper.delete(
new QueryWrapper<RolePermissions>()
.eq("role_id", roleId)
.eq("permission_id", permissionId));
return result > 0;
} catch (BusinessException e) {
throw e;
} catch (Exception e) {
throw new BusinessException(ErrorCode.DATABASE_ERROR, "移除角色权限关联失败", e);
}
}
@Override
public boolean batchAddPermissionsToRole(Long roleId, List<Long> permissionIds) {
if (ValidateUtil.isEmpty(roleId)) {
throw new BusinessException(ErrorCode.MISSING_PARAM, "角色ID不能为空");
}
if (ValidateUtil.isEmpty(permissionIds)) {
throw new BusinessException(ErrorCode.MISSING_PARAM, "权限ID列表不能为空");
}
if (permissionIds.isEmpty()) {
throw new BusinessException(ErrorCode.MISSING_PARAM, "权限ID列表不能为空");
}
try {
for (Long permissionId : permissionIds) {
if (ValidateUtil.isEmpty(permissionId)) {
throw new BusinessException(ErrorCode.INVALID_PARAM, "权限ID列表中存在空值");
}
// 检查是否已经存在该关联关系
RolePermissions existing = rolePermissionsMapper.selectOne(
new QueryWrapper<RolePermissions>()
.eq("role_id", roleId)
.eq("permission_id", permissionId));
if (existing == null) {
RolePermissions rolePermission = new RolePermissions();
rolePermission.setRoleId(roleId);
rolePermission.setPermissionId(permissionId);
rolePermissionsMapper.insert(rolePermission);
}
}
return true;
} catch (BusinessException e) {
throw e;
} catch (Exception e) {
throw new BusinessException(ErrorCode.DATABASE_ERROR, "批量添加角色权限关联失败", e);
}
}
@Override
public boolean clearRolePermissions(Long roleId) {
if (ValidateUtil.isEmpty(roleId)) {
throw new BusinessException(ErrorCode.MISSING_PARAM, "角色ID不能为空");
}
try {
// 检查角色是否有权限关联
List<RolePermissions> existingPermissions = rolePermissionsMapper.selectList(
new QueryWrapper<RolePermissions>().eq("role_id", roleId));
if (existingPermissions.isEmpty()) {
throw new BusinessException(ErrorCode.BUSINESS_ERROR, "该角色没有关联的权限");
}
int result = rolePermissionsMapper.delete(
new QueryWrapper<RolePermissions>().eq("role_id", roleId));
return result > 0;
} catch (BusinessException e) {
throw e;
} catch (Exception e) {
throw new BusinessException(ErrorCode.DATABASE_ERROR, "清除角色权限关联失败", e);
}
}
@Override
public boolean checkRoleHasPermission(Long roleId, Long permissionId) {
if (ValidateUtil.isEmpty(roleId)) {
throw new BusinessException(ErrorCode.MISSING_PARAM, "角色ID不能为空");
}
if (ValidateUtil.isEmpty(permissionId)) {
throw new BusinessException(ErrorCode.MISSING_PARAM, "权限ID不能为空");
}
try {
RolePermissions rolePermission = rolePermissionsMapper.selectOne(
new QueryWrapper<RolePermissions>()
.eq("role_id", roleId)
.eq("permission_id", permissionId));
return rolePermission != null;
} catch (BusinessException e) {
throw e;
} catch (Exception e) {
throw new BusinessException(ErrorCode.DATABASE_ERROR, "检查角色权限关系失败", e);
}
}
@Override
public List<Long> listPermissionIdsByRoleId(Long roleId) {
if (ValidateUtil.isEmpty(roleId)) {
throw new BusinessException(ErrorCode.MISSING_PARAM, "角色ID不能为空");
}
try {
List<RolePermissions> rolePermissions = rolePermissionsMapper.selectList(
new QueryWrapper<RolePermissions>().eq("role_id", roleId));
List<Long> permissionIds = new ArrayList<>();
for (RolePermissions rp : rolePermissions) {
permissionIds.add(rp.getPermissionId());
}
return permissionIds;
} catch (BusinessException e) {
throw e;
} catch (Exception e) {
throw new BusinessException(ErrorCode.DATABASE_ERROR, "查询角色权限ID列表失败", e);
}
}
}

View File

@@ -7,14 +7,22 @@ package com.qf.backend.service.impl;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qf.backend.dto.Result;
import com.qf.backend.entity.Roles;
import com.qf.backend.exception.BusinessException;
import com.qf.backend.exception.ErrorCode;
import com.qf.backend.mapper.RolesMapper;
import com.qf.backend.service.RolesService;
import com.qf.backend.util.ResultUtils;
import com.qf.backend.util.ValidateUtil;
/**
*
@@ -23,66 +31,224 @@ import com.qf.backend.service.RolesService;
@Service
public class RolesServiceImpl extends ServiceImpl<RolesMapper, Roles> implements RolesService {
private static final Logger logger = LoggerFactory.getLogger(RolesServiceImpl.class);
@Autowired
private RolesMapper rolesMapper;
// 根据角色名称查询角色
@Override
public Roles getRoleByName(String roleName) {
public Result<Roles> getRoleByName(String roleName) {
logger.info("根据角色名称查询角色: {}", roleName);
// 参数校验
if (ValidateUtil.isEmpty(roleName)) {
throw new BusinessException(ErrorCode.MISSING_PARAM, "角色名称不能为空");
}
try {
if (roleName == null) {
return null;
Roles role = rolesMapper.selectOne(new QueryWrapper<Roles>().eq("role_name", roleName));
if (role == null) {
logger.warn("角色 {} 不存在", roleName);
throw new BusinessException(ErrorCode.ROLE_NOT_FOUND, "角色不存在: " + roleName);
}
Roles roles = rolesMapper.selectOne(new QueryWrapper<Roles>().eq("role_name", roleName));
if (roles == null) {
return null;
}
return roles;
return ResultUtils.success(role);
} catch (BusinessException e) {
throw e;
} catch (Exception e) {
return null;
logger.error("查询角色失败: {}", e.getMessage(), e);
throw new BusinessException(ErrorCode.DATABASE_ERROR, "查询角色失败: " + e.getMessage(), e);
}
}
// 查询所有角色
@Override
public List<Roles> listAllRoles() {
public Result<Boolean> createRole(Roles roles) {
logger.info("创建角色: {}", roles);
throw new UnsupportedOperationException("Unimplemented method 'listAllRoles'");
try {
// 使用ValidateUtil进行实体验证
ValidateUtil.validateEntity(roles, "roleName");
// 检查角色名称是否已存在
Roles existingRole = rolesMapper.selectOne(new QueryWrapper<Roles>().eq("role_name", roles.getRoleName()));
if (existingRole != null) {
throw new BusinessException(ErrorCode.BUSINESS_ERROR, "角色名称已存在: " + roles.getRoleName());
}
int result = rolesMapper.insert(roles);
if (result <= 0) {
throw new BusinessException(ErrorCode.BUSINESS_ERROR, "创建角色失败");
}
return ResultUtils.success(true);
} catch (IllegalArgumentException e) {
// 转换为业务异常
throw new BusinessException(ErrorCode.INVALID_PARAM, e.getMessage());
} catch (IllegalAccessException e) {
logger.error("验证角色信息失败: {}", e.getMessage(), e);
throw new BusinessException(ErrorCode.BUSINESS_ERROR, "验证角色信息失败: " + e.getMessage(), e);
} catch (BusinessException e) {
throw e;
} catch (Exception e) {
logger.error("创建角色失败: {}", e.getMessage(), e);
throw new BusinessException(ErrorCode.DATABASE_ERROR, "创建角色失败: " + e.getMessage(), e);
}
}
// 根据ID查询角色
@Override
public Roles getRoleById(Long id) {
throw new UnsupportedOperationException("Unimplemented method 'getRoleById'");
@Override
public Result<Boolean> updateRole(Roles roles) {
logger.info("更新角色: {}", roles);
try {
// 检查角色ID是否为空
if (roles == null || roles.getId() == null) {
throw new BusinessException(ErrorCode.MISSING_PARAM, "角色信息或角色ID不能为空");
}
// 使用ValidateUtil进行实体验证
ValidateUtil.validateEntity(roles, "roleName");
// 检查角色是否存在
Roles existingRole = rolesMapper.selectById(roles.getId());
if (existingRole == null) {
throw new BusinessException(ErrorCode.ROLE_NOT_FOUND, "角色不存在");
}
// 检查角色名称是否与其他角色重复
Roles nameConflictRole = rolesMapper.selectOne(
new QueryWrapper<Roles>().eq("role_name", roles.getRoleName()).ne("id", roles.getId())
);
if (nameConflictRole != null) {
throw new BusinessException(ErrorCode.BUSINESS_ERROR, "角色名称已存在: " + roles.getRoleName());
}
rolesMapper.updateInfo(roles, new UpdateWrapper<Roles>().eq("id", roles.getId()));
return ResultUtils.success(true);
} catch (IllegalArgumentException e) {
// 转换为业务异常
throw new BusinessException(ErrorCode.INVALID_PARAM, e.getMessage());
} catch (IllegalAccessException e) {
logger.error("验证角色信息失败: {}", e.getMessage(), e);
throw new BusinessException(ErrorCode.BUSINESS_ERROR, "验证角色信息失败: " + e.getMessage(), e);
} catch (BusinessException e) {
throw e;
} catch (Exception e) {
logger.error("更新角色失败: {}", e.getMessage(), e);
throw new BusinessException(ErrorCode.DATABASE_ERROR, "更新角色失败: " + e.getMessage(), e);
}
}
// 根据用户ID查询角色
@Override
public List<Roles> listRolesByUserId(Long userId) {
throw new UnsupportedOperationException("Unimplemented method 'listRolesByUserId'");
@Override
public Result<Boolean> deleteRole(Long id) {
logger.info("删除角色: {}", id);
// 参数校验
if (id == null) {
throw new BusinessException(ErrorCode.MISSING_PARAM, "角色ID不能为空");
}
try {
// 检查角色是否存在
Roles role = rolesMapper.selectById(id);
if (role == null) {
throw new BusinessException(ErrorCode.ROLE_NOT_FOUND, "角色不存在");
}
// 删除角色
int result = rolesMapper.deleteById(id);
if (result <= 0) {
throw new BusinessException(ErrorCode.BUSINESS_ERROR, "删除角色失败");
}
return ResultUtils.success(true);
} catch (BusinessException e) {
throw e;
} catch (Exception e) {
logger.error("删除角色失败: {}", e.getMessage(), e);
throw new BusinessException(ErrorCode.DATABASE_ERROR, "删除角色失败: " + e.getMessage(), e);
}
}
// 创建角色
@Override
public boolean createRole(Roles roles) {
throw new UnsupportedOperationException("Unimplemented method 'createRole'");
@Override
public Result<List<Roles>> listAllRoles() {
logger.info("查询所有角色");
try {
List<Roles> rolesList = rolesMapper.selectList(null);
return ResultUtils.success(rolesList);
} catch (Exception e) {
logger.error("查询所有角色失败: {}", e.getMessage(), e);
throw new BusinessException(ErrorCode.DATABASE_ERROR, "查询所有角色失败: " + e.getMessage(), e);
}
}
// 更新角色
@Override
public boolean updateRole(Roles roles) {
throw new UnsupportedOperationException("Unimplemented method 'updateRole'");
@Override
public Result<Roles> getRoleById(Long id) {
logger.info("根据ID查询角色: {}", id);
// 参数校验
if (id == null) {
throw new BusinessException(ErrorCode.MISSING_PARAM, "角色ID不能为空");
}
try {
Roles role = rolesMapper.selectById(id);
if (role == null) {
throw new BusinessException(ErrorCode.ROLE_NOT_FOUND, "角色不存在");
}
return ResultUtils.success(role);
} catch (BusinessException e) {
throw e;
} catch (Exception e) {
logger.error("查询角色失败: {}", e.getMessage(), e);
throw new BusinessException(ErrorCode.DATABASE_ERROR, "查询角色失败: " + e.getMessage(), e);
}
}
// 批量删除角色
@Override
public boolean batchDeleteRoles(List<Long> ids) {
throw new UnsupportedOperationException("Unimplemented method 'batchDeleteRoles'");
@Override
public Result<Boolean> batchDeleteRoles(List<Long> ids) {
logger.info("批量删除角色: {}", ids);
// 参数校验
if (ids == null || ids.isEmpty()) {
throw new BusinessException(ErrorCode.MISSING_PARAM, "角色ID列表不能为空");
}
try {
// 检查所有角色是否存在
for (Long id : ids) {
Roles role = rolesMapper.selectById(id);
if (role == null) {
throw new BusinessException(ErrorCode.ROLE_NOT_FOUND, "角色不存在: " + id);
}
}
int result = rolesMapper.deleteBatchIds(ids);
if (result <= 0) {
throw new BusinessException(ErrorCode.BUSINESS_ERROR, "批量删除角色失败");
}
return ResultUtils.success(true);
} catch (BusinessException e) {
throw e;
} catch (Exception e) {
logger.error("批量删除角色失败: {}", e.getMessage(), e);
throw new BusinessException(ErrorCode.DATABASE_ERROR, "批量删除角色失败: " + e.getMessage(), e);
}
}
// 删除角色
@Override
public boolean deleteRole(Long id) {
throw new UnsupportedOperationException("Unimplemented method 'deleteRole'");
@Override
public Result<List<Roles>> listRolesByUserId(Long userId) {
logger.info("查询用户角色: 用户ID = {}", userId);
// 参数校验
if (userId == null) {
throw new BusinessException(ErrorCode.MISSING_PARAM, "用户ID不能为空");
}
try {
List<Roles> rolesList = rolesMapper.selectList(new QueryWrapper<Roles>().inSql("id", "select role_id from user_roles where user_id = " + userId));
return ResultUtils.success(rolesList);
} catch (Exception e) {
logger.error("查询用户角色失败: {}", e.getMessage(), e);
throw new BusinessException(ErrorCode.DATABASE_ERROR, "查询用户角色失败: " + e.getMessage(), e);
}
}
}

View File

@@ -0,0 +1,282 @@
package com.qf.backend.service.impl;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qf.backend.dto.Result;
import com.qf.backend.entity.ShopCategories;
import com.qf.backend.exception.BusinessException;
import com.qf.backend.exception.ErrorCode;
import com.qf.backend.mapper.ShopCategoriesMapper;
import com.qf.backend.service.ShopCategoriesService;
import com.qf.backend.util.ResultUtils;
import com.qf.backend.util.ValidateUtil;
@Service
public class ShopCategoriesServiceImpl extends ServiceImpl<ShopCategoriesMapper, ShopCategories> implements ShopCategoriesService {
private static final Logger logger = LoggerFactory.getLogger(ShopCategoriesServiceImpl.class);
@Autowired
private ShopCategoriesMapper shopCategoriesMapper;
@Override
public Result<ShopCategories> getCategoryByName(String categoryName) {
logger.info("根据分类名称查询分类: {}", categoryName);
try {
if (ValidateUtil.isEmpty(categoryName)) {
throw new BusinessException(ErrorCode.INVALID_PARAM, "分类名称不能为空");
}
ShopCategories category = shopCategoriesMapper.selectOne(new QueryWrapper<ShopCategories>().eq("category_name", categoryName));
if (category == null) {
throw new BusinessException(ErrorCode.NOT_FOUND, "分类不存在: " + categoryName);
}
return ResultUtils.success(category);
} catch (BusinessException e) {
throw e;
} catch (Exception e) {
logger.error("查询分类失败: {}", e.getMessage(), e);
throw new BusinessException(ErrorCode.DATABASE_ERROR, "查询分类失败: " + e.getMessage(), e);
}
}
@Override
public Result<List<ShopCategories>> getSubCategoriesByParentId(Long parentId) {
logger.info("根据父分类ID查询子分类: {}", parentId);
try {
if (parentId == null) {
throw new BusinessException(ErrorCode.MISSING_PARAM, "父分类ID不能为空");
}
List<ShopCategories> subCategories = shopCategoriesMapper.selectList(new QueryWrapper<ShopCategories>().eq("parent_id", parentId));
return ResultUtils.success(subCategories);
} catch (BusinessException e) {
throw e;
} catch (Exception e) {
logger.error("查询子分类失败: {}", e.getMessage(), e);
throw new BusinessException(ErrorCode.DATABASE_ERROR, "查询子分类失败: " + e.getMessage(), e);
}
}
@Override
public Result<Boolean> createCategory(ShopCategories shopCategories) {
logger.info("创建分类: 分类对象");
try {
// 使用ValidateUtil进行实体验证
ValidateUtil.validateEntity(shopCategories, "categoryName");
int result = shopCategoriesMapper.insert(shopCategories);
if (result <= 0) {
throw new BusinessException(ErrorCode.BUSINESS_ERROR, "创建分类失败");
}
logger.info("分类创建成功");
return ResultUtils.success(true);
} catch (IllegalArgumentException e) {
// 转换为业务异常
throw new BusinessException(ErrorCode.INVALID_PARAM, e.getMessage());
} catch (IllegalAccessException e) {
logger.error("验证分类信息失败: {}", e.getMessage(), e);
throw new BusinessException(ErrorCode.BUSINESS_ERROR, "验证分类信息失败: " + e.getMessage(), e);
} catch (BusinessException e) {
throw e;
} catch (Exception e) {
logger.error("创建分类失败: {}", e.getMessage(), e);
throw new BusinessException(ErrorCode.DATABASE_ERROR, "创建分类失败: " + e.getMessage(), e);
}
}
@Override
public Result<Boolean> updateCategory(ShopCategories shopCategories) {
logger.info("更新分类信息: 分类ID = {}", shopCategories.getId());
try {
if (shopCategories == null || shopCategories.getId() == null) {
throw new BusinessException(ErrorCode.MISSING_PARAM, "分类信息或分类ID不能为空");
}
// 检查分类是否存在
ShopCategories existingCategory = getCategoryByIdAndCheckExist(shopCategories.getId());
if (existingCategory == null) {
throw new BusinessException(ErrorCode.NOT_FOUND, "分类不存在");
}
// 使用ValidateUtil进行实体验证
ValidateUtil.validateEntity(shopCategories, "categoryName");
// 更新分类信息
int result = shopCategoriesMapper.updateById(shopCategories);
if (result <= 0) {
throw new BusinessException(ErrorCode.BUSINESS_ERROR, "更新分类信息失败");
}
logger.info("分类信息更新成功: 分类ID = {}", shopCategories.getId());
return ResultUtils.success(true);
} catch (IllegalArgumentException e) {
// 转换为业务异常
throw new BusinessException(ErrorCode.INVALID_PARAM, e.getMessage());
} catch (IllegalAccessException e) {
logger.error("验证分类信息失败: {}", e.getMessage(), e);
throw new BusinessException(ErrorCode.BUSINESS_ERROR, "验证分类信息失败: " + e.getMessage(), e);
} catch (BusinessException e) {
throw e;
} catch (Exception e) {
logger.error("更新分类信息失败: {}", e.getMessage(), e);
throw new BusinessException(ErrorCode.DATABASE_ERROR, "更新分类信息失败: " + e.getMessage(), e);
}
}
@Override
public Result<Boolean> deleteCategory(Long id) {
logger.info("删除分类: 分类ID = {}", id);
try {
if (id == null) {
throw new BusinessException(ErrorCode.MISSING_PARAM, "分类ID不能为空");
}
// 检查分类是否存在
ShopCategories category = getCategoryByIdAndCheckExist(id);
if (category == null) {
throw new BusinessException(ErrorCode.NOT_FOUND, "分类不存在");
}
// 检查是否有子分类
List<ShopCategories> subCategories = shopCategoriesMapper.selectList(new QueryWrapper<ShopCategories>().eq("parent_id", id));
if (subCategories != null && !subCategories.isEmpty()) {
throw new BusinessException(ErrorCode.BUSINESS_ERROR, "该分类下存在子分类,无法删除");
}
int result = shopCategoriesMapper.deleteById(id);
if (result <= 0) {
throw new BusinessException(ErrorCode.BUSINESS_ERROR, "删除分类失败");
}
logger.info("分类删除成功: 分类ID = {}", id);
return ResultUtils.success(true);
} catch (BusinessException e) {
throw e;
} catch (Exception e) {
logger.error("删除分类失败: {}", e.getMessage(), e);
throw new BusinessException(ErrorCode.DATABASE_ERROR, "删除分类失败: " + e.getMessage(), e);
}
}
@Override
public Result<List<ShopCategories>> listRootCategories() {
logger.info("查询所有根分类");
try {
// 查询父分类ID为0或null的分类
List<ShopCategories> rootCategories = shopCategoriesMapper.selectList(new QueryWrapper<ShopCategories>().isNull("parent_id").or().eq("parent_id", 0));
logger.info("查询到 {} 个根分类", rootCategories.size());
return ResultUtils.success(rootCategories);
} catch (Exception e) {
logger.error("查询根分类失败: {}", e.getMessage(), e);
throw new BusinessException(ErrorCode.DATABASE_ERROR, "查询根分类失败: " + e.getMessage(), e);
}
}
@Override
public Result<ShopCategories> getCategoryById(Long id) {
logger.info("根据ID查询分类: 分类ID = {}", id);
try {
if (id == null) {
throw new BusinessException(ErrorCode.MISSING_PARAM, "分类ID不能为空");
}
ShopCategories category = getCategoryByIdAndCheckExist(id);
if (category == null) {
throw new BusinessException(ErrorCode.NOT_FOUND, "分类不存在");
}
return ResultUtils.success(category);
} catch (BusinessException e) {
throw e;
} catch (Exception e) {
logger.error("查询分类失败: {}", e.getMessage(), e);
throw new BusinessException(ErrorCode.DATABASE_ERROR, "查询分类失败: " + e.getMessage(), e);
}
}
@Override
public Result<Boolean> batchDeleteCategories(List<Long> ids) {
logger.info("批量删除分类: 分类ID列表 = {}", ids);
try {
if (ids == null || ids.isEmpty()) {
throw new BusinessException(ErrorCode.MISSING_PARAM, "分类ID列表不能为空");
}
// 检查所有分类是否存在且没有子分类
for (Long id : ids) {
ShopCategories category = getCategoryByIdAndCheckExist(id);
if (category == null) {
throw new BusinessException(ErrorCode.NOT_FOUND, "分类不存在: " + id);
}
// 检查是否有子分类
List<ShopCategories> subCategories = shopCategoriesMapper.selectList(new QueryWrapper<ShopCategories>().eq("parent_id", id));
if (subCategories != null && !subCategories.isEmpty()) {
throw new BusinessException(ErrorCode.BUSINESS_ERROR, "分类 " + id + " 下存在子分类,无法删除");
}
}
int result = shopCategoriesMapper.deleteBatchIds(ids);
if (result <= 0) {
throw new BusinessException(ErrorCode.BUSINESS_ERROR, "批量删除分类失败");
}
logger.info("批量删除分类成功: 删除了 {} 个分类", result);
return ResultUtils.success(true);
} catch (BusinessException e) {
throw e;
} catch (Exception e) {
logger.error("批量删除分类失败: {}", e.getMessage(), e);
throw new BusinessException(ErrorCode.DATABASE_ERROR, "批量删除分类失败: " + e.getMessage(), e);
}
}
@Override
public Result<List<ShopCategories>> listAllCategoriesWithTree() {
logger.info("查询所有分类(树形结构)");
try {
// 查询所有分类
List<ShopCategories> allCategories = shopCategoriesMapper.selectList(null);
// TODO: 实现树形结构转换逻辑
// 这里简单返回所有分类,实际项目中需要将分类转换为树形结构
logger.info("查询到 {} 个分类", allCategories.size());
return ResultUtils.success(allCategories);
} catch (Exception e) {
logger.error("查询分类树形结构失败: {}", e.getMessage(), e);
throw new BusinessException(ErrorCode.DATABASE_ERROR, "查询分类树形结构失败: " + e.getMessage(), e);
}
}
/**
* 根据分类ID查询分类并检查是否存在
* @param id 分类ID
* @return 分类对象如果分类不存在则返回null
*/
private ShopCategories getCategoryByIdAndCheckExist(Long id) {
if (id == null) {
return null;
}
QueryWrapper<ShopCategories> queryWrapper = new QueryWrapper<ShopCategories>().eq("id", id);
return shopCategoriesMapper.selectOne(queryWrapper);
}
}

View File

@@ -0,0 +1,373 @@
package com.qf.backend.service.impl;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qf.backend.dto.Result;
import com.qf.backend.entity.ShopRatings;
import com.qf.backend.exception.BusinessException;
import com.qf.backend.exception.ErrorCode;
import com.qf.backend.mapper.ShopRatingsMapper;
import com.qf.backend.service.ShopRatingsService;
import com.qf.backend.util.ResultUtils;
import com.qf.backend.util.ValidateUtil;
@Service
public class ShopRatingsServiceImpl extends ServiceImpl<ShopRatingsMapper, ShopRatings> implements ShopRatingsService {
private static final Logger logger = LoggerFactory.getLogger(ShopRatingsServiceImpl.class);
@Autowired
private ShopRatingsMapper shopRatingsMapper;
// 根据店铺ID查询评分
@Override
public Result<List<ShopRatings>> getRatingsByShopId(Long shopId) {
logger.info("根据店铺ID查询评分: {}", shopId);
try {
if (shopId == null) {
throw new BusinessException(ErrorCode.MISSING_PARAM, "店铺ID不能为空");
}
QueryWrapper<ShopRatings> queryWrapper = new QueryWrapper<ShopRatings>().eq("shop_id", shopId);
List<ShopRatings> ratingsList = shopRatingsMapper.selectList(queryWrapper);
logger.info("查询到 {} 个评分", ratingsList.size());
return ResultUtils.success(ratingsList);
} catch (BusinessException e) {
throw e;
} catch (Exception e) {
logger.error("查询评分失败: {}", e.getMessage(), e);
throw new BusinessException(ErrorCode.DATABASE_ERROR, "查询评分失败: " + e.getMessage(), e);
}
}
// 根据用户ID查询评分
@Override
public Result<List<ShopRatings>> getRatingsByUserId(Long userId) {
logger.info("根据用户ID查询评分: {}", userId);
try {
if (userId == null) {
throw new BusinessException(ErrorCode.MISSING_PARAM, "用户ID不能为空");
}
QueryWrapper<ShopRatings> queryWrapper = new QueryWrapper<ShopRatings>().eq("user_id", userId);
List<ShopRatings> ratingsList = shopRatingsMapper.selectList(queryWrapper);
logger.info("查询到 {} 个评分", ratingsList.size());
return ResultUtils.success(ratingsList);
} catch (BusinessException e) {
throw e;
} catch (Exception e) {
logger.error("查询评分失败: {}", e.getMessage(), e);
throw new BusinessException(ErrorCode.DATABASE_ERROR, "查询评分失败: " + e.getMessage(), e);
}
}
// 创建评分
@Override
public Result<Boolean> createRating(ShopRatings shopRatings) {
logger.info("创建评分: 评分对象");
try {
// 使用ValidateUtil进行实体验证
ValidateUtil.validateEntity(shopRatings, "shopId", "userId", "rating");
// 检查评分范围
if (shopRatings.getRating() < 1 || shopRatings.getRating() > 5) {
throw new BusinessException(ErrorCode.INVALID_PARAM, "评分必须在1-5之间");
}
int result = shopRatingsMapper.insert(shopRatings);
if (result <= 0) {
throw new BusinessException(ErrorCode.BUSINESS_ERROR, "创建评分失败");
}
logger.info("评分创建成功");
return ResultUtils.success(true);
} catch (IllegalArgumentException e) {
// 转换为业务异常
throw new BusinessException(ErrorCode.INVALID_PARAM, e.getMessage());
} catch (IllegalAccessException e) {
logger.error("验证评分信息失败: {}", e.getMessage(), e);
throw new BusinessException(ErrorCode.BUSINESS_ERROR, "验证评分信息失败: " + e.getMessage(), e);
} catch (BusinessException e) {
throw e;
} catch (Exception e) {
logger.error("创建评分失败: {}", e.getMessage(), e);
throw new BusinessException(ErrorCode.DATABASE_ERROR, "创建评分失败: " + e.getMessage(), e);
}
}
// 更新评分信息
@Override
public Result<Boolean> updateRating(ShopRatings shopRatings) {
logger.info("更新评分信息: 评分ID = {}", shopRatings.getId());
try {
if (shopRatings == null || shopRatings.getId() == null) {
throw new BusinessException(ErrorCode.MISSING_PARAM, "评分信息或评分ID不能为空");
}
// 检查评分是否存在
ShopRatings existingRating = getRatingByIdAndCheckExist(shopRatings.getId());
if (existingRating == null) {
throw new BusinessException(ErrorCode.NOT_FOUND, "评分不存在");
}
// 使用ValidateUtil进行实体验证
ValidateUtil.validateEntity(shopRatings, "shopId", "userId", "rating");
// 检查评分范围
if (shopRatings.getRating() < 1 || shopRatings.getRating() > 5) {
throw new BusinessException(ErrorCode.INVALID_PARAM, "评分必须在1-5之间");
}
// 更新评分信息
int result = shopRatingsMapper.updateById(shopRatings);
if (result <= 0) {
throw new BusinessException(ErrorCode.BUSINESS_ERROR, "更新评分信息失败");
}
logger.info("评分信息更新成功: 评分ID = {}", shopRatings.getId());
return ResultUtils.success(true);
} catch (IllegalArgumentException e) {
// 转换为业务异常
throw new BusinessException(ErrorCode.INVALID_PARAM, e.getMessage());
} catch (IllegalAccessException e) {
logger.error("验证评分信息失败: {}", e.getMessage(), e);
throw new BusinessException(ErrorCode.BUSINESS_ERROR, "验证评分信息失败: " + e.getMessage(), e);
} catch (BusinessException e) {
throw e;
} catch (Exception e) {
logger.error("更新评分信息失败: {}", e.getMessage(), e);
throw new BusinessException(ErrorCode.DATABASE_ERROR, "更新评分信息失败: " + e.getMessage(), e);
}
}
// 删除评分
@Override
public Result<Boolean> deleteRating(Long id) {
logger.info("删除评分: 评分ID = {}", id);
try {
if (id == null) {
throw new BusinessException(ErrorCode.MISSING_PARAM, "评分ID不能为空");
}
// 检查评分是否存在
ShopRatings rating = getRatingByIdAndCheckExist(id);
if (rating == null) {
throw new BusinessException(ErrorCode.NOT_FOUND, "评分不存在");
}
int result = shopRatingsMapper.deleteById(id);
if (result <= 0) {
throw new BusinessException(ErrorCode.BUSINESS_ERROR, "删除评分失败");
}
logger.info("评分删除成功: 评分ID = {}", id);
return ResultUtils.success(true);
} catch (BusinessException e) {
throw e;
} catch (Exception e) {
logger.error("删除评分失败: {}", e.getMessage(), e);
throw new BusinessException(ErrorCode.DATABASE_ERROR, "删除评分失败: " + e.getMessage(), e);
}
}
// 根据评分ID查询评分
@Override
public Result<ShopRatings> getRatingById(Long id) {
logger.info("根据ID查询评分: 评分ID = {}", id);
try {
if (id == null) {
throw new BusinessException(ErrorCode.MISSING_PARAM, "评分ID不能为空");
}
ShopRatings rating = getRatingByIdAndCheckExist(id);
if (rating == null) {
throw new BusinessException(ErrorCode.NOT_FOUND, "评分不存在");
}
return ResultUtils.success(rating);
} catch (BusinessException e) {
throw e;
} catch (Exception e) {
logger.error("查询评分失败: {}", e.getMessage(), e);
throw new BusinessException(ErrorCode.DATABASE_ERROR, "查询评分失败: " + e.getMessage(), e);
}
}
// 获取店铺平均评分
@Override
public Result<Double> getAverageRatingByShopId(Long shopId) {
logger.info("获取店铺平均评分: 店铺ID = {}", shopId);
try {
if (shopId == null) {
throw new BusinessException(ErrorCode.MISSING_PARAM, "店铺ID不能为空");
}
// 使用QueryWrapper查询所有评分
QueryWrapper<ShopRatings> queryWrapper = new QueryWrapper<ShopRatings>().eq("shop_id", shopId);
List<ShopRatings> ratingsList = shopRatingsMapper.selectList(queryWrapper);
// 计算平均评分
Double averageRating = 0.0;
if (ratingsList != null && !ratingsList.isEmpty()) {
int totalRating = 0;
for (ShopRatings rating : ratingsList) {
totalRating += rating.getRating();
}
averageRating = (double) totalRating / ratingsList.size();
}
logger.info("店铺平均评分: {}", averageRating);
return ResultUtils.success(averageRating);
} catch (BusinessException e) {
throw e;
} catch (Exception e) {
logger.error("获取店铺平均评分失败: {}", e.getMessage(), e);
throw new BusinessException(ErrorCode.DATABASE_ERROR, "获取店铺平均评分失败: " + e.getMessage(), e);
}
}
// 获取店铺评分数量
@Override
public Result<Integer> getRatingCountByShopId(Long shopId) {
logger.info("获取店铺评分数量: 店铺ID = {}", shopId);
try {
if (shopId == null) {
throw new BusinessException(ErrorCode.MISSING_PARAM, "店铺ID不能为空");
}
// 使用QueryWrapper查询评分数量
QueryWrapper<ShopRatings> queryWrapper = new QueryWrapper<ShopRatings>().eq("shop_id", shopId);
Long ratingCount = shopRatingsMapper.selectCount(queryWrapper);
logger.info("店铺评分数量: {}", ratingCount);
return ResultUtils.success(ratingCount != null ? ratingCount.intValue() : 0);
} catch (BusinessException e) {
throw e;
} catch (Exception e) {
logger.error("获取店铺评分数量失败: {}", e.getMessage(), e);
throw new BusinessException(ErrorCode.DATABASE_ERROR, "获取店铺评分数量失败: " + e.getMessage(), e);
}
}
// 根据评分星级查询店铺评分
@Override
public Result<List<ShopRatings>> getRatingsByShopIdAndRating(Long shopId, Integer rating) {
logger.info("根据评分星级查询店铺评分: 店铺ID = {}, 评分 = {}", shopId, rating);
try {
if (shopId == null) {
throw new BusinessException(ErrorCode.MISSING_PARAM, "店铺ID不能为空");
}
if (rating == null) {
throw new BusinessException(ErrorCode.MISSING_PARAM, "评分不能为空");
}
// 检查评分范围
if (rating < 1 || rating > 5) {
throw new BusinessException(ErrorCode.INVALID_PARAM, "评分必须在1-5之间");
}
QueryWrapper<ShopRatings> queryWrapper = new QueryWrapper<ShopRatings>()
.eq("shop_id", shopId)
.eq("rating", rating);
List<ShopRatings> ratingsList = shopRatingsMapper.selectList(queryWrapper);
logger.info("查询到 {} 个评分", ratingsList.size());
return ResultUtils.success(ratingsList);
} catch (BusinessException e) {
throw e;
} catch (Exception e) {
logger.error("根据评分星级查询店铺评分失败: {}", e.getMessage(), e);
throw new BusinessException(ErrorCode.DATABASE_ERROR, "根据评分星级查询店铺评分失败: " + e.getMessage(), e);
}
}
// 检查用户是否已对店铺评分
@Override
public Result<Boolean> checkUserHasRated(Long shopId, Long userId) {
logger.info("检查用户是否已对店铺评分: 店铺ID = {}, 用户ID = {}", shopId, userId);
try {
if (shopId == null) {
throw new BusinessException(ErrorCode.MISSING_PARAM, "店铺ID不能为空");
}
if (userId == null) {
throw new BusinessException(ErrorCode.MISSING_PARAM, "用户ID不能为空");
}
QueryWrapper<ShopRatings> queryWrapper = new QueryWrapper<ShopRatings>()
.eq("shop_id", shopId)
.eq("user_id", userId);
ShopRatings rating = shopRatingsMapper.selectOne(queryWrapper);
boolean hasRated = rating != null;
logger.info("用户是否已评分: {}", hasRated);
return ResultUtils.success(hasRated);
} catch (BusinessException e) {
throw e;
} catch (Exception e) {
logger.error("检查用户是否已对店铺评分失败: {}", e.getMessage(), e);
throw new BusinessException(ErrorCode.DATABASE_ERROR, "检查用户是否已对店铺评分失败: " + e.getMessage(), e);
}
}
// 分页查询店铺评分
@Override
public Result<List<ShopRatings>> listRatingsByShopIdAndPage(Long shopId, int page, int size) {
logger.info("分页查询店铺评分: 店铺ID = {}, 页码 = {}, 每页大小 = {}", shopId, page, size);
try {
if (shopId == null) {
throw new BusinessException(ErrorCode.MISSING_PARAM, "店铺ID不能为空");
}
// 参数校验
if (page < 1) {
throw new BusinessException(ErrorCode.INVALID_PARAM, "页码不能小于1");
}
if (size < 1 || size > 100) {
throw new BusinessException(ErrorCode.INVALID_PARAM, "每页大小必须在1-100之间");
}
// 使用MyBatis-Plus的分页功能
Page<ShopRatings> ratingPage = new Page<>(page, size);
QueryWrapper<ShopRatings> queryWrapper = new QueryWrapper<ShopRatings>().eq("shop_id", shopId);
Page<ShopRatings> resultPage = shopRatingsMapper.selectPage(ratingPage, queryWrapper);
logger.info("分页查询成功: 共 {} 条记录, 第 {} 页", resultPage.getTotal(), page);
return ResultUtils.success(resultPage.getRecords());
} catch (BusinessException e) {
throw e;
} catch (Exception e) {
logger.error("分页查询店铺评分失败: {}", e.getMessage(), e);
throw new BusinessException(ErrorCode.DATABASE_ERROR, "分页查询店铺评分失败: " + e.getMessage(), e);
}
}
/**
* 根据评分ID查询评分并检查是否存在
* @param id 评分ID
* @return 评分对象如果评分不存在则返回null
*/
private ShopRatings getRatingByIdAndCheckExist(Long id) {
if (id == null) {
return null;
}
QueryWrapper<ShopRatings> queryWrapper = new QueryWrapper<ShopRatings>().eq("id", id);
return shopRatingsMapper.selectOne(queryWrapper);
}
}

View File

@@ -0,0 +1,335 @@
package com.qf.backend.service.impl;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qf.backend.dto.Result;
import com.qf.backend.entity.Shops;
import com.qf.backend.exception.BusinessException;
import com.qf.backend.exception.ErrorCode;
import com.qf.backend.mapper.ShopsMapper;
import com.qf.backend.service.ShopsService;
import com.qf.backend.util.ResultUtils;
import com.qf.backend.util.ValidateUtil;
@Service
public class ShopsServiceImpl extends ServiceImpl<ShopsMapper, Shops> implements ShopsService {
private static final Logger logger = LoggerFactory.getLogger(ShopsServiceImpl.class);
@Autowired
private ShopsMapper shopsMapper;
// 根据店铺名称查询店铺
@Override
public Result<List<Shops>> getShopsByName(String shopName) {
logger.info("根据店铺名称查询店铺: {}", shopName);
try {
if (ValidateUtil.isEmpty(shopName)) {
throw new BusinessException(ErrorCode.INVALID_PARAM, "店铺名称不能为空");
}
QueryWrapper<Shops> queryWrapper = new QueryWrapper<Shops>().like("shop_name", shopName);
List<Shops> shopsList = shopsMapper.selectList(queryWrapper);
logger.info("查询到 {} 个店铺", shopsList.size());
return ResultUtils.success(shopsList);
} catch (BusinessException e) {
throw e;
} catch (Exception e) {
logger.error("查询店铺失败: {}", e.getMessage(), e);
throw new BusinessException(ErrorCode.DATABASE_ERROR, "查询店铺失败: " + e.getMessage(), e);
}
}
// 根据用户ID查询店铺
@Override
public Result<Shops> getShopByUserId(Long userId) {
logger.info("根据用户ID查询店铺: {}", userId);
try {
if (userId == null) {
throw new BusinessException(ErrorCode.MISSING_PARAM, "用户ID不能为空");
}
QueryWrapper<Shops> queryWrapper = new QueryWrapper<Shops>().eq("user_id", userId);
Shops shop = shopsMapper.selectOne(queryWrapper);
if (shop == null) {
throw new BusinessException(ErrorCode.SHOP_NOT_FOUND, "店铺不存在: 用户ID = " + userId);
}
return ResultUtils.success(shop);
} catch (BusinessException e) {
throw e;
} catch (Exception e) {
logger.error("查询店铺失败: {}", e.getMessage(), e);
throw new BusinessException(ErrorCode.DATABASE_ERROR, "查询店铺失败: " + e.getMessage(), e);
}
}
// 创建店铺
@Override
public Result<Boolean> createShop(Shops shops) {
logger.info("创建店铺: 店铺对象");
try {
// 使用ValidateUtil进行实体验证
ValidateUtil.validateEntity(shops, "shopName", "userId", "categoryId");
int result = shopsMapper.insert(shops);
if (result <= 0) {
throw new BusinessException(ErrorCode.BUSINESS_ERROR, "创建店铺失败");
}
logger.info("店铺创建成功");
return ResultUtils.success(true);
} catch (IllegalArgumentException e) {
// 转换为业务异常
throw new BusinessException(ErrorCode.INVALID_PARAM, e.getMessage());
} catch (IllegalAccessException e) {
logger.error("验证店铺信息失败: {}", e.getMessage(), e);
throw new BusinessException(ErrorCode.BUSINESS_ERROR, "验证店铺信息失败: " + e.getMessage(), e);
} catch (BusinessException e) {
throw e;
} catch (Exception e) {
logger.error("创建店铺失败: {}", e.getMessage(), e);
throw new BusinessException(ErrorCode.DATABASE_ERROR, "创建店铺失败: " + e.getMessage(), e);
}
}
// 更新店铺信息
@Override
public Result<Boolean> updateShop(Shops shops) {
logger.info("更新店铺信息: 店铺ID = {}", shops.getId());
try {
if (shops == null || shops.getId() == null) {
throw new BusinessException(ErrorCode.MISSING_PARAM, "店铺信息或店铺ID不能为空");
}
// 检查店铺是否存在
Shops existingShop = getShopByIdAndCheckExist(shops.getId());
if (existingShop == null) {
throw new BusinessException(ErrorCode.SHOP_NOT_FOUND, "店铺不存在");
}
// 使用ValidateUtil进行实体验证
ValidateUtil.validateEntity(shops, "shopName", "categoryId");
// 更新店铺信息
int result = shopsMapper.updateById(shops);
if (result <= 0) {
throw new BusinessException(ErrorCode.BUSINESS_ERROR, "更新店铺信息失败");
}
logger.info("店铺信息更新成功: 店铺ID = {}", shops.getId());
return ResultUtils.success(true);
} catch (IllegalArgumentException e) {
// 转换为业务异常
throw new BusinessException(ErrorCode.INVALID_PARAM, e.getMessage());
} catch (IllegalAccessException e) {
logger.error("验证店铺信息失败: {}", e.getMessage(), e);
throw new BusinessException(ErrorCode.BUSINESS_ERROR, "验证店铺信息失败: " + e.getMessage(), e);
} catch (BusinessException e) {
throw e;
} catch (Exception e) {
logger.error("更新店铺信息失败: {}", e.getMessage(), e);
throw new BusinessException(ErrorCode.DATABASE_ERROR, "更新店铺信息失败: " + e.getMessage(), e);
}
}
// 删除店铺
@Override
public Result<Boolean> deleteShop(Long id) {
logger.info("删除店铺: 店铺ID = {}", id);
try {
if (id == null) {
throw new BusinessException(ErrorCode.MISSING_PARAM, "店铺ID不能为空");
}
// 检查店铺是否存在
Shops shop = getShopByIdAndCheckExist(id);
if (shop == null) {
throw new BusinessException(ErrorCode.SHOP_NOT_FOUND, "店铺不存在");
}
int result = shopsMapper.deleteById(id);
if (result <= 0) {
throw new BusinessException(ErrorCode.BUSINESS_ERROR, "删除店铺失败");
}
logger.info("店铺删除成功: 店铺ID = {}", id);
return ResultUtils.success(true);
} catch (BusinessException e) {
throw e;
} catch (Exception e) {
logger.error("删除店铺失败: {}", e.getMessage(), e);
throw new BusinessException(ErrorCode.DATABASE_ERROR, "删除店铺失败: " + e.getMessage(), e);
}
}
// 根据店铺ID查询店铺
@Override
public Result<Shops> getShopById(Long id) {
logger.info("根据ID查询店铺: 店铺ID = {}", id);
try {
if (id == null) {
throw new BusinessException(ErrorCode.MISSING_PARAM, "店铺ID不能为空");
}
Shops shop = getShopByIdAndCheckExist(id);
if (shop == null) {
throw new BusinessException(ErrorCode.SHOP_NOT_FOUND, "店铺不存在");
}
return ResultUtils.success(shop);
} catch (BusinessException e) {
throw e;
} catch (Exception e) {
logger.error("查询店铺失败: {}", e.getMessage(), e);
throw new BusinessException(ErrorCode.DATABASE_ERROR, "查询店铺失败: " + e.getMessage(), e);
}
}
// 分页查询店铺
@Override
public Result<List<Shops>> listShopsByPage(int page, int size) {
logger.info("分页查询店铺: 页码 = {}, 每页大小 = {}", page, size);
try {
// 参数校验
if (page < 1) {
throw new BusinessException(ErrorCode.INVALID_PARAM, "页码不能小于1");
}
if (size < 1 || size > 100) {
throw new BusinessException(ErrorCode.INVALID_PARAM, "每页大小必须在1-100之间");
}
// 使用MyBatis-Plus的分页功能
Page<Shops> shopPage = new Page<>(page, size);
Page<Shops> resultPage = shopsMapper.selectPage(shopPage, null);
logger.info("分页查询成功: 共 {} 条记录, 第 {} 页", resultPage.getTotal(), page);
return ResultUtils.success(resultPage.getRecords());
} catch (BusinessException e) {
throw e;
} catch (Exception e) {
logger.error("分页查询店铺失败: {}", e.getMessage(), e);
throw new BusinessException(ErrorCode.DATABASE_ERROR, "分页查询店铺失败: " + e.getMessage(), e);
}
}
// 根据店铺分类ID查询店铺
@Override
public Result<List<Shops>> getShopsByCategoryId(Long categoryId) {
logger.info("根据店铺分类ID查询店铺: 分类ID = {}", categoryId);
try {
if (categoryId == null) {
throw new BusinessException(ErrorCode.MISSING_PARAM, "分类ID不能为空");
}
QueryWrapper<Shops> queryWrapper = new QueryWrapper<Shops>().eq("category_id", categoryId);
List<Shops> shopsList = shopsMapper.selectList(queryWrapper);
logger.info("查询到 {} 个店铺", shopsList.size());
return ResultUtils.success(shopsList);
} catch (BusinessException e) {
throw e;
} catch (Exception e) {
logger.error("根据分类ID查询店铺失败: {}", e.getMessage(), e);
throw new BusinessException(ErrorCode.DATABASE_ERROR, "根据分类ID查询店铺失败: " + e.getMessage(), e);
}
}
// 更新店铺状态
@Override
public Result<Boolean> updateShopStatus(Long shopId, Integer status) {
logger.info("更新店铺状态: 店铺ID = {}, 状态 = {}", shopId, status);
try {
if (shopId == null) {
throw new BusinessException(ErrorCode.MISSING_PARAM, "店铺ID不能为空");
}
if (status == null) {
throw new BusinessException(ErrorCode.MISSING_PARAM, "店铺状态不能为空");
}
// 检查店铺是否存在
Shops shop = getShopByIdAndCheckExist(shopId);
if (shop == null) {
throw new BusinessException(ErrorCode.SHOP_NOT_FOUND, "店铺不存在");
}
// 更新店铺状态
shop.setStatus(status);
int result = shopsMapper.updateById(shop);
if (result <= 0) {
throw new BusinessException(ErrorCode.BUSINESS_ERROR, "更新店铺状态失败");
}
logger.info("店铺状态更新成功: 店铺ID = {}, 新状态 = {}", shopId, status);
return ResultUtils.success(true);
} catch (BusinessException e) {
throw e;
} catch (Exception e) {
logger.error("更新店铺状态失败: {}", e.getMessage(), e);
throw new BusinessException(ErrorCode.DATABASE_ERROR, "更新店铺状态失败: " + e.getMessage(), e);
}
}
// 搜索店铺
@Override
public Result<List<Shops>> searchShops(String keyword, int page, int size) {
logger.info("搜索店铺: 关键词 = {}, 页码 = {}, 每页大小 = {}", keyword, page, size);
try {
if (ValidateUtil.isEmpty(keyword)) {
throw new BusinessException(ErrorCode.INVALID_PARAM, "搜索关键词不能为空");
}
// 参数校验
if (page < 1) {
throw new BusinessException(ErrorCode.INVALID_PARAM, "页码不能小于1");
}
if (size < 1 || size > 100) {
throw new BusinessException(ErrorCode.INVALID_PARAM, "每页大小必须在1-100之间");
}
// 使用MyBatis-Plus的分页功能
Page<Shops> shopPage = new Page<>(page, size);
QueryWrapper<Shops> queryWrapper = new QueryWrapper<Shops>()
.like("shop_name", keyword)
.or().like("description", keyword);
Page<Shops> resultPage = shopsMapper.selectPage(shopPage, queryWrapper);
logger.info("搜索成功: 共 {} 条记录, 第 {} 页", resultPage.getTotal(), page);
return ResultUtils.success(resultPage.getRecords());
} catch (BusinessException e) {
throw e;
} catch (Exception e) {
logger.error("搜索店铺失败: {}", e.getMessage(), e);
throw new BusinessException(ErrorCode.DATABASE_ERROR, "搜索店铺失败: " + e.getMessage(), e);
}
}
/**
* 根据店铺ID查询店铺并检查是否存在
* @param id 店铺ID
* @return 店铺对象如果店铺不存在则返回null
*/
private Shops getShopByIdAndCheckExist(Long id) {
if (id == null) {
return null;
}
QueryWrapper<Shops> queryWrapper = new QueryWrapper<Shops>().eq("id", id);
return shopsMapper.selectOne(queryWrapper);
}
}

View File

@@ -0,0 +1,87 @@
package com.qf.backend.service.impl;
import java.util.ArrayList;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import com.qf.backend.dto.Result;
import com.qf.backend.entity.Roles;
import com.qf.backend.entity.UserRoles;
import com.qf.backend.entity.Users;
import com.qf.backend.service.RolesService;
import com.qf.backend.service.UserRolesService;
import com.qf.backend.service.UsersService;
/**
* UserDetailsService实现类用于从数据库中加载用户信息
* 该类实现了Spring Security的UserDetailsService接口用于根据用户名加载用户信息
*/
@Service
public class UserDetailsServiceImpl implements UserDetailsService {
/**
* 注入用户服务,用于查询用户信息
*/
@Autowired
private UsersService usersService;
@Autowired
private UserRolesService userRolesService;
@Autowired
private RolesService RolesService;
/**
* 根据用户名加载用户信息
* @param username 用户名
* @return UserDetails 用户详情对象,包含用户名、密码、权限等信息
* @throws UsernameNotFoundException 如果用户名不存在
*/
@Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
// 1. 从数据库中查询用户
Result<Users> result = usersService.getUserByUsername(username);
if (result == null || result.getData() == null) {
throw new UsernameNotFoundException("用户名不存在: " + username);
}
Users user = result.getData();
// 2. 构建权限列表(这里简化处理,实际应从数据库中查询用户的角色和权限)
List<GrantedAuthority> authorities = new ArrayList<>();
// 查询用户角色关联
Result<List<UserRoles>> userRoleResultList = userRolesService.getUserRolesByUserId(user.getId());
if (userRoleResultList == null || userRoleResultList.getData() == null) {
throw new UsernameNotFoundException("用户角色不存在: " + user.getId());
}
// 3. 查询角色权限
for (UserRoles userRole : userRoleResultList.getData()) {
Result<Roles> roleResult = RolesService.getRoleById(userRole.getRoleId());
if (roleResult == null || roleResult.getData() == null) {
throw new UsernameNotFoundException("权限不存在: " + userRole.getRoleId());
}
Roles role = roleResult.getData();
// 4. 转换为Spring Security的GrantedAuthority对象
authorities.add(new SimpleGrantedAuthority("ROLE_" + role.getRoleName().toUpperCase()));
}
// 3. 返回UserDetails对象
// 注意:在实际应用中,密码应该加密存储,这里直接使用明文密码(仅用于演示)
return User.builder()
.username(user.getUsername()) // 用户名
.password(user.getPassword()) // 密码需要加密存储,这里直接使用明文密码(仅用于演示)
.authorities(authorities) // 假设用户默认拥有USER权限
.accountExpired(false) // 假设账号永不过期
.accountLocked(false) // 假设账号永不过期
.credentialsExpired(false) // 假设密码永不过期
.disabled(user.getStatus() == 0) // 假设status为0表示禁用
.build();
}
}

View File

@@ -0,0 +1,117 @@
/*
* Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license
* Click nbfs://nbhost/SystemFileSystem/Templates/Classes/Class.java to edit this template
*/
package com.qf.backend.service.impl;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.qf.backend.dto.LoginResponse;
import com.qf.backend.dto.Result;
import com.qf.backend.entity.Permissions;
import com.qf.backend.entity.Roles;
import com.qf.backend.entity.UserRoles;
import com.qf.backend.entity.Users;
import com.qf.backend.exception.ErrorCode;
import com.qf.backend.service.PermissionsService;
import com.qf.backend.service.RolePermissionsService;
import com.qf.backend.service.RolesService;
import com.qf.backend.service.UserLoginService;
import com.qf.backend.service.UserRolesService;
import com.qf.backend.service.UsersService;
import com.qf.backend.util.ResultUtils;
import com.qf.backend.util.ValidateUtil;
/**
*
* @author 30803
*/
@Service
public class UserLoginServiceImpl implements UserLoginService {
private Logger logger = LoggerFactory.getLogger(UserLoginServiceImpl.class);
@Autowired
private UsersService usersServiceImpl;
@Autowired
private UserRolesService userRolesServiceImpl;
@Autowired
private RolesService rolesServiceImpl;
@Autowired
private RolePermissionsService rolePermissionsServiceImpl;
@Autowired
private PermissionsService permissionsServiceImpl;
/**
* 用户登录
* @param username 用户名
* @param password 密码
* @return 登录结果
*/
@Override
public Result<LoginResponse> login(String username, String password) {
logger.info("用户登录,用户名:{}", username);
// 1. 校验用户名和密码是否为空
try{
if (ValidateUtil.isEmpty(username) || ValidateUtil.isEmpty(password)) {
throw new IllegalArgumentException("用户名或密码不能为空");
}
// 2. 登录
Result<Users> result = usersServiceImpl.login(username, password);
if (result == null || result.getData() == null) {
throw new IllegalArgumentException("用户名不存在或密码错误");
}
Users user = result.getData();
// 3. 获取用户角色
Result<List<UserRoles>> userRolesResult = userRolesServiceImpl.getUserRolesByUserId(user.getId());
if (userRolesResult == null || userRolesResult.getData() == null) {
throw new IllegalArgumentException("获取用户角色失败");
}
List<UserRoles> userRoles = userRolesResult.getData();
Set<String> roleNames = new HashSet<>();
Set<Long> roleIds = new HashSet<>();
// 4. 获取角色名称和角色ID
for (UserRoles ur : userRoles) {
Roles role = rolesServiceImpl.getById(ur.getRoleId());
if (role != null) {
roleNames.add(String.valueOf(role.getRoleType()));
roleIds.add(role.getId());
}
}
// 5. 获取用户权限
Set<String> permissionCodes = new HashSet<>();
for (Long roleId : roleIds) {
List<Long> permissionIds = rolePermissionsServiceImpl.listPermissionIdsByRoleId(roleId);
for (Long permissionId : permissionIds) {
Permissions permission = permissionsServiceImpl.getById(permissionId);
if (permission != null) {
permissionCodes.add(permission.getPermissionCode());
}
}
}
// 6. 构建LoginResponse对象
LoginResponse loginResponse = new LoginResponse();
loginResponse.setUsername(user.getUsername());
loginResponse.setRoles(new ArrayList<>(roleNames));
loginResponse.setPermissions(new ArrayList<>(permissionCodes));
return ResultUtils.success(loginResponse);
} catch (Exception e) {
logger.error("用户登录失败,用户名:{}", username, e);
return ResultUtils.fail(ErrorCode.SYSTEM_ERROR, e.getMessage());
}
}
}

View File

@@ -0,0 +1,174 @@
/*
* Click nbfs://nbhost/SystemFileSystem/Templates/Licenses/license-default.txt to change this license
* Click nbfs://nbhost/SystemFileSystem/Templates/Classes/Class.java to edit this template
*/
package com.qf.backend.service.impl;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qf.backend.dto.Result;
import com.qf.backend.entity.UserRoles;
import com.qf.backend.exception.BusinessException;
import com.qf.backend.exception.ErrorCode;
import com.qf.backend.mapper.UserRolesMapper;
import com.qf.backend.service.UserRolesService;
import com.qf.backend.util.ResultUtils;
/**
*
* @author 30803
*/
@Service
public class UsersRolesServiceImpl extends ServiceImpl<UserRolesMapper, UserRoles> implements UserRolesService {
@Autowired
private UserRolesMapper userRolesMapper;
@Override
public Result<List<UserRoles>> getUserRolesByUserId(Long userId) {
if (userId == null) {
throw new BusinessException(ErrorCode.MISSING_PARAM, "用户ID不能为空");
}
try {
List<UserRoles> userRoles = userRolesMapper.selectList(new QueryWrapper<UserRoles>().eq("user_id", userId));
return ResultUtils.success(userRoles);
} catch (BusinessException e) {
throw e;
} catch (Exception e) {
throw new BusinessException(ErrorCode.DATABASE_ERROR, "查询用户角色信息失败", e);
}
}
@Override
public Result<List<UserRoles>> getUserRolesByRoleId(Long roleId) {
if (roleId == null) {
throw new BusinessException(ErrorCode.MISSING_PARAM, "角色ID不能为空");
}
try {
List<UserRoles> userRoles = userRolesMapper.selectList(new QueryWrapper<UserRoles>().eq("role_id", roleId));
return ResultUtils.success(userRoles);
} catch (BusinessException e) {
throw e;
} catch (Exception e) {
throw new BusinessException(ErrorCode.DATABASE_ERROR, "查询角色用户信息失败", e);
}
}
@Override
public Result<Boolean> addRoleToUser(Long userId, Long roleId) {
if (userId == null || roleId == null) {
throw new BusinessException(ErrorCode.MISSING_PARAM, "用户ID和角色ID不能为空");
}
try {
// 检查是否已经存在该关联关系
UserRoles existing = userRolesMapper.selectOne(new QueryWrapper<UserRoles>().eq("user_id", userId).eq("role_id", roleId));
if (existing != null) {
throw new BusinessException(ErrorCode.BUSINESS_ERROR, "用户已拥有该角色");
}
UserRoles userRoles = new UserRoles();
userRoles.setUserId(userId);
userRoles.setRoleId(roleId);
int result = userRolesMapper.insert(userRoles);
return ResultUtils.success(result > 0);
} catch (BusinessException e) {
throw e;
} catch (Exception e) {
throw new BusinessException(ErrorCode.DATABASE_ERROR, "添加用户角色关联失败", e);
}
}
@Override
public Result<Boolean> removeRoleFromUser(Long userId, Long roleId) {
if (userId == null || roleId == null) {
throw new BusinessException(ErrorCode.MISSING_PARAM, "用户ID和角色ID不能为空");
}
try {
// 检查关联关系是否存在
UserRoles existing = userRolesMapper.selectOne(new QueryWrapper<UserRoles>().eq("user_id", userId).eq("role_id", roleId));
if (existing == null) {
throw new BusinessException(ErrorCode.BUSINESS_ERROR, "用户与角色的关联关系不存在");
}
int result = userRolesMapper.delete(new QueryWrapper<UserRoles>().eq("user_id", userId).eq("role_id", roleId));
return ResultUtils.success(result > 0);
} catch (BusinessException e) {
throw e;
} catch (Exception e) {
throw new BusinessException(ErrorCode.DATABASE_ERROR, "移除用户角色关联失败", e);
}
}
@Override
public Result<Boolean> batchAddRolesToUser(Long userId, List<Long> roleIds) {
if (userId == null) {
throw new BusinessException(ErrorCode.MISSING_PARAM, "用户ID不能为空");
}
if (roleIds == null || roleIds.isEmpty()) {
throw new BusinessException(ErrorCode.MISSING_PARAM, "角色ID列表不能为空");
}
try {
for (Long roleId : roleIds) {
if (roleId == null) {
throw new BusinessException(ErrorCode.INVALID_PARAM, "角色ID列表中存在空值");
}
// 检查是否已经存在该关联关系
UserRoles existing = userRolesMapper.selectOne(new QueryWrapper<UserRoles>().eq("user_id", userId).eq("role_id", roleId));
if (existing == null) {
UserRoles userRoles = new UserRoles();
userRoles.setUserId(userId);
userRoles.setRoleId(roleId);
userRolesMapper.insert(userRoles);
}
}
return ResultUtils.success(true);
} catch (BusinessException e) {
throw e;
} catch (Exception e) {
throw new BusinessException(ErrorCode.DATABASE_ERROR, "批量添加用户角色关联失败", e);
}
}
@Override
public Result<Boolean> clearUserRoles(Long userId) {
if (userId == null) {
throw new BusinessException(ErrorCode.MISSING_PARAM, "用户ID不能为空");
}
try {
// 检查用户是否有角色关联
List<UserRoles> existingRoles = userRolesMapper.selectList(new QueryWrapper<UserRoles>().eq("user_id", userId));
if (existingRoles.isEmpty()) {
throw new BusinessException(ErrorCode.BUSINESS_ERROR, "该用户没有关联的角色");
}
int result = userRolesMapper.delete(new QueryWrapper<UserRoles>().eq("user_id", userId));
return ResultUtils.success(result > 0);
} catch (BusinessException e) {
throw e;
} catch (Exception e) {
throw new BusinessException(ErrorCode.DATABASE_ERROR, "清除用户角色关联失败", e);
}
}
@Override
public Result<Boolean> checkUserHasRole(Long userId, Long roleId) {
if (userId == null || roleId == null) {
throw new BusinessException(ErrorCode.MISSING_PARAM, "用户ID和角色ID不能为空");
}
try {
// 修改selectInfo为selectOne因为selectInfo方法可能不存在
UserRoles userRoles = userRolesMapper.selectOne(new QueryWrapper<UserRoles>().eq("user_id", userId).eq("role_id", roleId));
return ResultUtils.success(userRoles != null);
} catch (BusinessException e) {
throw e;
} catch (Exception e) {
throw new BusinessException(ErrorCode.DATABASE_ERROR, "检查用户角色关系失败", e);
}
}
}

View File

@@ -2,190 +2,331 @@ package com.qf.backend.service.impl;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qf.backend.common.Result;
import com.qf.backend.common.ResultUtils;
import com.qf.backend.dto.Result;
import com.qf.backend.entity.Users;
import com.qf.backend.exception.BusinessException;
import com.qf.backend.exception.ErrorCode;
import com.qf.backend.mapper.UsersMapper;
import com.qf.backend.service.UsersService;
import com.qf.backend.util.ResultUtils;
import com.qf.backend.util.ValidateUtil;
@Service
public class UsersServiceImpl extends ServiceImpl<UsersMapper, Users> implements UsersService {
private static final Logger logger = LoggerFactory.getLogger(UsersServiceImpl.class);
@Autowired
private UsersMapper usersMapper;
// 根据用户名查询用户
@Override
public Result<Users> getUserByUsername(String username) {
logger.info("根据用户名查询用户: {}", username);
try {
if (username == null || username.isEmpty()) {
return ResultUtils.fail(ErrorCode.INVALID_PARAM);
if (ValidateUtil.isEmpty(username)) {
throw new BusinessException(ErrorCode.INVALID_PARAM, "用户名不能为空");
}
Users users = usersMapper.selectByUsername(username);
if (users == null) {
return ResultUtils.fail(ErrorCode.USER_NOT_FOUND);
throw new BusinessException(ErrorCode.USER_NOT_FOUND, "用户不存在: " + username);
}
return ResultUtils.success(users);
} catch (BusinessException e) {
throw e;
} catch (Exception e) {
return ResultUtils.fail(ErrorCode.DATABASE_ERROR);
logger.error("查询用户失败: {}", e.getMessage(), e);
throw new BusinessException(ErrorCode.DATABASE_ERROR, "查询用户失败: " + e.getMessage(), e);
}
}
// 根据邮箱查询用户
@Override
public Result<Users> getUserByEmail(String email) {
logger.info("根据邮箱查询用户: {}", email);
try {
if (email == null || email.isEmpty()) {
return ResultUtils.fail(ErrorCode.INVALID_PARAM);
if (ValidateUtil.isEmpty(email)) {
throw new BusinessException(ErrorCode.INVALID_PARAM, "邮箱不能为空");
}
// 使用ValidateUtil进行邮箱格式校验
if (!ValidateUtil.isValidEmail(email)) {
throw new BusinessException(ErrorCode.INVALID_PARAM, "邮箱格式不正确");
}
Users users = usersMapper.selectByEmail(email);
if (users == null) {
return ResultUtils.fail(ErrorCode.USER_NOT_FOUND);
throw new BusinessException(ErrorCode.USER_NOT_FOUND, "用户不存在: " + email);
}
return ResultUtils.success(users);
} catch (BusinessException e) {
throw e;
} catch (Exception e) {
return ResultUtils.fail(ErrorCode.DATABASE_ERROR);
logger.error("查询用户失败: {}", e.getMessage(), e);
throw new BusinessException(ErrorCode.DATABASE_ERROR, "查询用户失败: " + e.getMessage(), e);
}
}
// 登录
@Override
public Result<Users> login(String username, String password) {
logger.info("登录: 用户名 = {}", username);
try {
if (ValidateUtil.isEmpty(username) || ValidateUtil.isEmpty(password)) {
throw new BusinessException(ErrorCode.INVALID_PARAM, "用户名或密码不能为空");
}
// 根据用户名查询用户
Users user = usersMapper.selectByUsername(username);
if (user == null) {
throw new BusinessException(ErrorCode.USER_NOT_FOUND, "用户名不存在或密码错误");
}
// 使用BCryptPasswordEncoder验证密码
BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
if (!passwordEncoder.matches(password, user.getPassword())) {
throw new BusinessException(ErrorCode.USER_NOT_FOUND, "用户名不存在或密码错误");
}
return ResultUtils.success(user);
} catch (BusinessException e) {
throw e;
} catch (Exception e) {
logger.error("登录失败: {}", e.getMessage(), e);
throw new BusinessException(ErrorCode.DATABASE_ERROR, "登录失败: " + e.getMessage(), e);
}
}
//创建用户
@Override
public Result<Boolean> createUser(Users users) {
logger.info("创建用户: 用户对象");
try {
// 调用封装的验证方法
Result<Boolean> validationResult = validateUserBeforeCreate(users);
if (validationResult != null) {
return validationResult;
}
// 使用ValidateUtil进行实体验证
ValidateUtil.validateEntity(users, "username", "email", "password");
// 加密密码
users.setPassword(new BCryptPasswordEncoder().encode(users.getPassword()));
int result = usersMapper.insert(users);
if (result <= 0) {
return ResultUtils.fail(ErrorCode.DATABASE_ERROR);
throw new BusinessException(ErrorCode.BUSINESS_ERROR, "创建用户失败");
}
return ResultUtils.success();
logger.info("用户创建成功");
return ResultUtils.success(true);
} catch (IllegalArgumentException e) {
// 转换为业务异常
throw new BusinessException(ErrorCode.INVALID_PARAM, e.getMessage());
} catch (IllegalAccessException e) {
logger.error("验证用户信息失败: {}", e.getMessage(), e);
throw new BusinessException(ErrorCode.BUSINESS_ERROR, "验证用户信息失败: " + e.getMessage(), e);
} catch (BusinessException e) {
throw e;
} catch (Exception e) {
return ResultUtils.fail(ErrorCode.DATABASE_ERROR);
logger.error("创建用户失败: {}", e.getMessage(), e);
throw new BusinessException(ErrorCode.DATABASE_ERROR, "创建用户失败: " + e.getMessage(), e);
}
}
// 更新用户信息
@Override
public Result<Boolean> updateUser(Users users) {
logger.info("更新用户信息: 用户ID = {}", users.getId());
try {
// 调用封装的验证方法
Result<Boolean> validationResult = validateUserBeforeCreate(users);
if (validationResult != null) {
return validationResult;
if (users == null || users.getId() == null) {
throw new BusinessException(ErrorCode.MISSING_PARAM, "用户信息或用户ID不能为空");
}
// 更新用户信息
int result = usersMapper.updateInfo(users, new UpdateWrapper<Users>().set("username", users.getUsername()).set("email", users.getEmail()).set("phone", users.getPhone()).set("avatar", users.getAvatar()).eq("id", users.getId()));
// 检查用户是否存在
Users existingUser = getUserByIdAndCheckExist(users.getId());
if (existingUser == null) {
throw new BusinessException(ErrorCode.USER_NOT_FOUND, "用户不存在");
}
// 使用ValidateUtil进行实体验证
ValidateUtil.validateEntity(users, "username", "email");
// 更新用户信息,不包含密码更新
int result = usersMapper.updateInfo(users, new UpdateWrapper<Users>()
.set("username", users.getUsername())
.set("email", users.getEmail())
.set("phone", users.getPhone())
.set("avatar", users.getAvatar())
.eq("id", users.getId()));
if (result <= 0) {
return ResultUtils.fail(ErrorCode.DATABASE_ERROR);
throw new BusinessException(ErrorCode.BUSINESS_ERROR, "更新用户信息失败");
}
return ResultUtils.success();
logger.info("用户信息更新成功: 用户ID = {}", users.getId());
return ResultUtils.success(true);
} catch (IllegalArgumentException e) {
// 转换为业务异常
throw new BusinessException(ErrorCode.INVALID_PARAM, e.getMessage());
} catch (IllegalAccessException e) {
logger.error("验证用户信息失败: {}", e.getMessage(), e);
throw new BusinessException(ErrorCode.BUSINESS_ERROR, "验证用户信息失败: " + e.getMessage(), e);
} catch (BusinessException e) {
throw e;
} catch (Exception e) {
return ResultUtils.fail(ErrorCode.DATABASE_ERROR);
logger.error("更新用户信息失败: {}", e.getMessage(), e);
throw new BusinessException(ErrorCode.DATABASE_ERROR, "更新用户信息失败: " + e.getMessage(), e);
}
}
// 删除用户
@Override
public Result<Boolean> deleteUser(Long id) {
logger.info("删除用户: 用户ID = {}", id);
try {
if (id == null) {
return ResultUtils.fail(ErrorCode.MISSING_PARAM);
throw new BusinessException(ErrorCode.MISSING_PARAM, "用户ID不能为空");
}
// 检查用户是否存在
Users users = getUserByIdAndCheckExist(id);
if (users == null) {
return ResultUtils.fail(ErrorCode.USER_NOT_FOUND);
throw new BusinessException(ErrorCode.USER_NOT_FOUND, "用户不存在");
}
int result = usersMapper.deleteById(id);
if (result <= 0) {
return ResultUtils.fail(ErrorCode.DATABASE_ERROR);
throw new BusinessException(ErrorCode.BUSINESS_ERROR, "删除用户失败");
}
return ResultUtils.success();
logger.info("用户删除成功: 用户ID = {}", id);
return ResultUtils.success(true);
} catch (BusinessException e) {
throw e;
} catch (Exception e) {
return ResultUtils.fail(ErrorCode.DATABASE_ERROR);
logger.error("删除用户失败: {}", e.getMessage(), e);
throw new BusinessException(ErrorCode.DATABASE_ERROR, "删除用户失败: " + e.getMessage(), e);
}
}
// 查询所有用户
@Override
public Result<List<Users>> listAllUsers() {
logger.info("查询所有用户列表");
try {
List<Users> usersList = usersMapper.selectList(null);
if (usersList == null || usersList.isEmpty()) {
return ResultUtils.fail(ErrorCode.NOT_FOUND);
}
logger.info("查询到 {} 个用户", usersList.size());
return ResultUtils.success(usersList);
} catch (Exception e) {
return ResultUtils.fail(ErrorCode.DATABASE_ERROR);
logger.error("查询用户列表失败: {}", e.getMessage(), e);
throw new BusinessException(ErrorCode.DATABASE_ERROR, "查询用户列表失败: " + e.getMessage(), e);
}
}
// 分页查询用户
@Override
public Result<List<Users>> listUsersByPage(int page, int size) {
logger.info("分页查询用户: 页码 = {}, 每页大小 = {}", page, size);
throw new UnsupportedOperationException("Unimplemented method 'listUsersByPage'");
try {
// 参数校验
if (page < 1) {
throw new BusinessException(ErrorCode.INVALID_PARAM, "页码不能小于1");
}
if (size < 1 || size > 100) {
throw new BusinessException(ErrorCode.INVALID_PARAM, "每页大小必须在1-100之间");
}
// 使用MyBatis-Plus的分页功能
Page<Users> userPage = new Page<>(page, size);
Page<Users> resultPage = usersMapper.selectPage(userPage, null);
logger.info("分页查询成功: 共 {} 条记录, 第 {} 页", resultPage.getTotal(), page);
return ResultUtils.success(resultPage.getRecords());
} catch (BusinessException e) {
throw e;
} catch (Exception e) {
logger.error("分页查询用户失败: {}", e.getMessage(), e);
throw new BusinessException(ErrorCode.DATABASE_ERROR, "分页查询用户失败: " + e.getMessage(), e);
}
}
// 根据ID查询用户
@Override
public Result<Users> getUserById(Long id) {
logger.info("根据ID查询用户: 用户ID = {}", id);
try {
if (id == null) {
return ResultUtils.fail(ErrorCode.MISSING_PARAM);
throw new BusinessException(ErrorCode.MISSING_PARAM, "用户ID不能为空");
}
Users users = getUserByIdAndCheckExist(id);
if (users == null) {
return ResultUtils.fail(ErrorCode.USER_NOT_FOUND);
throw new BusinessException(ErrorCode.USER_NOT_FOUND, "用户不存在");
}
return ResultUtils.success(users);
} catch (BusinessException e) {
throw e;
} catch (Exception e) {
return ResultUtils.fail(ErrorCode.DATABASE_ERROR);
logger.error("查询用户失败: {}", e.getMessage(), e);
throw new BusinessException(ErrorCode.DATABASE_ERROR, "查询用户失败: " + e.getMessage(), e);
}
}
// 更新用户密码
@Override
public Result<Boolean> updatePassword(Long id, String newPassword) {
logger.info("更新用户密码: 用户ID = {}", id);
try {
if (id == null || newPassword == null || newPassword.isEmpty()) {
return ResultUtils.fail(ErrorCode.MISSING_PARAM);
if (id == null) {
throw new BusinessException(ErrorCode.MISSING_PARAM, "用户ID不能为空");
}
if (ValidateUtil.isEmpty(newPassword)) {
throw new BusinessException(ErrorCode.MISSING_PARAM, "新密码不能为空");
}
// 密码强度校验
if (newPassword.length() < 6) {
throw new BusinessException(ErrorCode.INVALID_PARAM, "密码长度不能少于6个字符");
}
Users users = getUserByIdAndCheckExist(id);
if (users == null) {
return ResultUtils.fail(ErrorCode.USER_NOT_FOUND);
throw new BusinessException(ErrorCode.USER_NOT_FOUND, "用户不存在");
}
// 加密新密码
users.setPassword(new BCryptPasswordEncoder().encode(newPassword));
// 更新密码
int result = usersMapper.updateInfo(users, new UpdateWrapper<Users>().set("password", users.getPassword()).eq("id", id));
int result = usersMapper.updateInfo(users, new UpdateWrapper<Users>()
.set("password", users.getPassword())
.eq("id", id));
if (result <= 0) {
return ResultUtils.fail(ErrorCode.DATABASE_ERROR);
throw new BusinessException(ErrorCode.BUSINESS_ERROR, "更新密码失败");
}
return ResultUtils.success();
logger.info("用户密码更新成功: 用户ID = {}", id);
return ResultUtils.success(true);
} catch (BusinessException e) {
throw e;
} catch (Exception e) {
return ResultUtils.fail(ErrorCode.DATABASE_ERROR);
logger.error("更新用户密码失败: {}", e.getMessage(), e);
throw new BusinessException(ErrorCode.DATABASE_ERROR, "更新用户密码失败: " + e.getMessage(), e);
}
}
@@ -202,43 +343,4 @@ public class UsersServiceImpl extends ServiceImpl<UsersMapper, Users> implements
return usersMapper.selectOne(queryWrapper);
}
/**
* 验证用户信息是否合法且不存在重复
*
* @param users 用户对象
* @return 验证失败时返回错误Result验证成功时返回null
*/
private Result<Boolean> validateUserBeforeCreate(Users users) {
// 检查用户对象是否为空
if (users == null) {
return ResultUtils.fail(ErrorCode.MISSING_PARAM);
}
// 检查必要字段是否为空
if (users.getUsername() == null || users.getUsername().isEmpty()) {
return ResultUtils.fail(ErrorCode.MISSING_PARAM);
}
if (users.getEmail() == null || users.getEmail().isEmpty()) {
return ResultUtils.fail(ErrorCode.MISSING_PARAM);
}
if (users.getPassword() == null || users.getPassword().isEmpty()) {
return ResultUtils.fail(ErrorCode.MISSING_PARAM);
}
// 检查用户名是否已存在
Users existingUserByUsername = usersMapper.selectByUsername(users.getUsername());
if (existingUserByUsername != null) {
return ResultUtils.fail(ErrorCode.USER_EXISTED);
}
// 检查邮箱是否已存在
Users existingUserByEmail = usersMapper.selectByEmail(users.getEmail());
if (existingUserByEmail != null) {
return ResultUtils.fail(ErrorCode.USER_EXISTED);
}
// 检查手机号是否已存在
Users existingUserByPhone = usersMapper.selectByPhone(users.getPhone());
if (existingUserByPhone != null) {
return ResultUtils.fail(ErrorCode.USER_EXISTED);
}
return null; // 验证通过
}
}

Some files were not shown because too many files have changed in this diff Show More