重构项目文件夹目录

This commit is contained in:
2026-06-15 15:53:55 +08:00
parent 8093e07190
commit 7cbe5b3de5
1098 changed files with 34 additions and 4441 deletions
+3
View File
@@ -0,0 +1,3 @@
wrapperVersion=3.3.4
distributionType=only-script
distributionUrl=https://repo.maven.apache.org/maven2/org/apache/maven/apache-maven/3.9.12/apache-maven-3.9.12-bin.zip
+306
View File
@@ -0,0 +1,306 @@
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.7.18</version>
<relativePath/>
</parent>
<groupId>com.xiaowang</groupId>
<artifactId>FingertipDesigner-Core</artifactId>
<version>1.0.0</version>
<name>FingertipDesigner-Core</name>
<description>FingertipDesigner-Core-核心业务微服务</description>
<properties>
<java.version>17</java.version>
<spring-cloud.version>2021.0.8</spring-cloud.version>
<spring-cloud-alibaba.version>2021.0.5.0</spring-cloud-alibaba.version>
<mybatis-plus.version>3.5.3.1</mybatis-plus.version>
<druid.version>1.2.23</druid.version>
<jwt.version>0.11.5</jwt.version>
</properties>
<dependencies>
<!-- Web Starter -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<exclusions>
<exclusion>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-logging</artifactId>
</exclusion>
</exclusions>
</dependency>
<!-- Log4j2 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-log4j2</artifactId>
</dependency>
<!-- Redis -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
<exclusions>
<exclusion>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-logging</artifactId>
</exclusion>
</exclusions>
</dependency>
<!-- RabbitMQ -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-amqp</artifactId>
<exclusions>
<exclusion>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-logging</artifactId>
</exclusion>
</exclusions>
</dependency>
<!-- Nacos Discovery -->
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
<exclusions>
<exclusion>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-logging</artifactId>
</exclusion>
</exclusions>
</dependency>
<!-- Nacos Config -->
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-nacos-config</artifactId>
<exclusions>
<exclusion>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-logging</artifactId>
</exclusion>
</exclusions>
</dependency>
<!-- Bootstrap for Nacos Config -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-bootstrap</artifactId>
<exclusions>
<exclusion>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-logging</artifactId>
</exclusion>
</exclusions>
</dependency>
<!-- MySQL & Druid & MyBatis-Plus -->
<dependency>
<groupId>com.mysql</groupId>
<artifactId>mysql-connector-j</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-boot-starter</artifactId>
<version>${mybatis-plus.version}</version>
<exclusions>
<exclusion>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-logging</artifactId>
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
<version>${druid.version}</version>
<exclusions>
<exclusion>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-logging</artifactId>
</exclusion>
</exclusions>
</dependency>
<!-- AOP -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
<exclusions>
<exclusion>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-logging</artifactId>
</exclusion>
</exclusions>
</dependency>
<!-- Validation -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
<exclusions>
<exclusion>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-logging</artifactId>
</exclusion>
</exclusions>
</dependency>
<!-- JWT -->
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt-api</artifactId>
<version>${jwt.version}</version>
</dependency>
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt-impl</artifactId>
<version>${jwt.version}</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt-jackson</artifactId>
<version>${jwt.version}</version>
<scope>runtime</scope>
</dependency>
<!-- BCrypt for password encryption -->
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-crypto</artifactId>
</dependency>
<!-- Caffeine -->
<dependency>
<groupId>com.github.ben-manes.caffeine</groupId>
<artifactId>caffeine</artifactId>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
</dependency>
<!-- MinIO -->
<dependency>
<groupId>io.minio</groupId>
<artifactId>minio</artifactId>
<version>8.5.7</version>
</dependency>
<!-- Aliyun OSS backup storage -->
<dependency>
<groupId>com.aliyun.oss</groupId>
<artifactId>aliyun-sdk-oss</artifactId>
<version>3.18.5</version>
</dependency>
<!-- Lombok -->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.32</version>
<optional>true</optional>
</dependency>
<!-- Test -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-logging</artifactId>
</exclusion>
</exclusions>
</dependency>
</dependencies>
<dependencyManagement>
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-dependencies</artifactId>
<version>${spring-cloud.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-alibaba-dependencies</artifactId>
<version>${spring-cloud-alibaba.version}</version>
<type>pom</type>
<scope>import</scope>
</dependency>
</dependencies>
</dependencyManagement>
<build>
<finalName>FingertipDesigner-Core</finalName>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<excludes>
<exclude>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</exclude>
</excludes>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-antrun-plugin</artifactId>
<version>3.1.0</version>
<executions>
<execution>
<id>copy-release-jar</id>
<phase>package</phase>
<goals>
<goal>run</goal>
</goals>
<configuration>
<target>
<mkdir dir="${project.basedir}/../docx/product"/>
<copy file="${project.build.directory}/${project.build.finalName}.jar"
tofile="${project.basedir}/../docx/product/FingertipDesigner-Core.jar"/>
</target>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.1</version>
<configuration>
<source>${java.version}</source>
<target>${java.version}</target>
<annotationProcessorPaths>
<path>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.32</version>
</path>
</annotationProcessorPaths>
</configuration>
</plugin>
</plugins>
</build>
</project>
@@ -0,0 +1,25 @@
package com.xiaowang.yuminailcore;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.scheduling.annotation.EnableScheduling;
@EnableDiscoveryClient
@EnableScheduling
@SpringBootApplication
/**
* Purpose: YumiNailCoreApplication supports YumiNailCoreApplication.java by holding or executing the yumi nail core application business role.
* Usage: reference this class from the owning layer and pass validated inputs before reading or updating related state.
*/
public class YumiNailCoreApplication {
/**
* Purpose: main supports YumiNailCoreApplication.java by holding or executing the main business role.
* Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state.
*/
public static void main(String[] args) {
SpringApplication.run(YumiNailCoreApplication.class, args);
}
}
@@ -0,0 +1,25 @@
package com.xiaowang.yuminailcore.annotation;
import com.xiaowang.yuminailcore.support.security.OperationGuardStrategy;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
/**
* Purpose: OperationGuard supports OperationGuard.java by holding or executing the operation guard business role.
* Usage: reference this interface from the owning layer and pass validated inputs before reading or updating related state.
*/
public @interface OperationGuard {
String action();
OperationGuardStrategy strategy() default OperationGuardStrategy.REJECT_IF_RUNNING;
int ttlSeconds() default 10;
String message() default "操作进行中,请勿重复点击";
}
@@ -0,0 +1,19 @@
package com.xiaowang.yuminailcore.annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
/**
* Purpose: RequirePermission supports RequirePermission.java by holding or executing the require permission business role.
* Usage: reference this interface from the owning layer and pass validated inputs before reading or updating related state.
*/
public @interface RequirePermission {
String value() default "";
int requireUserType() default -1;
}
@@ -0,0 +1,66 @@
package com.xiaowang.yuminailcore.aspect;
import com.xiaowang.yuminailcore.annotation.OperationGuard;
import com.xiaowang.yuminailcore.common.Result;
import com.xiaowang.yuminailcore.support.security.OperationGuardService;
import com.xiaowang.yuminailcore.support.security.OperationGuardStrategy;
import lombok.RequiredArgsConstructor;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import javax.servlet.http.HttpServletRequest;
import java.time.Duration;
@Aspect
@Component
@Order(100)
@RequiredArgsConstructor
/**
* Purpose: OperationGuardAspect supports OperationGuardAspect.java by holding or executing the operation guard aspect business role.
* Usage: reference this class from the owning layer and pass validated inputs before reading or updating related state.
*/
public class OperationGuardAspect {
/**
* Purpose: operationGuardService supports OperationGuardAspect.java by holding or executing the operation guard service business role.
* Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state.
*/
private final OperationGuardService operationGuardService;
@Around("@annotation(operationGuard)")
/**
* Purpose: guardOperation supports OperationGuardAspect.java by holding or executing the guard operation business role.
* Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state.
*/
public Object guardOperation(ProceedingJoinPoint joinPoint, OperationGuard operationGuard) throws Throwable {
ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
if (attributes == null) {
return Result.error(500, "无法获取请求信息");
}
HttpServletRequest request = attributes.getRequest();
OperationGuardService.GuardHandle handle = operationGuardService.tryAcquire(
request,
operationGuard.action(),
Duration.ofSeconds(Math.max(1, operationGuard.ttlSeconds()))
);
if (!handle.acquired()) {
if (operationGuard.strategy() == OperationGuardStrategy.NOOP_IF_DUPLICATE) {
return Result.success();
}
return Result.error(409, operationGuard.message());
}
try {
return joinPoint.proceed();
} finally {
operationGuardService.release(handle);
}
}
}
@@ -0,0 +1,147 @@
package com.xiaowang.yuminailcore.aspect;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.xiaowang.yuminailcore.annotation.RequirePermission;
import com.xiaowang.yuminailcore.common.Result;
import com.xiaowang.yuminailcore.modules.security.entity.PermissionDO;
import com.xiaowang.yuminailcore.modules.user.entity.UserDO;
import com.xiaowang.yuminailcore.modules.security.mapper.PermissionMapper;
import com.xiaowang.yuminailcore.modules.user.mapper.UserMapper;
import com.xiaowang.yuminailcore.modules.security.service.PermissionService;
import com.xiaowang.yuminailcore.modules.security.support.PermissionCatalog;
import lombok.RequiredArgsConstructor;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
@Aspect
@Component
@Order(Ordered.HIGHEST_PRECEDENCE)
@RequiredArgsConstructor
/**
* Purpose: PermissionAspect supports PermissionAspect.java by holding or executing the permission aspect business role.
* Usage: reference this class from the owning layer and pass validated inputs before reading or updating related state.
*/
public class PermissionAspect {
/**
* Purpose: permissionService supports PermissionAspect.java by holding or executing the permission service business role.
* Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state.
*/
private final PermissionService permissionService;
/**
* Purpose: permissionMapper supports PermissionAspect.java by holding or executing the permission mapper business role.
* Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state.
*/
private final PermissionMapper permissionMapper;
/**
* Purpose: userMapper supports PermissionAspect.java by holding or executing the user mapper business role.
* Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state.
*/
private final UserMapper userMapper;
@Around("@annotation(com.xiaowang.yuminailcore.annotation.RequirePermission)")
/**
* Purpose: checkPermission supports PermissionAspect.java by holding or executing the check permission business role.
* Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state.
*/
public Object checkPermission(ProceedingJoinPoint joinPoint) throws Throwable {
ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
if (attributes == null) {
return Result.error(403, "无法获取请求信息");
}
HttpServletRequest request = attributes.getRequest();
Long userId = (Long) request.getAttribute("userId");
if (userId == null) {
return Result.error(401, "未登录");
}
MethodSignature signature = (MethodSignature) joinPoint.getSignature();
Method method = signature.getMethod();
RequirePermission requirePermission = method.getAnnotation(RequirePermission.class);
if (requirePermission == null) {
return joinPoint.proceed();
}
UserDO userDO = userMapper.selectById(userId);
if (userDO == null) {
return Result.error(404, "用户不存在");
}
String permissionCode = requirePermission.value();
Long currentShopId = parseShopId(request.getAttribute("currentShopId"));
if (Integer.valueOf(4).equals(userDO.getType())
&& currentShopId == null
&& StringUtils.hasText(permissionCode)
&& !PermissionCatalog.isAllowedForPlatformOverview(permissionCode)) {
return Result.error(403, "平台总览模式下仅允许查看店铺业务数据,请勿进行编辑操作");
}
if (Integer.valueOf(4).equals(userDO.getType())
&& currentShopId == null
&& StringUtils.hasText(permissionCode)
&& PermissionCatalog.isAllowedForPlatformOverview(permissionCode)) {
return joinPoint.proceed();
}
boolean hasPermission = !StringUtils.hasText(permissionCode)
|| permissionService.hasPermission(userId, permissionCode);
if (!hasPermission) {
return Result.error(403, buildPermissionDeniedMessage(permissionCode));
}
return joinPoint.proceed();
}
/**
* Purpose: buildPermissionDeniedMessage supports PermissionAspect.java by holding or executing the build permission denied message business role.
* Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state.
*/
private String buildPermissionDeniedMessage(String permissionCode) {
if (!StringUtils.hasText(permissionCode)) {
return "权限不足";
}
PermissionDO permissionDO = permissionMapper.selectOne(
Wrappers.lambdaQuery(PermissionDO.class)
.eq(PermissionDO::getPermissionCode, permissionCode)
.eq(PermissionDO::getIsDelete, 0)
.last("limit 1")
);
if (permissionDO != null && StringUtils.hasText(permissionDO.getPermissionName())) {
return "权限不足:缺少权限(" + permissionDO.getPermissionName() + " / " + permissionCode + ")";
}
return "权限不足:缺少权限代码 " + permissionCode;
}
/**
* Purpose: parseShopId supports PermissionAspect.java by holding or executing the parse shop id business role.
* Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state.
*/
private Long parseShopId(Object value) {
if (value instanceof Number number) {
long shopId = number.longValue();
return shopId > 0 ? shopId : null;
}
if (value instanceof String text && StringUtils.hasText(text)) {
try {
long shopId = Long.parseLong(text.trim());
return shopId > 0 ? shopId : null;
} catch (NumberFormatException ignored) {
return null;
}
}
return null;
}
}
@@ -0,0 +1,39 @@
package com.xiaowang.yuminailcore.common;
/**
* 业务异常。
*/
public class BusinessException extends RuntimeException {
/**
* Purpose: code supports BusinessException.java by holding or executing the code business role.
* Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state.
*/
private final Integer code;
public BusinessException(String message) {
this(500, message);
}
public BusinessException(Integer code, String message) {
super(message);
this.code = code;
}
public BusinessException(String message, Throwable cause) {
this(500, message, cause);
}
public BusinessException(Integer code, String message, Throwable cause) {
super(message, cause);
this.code = code;
}
/**
* Purpose: getCode supports BusinessException.java by holding or executing the get code business role.
* Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state.
*/
public Integer getCode() {
return code;
}
}
@@ -0,0 +1,155 @@
package com.xiaowang.yuminailcore.common;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.support.DefaultMessageSourceResolvable;
import org.springframework.validation.BindException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.multipart.MaxUploadSizeExceededException;
import org.springframework.web.multipart.MultipartException;
import javax.validation.ConstraintViolationException;
/**
* 全局异常处理器。
*/
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {
/**
* Purpose: MAX_UPLOAD_SIZE_BYTES supports GlobalExceptionHandler.java by holding or executing the max upload size bytes business role.
* Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state.
*/
private static final long MAX_UPLOAD_SIZE_BYTES = 5L * 1024 * 1024;
@ExceptionHandler(MethodArgumentNotValidException.class)
/**
* Purpose: handleMethodArgumentNotValidException supports GlobalExceptionHandler.java by holding or executing the handle method argument not valid exception business role.
* Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state.
*/
public Result<Void> handleMethodArgumentNotValidException(MethodArgumentNotValidException e) {
String message = e.getBindingResult().getAllErrors().stream()
.map(DefaultMessageSourceResolvable::getDefaultMessage)
.findFirst()
.orElse("请求参数不合法");
return Result.error(message);
}
@ExceptionHandler(BindException.class)
/**
* Purpose: handleBindException supports GlobalExceptionHandler.java by holding or executing the handle bind exception business role.
* Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state.
*/
public Result<Void> handleBindException(BindException e) {
String message = e.getBindingResult().getAllErrors().stream()
.map(DefaultMessageSourceResolvable::getDefaultMessage)
.findFirst()
.orElse("请求参数不合法");
return Result.error(message);
}
@ExceptionHandler(ConstraintViolationException.class)
/**
* Purpose: handleConstraintViolationException supports GlobalExceptionHandler.java by holding or executing the handle constraint violation exception business role.
* Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state.
*/
public Result<Void> handleConstraintViolationException(ConstraintViolationException e) {
String message = e.getConstraintViolations().stream()
.map(violation -> violation.getMessage())
.findFirst()
.orElse("请求参数不合法");
return Result.error(message);
}
@ExceptionHandler(MaxUploadSizeExceededException.class)
/**
* Purpose: handleMaxUploadSizeExceededException supports GlobalExceptionHandler.java by holding or executing the handle max upload size exceeded exception business role.
* Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state.
*/
public Result<Void> handleMaxUploadSizeExceededException(MaxUploadSizeExceededException e) {
log.warn("上传文件超过限制: {}", e.getMessage());
return Result.error(buildUploadLimitMessage());
}
@ExceptionHandler(MultipartException.class)
/**
* Purpose: handleMultipartException supports GlobalExceptionHandler.java by holding or executing the handle multipart exception business role.
* Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state.
*/
public Result<Void> handleMultipartException(MultipartException e) {
log.warn("文件上传请求异常: {}", e.getMessage());
return Result.error(buildUploadLimitMessage());
}
@ExceptionHandler(IllegalStateException.class)
/**
* Purpose: handleIllegalStateException supports GlobalExceptionHandler.java by holding or executing the handle illegal state exception business role.
* Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state.
*/
public Result<Void> handleIllegalStateException(IllegalStateException e) {
if (isUploadLimitException(e)) {
log.warn("上传文件超过限制: {}", e.getMessage());
return Result.error(buildUploadLimitMessage());
}
log.error("非法状态异常", e);
return Result.error(e.getMessage());
}
@ExceptionHandler(BusinessException.class)
/**
* Purpose: handleBusinessException supports GlobalExceptionHandler.java by holding or executing the handle business exception business role.
* Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state.
*/
public Result<Void> handleBusinessException(BusinessException e) {
log.warn("业务异常: {}", e.getMessage());
return Result.error(e.getCode(), e.getMessage());
}
@ExceptionHandler(RuntimeException.class)
/**
* Purpose: handleRuntimeException supports GlobalExceptionHandler.java by holding or executing the handle runtime exception business role.
* Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state.
*/
public Result<Void> handleRuntimeException(RuntimeException e) {
log.error("运行时异常", e);
return Result.error(e.getMessage());
}
@ExceptionHandler(Exception.class)
/**
* Purpose: handleException supports GlobalExceptionHandler.java by holding or executing the handle exception business role.
* Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state.
*/
public Result<Void> handleException(Exception e) {
log.error("系统异常", e);
return Result.error("系统繁忙,请稍后再试");
}
/**
* Purpose: buildUploadLimitMessage supports GlobalExceptionHandler.java by holding or executing the build upload limit message business role.
* Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state.
*/
private String buildUploadLimitMessage() {
return "上传文件不能超过 " + (MAX_UPLOAD_SIZE_BYTES / 1024 / 1024) + "MB";
}
/**
* Purpose: isUploadLimitException supports GlobalExceptionHandler.java by holding or executing the is upload limit exception business role.
* Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state.
*/
private boolean isUploadLimitException(Throwable throwable) {
Throwable current = throwable;
while (current != null) {
String message = current.getMessage();
if (message != null && (message.contains("maximum permitted size")
|| message.contains("FileSizeLimitExceededException")
|| message.contains("exceeds its maximum permitted size"))) {
return true;
}
current = current.getCause();
}
return false;
}
}
@@ -0,0 +1,68 @@
package com.xiaowang.yuminailcore.common;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.io.Serializable;
/**
* 统一响应结果类
*
* @param <T> 数据类型
* @author xiaowang
* @date 2026-02-12
*/
@Data
@NoArgsConstructor
@AllArgsConstructor
public class Result<T> implements Serializable {
/**
* Purpose: code supports Result.java by holding or executing the code business role.
* Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state.
*/
private Integer code;
/**
* Purpose: message supports Result.java by holding or executing the message business role.
* Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state.
*/
private String message;
/**
* Purpose: data supports Result.java by holding or executing the data business role.
* Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state.
*/
private T data;
/**
* Purpose: success supports Result.java by holding or executing the success business role.
* Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state.
*/
public static <T> Result<T> success() {
return new Result<>(200, "操作成功", null);
}
/**
* Purpose: success supports Result.java by holding or executing the success business role.
* Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state.
*/
public static <T> Result<T> success(T data) {
return new Result<>(200, "操作成功", data);
}
/**
* Purpose: error supports Result.java by holding or executing the error business role.
* Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state.
*/
public static <T> Result<T> error(String message) {
return new Result<>(500, message, null);
}
/**
* Purpose: error supports Result.java by holding or executing the error business role.
* Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state.
*/
public static <T> Result<T> error(Integer code, String message) {
return new Result<>(code, message, null);
}
}
@@ -0,0 +1,16 @@
package com.xiaowang.yuminailcore.common.dto;
import java.util.Map;
/**
* Purpose: AgreementAwareRequest supports AgreementAwareRequest.java by holding or executing the agreement aware request business role.
* Usage: reference this interface from the owning layer and pass validated inputs before reading or updating related state.
*/
public interface AgreementAwareRequest {
Boolean getAgreementAccepted();
Map<String, String> getAgreementVersions();
String getClientType();
}
@@ -0,0 +1,38 @@
package com.xiaowang.yuminailcore.common.entity;
import com.baomidou.mybatisplus.annotation.FieldFill;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableId;
import lombok.Data;
import java.time.LocalDateTime;
/**
* 实体类基类
* 提取公共字段,方便后续实体类扩展
*
* @author xiaowang
* @date 2026-02-12
*/
@Data
public abstract class BaseEntity {
/**
* 主键ID
*/
@TableId(type = IdType.ASSIGN_ID)
private Long id;
/**
* 创建时间
*/
@TableField(fill = FieldFill.INSERT)
private LocalDateTime createTime;
/**
* 更新时间
*/
@TableField(fill = FieldFill.INSERT_UPDATE)
private LocalDateTime updateTime;
}
@@ -0,0 +1,29 @@
package com.xiaowang.yuminailcore.common.vo;
import lombok.Data;
import java.util.List;
@Data
/**
* PageResultVO is a response VO. Services build it and controllers return it to the frontend.
* Field and parameter names are kept consistent with the frontend/API payload to make tracing easier.
*/
public class PageResultVO<T> {
/**
* Field `list` (List<T>): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled.
*/
private List<T> list;
/**
* Field `total` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled.
*/
private Long total;
/**
* Field `page` (Integer): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled.
*/
private Integer page;
/**
* Field `size` (Integer): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled.
*/
private Integer size;
}
@@ -0,0 +1,60 @@
package com.xiaowang.yuminailcore.config;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
/**
* 多级缓存配置。
*/
@Data
@Configuration
@ConfigurationProperties(prefix = "yuminail.cache")
public class AppCacheProperties {
/**
* Purpose: localMaxSize supports AppCacheProperties.java by holding or executing the local max size business role.
* Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state.
*/
private long localMaxSize = 2048;
private CacheSpec productDetail = new CacheSpec(120, 900);
private CacheSpec productList = new CacheSpec(60, 300);
private CacheSpec productSearch = new CacheSpec(60, 300);
private CacheSpec shop = new CacheSpec(180, 900);
private CacheSpec tag = new CacheSpec(300, 1200);
private CacheSpec objectStorageFile = new CacheSpec(300, 1800);
private CacheSpec dashboard = new CacheSpec(30, 90);
@Data
/**
* Purpose: CacheSpec supports AppCacheProperties.java by holding or executing the cache spec business role.
* Usage: reference this class from the owning layer and pass validated inputs before reading or updating related state.
*/
public static class CacheSpec {
/**
* Purpose: localTtlSeconds supports AppCacheProperties.java by holding or executing the local ttl seconds business role.
* Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state.
*/
private long localTtlSeconds;
/**
* Purpose: redisTtlSeconds supports AppCacheProperties.java by holding or executing the redis ttl seconds business role.
* Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state.
*/
private long redisTtlSeconds;
public CacheSpec() {
}
public CacheSpec(long localTtlSeconds, long redisTtlSeconds) {
this.localTtlSeconds = localTtlSeconds;
this.redisTtlSeconds = redisTtlSeconds;
}
}
}
@@ -0,0 +1,230 @@
package com.xiaowang.yuminailcore.config;
import com.xiaowang.yuminailcore.modules.user.entity.UserDO;
import com.xiaowang.yuminailcore.modules.user.mapper.UserMapper;
import com.xiaowang.yuminailcore.support.RequestShopContext;
import com.xiaowang.yuminailcore.modules.shop.support.UserShopBindingSupport;
import com.xiaowang.yuminailcore.support.security.RequestSignatureService;
import com.xiaowang.yuminailcore.support.security.RequestThrottleService;
import com.xiaowang.yuminailcore.support.security.UserSessionService;
import com.xiaowang.yuminailcore.utils.JwtUtil;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@Component
@RequiredArgsConstructor
/**
* Purpose: AuthInterceptor supports AuthInterceptor.java by holding or executing the auth interceptor business role.
* Usage: reference this class from the owning layer and pass validated inputs before reading or updating related state.
*/
public class AuthInterceptor implements HandlerInterceptor {
/**
* Purpose: jwtUtil supports AuthInterceptor.java by holding or executing the jwt util business role.
* Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state.
*/
private final JwtUtil jwtUtil;
/**
* Purpose: userMapper supports AuthInterceptor.java by holding or executing the user mapper business role.
* Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state.
*/
private final UserMapper userMapper;
/**
* Purpose: userShopBindingSupport supports AuthInterceptor.java by holding or executing the user shop binding support business role.
* Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state.
*/
private final UserShopBindingSupport userShopBindingSupport;
/**
* Purpose: userSessionService supports AuthInterceptor.java by holding or executing the user session service business role.
* Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state.
*/
private final UserSessionService userSessionService;
/**
* Purpose: requestSignatureService supports AuthInterceptor.java by holding or executing the request signature service business role.
* Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state.
*/
private final RequestSignatureService requestSignatureService;
/**
* Purpose: requestThrottleService supports AuthInterceptor.java by holding or executing the request throttle service business role.
* Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state.
*/
private final RequestThrottleService requestThrottleService;
/**
* Purpose: AUTHORIZATION_HEADER supports AuthInterceptor.java by holding or executing the authorization header business role.
* Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state.
*/
private static final String AUTHORIZATION_HEADER = "Authorization";
/**
* Purpose: BEARER_PREFIX supports AuthInterceptor.java by holding or executing the bearer prefix business role.
* Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state.
*/
private static final String BEARER_PREFIX = "Bearer ";
@Override
/**
* Purpose: preHandle supports AuthInterceptor.java by holding or executing the pre handle business role.
* Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state.
*/
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
String path = request.getRequestURI();
String authHeader = request.getHeader(AUTHORIZATION_HEADER);
if (authHeader == null || !authHeader.startsWith(BEARER_PREFIX)) {
response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
response.setContentType("application/json;charset=UTF-8");
response.getWriter().write("{\"code\":401,\"message\":\"未提供认证Token\"}");
return false;
}
String token = authHeader.substring(BEARER_PREFIX.length());
if (!jwtUtil.validateToken(token)) {
writeJsonResponse(response, HttpServletResponse.SC_UNAUTHORIZED, "Token无效或已过期");
return false;
}
if (!jwtUtil.isAccessToken(token)) {
writeJsonResponse(response, HttpServletResponse.SC_UNAUTHORIZED, "Token类型错误");
return false;
}
Long userId = jwtUtil.getUserIdFromToken(token);
String account = jwtUtil.getAccountFromToken(token);
Long currentShopId = jwtUtil.getShopIdFromToken(token);
String sessionId = jwtUtil.getSessionIdFromToken(token);
String jti = jwtUtil.getJtiFromToken(token);
if (!userSessionService.isAccessSessionActive(userId, sessionId, jti)) {
writeJsonResponse(response, HttpServletResponse.SC_UNAUTHORIZED, "登录态已失效,请重新登录");
return false;
}
UserDO currentUser = userMapper.selectById(userId);
if (currentUser == null || Integer.valueOf(1).equals(currentUser.getIsDelete())) {
writeJsonResponse(response, HttpServletResponse.SC_UNAUTHORIZED, "用户不存在或已失效");
return false;
}
if (currentUser.getStatus() != null && !Integer.valueOf(1).equals(currentUser.getStatus())) {
writeJsonResponse(response, HttpServletResponse.SC_FORBIDDEN, "账号已被禁用");
return false;
}
boolean adminPath = isAdminPath(path);
if (adminPath && (currentUser.getType() == null || currentUser.getType() < 2)) {
writeJsonResponse(response, HttpServletResponse.SC_FORBIDDEN, "无后台访问权限");
return false;
}
boolean canAccessShop = userShopBindingSupport.canUserAccessShop(
userId,
currentShopId,
adminPath,
currentUser.getType()
);
if (!canAccessShop) {
String message = currentShopId == null || currentShopId <= 0
? "当前登录未选择可用店铺,请重新登录"
: (userShopBindingSupport.isShopEnabledIgnoringAuthorization(currentShopId)
&& userShopBindingSupport.isShopAuthorizationExpired(currentShopId)
? "店铺已被冻结"
: "当前登录店铺已停用或账号已失去该店铺访问权限");
writeJsonResponse(response, HttpServletResponse.SC_UNAUTHORIZED, message);
return false;
}
if (adminPath
&& !Integer.valueOf(4).equals(currentUser.getType())
&& userShopBindingSupport.isShopAuthorizationExpired(currentShopId)
&& !isExpiredAdminAllowedPath(path)) {
writeJsonResponse(response, HttpServletResponse.SC_FORBIDDEN, "授权已到期,请联系管理员");
return false;
}
if (requiresSignature(request)) {
try {
requestSignatureService.validateRequest(request, token, userId);
} catch (RuntimeException exception) {
writeJsonResponse(response, HttpServletResponse.SC_UNAUTHORIZED, exception.getMessage());
return false;
}
}
if (requiresWriteRateLimit(request)) {
try {
requestThrottleService.checkAuthenticatedWrite(request, userId);
} catch (RuntimeException exception) {
writeJsonResponse(response, 429, exception.getMessage());
return false;
}
}
request.setAttribute("userId", userId);
request.setAttribute("account", account);
request.setAttribute("userType", currentUser.getType());
request.setAttribute("accessToken", token);
request.setAttribute("sessionId", sessionId);
request.setAttribute("tokenJti", jti);
request.setAttribute(RequestShopContext.CURRENT_SHOP_ID_ATTRIBUTE, currentShopId);
return true;
}
/**
* Purpose: requiresSignature supports AuthInterceptor.java by holding or executing the requires signature business role.
* Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state.
*/
private boolean requiresSignature(HttpServletRequest request) {
return requiresWriteRateLimit(request);
}
/**
* Purpose: requiresWriteRateLimit supports AuthInterceptor.java by holding or executing the requires write rate limit business role.
* Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state.
*/
private boolean requiresWriteRateLimit(HttpServletRequest request) {
String method = request.getMethod();
if (!StringUtils.hasText(method)) {
return false;
}
String normalized = method.toUpperCase();
return !("GET".equals(normalized) || "HEAD".equals(normalized) || "OPTIONS".equals(normalized));
}
/**
* Purpose: isAdminPath supports AuthInterceptor.java by holding or executing the is admin path business role.
* Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state.
*/
private boolean isAdminPath(String path) {
return path.startsWith("/admin/") || path.startsWith("/order/admin/");
}
/**
* Purpose: isExpiredAdminAllowedPath supports AuthInterceptor.java by holding or executing the is expired admin allowed path business role.
* Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state.
*/
private boolean isExpiredAdminAllowedPath(String path) {
return path.startsWith("/admin/auth/")
|| path.equals("/admin/user/info")
|| path.equals("/permission/list/user/current")
|| path.equals("/api/permission/list/user/current")
|| path.startsWith("/admin/planning/")
|| path.startsWith("/admin/shops/");
}
/**
* Purpose: writeJsonResponse supports AuthInterceptor.java by holding or executing the write json response business role.
* Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state.
*/
private void writeJsonResponse(HttpServletResponse response, int status, String message) throws Exception {
response.setStatus(status);
response.setContentType("application/json;charset=UTF-8");
response.getWriter().write("{\"code\":" + status + ",\"message\":\"" + message + "\"}");
}
}
@@ -0,0 +1,54 @@
package com.xiaowang.yuminailcore.config;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.client.HttpComponentsClientHttpRequestFactory;
import org.springframework.web.client.RestTemplate;
import java.util.concurrent.TimeUnit;
@Configuration
/**
* Purpose: HttpClientConfig supports HttpClientConfig.java by holding or executing the http client config business role.
* Usage: reference this class from the owning layer and pass validated inputs before reading or updating related state.
*/
public class HttpClientConfig {
@Bean
/**
* Purpose: poolingHttpClientConnectionManager supports HttpClientConfig.java by holding or executing the pooling http client connection manager business role.
* Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state.
*/
public PoolingHttpClientConnectionManager poolingHttpClientConnectionManager(HttpClientProperties properties) {
PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager();
connectionManager.setMaxTotal(properties.getMaxTotalConnections());
connectionManager.setDefaultMaxPerRoute(properties.getMaxConnectionsPerRoute());
return connectionManager;
}
@Bean
public RestTemplate restTemplate(HttpClientProperties properties,
PoolingHttpClientConnectionManager connectionManager) {
RequestConfig requestConfig = RequestConfig.custom()
.setConnectTimeout(properties.getConnectTimeoutMs())
.setSocketTimeout(properties.getReadTimeoutMs())
.setConnectionRequestTimeout(properties.getConnectionRequestTimeoutMs())
.build();
CloseableHttpClient httpClient = HttpClients.custom()
.setConnectionManager(connectionManager)
.setDefaultRequestConfig(requestConfig)
.disableCookieManagement()
.evictIdleConnections(30, TimeUnit.SECONDS)
.build();
HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory(httpClient);
requestFactory.setConnectTimeout(properties.getConnectTimeoutMs());
requestFactory.setReadTimeout(properties.getReadTimeoutMs());
requestFactory.setConnectionRequestTimeout(properties.getConnectionRequestTimeoutMs());
return new RestTemplate(requestFactory);
}
}
@@ -0,0 +1,45 @@
package com.xiaowang.yuminailcore.config;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
@Data
@Configuration
@ConfigurationProperties(prefix = "yuminail.http-client")
/**
* Purpose: HttpClientProperties supports HttpClientProperties.java by holding or executing the http client properties business role.
* Usage: reference this class from the owning layer and pass validated inputs before reading or updating related state.
*/
public class HttpClientProperties {
/**
* Purpose: connectTimeoutMs supports HttpClientProperties.java by holding or executing the connect timeout ms business role.
* Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state.
*/
private int connectTimeoutMs = 3000;
/**
* Purpose: readTimeoutMs supports HttpClientProperties.java by holding or executing the read timeout ms business role.
* Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state.
*/
private int readTimeoutMs = 5000;
/**
* Purpose: connectionRequestTimeoutMs supports HttpClientProperties.java by holding or executing the connection request timeout ms business role.
* Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state.
*/
private int connectionRequestTimeoutMs = 1000;
/**
* Purpose: maxTotalConnections supports HttpClientProperties.java by holding or executing the max total connections business role.
* Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state.
*/
private int maxTotalConnections = 200;
/**
* Purpose: maxConnectionsPerRoute supports HttpClientProperties.java by holding or executing the max connections per route business role.
* Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state.
*/
private int maxConnectionsPerRoute = 50;
}
@@ -0,0 +1,64 @@
package com.xiaowang.yuminailcore.config;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.databind.ser.std.ToStringSerializer;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import org.springframework.boot.autoconfigure.jackson.Jackson2ObjectMapperBuilderCustomizer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import java.time.LocalDateTime;
import java.io.IOException;
import java.time.format.DateTimeFormatter;
@Configuration
/**
* Purpose: JacksonConfig supports JacksonConfig.java by holding or executing the jackson config business role.
* Usage: reference this class from the owning layer and pass validated inputs before reading or updating related state.
*/
public class JacksonConfig {
@Bean
/**
* Purpose: longToStringJacksonCustomizer supports JacksonConfig.java by holding or executing the long to string jackson customizer business role.
* Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state.
*/
public Jackson2ObjectMapperBuilderCustomizer longToStringJacksonCustomizer() {
return builder -> {
// Snowflake IDs are serialized as strings so the web and mini program do not lose precision.
builder.serializerByType(Long.class, ToStringSerializer.instance);
builder.serializerByType(Long.TYPE, ToStringSerializer.instance);
JavaTimeModule javaTimeModule = new JavaTimeModule();
javaTimeModule.addDeserializer(LocalDateTime.class, new FlexibleLocalDateTimeDeserializer());
builder.modules(javaTimeModule);
};
}
/**
* Purpose: FlexibleLocalDateTimeDeserializer supports JacksonConfig.java by holding or executing the flexible local date time deserializer business role.
* Usage: reference this class from the owning layer and pass validated inputs before reading or updating related state.
*/
private static class FlexibleLocalDateTimeDeserializer extends JsonDeserializer<LocalDateTime> {
private static final DateTimeFormatter SPACE_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
@Override
/**
* Purpose: deserialize supports JacksonConfig.java by holding or executing the deserialize business role.
* Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state.
*/
public LocalDateTime deserialize(JsonParser parser, DeserializationContext context) throws IOException {
String value = parser.getValueAsString();
if (value == null || value.trim().isEmpty()) {
return null;
}
String normalized = value.trim();
if (normalized.contains("T")) {
return LocalDateTime.parse(normalized);
}
return LocalDateTime.parse(normalized, SPACE_FORMATTER);
}
}
}
@@ -0,0 +1,39 @@
package com.xiaowang.yuminailcore.config;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
/**
* JWT 配置。
*/
@Data
@Configuration
@ConfigurationProperties(prefix = "yuminail.security.jwt")
public class JwtProperties {
/**
* HS512 密钥,生产环境请通过 Nacos 覆盖。
*/
private String secret = "yuminail-secret-key-for-jwt-token-generation-2026-must-be-at-least-512-bits-long-for-hs512-algorithm-security-requirements";
/**
* Token 发行者。
*/
private String issuer = "yuminail";
/**
* AccessToken 有效期,单位秒。
*/
private long accessTokenExpirationSeconds = 2 * 60 * 60;
/**
* RefreshToken 有效期,单位秒。
*/
private long refreshTokenExpirationSeconds = 7 * 24 * 60 * 60;
/**
* 时钟偏移容忍,单位秒。
*/
private long clockSkewSeconds = 30;
}
@@ -0,0 +1,33 @@
package com.xiaowang.yuminailcore.config;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
@Data
@Configuration
@ConfigurationProperties(prefix = "yuminail.security.login-lock")
/**
* Purpose: LoginLockProperties supports LoginLockProperties.java by holding or executing the login lock properties business role.
* Usage: reference this class from the owning layer and pass validated inputs before reading or updating related state.
*/
public class LoginLockProperties {
/**
* Purpose: maxFailures supports LoginLockProperties.java by holding or executing the max failures business role.
* Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state.
*/
private int maxFailures = 5;
/**
* Purpose: windowSeconds supports LoginLockProperties.java by holding or executing the window seconds business role.
* Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state.
*/
private long windowSeconds = 600;
/**
* Purpose: lockSeconds supports LoginLockProperties.java by holding or executing the lock seconds business role.
* Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state.
*/
private long lockSeconds = 900;
}
@@ -0,0 +1,50 @@
package com.xiaowang.yuminailcore.config;
import io.minio.MinioClient;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Data
@Configuration
@ConfigurationProperties(prefix = "minio")
/**
* Purpose: MinioConfig supports MinioConfig.java by holding or executing the minio config business role.
* Usage: reference this class from the owning layer and pass validated inputs before reading or updating related state.
*/
public class MinioConfig {
/**
* Purpose: endpoint supports MinioConfig.java by holding or executing the endpoint business role.
* Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state.
*/
private String endpoint;
/**
* Purpose: accessKey supports MinioConfig.java by holding or executing the access key business role.
* Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state.
*/
private String accessKey;
/**
* Purpose: secretKey supports MinioConfig.java by holding or executing the secret key business role.
* Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state.
*/
private String secretKey;
/**
* Purpose: bucketName supports MinioConfig.java by holding or executing the bucket name business role.
* Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state.
*/
private String bucketName;
@Bean
/**
* Purpose: minioClient supports MinioConfig.java by holding or executing the minio client business role.
* Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state.
*/
public MinioClient minioClient() {
return MinioClient.builder()
.endpoint(endpoint)
.credentials(accessKey, secretKey)
.build();
}
}
@@ -0,0 +1,87 @@
package com.xiaowang.yuminailcore.config;
import com.baomidou.mybatisplus.annotation.DbType;
import com.baomidou.mybatisplus.core.incrementer.IdentifierGenerator;
import com.baomidou.mybatisplus.extension.plugins.MybatisPlusInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.BlockAttackInnerInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.OptimisticLockerInnerInterceptor;
import com.baomidou.mybatisplus.extension.plugins.inner.PaginationInnerInterceptor;
import com.xiaowang.yuminailcore.support.id.TimeOrderedSnowflakeIdGenerator;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
* MyBatis-Plus配置类
* 配置分页、乐观锁和防止全表更新等插件
*
* @author xiaowang
* @date 2026-02-12
*/
@Configuration
@MapperScan({
"com.xiaowang.yuminailcore.modules.artist.mapper",
"com.xiaowang.yuminailcore.modules.auth.mapper",
"com.xiaowang.yuminailcore.modules.content.mapper",
"com.xiaowang.yuminailcore.modules.file.mapper",
"com.xiaowang.yuminailcore.modules.integration.mapper",
"com.xiaowang.yuminailcore.modules.inventory.mapper",
"com.xiaowang.yuminailcore.modules.marketing.mapper",
"com.xiaowang.yuminailcore.modules.message.mapper",
"com.xiaowang.yuminailcore.modules.order.mapper",
"com.xiaowang.yuminailcore.modules.payment.mapper",
"com.xiaowang.yuminailcore.modules.planning.mapper",
"com.xiaowang.yuminailcore.modules.product.mapper",
"com.xiaowang.yuminailcore.modules.security.mapper",
"com.xiaowang.yuminailcore.modules.shop.mapper",
"com.xiaowang.yuminailcore.modules.system.mapper",
"com.xiaowang.yuminailcore.modules.user.mapper"
})
public class MyBatisPlusConfig {
/**
* 配置MyBatis-Plus插件
*/
@Bean
public MybatisPlusInterceptor mybatisPlusInterceptor() {
MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
// 1. 分页插件
interceptor.addInnerInterceptor(new PaginationInnerInterceptor(DbType.MYSQL));
// 2. 乐观锁插件
interceptor.addInnerInterceptor(new OptimisticLockerInnerInterceptor());
// 3. 防止全表更新与删除插件
interceptor.addInnerInterceptor(new BlockAttackInnerInterceptor());
return interceptor;
}
@Bean
/**
* Purpose: identifierGenerator supports MyBatisPlusConfig.java by holding or executing the identifier generator business role.
* Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state.
*/
public IdentifierGenerator identifierGenerator(TimeOrderedSnowflakeIdGenerator snowflakeIdGenerator) {
return new IdentifierGenerator() {
@Override
/**
* Purpose: nextId supports MyBatisPlusConfig.java by holding or executing the next id business role.
* Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state.
*/
public Number nextId(Object entity) {
return snowflakeIdGenerator.nextId();
}
@Override
/**
* Purpose: nextUUID supports MyBatisPlusConfig.java by holding or executing the next uuid business role.
* Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state.
*/
public String nextUUID(Object entity) {
return snowflakeIdGenerator.nextIdString();
}
};
}
}
@@ -0,0 +1,41 @@
package com.xiaowang.yuminailcore.config;
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;
import java.time.LocalDateTime;
/**
* MyBatis-Plus 自动填充配置
* 用于自动填充实体类中的创建时间、更新时间等字段
*
* @author xiaowang
* @date 2026-02-12
*/
@Slf4j
@Component
public class MyMetaObjectHandler implements MetaObjectHandler {
@Override
/**
* Purpose: insertFill supports MyMetaObjectHandler.java by holding or executing the insert fill business role.
* Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state.
*/
public void insertFill(MetaObject metaObject) {
log.info("start insert fill ....");
this.strictInsertFill(metaObject, "createTime", LocalDateTime.class, LocalDateTime.now());
this.strictInsertFill(metaObject, "updateTime", LocalDateTime.class, LocalDateTime.now());
}
@Override
/**
* Purpose: updateFill supports MyMetaObjectHandler.java by holding or executing the update fill business role.
* Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state.
*/
public void updateFill(MetaObject metaObject) {
log.info("start update fill ....");
this.strictUpdateFill(metaObject, "updateTime", LocalDateTime.class, LocalDateTime.now());
}
}
@@ -0,0 +1,59 @@
package com.xiaowang.yuminailcore.config;
import org.springframework.amqp.core.Binding;
import org.springframework.amqp.core.BindingBuilder;
import org.springframework.amqp.core.DirectExchange;
import org.springframework.amqp.core.Queue;
import org.springframework.amqp.support.converter.Jackson2JsonMessageConverter;
import org.springframework.amqp.support.converter.MessageConverter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
@Configuration
public class RabbitMQConfig {
public static final String EXAMPLE_QUEUE = "yuminail.example.queue";
public static final String EXAMPLE_EXCHANGE = "yuminail.example.exchange";
public static final String EXAMPLE_ROUTING_KEY = "yuminail.example.routing.key";
public static final String FILE_OSS_BACKUP_EXCHANGE = "yuminail.file.oss.backup.exchange";
public static final String FILE_OSS_BACKUP_QUEUE = "yuminail.file.oss.backup.queue";
public static final String FILE_OSS_BACKUP_ROUTING_KEY = "yuminail.file.oss.backup";
@Bean
public MessageConverter jsonMessageConverter() {
return new Jackson2JsonMessageConverter();
}
@Bean
public Queue exampleQueue() {
return new Queue(EXAMPLE_QUEUE, true);
}
@Bean
public DirectExchange exampleExchange() {
return new DirectExchange(EXAMPLE_EXCHANGE);
}
@Bean
public Binding exampleBinding() {
return BindingBuilder.bind(exampleQueue()).to(exampleExchange()).with(EXAMPLE_ROUTING_KEY);
}
@Bean
public Queue fileOssBackupQueue() {
return new Queue(FILE_OSS_BACKUP_QUEUE, true);
}
@Bean
public DirectExchange fileOssBackupExchange() {
return new DirectExchange(FILE_OSS_BACKUP_EXCHANGE, true, false);
}
@Bean
public Binding fileOssBackupBinding() {
return BindingBuilder.bind(fileOssBackupQueue())
.to(fileOssBackupExchange())
.with(FILE_OSS_BACKUP_ROUTING_KEY);
}
}
@@ -0,0 +1,56 @@
package com.xiaowang.yuminailcore.config;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
/**
* 限流配置。
*/
@Data
@Configuration
@ConfigurationProperties(prefix = "yuminail.security.rate-limit")
public class RateLimitProperties {
private LimitRule login = new LimitRule(10, 60);
private LimitRule register = new LimitRule(5, 300);
private LimitRule sendCode = new LimitRule(5, 60);
private LimitRule resetPassword = new LimitRule(5, 600);
private LimitRule wechatMiniLogin = new LimitRule(10, 60);
private LimitRule agreementRead = new LimitRule(60, 60);
private LimitRule authenticatedWrite = new LimitRule(80, 60);
private LimitRule orderCreate = new LimitRule(10, 60);
@Data
/**
* Purpose: LimitRule supports RateLimitProperties.java by holding or executing the limit rule business role.
* Usage: reference this class from the owning layer and pass validated inputs before reading or updating related state.
*/
public static class LimitRule {
/**
* Purpose: limit supports RateLimitProperties.java by holding or executing the limit business role.
* Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state.
*/
private int limit;
/**
* Purpose: windowSeconds supports RateLimitProperties.java by holding or executing the window seconds business role.
* Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state.
*/
private long windowSeconds;
public LimitRule() {
}
public LimitRule(int limit, long windowSeconds) {
this.limit = limit;
this.windowSeconds = windowSeconds;
}
}
}
@@ -0,0 +1,56 @@
package com.xiaowang.yuminailcore.config;
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.jsontype.impl.LaissezFaireSubTypeValidator;
import org.springframework.cache.annotation.CachingConfigurerSupport;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
/**
* Redis配置类
*
* @author xiaowang
* @date 2026-02-12
*/
@Configuration
@EnableCaching
public class RedisConfig extends CachingConfigurerSupport {
@Bean
/**
* Purpose: redisTemplate supports RedisConfig.java by holding or executing the redis template business role.
* Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state.
*/
public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) {
RedisTemplate<String, Object> template = new RedisTemplate<>();
template.setConnectionFactory(factory);
// 使用Jackson2JsonRedisSerializer来序列化和反序列化redis的value值
Jackson2JsonRedisSerializer<Object> jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer<>(Object.class);
ObjectMapper om = new ObjectMapper();
om.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
om.activateDefaultTyping(LaissezFaireSubTypeValidator.instance, ObjectMapper.DefaultTyping.NON_FINAL);
jackson2JsonRedisSerializer.setObjectMapper(om);
StringRedisSerializer stringRedisSerializer = new StringRedisSerializer();
// key采用String的序列化方式
template.setKeySerializer(stringRedisSerializer);
// hash的key也采用String的序列化方式
template.setHashKeySerializer(stringRedisSerializer);
// value序列化方式采用jackson
template.setValueSerializer(jackson2JsonRedisSerializer);
// hash的value序列化方式采用jackson
template.setHashValueSerializer(jackson2JsonRedisSerializer);
template.afterPropertiesSet();
return template;
}
}
@@ -0,0 +1,29 @@
package com.xiaowang.yuminailcore.config;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
/**
* 请求签名配置。
*/
@Data
@Configuration
@ConfigurationProperties(prefix = "yuminail.security.signature")
public class RequestSignatureProperties {
/**
* 是否启用签名校验。
*/
private boolean enabled = true;
/**
* 时间窗口,单位秒。
*/
private long windowSeconds = 300;
/**
* nonce 额外保留时间,单位秒。
*/
private long nonceRetentionSeconds = 600;
}
@@ -0,0 +1,34 @@
package com.xiaowang.yuminailcore.config;
import org.springframework.stereotype.Component;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@Component
/**
* Purpose: SecurityHeadersFilter supports SecurityHeadersFilter.java by holding or executing the security headers filter business role.
* Usage: reference this class from the owning layer and pass validated inputs before reading or updating related state.
*/
public class SecurityHeadersFilter implements Filter {
@Override
/**
* Purpose: doFilter supports SecurityHeadersFilter.java by holding or executing the do filter business role.
* Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state.
*/
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
if (response instanceof HttpServletResponse httpResponse) {
httpResponse.setHeader("X-Content-Type-Options", "nosniff");
httpResponse.setHeader("X-Frame-Options", "DENY");
httpResponse.setHeader("Referrer-Policy", "strict-origin-when-cross-origin");
httpResponse.setHeader("Content-Security-Policy", "default-src 'self'; img-src 'self' data: blob: http: https:; style-src 'self' 'unsafe-inline'; script-src 'self'; connect-src 'self' http: https:");
}
chain.doFilter(request, response);
}
}
@@ -0,0 +1,33 @@
package com.xiaowang.yuminailcore.config;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
@Data
@Configuration
@ConfigurationProperties(prefix = "yuminail.slow-request")
/**
* Purpose: SlowRequestLogProperties supports SlowRequestLogProperties.java by holding or executing the slow request log properties business role.
* Usage: reference this class from the owning layer and pass validated inputs before reading or updating related state.
*/
public class SlowRequestLogProperties {
/**
* Purpose: enabled supports SlowRequestLogProperties.java by holding or executing the enabled business role.
* Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state.
*/
private boolean enabled = true;
/**
* Purpose: thresholdMs supports SlowRequestLogProperties.java by holding or executing the threshold ms business role.
* Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state.
*/
private long thresholdMs = 300;
/**
* Purpose: logResponseHeaderRequestId supports SlowRequestLogProperties.java by holding or executing the log response header request id business role.
* Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state.
*/
private boolean logResponseHeaderRequestId = true;
}
@@ -0,0 +1,172 @@
package com.xiaowang.yuminailcore.config;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.lang.Nullable;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.HandlerMapping;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.UUID;
@Component
/**
* Purpose: SlowRequestLoggingInterceptor supports SlowRequestLoggingInterceptor.java by holding or executing the slow request logging interceptor business role.
* Usage: reference this class from the owning layer and pass validated inputs before reading or updating related state.
*/
public class SlowRequestLoggingInterceptor implements HandlerInterceptor {
/**
* Purpose: REQUEST_ID_HEADER supports SlowRequestLoggingInterceptor.java by holding or executing the request id header business role.
* Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state.
*/
public static final String REQUEST_ID_HEADER = "X-Request-Id";
private static final String START_TIME_ATTRIBUTE = SlowRequestLoggingInterceptor.class.getName() + ".startTime";
private static final Logger SLOW_REQUEST_LOGGER = LoggerFactory.getLogger("core-slow");
/**
* Purpose: properties supports SlowRequestLoggingInterceptor.java by holding or executing the properties business role.
* Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state.
*/
private final SlowRequestLogProperties properties;
public SlowRequestLoggingInterceptor(SlowRequestLogProperties properties) {
this.properties = properties;
}
@Override
/**
* Purpose: preHandle supports SlowRequestLoggingInterceptor.java by holding or executing the pre handle business role.
* Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state.
*/
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
String requestId = resolveRequestId(request);
request.setAttribute(REQUEST_ID_HEADER, requestId);
if (properties.isLogResponseHeaderRequestId()) {
response.setHeader(REQUEST_ID_HEADER, requestId);
}
if (properties.isEnabled()) {
request.setAttribute(START_TIME_ATTRIBUTE, System.nanoTime());
}
return true;
}
@Override
/**
* Purpose: afterCompletion supports SlowRequestLoggingInterceptor.java by holding or executing the after completion business role.
* Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state.
*/
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable Exception ex) {
if (!properties.isEnabled()) {
return;
}
Object startTimeValue = request.getAttribute(START_TIME_ATTRIBUTE);
if (!(startTimeValue instanceof Long)) {
return;
}
long durationMs = Math.max(0L, (System.nanoTime() - (Long) startTimeValue) / 1_000_000L);
if (durationMs < properties.getThresholdMs()) {
return;
}
String requestId = (String) request.getAttribute(REQUEST_ID_HEADER);
String bestMatchingPattern = toStringValue(request.getAttribute(HandlerMapping.BEST_MATCHING_PATTERN_ATTRIBUTE));
String controllerMethod = resolveControllerMethod(handler);
String exceptionClass = ex == null ? "" : ex.getClass().getSimpleName();
SLOW_REQUEST_LOGGER.warn(
"requestId={} method={} uri={} query={} bestMatchingPattern={} controllerMethod={} status={} durationMs={} userId={} userType={} shopId={} clientIp={} contentLength={} exceptionClass={}",
sanitize(requestId),
request.getMethod(),
request.getRequestURI(),
sanitize(request.getQueryString()),
sanitize(bestMatchingPattern),
sanitize(controllerMethod),
response.getStatus(),
durationMs,
castLong(request.getAttribute("userId")),
castInteger(request.getAttribute("userType")),
castLong(request.getAttribute("currentShopId")),
resolveClientIp(request),
request.getContentLengthLong(),
sanitize(exceptionClass)
);
}
/**
* Purpose: resolveRequestId supports SlowRequestLoggingInterceptor.java by holding or executing the resolve request id business role.
* Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state.
*/
private String resolveRequestId(HttpServletRequest request) {
String requestId = request.getHeader(REQUEST_ID_HEADER);
return StringUtils.hasText(requestId) ? requestId.trim() : UUID.randomUUID().toString().replace("-", "");
}
/**
* Purpose: resolveControllerMethod supports SlowRequestLoggingInterceptor.java by holding or executing the resolve controller method business role.
* Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state.
*/
private String resolveControllerMethod(Object handler) {
if (handler instanceof HandlerMethod handlerMethod) {
return handlerMethod.getBeanType().getSimpleName() + "#" + handlerMethod.getMethod().getName();
}
return "";
}
/**
* Purpose: resolveClientIp supports SlowRequestLoggingInterceptor.java by holding or executing the resolve client ip business role.
* Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state.
*/
private String resolveClientIp(HttpServletRequest request) {
String forwarded = request.getHeader("X-Forwarded-For");
if (StringUtils.hasText(forwarded)) {
return forwarded.split(",")[0].trim();
}
String realIp = request.getHeader("X-Real-IP");
if (StringUtils.hasText(realIp)) {
return realIp.trim();
}
return request.getRemoteAddr();
}
/**
* Purpose: sanitize supports SlowRequestLoggingInterceptor.java by holding or executing the sanitize business role.
* Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state.
*/
private String sanitize(String value) {
if (!StringUtils.hasText(value)) {
return "";
}
return value.replace('\n', '_').replace('\r', '_');
}
/**
* Purpose: toStringValue supports SlowRequestLoggingInterceptor.java by holding or executing the to string value business role.
* Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state.
*/
private String toStringValue(Object value) {
return value == null ? "" : value.toString();
}
/**
* Purpose: castLong supports SlowRequestLoggingInterceptor.java by holding or executing the cast long business role.
* Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state.
*/
private Long castLong(Object value) {
return value instanceof Long ? (Long) value : null;
}
/**
* Purpose: castInteger supports SlowRequestLoggingInterceptor.java by holding or executing the cast integer business role.
* Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state.
*/
private Integer castInteger(Object value) {
return value instanceof Integer ? (Integer) value : null;
}
}
@@ -0,0 +1,31 @@
package com.xiaowang.yuminailcore.config;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
import java.util.ArrayList;
import java.util.List;
@Data
@Configuration
@ConfigurationProperties(prefix = "yuminail.security.upload")
/**
* Purpose: UploadSecurityProperties supports UploadSecurityProperties.java by holding or executing the upload security properties business role.
* Usage: reference this class from the owning layer and pass validated inputs before reading or updating related state.
*/
public class UploadSecurityProperties {
/**
* Purpose: maxSize supports UploadSecurityProperties.java by holding or executing the max size business role.
* Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state.
*/
private long maxSize = 10 * 1024 * 1024;
private List<String> allowedMimeTypes = new ArrayList<>(List.of(
"image/jpeg",
"image/png",
"image/webp",
"image/gif"
));
}
@@ -0,0 +1,75 @@
package com.xiaowang.yuminailcore.config;
import lombok.RequiredArgsConstructor;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
@RequiredArgsConstructor
/**
* Purpose: WebMvcConfig supports WebMvcConfig.java by holding or executing the web mvc config business role.
* Usage: reference this class from the owning layer and pass validated inputs before reading or updating related state.
*/
public class WebMvcConfig implements WebMvcConfigurer {
/**
* Purpose: authInterceptor supports WebMvcConfig.java by holding or executing the auth interceptor business role.
* Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state.
*/
private final AuthInterceptor authInterceptor;
/**
* Purpose: slowRequestLoggingInterceptor supports WebMvcConfig.java by holding or executing the slow request logging interceptor business role.
* Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state.
*/
private final SlowRequestLoggingInterceptor slowRequestLoggingInterceptor;
@Override
/**
* Purpose: addInterceptors supports WebMvcConfig.java by holding or executing the add interceptors business role.
* Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state.
*/
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(slowRequestLoggingInterceptor)
.addPathPatterns("/**")
.order(-100);
registry.addInterceptor(authInterceptor)
.addPathPatterns("/**")
.order(0)
.excludePathPatterns(
"/user/login",
"/user/register",
"/user/check/**",
"/user/refresh-token",
"/user/send-verification-code",
"/user/phone-login",
"/user/wechat-mini/**",
"/user/reset-password-by-phone",
"/legal-agreement/current",
"/legal-agreement/current/**",
"/api/legal-agreement/current",
"/api/legal-agreement/current/**",
"/product/get/**",
"/product/list/**",
"/comment/list/product/**",
"/api/comment/list/product/**",
"/nail-artist/profile/**",
"/nail-artist/*/availability",
"/nail-artist/*/reviews",
"/shop/get/**",
"/shop/trust-profile/**",
"/shop/list",
"/shop/list/public",
"/shop/list/simple",
"/tag/list/all",
"/tag/list/filter-options",
"/file/get-signed-url/**",
"/admin/auth/login",
"/admin/auth/login-shops/**",
"/admin/auth/refresh",
"/error",
"/health/**"
);
}
}
@@ -0,0 +1,40 @@
package com.xiaowang.yuminailcore.config;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Configuration;
/**
* 微信小程序登录配置。
*/
@Data
@Configuration
@ConfigurationProperties(prefix = "yuminail.wechat.mini")
public class WechatMiniProperties {
/**
* Purpose: appId supports WechatMiniProperties.java by holding or executing the app id business role.
* Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state.
*/
private String appId;
/**
* Purpose: appSecret supports WechatMiniProperties.java by holding or executing the app secret business role.
* Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state.
*/
private String appSecret;
/**
* Purpose: code2sessionUrl supports WechatMiniProperties.java by holding or executing the code2session url business role.
* Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state.
*/
private String code2sessionUrl = "https://api.weixin.qq.com/sns/jscode2session";
/**
* Purpose: phoneNumberUrl supports WechatMiniProperties.java by holding or executing the phone number url business role.
* Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state.
*/
private String phoneNumberUrl = "https://api.weixin.qq.com/wxa/business/getuserphonenumber";
/**
* Purpose: accessTokenBufferSeconds supports WechatMiniProperties.java by holding or executing the access token buffer seconds business role.
* Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state.
*/
private Integer accessTokenBufferSeconds = 60;
}
@@ -0,0 +1,60 @@
package com.xiaowang.yuminailcore.filter;
import com.xiaowang.yuminailcore.support.security.CachedBodyHttpServletRequest;
import com.xiaowang.yuminailcore.support.security.RequestSignatureService;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.util.StreamUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
/**
* 缓存 JSON 请求体,供签名校验复用。
*/
@Component
@Order(Ordered.HIGHEST_PRECEDENCE)
public class RequestBodyCacheFilter extends OncePerRequestFilter {
@Override
protected void doFilterInternal(HttpServletRequest request,
HttpServletResponse response,
FilterChain filterChain) throws ServletException, IOException {
if (!shouldWrap(request)) {
filterChain.doFilter(request, response);
return;
}
byte[] body = StreamUtils.copyToByteArray(request.getInputStream());
CachedBodyHttpServletRequest wrappedRequest = new CachedBodyHttpServletRequest(request, body);
wrappedRequest.setAttribute(RequestSignatureService.REQUEST_BODY_ATTRIBUTE, body);
filterChain.doFilter(wrappedRequest, response);
}
/**
* Purpose: shouldWrap supports RequestBodyCacheFilter.java by holding or executing the should wrap business role.
* Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state.
*/
private boolean shouldWrap(HttpServletRequest request) {
String method = request.getMethod();
if (!StringUtils.hasText(method)) {
return false;
}
String normalizedMethod = method.toUpperCase();
if (!("POST".equals(normalizedMethod) || "PUT".equals(normalizedMethod) || "PATCH".equals(normalizedMethod) || "DELETE".equals(normalizedMethod))) {
return false;
}
String contentType = request.getContentType();
if (!StringUtils.hasText(contentType)) {
return false;
}
String normalizedType = contentType.toLowerCase();
return normalizedType.contains("application/json");
}
}
@@ -0,0 +1,32 @@
package com.xiaowang.yuminailcore.modules.analytics.controller.admin;
import com.xiaowang.yuminailcore.annotation.RequirePermission;
import com.xiaowang.yuminailcore.common.Result;
import com.xiaowang.yuminailcore.modules.user.entity.UserDO;
import com.xiaowang.yuminailcore.modules.analytics.service.WorkbenchService;
import com.xiaowang.yuminailcore.modules.security.support.AdminScopeHelper;
import com.xiaowang.yuminailcore.modules.analytics.vo.StoreWorkbenchVO;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletRequest;
@RestController
@RequestMapping("/admin/workbench")
@RequiredArgsConstructor
public class AdminWorkbenchController {
private final AdminScopeHelper adminScopeHelper;
private final WorkbenchService workbenchService;
@GetMapping("/summary")
@RequirePermission("workbench:view")
public Result<StoreWorkbenchVO> summary(HttpServletRequest request) {
UserDO currentUser = adminScopeHelper.getCurrentUser(request);
Long shopId = adminScopeHelper.resolveShopScope(currentUser, null);
Long artistId = currentUser != null && Integer.valueOf(3).equals(currentUser.getType()) ? currentUser.getId() : null;
return Result.success(workbenchService.getWorkbench(shopId, artistId));
}
}
@@ -0,0 +1,451 @@
package com.xiaowang.yuminailcore.modules.analytics.controller.front;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.fasterxml.jackson.core.type.TypeReference;
import com.xiaowang.yuminailcore.annotation.RequirePermission;
import com.xiaowang.yuminailcore.common.Result;
import com.xiaowang.yuminailcore.config.AppCacheProperties;
import com.xiaowang.yuminailcore.modules.content.entity.CommentDO;
import com.xiaowang.yuminailcore.modules.order.entity.OrderDO;
import com.xiaowang.yuminailcore.modules.order.entity.OrderItemDO;
import com.xiaowang.yuminailcore.modules.product.entity.ProductDO;
import com.xiaowang.yuminailcore.modules.user.entity.UserDO;
import com.xiaowang.yuminailcore.modules.content.mapper.CommentMapper;
import com.xiaowang.yuminailcore.modules.order.mapper.OrderItemMapper;
import com.xiaowang.yuminailcore.modules.order.mapper.OrderMapper;
import com.xiaowang.yuminailcore.modules.product.mapper.ProductMapper;
import com.xiaowang.yuminailcore.modules.shop.mapper.ShopMapper;
import com.xiaowang.yuminailcore.modules.user.mapper.UserMapper;
import com.xiaowang.yuminailcore.modules.analytics.service.OperationsAnalyticsService;
import com.xiaowang.yuminailcore.modules.security.support.AdminScopeHelper;
import com.xiaowang.yuminailcore.modules.order.support.OrderStatus;
import com.xiaowang.yuminailcore.modules.shop.support.UserShopBindingSupport;
import com.xiaowang.yuminailcore.support.cache.MultiLevelCacheService;
import com.xiaowang.yuminailcore.modules.analytics.vo.DashboardStatsVO;
import com.xiaowang.yuminailcore.modules.product.vo.HotProductVO;
import com.xiaowang.yuminailcore.modules.analytics.vo.OperationsAnalyticsVO;
import com.xiaowang.yuminailcore.modules.analytics.vo.RecentActivityVO;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.time.Duration;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;
@RestController
@RequestMapping("/admin/dashboard")
@RequiredArgsConstructor
/**
* DashboardController exposes HTTP endpoints. Start here to learn the request path, parameter names, and which service method is called.
* Beginner guide: follow the call chain Controller -> Service -> ServiceImpl -> Mapper/support class.
*/
public class DashboardController {
/**
* Variable `userMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls.
*/
private final UserMapper userMapper;
/**
* Variable `productMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls.
*/
private final ProductMapper productMapper;
/**
* Variable `shopMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls.
*/
private final ShopMapper shopMapper;
/**
* Variable `commentMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls.
*/
private final CommentMapper commentMapper;
/**
* Variable `orderMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls.
*/
private final OrderMapper orderMapper;
/**
* Variable `orderItemMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls.
*/
private final OrderItemMapper orderItemMapper;
/**
* Variable `adminScopeHelper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls.
*/
private final AdminScopeHelper adminScopeHelper;
/**
* Variable `userShopBindingSupport`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls.
*/
private final UserShopBindingSupport userShopBindingSupport;
/**
* Variable `multiLevelCacheService`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls.
*/
private final MultiLevelCacheService multiLevelCacheService;
/**
* Variable `appCacheProperties`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls.
*/
private final AppCacheProperties appCacheProperties;
private final OperationsAnalyticsService operationsAnalyticsService;
@GetMapping("/stats")
@RequirePermission("dashboard:view")
/**
* Load data by the supplied parameter.
* Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result.
* @param request parameter `request` supplied by the caller
* @return Result<DashboardStatsVO> result consumed by the caller or returned to the frontend
*/
public Result<DashboardStatsVO> getDashboardStats(HttpServletRequest request) {
UserDO currentUser = adminScopeHelper.getCurrentUser(request);
Long shopIdScope = resolveShopScope(currentUser);
String cacheScope = currentUser == null ? "anonymous" : (shopIdScope == null ? "admin" : "shop:" + shopIdScope);
AppCacheProperties.CacheSpec cacheSpec = appCacheProperties.getDashboard();
DashboardStatsVO stats = multiLevelCacheService.getOrLoad(
"cache:dashboard:stats:" + cacheScope,
Duration.ofSeconds(cacheSpec.getLocalTtlSeconds()),
Duration.ofSeconds(cacheSpec.getRedisTtlSeconds()),
new TypeReference<DashboardStatsVO>() {
},
() -> buildDashboardStats(currentUser, shopIdScope)
);
return Result.success(stats);
}
@GetMapping("/analytics")
@RequirePermission("analytics:view")
public Result<OperationsAnalyticsVO> getAnalytics(HttpServletRequest request) {
UserDO currentUser = adminScopeHelper.getCurrentUser(request);
Long shopIdScope = resolveShopScope(currentUser);
Long artistScope = currentUser != null && Integer.valueOf(3).equals(currentUser.getType()) ? currentUser.getId() : null;
return Result.success(operationsAnalyticsService.getDashboardAnalytics(shopIdScope, artistScope));
}
/**
* Run business method `buildDashboardStats`.
* Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result.
* @param currentUser parameter `currentUser` supplied by the caller
* @param shopIdScope parameter `shopIdScope` supplied by the caller
* @return private DashboardStatsVO result consumed by the caller or returned to the frontend
*/
private DashboardStatsVO buildDashboardStats(UserDO currentUser, Long shopIdScope) {
DashboardStatsVO stats = new DashboardStatsVO();
Long artistScope = currentUser != null && Integer.valueOf(3).equals(currentUser.getType()) ? currentUser.getId() : null;
if (currentUser != null) {
// 根据用户类型显示不同的数据
if (currentUser.getType() == 4) { // 管理员
stats.setTotalUsers(userMapper.selectCount(null));
stats.setTotalProducts(productMapper.selectCount(null));
stats.setTotalShops(shopMapper.selectCount(null));
stats.setTodayOrders(getTodayOrders(null));
stats.setTotalCustomers(countUsers(null, 0, null, null));
stats.setTotalArtists(countUsers(null, 3, null, null));
} else { // 店长或美甲师
Long shopId = currentUser.getShopId();
if (shopId != null) {
shopIdScope = shopId;
// 只显示当前店铺的数据
stats.setTotalUsers(userShopBindingSupport.countUsersByShopId(shopId, false));
stats.setTotalProducts(productMapper.selectCount(new LambdaQueryWrapper<ProductDO>().eq(ProductDO::getShopId, shopId)));
stats.setTotalShops(0L); // 非管理员不显示店铺数量
stats.setTodayOrders(getTodayOrders(shopId));
stats.setTotalCustomers(countUsers(shopId, 0, null, null));
stats.setTotalArtists(countUsers(shopId, 3, null, null));
} else {
// 没有店铺ID的情况
stats.setTotalUsers(0L);
stats.setTotalProducts(0L);
stats.setTotalShops(0L);
stats.setTodayOrders(0L);
stats.setTotalCustomers(0L);
stats.setTotalArtists(0L);
}
}
} else {
// 无法获取用户信息的情况
stats.setTotalUsers(0L);
stats.setTotalProducts(0L);
stats.setTotalShops(0L);
stats.setTodayOrders(0L);
stats.setTotalCustomers(0L);
stats.setTotalArtists(0L);
}
LocalDateTime todayStart = LocalDateTime.now().withHour(0).withMinute(0).withSecond(0).withNano(0);
LocalDateTime weekStart = todayStart.minusDays(6);
stats.setTotalOrderAmount(sumOrderAmount(shopIdScope, artistScope, null, null));
stats.setTodayOrderAmount(sumOrderAmount(shopIdScope, artistScope, todayStart, null));
stats.setWeekOrderAmount(sumOrderAmount(shopIdScope, artistScope, weekStart, null));
stats.setNewCustomersToday(countUsers(shopIdScope, 0, todayStart, null));
stats.setNewCustomers7Days(countUsers(shopIdScope, 0, weekStart, null));
stats.setNewOrders7Days(countOrders(shopIdScope, artistScope, null, weekStart, null));
long priceConfirmingOrders = countOrders(shopIdScope, artistScope, OrderStatus.PRICE_CONFIRMING.getCode(), null, null);
long pendingServiceOrders = countOrders(shopIdScope, artistScope, OrderStatus.PENDING_SERVICE.getCode(), null, null);
stats.setPendingOrders(priceConfirmingOrders + pendingServiceOrders);
stats.setCompletedOrders(countOrders(shopIdScope, artistScope, OrderStatus.COMPLETED.getCode(), null, null));
stats.setHotProducts(getHotProducts(shopIdScope));
stats.setRecentActivities(getRecentActivities(shopIdScope));
return stats;
}
/**
* Run business method `resolveShopScope`.
* Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result.
* @param currentUser parameter `currentUser` supplied by the caller
* @return private Long result consumed by the caller or returned to the frontend
*/
private Long resolveShopScope(UserDO currentUser) {
if (currentUser == null || currentUser.getType() == 4) {
return null;
}
return currentUser.getShopId();
}
/**
* Purpose: countUsers supports DashboardController.java by holding or executing the count users business role.
* Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state.
*/
private Long countUsers(Long shopId, Integer type, LocalDateTime from, LocalDateTime to) {
LambdaQueryWrapper<UserDO> wrapper = new LambdaQueryWrapper<>();
if (type != null) {
wrapper.eq(UserDO::getType, type);
}
if (from != null) {
wrapper.ge(UserDO::getCreateTime, from);
}
if (to != null) {
wrapper.le(UserDO::getCreateTime, to);
}
if (shopId != null) {
List<Long> userIds = userShopBindingSupport.listUserIdsByShopId(shopId, false);
if (userIds.isEmpty()) {
return 0L;
}
wrapper.in(UserDO::getId, userIds);
}
return userMapper.selectCount(wrapper);
}
/**
* Purpose: countOrders supports DashboardController.java by holding or executing the count orders business role.
* Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state.
*/
private Long countOrders(Long shopId, Long artistId, Integer status, LocalDateTime from, LocalDateTime to) {
return (long) listScopedOrders(shopId, artistId, status, from, to).size();
}
/**
* Purpose: sumOrderAmount supports DashboardController.java by holding or executing the sum order amount business role.
* Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state.
*/
private BigDecimal sumOrderAmount(Long shopId, Long artistId, LocalDateTime from, LocalDateTime to) {
return listScopedOrders(shopId, artistId, null, from, to).stream()
.map(order -> order.getActualAmount() != null ? order.getActualAmount() : order.getTotalAmount())
.filter(amount -> amount != null)
.reduce(BigDecimal.ZERO, BigDecimal::add);
}
/**
* Purpose: listScopedOrders supports DashboardController.java by holding or executing the list scoped orders business role.
* Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state.
*/
private List<OrderDO> listScopedOrders(Long shopId, Long artistId, Integer status, LocalDateTime from, LocalDateTime to) {
LambdaQueryWrapper<OrderDO> wrapper = new LambdaQueryWrapper<>();
if (shopId != null) {
wrapper.eq(OrderDO::getShopId, shopId);
}
if (status != null) {
wrapper.eq(OrderDO::getStatus, status);
}
if (from != null) {
wrapper.ge(OrderDO::getCreateTime, from);
}
if (to != null) {
wrapper.le(OrderDO::getCreateTime, to);
}
if (artistId != null) {
Set<Long> orderIds = listOrderIdsByArtist(artistId);
if (orderIds.isEmpty()) {
return Collections.emptyList();
}
wrapper.in(OrderDO::getId, orderIds);
}
return orderMapper.selectList(wrapper);
}
/**
* Purpose: listOrderIdsByArtist supports DashboardController.java by holding or executing the list order ids by artist business role.
* Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state.
*/
private Set<Long> listOrderIdsByArtist(Long artistId) {
List<OrderItemDO> items = orderItemMapper.selectList(new LambdaQueryWrapper<OrderItemDO>()
.select(OrderItemDO::getOrderId)
.eq(OrderItemDO::getArtistId, artistId));
return items.stream()
.map(OrderItemDO::getOrderId)
.filter(id -> id != null)
.collect(Collectors.toCollection(HashSet::new));
}
/**
* Load data by the supplied parameter.
* Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result.
* @param shopId parameter `shopId` supplied by the caller
* @return private Long result consumed by the caller or returned to the frontend
*/
private Long getTodayOrders(Long shopId) {
// 获取今天的开始时间
LocalDateTime todayStart = LocalDateTime.now().withHour(0).withMinute(0).withSecond(0).withNano(0);
String todayStartStr = todayStart.format(java.time.format.DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
if (shopId != null) {
// 非管理员只查询自己店铺的订单,通过订单商品关联到商品,再关联到店铺
java.util.Map<String, Object> result = orderItemMapper.countTodayOrdersByShopId(shopId, todayStartStr);
return result != null && result.get("count") != null ? Long.valueOf(result.get("count").toString()) : 0L;
} else {
// 管理员查询所有订单
java.util.Map<String, Object> result = orderItemMapper.countTodayOrders(todayStartStr);
return result != null && result.get("count") != null ? Long.valueOf(result.get("count").toString()) : 0L;
}
}
/**
* Load data by the supplied parameter.
* Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result.
* @param shopId parameter `shopId` supplied by the caller
* @return private List<HotProductVO> result consumed by the caller or returned to the frontend
*/
private List<HotProductVO> getHotProducts(Long shopId) {
// 通过订单商品表统计每个商品的订单数量,按订单数量排序
// 使用SQL查询获取商品及其订单数量
List<Map<String, Object>> productOrderCounts = orderItemMapper.selectMaps(
new com.baomidou.mybatisplus.core.conditions.query.QueryWrapper<OrderItemDO>()
.select("product_id, COUNT(*) as order_count")
.groupBy("product_id")
.orderByDesc("order_count")
.last("LIMIT 5")
);
List<HotProductVO> hotProducts = new ArrayList<>();
// 遍历查询结果,获取商品详情
for (Map<String, Object> map : productOrderCounts) {
Long productId = Long.valueOf(map.get("product_id").toString());
ProductDO product = productMapper.selectById(productId);
if (product != null && (shopId == null || shopId.equals(product.getShopId()))) {
HotProductVO vo = new HotProductVO();
BeanUtils.copyProperties(product, vo);
vo.setLikeCount(product.getLikeCount() != null ? product.getLikeCount() : 0);
hotProducts.add(vo);
}
}
// 如果按订单数量查询没有结果,使用点赞数作为备选
if (hotProducts.isEmpty()) {
LambdaQueryWrapper<ProductDO> wrapper = new LambdaQueryWrapper<>();
if (shopId != null) {
wrapper.eq(ProductDO::getShopId, shopId);
}
wrapper.orderByDesc(ProductDO::getLikeCount)
.last("LIMIT 5");
List<ProductDO> products = productMapper.selectList(wrapper);
hotProducts = products.stream().map(product -> {
HotProductVO vo = new HotProductVO();
BeanUtils.copyProperties(product, vo);
vo.setLikeCount(product.getLikeCount() != null ? product.getLikeCount() : 0);
return vo;
}).collect(Collectors.toList());
}
return hotProducts;
}
/**
* Load data by the supplied parameter.
* Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result.
* @param shopId parameter `shopId` supplied by the caller
* @return private List<RecentActivityVO> result consumed by the caller or returned to the frontend
*/
private List<RecentActivityVO> getRecentActivities(Long shopId) {
List<RecentActivityVO> activities = new ArrayList<>();
LambdaQueryWrapper<UserDO> userWrapper = new LambdaQueryWrapper<>();
if (shopId != null) {
List<Long> userIds = userShopBindingSupport.listUserIdsByShopId(shopId, false);
if (userIds.isEmpty()) {
userWrapper.eq(UserDO::getId, -1L);
} else {
userWrapper.in(UserDO::getId, userIds);
}
}
userWrapper.orderByDesc(UserDO::getCreateTime)
.last("LIMIT 3");
List<UserDO> recentUsers = userMapper.selectList(userWrapper);
for (UserDO user : recentUsers) {
RecentActivityVO vo = new RecentActivityVO();
vo.setId(user.getId());
vo.setType("user");
vo.setTitle("新用户注册");
vo.setDescription("用户\"" + user.getNickname() + "\"注册成功");
vo.setTime(user.getCreateTime());
vo.setColor("");
activities.add(vo);
}
LambdaQueryWrapper<ProductDO> productWrapper = new LambdaQueryWrapper<>();
if (shopId != null) {
productWrapper.eq(ProductDO::getShopId, shopId);
}
productWrapper.orderByDesc(ProductDO::getCreateTime)
.last("LIMIT 2");
List<ProductDO> recentProducts = productMapper.selectList(productWrapper);
for (ProductDO product : recentProducts) {
RecentActivityVO vo = new RecentActivityVO();
vo.setId(product.getId());
vo.setType("product");
vo.setTitle("新品上架");
vo.setDescription("新品\"" + product.getTitle() + "\"已上架");
vo.setTime(product.getCreateTime());
vo.setColor("blue");
activities.add(vo);
}
LambdaQueryWrapper<CommentDO> commentWrapper = new LambdaQueryWrapper<>();
if (shopId != null) {
commentWrapper.eq(CommentDO::getShopId, shopId);
}
commentWrapper.orderByDesc(CommentDO::getCreateTime)
.last("LIMIT 2");
List<CommentDO> recentComments = commentMapper.selectList(commentWrapper);
for (CommentDO comment : recentComments) {
RecentActivityVO vo = new RecentActivityVO();
vo.setId(comment.getId());
vo.setType("comment");
vo.setTitle("用户评论");
String content = comment.getCommentContent();
if (content != null && content.length() > 20) {
content = content.substring(0, 20) + "...";
}
vo.setDescription(content != null ? content : "用户发表了评论");
vo.setTime(comment.getCreateTime());
vo.setColor("green");
activities.add(vo);
}
activities.sort((a, b) -> b.getTime().compareTo(a.getTime()));
return activities.stream().limit(5).collect(Collectors.toList());
}
}
@@ -0,0 +1,7 @@
package com.xiaowang.yuminailcore.modules.analytics.service;
import com.xiaowang.yuminailcore.modules.analytics.vo.OperationsAnalyticsVO;
public interface OperationsAnalyticsService {
OperationsAnalyticsVO getDashboardAnalytics(Long shopId, Long artistId);
}
@@ -0,0 +1,7 @@
package com.xiaowang.yuminailcore.modules.analytics.service;
import com.xiaowang.yuminailcore.modules.analytics.vo.StoreWorkbenchVO;
public interface WorkbenchService {
StoreWorkbenchVO getWorkbench(Long shopId, Long artistId);
}
@@ -0,0 +1,66 @@
package com.xiaowang.yuminailcore.modules.analytics.service.impl;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.xiaowang.yuminailcore.modules.order.entity.OrderDO;
import com.xiaowang.yuminailcore.modules.order.entity.OrderItemDO;
import com.xiaowang.yuminailcore.modules.product.entity.ProductDO;
import com.xiaowang.yuminailcore.modules.user.entity.UserGrowthRecordDO;
import com.xiaowang.yuminailcore.modules.order.mapper.OrderItemMapper;
import com.xiaowang.yuminailcore.modules.order.mapper.OrderMapper;
import com.xiaowang.yuminailcore.modules.product.mapper.ProductMapper;
import com.xiaowang.yuminailcore.modules.user.mapper.UserGrowthRecordMapper;
import com.xiaowang.yuminailcore.modules.analytics.service.OperationsAnalyticsService;
import com.xiaowang.yuminailcore.modules.analytics.vo.OperationsAnalyticsVO;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import java.math.BigDecimal;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
@Service
@RequiredArgsConstructor
public class OperationsAnalyticsServiceImpl implements OperationsAnalyticsService {
private final OrderMapper orderMapper;
private final OrderItemMapper orderItemMapper;
private final ProductMapper productMapper;
private final UserGrowthRecordMapper userGrowthRecordMapper;
@Override
public OperationsAnalyticsVO getDashboardAnalytics(Long shopId, Long artistId) {
List<OrderDO> orders = orderMapper.selectList(new LambdaQueryWrapper<OrderDO>()
.eq(shopId != null, OrderDO::getShopId, shopId)
.eq(OrderDO::getIsDelete, 0));
if (artistId != null) {
Set<Long> orderIds = new HashSet<>();
orderItemMapper.selectList(new LambdaQueryWrapper<OrderItemDO>()
.eq(OrderItemDO::getArtistId, artistId)
.eq(OrderItemDO::getIsDelete, 0))
.forEach(item -> orderIds.add(item.getOrderId()));
orders = orders.stream().filter(order -> orderIds.contains(order.getId())).toList();
}
OperationsAnalyticsVO vo = new OperationsAnalyticsVO();
vo.setViewCount(productMapper.selectList(new LambdaQueryWrapper<ProductDO>()
.eq(shopId != null, ProductDO::getShopId, shopId)
.eq(ProductDO::getIsDelete, 0))
.stream().map(ProductDO::getLikeCount).filter(v -> v != null).mapToLong(Integer::longValue).sum());
vo.setFavoriteCount(productMapper.selectList(new LambdaQueryWrapper<ProductDO>()
.eq(shopId != null, ProductDO::getShopId, shopId)
.eq(ProductDO::getIsDelete, 0))
.stream().map(ProductDO::getCollectCount).filter(v -> v != null).mapToLong(Integer::longValue).sum());
vo.setCartCount(0L);
vo.setOrderCount((long) orders.size());
vo.setPaidOrderCount(orders.stream().filter(order -> "PAID".equals(order.getPaymentStatus())).count());
vo.setCompletedOrderCount(orders.stream().filter(order -> Integer.valueOf(2).equals(order.getStatus())).count());
vo.setReviewCount(userGrowthRecordMapper.selectCount(new LambdaQueryWrapper<UserGrowthRecordDO>()
.eq(UserGrowthRecordDO::getSourceType, "REVIEW")));
vo.setRebookCount(userGrowthRecordMapper.selectCount(new LambdaQueryWrapper<UserGrowthRecordDO>()
.eq(UserGrowthRecordDO::getSourceType, "REBOOK")));
vo.setTotalAmount(orders.stream()
.map(order -> order.getActualAmount() == null ? BigDecimal.ZERO : order.getActualAmount())
.reduce(BigDecimal.ZERO, BigDecimal::add));
return vo;
}
}
@@ -0,0 +1,146 @@
package com.xiaowang.yuminailcore.modules.analytics.service.impl;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.xiaowang.yuminailcore.modules.order.entity.AfterSaleDO;
import com.xiaowang.yuminailcore.modules.artist.entity.ArtistScheduleDO;
import com.xiaowang.yuminailcore.modules.inventory.entity.InventoryItemDO;
import com.xiaowang.yuminailcore.modules.order.entity.OrderArtistChangeRequestDO;
import com.xiaowang.yuminailcore.modules.order.entity.OrderArtistReviewDO;
import com.xiaowang.yuminailcore.modules.order.entity.OrderDO;
import com.xiaowang.yuminailcore.modules.order.entity.OrderItemDO;
import com.xiaowang.yuminailcore.modules.order.mapper.AfterSaleMapper;
import com.xiaowang.yuminailcore.modules.artist.mapper.ArtistScheduleMapper;
import com.xiaowang.yuminailcore.modules.inventory.mapper.InventoryItemMapper;
import com.xiaowang.yuminailcore.modules.order.mapper.OrderArtistChangeRequestMapper;
import com.xiaowang.yuminailcore.modules.order.mapper.OrderArtistReviewMapper;
import com.xiaowang.yuminailcore.modules.order.mapper.OrderItemMapper;
import com.xiaowang.yuminailcore.modules.order.mapper.OrderMapper;
import com.xiaowang.yuminailcore.modules.analytics.service.WorkbenchService;
import com.xiaowang.yuminailcore.modules.order.support.OrderStatus;
import com.xiaowang.yuminailcore.modules.analytics.vo.StoreWorkbenchVO;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
@Service
@RequiredArgsConstructor
public class WorkbenchServiceImpl implements WorkbenchService {
private final OrderMapper orderMapper;
private final OrderItemMapper orderItemMapper;
private final AfterSaleMapper afterSaleMapper;
private final OrderArtistChangeRequestMapper orderArtistChangeRequestMapper;
private final InventoryItemMapper inventoryItemMapper;
private final ArtistScheduleMapper artistScheduleMapper;
private final OrderArtistReviewMapper orderArtistReviewMapper;
@Override
public StoreWorkbenchVO getWorkbench(Long shopId, Long artistId) {
LocalDateTime todayStart = LocalDate.now().atStartOfDay();
LocalDateTime tomorrowStart = todayStart.plusDays(1);
List<OrderDO> orders = scopedOrders(shopId, artistId);
StoreWorkbenchVO vo = new StoreWorkbenchVO();
vo.setTodayOrderCount(orders.stream().filter(order -> between(order.getCreateTime(), todayStart, tomorrowStart)).count());
vo.setPendingOrderCount(orders.stream().filter(this::isActionableOrder).count());
vo.setPendingAfterSaleCount(countAfterSales(shopId));
vo.setPendingArtistChangeCount(countArtistChanges(shopId, artistId));
vo.setLowStockItemCount(countLowStock(shopId));
vo.setScheduleReminderCount(countMissingSchedules(shopId, artistId, todayStart.toLocalDate()));
vo.setTodayServiceCount(countTodayServices(artistId, todayStart, tomorrowStart));
vo.setCompletedServiceCount(orders.stream().filter(order -> Integer.valueOf(2).equals(order.getStatus())).count());
vo.setServiceAmount(orders.stream()
.map(order -> order.getActualAmount() == null ? BigDecimal.ZERO : order.getActualAmount())
.reduce(BigDecimal.ZERO, BigDecimal::add));
vo.setAverageRating(resolveRating(artistId));
return vo;
}
private boolean isActionableOrder(OrderDO order) {
if (order == null || order.getStatus() == null) {
return false;
}
return Integer.valueOf(OrderStatus.PRICE_CONFIRMING.getCode()).equals(order.getStatus())
|| Integer.valueOf(OrderStatus.PENDING_SERVICE.getCode()).equals(order.getStatus());
}
private List<OrderDO> scopedOrders(Long shopId, Long artistId) {
List<OrderDO> orders = orderMapper.selectList(new LambdaQueryWrapper<OrderDO>()
.eq(shopId != null, OrderDO::getShopId, shopId)
.eq(OrderDO::getIsDelete, 0));
if (artistId == null) {
return orders;
}
Set<Long> orderIds = new HashSet<>();
orderItemMapper.selectList(new LambdaQueryWrapper<OrderItemDO>()
.eq(OrderItemDO::getArtistId, artistId)
.eq(OrderItemDO::getIsDelete, 0))
.forEach(item -> orderIds.add(item.getOrderId()));
return orders.stream().filter(order -> orderIds.contains(order.getId())).toList();
}
private long countAfterSales(Long shopId) {
return afterSaleMapper.selectCount(new LambdaQueryWrapper<AfterSaleDO>()
.eq(shopId != null, AfterSaleDO::getShopId, shopId)
.eq(AfterSaleDO::getStatus, "PENDING")
.eq(AfterSaleDO::getIsDelete, 0));
}
private long countArtistChanges(Long shopId, Long artistId) {
return orderArtistChangeRequestMapper.selectCount(new LambdaQueryWrapper<OrderArtistChangeRequestDO>()
.eq(shopId != null, OrderArtistChangeRequestDO::getShopId, shopId)
.eq(artistId != null, OrderArtistChangeRequestDO::getRequesterId, artistId)
.eq(OrderArtistChangeRequestDO::getStatus, "PENDING")
.eq(OrderArtistChangeRequestDO::getIsDelete, 0));
}
private long countLowStock(Long shopId) {
return inventoryItemMapper.selectList(new LambdaQueryWrapper<InventoryItemDO>()
.eq(shopId != null, InventoryItemDO::getShopId, shopId)
.eq(InventoryItemDO::getIsDelete, 0))
.stream()
.filter(item -> item.getStockQuantity() != null
&& item.getWarningThreshold() != null
&& item.getStockQuantity().compareTo(item.getWarningThreshold()) <= 0)
.count();
}
private long countMissingSchedules(Long shopId, Long artistId, LocalDate today) {
return artistScheduleMapper.selectCount(new LambdaQueryWrapper<ArtistScheduleDO>()
.eq(shopId != null, ArtistScheduleDO::getShopId, shopId)
.eq(artistId != null, ArtistScheduleDO::getArtistId, artistId)
.ge(ArtistScheduleDO::getWorkDate, today)
.lt(ArtistScheduleDO::getWorkDate, today.plusDays(3))
.eq(ArtistScheduleDO::getIsDelete, 0));
}
private long countTodayServices(Long artistId, LocalDateTime todayStart, LocalDateTime tomorrowStart) {
if (artistId == null) {
return 0L;
}
return orderItemMapper.selectList(new LambdaQueryWrapper<OrderItemDO>()
.eq(OrderItemDO::getArtistId, artistId)
.ge(OrderItemDO::getAppointmentTime, todayStart)
.lt(OrderItemDO::getAppointmentTime, tomorrowStart)
.eq(OrderItemDO::getIsDelete, 0))
.size();
}
private BigDecimal resolveRating(Long artistId) {
if (artistId == null) {
return BigDecimal.ZERO.setScale(1, RoundingMode.HALF_UP);
}
BigDecimal rating = orderArtistReviewMapper.selectAverageSubmittedRatingByArtistId(artistId);
return (rating == null ? BigDecimal.ZERO : rating).setScale(1, RoundingMode.HALF_UP);
}
private boolean between(LocalDateTime value, LocalDateTime start, LocalDateTime end) {
return value != null && !value.isBefore(start) && value.isBefore(end);
}
}
@@ -0,0 +1,89 @@
package com.xiaowang.yuminailcore.modules.analytics.vo;
import lombok.Data;
import java.math.BigDecimal;
import java.util.List;
import com.xiaowang.yuminailcore.modules.product.vo.HotProductVO;
@Data
/**
* DashboardStatsVO is a response VO. Services build it and controllers return it to the frontend.
* Field and parameter names are kept consistent with the frontend/API payload to make tracing easier.
*/
public class DashboardStatsVO {
/**
* Field `totalUsers` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled.
*/
private Long totalUsers;
/**
* Field `totalProducts` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled.
*/
private Long totalProducts;
/**
* Field `totalShops` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled.
*/
private Long totalShops;
/**
* Field `todayOrders` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled.
*/
private Long todayOrders;
/**
* Purpose: totalOrderAmount supports DashboardStatsVO.java by holding or executing the total order amount business role.
* Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state.
*/
private BigDecimal totalOrderAmount;
/**
* Purpose: todayOrderAmount supports DashboardStatsVO.java by holding or executing the today order amount business role.
* Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state.
*/
private BigDecimal todayOrderAmount;
/**
* Purpose: weekOrderAmount supports DashboardStatsVO.java by holding or executing the week order amount business role.
* Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state.
*/
private BigDecimal weekOrderAmount;
/**
* Purpose: totalCustomers supports DashboardStatsVO.java by holding or executing the total customers business role.
* Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state.
*/
private Long totalCustomers;
/**
* Purpose: totalArtists supports DashboardStatsVO.java by holding or executing the total artists business role.
* Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state.
*/
private Long totalArtists;
/**
* Purpose: newCustomersToday supports DashboardStatsVO.java by holding or executing the new customers today business role.
* Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state.
*/
private Long newCustomersToday;
/**
* Purpose: newCustomers7Days supports DashboardStatsVO.java by holding or executing the new customers7 days business role.
* Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state.
*/
private Long newCustomers7Days;
/**
* Purpose: newOrders7Days supports DashboardStatsVO.java by holding or executing the new orders7 days business role.
* Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state.
*/
private Long newOrders7Days;
/**
* Purpose: pendingOrders supports DashboardStatsVO.java by holding or executing the pending orders business role.
* Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state.
*/
private Long pendingOrders;
/**
* Purpose: completedOrders supports DashboardStatsVO.java by holding or executing the completed orders business role.
* Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state.
*/
private Long completedOrders;
/**
* Field `hotProducts` (List<HotProductVO>): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled.
*/
private List<HotProductVO> hotProducts;
/**
* Field `recentActivities` (List<RecentActivityVO>): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled.
*/
private List<RecentActivityVO> recentActivities;
}
@@ -0,0 +1,18 @@
package com.xiaowang.yuminailcore.modules.analytics.vo;
import lombok.Data;
import java.math.BigDecimal;
@Data
public class OperationsAnalyticsVO {
private Long viewCount;
private Long favoriteCount;
private Long cartCount;
private Long orderCount;
private Long paidOrderCount;
private Long completedOrderCount;
private Long reviewCount;
private Long rebookCount;
private BigDecimal totalAmount;
}
@@ -0,0 +1,37 @@
package com.xiaowang.yuminailcore.modules.analytics.vo;
import lombok.Data;
import java.time.LocalDateTime;
@Data
/**
* RecentActivityVO is a response VO. Services build it and controllers return it to the frontend.
* Field and parameter names are kept consistent with the frontend/API payload to make tracing easier.
*/
public class RecentActivityVO {
/**
* Field `id` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled.
*/
private Long id;
/**
* Field `type` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled.
*/
private String type;
/**
* Field `title` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled.
*/
private String title;
/**
* Field `description` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled.
*/
private String description;
/**
* Field `time` (LocalDateTime): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled.
*/
private LocalDateTime time;
/**
* Field `color` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled.
*/
private String color;
}
@@ -0,0 +1,19 @@
package com.xiaowang.yuminailcore.modules.analytics.vo;
import lombok.Data;
import java.math.BigDecimal;
@Data
public class StoreWorkbenchVO {
private Long todayOrderCount;
private Long pendingOrderCount;
private Long pendingAfterSaleCount;
private Long pendingArtistChangeCount;
private Long lowStockItemCount;
private Long scheduleReminderCount;
private Long todayServiceCount;
private Long completedServiceCount;
private BigDecimal serviceAmount;
private BigDecimal averageRating;
}
@@ -0,0 +1,59 @@
package com.xiaowang.yuminailcore.modules.artist.controller.admin;
import com.xiaowang.yuminailcore.annotation.RequirePermission;
import com.xiaowang.yuminailcore.common.Result;
import com.xiaowang.yuminailcore.modules.artist.dto.ArtistScheduleDTO;
import com.xiaowang.yuminailcore.modules.user.entity.UserDO;
import com.xiaowang.yuminailcore.modules.artist.service.ArtistScheduleService;
import com.xiaowang.yuminailcore.modules.security.support.AdminScopeHelper;
import com.xiaowang.yuminailcore.modules.security.support.SecurityAuditActions;
import com.xiaowang.yuminailcore.modules.security.support.SecurityAuditSupport;
import com.xiaowang.yuminailcore.modules.artist.vo.ArtistScheduleVO;
import lombok.RequiredArgsConstructor;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletRequest;
import java.time.LocalDate;
import java.util.List;
@RestController
@RequestMapping("/admin/artist-schedule")
@RequiredArgsConstructor
public class AdminArtistScheduleController {
private final ArtistScheduleService artistScheduleService;
private final AdminScopeHelper adminScopeHelper;
private final SecurityAuditSupport securityAuditSupport;
@PostMapping("/save")
@RequirePermission("schedule:edit")
public Result<ArtistScheduleVO> save(HttpServletRequest request, @RequestBody ArtistScheduleDTO dto) {
UserDO currentUser = adminScopeHelper.getCurrentUser(request);
dto.setShopId(adminScopeHelper.resolveShopScope(currentUser, dto.getShopId()));
try {
ArtistScheduleVO result = artistScheduleService.saveSchedule(dto);
securityAuditSupport.success(request, SecurityAuditActions.SCHEDULE_UPDATE, "artistId=" + dto.getArtistId() + ",date=" + dto.getWorkDate());
return Result.success(result);
} catch (RuntimeException exception) {
securityAuditSupport.fail(request, SecurityAuditActions.SCHEDULE_UPDATE, "artistId=" + dto.getArtistId() + ",reason=" + exception.getMessage());
throw exception;
}
}
@GetMapping("/list")
@RequirePermission("schedule:view")
public Result<List<ArtistScheduleVO>> list(HttpServletRequest request,
@RequestParam(required = false) Long artistId,
@RequestParam(required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate startDate,
@RequestParam(required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate endDate) {
UserDO currentUser = adminScopeHelper.getCurrentUser(request);
Long shopId = adminScopeHelper.resolveShopScope(currentUser, null);
return Result.success(artistScheduleService.listSchedules(shopId, artistId, startDate, endDate));
}
}
@@ -0,0 +1,142 @@
package com.xiaowang.yuminailcore.modules.artist.controller.admin;
import com.xiaowang.yuminailcore.annotation.RequirePermission;
import com.xiaowang.yuminailcore.annotation.OperationGuard;
import com.xiaowang.yuminailcore.common.Result;
import com.xiaowang.yuminailcore.modules.artist.dto.NailArtistInfoDTO;
import com.xiaowang.yuminailcore.modules.user.entity.UserDO;
import com.xiaowang.yuminailcore.modules.artist.service.NailArtistInfoService;
import com.xiaowang.yuminailcore.modules.security.support.AdminScopeHelper;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
@RestController
@RequestMapping("/admin/nail-artist")
@RequiredArgsConstructor
/**
* AdminNailArtistController exposes HTTP endpoints. Start here to learn the request path, parameter names, and which service method is called.
* Beginner guide: follow the call chain Controller -> Service -> ServiceImpl -> Mapper/support class.
*/
public class AdminNailArtistController {
/**
* Purpose: USER_NOT_FOUND_MESSAGE supports AdminNailArtistController.java by holding or executing the user not found message business role.
* Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state.
*/
private static final String USER_NOT_FOUND_MESSAGE = "用户信息不存在";
/**
* Purpose: VIEW_SCOPE_MESSAGE supports AdminNailArtistController.java by holding or executing the view scope message business role.
* Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state.
*/
private static final String VIEW_SCOPE_MESSAGE = "当前登录店铺无权查看该美甲师,请切换到所属店铺后重试";
/**
* Purpose: EDIT_SCOPE_MESSAGE supports AdminNailArtistController.java by holding or executing the edit scope message business role.
* Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state.
*/
private static final String EDIT_SCOPE_MESSAGE = "当前登录店铺无权编辑该美甲师,请切换到所属店铺后重试";
/**
* Variable `nailArtistInfoService`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls.
*/
private final NailArtistInfoService nailArtistInfoService;
/**
* Variable `adminScopeHelper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls.
*/
private final AdminScopeHelper adminScopeHelper;
@RequirePermission("nail_artist:view")
@GetMapping("/list")
/**
* Load data by the supplied parameter.
* Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result.
* @param request parameter `request` supplied by the caller
* @return Result<List<NailArtistInfoDTO>> result consumed by the caller or returned to the frontend
*/
public Result<List<NailArtistInfoDTO>> getAllNailArtists(HttpServletRequest request) {
UserDO currentUser = adminScopeHelper.getCurrentUser(request);
if (currentUser == null) {
return Result.error(USER_NOT_FOUND_MESSAGE);
}
List<NailArtistInfoDTO> nailArtistInfoDTOList;
if (Integer.valueOf(4).equals(currentUser.getType())) {
nailArtistInfoDTOList = nailArtistInfoService.getAllNailArtists();
} else if (Integer.valueOf(2).equals(currentUser.getType())) {
nailArtistInfoDTOList = nailArtistInfoService.getByShopId(currentUser.getShopId());
} else {
return Result.error("权限不足:缺少权限【查看美甲师】(nail_artist:view)");
}
return Result.success(nailArtistInfoDTOList);
}
@RequirePermission("nail_artist:view")
@GetMapping("/get/{userId}")
/**
* Load data by the supplied parameter.
* Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result.
* @param userId parameter `userId` supplied by the caller
* @param request parameter `request` supplied by the caller
* @return Result<NailArtistInfoDTO> result consumed by the caller or returned to the frontend
*/
public Result<NailArtistInfoDTO> getNailArtistInfo(@PathVariable Long userId, HttpServletRequest request) {
UserDO currentUser = adminScopeHelper.getCurrentUser(request);
if (currentUser == null) {
return Result.error(USER_NOT_FOUND_MESSAGE);
}
if (!Integer.valueOf(4).equals(currentUser.getType())) {
if (Integer.valueOf(2).equals(currentUser.getType())) {
adminScopeHelper.ensureUserAccessibleInCurrentShop(currentUser, userId, VIEW_SCOPE_MESSAGE);
} else if (Integer.valueOf(3).equals(currentUser.getType())) {
if (!currentUser.getId().equals(userId)) {
return Result.error(VIEW_SCOPE_MESSAGE);
}
} else {
return Result.error("权限不足:缺少权限【查看美甲师】(nail_artist:view)");
}
}
NailArtistInfoDTO nailArtistInfoDTO = nailArtistInfoService.getByUserId(userId);
return Result.success(nailArtistInfoDTO);
}
@RequirePermission("nail_artist:edit")
@PostMapping("/save")
@OperationGuard(action = "admin-nail-artist-save", ttlSeconds = 10, message = "保存处理中,请勿重复提交")
/**
* Save submitted data.
* Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result.
* @param nailArtistInfoDTO parameter `nailArtistInfoDTO` supplied by the caller
* @param request parameter `request` supplied by the caller
* @return Result<NailArtistInfoDTO> result consumed by the caller or returned to the frontend
*/
public Result<NailArtistInfoDTO> saveNailArtistInfo(@RequestBody NailArtistInfoDTO nailArtistInfoDTO, HttpServletRequest request) {
UserDO currentUser = adminScopeHelper.getCurrentUser(request);
if (currentUser == null) {
return Result.error(USER_NOT_FOUND_MESSAGE);
}
if (!Integer.valueOf(4).equals(currentUser.getType())) {
if (Integer.valueOf(2).equals(currentUser.getType())) {
adminScopeHelper.ensureUserAccessibleInCurrentShop(currentUser, nailArtistInfoDTO.getUserId(), EDIT_SCOPE_MESSAGE);
} else if (Integer.valueOf(3).equals(currentUser.getType())) {
if (!currentUser.getId().equals(nailArtistInfoDTO.getUserId())) {
return Result.error(EDIT_SCOPE_MESSAGE);
}
} else {
return Result.error("权限不足:缺少权限【编辑美甲师】(nail_artist:edit)");
}
}
NailArtistInfoDTO saved = nailArtistInfoService.saveOrUpdateNailArtistInfo(nailArtistInfoDTO);
return Result.success(saved);
}
}
@@ -0,0 +1,68 @@
package com.xiaowang.yuminailcore.modules.artist.controller.front;
import com.xiaowang.yuminailcore.common.Result;
import com.xiaowang.yuminailcore.modules.artist.dto.NailArtistInfoDTO;
import com.xiaowang.yuminailcore.modules.artist.service.NailArtistInfoService;
import com.xiaowang.yuminailcore.modules.artist.vo.NailArtistAvailabilityVO;
import com.xiaowang.yuminailcore.modules.artist.vo.NailArtistProfileVO;
import com.xiaowang.yuminailcore.modules.artist.vo.NailArtistReviewVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
/**
* 美甲师信息Controller(前台)
*/
@RestController
@RequestMapping("/nail-artist")
public class NailArtistController {
@Autowired
/**
* Purpose: nailArtistInfoService supports NailArtistController.java by holding or executing the nail artist info service business role.
* Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state.
*/
private NailArtistInfoService nailArtistInfoService;
/**
* 获取所有可用的美甲师信息(前台使用)
*/
@GetMapping("/list")
public Result<List<NailArtistInfoDTO>> getAllAvailableNailArtists() {
List<NailArtistInfoDTO> nailArtistInfoDTOList = nailArtistInfoService.getAllAvailableNailArtists();
return Result.success(nailArtistInfoDTOList);
}
@GetMapping("/list/shop/{shopId}")
public Result<List<NailArtistInfoDTO>> listByShopId(@PathVariable Long shopId) {
return Result.success(nailArtistInfoService.getByShopId(shopId));
}
/**
* 根据用户ID获取美甲师信息(前台使用)
*/
@GetMapping("/get/{userId}")
public Result<NailArtistInfoDTO> getNailArtistInfo(@PathVariable Long userId) {
NailArtistInfoDTO nailArtistInfoDTO = nailArtistInfoService.getByUserId(userId);
return Result.success(nailArtistInfoDTO);
}
@GetMapping("/profile/{artistId}")
public Result<NailArtistProfileVO> getPublicProfile(@PathVariable Long artistId) {
return Result.success(nailArtistInfoService.getPublicProfile(artistId));
}
@GetMapping("/{artistId}/availability")
public Result<List<NailArtistAvailabilityVO>> getAvailability(@PathVariable Long artistId) {
return Result.success(nailArtistInfoService.getAvailability(artistId));
}
@GetMapping("/{artistId}/reviews")
public Result<List<NailArtistReviewVO>> listPublicReviews(@PathVariable Long artistId) {
return Result.success(nailArtistInfoService.listPublicReviews(artistId));
}
}
@@ -0,0 +1,19 @@
package com.xiaowang.yuminailcore.modules.artist.dto;
import lombok.Data;
import java.time.LocalDate;
import java.time.LocalTime;
@Data
public class ArtistScheduleDTO {
private Long shopId;
private Long artistId;
private LocalDate workDate;
private LocalTime startTime;
private LocalTime endTime;
private Integer slotMinutes;
private Integer capacity;
private Integer status;
private String remark;
}
@@ -0,0 +1,102 @@
package com.xiaowang.yuminailcore.modules.artist.dto;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import com.fasterxml.jackson.databind.ser.std.ToStringSerializer;
import lombok.Data;
import java.math.BigDecimal;
import java.time.LocalTime;
/**
* 美甲师信息DTO
*/
@Data
public class NailArtistInfoDTO {
/**
* 主键ID
*/
@JsonSerialize(using = ToStringSerializer.class)
private Long id;
/**
* 关联用户表主键(美甲师用户)
*/
@JsonSerialize(using = ToStringSerializer.class)
private Long userId;
/**
* 身份
*/
private String identity;
/**
* 从业年限
*/
private Integer experience;
/**
* 技能标签ID集合,多个ID以逗号分隔
*/
private String skills;
/**
* 评分
*/
private BigDecimal rating;
/**
* 状态:1-营业中,0-休息中
*/
private Integer status;
/**
* Field `participateProduction` (Integer): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled.
*/
private Integer participateProduction;
/**
* Field `workStartTime` (LocalTime): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled.
*/
private LocalTime workStartTime;
/**
* Field `workEndTime` (LocalTime): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled.
*/
private LocalTime workEndTime;
/**
* Field `userType` (Integer): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled.
*/
private Integer userType;
/**
* Field `userTypeName` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled.
*/
private String userTypeName;
/**
* 作品集商品ID集合,多个ID以逗号分隔
*/
private String portfolio;
/**
* 美甲师姓名(从用户表获取)
*/
private String nickname;
/**
* 所属店铺ID
*/
@JsonSerialize(using = ToStringSerializer.class)
private Long shopId;
/**
* 店铺名称
*/
private String shopName;
/**
* 用户签名
*/
private String signature;
}
@@ -0,0 +1,38 @@
package com.xiaowang.yuminailcore.modules.artist.entity;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableLogic;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.Data;
import lombok.EqualsAndHashCode;
import java.time.LocalDate;
import java.time.LocalTime;
import com.xiaowang.yuminailcore.common.entity.BaseEntity;
@Data
@EqualsAndHashCode(callSuper = true)
@TableName("t_artist_schedule")
public class ArtistScheduleDO extends BaseEntity {
@TableField("shop_id")
private Long shopId;
@TableField("artist_id")
private Long artistId;
@TableField("work_date")
private LocalDate workDate;
@TableField("start_time")
private LocalTime startTime;
@TableField("end_time")
private LocalTime endTime;
@TableField("slot_minutes")
private Integer slotMinutes;
@TableField("capacity")
private Integer capacity;
@TableField("status")
private Integer status;
@TableField("remark")
private String remark;
@TableField("is_delete")
@TableLogic
private Integer isDelete;
}
@@ -0,0 +1,79 @@
package com.xiaowang.yuminailcore.modules.artist.entity;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableLogic;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.Data;
import lombok.EqualsAndHashCode;
import java.math.BigDecimal;
import java.time.LocalTime;
import com.xiaowang.yuminailcore.common.entity.BaseEntity;
/**
* 美甲师信息实体类
*/
@Data
@EqualsAndHashCode(callSuper = true)
@TableName("t_nail_artist_info")
public class NailArtistInfoDO extends BaseEntity {
/**
* 关联用户表主键(美甲师用户)
*/
private Long userId;
/**
* 身份
*/
private String identity;
/**
* 从业年限
*/
private Integer experience;
/**
* 技能标签ID集合,多个ID以逗号分隔
*/
private String skills;
/**
* 评分
*/
private BigDecimal rating;
/**
* 状态:1-营业中,0-休息中
*/
private Integer status;
@TableField("participate_production")
/**
* Field `participateProduction` (Integer): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled.
*/
private Integer participateProduction;
@TableField("work_start_time")
/**
* Field `workStartTime` (LocalTime): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled.
*/
private LocalTime workStartTime;
@TableField("work_end_time")
/**
* Field `workEndTime` (LocalTime): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled.
*/
private LocalTime workEndTime;
/**
* 作品集商品ID集合,多个ID以逗号分隔
*/
private String portfolio;
/**
* 逻辑删除:0-未删,1-已删
*/
@TableField("is_delete")
@TableLogic
private Integer isDelete;
}
@@ -0,0 +1,22 @@
package com.xiaowang.yuminailcore.modules.artist.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.xiaowang.yuminailcore.modules.artist.entity.ArtistScheduleDO;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import java.time.LocalDate;
import java.time.LocalTime;
@Mapper
public interface ArtistScheduleMapper extends BaseMapper<ArtistScheduleDO> {
@Select("SELECT * FROM t_artist_schedule WHERE shop_id = #{shopId} AND artist_id = #{artistId} " +
"AND work_date = #{workDate} AND start_time <= #{startTime} AND end_time >= #{endTime} " +
"AND is_delete = 0 ORDER BY CASE WHEN status = 1 THEN 0 ELSE 1 END, start_time ASC LIMIT 1 FOR UPDATE")
ArtistScheduleDO selectCoveringSchedule(@Param("shopId") Long shopId,
@Param("artistId") Long artistId,
@Param("workDate") LocalDate workDate,
@Param("startTime") LocalTime startTime,
@Param("endTime") LocalTime endTime);
}
@@ -0,0 +1,12 @@
package com.xiaowang.yuminailcore.modules.artist.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.xiaowang.yuminailcore.modules.artist.entity.NailArtistInfoDO;
import org.apache.ibatis.annotations.Mapper;
/**
* 美甲师信息Mapper
*/
@Mapper
public interface NailArtistInfoMapper extends BaseMapper<NailArtistInfoDO> {
}
@@ -0,0 +1,13 @@
package com.xiaowang.yuminailcore.modules.artist.service;
import com.xiaowang.yuminailcore.modules.artist.dto.ArtistScheduleDTO;
import com.xiaowang.yuminailcore.modules.artist.vo.ArtistScheduleVO;
import java.time.LocalDate;
import java.util.List;
public interface ArtistScheduleService {
ArtistScheduleVO saveSchedule(ArtistScheduleDTO dto);
List<ArtistScheduleVO> listSchedules(Long shopId, Long artistId, LocalDate startDate, LocalDate endDate);
}
@@ -0,0 +1,54 @@
package com.xiaowang.yuminailcore.modules.artist.service;
import com.baomidou.mybatisplus.extension.service.IService;
import com.xiaowang.yuminailcore.modules.artist.dto.NailArtistInfoDTO;
import com.xiaowang.yuminailcore.modules.artist.entity.NailArtistInfoDO;
import com.xiaowang.yuminailcore.modules.artist.vo.NailArtistAvailabilityVO;
import com.xiaowang.yuminailcore.modules.artist.vo.NailArtistProfileVO;
import com.xiaowang.yuminailcore.modules.artist.vo.NailArtistReviewVO;
import java.util.List;
/**
* 美甲师信息服务
*/
public interface NailArtistInfoService extends IService<NailArtistInfoDO> {
/**
* 根据用户ID获取美甲师信息
* @param userId 用户ID
* @return 美甲师信息
*/
NailArtistInfoDTO getByUserId(Long userId);
/**
* 获取所有美甲师信息
* @return 美甲师信息列表
*/
List<NailArtistInfoDTO> getAllNailArtists();
/**
* 根据店铺ID获取美甲师信息
* @param shopId 店铺ID
* @return 美甲师信息列表
*/
List<NailArtistInfoDTO> getByShopId(Long shopId);
/**
* 保存或更新美甲师信息
* @param nailArtistInfoDTO 美甲师信息DTO
* @return 保存后的美甲师信息
*/
NailArtistInfoDTO saveOrUpdateNailArtistInfo(NailArtistInfoDTO nailArtistInfoDTO);
/**
* 获取所有可用的美甲师信息(前台使用)
* @return 美甲师信息列表
*/
List<NailArtistInfoDTO> getAllAvailableNailArtists();
NailArtistProfileVO getPublicProfile(Long artistId);
List<NailArtistAvailabilityVO> getAvailability(Long artistId);
List<NailArtistReviewVO> listPublicReviews(Long artistId);
}
@@ -0,0 +1,66 @@
package com.xiaowang.yuminailcore.modules.artist.service.impl;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.xiaowang.yuminailcore.modules.artist.dto.ArtistScheduleDTO;
import com.xiaowang.yuminailcore.modules.artist.entity.ArtistScheduleDO;
import com.xiaowang.yuminailcore.modules.artist.mapper.ArtistScheduleMapper;
import com.xiaowang.yuminailcore.modules.artist.service.ArtistScheduleService;
import com.xiaowang.yuminailcore.modules.artist.vo.ArtistScheduleVO;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.time.LocalDate;
import java.util.List;
@Service
@RequiredArgsConstructor
public class ArtistScheduleServiceImpl implements ArtistScheduleService {
private final ArtistScheduleMapper artistScheduleMapper;
@Override
@Transactional
public ArtistScheduleVO saveSchedule(ArtistScheduleDTO dto) {
if (dto == null || dto.getShopId() == null || dto.getArtistId() == null || dto.getWorkDate() == null
|| dto.getStartTime() == null || dto.getEndTime() == null) {
throw new RuntimeException("排班信息不完整");
}
ArtistScheduleDO schedule = new ArtistScheduleDO();
BeanUtils.copyProperties(dto, schedule);
schedule.setSlotMinutes(dto.getSlotMinutes() == null ? 60 : dto.getSlotMinutes());
schedule.setCapacity(dto.getCapacity() == null || dto.getCapacity() < 1 ? 1 : dto.getCapacity());
schedule.setStatus(dto.getStatus() == null ? 1 : dto.getStatus());
schedule.setIsDelete(0);
artistScheduleMapper.insert(schedule);
return toVO(schedule);
}
@Override
public List<ArtistScheduleVO> listSchedules(Long shopId, Long artistId, LocalDate startDate, LocalDate endDate) {
LambdaQueryWrapper<ArtistScheduleDO> wrapper = new LambdaQueryWrapper<ArtistScheduleDO>()
.eq(ArtistScheduleDO::getIsDelete, 0)
.orderByAsc(ArtistScheduleDO::getWorkDate)
.orderByAsc(ArtistScheduleDO::getStartTime);
if (shopId != null) {
wrapper.eq(ArtistScheduleDO::getShopId, shopId);
}
if (artistId != null) {
wrapper.eq(ArtistScheduleDO::getArtistId, artistId);
}
if (startDate != null) {
wrapper.ge(ArtistScheduleDO::getWorkDate, startDate);
}
if (endDate != null) {
wrapper.le(ArtistScheduleDO::getWorkDate, endDate);
}
return artistScheduleMapper.selectList(wrapper).stream().map(this::toVO).toList();
}
private ArtistScheduleVO toVO(ArtistScheduleDO schedule) {
ArtistScheduleVO vo = new ArtistScheduleVO();
BeanUtils.copyProperties(schedule, vo);
return vo;
}
}
@@ -0,0 +1,757 @@
package com.xiaowang.yuminailcore.modules.artist.service.impl;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xiaowang.yuminailcore.modules.artist.dto.NailArtistInfoDTO;
import com.xiaowang.yuminailcore.modules.artist.entity.ArtistScheduleDO;
import com.xiaowang.yuminailcore.modules.artist.entity.NailArtistInfoDO;
import com.xiaowang.yuminailcore.modules.order.entity.OrderArtistReviewDO;
import com.xiaowang.yuminailcore.modules.order.entity.OrderDO;
import com.xiaowang.yuminailcore.modules.order.entity.OrderItemDO;
import com.xiaowang.yuminailcore.modules.product.entity.ProductDO;
import com.xiaowang.yuminailcore.modules.shop.entity.ShopDO;
import com.xiaowang.yuminailcore.modules.user.entity.UserDO;
import com.xiaowang.yuminailcore.modules.artist.mapper.NailArtistInfoMapper;
import com.xiaowang.yuminailcore.modules.planning.mapper.AppointmentReservationMapper;
import com.xiaowang.yuminailcore.modules.artist.mapper.ArtistScheduleMapper;
import com.xiaowang.yuminailcore.modules.order.mapper.OrderArtistReviewMapper;
import com.xiaowang.yuminailcore.modules.order.mapper.OrderItemMapper;
import com.xiaowang.yuminailcore.modules.order.mapper.OrderMapper;
import com.xiaowang.yuminailcore.modules.product.mapper.ProductMapper;
import com.xiaowang.yuminailcore.modules.shop.mapper.ShopMapper;
import com.xiaowang.yuminailcore.modules.user.mapper.UserMapper;
import com.xiaowang.yuminailcore.modules.artist.service.NailArtistInfoService;
import com.xiaowang.yuminailcore.modules.file.service.ObjectStorageFileService;
import com.xiaowang.yuminailcore.modules.file.support.ObjectStorageUrlSupport;
import com.xiaowang.yuminailcore.modules.shop.support.UserShopBindingSupport;
import com.xiaowang.yuminailcore.modules.artist.vo.NailArtistAvailabilityVO;
import com.xiaowang.yuminailcore.modules.artist.vo.NailArtistProfileVO;
import com.xiaowang.yuminailcore.modules.artist.vo.NailArtistReviewVO;
import com.xiaowang.yuminailcore.modules.artist.vo.NailArtistWorkVO;
import com.xiaowang.yuminailcore.modules.file.vo.ObjectStorageFileVO;
import com.xiaowang.yuminailcore.modules.shop.vo.ShopSimpleVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.stream.Collectors;
import com.xiaowang.yuminailcore.common.Result;
@Service
/**
* NailArtistInfoServiceImpl contains the concrete business logic. It validates input, calls mappers/support services, and builds return objects.
* Beginner guide: follow the call chain Controller -> Service -> ServiceImpl -> Mapper/support class.
*/
public class NailArtistInfoServiceImpl extends ServiceImpl<NailArtistInfoMapper, NailArtistInfoDO> implements NailArtistInfoService {
private static final int REVIEW_STATUS_SUBMITTED = 1;
private static final int ORDER_STATUS_COMPLETED = 2;
private static final int AVAILABILITY_DAYS = 7;
private static final int SLOT_MINUTES = 60;
private static final int MAX_AVAILABILITY_SLOTS = 16;
private static final DateTimeFormatter DATE_TEXT_FORMATTER = DateTimeFormatter.ISO_LOCAL_DATE;
private static final DateTimeFormatter TIME_TEXT_FORMATTER = DateTimeFormatter.ofPattern("HH:mm");
@Autowired
/**
* Purpose: userMapper supports NailArtistInfoServiceImpl.java by holding or executing the user mapper business role.
* Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state.
*/
private UserMapper userMapper;
@Autowired
/**
* Purpose: shopMapper supports NailArtistInfoServiceImpl.java by holding or executing the shop mapper business role.
* Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state.
*/
private ShopMapper shopMapper;
@Autowired
/**
* Purpose: userShopBindingSupport supports NailArtistInfoServiceImpl.java by holding or executing the user shop binding support business role.
* Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state.
*/
private UserShopBindingSupport userShopBindingSupport;
@Autowired
private ProductMapper productMapper;
@Autowired
private OrderMapper orderMapper;
@Autowired
private OrderItemMapper orderItemMapper;
@Autowired
private OrderArtistReviewMapper orderArtistReviewMapper;
@Autowired
private ObjectStorageFileService objectStorageFileService;
@Autowired
private ObjectStorageUrlSupport objectStorageUrlSupport;
@Autowired(required = false)
private ArtistScheduleMapper artistScheduleMapper;
@Autowired(required = false)
private AppointmentReservationMapper appointmentReservationMapper;
@Override
/**
* Load data by the supplied parameter.
* Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result.
* @param userId parameter `userId` supplied by the caller
* @return NailArtistInfoDTO result consumed by the caller or returned to the frontend
*/
public NailArtistInfoDTO getByUserId(Long userId) {
NailArtistInfoDO info = getOne(new LambdaQueryWrapper<NailArtistInfoDO>()
.eq(NailArtistInfoDO::getUserId, userId)
.eq(NailArtistInfoDO::getIsDelete, 0)
.last("LIMIT 1"));
return info == null ? null : convertToDTO(info);
}
@Override
/**
* Load data by the supplied parameter.
* Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result.
* @return List<NailArtistInfoDTO> result consumed by the caller or returned to the frontend
*/
public List<NailArtistInfoDTO> getAllNailArtists() {
List<NailArtistInfoDTO> result = new ArrayList<>();
List<NailArtistInfoDO> records = list(new LambdaQueryWrapper<NailArtistInfoDO>()
.eq(NailArtistInfoDO::getIsDelete, 0));
for (NailArtistInfoDO record : records) {
NailArtistInfoDTO dto = convertToDTO(record);
if (isVisibleServiceUser(dto)) {
result.add(dto);
}
}
return result;
}
@Override
/**
* Load data by the supplied parameter.
* Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result.
* @param shopId parameter `shopId` supplied by the caller
* @return List<NailArtistInfoDTO> result consumed by the caller or returned to the frontend
*/
public List<NailArtistInfoDTO> getByShopId(Long shopId) {
List<Long> serviceUserIds = userShopBindingSupport.listUserIdsByShopId(shopId, true);
if (serviceUserIds.isEmpty()) {
return new ArrayList<>();
}
List<UserDO> users = userMapper.selectList(new LambdaQueryWrapper<UserDO>()
.in(UserDO::getId, serviceUserIds)
.eq(UserDO::getType, 3)
.eq(UserDO::getStatus, 1)
.eq(UserDO::getIsDelete, 0)
.orderByAsc(UserDO::getCreateTime)
.orderByAsc(UserDO::getId));
List<NailArtistInfoDTO> result = new ArrayList<>();
ShopDO shop = shopMapper.selectById(shopId);
for (UserDO user : users) {
NailArtistInfoDTO dto = getByUserId(user.getId());
if (dto == null) {
dto = buildFallbackArtistInfo(user);
}
dto.setShopId(shopId);
dto.setShopName(shop == null ? null : shop.getShopName());
result.add(dto);
}
return result;
}
@Override
/**
* Save submitted data.
* Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result.
* @param dto parameter `dto` supplied by the caller
* @return NailArtistInfoDTO result consumed by the caller or returned to the frontend
*/
public NailArtistInfoDTO saveOrUpdateNailArtistInfo(NailArtistInfoDTO dto) {
NailArtistInfoDO entity = new NailArtistInfoDO();
BeanUtils.copyProperties(dto, entity);
NailArtistInfoDO existing = getOne(new LambdaQueryWrapper<NailArtistInfoDO>()
.eq(NailArtistInfoDO::getUserId, dto.getUserId())
.eq(NailArtistInfoDO::getIsDelete, 0)
.last("LIMIT 1"));
if (existing != null) {
entity.setId(existing.getId());
}
if (entity.getStatus() == null) {
entity.setStatus(1);
}
if (entity.getParticipateProduction() == null) {
UserDO user = userMapper.selectById(dto.getUserId());
entity.setParticipateProduction(user != null && Integer.valueOf(3).equals(user.getType()) ? 1 : 0);
}
/**
* Save submitted data.
* Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result.
* @param entity parameter `entity` supplied by the caller
* @return result consumed by the caller or returned to the frontend
*/
saveOrUpdate(entity);
/**
* Run business method `convertToDTO`.
* Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result.
* @param entity parameter `entity` supplied by the caller
* @return return result consumed by the caller or returned to the frontend
*/
return convertToDTO(entity);
}
@Override
/**
* Load data by the supplied parameter.
* Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result.
* @return List<NailArtistInfoDTO> result consumed by the caller or returned to the frontend
*/
public List<NailArtistInfoDTO> getAllAvailableNailArtists() {
List<NailArtistInfoDTO> result = new ArrayList<>();
List<NailArtistInfoDO> records = list(new LambdaQueryWrapper<NailArtistInfoDO>()
.eq(NailArtistInfoDO::getStatus, 1)
.eq(NailArtistInfoDO::getIsDelete, 0));
for (NailArtistInfoDO record : records) {
NailArtistInfoDTO dto = convertToDTO(record);
if (isBookableServiceUser(dto)) {
result.add(dto);
}
}
return result;
}
@Override
public NailArtistProfileVO getPublicProfile(Long artistId) {
NailArtistInfoDTO artistInfo = loadPublicArtistInfo(artistId);
UserDO artist = userMapper.selectById(artistId);
if (artist == null || isDeleted(artist.getIsDelete())) {
throw new RuntimeException("美甲师信息不存在");
}
List<OrderItemDO> servedItems = loadArtistOrderItems(artistId, true);
List<NailArtistReviewVO> reviews = listPublicReviews(artistId);
NailArtistProfileVO profile = new NailArtistProfileVO();
profile.setArtistId(artistId);
profile.setArtistName(resolveArtistName(artistInfo, artist));
profile.setAvatar(artist.getAvatar());
profile.setIdentity(artistInfo.getIdentity());
profile.setSignature(artistInfo.getSignature());
profile.setExperience(artistInfo.getExperience());
profile.setStatus(artistInfo.getStatus());
profile.setShopId(artistInfo.getShopId());
profile.setShopName(artistInfo.getShopName());
profile.setRating(resolvePublicRating(artistId, artistInfo));
profile.setServiceCount(countServiceQuantity(servedItems));
profile.setWorkStartTime(artistInfo.getWorkStartTime());
profile.setWorkEndTime(artistInfo.getWorkEndTime());
profile.setStyleTags(parseTextTokens(artistInfo.getSkills()));
profile.setWorks(buildWorks(artistInfo.getPortfolio(), servedItems, 6));
profile.setReviews(reviews.stream().limit(3).collect(Collectors.toList()));
profile.setAvailability(getAvailability(artistId).stream().limit(8).collect(Collectors.toList()));
return profile;
}
@Override
public List<NailArtistAvailabilityVO> getAvailability(Long artistId) {
NailArtistInfoDTO artistInfo = loadPublicArtistInfo(artistId);
if (!Integer.valueOf(1).equals(artistInfo.getStatus())) {
return new ArrayList<>();
}
List<NailArtistAvailabilityVO> scheduleSlots = buildScheduleAvailabilitySlots(artistId, artistInfo);
if (!scheduleSlots.isEmpty()) {
return scheduleSlots;
}
LocalTime workStart = artistInfo.getWorkStartTime() == null ? LocalTime.of(10, 0) : artistInfo.getWorkStartTime();
LocalTime workEnd = artistInfo.getWorkEndTime() == null ? LocalTime.of(20, 0) : artistInfo.getWorkEndTime();
if (!workEnd.isAfter(workStart)) {
workStart = LocalTime.of(10, 0);
workEnd = LocalTime.of(20, 0);
}
LocalDate today = LocalDate.now();
LocalDateTime rangeStart = today.atStartOfDay();
LocalDateTime rangeEnd = today.plusDays(AVAILABILITY_DAYS + 1L).atStartOfDay();
Set<LocalDateTime> bookedStarts = loadBookedSlotStarts(artistId, rangeStart, rangeEnd);
LocalDateTime now = LocalDateTime.now();
List<NailArtistAvailabilityVO> slots = new ArrayList<>();
for (int dayOffset = 0; dayOffset < AVAILABILITY_DAYS && slots.size() < MAX_AVAILABILITY_SLOTS; dayOffset++) {
LocalDate date = today.plusDays(dayOffset);
LocalTime cursor = workStart;
while (!cursor.plusMinutes(SLOT_MINUTES).isAfter(workEnd) && slots.size() < MAX_AVAILABILITY_SLOTS) {
LocalDateTime slotStart = date.atTime(cursor);
LocalDateTime slotEnd = slotStart.plusMinutes(SLOT_MINUTES);
if (slotStart.isAfter(now.plusMinutes(30)) && !bookedStarts.contains(truncateToMinute(slotStart))) {
slots.add(buildAvailabilitySlot(slotStart, slotEnd));
}
cursor = cursor.plusMinutes(SLOT_MINUTES);
}
}
return slots;
}
private List<NailArtistAvailabilityVO> buildScheduleAvailabilitySlots(Long artistId, NailArtistInfoDTO artistInfo) {
if (artistScheduleMapper == null || artistInfo.getShopId() == null) {
return new ArrayList<>();
}
LocalDate today = LocalDate.now();
List<ArtistScheduleDO> schedules = artistScheduleMapper.selectList(new LambdaQueryWrapper<ArtistScheduleDO>()
.eq(ArtistScheduleDO::getShopId, artistInfo.getShopId())
.eq(ArtistScheduleDO::getArtistId, artistId)
.eq(ArtistScheduleDO::getStatus, 1)
.eq(ArtistScheduleDO::getIsDelete, 0)
.ge(ArtistScheduleDO::getWorkDate, today)
.lt(ArtistScheduleDO::getWorkDate, today.plusDays(AVAILABILITY_DAYS))
.orderByAsc(ArtistScheduleDO::getWorkDate)
.orderByAsc(ArtistScheduleDO::getStartTime));
if (schedules == null || schedules.isEmpty()) {
return new ArrayList<>();
}
LocalDateTime minStart = LocalDateTime.now().plusMinutes(30);
List<NailArtistAvailabilityVO> slots = new ArrayList<>();
for (ArtistScheduleDO schedule : schedules) {
int slotMinutes = schedule.getSlotMinutes() == null || schedule.getSlotMinutes() < 15 ? SLOT_MINUTES : schedule.getSlotMinutes();
int capacity = schedule.getCapacity() == null || schedule.getCapacity() < 1 ? 1 : schedule.getCapacity();
LocalTime cursor = schedule.getStartTime();
while (cursor != null && schedule.getEndTime() != null
&& !cursor.plusMinutes(slotMinutes).isAfter(schedule.getEndTime())
&& slots.size() < MAX_AVAILABILITY_SLOTS) {
LocalDateTime slotStart = schedule.getWorkDate().atTime(cursor);
LocalDateTime slotEnd = slotStart.plusMinutes(slotMinutes);
int used = appointmentReservationMapper == null ? 0
: appointmentReservationMapper.countOverlappingActive(artistId, slotStart, slotEnd);
if (slotStart.isAfter(minStart) && used < capacity) {
slots.add(buildAvailabilitySlot(slotStart, slotEnd));
}
cursor = cursor.plusMinutes(slotMinutes);
}
if (slots.size() >= MAX_AVAILABILITY_SLOTS) {
break;
}
}
return slots;
}
@Override
public List<NailArtistReviewVO> listPublicReviews(Long artistId) {
if (artistId == null) {
return new ArrayList<>();
}
List<OrderArtistReviewDO> reviews = orderArtistReviewMapper.selectList(new LambdaQueryWrapper<OrderArtistReviewDO>()
.eq(OrderArtistReviewDO::getArtistId, artistId)
.eq(OrderArtistReviewDO::getStatus, REVIEW_STATUS_SUBMITTED)
.eq(OrderArtistReviewDO::getIsDelete, 0)
.orderByDesc(OrderArtistReviewDO::getSubmittedAt)
.orderByDesc(OrderArtistReviewDO::getId));
if (reviews == null || reviews.isEmpty()) {
return new ArrayList<>();
}
List<OrderArtistReviewDO> limitedReviews = reviews.stream().limit(20).collect(Collectors.toList());
Map<Long, UserDO> customerMap = loadUsers(limitedReviews.stream()
.map(OrderArtistReviewDO::getCustomerId)
.collect(Collectors.toCollection(LinkedHashSet::new)));
Map<Long, ProductDO> productMap = loadProducts(limitedReviews.stream()
.map(OrderArtistReviewDO::getProductId)
.collect(Collectors.toCollection(LinkedHashSet::new)));
Set<Long> imageIds = new LinkedHashSet<>();
for (OrderArtistReviewDO review : limitedReviews) {
imageIds.addAll(parseLongTokens(review.getImageFileIds()));
}
Map<Long, ObjectStorageFileVO> fileMap = loadFiles(imageIds);
List<NailArtistReviewVO> result = new ArrayList<>();
for (OrderArtistReviewDO review : limitedReviews) {
result.add(buildReviewVO(review, customerMap, productMap, fileMap));
}
return result;
}
/**
* Run business method `convertToDTO`.
* Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result.
* @param entity parameter `entity` supplied by the caller
* @return private NailArtistInfoDTO result consumed by the caller or returned to the frontend
*/
private NailArtistInfoDTO convertToDTO(NailArtistInfoDO entity) {
NailArtistInfoDTO dto = new NailArtistInfoDTO();
BeanUtils.copyProperties(entity, dto);
UserDO user = userMapper.selectById(entity.getUserId());
if (user != null) {
dto.setNickname(user.getNickname());
dto.setSignature(user.getSignature());
dto.setUserType(user.getType());
dto.setUserTypeName(resolveUserTypeName(user.getType()));
if (dto.getParticipateProduction() == null) {
dto.setParticipateProduction(Integer.valueOf(3).equals(user.getType()) ? 1 : 0);
}
List<ShopSimpleVO> shopOptions = userShopBindingSupport.listShopOptionsByUserId(user.getId(), true, true);
if (!shopOptions.isEmpty()) {
ShopSimpleVO primaryShop = shopOptions.get(0);
dto.setShopId(primaryShop.getId());
dto.setShopName(primaryShop.getShopName());
} else if (user.getShopId() != null && user.getShopId() > 0) {
ShopDO shop = shopMapper.selectById(user.getShopId());
if (shop != null) {
dto.setShopId(shop.getId());
dto.setShopName(shop.getShopName());
}
}
}
return dto;
}
private NailArtistInfoDTO buildFallbackArtistInfo(UserDO user) {
NailArtistInfoDTO dto = new NailArtistInfoDTO();
dto.setUserId(user.getId());
dto.setNickname(user.getNickname());
dto.setSignature(user.getSignature());
dto.setUserType(user.getType());
dto.setUserTypeName(resolveUserTypeName(user.getType()));
dto.setIdentity("美甲师");
dto.setStatus(1);
dto.setParticipateProduction(1);
dto.setShopId(user.getShopId());
List<ShopSimpleVO> shopOptions = userShopBindingSupport.listShopOptionsByUserId(user.getId(), true, true);
if (!shopOptions.isEmpty()) {
ShopSimpleVO primaryShop = shopOptions.get(0);
dto.setShopId(primaryShop.getId());
dto.setShopName(primaryShop.getShopName());
} else if (user.getShopId() != null && user.getShopId() > 0) {
ShopDO shop = shopMapper.selectById(user.getShopId());
if (shop != null) {
dto.setShopId(shop.getId());
dto.setShopName(shop.getShopName());
}
}
return dto;
}
/**
* Run business method `isVisibleServiceUser`.
* Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result.
* @param dto parameter `dto` supplied by the caller
* @return private boolean result consumed by the caller or returned to the frontend
*/
private boolean isVisibleServiceUser(NailArtistInfoDTO dto) {
if (dto == null || dto.getUserType() == null) {
return false;
}
return Integer.valueOf(3).equals(dto.getUserType())
|| Integer.valueOf(2).equals(dto.getUserType());
}
/**
* Run business method `isBookableServiceUser`.
* Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result.
* @param dto parameter `dto` supplied by the caller
* @return private boolean result consumed by the caller or returned to the frontend
*/
private boolean isBookableServiceUser(NailArtistInfoDTO dto) {
return isVisibleServiceUser(dto) && Integer.valueOf(1).equals(dto.getStatus());
}
/**
* Run business method `resolveUserTypeName`.
* Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result.
* @param type parameter `type` supplied by the caller
* @return private String result consumed by the caller or returned to the frontend
*/
private String resolveUserTypeName(Integer type) {
if (Integer.valueOf(2).equals(type)) {
return "店长";
}
if (Integer.valueOf(3).equals(type)) {
return "美甲师";
}
return "用户";
}
private NailArtistInfoDTO loadPublicArtistInfo(Long artistId) {
if (artistId == null) {
throw new RuntimeException("美甲师信息不存在");
}
NailArtistInfoDTO artistInfo = getByUserId(artistId);
if (artistInfo != null && isVisibleServiceUser(artistInfo)) {
return artistInfo;
}
UserDO artist = userMapper.selectById(artistId);
if (artist == null
|| isDeleted(artist.getIsDelete())
|| !Integer.valueOf(3).equals(artist.getType())
|| !Integer.valueOf(1).equals(artist.getStatus())) {
throw new RuntimeException("美甲师信息不存在");
}
return buildFallbackArtistInfo(artist);
}
private BigDecimal resolvePublicRating(Long artistId, NailArtistInfoDTO artistInfo) {
BigDecimal averageRating = orderArtistReviewMapper.selectAverageSubmittedRatingByArtistId(artistId);
BigDecimal rating = averageRating == null ? artistInfo.getRating() : averageRating;
if (rating == null) {
return BigDecimal.ZERO.setScale(1, RoundingMode.HALF_UP);
}
return rating.setScale(1, RoundingMode.HALF_UP);
}
private List<OrderItemDO> loadArtistOrderItems(Long artistId, boolean completedOnly) {
List<OrderDO> orders = orderMapper.selectByArtistId(artistId);
if (orders == null || orders.isEmpty()) {
return new ArrayList<>();
}
Set<Long> allowedOrderIds = orders.stream()
.filter(order -> !isDeleted(order.getIsDelete()))
.filter(order -> !completedOnly || Integer.valueOf(ORDER_STATUS_COMPLETED).equals(order.getStatus()))
.map(OrderDO::getId)
.collect(Collectors.toCollection(LinkedHashSet::new));
if (allowedOrderIds.isEmpty()) {
return new ArrayList<>();
}
List<OrderItemDO> items = new ArrayList<>();
for (Long orderId : allowedOrderIds) {
List<OrderItemDO> orderItems = orderItemMapper.selectByOrderId(orderId);
if (orderItems == null) {
continue;
}
for (OrderItemDO item : orderItems) {
if (item != null
&& artistId.equals(item.getArtistId())
&& !isDeleted(item.getIsDelete())) {
items.add(item);
}
}
}
return items;
}
private long countServiceQuantity(List<OrderItemDO> items) {
if (items == null || items.isEmpty()) {
return 0L;
}
long count = 0L;
for (OrderItemDO item : items) {
if (item == null) {
continue;
}
count += item.getQuantity() == null || item.getQuantity() < 1 ? 1L : item.getQuantity();
}
return count;
}
private List<NailArtistWorkVO> buildWorks(String portfolio, List<OrderItemDO> servedItems, int limit) {
LinkedHashSet<Long> productIds = new LinkedHashSet<>(parseLongTokens(portfolio));
if (servedItems != null) {
servedItems.stream()
.sorted(Comparator.comparing(OrderItemDO::getCreateTime, Comparator.nullsLast(Comparator.reverseOrder())))
.map(OrderItemDO::getProductId)
.filter(productId -> productId != null && productId > 0)
.forEach(productIds::add);
}
if (productIds.isEmpty()) {
return new ArrayList<>();
}
List<Long> limitedIds = productIds.stream().limit(Math.max(limit, 1)).collect(Collectors.toList());
Map<Long, ProductDO> productMap = loadProducts(new LinkedHashSet<>(limitedIds));
Set<Long> fileIds = new LinkedHashSet<>();
for (ProductDO product : productMap.values()) {
fileIds.addAll(parseLongTokens(product.getImageFileIds()));
}
Map<Long, ObjectStorageFileVO> fileMap = loadFiles(fileIds);
List<NailArtistWorkVO> works = new ArrayList<>();
for (Long productId : limitedIds) {
ProductDO product = productMap.get(productId);
if (product == null || isDeleted(product.getIsDelete())) {
continue;
}
works.add(buildWorkVO(product, fileMap));
}
return works;
}
private NailArtistWorkVO buildWorkVO(ProductDO product, Map<Long, ObjectStorageFileVO> fileMap) {
NailArtistWorkVO work = new NailArtistWorkVO();
work.setId(product.getId());
work.setTitle(product.getTitle());
work.setDescription(product.getDescription());
work.setPrice(product.getPrice());
work.setTags(parseTextTokens(product.getTags()));
work.setLikeCount(product.getLikeCount());
work.setCollectCount(product.getCollectCount());
List<String> imageUrls = resolveImageUrls(parseLongTokens(product.getImageFileIds()), fileMap);
work.setImageUrls(imageUrls);
work.setCoverImageUrl(imageUrls.isEmpty() ? null : imageUrls.get(0));
return work;
}
private NailArtistReviewVO buildReviewVO(OrderArtistReviewDO review,
Map<Long, UserDO> customerMap,
Map<Long, ProductDO> productMap,
Map<Long, ObjectStorageFileVO> fileMap) {
NailArtistReviewVO vo = new NailArtistReviewVO();
vo.setId(review.getId());
vo.setArtistId(review.getArtistId());
vo.setCustomerId(review.getCustomerId());
UserDO customer = customerMap.get(review.getCustomerId());
vo.setCustomerName(customer == null || !StringUtils.hasText(customer.getNickname()) ? "匿名用户" : customer.getNickname());
vo.setCustomerAvatar(customer == null ? null : customer.getAvatar());
vo.setProductId(review.getProductId());
ProductDO product = productMap.get(review.getProductId());
vo.setProductTitle(product == null ? null : product.getTitle());
vo.setRating(review.getRatingScore());
vo.setContent(review.getContent());
List<Long> imageFileIds = parseLongTokens(review.getImageFileIds());
vo.setImageFileIds(imageFileIds);
vo.setImageUrls(resolveImageUrls(imageFileIds, fileMap));
vo.setSubmittedAt(review.getSubmittedAt());
return vo;
}
private Set<LocalDateTime> loadBookedSlotStarts(Long artistId, LocalDateTime rangeStart, LocalDateTime rangeEnd) {
List<OrderItemDO> bookedItems = orderItemMapper.selectArtistCalendarItems(artistId, rangeStart, rangeEnd);
if (bookedItems == null || bookedItems.isEmpty()) {
return new HashSet<>();
}
return bookedItems.stream()
.map(OrderItemDO::getAppointmentTime)
.filter(appointmentTime -> appointmentTime != null)
.map(this::truncateToMinute)
.collect(Collectors.toSet());
}
private NailArtistAvailabilityVO buildAvailabilitySlot(LocalDateTime startTime, LocalDateTime endTime) {
NailArtistAvailabilityVO slot = new NailArtistAvailabilityVO();
slot.setStartTime(startTime);
slot.setEndTime(endTime);
slot.setDateText(DATE_TEXT_FORMATTER.format(startTime.toLocalDate()));
slot.setTimeText(TIME_TEXT_FORMATTER.format(startTime.toLocalTime()));
slot.setAvailable(true);
return slot;
}
private Map<Long, ProductDO> loadProducts(Set<Long> productIds) {
if (productIds == null || productIds.isEmpty()) {
return new HashMap<>();
}
List<ProductDO> products = productMapper.selectBatchIds(productIds);
if (products == null || products.isEmpty()) {
return new HashMap<>();
}
return products.stream()
.filter(product -> product != null && product.getId() != null && !isDeleted(product.getIsDelete()))
.collect(Collectors.toMap(ProductDO::getId, product -> product, (left, right) -> left, HashMap::new));
}
private Map<Long, UserDO> loadUsers(Set<Long> userIds) {
if (userIds == null || userIds.isEmpty()) {
return new HashMap<>();
}
List<UserDO> users = userMapper.selectBatchIds(new ArrayList<>(userIds));
if (users == null || users.isEmpty()) {
return new HashMap<>();
}
return users.stream()
.filter(user -> user != null && user.getId() != null)
.collect(Collectors.toMap(UserDO::getId, user -> user, (left, right) -> left, HashMap::new));
}
private Map<Long, ObjectStorageFileVO> loadFiles(Set<Long> fileIds) {
if (fileIds == null || fileIds.isEmpty()) {
return new HashMap<>();
}
Map<Long, ObjectStorageFileVO> files = objectStorageFileService.getObjectStorageFileMapByIds(fileIds);
return files == null ? new HashMap<>() : files;
}
private List<String> resolveImageUrls(List<Long> fileIds, Map<Long, ObjectStorageFileVO> fileMap) {
if (fileIds == null || fileIds.isEmpty() || fileMap == null || fileMap.isEmpty()) {
return new ArrayList<>();
}
List<String> urls = new ArrayList<>();
for (Long fileId : fileIds) {
ObjectStorageFileVO file = fileMap.get(fileId);
if (file != null && StringUtils.hasText(file.getFileUrl())) {
urls.add(objectStorageUrlSupport.toAccessibleUrl(file));
}
}
return urls;
}
private List<Long> parseLongTokens(String raw) {
if (!StringUtils.hasText(raw)) {
return new ArrayList<>();
}
LinkedHashSet<Long> ids = new LinkedHashSet<>();
for (String token : raw.split("[,;,;\\s]+")) {
if (!StringUtils.hasText(token)) {
continue;
}
try {
ids.add(Long.parseLong(token.trim()));
} catch (NumberFormatException ignored) {
// Some legacy fields store tag names instead of ids.
}
}
return new ArrayList<>(ids);
}
private List<String> parseTextTokens(String raw) {
if (!StringUtils.hasText(raw)) {
return new ArrayList<>();
}
LinkedHashSet<String> tokens = new LinkedHashSet<>();
for (String token : raw.split("[,;,;、\\s]+")) {
if (StringUtils.hasText(token)) {
tokens.add(token.trim());
}
}
return new ArrayList<>(tokens);
}
private String resolveArtistName(NailArtistInfoDTO artistInfo, UserDO artist) {
if (artistInfo != null && StringUtils.hasText(artistInfo.getNickname())) {
return artistInfo.getNickname();
}
if (artist != null && StringUtils.hasText(artist.getNickname())) {
return artist.getNickname();
}
return "美甲师";
}
private boolean isDeleted(Integer isDelete) {
return Integer.valueOf(1).equals(isDelete);
}
private LocalDateTime truncateToMinute(LocalDateTime value) {
return value == null ? null : value.withSecond(0).withNano(0);
}
}
@@ -0,0 +1,116 @@
package com.xiaowang.yuminailcore.modules.artist.support;
import com.xiaowang.yuminailcore.modules.user.entity.UserDO;
import com.xiaowang.yuminailcore.modules.artist.entity.NailArtistInfoDO;
import com.xiaowang.yuminailcore.modules.artist.mapper.NailArtistInfoMapper;
import com.xiaowang.yuminailcore.modules.user.mapper.UserMapper;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import java.util.LinkedHashSet;
import java.util.Set;
import java.util.stream.Collectors;
import com.xiaowang.yuminailcore.modules.shop.support.UserShopBindingSupport;
@Component
@RequiredArgsConstructor
/**
* Purpose: BookableArtistSupport supports BookableArtistSupport.java by holding or executing the bookable artist support business role.
* Usage: reference this class from the owning layer and pass validated inputs before reading or updating related state.
*/
public class BookableArtistSupport {
/**
* Purpose: userMapper supports BookableArtistSupport.java by holding or executing the user mapper business role.
* Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state.
*/
private final UserMapper userMapper;
/**
* Purpose: nailArtistInfoMapper supports BookableArtistSupport.java by holding or executing the nail artist info mapper business role.
* Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state.
*/
private final NailArtistInfoMapper nailArtistInfoMapper;
/**
* Purpose: userShopBindingSupport supports BookableArtistSupport.java by holding or executing the user shop binding support business role.
* Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state.
*/
private final UserShopBindingSupport userShopBindingSupport;
/**
* Purpose: isValidBookableArtist supports BookableArtistSupport.java by holding or executing the is valid bookable artist business role.
* Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state.
*/
public boolean isValidBookableArtist(Long shopId, Long artistId) {
if (artistId == null || artistId <= 0) {
return false;
}
UserDO artist = userMapper.selectById(artistId);
if (artist == null || Integer.valueOf(1).equals(artist.getIsDelete())) {
return false;
}
if (!isBookableServiceUser(artist)) {
return false;
}
if (!Integer.valueOf(1).equals(artist.getStatus())) {
return false;
}
return shopId == null || shopId <= 0 || userShopBindingSupport.isUserAccessibleInShop(artistId, shopId);
}
/**
* Purpose: isBookableServiceUser supports BookableArtistSupport.java by holding or executing the is bookable service user business role.
* Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state.
*/
public boolean isBookableServiceUser(UserDO user) {
if (user == null || Integer.valueOf(1).equals(user.getIsDelete()) || !Integer.valueOf(1).equals(user.getStatus())) {
return false;
}
if (Integer.valueOf(3).equals(user.getType())) {
return true;
}
if (!Integer.valueOf(2).equals(user.getType())) {
return false;
}
NailArtistInfoDO info = nailArtistInfoMapper.selectOne(
new LambdaQueryWrapper<NailArtistInfoDO>()
.eq(NailArtistInfoDO::getUserId, user.getId())
.eq(NailArtistInfoDO::getIsDelete, 0)
.last("LIMIT 1")
);
return info != null
&& Integer.valueOf(1).equals(info.getStatus())
&& Integer.valueOf(1).equals(info.getParticipateProduction());
}
/**
* Purpose: filterValidBookableArtists supports BookableArtistSupport.java by holding or executing the filter valid bookable artists business role.
* Usage: reference this method from the owning layer and pass validated inputs before reading or updating related state.
*/
public String filterValidBookableArtists(Long shopId, String rawBookableArtists) {
if (!StringUtils.hasText(rawBookableArtists)) {
return "";
}
Set<Long> validArtistIds = new LinkedHashSet<>();
for (String artistIdText : rawBookableArtists.split(",")) {
if (!StringUtils.hasText(artistIdText)) {
continue;
}
try {
Long artistId = Long.parseLong(artistIdText.trim());
if (isValidBookableArtist(shopId, artistId)) {
validArtistIds.add(artistId);
}
} catch (NumberFormatException ignored) {
// Ignore invalid configured IDs and only expose currently valid artists.
}
}
return validArtistIds.stream()
.map(String::valueOf)
.collect(Collectors.joining(","));
}
}
@@ -0,0 +1,91 @@
package com.xiaowang.yuminailcore.modules.artist.vo;
import lombok.Data;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import com.xiaowang.yuminailcore.modules.order.support.OrderStatus;
@Data
/**
* ArtistCalendarAppointmentVO is a response VO. Services build it and controllers return it to the frontend.
* Field and parameter names are kept consistent with the frontend/API payload to make tracing easier.
*/
public class ArtistCalendarAppointmentVO {
/**
* Field `orderId` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled.
*/
private Long orderId;
/**
* Field `orderNo` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled.
*/
private String orderNo;
/**
* Field `totalAmount` (BigDecimal): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled.
*/
private BigDecimal totalAmount;
/**
* Field `actualAmount` (BigDecimal): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled.
*/
private BigDecimal actualAmount;
/**
* Field `orderStatus` (Integer): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled.
*/
private Integer orderStatus;
/**
* Field `orderStatusText` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled.
*/
private String orderStatusText;
/**
* Field `orderItemId` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled.
*/
private Long orderItemId;
/**
* Field `productId` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled.
*/
private Long productId;
/**
* Field `productTitle` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled.
*/
private String productTitle;
/**
* Field `artistId` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled.
*/
private Long artistId;
/**
* Field `artistName` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled.
*/
private String artistName;
/**
* Field `customerNickname` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled.
*/
private String customerNickname;
/**
* Field `customerPhoneMasked` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled.
*/
private String customerPhoneMasked;
/**
* Field `shopId` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled.
*/
private Long shopId;
/**
* Field `shopName` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled.
*/
private String shopName;
/**
* Field `appointmentStartTime` (LocalDateTime): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled.
*/
private LocalDateTime appointmentStartTime;
/**
* Field `appointmentEndTime` (LocalDateTime): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled.
*/
private LocalDateTime appointmentEndTime;
/**
* Field `quantity` (Integer): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled.
*/
private Integer quantity;
/**
* Field `durationMinutes` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled.
*/
private Long durationMinutes;
}
@@ -0,0 +1,22 @@
package com.xiaowang.yuminailcore.modules.artist.vo;
import lombok.Data;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
@Data
public class ArtistScheduleVO {
private Long id;
private Long shopId;
private Long artistId;
private LocalDate workDate;
private LocalTime startTime;
private LocalTime endTime;
private Integer slotMinutes;
private Integer capacity;
private Integer status;
private String remark;
private LocalDateTime createTime;
}
@@ -0,0 +1,14 @@
package com.xiaowang.yuminailcore.modules.artist.vo;
import lombok.Data;
import java.time.LocalDateTime;
@Data
public class NailArtistAvailabilityVO {
private LocalDateTime startTime;
private LocalDateTime endTime;
private String dateText;
private String timeText;
private Boolean available;
}
@@ -0,0 +1,33 @@
package com.xiaowang.yuminailcore.modules.artist.vo;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import com.fasterxml.jackson.databind.ser.std.ToStringSerializer;
import lombok.Data;
import java.math.BigDecimal;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.List;
@Data
public class NailArtistProfileVO {
@JsonSerialize(using = ToStringSerializer.class)
private Long artistId;
private String artistName;
private String avatar;
private String identity;
private String signature;
private Integer experience;
private Integer status;
@JsonSerialize(using = ToStringSerializer.class)
private Long shopId;
private String shopName;
private BigDecimal rating;
private Long serviceCount;
private LocalTime workStartTime;
private LocalTime workEndTime;
private List<String> styleTags = new ArrayList<>();
private List<NailArtistWorkVO> works = new ArrayList<>();
private List<NailArtistReviewVO> reviews = new ArrayList<>();
private List<NailArtistAvailabilityVO> availability = new ArrayList<>();
}
@@ -0,0 +1,30 @@
package com.xiaowang.yuminailcore.modules.artist.vo;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import com.fasterxml.jackson.databind.ser.std.ToStringSerializer;
import lombok.Data;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
@Data
public class NailArtistReviewVO {
@JsonSerialize(using = ToStringSerializer.class)
private Long id;
@JsonSerialize(using = ToStringSerializer.class)
private Long artistId;
@JsonSerialize(using = ToStringSerializer.class)
private Long customerId;
private String customerName;
private String customerAvatar;
@JsonSerialize(using = ToStringSerializer.class)
private Long productId;
private String productTitle;
private BigDecimal rating;
private String content;
private List<Long> imageFileIds = new ArrayList<>();
private List<String> imageUrls = new ArrayList<>();
private LocalDateTime submittedAt;
}
@@ -0,0 +1,23 @@
package com.xiaowang.yuminailcore.modules.artist.vo;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import com.fasterxml.jackson.databind.ser.std.ToStringSerializer;
import lombok.Data;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
@Data
public class NailArtistWorkVO {
@JsonSerialize(using = ToStringSerializer.class)
private Long id;
private String title;
private String description;
private BigDecimal price;
private String coverImageUrl;
private List<String> imageUrls = new ArrayList<>();
private List<String> tags = new ArrayList<>();
private Integer likeCount;
private Integer collectCount;
}
@@ -0,0 +1,131 @@
package com.xiaowang.yuminailcore.modules.auth.controller.admin;
import com.xiaowang.yuminailcore.annotation.OperationGuard;
import com.xiaowang.yuminailcore.common.Result;
import com.xiaowang.yuminailcore.modules.auth.dto.LoginRequestDTO;
import com.xiaowang.yuminailcore.modules.planning.dto.PlanningManagerRegisterDTO;
import com.xiaowang.yuminailcore.modules.auth.dto.RefreshTokenRequestDTO;
import com.xiaowang.yuminailcore.modules.auth.dto.SwitchShopRequestDTO;
import com.xiaowang.yuminailcore.modules.user.service.UserService;
import com.xiaowang.yuminailcore.modules.security.service.SecurityAuditLogService;
import com.xiaowang.yuminailcore.support.security.RequestThrottleService;
import com.xiaowang.yuminailcore.support.security.OperationGuardStrategy;
import com.xiaowang.yuminailcore.utils.AccountValidationUtils;
import com.xiaowang.yuminailcore.modules.auth.vo.LoginShopSelectionVO;
import com.xiaowang.yuminailcore.modules.auth.vo.LoginResponseVO;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;
import javax.validation.Valid;
import javax.servlet.http.HttpServletRequest;
@RestController
@RequestMapping("/admin/auth")
@RequiredArgsConstructor
/**
* AdminAuthController exposes HTTP endpoints. Start here to learn the request path, parameter names, and which service method is called.
* Beginner guide: follow the call chain Controller -> Service -> ServiceImpl -> Mapper/support class.
*/
public class AdminAuthController {
/**
* Variable `userService`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls.
*/
private final UserService userService;
/**
* Variable `requestThrottleService`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls.
*/
private final RequestThrottleService requestThrottleService;
/**
* Purpose: securityAuditLogService supports AdminAuthController.java by holding or executing the security audit log service business role.
* Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state.
*/
private final SecurityAuditLogService securityAuditLogService;
@PostMapping("/login")
@OperationGuard(action = "admin-login", ttlSeconds = 8, message = "登录处理中,请勿重复提交")
/**
* Run the login flow.
* Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result.
* @param request parameter `request` supplied by the caller
* @param loginRequestDTO parameter `loginRequestDTO` supplied by the caller
* @return Result<LoginResponseVO> result consumed by the caller or returned to the frontend
*/
public Result<LoginResponseVO> login(HttpServletRequest request, @Valid @RequestBody LoginRequestDTO loginRequestDTO) {
requestThrottleService.checkLogin(request, loginRequestDTO.getAccount());
try {
LoginResponseVO loginResponseVO = userService.adminLogin(loginRequestDTO);
requestThrottleService.clearLoginFailure(request, loginRequestDTO.getAccount());
securityAuditLogService.record(loginResponseVO.getUserInfo().getId(), loginRequestDTO.getAccount(), "ADMIN_LOGIN", "SUCCESS", null, request);
return Result.success(loginResponseVO);
} catch (RuntimeException exception) {
requestThrottleService.recordLoginFailure(request, loginRequestDTO.getAccount());
securityAuditLogService.record(null, loginRequestDTO.getAccount(), "ADMIN_LOGIN", "FAIL", exception.getMessage(), request);
throw exception;
}
}
@PostMapping("/register")
@OperationGuard(action = "admin-planning-register", ttlSeconds = 10, message = "注册处理中,请勿重复提交")
public Result<LoginResponseVO> register(@RequestBody PlanningManagerRegisterDTO registerDTO) {
return Result.success(userService.registerPlanningManager(registerDTO));
}
@GetMapping("/login-shops/{account}")
/**
* Load data by the supplied parameter.
* Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result.
* @param account parameter `account` supplied by the caller
* @return Result<LoginShopSelectionVO> result consumed by the caller or returned to the frontend
*/
public Result<LoginShopSelectionVO> getLoginShops(@PathVariable String account) {
return Result.success(userService.getAdminLoginShopSelection(AccountValidationUtils.requireValidAccount(account)));
}
@PostMapping("/switch-shop")
@OperationGuard(action = "admin-switch-shop", ttlSeconds = 10, message = "门店切换中,请勿重复操作")
/**
* Run business method `switchShop`.
* Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result.
* @param request parameter `request` supplied by the caller
* @param switchShopRequestDTO parameter `switchShopRequestDTO` supplied by the caller
* @return Result<LoginResponseVO> result consumed by the caller or returned to the frontend
*/
public Result<LoginResponseVO> switchShop(HttpServletRequest request, @RequestBody SwitchShopRequestDTO switchShopRequestDTO) {
Long userId = (Long) request.getAttribute("userId");
return Result.success(userService.switchAdminShop(userId, switchShopRequestDTO.getShopId(), (String) request.getAttribute("sessionId")));
}
@PostMapping("/logout")
@OperationGuard(action = "admin-logout", strategy = OperationGuardStrategy.NOOP_IF_DUPLICATE, ttlSeconds = 5)
/**
* Run business method `logout`.
* Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result.
* @param request parameter `request` supplied by the caller
* @return Result<Boolean> result consumed by the caller or returned to the frontend
*/
public Result<Boolean> logout(HttpServletRequest request) {
return Result.success(userService.logout((String) request.getAttribute("sessionId")));
}
@PostMapping("/refresh")
/**
* Run business method `refreshToken`.
* Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result.
* @param refreshTokenRequestDTO parameter `refreshTokenRequestDTO` supplied by the caller
* @return Result<LoginResponseVO> result consumed by the caller or returned to the frontend
*/
public Result<LoginResponseVO> refreshToken(@RequestBody RefreshTokenRequestDTO refreshTokenRequestDTO) {
LoginResponseVO loginResponseVO = userService.refreshToken(refreshTokenRequestDTO.getRefreshToken());
if (loginResponseVO.getUserInfo() == null
|| loginResponseVO.getUserInfo().getType() == null
|| loginResponseVO.getUserInfo().getType() < 2) {
/**
* Run business method `RuntimeException`.
* Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result.
* @return throw new result consumed by the caller or returned to the frontend
*/
throw new RuntimeException("您没有后台管理权限");
}
return Result.success(loginResponseVO);
}
}
@@ -0,0 +1,111 @@
package com.xiaowang.yuminailcore.modules.auth.controller.front;
import com.xiaowang.yuminailcore.common.Result;
import com.xiaowang.yuminailcore.modules.auth.dto.LoginIdentityDTO;
import com.xiaowang.yuminailcore.modules.auth.vo.LoginIdentityVO;
import com.xiaowang.yuminailcore.modules.auth.service.LoginIdentityService;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;
import java.util.List;
/**
* 用户登录标识信息表 Controller
* 对应数据库表 t_login_identity
*
* @author xiaowang
* @date 2026-02-13
*/
@RestController
@RequestMapping({"/login-identity", "/api/login-identity"})
@RequiredArgsConstructor
public class LoginIdentityController {
/**
* Variable `loginIdentityService`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls.
*/
private final LoginIdentityService loginIdentityService;
/**
* 创建登录标识
*
* @param loginIdentityDTO 登录标识DTO
* @return 登录标识ID
*/
@PostMapping("/create")
public Result<Long> createLoginIdentity(@RequestBody LoginIdentityDTO loginIdentityDTO) {
Long id = loginIdentityService.createLoginIdentity(loginIdentityDTO);
return Result.success(id);
}
/**
* 更新登录标识
*
* @param id 登录标识ID
* @param loginIdentityDTO 登录标识DTO
* @return 是否更新成功
*/
@PutMapping("/update/{id}")
public Result<Boolean> updateLoginIdentity(@PathVariable Long id, @RequestBody LoginIdentityDTO loginIdentityDTO) {
boolean success = loginIdentityService.updateLoginIdentity(id, loginIdentityDTO);
return Result.success(success);
}
/**
* 删除登录标识
*
* @param id 登录标识ID
* @return 是否删除成功
*/
@DeleteMapping("/delete/{id}")
public Result<Boolean> deleteLoginIdentity(@PathVariable Long id) {
boolean success = loginIdentityService.deleteLoginIdentity(id);
return Result.success(success);
}
/**
* 根据ID查询登录标识
*
* @param id 登录标识ID
* @return 登录标识VO
*/
@GetMapping("/get/{id}")
public Result<LoginIdentityVO> getLoginIdentityById(@PathVariable Long id) {
LoginIdentityVO loginIdentityVO = loginIdentityService.getLoginIdentityById(id);
return Result.success(loginIdentityVO);
}
/**
* 查询所有登录标识
*
* @return 登录标识VO列表
*/
@GetMapping("/list/all")
public Result<List<LoginIdentityVO>> listAllLoginIdentities() {
List<LoginIdentityVO> loginIdentityVOs = loginIdentityService.listAllLoginIdentities();
return Result.success(loginIdentityVOs);
}
/**
* 根据用户ID查询登录标识
*
* @param userId 用户ID
* @return 登录标识VO列表
*/
@GetMapping("/list/user/{userId}")
public Result<List<LoginIdentityVO>> listLoginIdentitiesByUserId(@PathVariable Long userId) {
List<LoginIdentityVO> loginIdentityVOs = loginIdentityService.listLoginIdentitiesByUserId(userId);
return Result.success(loginIdentityVOs);
}
/**
* 根据登录方式查询登录标识
*
* @param loginMethod 登录方式
* @return 登录标识VO列表
*/
@GetMapping("/list/loginMethod/{loginMethod}")
public Result<List<LoginIdentityVO>> listLoginIdentitiesByLoginMethod(@PathVariable String loginMethod) {
List<LoginIdentityVO> loginIdentityVOs = loginIdentityService.listLoginIdentitiesByLoginMethod(loginMethod);
return Result.success(loginIdentityVOs);
}
}
@@ -0,0 +1,24 @@
package com.xiaowang.yuminailcore.modules.auth.dto;
import lombok.Data;
/**
* 绑定邮箱请求 DTO
* 用于用户绑定邮箱账号
*
* @author xiaowang
* @date 2026-03-12
*/
@Data
public class BindEmailRequestDTO {
/**
* 邮箱地址
*/
private String email;
/**
* 验证码
*/
private String code;
}
@@ -0,0 +1,26 @@
package com.xiaowang.yuminailcore.modules.auth.dto;
import com.fasterxml.jackson.annotation.JsonAlias;
import lombok.Data;
/**
* 绑定手机号请求 DTO
* 用于用户绑定手机号
*
* @author xiaowang
* @date 2026-03-12
*/
@Data
public class BindPhoneRequestDTO {
/**
* 手机号
*/
private String phone;
/**
* 验证码
*/
@JsonAlias("code")
private String verificationCode;
}
@@ -0,0 +1,41 @@
package com.xiaowang.yuminailcore.modules.auth.dto;
import lombok.Data;
import java.time.LocalDateTime;
/**
* 用户登录标识信息表 DTO
* 用于登录标识信息的传输
*
* @author xiaowang
* @date 2026-02-13
*/
@Data
public class LoginIdentityDTO {
/**
* 关联用户表主键
*/
private Long userId;
/**
* 登录方式(0-手机号、1-账号、2-邮箱)
*/
private String loginMethod;
/**
* 前端输入的具体值(如手机号、账号、邮箱)
*/
private String inputValue;
/**
* 输入时间
*/
private LocalDateTime inputTime;
/**
* 状态:1-有效,0-无效
*/
private Integer status;
}
@@ -0,0 +1,62 @@
package com.xiaowang.yuminailcore.modules.auth.dto;
import com.xiaowang.yuminailcore.utils.AccountValidationUtils;
import lombok.Getter;
import lombok.Setter;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.Pattern;
import java.util.Map;
import com.xiaowang.yuminailcore.common.dto.AgreementAwareRequest;
/**
* 登录请求 DTO
* 用于用户账号密码登录
*
* @author xiaowang
* @date 2026-02-14
*/
@Getter
@Setter
public class LoginRequestDTO implements AgreementAwareRequest {
/**
* 账号
*/
@NotBlank(message = "账号不能为空")
@Pattern(regexp = AccountValidationUtils.ACCOUNT_REGEX, message = "账号只能包含字母和数字")
private String account;
/**
* 密码
*/
private String password;
/**
* 记住我标志
*/
private Boolean rememberMe;
/**
* 店铺ID
*/
private Long shopId;
/**
* Purpose: agreementAccepted supports LoginRequestDTO.java by holding or executing the agreement accepted business role.
* Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state.
*/
private Boolean agreementAccepted;
/**
* Purpose: agreementVersions supports LoginRequestDTO.java by holding or executing the agreement versions business role.
* Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state.
*/
private Map<String, String> agreementVersions;
/**
* Purpose: clientType supports LoginRequestDTO.java by holding or executing the client type business role.
* Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state.
*/
private String clientType;
}
@@ -0,0 +1,54 @@
package com.xiaowang.yuminailcore.modules.auth.dto;
import lombok.Data;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.Pattern;
import java.util.Map;
import com.xiaowang.yuminailcore.common.dto.AgreementAwareRequest;
/**
* 手机号验证码登录请求 DTO
*
* @author xiaowang
* @date 2026-03-03
*/
@Data
public class PhoneLoginRequestDTO implements AgreementAwareRequest {
@NotBlank(message = "手机号不能为空")
@Pattern(regexp = "^1[3-9]\\d{9}$", message = "手机号格式不正确")
/**
* Field `phone` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled.
*/
private String phone;
@NotBlank(message = "验证码不能为空")
@Pattern(regexp = "^\\d{6}$", message = "验证码必须是6位数字")
/**
* Field `verificationCode` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled.
*/
private String verificationCode;
/**
* Field `shopId` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled.
*/
private Long shopId;
/**
* Purpose: agreementAccepted supports PhoneLoginRequestDTO.java by holding or executing the agreement accepted business role.
* Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state.
*/
private Boolean agreementAccepted;
/**
* Purpose: agreementVersions supports PhoneLoginRequestDTO.java by holding or executing the agreement versions business role.
* Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state.
*/
private Map<String, String> agreementVersions;
/**
* Purpose: clientType supports PhoneLoginRequestDTO.java by holding or executing the client type business role.
* Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state.
*/
private String clientType;
}
@@ -0,0 +1,19 @@
package com.xiaowang.yuminailcore.modules.auth.dto;
import lombok.Data;
/**
* 刷新Token请求 DTO
* 用于刷新访问令牌
*
* @author xiaowang
* @date 2026-02-14
*/
@Data
public class RefreshTokenRequestDTO {
/**
* 刷新令牌
*/
private String refreshToken;
}
@@ -0,0 +1,78 @@
package com.xiaowang.yuminailcore.modules.auth.dto;
import com.xiaowang.yuminailcore.utils.AccountValidationUtils;
import lombok.Data;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.Pattern;
import java.util.Map;
import com.xiaowang.yuminailcore.common.dto.AgreementAwareRequest;
/**
* 注册请求 DTO
*
* @author xiaowang
* @date 2026-02-14
*/
@Data
public class RegisterRequestDTO implements AgreementAwareRequest {
@NotBlank(message = "账号不能为空")
@Pattern(regexp = AccountValidationUtils.ACCOUNT_REGEX, message = "账号只能包含字母和数字")
/**
* Field `account` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled.
*/
private String account;
@NotBlank(message = "密码不能为空")
/**
* Field `password` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled.
*/
private String password;
/**
* Field `nickname` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled.
*/
private String nickname;
/**
* Field `shopId` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled.
*/
private Long shopId;
/**
* Field `inviteCode` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled.
*/
private String inviteCode;
@NotBlank(message = "手机号不能为空")
@Pattern(regexp = "^1[3-9]\\d{9}$", message = "手机号格式不正确")
/**
* Field `phone` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled.
*/
private String phone;
@NotBlank(message = "验证码不能为空")
@Pattern(regexp = "^\\d{6}$", message = "验证码必须是6位数字")
/**
* Field `verificationCode` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled.
*/
private String verificationCode;
/**
* Purpose: agreementAccepted supports RegisterRequestDTO.java by holding or executing the agreement accepted business role.
* Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state.
*/
private Boolean agreementAccepted;
/**
* Purpose: agreementVersions supports RegisterRequestDTO.java by holding or executing the agreement versions business role.
* Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state.
*/
private Map<String, String> agreementVersions;
/**
* Purpose: clientType supports RegisterRequestDTO.java by holding or executing the client type business role.
* Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state.
*/
private String clientType;
}
@@ -0,0 +1,29 @@
package com.xiaowang.yuminailcore.modules.auth.dto;
import lombok.Data;
/**
* 重置密码请求 DTO
* 用于用户重置密码
*
* @author xiaowang
* @date 2026-03-12
*/
@Data
public class ResetPasswordRequestDTO {
/**
* 手机号
*/
private String phone;
/**
* 验证码
*/
private String verificationCode;
/**
* 新密码
*/
private String newPassword;
}
@@ -0,0 +1,25 @@
package com.xiaowang.yuminailcore.modules.auth.dto;
import lombok.Data;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.Pattern;
/**
* 发送验证码请求 DTO。
*/
@Data
public class SendVerificationCodeRequestDTO {
@NotBlank(message = "手机号不能为空")
@Pattern(regexp = "^1[3-9]\\d{9}$", message = "手机号格式不正确")
/**
* Field `phone` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled.
*/
private String phone;
/**
* 业务场景编码,用来选择 YumiNail 投递 MessageHub 时的配置。
*/
private String sceneCode;
}
@@ -0,0 +1,16 @@
package com.xiaowang.yuminailcore.modules.auth.dto;
import lombok.Data;
@Data
/**
* SwitchShopRequestDTO is a request DTO. Controllers receive it from JSON body or query parameters and pass it into services.
* Field and parameter names are kept consistent with the frontend/API payload to make tracing easier.
*/
public class SwitchShopRequestDTO {
/**
* Field `shopId` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled.
*/
private Long shopId;
}
@@ -0,0 +1,29 @@
package com.xiaowang.yuminailcore.modules.auth.dto;
import lombok.Data;
/**
* 更换手机号请求 DTO
* 用于用户更换绑定的手机号
*
* @author xiaowang
* @date 2026-03-12
*/
@Data
public class UpdatePhoneRequestDTO {
/**
* 原手机号
*/
private String oldPhone;
/**
* 新手机号
*/
private String newPhone;
/**
* 验证码
*/
private String verificationCode;
}
@@ -0,0 +1,52 @@
package com.xiaowang.yuminailcore.modules.auth.entity;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.Data;
import lombok.EqualsAndHashCode;
import java.time.LocalDateTime;
import com.xiaowang.yuminailcore.common.entity.BaseEntity;
/**
* 用户登录标识信息表 DO
* 对应数据库表 t_login_identity
*
* @author xiaowang
* @date 2026-02-13
*/
@Data
@EqualsAndHashCode(callSuper = true)
@TableName("t_login_identity")
public class LoginIdentityDO extends BaseEntity {
/**
* 关联用户表主键
*/
@TableField("user_id")
private Long userId;
/**
* 登录方式(0-手机号、1-账号、2-邮箱)
*/
@TableField("login_method")
private String loginMethod;
/**
* 前端输入的具体值(如手机号、账号、邮箱)
*/
@TableField("input_value")
private String inputValue;
/**
* 输入时间
*/
@TableField("input_time")
private LocalDateTime inputTime;
/**
* 状态:1-有效,0-无效
*/
@TableField("status")
private Integer status;
}
@@ -0,0 +1,14 @@
package com.xiaowang.yuminailcore.modules.auth.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.xiaowang.yuminailcore.modules.auth.entity.LoginIdentityDO;
/**
* 用户登录标识信息表 Mapper
* 对应数据库表 t_login_identity
*
* @author xiaowang
* @date 2026-02-13
*/
public interface LoginIdentityMapper extends BaseMapper<LoginIdentityDO> {
}
@@ -0,0 +1,74 @@
package com.xiaowang.yuminailcore.modules.auth.service;
import com.baomidou.mybatisplus.extension.service.IService;
import com.xiaowang.yuminailcore.modules.auth.entity.LoginIdentityDO;
import com.xiaowang.yuminailcore.modules.auth.dto.LoginIdentityDTO;
import com.xiaowang.yuminailcore.modules.auth.vo.LoginIdentityVO;
import java.util.List;
/**
* 用户登录标识信息表 Service
* 对应数据库表 t_login_identity
*
* @author xiaowang
* @date 2026-02-13
*/
public interface LoginIdentityService extends IService<LoginIdentityDO> {
/**
* 创建登录标识
*
* @param loginIdentityDTO 登录标识DTO
* @return 登录标识ID
*/
Long createLoginIdentity(LoginIdentityDTO loginIdentityDTO);
/**
* 更新登录标识
*
* @param id 登录标识ID
* @param loginIdentityDTO 登录标识DTO
* @return 是否更新成功
*/
boolean updateLoginIdentity(Long id, LoginIdentityDTO loginIdentityDTO);
/**
* 删除登录标识
*
* @param id 登录标识ID
* @return 是否删除成功
*/
boolean deleteLoginIdentity(Long id);
/**
* 根据ID查询登录标识
*
* @param id 登录标识ID
* @return 登录标识VO
*/
LoginIdentityVO getLoginIdentityById(Long id);
/**
* 查询所有登录标识
*
* @return 登录标识VO列表
*/
List<LoginIdentityVO> listAllLoginIdentities();
/**
* 根据用户ID查询登录标识
*
* @param userId 用户ID
* @return 登录标识VO列表
*/
List<LoginIdentityVO> listLoginIdentitiesByUserId(Long userId);
/**
* 根据登录方式查询登录标识
*
* @param loginMethod 登录方式
* @return 登录标识VO列表
*/
List<LoginIdentityVO> listLoginIdentitiesByLoginMethod(String loginMethod);
}
@@ -0,0 +1,51 @@
package com.xiaowang.yuminailcore.modules.auth.service;
import com.xiaowang.yuminailcore.common.Result;
/**
* 验证码服务接口
*
* @author xiaowang
* @date 2026-03-03
*/
public interface VerificationCodeService {
/**
* Run business method `generateVerificationCode`.
* Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result.
* @return String result consumed by the caller or returned to the frontend
*/
String generateVerificationCode();
/**
* Send or dispatch a message.
* Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result.
* @param phone parameter `phone` supplied by the caller
*/
void sendVerificationCode(String phone);
/**
* Send or dispatch a message.
* Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result.
* @param phone parameter `phone` supplied by the caller
* @param sceneCode parameter `sceneCode` supplied by the caller
*/
void sendVerificationCode(String phone, String sceneCode);
/**
* Run business method `verifyCode`.
* Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result.
* @param phone parameter `phone` supplied by the caller
* @param code parameter `code` supplied by the caller
* @return boolean result consumed by the caller or returned to the frontend
*/
boolean verifyCode(String phone, String code);
/**
* Run business method `canResend`.
* Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result.
* @param phone parameter `phone` supplied by the caller
* @return boolean result consumed by the caller or returned to the frontend
*/
boolean canResend(String phone);
}
@@ -0,0 +1,167 @@
package com.xiaowang.yuminailcore.modules.auth.service.impl;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xiaowang.yuminailcore.modules.auth.dto.LoginIdentityDTO;
import com.xiaowang.yuminailcore.modules.auth.entity.LoginIdentityDO;
import com.xiaowang.yuminailcore.modules.auth.mapper.LoginIdentityMapper;
import com.xiaowang.yuminailcore.modules.auth.service.LoginIdentityService;
import com.xiaowang.yuminailcore.modules.auth.vo.LoginIdentityVO;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.stream.Collectors;
import com.xiaowang.yuminailcore.common.Result;
/**
* 用户登录标识信息表 Service 实现
* 对应数据库表 t_login_identity
*
* @author xiaowang
* @date 2026-02-13
*/
@Service
@RequiredArgsConstructor
public class LoginIdentityServiceImpl extends ServiceImpl<LoginIdentityMapper, LoginIdentityDO> implements LoginIdentityService {
/**
* Variable `loginIdentityMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls.
*/
private final LoginIdentityMapper loginIdentityMapper;
@Override
/**
* Create a new record.
* Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result.
* @param loginIdentityDTO parameter `loginIdentityDTO` supplied by the caller
* @return Long result consumed by the caller or returned to the frontend
*/
public Long createLoginIdentity(LoginIdentityDTO loginIdentityDTO) {
LoginIdentityDO loginIdentityDO = new LoginIdentityDO();
loginIdentityDO.setUserId(loginIdentityDTO.getUserId());
loginIdentityDO.setLoginMethod(loginIdentityDTO.getLoginMethod());
loginIdentityDO.setInputValue(loginIdentityDTO.getInputValue());
loginIdentityDO.setInputTime(loginIdentityDTO.getInputTime());
loginIdentityDO.setStatus(loginIdentityDTO.getStatus());
loginIdentityMapper.insert(loginIdentityDO);
return loginIdentityDO.getId();
}
@Override
/**
* Update an existing record.
* Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result.
* @param id parameter `id` supplied by the caller
* @param loginIdentityDTO parameter `loginIdentityDTO` supplied by the caller
* @return boolean result consumed by the caller or returned to the frontend
*/
public boolean updateLoginIdentity(Long id, LoginIdentityDTO loginIdentityDTO) {
LoginIdentityDO loginIdentityDO = loginIdentityMapper.selectById(id);
if (loginIdentityDO == null) {
return false;
}
loginIdentityDO.setUserId(loginIdentityDTO.getUserId());
loginIdentityDO.setLoginMethod(loginIdentityDTO.getLoginMethod());
loginIdentityDO.setInputValue(loginIdentityDTO.getInputValue());
loginIdentityDO.setInputTime(loginIdentityDTO.getInputTime());
loginIdentityDO.setStatus(loginIdentityDTO.getStatus());
return loginIdentityMapper.updateById(loginIdentityDO) > 0;
}
@Override
/**
* Delete, revoke, or logically remove a record.
* Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result.
* @param id parameter `id` supplied by the caller
* @return boolean result consumed by the caller or returned to the frontend
*/
public boolean deleteLoginIdentity(Long id) {
return loginIdentityMapper.deleteById(id) > 0;
}
@Override
/**
* Load data by the supplied parameter.
* Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result.
* @param id parameter `id` supplied by the caller
* @return LoginIdentityVO result consumed by the caller or returned to the frontend
*/
public LoginIdentityVO getLoginIdentityById(Long id) {
LoginIdentityDO loginIdentityDO = loginIdentityMapper.selectById(id);
if (loginIdentityDO == null) {
return null;
}
/**
* Run business method `convertToVO`.
* Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result.
* @param loginIdentityDO parameter `loginIdentityDO` supplied by the caller
* @return return result consumed by the caller or returned to the frontend
*/
return convertToVO(loginIdentityDO);
}
@Override
/**
* List records for the current query or current user scope.
* Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result.
* @return List<LoginIdentityVO> result consumed by the caller or returned to the frontend
*/
public List<LoginIdentityVO> listAllLoginIdentities() {
List<LoginIdentityDO> loginIdentityDOs = loginIdentityMapper.selectList(null);
return loginIdentityDOs.stream()
.map(this::convertToVO)
.collect(Collectors.toList());
}
@Override
/**
* List records for the current query or current user scope.
* Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result.
* @param userId parameter `userId` supplied by the caller
* @return List<LoginIdentityVO> result consumed by the caller or returned to the frontend
*/
public List<LoginIdentityVO> listLoginIdentitiesByUserId(Long userId) {
List<LoginIdentityDO> loginIdentityDOs = loginIdentityMapper.selectList(
Wrappers.lambdaQuery(LoginIdentityDO.class)
.eq(LoginIdentityDO::getUserId, userId)
);
return loginIdentityDOs.stream()
.map(this::convertToVO)
.collect(Collectors.toList());
}
@Override
/**
* List records for the current query or current user scope.
* Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result.
* @param loginMethod parameter `loginMethod` supplied by the caller
* @return List<LoginIdentityVO> result consumed by the caller or returned to the frontend
*/
public List<LoginIdentityVO> listLoginIdentitiesByLoginMethod(String loginMethod) {
List<LoginIdentityDO> loginIdentityDOs = loginIdentityMapper.selectList(
Wrappers.lambdaQuery(LoginIdentityDO.class)
.eq(LoginIdentityDO::getLoginMethod, loginMethod)
);
return loginIdentityDOs.stream()
.map(this::convertToVO)
.collect(Collectors.toList());
}
/**
* 将 DO 转换为 VO
*
* @param loginIdentityDO 登录标识DO
* @return 登录标识VO
*/
private LoginIdentityVO convertToVO(LoginIdentityDO loginIdentityDO) {
LoginIdentityVO loginIdentityVO = new LoginIdentityVO();
loginIdentityVO.setId(loginIdentityDO.getId());
loginIdentityVO.setUserId(loginIdentityDO.getUserId());
loginIdentityVO.setLoginMethod(loginIdentityDO.getLoginMethod());
loginIdentityVO.setInputValue(loginIdentityDO.getInputValue());
loginIdentityVO.setInputTime(loginIdentityDO.getInputTime());
loginIdentityVO.setUpdateTime(loginIdentityDO.getUpdateTime());
loginIdentityVO.setStatus(loginIdentityDO.getStatus());
return loginIdentityVO;
}
}
@@ -0,0 +1,148 @@
package com.xiaowang.yuminailcore.modules.auth.service.impl;
import com.xiaowang.yuminailcore.modules.integration.service.MessageHubClientService;
import com.xiaowang.yuminailcore.modules.auth.service.VerificationCodeService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import java.security.SecureRandom;
import java.time.Duration;
import com.xiaowang.yuminailcore.common.Result;
/**
* 验证码服务实现。
*/
@Slf4j
@Service
@RequiredArgsConstructor
public class VerificationCodeServiceImpl implements VerificationCodeService {
/**
* Purpose: CODE_PREFIX supports VerificationCodeServiceImpl.java by holding or executing the code prefix business role.
* Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state.
*/
private static final String CODE_PREFIX = "verification:code:";
/**
* Purpose: SEND_TIME_PREFIX supports VerificationCodeServiceImpl.java by holding or executing the send time prefix business role.
* Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state.
*/
private static final String SEND_TIME_PREFIX = "verification:send_time:";
/**
* Purpose: CODE_LENGTH supports VerificationCodeServiceImpl.java by holding or executing the code length business role.
* Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state.
*/
private static final int CODE_LENGTH = 6;
/**
* Purpose: CODE_EXPIRE_MINUTES supports VerificationCodeServiceImpl.java by holding or executing the code expire minutes business role.
* Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state.
*/
private static final int CODE_EXPIRE_MINUTES = 5;
/**
* Purpose: RESEND_INTERVAL_SECONDS supports VerificationCodeServiceImpl.java by holding or executing the resend interval seconds business role.
* Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state.
*/
private static final int RESEND_INTERVAL_SECONDS = 60;
/**
* Variable `redisTemplate`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls.
*/
private final StringRedisTemplate redisTemplate;
/**
* Variable `messageHubClientService`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls.
*/
private final MessageHubClientService messageHubClientService;
@Override
/**
* Run business method `generateVerificationCode`.
* Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result.
* @return String result consumed by the caller or returned to the frontend
*/
public String generateVerificationCode() {
SecureRandom random = new SecureRandom();
StringBuilder code = new StringBuilder();
for (int i = 0; i < CODE_LENGTH; i++) {
code.append(random.nextInt(10));
}
return code.toString();
}
@Override
/**
* Send or dispatch a message.
* Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result.
* @param phone parameter `phone` supplied by the caller
*/
public void sendVerificationCode(String phone) {
/**
* Send or dispatch a message.
* Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result.
* @param phone parameter `phone` supplied by the caller
* @param USER_LOGIN_SMS_CODE parameter `USER_LOGIN_SMS_CODE` supplied by the caller
* @return result consumed by the caller or returned to the frontend
*/
sendVerificationCode(phone, "USER_LOGIN_SMS_CODE");
}
@Override
/**
* Send or dispatch a message.
* Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result.
* @param phone parameter `phone` supplied by the caller
* @param sceneCode parameter `sceneCode` supplied by the caller
*/
public void sendVerificationCode(String phone, String sceneCode) {
String code = generateVerificationCode();
String codeKey = CODE_PREFIX + phone;
String sendTimeKey = SEND_TIME_PREFIX + phone;
redisTemplate.opsForValue().set(codeKey, code, Duration.ofMinutes(CODE_EXPIRE_MINUTES));
redisTemplate.opsForValue().set(sendTimeKey, String.valueOf(System.currentTimeMillis()),
Duration.ofSeconds(RESEND_INTERVAL_SECONDS));
messageHubClientService.sendSmsVerificationCode(sceneCode, phone, code);
log.info("验证码已发送,手机号: {}, sceneCode: {}", phone, sceneCode);
}
@Override
/**
* Run business method `verifyCode`.
* Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result.
* @param phone parameter `phone` supplied by the caller
* @param code parameter `code` supplied by the caller
* @return boolean result consumed by the caller or returned to the frontend
*/
public boolean verifyCode(String phone, String code) {
String codeKey = CODE_PREFIX + phone;
String storedCode = redisTemplate.opsForValue().get(codeKey);
if (storedCode == null) {
log.warn("验证码不存在或已过期,手机号: {}", phone);
return false;
}
if (!storedCode.equals(code)) {
log.warn("验证码错误,手机号: {}", phone);
return false;
}
redisTemplate.delete(codeKey);
log.info("验证码验证成功,手机号: {}", phone);
return true;
}
@Override
/**
* Run business method `canResend`.
* Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result.
* @param phone parameter `phone` supplied by the caller
* @return boolean result consumed by the caller or returned to the frontend
*/
public boolean canResend(String phone) {
String sendTimeKey = SEND_TIME_PREFIX + phone;
String sendTime = redisTemplate.opsForValue().get(sendTimeKey);
return sendTime == null;
}
}
@@ -0,0 +1,66 @@
package com.xiaowang.yuminailcore.modules.auth.vo;
import lombok.Data;
import java.time.LocalDateTime;
/**
* 用户登录标识信息表 VO
* 用于前端展示登录标识信息
*
* @author xiaowang
* @date 2026-02-13
*/
@Data
public class LoginIdentityVO {
/**
* 登录标识唯一主键ID(雪花id)
*/
private Long id;
/**
* 关联用户表主键
*/
private Long userId;
/**
* 用户昵称
*/
private String userNickname;
/**
* 登录方式(0-手机号、1-账号、2-邮箱)
*/
private String loginMethod;
/**
* 登录方式名称
*/
private String loginMethodName;
/**
* 前端输入的具体值(如手机号、账号、邮箱)
*/
private String inputValue;
/**
* 输入时间
*/
private LocalDateTime inputTime;
/**
* 更新时间
*/
private LocalDateTime updateTime;
/**
* 状态:1-有效,0-无效
*/
private Integer status;
/**
* 状态名称
*/
private String statusName;
}
@@ -0,0 +1,97 @@
package com.xiaowang.yuminailcore.modules.auth.vo;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import com.fasterxml.jackson.databind.ser.std.ToStringSerializer;
import lombok.Data;
import java.time.LocalDateTime;
import java.util.List;
/**
* 登录响应 VO
*
* @author xiaowang
* @date 2026-02-14
*/
@Data
public class LoginResponseVO {
/**
* Field `accessToken` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled.
*/
private String accessToken;
/**
* Field `refreshToken` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled.
*/
private String refreshToken;
/**
* Field `userInfo` (UserInfo): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled.
*/
private UserInfo userInfo;
/**
* Field `needSetPassword` (boolean): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled.
*/
private boolean needSetPassword; // 是否需要设置密码
@Data
/**
* Purpose: UserInfo supports LoginResponseVO.java by holding or executing the user info business role.
* Usage: reference this class from the owning layer and pass validated inputs before reading or updating related state.
*/
public static class UserInfo {
@JsonSerialize(using = ToStringSerializer.class)
/**
* Field `id` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled.
*/
private Long id;
/**
* Field `account` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled.
*/
private String account;
/**
* Field `nickname` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled.
*/
private String nickname;
/**
* Field `avatar` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled.
*/
private String avatar;
/**
* Field `type` (Integer): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled.
*/
private Integer type;
@JsonSerialize(using = ToStringSerializer.class)
/**
* Field `shopId` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled.
*/
private Long shopId;
/**
* Field `shopName` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled.
*/
private String shopName;
/**
* Field `shopAuthorizationExpireTime` (LocalDateTime): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled.
*/
private LocalDateTime shopAuthorizationExpireTime;
/**
* Field `shopAuthorizationExpired` (Boolean): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled.
*/
private Boolean shopAuthorizationExpired;
@JsonSerialize(contentUsing = ToStringSerializer.class)
/**
* Field `shopIds` (List<Long>): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled.
*/
private List<Long> shopIds;
/**
* Field `shopNames` (List<String>): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled.
*/
private List<String> shopNames;
/**
* Field `createTime` (LocalDateTime): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled.
*/
private LocalDateTime createTime;
}
}
@@ -0,0 +1,29 @@
package com.xiaowang.yuminailcore.modules.auth.vo;
import lombok.Data;
import java.util.ArrayList;
import java.util.List;
import com.xiaowang.yuminailcore.modules.shop.vo.ShopSimpleVO;
/**
* 登录页可选店铺结果。
*/
@Data
public class LoginShopSelectionVO {
/**
* Field `allowShoplessLogin` (boolean): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled.
*/
private boolean allowShoplessLogin;
/**
* Field `message` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled.
*/
private String message;
/**
* Field `shops` (List<ShopSimpleVO>): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled.
*/
private List<ShopSimpleVO> shops = new ArrayList<>();
}
@@ -0,0 +1,65 @@
package com.xiaowang.yuminailcore.modules.content.controller.admin;
import com.xiaowang.yuminailcore.annotation.RequirePermission;
import com.xiaowang.yuminailcore.common.Result;
import com.xiaowang.yuminailcore.modules.user.entity.UserDO;
import com.xiaowang.yuminailcore.modules.content.service.CommentService;
import com.xiaowang.yuminailcore.modules.security.support.AdminScopeHelper;
import com.xiaowang.yuminailcore.modules.content.vo.CommentVO;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
@RestController
@RequestMapping("/admin/comment")
@RequiredArgsConstructor
/**
* AdminCommentController exposes HTTP endpoints. Start here to learn the request path, parameter names, and which service method is called.
* Beginner guide: follow the call chain Controller -> Service -> ServiceImpl -> Mapper/support class.
*/
public class AdminCommentController {
/**
* Variable `commentService`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls.
*/
private final CommentService commentService;
/**
* Variable `adminScopeHelper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls.
*/
private final AdminScopeHelper adminScopeHelper;
@GetMapping("/list")
@RequirePermission("comment:view")
public Result<List<CommentVO>> listComments(
HttpServletRequest request,
@RequestParam(required = false) Long productId,
@RequestParam(required = false) Long userId,
@RequestParam(required = false) Long shopId,
@RequestParam(required = false) String keyword
) {
UserDO currentUser = adminScopeHelper.getCurrentUser(request);
Long scopedShopId = adminScopeHelper.resolveShopScope(currentUser, shopId);
return Result.success(commentService.listAdminComments(productId, userId, scopedShopId, keyword));
}
@DeleteMapping("/delete/{id}")
@RequirePermission("comment:delete")
/**
* Delete, revoke, or logically remove a record.
* Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result.
* @param request parameter `request` supplied by the caller
* @param id parameter `id` supplied by the caller
* @return Result<Boolean> result consumed by the caller or returned to the frontend
*/
public Result<Boolean> deleteComment(HttpServletRequest request, @PathVariable Long id) {
UserDO currentUser = adminScopeHelper.getCurrentUser(request);
Long managedShopId = adminScopeHelper.resolveShopScope(currentUser, null);
return Result.success(commentService.adminDeleteComment(id, managedShopId));
}
}
@@ -0,0 +1,190 @@
package com.xiaowang.yuminailcore.modules.content.controller.front;
import com.xiaowang.yuminailcore.annotation.OperationGuard;
import com.xiaowang.yuminailcore.common.Result;
import com.xiaowang.yuminailcore.modules.content.dto.CommentDTO;
import com.xiaowang.yuminailcore.modules.file.dto.ObjectStorageFileDTO;
import com.xiaowang.yuminailcore.modules.content.service.CommentService;
import com.xiaowang.yuminailcore.modules.file.service.MinioService;
import com.xiaowang.yuminailcore.modules.file.service.ObjectStorageFileService;
import com.xiaowang.yuminailcore.support.id.TimeOrderedSnowflakeIdGenerator;
import com.xiaowang.yuminailcore.support.security.UploadSecurityValidator;
import com.xiaowang.yuminailcore.modules.content.vo.CommentVO;
import com.xiaowang.yuminailcore.modules.file.vo.ObjectStorageFileVO;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
/**
* 用户评论信息表 Controller
* 对应数据库表 t_comment
*
* @author xiaowang
* @date 2026-02-13
*/
@RestController
@RequestMapping({"/comment", "/api/comment"})
@RequiredArgsConstructor
public class CommentController {
/**
* Variable `commentService`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls.
*/
private final CommentService commentService;
private final ObjectStorageFileService objectStorageFileService;
private final MinioService minioService;
private final TimeOrderedSnowflakeIdGenerator snowflakeIdGenerator;
private final UploadSecurityValidator uploadSecurityValidator;
/**
* 创建评论
*
* @param commentDTO 评论DTO
* @return 评论ID
*/
@PostMapping("/create")
public Result<Long> createComment(HttpServletRequest request, @RequestBody CommentDTO commentDTO) {
Long userId = (Long) request.getAttribute("userId");
Long id = commentService.createComment(userId, commentDTO);
return Result.success(id);
}
@PostMapping("/upload-image")
@OperationGuard(action = "comment-image-upload", ttlSeconds = 15, message = "图片正在上传中,请勿重复操作")
public Result<ObjectStorageFileVO> uploadCommentImage(HttpServletRequest request, @RequestParam("file") MultipartFile file) {
Long userId = (Long) request.getAttribute("userId");
if (userId == null) {
return Result.error("请先登录后再上传评价图片");
}
try {
uploadSecurityValidator.validate(file);
String originalFilename = file.getOriginalFilename();
if (originalFilename == null || originalFilename.isEmpty()) {
originalFilename = "comment-image";
}
String fileExtension = originalFilename == null || !originalFilename.contains(".")
? ""
: originalFilename.substring(originalFilename.lastIndexOf("."));
String objectName = snowflakeIdGenerator.nextIdString() + fileExtension;
String fileUrl = minioService.uploadFile(file, objectName);
ObjectStorageFileDTO dto = new ObjectStorageFileDTO();
dto.setFileName(originalFilename);
dto.setFileUrl(fileUrl);
dto.setObjectName(objectName);
dto.setMinioUrl(fileUrl);
dto.setContentType(file.getContentType());
dto.setFileSize(file.getSize());
dto.setMinioUploadStatus(1);
dto.setOssUploadStatus(0);
dto.setOssRetryCount(0);
dto.setStatus(1);
Long fileId = objectStorageFileService.createObjectStorageFile(dto);
return Result.success(objectStorageFileService.getObjectStorageFileById(fileId));
} catch (Exception e) {
e.printStackTrace();
return Result.error("评价图片上传失败: " + e.getMessage());
}
}
/**
* 更新评论
*
* @param id 评论ID
* @param commentDTO 评论DTO
* @return 是否更新成功
*/
@PutMapping("/update/{id}")
public Result<Boolean> updateComment(HttpServletRequest request, @PathVariable Long id, @RequestBody CommentDTO commentDTO) {
Long userId = (Long) request.getAttribute("userId");
boolean success = commentService.updateComment(id, userId, commentDTO);
return Result.success(success);
}
/**
* 删除评论
*
* @param id 评论ID
* @return 是否删除成功
*/
@DeleteMapping("/delete/{id}")
public Result<Boolean> deleteComment(HttpServletRequest request, @PathVariable Long id) {
Long userId = (Long) request.getAttribute("userId");
boolean success = commentService.deleteComment(id, userId);
return Result.success(success);
}
/**
* 根据ID查询评论
*
* @param id 评论ID
* @return 评论VO
*/
@GetMapping("/get/{id}")
public Result<CommentVO> getCommentById(@PathVariable Long id) {
CommentVO commentVO = commentService.getCommentById(id);
return Result.success(commentVO);
}
/**
* 查询所有评论
*
* @return 评论VO列表
*/
@GetMapping("/list/all")
public Result<List<CommentVO>> listAllComments() {
List<CommentVO> commentVOs = commentService.listAllComments();
return Result.success(commentVOs);
}
/**
* 根据用户ID查询评论
*
* @param userId 用户ID
* @return 评论VO列表
*/
@GetMapping("/list/user/{userId}")
public Result<List<CommentVO>> listCommentsByUserId(@PathVariable Long userId) {
List<CommentVO> commentVOs = commentService.listCommentsByUserId(userId);
return Result.success(commentVOs);
}
/**
* 根据店铺ID查询评论
*
* @param shopId 店铺ID
* @return 评论VO列表
*/
@GetMapping("/list/shop/{shopId}")
public Result<List<CommentVO>> listCommentsByShopId(@PathVariable Long shopId) {
List<CommentVO> commentVOs = commentService.listCommentsByShopId(shopId);
return Result.success(commentVOs);
}
/**
* 根据商品ID查询评论
*
* @param productId 商品ID
* @return 评论VO列表
*/
@GetMapping("/list/product/{productId}")
public Result<List<CommentVO>> listCommentsByProductId(@PathVariable Long productId) {
List<CommentVO> commentVOs = commentService.listCommentsByProductId(productId);
return Result.success(commentVOs);
}
/**
* 根据父级评论ID查询回复
*
* @param parentCommentId 父级评论ID
* @return 评论VO列表
*/
@GetMapping("/list/parent/{parentCommentId}")
public Result<List<CommentVO>> listCommentsByParentCommentId(@PathVariable Long parentCommentId) {
List<CommentVO> commentVOs = commentService.listCommentsByParentCommentId(parentCommentId);
return Result.success(commentVOs);
}
}
@@ -0,0 +1,51 @@
package com.xiaowang.yuminailcore.modules.content.dto;
import lombok.Data;
import java.util.List;
/**
* 用户评论信息表 DTO
* 用于评论信息的传输
*
* @author xiaowang
* @date 2026-02-13
*/
@Data
public class CommentDTO {
/**
* 评论用户ID,关联用户表主键
*/
private Long userId;
/**
* 关联店铺表主键(0表示非店铺评论)
*/
private Long shopId;
/**
* 关联商品表主键(0表示非商品评论)
*/
private Long productId;
/**
* 评论内容
*/
private String commentContent;
/**
* 父级评论ID(0表示为根评论)
*/
private Long parentCommentId;
/**
* 评论评分:1-5星,根评论使用
*/
private Integer ratingScore;
/**
* 评论图片文件ID集合,根评论使用
*/
private List<Long> imageFileIds;
}
@@ -0,0 +1,74 @@
package com.xiaowang.yuminailcore.modules.content.entity;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableName;
import lombok.Data;
import lombok.EqualsAndHashCode;
import com.xiaowang.yuminailcore.common.entity.BaseEntity;
/**
* 用户评论信息表 DO
* 对应数据库表 t_comment
*
* @author xiaowang
* @date 2026-02-13
*/
@Data
@EqualsAndHashCode(callSuper = true)
@TableName("t_comment")
public class CommentDO extends BaseEntity {
/**
* 评论用户ID,关联用户表主键
*/
@TableField("user_id")
private Long userId;
/**
* 关联店铺表主键(0表示非店铺评论)
*/
@TableField("shop_id")
private Long shopId;
/**
* 关联商品表主键(0表示非商品评论)
*/
@TableField("product_id")
private Long productId;
/**
* 评论内容
*/
@TableField("comment_content")
private String commentContent;
/**
* 父级评论ID(0表示为根评论)
*/
@TableField("parent_comment_id")
private Long parentCommentId;
/**
* 评论评分:1-5星
*/
@TableField("rating_score")
private Integer ratingScore;
/**
* 评论图片文件ID集合,多个ID以逗号分隔
*/
@TableField("image_file_ids")
private String imageFileIds;
/**
* 评论点赞数
*/
@TableField("like_count")
private Integer likeCount;
/**
* 逻辑删除标识:0-未删除,1-已删除
*/
@TableField("is_delete")
private Integer isDelete;
}
@@ -0,0 +1,14 @@
package com.xiaowang.yuminailcore.modules.content.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.xiaowang.yuminailcore.modules.content.entity.CommentDO;
/**
* 用户评论信息表 Mapper
* 对应数据库表 t_comment
*
* @author xiaowang
* @date 2026-02-13
*/
public interface CommentMapper extends BaseMapper<CommentDO> {
}
@@ -0,0 +1,139 @@
package com.xiaowang.yuminailcore.modules.content.service;
import com.baomidou.mybatisplus.extension.service.IService;
import com.xiaowang.yuminailcore.modules.content.entity.CommentDO;
import com.xiaowang.yuminailcore.modules.content.dto.CommentDTO;
import com.xiaowang.yuminailcore.modules.content.vo.CommentVO;
import java.util.List;
import com.xiaowang.yuminailcore.common.Result;
/**
* 用户评论信息表 Service
* 对应数据库表 t_comment
*
* @author xiaowang
* @date 2026-02-13
*/
public interface CommentService extends IService<CommentDO> {
/**
* 创建评论
*
* @param commentDTO 评论DTO
* @return 评论ID
*/
Long createComment(CommentDTO commentDTO);
/**
* Create a new record.
* Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result.
* @param currentUserId parameter `currentUserId` supplied by the caller
* @param commentDTO parameter `commentDTO` supplied by the caller
* @return Long result consumed by the caller or returned to the frontend
*/
Long createComment(Long currentUserId, CommentDTO commentDTO);
/**
* 更新评论
*
* @param id 评论ID
* @param commentDTO 评论DTO
* @return 是否更新成功
*/
boolean updateComment(Long id, CommentDTO commentDTO);
/**
* Update an existing record.
* Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result.
* @param id parameter `id` supplied by the caller
* @param currentUserId parameter `currentUserId` supplied by the caller
* @param commentDTO parameter `commentDTO` supplied by the caller
* @return boolean result consumed by the caller or returned to the frontend
*/
boolean updateComment(Long id, Long currentUserId, CommentDTO commentDTO);
/**
* 删除评论
*
* @param id 评论ID
* @return 是否删除成功
*/
boolean deleteComment(Long id);
/**
* Delete, revoke, or logically remove a record.
* Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result.
* @param id parameter `id` supplied by the caller
* @param currentUserId parameter `currentUserId` supplied by the caller
* @return boolean result consumed by the caller or returned to the frontend
*/
boolean deleteComment(Long id, Long currentUserId);
/**
* Run business method `adminDeleteComment`.
* Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result.
* @param id parameter `id` supplied by the caller
* @param managedShopId parameter `managedShopId` supplied by the caller
* @return boolean result consumed by the caller or returned to the frontend
*/
boolean adminDeleteComment(Long id, Long managedShopId);
/**
* List records for the current query or current user scope.
* Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result.
* @param productId parameter `productId` supplied by the caller
* @param userId parameter `userId` supplied by the caller
* @param shopId parameter `shopId` supplied by the caller
* @param keyword parameter `keyword` supplied by the caller
* @return List<CommentVO> result consumed by the caller or returned to the frontend
*/
List<CommentVO> listAdminComments(Long productId, Long userId, Long shopId, String keyword);
/**
* 根据ID查询评论
*
* @param id 评论ID
* @return 评论VO
*/
CommentVO getCommentById(Long id);
/**
* 查询所有评论
*
* @return 评论VO列表
*/
List<CommentVO> listAllComments();
/**
* 根据用户ID查询评论
*
* @param userId 用户ID
* @return 评论VO列表
*/
List<CommentVO> listCommentsByUserId(Long userId);
/**
* 根据店铺ID查询评论
*
* @param shopId 店铺ID
* @return 评论VO列表
*/
List<CommentVO> listCommentsByShopId(Long shopId);
/**
* 根据商品ID查询评论
*
* @param productId 商品ID
* @return 评论VO列表
*/
List<CommentVO> listCommentsByProductId(Long productId);
/**
* 根据父级评论ID查询回复
*
* @param parentCommentId 父级评论ID
* @return 评论VO列表
*/
List<CommentVO> listCommentsByParentCommentId(Long parentCommentId);
}
@@ -0,0 +1,621 @@
package com.xiaowang.yuminailcore.modules.content.service.impl;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xiaowang.yuminailcore.modules.content.dto.CommentDTO;
import com.xiaowang.yuminailcore.modules.content.entity.CommentDO;
import com.xiaowang.yuminailcore.modules.product.entity.ProductDO;
import com.xiaowang.yuminailcore.modules.shop.entity.ShopDO;
import com.xiaowang.yuminailcore.modules.user.entity.UserDO;
import com.xiaowang.yuminailcore.modules.content.mapper.CommentMapper;
import com.xiaowang.yuminailcore.modules.product.mapper.ProductMapper;
import com.xiaowang.yuminailcore.modules.shop.mapper.ShopMapper;
import com.xiaowang.yuminailcore.modules.user.mapper.UserMapper;
import com.xiaowang.yuminailcore.modules.content.service.CommentService;
import com.xiaowang.yuminailcore.modules.file.service.ObjectStorageFileService;
import com.xiaowang.yuminailcore.modules.file.support.ObjectStorageUrlSupport;
import com.xiaowang.yuminailcore.modules.content.vo.CommentVO;
import com.xiaowang.yuminailcore.modules.file.vo.ObjectStorageFileVO;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.HashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import com.xiaowang.yuminailcore.common.Result;
/**
* 用户评论信息表 Service 实现
* 对应数据库表 t_comment
*
* @author xiaowang
* @date 2026-02-13
*/
@Service
@RequiredArgsConstructor
public class CommentServiceImpl extends ServiceImpl<CommentMapper, CommentDO> implements CommentService {
/**
* Variable `commentMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls.
*/
private final CommentMapper commentMapper;
/**
* Variable `userMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls.
*/
private final UserMapper userMapper;
/**
* Variable `shopMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls.
*/
private final ShopMapper shopMapper;
/**
* Variable `productMapper`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls.
*/
private final ProductMapper productMapper;
private final ObjectStorageFileService objectStorageFileService;
private final ObjectStorageUrlSupport objectStorageUrlSupport;
@Override
/**
* Create a new record.
* Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result.
* @param commentDTO parameter `commentDTO` supplied by the caller
* @return Long result consumed by the caller or returned to the frontend
*/
public Long createComment(CommentDTO commentDTO) {
if (commentDTO == null || commentDTO.getUserId() == null) {
/**
* Run business method `RuntimeException`.
* Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result.
* @return throw new result consumed by the caller or returned to the frontend
*/
throw new RuntimeException("请先登录后再评论");
}
return createComment(commentDTO.getUserId(), commentDTO);
}
@Override
/**
* Create a new record.
* Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result.
* @param currentUserId parameter `currentUserId` supplied by the caller
* @param commentDTO parameter `commentDTO` supplied by the caller
* @return Long result consumed by the caller or returned to the frontend
*/
public Long createComment(Long currentUserId, CommentDTO commentDTO) {
if (currentUserId == null) {
/**
* Run business method `RuntimeException`.
* Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result.
* @return throw new result consumed by the caller or returned to the frontend
*/
throw new RuntimeException("请先登录后再评论");
}
if (commentDTO == null) {
/**
* Run business method `RuntimeException`.
* Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result.
* @return throw new result consumed by the caller or returned to the frontend
*/
throw new RuntimeException("评论内容不能为空");
}
String content = sanitizeContent(commentDTO.getCommentContent());
Long productId = normalizeId(commentDTO.getProductId());
Long parentCommentId = normalizeId(commentDTO.getParentCommentId());
if (productId == null && parentCommentId == null) {
/**
* Run business method `RuntimeException`.
* Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result.
* @return throw new result consumed by the caller or returned to the frontend
*/
throw new RuntimeException("请选择要评论的作品");
}
CommentDO parentComment = null;
if (parentCommentId != null) {
parentComment = commentMapper.selectById(parentCommentId);
if (parentComment == null || Integer.valueOf(1).equals(parentComment.getIsDelete())) {
/**
* Run business method `RuntimeException`.
* Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result.
* @return throw new result consumed by the caller or returned to the frontend
*/
throw new RuntimeException("回复的评论不存在");
}
if (productId == null) {
productId = parentComment.getProductId();
} else if (parentComment.getProductId() != null && !productId.equals(parentComment.getProductId())) {
/**
* Run business method `RuntimeException`.
* Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result.
* @return throw new result consumed by the caller or returned to the frontend
*/
throw new RuntimeException("回复内容与作品不匹配");
}
}
Long shopId = normalizeId(commentDTO.getShopId());
if (shopId == null && productId != null) {
ProductDO product = productMapper.selectById(productId);
if (product != null && !Integer.valueOf(1).equals(product.getIsDelete())) {
shopId = product.getShopId();
}
}
CommentDO commentDO = new CommentDO();
boolean rootComment = parentCommentId == null;
commentDO.setUserId(currentUserId);
commentDO.setShopId(shopId);
commentDO.setProductId(productId);
commentDO.setCommentContent(content);
commentDO.setParentCommentId(parentCommentId);
if (rootComment) {
commentDO.setRatingScore(normalizeRatingScore(commentDTO.getRatingScore()));
commentDO.setImageFileIds(joinImageFileIds(commentDTO.getImageFileIds()));
}
commentDO.setLikeCount(0);
commentDO.setIsDelete(0);
commentMapper.insert(commentDO);
return commentDO.getId();
}
@Override
/**
* Update an existing record.
* Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result.
* @param id parameter `id` supplied by the caller
* @param commentDTO parameter `commentDTO` supplied by the caller
* @return boolean result consumed by the caller or returned to the frontend
*/
public boolean updateComment(Long id, CommentDTO commentDTO) {
CommentDO commentDO = commentMapper.selectById(id);
if (commentDO == null) {
return false;
}
commentDO.setCommentContent(sanitizeContent(commentDTO.getCommentContent()));
commentDO.setUpdateTime(LocalDateTime.now());
return commentMapper.updateById(commentDO) > 0;
}
@Override
/**
* Delete, revoke, or logically remove a record.
* Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result.
* @param id parameter `id` supplied by the caller
* @return boolean result consumed by the caller or returned to the frontend
*/
public boolean deleteComment(Long id) {
CommentDO commentDO = commentMapper.selectById(id);
if (commentDO == null) {
return false;
}
commentDO.setIsDelete(1);
return commentMapper.updateById(commentDO) > 0;
}
@Override
/**
* Update an existing record.
* Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result.
* @param id parameter `id` supplied by the caller
* @param currentUserId parameter `currentUserId` supplied by the caller
* @param commentDTO parameter `commentDTO` supplied by the caller
* @return boolean result consumed by the caller or returned to the frontend
*/
public boolean updateComment(Long id, Long currentUserId, CommentDTO commentDTO) {
CommentDO commentDO = commentMapper.selectById(id);
if (commentDO == null || Integer.valueOf(1).equals(commentDO.getIsDelete())) {
return false;
}
if (currentUserId == null || !currentUserId.equals(commentDO.getUserId())) {
/**
* Run business method `RuntimeException`.
* Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result.
* @return throw new result consumed by the caller or returned to the frontend
*/
throw new RuntimeException("只能修改自己的评论");
}
commentDO.setCommentContent(sanitizeContent(commentDTO.getCommentContent()));
commentDO.setUpdateTime(LocalDateTime.now());
return commentMapper.updateById(commentDO) > 0;
}
@Override
/**
* Delete, revoke, or logically remove a record.
* Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result.
* @param id parameter `id` supplied by the caller
* @param currentUserId parameter `currentUserId` supplied by the caller
* @return boolean result consumed by the caller or returned to the frontend
*/
public boolean deleteComment(Long id, Long currentUserId) {
CommentDO commentDO = commentMapper.selectById(id);
if (commentDO == null || Integer.valueOf(1).equals(commentDO.getIsDelete())) {
return false;
}
if (currentUserId == null || !currentUserId.equals(commentDO.getUserId())) {
/**
* Run business method `RuntimeException`.
* Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result.
* @return throw new result consumed by the caller or returned to the frontend
*/
throw new RuntimeException("只能删除自己的评论");
}
commentDO.setIsDelete(1);
commentDO.setUpdateTime(LocalDateTime.now());
return commentMapper.updateById(commentDO) > 0;
}
@Override
/**
* Run business method `adminDeleteComment`.
* Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result.
* @param id parameter `id` supplied by the caller
* @param managedShopId parameter `managedShopId` supplied by the caller
* @return boolean result consumed by the caller or returned to the frontend
*/
public boolean adminDeleteComment(Long id, Long managedShopId) {
CommentDO commentDO = commentMapper.selectById(id);
if (commentDO == null || Integer.valueOf(1).equals(commentDO.getIsDelete())) {
return false;
}
if (managedShopId != null && !managedShopId.equals(commentDO.getShopId())) {
/**
* Run business method `RuntimeException`.
* Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result.
* @return throw new result consumed by the caller or returned to the frontend
*/
throw new RuntimeException("无权删除其他门店评论");
}
commentDO.setIsDelete(1);
commentDO.setUpdateTime(LocalDateTime.now());
return commentMapper.updateById(commentDO) > 0;
}
@Override
/**
* Load data by the supplied parameter.
* Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result.
* @param id parameter `id` supplied by the caller
* @return CommentVO result consumed by the caller or returned to the frontend
*/
public CommentVO getCommentById(Long id) {
CommentDO commentDO = commentMapper.selectById(id);
if (commentDO == null || Integer.valueOf(1).equals(commentDO.getIsDelete())) {
return null;
}
/**
* Run business method `convertToVO`.
* Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result.
* @param commentDO parameter `commentDO` supplied by the caller
* @return return result consumed by the caller or returned to the frontend
*/
return convertToVO(commentDO);
}
@Override
/**
* List records for the current query or current user scope.
* Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result.
* @return List<CommentVO> result consumed by the caller or returned to the frontend
*/
public List<CommentVO> listAllComments() {
return toCommentVOList(activeQuery().orderByDesc(CommentDO::getCreateTime));
}
@Override
/**
* List records for the current query or current user scope.
* Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result.
* @param userId parameter `userId` supplied by the caller
* @return List<CommentVO> result consumed by the caller or returned to the frontend
*/
public List<CommentVO> listCommentsByUserId(Long userId) {
List<CommentDO> commentDOs = commentMapper.selectList(
Wrappers.lambdaQuery(CommentDO.class)
.eq(CommentDO::getUserId, userId)
.eq(CommentDO::getIsDelete, 0)
.orderByDesc(CommentDO::getCreateTime)
);
return commentDOs.stream()
.map(this::convertToVO)
.collect(Collectors.toList());
}
@Override
/**
* List records for the current query or current user scope.
* Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result.
* @param shopId parameter `shopId` supplied by the caller
* @return List<CommentVO> result consumed by the caller or returned to the frontend
*/
public List<CommentVO> listCommentsByShopId(Long shopId) {
List<CommentDO> commentDOs = commentMapper.selectList(
Wrappers.lambdaQuery(CommentDO.class)
.eq(CommentDO::getShopId, shopId)
.eq(CommentDO::getIsDelete, 0)
.orderByDesc(CommentDO::getCreateTime)
);
return commentDOs.stream()
.map(this::convertToVO)
.collect(Collectors.toList());
}
@Override
/**
* List records for the current query or current user scope.
* Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result.
* @param productId parameter `productId` supplied by the caller
* @return List<CommentVO> result consumed by the caller or returned to the frontend
*/
public List<CommentVO> listCommentsByProductId(Long productId) {
List<CommentDO> commentDOs = commentMapper.selectList(
Wrappers.lambdaQuery(CommentDO.class)
.eq(CommentDO::getProductId, productId)
.eq(CommentDO::getIsDelete, 0)
.orderByDesc(CommentDO::getCreateTime)
);
/**
* Run business method `buildTree`.
* Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result.
* @param commentDOs parameter `commentDOs` supplied by the caller
* @return return result consumed by the caller or returned to the frontend
*/
return buildTree(commentDOs);
}
@Override
/**
* List records for the current query or current user scope.
* Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result.
* @param parentCommentId parameter `parentCommentId` supplied by the caller
* @return List<CommentVO> result consumed by the caller or returned to the frontend
*/
public List<CommentVO> listCommentsByParentCommentId(Long parentCommentId) {
List<CommentDO> commentDOs = commentMapper.selectList(
Wrappers.lambdaQuery(CommentDO.class)
.eq(CommentDO::getParentCommentId, parentCommentId)
.eq(CommentDO::getIsDelete, 0)
.orderByAsc(CommentDO::getCreateTime)
);
return commentDOs.stream()
.map(this::convertToVO)
.collect(Collectors.toList());
}
@Override
/**
* List records for the current query or current user scope.
* Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result.
* @param productId parameter `productId` supplied by the caller
* @param userId parameter `userId` supplied by the caller
* @param shopId parameter `shopId` supplied by the caller
* @param keyword parameter `keyword` supplied by the caller
* @return List<CommentVO> result consumed by the caller or returned to the frontend
*/
public List<CommentVO> listAdminComments(Long productId, Long userId, Long shopId, String keyword) {
List<CommentDO> commentDOs = commentMapper.selectList(
Wrappers.lambdaQuery(CommentDO.class)
.eq(CommentDO::getIsDelete, 0)
.eq(productId != null && productId > 0, CommentDO::getProductId, productId)
.eq(userId != null && userId > 0, CommentDO::getUserId, userId)
.eq(shopId != null && shopId > 0, CommentDO::getShopId, shopId)
.like(StringUtils.hasText(keyword), CommentDO::getCommentContent, keyword)
.orderByDesc(CommentDO::getCreateTime)
);
return commentDOs.stream().map(this::convertToVO).collect(Collectors.toList());
}
/**
* 将 DO 转换为 VO
*
* @param commentDO 评论DO
* @return 评论VO
*/
private CommentVO convertToVO(CommentDO commentDO) {
CommentVO commentVO = new CommentVO();
commentVO.setId(commentDO.getId());
commentVO.setUserId(commentDO.getUserId());
commentVO.setShopId(commentDO.getShopId());
commentVO.setProductId(commentDO.getProductId());
commentVO.setCommentContent(commentDO.getCommentContent());
commentVO.setParentCommentId(commentDO.getParentCommentId());
commentVO.setLikeCount(commentDO.getLikeCount());
commentVO.setRatingScore(commentDO.getRatingScore());
List<Long> imageFileIds = parseImageFileIds(commentDO.getImageFileIds());
commentVO.setImageFileIds(imageFileIds);
commentVO.setImageUrls(resolveImageUrls(imageFileIds));
commentVO.setCreateTime(commentDO.getCreateTime());
commentVO.setUpdateTime(commentDO.getUpdateTime());
/**
* Run business method `fillDisplayFields`.
* Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result.
* @param commentVO parameter `commentVO` supplied by the caller
* @param commentDO parameter `commentDO` supplied by the caller
* @return result consumed by the caller or returned to the frontend
*/
fillDisplayFields(commentVO, commentDO);
return commentVO;
}
/**
* Run business method `toCommentVOList`.
* Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result.
* @param wrapper parameter `wrapper` supplied by the caller
* @return private List<CommentVO> result consumed by the caller or returned to the frontend
*/
private List<CommentVO> toCommentVOList(com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper<CommentDO> wrapper) {
return commentMapper.selectList(wrapper).stream().map(this::convertToVO).collect(Collectors.toList());
}
/**
* Run business method `buildTree`.
* Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result.
* @param commentDOs parameter `commentDOs` supplied by the caller
* @return private List<CommentVO> result consumed by the caller or returned to the frontend
*/
private List<CommentVO> buildTree(List<CommentDO> commentDOs) {
Map<Long, CommentVO> rootMap = new HashMap<>();
List<CommentVO> roots = new ArrayList<>();
List<CommentVO> replies = new ArrayList<>();
for (CommentDO commentDO : commentDOs) {
CommentVO vo = convertToVO(commentDO);
if (commentDO.getParentCommentId() == null || commentDO.getParentCommentId() <= 0) {
vo.setReplies(new ArrayList<>());
rootMap.put(commentDO.getId(), vo);
roots.add(vo);
} else {
replies.add(vo);
}
}
replies.sort(Comparator.comparing(CommentVO::getCreateTime, Comparator.nullsLast(Comparator.naturalOrder())));
for (CommentVO reply : replies) {
CommentVO root = rootMap.get(reply.getParentCommentId());
if (root != null) {
root.getReplies().add(reply);
}
}
roots.sort(Comparator.comparing(CommentVO::getCreateTime, Comparator.nullsLast(Comparator.naturalOrder())).reversed());
return roots;
}
/**
* Run business method `fillDisplayFields`.
* Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result.
* @param commentVO parameter `commentVO` supplied by the caller
* @param commentDO parameter `commentDO` supplied by the caller
* @return private void result consumed by the caller or returned to the frontend
*/
private void fillDisplayFields(CommentVO commentVO, CommentDO commentDO) {
UserDO user = commentDO.getUserId() == null ? null : userMapper.selectById(commentDO.getUserId());
if (user != null) {
commentVO.setUserNickname(StringUtils.hasText(user.getNickname()) ? user.getNickname() : user.getAccount());
}
ShopDO shop = commentDO.getShopId() == null ? null : shopMapper.selectById(commentDO.getShopId());
if (shop != null) {
commentVO.setShopName(shop.getShopName());
}
ProductDO product = commentDO.getProductId() == null ? null : productMapper.selectById(commentDO.getProductId());
if (product != null) {
commentVO.setProductTitle(product.getTitle());
}
if (commentDO.getParentCommentId() != null && commentDO.getParentCommentId() > 0) {
CommentDO parent = commentMapper.selectById(commentDO.getParentCommentId());
if (parent != null && !Integer.valueOf(1).equals(parent.getIsDelete())) {
commentVO.setParentCommentContent(parent.getCommentContent());
}
}
}
private Integer normalizeRatingScore(Integer ratingScore) {
if (ratingScore == null) {
return 5;
}
return Math.max(1, Math.min(5, ratingScore));
}
private String joinImageFileIds(List<Long> imageFileIds) {
if (imageFileIds == null || imageFileIds.isEmpty()) {
return null;
}
return imageFileIds.stream()
.filter(id -> id != null && id > 0)
.distinct()
.limit(6)
.map(String::valueOf)
.collect(Collectors.joining(","));
}
private List<Long> parseImageFileIds(String imageFileIds) {
List<Long> result = new ArrayList<>();
if (!StringUtils.hasText(imageFileIds)) {
return result;
}
for (String token : imageFileIds.split(",")) {
if (!StringUtils.hasText(token)) {
continue;
}
try {
Long id = Long.valueOf(token.trim());
if (id > 0) {
result.add(id);
}
} catch (NumberFormatException ignored) {
// Ignore malformed legacy tokens.
}
}
return new ArrayList<>(new LinkedHashSet<>(result));
}
private List<String> resolveImageUrls(List<Long> imageFileIds) {
if (imageFileIds == null || imageFileIds.isEmpty()) {
return new ArrayList<>();
}
Map<Long, ObjectStorageFileVO> fileMap = objectStorageFileService.getObjectStorageFileMapByIds(new LinkedHashSet<>(imageFileIds));
List<String> urls = new ArrayList<>();
for (Long imageFileId : imageFileIds) {
ObjectStorageFileVO fileVO = fileMap.get(imageFileId);
if (fileVO == null || !StringUtils.hasText(fileVO.getFileUrl())) {
continue;
}
urls.add(objectStorageUrlSupport.toAccessibleUrl(fileVO));
}
return urls;
}
/**
* Run business method `activeQuery`.
* Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result.
* @return private com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper<CommentDO> result consumed by the caller or returned to the frontend
*/
private com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper<CommentDO> activeQuery() {
return Wrappers.lambdaQuery(CommentDO.class).eq(CommentDO::getIsDelete, 0);
}
/**
* Run business method `normalizeId`.
* Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result.
* @param id parameter `id` supplied by the caller
* @return private Long result consumed by the caller or returned to the frontend
*/
private Long normalizeId(Long id) {
return id == null || id <= 0 ? null : id;
}
/**
* Run business method `sanitizeContent`.
* Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result.
* @param content parameter `content` supplied by the caller
* @return private String result consumed by the caller or returned to the frontend
*/
private String sanitizeContent(String content) {
if (!StringUtils.hasText(content)) {
/**
* Run business method `RuntimeException`.
* Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result.
* @return throw new result consumed by the caller or returned to the frontend
*/
throw new RuntimeException("评论内容不能为空");
}
String sanitized = content.replaceAll("[\\p{Cntrl}&&[^\r\n\t]]", "").trim();
sanitized = sanitized.replaceAll("<[^>]*>", "");
if (!StringUtils.hasText(sanitized)) {
/**
* Run business method `RuntimeException`.
* Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result.
* @return throw new result consumed by the caller or returned to the frontend
*/
throw new RuntimeException("评论内容不能为空");
}
if (sanitized.length() > 300) {
/**
* Run business method `RuntimeException`.
* Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result.
* @return throw new result consumed by the caller or returned to the frontend
*/
throw new RuntimeException("评论最多输入 300 个字");
}
return sanitized;
}
}
@@ -0,0 +1,102 @@
package com.xiaowang.yuminailcore.modules.content.vo;
import lombok.Data;
import java.time.LocalDateTime;
import java.util.List;
/**
* 用户评论信息表 VO
* 用于前端展示评论信息
*
* @author xiaowang
* @date 2026-02-13
*/
@Data
public class CommentVO {
/**
* 评论唯一主键ID(雪花ID)
*/
private Long id;
/**
* 评论用户ID,关联用户表主键
*/
private Long userId;
/**
* 用户昵称
*/
private String userNickname;
/**
* 关联店铺表主键(0表示非店铺评论)
*/
private Long shopId;
/**
* 店铺名称
*/
private String shopName;
/**
* 关联商品表主键(0表示非商品评论)
*/
private Long productId;
/**
* 商品标题
*/
private String productTitle;
/**
* 评论内容
*/
private String commentContent;
/**
* 父级评论ID(0表示为根评论)
*/
private Long parentCommentId;
/**
* 父级评论内容
*/
private String parentCommentContent;
/**
* 评论点赞数
*/
private Integer likeCount;
/**
* 评论评分:1-5星
*/
private Integer ratingScore;
/**
* 评论图片文件ID集合
*/
private List<Long> imageFileIds;
/**
* 评论图片展示链接
*/
private List<String> imageUrls;
/**
* 评论创建时间
*/
private LocalDateTime createTime;
/**
* 评论更新时间
*/
private LocalDateTime updateTime;
/**
* 回复列表
*/
private List<CommentVO> replies;
}
@@ -0,0 +1,35 @@
package com.xiaowang.yuminailcore.modules.file.config;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import lombok.Data;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.StringUtils;
@Data
@Configuration
@ConfigurationProperties(prefix = "aliyun.oss")
public class AliyunOssConfig {
private boolean enabled = false;
private String endpoint;
private String region;
private String bucketName = "fingertipdesigner";
private String accessKeyId;
private String accessKeySecret;
private int signedUrlExpireMinutes = 30;
@Bean(destroyMethod = "shutdown")
@ConditionalOnProperty(prefix = "aliyun.oss", name = "enabled", havingValue = "true")
public OSS aliyunOssClient() {
if (!StringUtils.hasText(endpoint)
|| !StringUtils.hasText(accessKeyId)
|| !StringUtils.hasText(accessKeySecret)) {
throw new IllegalStateException("Aliyun OSS is enabled but endpoint/accessKeyId/accessKeySecret is incomplete");
}
return new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);
}
}
@@ -0,0 +1,84 @@
package com.xiaowang.yuminailcore.modules.file.controller.front;
import com.xiaowang.yuminailcore.common.Result;
import com.xiaowang.yuminailcore.modules.product.mapper.EffectDiagramMapper;
import com.xiaowang.yuminailcore.modules.product.mapper.ProductMapper;
import com.xiaowang.yuminailcore.modules.shop.mapper.ShopMapper;
import com.xiaowang.yuminailcore.modules.file.service.ObjectStorageFileService;
import com.xiaowang.yuminailcore.modules.file.support.ObjectStorageUrlSupport;
import com.xiaowang.yuminailcore.modules.file.vo.ObjectStorageFileVO;
import lombok.RequiredArgsConstructor;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
/**
* Purpose: FrontendFileController exposes signed-file access only for public frontend references.
* Usage: anonymous clients call /file/get-signed-url/{fileId}; the controller verifies the file is referenced by public content before returning a URL.
*/
@RestController
@RequestMapping("/file")
@RequiredArgsConstructor
public class FrontendFileController {
private final ObjectStorageFileService objectStorageFileService;
private final ObjectStorageUrlSupport objectStorageUrlSupport;
private final ProductMapper productMapper;
private final ShopMapper shopMapper;
private final EffectDiagramMapper effectDiagramMapper;
/**
* Purpose: getSignedUrl returns a short-lived URL for public image references, or the original external URL when it is already public.
* Usage: pass a public file id and optional expiry minutes; private or unreferenced files are rejected.
*/
@GetMapping("/get-signed-url/{fileId}")
public Result<String> getSignedUrl(@PathVariable Long fileId,
@RequestParam(defaultValue = "60") Integer expiryTimeInMinutes) {
try {
ObjectStorageFileVO fileVO = objectStorageFileService.getObjectStorageFileById(fileId);
if (fileVO == null) {
return Result.error("文件不存在");
}
if (!Integer.valueOf(1).equals(fileVO.getStatus()) || !isPublicFileReference(fileId)) {
return Result.error("文件不可公开访问");
}
String signedUrl = hasObjectStorageReference(fileVO)
? objectStorageUrlSupport.getSignedUrlOrThrow(fileVO, expiryTimeInMinutes)
: fileVO.getFileUrl();
return Result.success(signedUrl);
} catch (Exception e) {
e.printStackTrace();
return Result.error("获取签名链接失败: " + e.getMessage());
}
}
private boolean hasObjectStorageReference(ObjectStorageFileVO fileVO) {
return StringUtils.hasText(fileVO.getObjectName())
|| StringUtils.hasText(objectStorageUrlSupport.extractObjectName(fileVO.getMinioUrl()))
|| StringUtils.hasText(objectStorageUrlSupport.extractObjectName(fileVO.getFileUrl()));
}
/**
* Purpose: isPublicFileReference prevents arbitrary uploaded files from being exposed through the public signing endpoint.
* Usage: call with a file id and keep mapper checks in sync with public content tables.
*/
private boolean isPublicFileReference(Long fileId) {
if (fileId == null) {
return false;
}
return positive(productMapper.countPublicImageReference(fileId))
|| positive(shopMapper.countPublicImageReference(fileId))
|| positive(effectDiagramMapper.countPublicImageReference(fileId));
}
/**
* Purpose: positive normalizes nullable mapper counts.
* Usage: use for COUNT(*) results where null should behave like zero.
*/
private boolean positive(Long count) {
return count != null && count > 0;
}
}
@@ -0,0 +1,268 @@
package com.xiaowang.yuminailcore.modules.file.controller.front;
import com.xiaowang.yuminailcore.annotation.OperationGuard;
import com.xiaowang.yuminailcore.common.Result;
import com.xiaowang.yuminailcore.modules.file.dto.ChunkUploadCompleteRequestDTO;
import com.xiaowang.yuminailcore.modules.file.dto.ChunkUploadInitRequestDTO;
import com.xiaowang.yuminailcore.modules.file.dto.ObjectStorageFileDTO;
import com.xiaowang.yuminailcore.modules.file.service.ChunkUploadService;
import com.xiaowang.yuminailcore.modules.file.service.MinioService;
import com.xiaowang.yuminailcore.modules.file.service.ObjectStorageFileService;
import com.xiaowang.yuminailcore.modules.file.support.ObjectStorageUrlSupport;
import com.xiaowang.yuminailcore.support.id.TimeOrderedSnowflakeIdGenerator;
import com.xiaowang.yuminailcore.support.security.OperationGuardStrategy;
import com.xiaowang.yuminailcore.support.security.UploadSecurityValidator;
import com.xiaowang.yuminailcore.modules.file.vo.ChunkUploadSessionVO;
import com.xiaowang.yuminailcore.modules.file.vo.ObjectStorageFileVO;
import lombok.RequiredArgsConstructor;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.io.FileInputStream;
import java.util.List;
/**
* 对象存储文件控制器,对应表 t_object_storage_file。
*/
@RestController
@RequestMapping("/admin/object-storage-file")
@RequiredArgsConstructor
@Validated
public class ObjectStorageFileController {
/**
* Variable `objectStorageFileService`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls.
*/
private final ObjectStorageFileService objectStorageFileService;
/**
* Variable `minioService`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls.
*/
private final MinioService minioService;
/**
* Variable `chunkUploadService`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls.
*/
private final ChunkUploadService chunkUploadService;
/**
* Variable `objectStorageUrlSupport`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls.
*/
private final ObjectStorageUrlSupport objectStorageUrlSupport;
/**
* Variable `snowflakeIdGenerator`: Spring-injected collaborator used by this class to finish database access, validation, or downstream calls.
*/
private final TimeOrderedSnowflakeIdGenerator snowflakeIdGenerator;
/**
* Purpose: uploadSecurityValidator supports ObjectStorageFileController.java by holding or executing the upload security validator business role.
* Usage: reference this field from the owning layer and pass validated inputs before reading or updating related state.
*/
private final UploadSecurityValidator uploadSecurityValidator;
@PostMapping("/upload/init")
@OperationGuard(action = "admin-upload-init", ttlSeconds = 10, message = "上传处理中,请勿重复操作")
public Result<ChunkUploadSessionVO> initChunkUpload(HttpServletRequest request,
@Valid @RequestBody ChunkUploadInitRequestDTO requestDTO) {
Long userId = (Long) request.getAttribute("userId");
uploadSecurityValidator.validateMetadata(requestDTO.getFileName(), requestDTO.getContentType(), requestDTO.getFileSize());
return Result.success(chunkUploadService.initAdminObjectStorageUpload(userId, requestDTO));
}
@PostMapping("/upload/chunk")
@OperationGuard(action = "admin-upload-chunk", strategy = OperationGuardStrategy.NOOP_IF_DUPLICATE, ttlSeconds = 20)
public Result<Boolean> uploadChunk(HttpServletRequest request,
@RequestParam("uploadId") String uploadId,
@RequestParam("chunkIndex") Integer chunkIndex,
@RequestParam("totalChunks") Integer totalChunks,
@RequestParam("chunk") MultipartFile chunkFile) {
Long userId = (Long) request.getAttribute("userId");
uploadSecurityValidator.validateChunk(chunkFile);
chunkUploadService.uploadAdminObjectStorageChunk(userId, uploadId, chunkIndex, totalChunks, chunkFile);
return Result.success(true);
}
@PostMapping("/upload/complete")
@OperationGuard(action = "admin-upload-complete", ttlSeconds = 30, message = "上传处理中,请勿重复操作")
public Result<ObjectStorageFileVO> completeChunkUpload(HttpServletRequest request,
@Valid @RequestBody ChunkUploadCompleteRequestDTO requestDTO) {
Long userId = (Long) request.getAttribute("userId");
try (ChunkUploadService.PreparedUploadFile preparedUploadFile =
chunkUploadService.prepareAdminObjectStorageFile(userId, requestDTO.getUploadId());
FileInputStream inputStream = new FileInputStream(preparedUploadFile.getFile())) {
String originalFilename = preparedUploadFile.getFileName();
String fileExtension = originalFilename.substring(originalFilename.lastIndexOf("."));
String objectName = snowflakeIdGenerator.nextIdString() + fileExtension;
String fileUrl = minioService.uploadStream(
inputStream,
preparedUploadFile.getFileSize(),
preparedUploadFile.getContentType(),
objectName
);
ObjectStorageFileDTO dto = new ObjectStorageFileDTO();
dto.setFileName(originalFilename);
dto.setFileUrl(fileUrl);
dto.setObjectName(objectName);
dto.setMinioUrl(fileUrl);
dto.setContentType(preparedUploadFile.getContentType());
dto.setFileSize(preparedUploadFile.getFileSize());
dto.setMinioUploadStatus(1);
dto.setOssUploadStatus(0);
dto.setOssRetryCount(0);
dto.setStatus(1);
Long fileId = objectStorageFileService.createObjectStorageFile(dto);
chunkUploadService.clearAdminObjectStorageUpload(userId, requestDTO.getUploadId());
return Result.success(objectStorageFileService.getObjectStorageFileById(fileId));
} catch (Exception e) {
e.printStackTrace();
return Result.error("文件上传失败: " + e.getMessage());
}
}
@DeleteMapping("/upload/{uploadId}")
@OperationGuard(action = "admin-upload-cancel", ttlSeconds = 30, message = "上传处理中,请勿重复操作")
/**
* Run business method `cancelChunkUpload`.
* Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result.
* @param request parameter `request` supplied by the caller
* @param uploadId parameter `uploadId` supplied by the caller
* @return Result<Boolean> result consumed by the caller or returned to the frontend
*/
public Result<Boolean> cancelChunkUpload(HttpServletRequest request, @PathVariable String uploadId) {
Long userId = (Long) request.getAttribute("userId");
chunkUploadService.clearAdminObjectStorageUpload(userId, uploadId);
return Result.success(true);
}
/**
* 上传文件。
*/
@PostMapping("/upload")
@OperationGuard(action = "admin-upload-direct", ttlSeconds = 30, message = "上传处理中,请勿重复操作")
public Result<ObjectStorageFileVO> uploadFile(@RequestParam("file") MultipartFile file) {
try {
uploadSecurityValidator.validate(file);
String originalFilename = file.getOriginalFilename();
String fileExtension = originalFilename.substring(originalFilename.lastIndexOf("."));
String objectName = snowflakeIdGenerator.nextIdString() + fileExtension;
String fileUrl = minioService.uploadFile(file, objectName);
ObjectStorageFileDTO dto = new ObjectStorageFileDTO();
dto.setFileName(originalFilename);
dto.setFileUrl(fileUrl);
dto.setObjectName(objectName);
dto.setMinioUrl(fileUrl);
dto.setContentType(file.getContentType());
dto.setFileSize(file.getSize());
dto.setMinioUploadStatus(1);
dto.setOssUploadStatus(0);
dto.setOssRetryCount(0);
dto.setStatus(1);
Long fileId = objectStorageFileService.createObjectStorageFile(dto);
return Result.success(objectStorageFileService.getObjectStorageFileById(fileId));
} catch (Exception e) {
e.printStackTrace();
return Result.error("文件上传失败: " + e.getMessage());
}
}
/**
* 获取带签名的图片链接。
*/
@GetMapping("/get-signed-url/{fileId}")
public Result<String> getSignedUrl(@PathVariable Long fileId,
@RequestParam(defaultValue = "60") Integer expiryTimeInMinutes) {
try {
ObjectStorageFileVO fileVO = objectStorageFileService.getObjectStorageFileById(fileId);
if (fileVO == null) {
return Result.error("文件不存在");
}
String signedUrl = objectStorageUrlSupport.getSignedUrlOrThrow(fileVO, expiryTimeInMinutes);
return Result.success(signedUrl);
} catch (Exception e) {
e.printStackTrace();
return Result.error("获取签名链接失败: " + e.getMessage());
}
}
@PostMapping("/create")
@OperationGuard(action = "admin-file-create", ttlSeconds = 10, message = "保存处理中,请勿重复提交")
/**
* Create a new record.
* Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result.
* @param objectStorageFileDTO parameter `objectStorageFileDTO` supplied by the caller
* @return Result<Long> result consumed by the caller or returned to the frontend
*/
public Result<Long> createObjectStorageFile(@RequestBody ObjectStorageFileDTO objectStorageFileDTO) {
Long id = objectStorageFileService.createObjectStorageFile(objectStorageFileDTO);
return Result.success(id);
}
@PutMapping("/update/{id}")
@OperationGuard(action = "admin-file-update", ttlSeconds = 10, message = "保存处理中,请勿重复提交")
public Result<Boolean> updateObjectStorageFile(@PathVariable Long id,
@RequestBody ObjectStorageFileDTO objectStorageFileDTO) {
boolean success = objectStorageFileService.updateObjectStorageFile(id, objectStorageFileDTO);
return Result.success(success);
}
@DeleteMapping("/delete/{id}")
@OperationGuard(action = "admin-file-delete", ttlSeconds = 10, message = "操作处理中,请勿重复提交")
/**
* Delete, revoke, or logically remove a record.
* Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result.
* @param id parameter `id` supplied by the caller
* @return Result<Boolean> result consumed by the caller or returned to the frontend
*/
public Result<Boolean> deleteObjectStorageFile(@PathVariable Long id) {
boolean success = objectStorageFileService.deleteObjectStorageFile(id);
return Result.success(success);
}
@GetMapping("/get/{id}")
/**
* Load data by the supplied parameter.
* Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result.
* @param id parameter `id` supplied by the caller
* @return Result<ObjectStorageFileVO> result consumed by the caller or returned to the frontend
*/
public Result<ObjectStorageFileVO> getObjectStorageFileById(@PathVariable Long id) {
ObjectStorageFileVO objectStorageFileVO = objectStorageFileService.getObjectStorageFileById(id);
return Result.success(objectStorageFileVO);
}
@GetMapping("/list/all")
/**
* List records for the current query or current user scope.
* Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result.
* @return Result<List<ObjectStorageFileVO>> result consumed by the caller or returned to the frontend
*/
public Result<List<ObjectStorageFileVO>> listAllObjectStorageFiles() {
List<ObjectStorageFileVO> objectStorageFileVOs = objectStorageFileService.listAllObjectStorageFiles();
return Result.success(objectStorageFileVOs);
}
@GetMapping("/list/status/{status}")
/**
* List records for the current query or current user scope.
* Call guide: pass the named parameters below from the controller or caller; the method validates them and returns the business result.
* @param status parameter `status` supplied by the caller
* @return Result<List<ObjectStorageFileVO>> result consumed by the caller or returned to the frontend
*/
public Result<List<ObjectStorageFileVO>> listObjectStorageFilesByStatus(@PathVariable Integer status) {
List<ObjectStorageFileVO> objectStorageFileVOs = objectStorageFileService.listObjectStorageFilesByStatus(status);
return Result.success(objectStorageFileVOs);
}
}
@@ -0,0 +1,18 @@
package com.xiaowang.yuminailcore.modules.file.dto;
import lombok.Data;
import javax.validation.constraints.NotBlank;
/**
* 分片上传完成请求
*/
@Data
public class ChunkUploadCompleteRequestDTO {
@NotBlank(message = "上传标识不能为空")
/**
* Field `uploadId` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled.
*/
private String uploadId;
}
@@ -0,0 +1,45 @@
package com.xiaowang.yuminailcore.modules.file.dto;
import lombok.Data;
import javax.validation.constraints.Min;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull;
/**
* 分片上传初始化请求
*/
@Data
public class ChunkUploadInitRequestDTO {
@NotBlank(message = "文件名不能为空")
/**
* Field `fileName` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled.
*/
private String fileName;
@NotNull(message = "文件大小不能为空")
@Min(value = 1, message = "文件大小不合法")
/**
* Field `fileSize` (Long): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled.
*/
private Long fileSize;
@NotBlank(message = "文件类型不能为空")
/**
* Field `contentType` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled.
*/
private String contentType;
@NotBlank(message = "文件指纹不能为空")
/**
* Field `fileFingerprint` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled.
*/
private String fileFingerprint;
@NotBlank(message = "上传场景不能为空")
/**
* Field `scene` (String): data variable carried by this DTO/VO/entity. Check controller/service usage to see when it is filled.
*/
private String scene;
}
@@ -0,0 +1,63 @@
package com.xiaowang.yuminailcore.modules.file.dto;
import lombok.Data;
import java.time.LocalDateTime;
/**
* 对象存储文件信息表 DTO
* 用于文件信息的传输
*
* @author xiaowang
* @date 2026-02-13
*/
@Data
public class ObjectStorageFileDTO {
/**
* 文件名称
*/
private String fileName;
/**
* 文件访问链接
*/
private String fileUrl;
private String objectName;
private String minioUrl;
private String ossUrl;
private String contentType;
private Long fileSize;
private Integer minioUploadStatus;
private Integer ossUploadStatus;
private Integer ossRetryCount;
private String ossLastError;
private LocalDateTime ossUploadedAt;
private LocalDateTime ossLastRetryTime;
/**
* 文件状态:1-可用,0-不可用,2-回收站
*/
private Integer status;
/**
* 文件删除时间(NULL表示未删除)
*/
private LocalDateTime deleteTime;
/**
* 文件移入回收站时间(NULL表示未移入)
*/
private LocalDateTime recycleTime;
}

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