Commit 6a0e3330 by 叶立庆

初始化项目

0 parents
Showing 131 changed files with 4760 additions and 0 deletions
target/
!.mvn/wrapper/maven-wrapper.jar
*.class
*.jar
*.war
*.log
logs/
.idea/
*.iml
.vscode/
.DS_Store
# 接口签名密钥(本地自动生成,严禁入库)
keys/
*.pem
This diff is collapsed. Click to expand it.
<?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>3.3.4</version>
<relativePath/>
</parent>
<groupId>com.youjia</groupId>
<artifactId>YouJia</artifactId>
<version>1.0.0-SNAPSHOT</version>
<packaging>pom</packaging>
<name>YouJia</name>
<description>优加门店上架系统</description>
<properties>
<java.version>17</java.version>
<maven.compiler.source>17</maven.compiler.source>
<maven.compiler.target>17</maven.compiler.target>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<spring-boot.version>3.3.4</spring-boot.version>
<spring-cloud-alibaba.version>2023.0.1.0</spring-cloud-alibaba.version>
<mybatis-plus.version>3.5.17</mybatis-plus.version>
<easyexcel.version>3.3.2</easyexcel.version>
<knife4j.version>4.3.0</knife4j.version>
<lombok.version>1.18.34</lombok.version>
<swagger-annotations.version>2.2.22</swagger-annotations.version>
<!-- knife4j 4.3.0 内置 springdoc 2.2.x,与 Spring Boot 3.3.x 不兼容(ControllerAdviceBean 构造器变更),
这里统一抬到 2.6.0(springdoc 官方支持 Spring Boot 3.3 的最低版本) -->
<springdoc.version>2.6.0</springdoc.version>
<revision>1.0.0-SNAPSHOT</revision>
</properties>
<modules>
<module>youjia-common</module>
<module>youjia-framework</module>
<module>youjia-module-system</module>
<module>youjia-module-store</module>
<module>youjia-server</module>
</modules>
<dependencyManagement>
<dependencies>
<!-- Spring Cloud Alibaba -->
<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>
<!-- springdoc 版本对齐(见 properties 说明) -->
<dependency>
<groupId>org.springdoc</groupId>
<artifactId>springdoc-openapi-starter-webmvc-ui</artifactId>
<version>${springdoc.version}</version>
</dependency>
<dependency>
<groupId>org.springdoc</groupId>
<artifactId>springdoc-openapi-starter-common</artifactId>
<version>${springdoc.version}</version>
</dependency>
<!-- 三方组件 -->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-spring-boot3-starter</artifactId>
<version>${mybatis-plus.version}</version>
</dependency>
<!-- MyBatis-Plus 3.5.9+ 将 JSqlParser 拆出,分页 / 防全表更新插件需要显式引入 -->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-jsqlparser</artifactId>
<version>${mybatis-plus.version}</version>
</dependency>
<!-- MyBatis-Plus 3.5.9+ 的 mybatis-plus 聚合包不再包含 extension,IService / ServiceImpl 需显式引入 -->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-extension</artifactId>
<version>${mybatis-plus.version}</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>easyexcel</artifactId>
<version>${easyexcel.version}</version>
</dependency>
<dependency>
<groupId>com.github.xiaoymin</groupId>
<artifactId>knife4j-openapi3-jakarta-spring-boot-starter</artifactId>
<version>${knife4j.version}</version>
</dependency>
<dependency>
<groupId>io.swagger.core.v3</groupId>
<artifactId>swagger-annotations-jakarta</artifactId>
<version>${swagger-annotations.version}</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>${lombok.version}</version>
</dependency>
<!-- 本项目内部模块 -->
<dependency>
<groupId>com.youjia</groupId>
<artifactId>youjia-common</artifactId>
<version>${revision}</version>
</dependency>
<dependency>
<groupId>com.youjia</groupId>
<artifactId>youjia-framework</artifactId>
<version>${revision}</version>
</dependency>
<dependency>
<groupId>com.youjia</groupId>
<artifactId>youjia-module-system</artifactId>
<version>${revision}</version>
</dependency>
<dependency>
<groupId>com.youjia</groupId>
<artifactId>youjia-module-store</artifactId>
<version>${revision}</version>
</dependency>
</dependencies>
</dependencyManagement>
<build>
<pluginManagement>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<parameters>true</parameters>
<encoding>UTF-8</encoding>
<annotationProcessorPaths>
<path>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>${lombok.version}</version>
</path>
</annotationProcessorPaths>
</configuration>
</plugin>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<mainClass>com.youjia.YouJiaApplication</mainClass>
<excludes>
<exclude>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
</exclude>
</excludes>
</configuration>
</plugin>
</plugins>
</pluginManagement>
</build>
</project>
-- ============================================================================
-- 优加门店上架系统 · 初始化数据(组织 / 内置角色 / 菜单权限 / 超级管理员)
-- 目标库:yj_service
-- 说明:请在 01_schema.sql 之后执行;脚本按显式主键写入,仅在首次初始化时执行一次
-- ============================================================================
SET NAMES utf8mb4;
-- ---------------------------------------------------------------------------
-- 1. 组织(优加主体为根节点)
-- ---------------------------------------------------------------------------
INSERT INTO `sys_org` (`org_id`, `parent_id`, `org_name`, `org_code`, `level`, `path`, `sort`, `status`, `create_time`, `update_time`) VALUES
(1, 0, '优加主体', 'YJ_ROOT', 1, '/1/', 1, 1, NOW(), NOW()),
(2, 1, '线上运营部', 'YJ_OPS', 2, '/1/2/', 1, 1, NOW(), NOW()),
(3, 1, '财务部', 'YJ_FINANCE', 2, '/1/3/', 2, 1, NOW(), NOW());
-- ---------------------------------------------------------------------------
-- 2. 内置角色
-- ---------------------------------------------------------------------------
INSERT INTO `sys_role` (`role_id`, `role_code`, `role_name`, `description`, `is_builtin`, `default_data_scope`, `sort`, `status`, `create_time`, `update_time`) VALUES
(1, 'SYS_ADMIN', '超级管理员', '全部菜单 + 全部操作,含系统设置(角色管理 / 账号管理)', 1, 1, 1, 1, NOW(), NOW()),
(2, 'YJ_FINANCE_MGR', '优加财务经理', '门店审批(通过 / 打回 / 批量审批)、门店列表查看与导出', 1, 1, 2, 1, NOW(), NOW()),
(3, 'ONLINE_OPS', '线上运营', '导入门店信息、门店列表查看;无审批权', 1, 3, 3, 1, NOW(), NOW()),
(4, 'OPS_LEADER', '运营主管', '线上运营全部权限 + 门店列表导出', 1, 2, 4, 1, NOW(), NOW()),
(5, 'VIEWER', '只读观察者', '门店列表只读查看,无导出', 1, 3, 5, 1, NOW(), NOW());
-- ---------------------------------------------------------------------------
-- 3. 菜单 / 权限(权限码规范:模块:功能:操作)
-- ---------------------------------------------------------------------------
INSERT INTO `sys_menu` (`menu_id`, `parent_id`, `menu_name`, `menu_type`, `perm_code`, `product`, `route`, `sort`, `visible`, `status`, `create_time`, `update_time`) VALUES
(1, 0, '门店上架', 1, NULL, '门店上架', NULL, 1, 1, 1, NOW(), NOW()),
(2, 1, '导入门店信息', 2, 'store:import:view', '门店上架', '/store/import', 1, 1, 1, NOW(), NOW()),
(3, 2, '下载导入模板', 3, 'store:import:template', '门店上架', NULL, 1, 1, 1, NOW(), NOW()),
(4, 2, '上传文件并校验', 3, 'store:import:upload', '门店上架', NULL, 2, 1, 1, NOW(), NOW()),
(5, 2, '确认并提交审批', 3, 'store:import:submit', '门店上架', NULL, 3, 1, 1, NOW(), NOW()),
(6, 1, '门店审批', 2, 'store:approve:view', '门店上架', '/store/approval', 2, 1, 1, NOW(), NOW()),
(7, 6, '审批通过', 3, 'store:approve:pass', '门店上架', NULL, 1, 1, 1, NOW(), NOW()),
(8, 6, '审批打回', 3, 'store:approve:reject', '门店上架', NULL, 2, 1, 1, NOW(), NOW()),
(9, 1, '门店列表', 2, 'store:list:view', '门店上架', '/store/listing', 3, 1, 1, NOW(), NOW()),
(10, 9, '导出门店数据', 3, 'store:list:export', '门店上架', NULL, 1, 1, 1, NOW(), NOW()),
(11, 0, '系统设置', 1, NULL, '系统设置', NULL, 2, 1, 1, NOW(), NOW()),
(12, 11, '角色管理', 2, 'system:role:view', '系统设置', '/system/role', 1, 1, 1, NOW(), NOW()),
(13, 12, '新增 / 编辑角色', 3, 'system:role:save', '系统设置', NULL, 1, 1, 1, NOW(), NOW()),
(14, 12, '配置菜单可见范围', 3, 'system:role:menu', '系统设置', NULL, 2, 1, 1, NOW(), NOW()),
(15, 11, '账号管理', 2, 'system:user:view', '系统设置', '/system/user', 2, 1, 1, NOW(), NOW()),
(16, 15, '新增 / 编辑账号', 3, 'system:user:save', '系统设置', NULL, 1, 1, 1, NOW(), NOW()),
(17, 15, '重置密码', 3, 'system:user:reset', '系统设置', NULL, 2, 1, 1, NOW(), NOW()),
(18, 15, '启用 / 停用账号', 3, 'system:user:status', '系统设置', NULL, 3, 1, 1, NOW(), NOW());
-- ---------------------------------------------------------------------------
-- 4. 角色-权限(权限矩阵初始值)
-- ---------------------------------------------------------------------------
-- 超级管理员:全部菜单
INSERT INTO `sys_role_menu` (`role_id`, `menu_id`, `create_time`, `update_time`)
SELECT 1, `menu_id`, NOW(), NOW() FROM `sys_menu`;
-- 优加财务经理:门店审批(含按钮)+ 门店列表(含导出)
INSERT INTO `sys_role_menu` (`role_id`, `menu_id`, `create_time`, `update_time`) VALUES
(2, 1, NOW(), NOW()), (2, 6, NOW(), NOW()), (2, 7, NOW(), NOW()), (2, 8, NOW(), NOW()),
(2, 9, NOW(), NOW()), (2, 10, NOW(), NOW());
-- 线上运营:导入门店信息(含按钮)+ 门店列表查看(无导出、无审批)
INSERT INTO `sys_role_menu` (`role_id`, `menu_id`, `create_time`, `update_time`) VALUES
(3, 1, NOW(), NOW()), (3, 2, NOW(), NOW()), (3, 3, NOW(), NOW()), (3, 4, NOW(), NOW()),
(3, 5, NOW(), NOW()), (3, 9, NOW(), NOW());
-- 运营主管:线上运营全部权限 + 门店列表导出
INSERT INTO `sys_role_menu` (`role_id`, `menu_id`, `create_time`, `update_time`) VALUES
(4, 1, NOW(), NOW()), (4, 2, NOW(), NOW()), (4, 3, NOW(), NOW()), (4, 4, NOW(), NOW()),
(4, 5, NOW(), NOW()), (4, 9, NOW(), NOW()), (4, 10, NOW(), NOW());
-- 只读观察者:门店列表只读,无导出
INSERT INTO `sys_role_menu` (`role_id`, `menu_id`, `create_time`, `update_time`) VALUES
(5, 1, NOW(), NOW()), (5, 9, NOW(), NOW());
-- ---------------------------------------------------------------------------
-- 5. 超级管理员账号
-- 初始密码:YouJia@123(BCrypt 密文);首次登录须强制修改
-- 如需调整,请通过 .env / 启动参数注入后使用接口重置密码
-- ---------------------------------------------------------------------------
INSERT INTO `sys_user` (`user_id`, `account`, `password`, `name`, `org_id`, `data_scope`, `status`, `remark`, `create_time`, `update_time`) VALUES
(1, 'admin', '$2b$10$CJ7qf35MiMZolY5Mjsy9l.gZ7SK6wZ4WjDAkxYMZhNSaEgX.dH0y2', '系统管理员', 1, 1, 1, '系统内置超级管理员,请首次登录后立即修改密码', NOW(), NOW());
INSERT INTO `sys_user_role` (`user_id`, `role_id`, `create_time`, `update_time`) VALUES
(1, 1, NOW(), NOW());
<?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>com.youjia</groupId>
<artifactId>YouJia</artifactId>
<version>1.0.0-SNAPSHOT</version>
</parent>
<artifactId>youjia-common</artifactId>
<name>youjia-common</name>
<description>通用基础模块:统一响应、业务异常、基础实体、业务枚举与常量</description>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>
<!-- 基础实体上的 Jackson 注解 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-json</artifactId>
</dependency>
<!-- MyBatis-Plus:基础实体注解 + IService / ServiceImpl 通用 CRUD 能力 -->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-spring-boot3-starter</artifactId>
</dependency>
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-extension</artifactId>
</dependency>
<dependency>
<groupId>io.swagger.core.v3</groupId>
<artifactId>swagger-annotations-jakarta</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
</dependencies>
</project>
package com.youjia.common.constant;
/**
* 全局通用常量。
*/
public final class CommonConstants {
private CommonConstants() {
}
/** 逻辑删除:未删除 */
public static final int NOT_DELETED = 0;
/** 逻辑删除:已删除 */
public static final int DELETED = 1;
/** 启用 */
public static final int STATUS_ENABLED = 1;
/** 停用 */
public static final int STATUS_DISABLED = 0;
/** 是否:是 */
public static final int YES = 1;
/** 是否:否 */
public static final int NO = 0;
/** 组织根节点 ID */
public static final long ROOT_ORG_ID = 1L;
/** 超级管理员角色编码 */
public static final String ROLE_SYS_ADMIN = "SYS_ADMIN";
/** 优加财务经理角色编码 */
public static final String ROLE_YJ_FINANCE_MGR = "YJ_FINANCE_MGR";
/** 线上运营角色编码 */
public static final String ROLE_ONLINE_OPS = "ONLINE_OPS";
/** 运营主管角色编码 */
public static final String ROLE_OPS_LEADER = "OPS_LEADER";
/** 只读观察者角色编码 */
public static final String ROLE_VIEWER = "VIEWER";
/** 毫秒时间戳请求头 */
public static final String HEADER_TIMESTAMP = "X-Timestamp";
/** 当前登录人透传头(网关 / 上游鉴权域透传) */
public static final String HEADER_USER_ID = "X-User-Id";
/** 当前登录人组织透传头 */
public static final String HEADER_ORG_ID = "X-Org-Id";
}
package com.youjia.common.core;
import io.swagger.v3.oas.annotations.media.Schema;
import jakarta.validation.constraints.Max;
import jakarta.validation.constraints.Min;
import lombok.Data;
import java.io.Serial;
import java.io.Serializable;
/**
* 分页请求基类。
*/
@Data
public class PageQuery implements Serializable {
@Serial
private static final long serialVersionUID = 1L;
@Schema(description = "页码,从 1 开始", defaultValue = "1")
@Min(value = 1, message = "页码不能小于 1")
private Long current = 1L;
@Schema(description = "每页条数", defaultValue = "20")
@Min(value = 1, message = "每页条数不能小于 1")
@Max(value = 200, message = "每页条数不能大于 200")
private Long size = 20L;
}
package com.youjia.common.core;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;
import java.io.Serial;
import java.io.Serializable;
import java.util.Collections;
import java.util.List;
/**
* 分页结果包装。
*
* @param <T> 列表元素类型
*/
@Data
@Schema(description = "分页结果")
public class PageResult<T> implements Serializable {
@Serial
private static final long serialVersionUID = 1L;
@Schema(description = "当前页数据")
private List<T> records = Collections.emptyList();
@Schema(description = "总记录数")
private Long total = 0L;
@Schema(description = "当前页码")
private Long current = 1L;
@Schema(description = "每页条数")
private Long size = 20L;
@Schema(description = "总页数")
private Long pages = 0L;
public static <T> PageResult<T> empty() {
return new PageResult<>();
}
public static <T> PageResult<T> of(List<T> records, Long total, Long current, Long size) {
PageResult<T> result = new PageResult<>();
result.setRecords(records == null ? Collections.emptyList() : records);
result.setTotal(total == null ? 0L : total);
result.setCurrent(current);
result.setSize(size);
if (size != null && size > 0) {
result.setPages((result.getTotal() + size - 1) / size);
}
return result;
}
}
package com.youjia.common.core;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;
import java.io.Serial;
import java.io.Serializable;
/**
* 统一响应结果。
*
* @param <T> 业务数据类型
*/
@Data
@Schema(description = "统一响应结果")
public class Result<T> implements Serializable {
@Serial
private static final long serialVersionUID = 1L;
@Schema(description = "业务状态码,200 表示成功")
private Integer code;
@Schema(description = "提示信息")
private String message;
@Schema(description = "业务数据")
private T data;
@Schema(description = "服务端时间戳(毫秒)")
private Long timestamp;
public Result() {
this.timestamp = System.currentTimeMillis();
}
public static <T> Result<T> success() {
return build(ResultCode.SUCCESS.getCode(), ResultCode.SUCCESS.getMessage(), null);
}
public static <T> Result<T> success(T data) {
return build(ResultCode.SUCCESS.getCode(), ResultCode.SUCCESS.getMessage(), data);
}
public static <T> Result<T> success(String message, T data) {
return build(ResultCode.SUCCESS.getCode(), message, data);
}
public static <T> Result<T> fail(String message) {
return build(ResultCode.FAIL.getCode(), message, null);
}
public static <T> Result<T> fail(ResultCode resultCode) {
return build(resultCode.getCode(), resultCode.getMessage(), null);
}
public static <T> Result<T> fail(ResultCode resultCode, String message) {
return build(resultCode.getCode(), message, null);
}
public static <T> Result<T> build(Integer code, String message, T data) {
Result<T> result = new Result<>();
result.setCode(code);
result.setMessage(message);
result.setData(data);
return result;
}
public boolean isSuccess() {
return ResultCode.SUCCESS.getCode().equals(this.code);
}
}
package com.youjia.common.core;
import lombok.Getter;
/**
* 业务状态码。
*
* <p>1xxxx 通用 / 2xxxx 系统设置 / 3xxxx 门店上架 / 4xxxx 外部依赖。</p>
*/
@Getter
public enum ResultCode {
SUCCESS(200, "操作成功"),
FAIL(500, "操作失败"),
/* ---------------- 通用 ---------------- */
PARAM_INVALID(10001, "请求参数不合法"),
UNAUTHORIZED(10002, "未登录或登录已过期"),
FORBIDDEN(10003, "无权访问该资源"),
DATA_NOT_FOUND(10004, "数据不存在"),
DATA_DUPLICATE(10005, "数据已存在"),
OPERATION_NOT_ALLOWED(10006, "当前状态不允许该操作"),
/* ---------------- 接口签名(前后端 RSA 非对称加签) ---------------- */
SIGN_MISSING(10010, "请求缺少签名信息,请检查签名请求头"),
SIGN_INVALID(10011, "请求签名校验失败"),
SIGN_EXPIRED(10012, "请求已过期,请校准客户端时间后重试"),
SIGN_REPLAY(10013, "请求已被处理,请勿重复提交"),
SIGN_ALGORITHM_UNSUPPORTED(10014, "不支持的签名算法"),
SIGN_KEY_NOT_CONFIGURED(10015, "服务端签名密钥未配置"),
/* ---------------- 系统设置 ---------------- */
USER_NOT_FOUND(20001, "账号不存在"),
USER_DISABLED(20002, "账号已停用"),
USER_PASSWORD_ERROR(20003, "账号或密码错误"),
USER_ACCOUNT_LOCKED(20004, "账号已锁定,请稍后再试"),
USER_ACCOUNT_EXISTS(20005, "账号已存在"),
ROLE_CODE_EXISTS(20006, "角色编码已存在"),
ROLE_BUILTIN_PROTECTED(20007, "内置角色不允许修改或删除"),
CANNOT_OPERATE_SELF(20008, "不允许对当前登录账号执行该操作"),
/* ---------------- 门店上架 ---------------- */
STORE_TEMPLATE_VERSION_MISMATCH(30001, "模板版本不匹配,请重新下载最新模板"),
STORE_IMPORT_FILE_INVALID(30002, "导入文件不合法"),
STORE_IMPORT_HEADER_INVALID(30003, "导入模板表头与系统模板不一致"),
STORE_IMPORT_ALL_FAILED(30004, "全部数据校验失败,无法进入下一步"),
STORE_LISTING_NOT_FOUND(30005, "门店上架记录不存在"),
STORE_LISTING_STATUS_ILLEGAL(30006, "门店上架记录状态不允许该操作"),
STORE_DUPLICATE_LISTING(30007, "该门店该业务场景已存在生效记录"),
STORE_OPER_COST_INCONSISTENT(30008, "同一门店的运营成本字段必须保持一致"),
/* ---------------- 外部依赖 ---------------- */
WECom_PUSH_FAILED(40001, "企业微信通知推送失败"),
REMOTE_CALL_FAILED(40002, "远程调用失败");
private final Integer code;
private final String message;
ResultCode(Integer code, String message) {
this.code = code;
this.message = message;
}
}
package com.youjia.common.entity;
import com.baomidou.mybatisplus.annotation.FieldFill;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableLogic;
import com.fasterxml.jackson.annotation.JsonIgnore;
import lombok.Data;
import java.io.Serial;
import java.io.Serializable;
import java.time.LocalDateTime;
/**
* 基础实体:审计字段 + 逻辑删除。
*
* <p>全库统一使用 is_deleted 逻辑删除,禁止物理删除业务数据。</p>
*/
@Data
public class BaseEntity implements Serializable {
@Serial
private static final long serialVersionUID = 1L;
@TableField(value = "create_by", fill = FieldFill.INSERT)
private Long createBy;
@TableField(value = "create_time", fill = FieldFill.INSERT)
private LocalDateTime createTime;
@TableField(value = "update_by", fill = FieldFill.INSERT_UPDATE)
private Long updateBy;
@TableField(value = "update_time", fill = FieldFill.INSERT_UPDATE)
private LocalDateTime updateTime;
/** 逻辑删除标记:0-未删除,1-已删除 */
@JsonIgnore
@TableLogic
@TableField(value = "is_deleted", select = false)
private Integer isDeleted;
}
package com.youjia.common.enums;
import lombok.Getter;
/**
* 审批动作(用于审批留痕)。
*/
@Getter
public enum ApprovalActionEnum {
SUBMIT("提交审批"),
PASS("审批通过"),
REJECT("审批打回"),
REVOKE("撤回"),
RESUBMIT("重新提交"),
VOID("作废"),
BATCH_PASS("批量通过");
private final String label;
ApprovalActionEnum(String label) {
this.label = label;
}
}
package com.youjia.common.enums;
import lombok.Getter;
import java.util.Arrays;
import java.util.Optional;
/**
* 业务场景字典(门店上架唯一项之一)。
*/
@Getter
public enum BusinessSceneEnum {
AFTER_SALE_MEMBER("售后会员权益升级"),
PRE_SALE_EXTENDED_WARRANTY("售前延保");
private final String label;
BusinessSceneEnum(String label) {
this.label = label;
}
public static Optional<BusinessSceneEnum> ofLabel(String label) {
return Arrays.stream(values()).filter(e -> e.label.equals(label)).findFirst();
}
public static boolean isValid(String label) {
return ofLabel(label).isPresent();
}
}
package com.youjia.common.enums;
import lombok.Getter;
import java.util.Arrays;
import java.util.Optional;
/**
* 计算模式字典。
*/
@Getter
public enum CalcModeEnum {
BY_CATEGORY("按品类计算"),
BY_ORDER("按整单计算");
private final String label;
CalcModeEnum(String label) {
this.label = label;
}
public static Optional<CalcModeEnum> ofLabel(String label) {
return Arrays.stream(values()).filter(e -> e.label.equals(label)).findFirst();
}
public static boolean isValid(String label) {
return ofLabel(label).isPresent();
}
}
package com.youjia.common.enums;
import lombok.Getter;
import java.util.Arrays;
import java.util.Optional;
/**
* 计算方式字典。区分「比例类」与「金额类」,决定导入数值列的取值口径。
*/
@Getter
public enum CalcWayEnum {
REVENUE("收入", ValueType.RATIO),
GROSS_PROFIT("毛利", ValueType.RATIO),
FIXED("固定", ValueType.AMOUNT),
FIXED_BY_PURCHASE_AMOUNT("固定*购买金额", ValueType.AMOUNT),
PARK_TOTAL_AMOUNT("园区店总金额", ValueType.RATIO),
PARK_GROSS_PROFIT_EXCLUDE_COST("园区店毛利(不扣除产品成本)", ValueType.RATIO),
PARK_GROSS_PROFIT("园区店毛利", ValueType.RATIO),
REVENUE_MINUS_OTHER("收入-其他费用", ValueType.RATIO),
REVENUE_MINUS_CUSTOM_OTHER("收入-自定义其他费用", ValueType.RATIO);
private final String label;
private final ValueType valueType;
CalcWayEnum(String label, ValueType valueType) {
this.label = label;
this.valueType = valueType;
}
public static Optional<CalcWayEnum> ofLabel(String label) {
return Arrays.stream(values()).filter(e -> e.label.equals(label)).findFirst();
}
public static boolean isValid(String label) {
return ofLabel(label).isPresent();
}
/**
* 数值列口径。
*/
public enum ValueType {
/** 比例:0 - 100,最多 2 位小数 */
RATIO,
/** 金额:>= 0,最多 2 位小数 */
AMOUNT
}
}
package com.youjia.common.enums;
import lombok.Getter;
import java.util.Arrays;
import java.util.Optional;
/**
* 组织数据域(RBAC0 之上的「+1」维度)。
*/
@Getter
public enum DataScopeEnum {
ALL(1, "全部数据"),
DEPT_AND_CHILD(2, "本部门及下级"),
DEPT(3, "本部门"),
SELF(4, "仅本人");
private final Integer code;
private final String label;
DataScopeEnum(Integer code, String label) {
this.code = code;
this.label = label;
}
public static Optional<DataScopeEnum> of(Integer code) {
return Arrays.stream(values()).filter(e -> e.code.equals(code)).findFirst();
}
}
package com.youjia.common.enums;
import lombok.Getter;
/**
* 启用 / 停用状态。
*/
@Getter
public enum EnableStatusEnum {
ENABLED(1, "启用"),
DISABLED(0, "停用");
private final Integer code;
private final String label;
EnableStatusEnum(Integer code, String label) {
this.code = code;
this.label = label;
}
}
package com.youjia.common.enums;
import lombok.Getter;
/**
* 菜单 / 权限类型。
*/
@Getter
public enum MenuTypeEnum {
/** 目录 */
CATALOG(1, "目录"),
/** 菜单(页面) */
MENU(2, "菜单"),
/** 按钮(操作权限) */
BUTTON(3, "按钮");
private final Integer code;
private final String label;
MenuTypeEnum(Integer code, String label) {
this.code = code;
this.label = label;
}
}
package com.youjia.common.enums;
import lombok.Getter;
import java.util.Arrays;
import java.util.Optional;
/**
* 产品分类字典,多级分类以「-」连接。
*/
@Getter
public enum ProductCategoryEnum {
FILM_ORIGINAL("太阳膜-原厂"),
COATING_ORIGINAL("车衣-原厂"),
ACCESSORY_TRAY("精品-小桌板"),
ACCESSORY_FLOOR_MAT("精品-脚垫"),
PEDAL("踏板"),
COATING_AFTERMARKET("车衣-副厂");
private final String label;
ProductCategoryEnum(String label) {
this.label = label;
}
public static Optional<ProductCategoryEnum> ofLabel(String label) {
return Arrays.stream(values()).filter(e -> e.label.equals(label)).findFirst();
}
public static boolean isValid(String label) {
return ofLabel(label).isPresent();
}
}
package com.youjia.common.enums;
import lombok.Getter;
import java.util.Arrays;
import java.util.Optional;
/**
* 门店上架记录状态。
*
* <p>仅 APPROVED(已生效)可对外展示;状态由系统自动流转,不提供人工改状态入口。</p>
*/
@Getter
public enum StoreStatusEnum {
PENDING("PENDING", "待审批", "warning"),
APPROVED("APPROVED", "已生效", "success"),
REJECTED("REJECTED", "已打回", "danger"),
REVOKED("REVOKED", "已撤回", "info"),
VOID("VOID", "已作废", "info");
private final String code;
private final String desc;
private final String badge;
StoreStatusEnum(String code, String desc, String badge) {
this.code = code;
this.desc = desc;
this.badge = badge;
}
public static Optional<StoreStatusEnum> of(String code) {
return Arrays.stream(values()).filter(e -> e.code.equals(code)).findFirst();
}
/** 是否可对外展示 */
public boolean displayable() {
return this == APPROVED;
}
/** 是否由发起人可撤回 */
public boolean revocable() {
return this == PENDING;
}
/** 是否允许修改后重新提交 */
public boolean resubmittable() {
return this == REJECTED || this == REVOKED;
}
}
package com.youjia.common.exception;
import com.youjia.common.core.ResultCode;
import lombok.Getter;
import java.io.Serial;
/**
* 业务异常。由全局异常处理器统一转换为 {@link com.youjia.common.core.Result}。
*/
@Getter
public class BusinessException extends RuntimeException {
@Serial
private static final long serialVersionUID = 1L;
private final Integer code;
public BusinessException(String message) {
super(message);
this.code = ResultCode.FAIL.getCode();
}
public BusinessException(ResultCode resultCode) {
super(resultCode.getMessage());
this.code = resultCode.getCode();
}
public BusinessException(ResultCode resultCode, String message) {
super(message);
this.code = resultCode.getCode();
}
public BusinessException(Integer code, String message) {
super(message);
this.code = code;
}
}
<?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>com.youjia</groupId>
<artifactId>YouJia</artifactId>
<version>1.0.0-SNAPSHOT</version>
</parent>
<artifactId>youjia-framework</artifactId>
<name>youjia-framework</name>
<description>技术框架模块:MyBatis-Plus、Redis、Knife4j、全局异常与跨域</description>
<dependencies>
<dependency>
<groupId>com.youjia</groupId>
<artifactId>youjia-common</artifactId>
</dependency>
<!-- MyBatis-Plus 分页 / 防全表更新插件所需的 JSqlParser 适配包 -->
<dependency>
<groupId>com.baomidou</groupId>
<artifactId>mybatis-plus-jsqlparser</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
<!-- Redis -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-pool2</artifactId>
</dependency>
<!-- MySQL 驱动(兼容 MariaDB 10.x) -->
<dependency>
<groupId>com.mysql</groupId>
<artifactId>mysql-connector-j</artifactId>
<scope>runtime</scope>
</dependency>
<!-- OpenAPI 3 文档:Knife4j -->
<dependency>
<groupId>com.github.xiaoymin</groupId>
<artifactId>knife4j-openapi3-jakarta-spring-boot-starter</artifactId>
</dependency>
<!-- 仅取 BCrypt 密码编码能力,不引入完整安全框架 -->
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-crypto</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
</dependencies>
</project>
package com.youjia.framework.config;
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.youjia.common.constant.CommonConstants;
import com.youjia.framework.security.CurrentUserHolder;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;
import java.time.LocalDateTime;
/**
* 审计字段自动填充。
*/
@Component
public class MetaObjectFillHandler implements MetaObjectHandler {
@Override
public void insertFill(MetaObject metaObject) {
LocalDateTime now = LocalDateTime.now();
Long userId = CurrentUserHolder.getUserId();
this.strictInsertFill(metaObject, "createTime", LocalDateTime.class, now);
this.strictInsertFill(metaObject, "updateTime", LocalDateTime.class, now);
this.strictInsertFill(metaObject, "createBy", Long.class, userId);
this.strictInsertFill(metaObject, "updateBy", Long.class, userId);
this.strictInsertFill(metaObject, "isDeleted", Integer.class, CommonConstants.NOT_DELETED);
}
@Override
public void updateFill(MetaObject metaObject) {
this.strictUpdateFill(metaObject, "updateTime", LocalDateTime.class, LocalDateTime.now());
this.strictUpdateFill(metaObject, "updateBy", Long.class, CurrentUserHolder.getUserId());
}
}
package com.youjia.framework.config;
import com.baomidou.mybatisplus.annotation.DbType;
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 org.mybatis.spring.annotation.MapperScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
* MyBatis-Plus 配置。
*
* <p>约定各业务模块的 Mapper 统一放在 {@code com.youjia.<module>.mapper} 包下。</p>
*/
@Configuration
@MapperScan("com.youjia.**.mapper")
public class MybatisPlusConfig {
@Bean
public MybatisPlusInterceptor mybatisPlusInterceptor() {
MybatisPlusInterceptor interceptor = new MybatisPlusInterceptor();
// 分页插件
PaginationInnerInterceptor pagination = new PaginationInnerInterceptor(DbType.MYSQL);
pagination.setMaxLimit(500L);
pagination.setOverflow(false);
interceptor.addInnerInterceptor(pagination);
// 乐观锁(门店上架记录并发审批)
interceptor.addInnerInterceptor(new OptimisticLockerInnerInterceptor());
// 阻断全表更新 / 删除
interceptor.addInnerInterceptor(new BlockAttackInnerInterceptor());
return interceptor;
}
}
package com.youjia.framework.config;
import io.swagger.v3.oas.models.OpenAPI;
import io.swagger.v3.oas.models.info.Contact;
import io.swagger.v3.oas.models.info.Info;
import org.springdoc.core.models.GroupedOpenApi;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
* Knife4j / OpenAPI 3 文档配置。
*
* <p>访问地址:http://localhost:8080/doc.html</p>
*/
@Configuration
public class OpenApiConfig {
@Bean
public OpenAPI youJiaOpenAPI() {
return new OpenAPI().info(new Info()
.title("优加门店上架系统 API")
.description("面向优加主体的门店上架后台:门店信息导入 → 单级审批 → 门店列表展示,基座为 RBAC0 + 组织数据域。")
.version("v1.0.0")
.contact(new Contact().name("优加门店上架项目组")));
}
@Bean
public GroupedOpenApi storeApi() {
return GroupedOpenApi.builder()
.group("门店上架")
.packagesToScan("com.youjia.store")
.build();
}
@Bean
public GroupedOpenApi systemApi() {
return GroupedOpenApi.builder()
.group("系统设置")
.packagesToScan("com.youjia.system")
.build();
}
}
package com.youjia.framework.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
/**
* 密码编码器。账号保存统一走 BCrypt,禁止明文落库。
*/
@Configuration
public class PasswordConfig {
@Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
}
package com.youjia.framework.config;
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.JsonTypeInfo;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import com.fasterxml.jackson.databind.jsontype.impl.LaissezFaireSubTypeValidator;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
/**
* Redis 序列化配置:key 用 String,value 用 JSON(保留类型信息以便反序列化)。
*/
@Configuration
public class RedisConfig {
@Bean
public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory connectionFactory) {
RedisTemplate<String, Object> template = new RedisTemplate<>();
template.setConnectionFactory(connectionFactory);
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.registerModule(new JavaTimeModule());
objectMapper.disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);
objectMapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
objectMapper.activateDefaultTyping(LaissezFaireSubTypeValidator.instance,
ObjectMapper.DefaultTyping.NON_FINAL, JsonTypeInfo.As.PROPERTY);
GenericJackson2JsonRedisSerializer jsonSerializer = new GenericJackson2JsonRedisSerializer(objectMapper);
StringRedisSerializer stringSerializer = new StringRedisSerializer();
template.setKeySerializer(stringSerializer);
template.setHashKeySerializer(stringSerializer);
template.setValueSerializer(jsonSerializer);
template.setHashValueSerializer(jsonSerializer);
template.afterPropertiesSet();
return template;
}
}
package com.youjia.framework.config;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
/**
* Web MVC 配置:跨域(供前端本地联调使用)。
*
* <p>接口层约定只使用 GET / POST 两种请求方式,跨域放行同步收敛为 GET / POST / OPTIONS。</p>
*
* <p>前端需要携带签名请求头(触发预检),并读取响应签名头,因此这里放开自定义请求头并
* 显式暴露响应签名头,否则浏览器侧读不到 {@code X-Sign}。</p>
*/
@Configuration
public class WebMvcConfig implements WebMvcConfigurer {
@Override
public void addCorsMappings(CorsRegistry registry) {
registry.addMapping("/**")
.allowedOriginPatterns("*")
.allowedMethods("GET", "POST", "OPTIONS")
.allowedHeaders("*")
.exposedHeaders("X-Sign", "X-Sign-Algorithm", "X-Sign-Timestamp", "X-Sign-Nonce")
.allowCredentials(true)
.maxAge(3600);
}
}
package com.youjia.framework.handler;
import com.youjia.common.core.Result;
import com.youjia.common.core.ResultCode;
import com.youjia.common.exception.BusinessException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.validation.ConstraintViolation;
import jakarta.validation.ConstraintViolationException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.validation.BindException;
import org.springframework.validation.FieldError;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.method.annotation.MethodArgumentTypeMismatchException;
import java.util.stream.Collectors;
/**
* 全局异常处理:业务异常按状态码返回,参数校验异常聚合提示,其余统一兜底。
*/
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(BusinessException.class)
public Result<Void> handleBusiness(BusinessException e, HttpServletRequest request) {
log.warn("业务异常 [{}] {} -> {}", request.getMethod(), request.getRequestURI(), e.getMessage());
return Result.build(e.getCode(), e.getMessage(), null);
}
@ExceptionHandler(MethodArgumentNotValidException.class)
public Result<Void> handleMethodArgumentNotValid(MethodArgumentNotValidException e) {
String message = e.getBindingResult().getFieldErrors().stream()
.map(FieldError::getDefaultMessage)
.collect(Collectors.joining(";"));
return Result.fail(ResultCode.PARAM_INVALID, message);
}
@ExceptionHandler(BindException.class)
public Result<Void> handleBind(BindException e) {
String message = e.getBindingResult().getFieldErrors().stream()
.map(FieldError::getDefaultMessage)
.collect(Collectors.joining(";"));
return Result.fail(ResultCode.PARAM_INVALID, message);
}
@ExceptionHandler(ConstraintViolationException.class)
public Result<Void> handleConstraintViolation(ConstraintViolationException e) {
String message = e.getConstraintViolations().stream()
.map(ConstraintViolation::getMessage)
.collect(Collectors.joining(";"));
return Result.fail(ResultCode.PARAM_INVALID, message);
}
@ExceptionHandler(MissingServletRequestParameterException.class)
public Result<Void> handleMissingParam(MissingServletRequestParameterException e) {
return Result.fail(ResultCode.PARAM_INVALID, "缺少必填参数:" + e.getParameterName());
}
@ExceptionHandler(MethodArgumentTypeMismatchException.class)
public Result<Void> handleTypeMismatch(MethodArgumentTypeMismatchException e) {
return Result.fail(ResultCode.PARAM_INVALID, "参数类型不正确:" + e.getName());
}
@ExceptionHandler(HttpMessageNotReadableException.class)
public Result<Void> handleMessageNotReadable(HttpMessageNotReadableException e) {
return Result.fail(ResultCode.PARAM_INVALID, "请求体解析失败,请检查 JSON 格式");
}
@ExceptionHandler(HttpRequestMethodNotSupportedException.class)
public Result<Void> handleMethodNotSupported(HttpRequestMethodNotSupportedException e) {
return Result.fail(ResultCode.OPERATION_NOT_ALLOWED,
"不支持的请求方法:" + e.getMethod() + ",本系统接口仅提供 GET / POST");
}
@ExceptionHandler(Exception.class)
public Result<Void> handleException(Exception e, HttpServletRequest request) {
log.error("系统异常 {} {}", request.getMethod(), request.getRequestURI(), e);
return Result.fail("系统繁忙,请稍后再试");
}
}
package com.youjia.framework.security;
import com.youjia.common.constant.CommonConstants;
import com.youjia.common.enums.DataScopeEnum;
/**
* 当前登录用户 ThreadLocal 上下文。
*
* <p>完整鉴权域接入后,由拦截器 / 过滤器统一写入;本期提供降级实现,保证审计字段不为空。</p>
*/
public final class CurrentUserHolder {
private static final ThreadLocal<LoginUser> HOLDER = new ThreadLocal<>();
private CurrentUserHolder() {
}
public static void set(LoginUser loginUser) {
HOLDER.set(loginUser);
}
public static LoginUser get() {
return HOLDER.get();
}
/** 取当前用户 ID,未登录时返回系统账号 ID(1) */
public static Long getUserId() {
LoginUser user = HOLDER.get();
return user == null || user.getUserId() == null ? 1L : user.getUserId();
}
/** 取当前用户数据域,未登录时按「全部数据」降级 */
public static Integer getDataScope() {
LoginUser user = HOLDER.get();
return user == null || user.getDataScope() == null
? DataScopeEnum.ALL.getCode()
: user.getDataScope();
}
/** 取当前用户主组织 ID */
public static Long getOrgId() {
LoginUser user = HOLDER.get();
return user == null || user.getOrgId() == null
? CommonConstants.ROOT_ORG_ID
: user.getOrgId();
}
/** 取当前用户姓名,未登录时返回系统用户占位 */
public static String getName() {
LoginUser user = HOLDER.get();
return user == null || user.getName() == null ? "系统用户" : user.getName();
}
public static void clear() {
HOLDER.remove();
}
}
package com.youjia.framework.security;
import lombok.Builder;
import lombok.Data;
import java.io.Serial;
import java.io.Serializable;
/**
* 当前登录用户上下文对象(由鉴权域透传,本期先落 ThreadLocal 占位)。
*/
@Data
@Builder
public class LoginUser implements Serializable {
@Serial
private static final long serialVersionUID = 1L;
/** 用户 ID */
private Long userId;
/** 账号 */
private String account;
/** 姓名 */
private String name;
/** 主属组织 ID */
private Long orgId;
/** 数据域:1-全部数据 2-本部门及下级 3-本部门 4-仅本人 */
private Integer dataScope;
}
package com.youjia.framework.sign;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Configuration;
/**
* 接口签名自动装配。
*
* <p>仅负责注册配置属性;验签过滤器、响应加签处理器与密钥管理器由组件扫描装配,
* 其中过滤器按 {@code youjia.api-sign.enabled} 条件生效。</p>
*/
@Configuration
@EnableConfigurationProperties(ApiSignProperties.class)
public class ApiSignConfig {
}
package com.youjia.framework.sign;
import com.youjia.common.core.Result;
import com.youjia.framework.sign.vo.SignPublicKeyVO;
import com.youjia.framework.sign.vo.SignSpecVO;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
/**
* 接口签名元信息接口。
*
* <p>这两个接口本身不要求携带签名(标注 {@link ApiSignIgnore}),用于前端对接阶段获取公钥与拼接规则。</p>
*/
@ApiSignIgnore
@RestController
@RequestMapping("/system/sign")
@RequiredArgsConstructor
@Tag(name = "接口签名", description = "前后端 RSA 非对称加签的公钥下发与规范说明")
public class ApiSignController {
/** 示例中使用的固定时间戳与随机串,仅用于演示拼接格式 */
private static final long SAMPLE_TIMESTAMP = 1730000000000L;
private static final String SAMPLE_NONCE = "5f2a9c1e8b7d4a63b0f1c2d3e4f5a6b7";
private static final String SAMPLE_BODY =
"{\"code\":200,\"message\":\"操作成功\",\"data\":null,\"timestamp\":1730000000000}";
private final ApiSignProperties properties;
private final ApiSignKeyManager keyManager;
@Operation(summary = "获取服务端签名公钥(前端用于响应验签)")
@GetMapping("/public-key")
public Result<SignPublicKeyVO> publicKey() {
SignPublicKeyVO vo = new SignPublicKeyVO();
vo.setAlgorithm(properties.getAlgorithm());
vo.setAllowedAlgorithms(properties.getAllowedAlgorithms());
vo.setKeySize(keyManager.getServerKeySize());
vo.setAppIds(properties.getAppIds());
vo.setExpireSeconds(properties.getExpireSeconds());
vo.setNonceEnabled(properties.isNonceEnabled());
vo.setPublicKey(keyManager.getServerPublicKeyBase64());
vo.setPublicKeyPem(keyManager.getServerPublicKeyPem());
vo.setServerTime(System.currentTimeMillis());
return Result.success(vo);
}
@Operation(summary = "获取接口签名规范与示例(含可直接自测的响应签名)")
@GetMapping("/spec")
public Result<SignSpecVO> spec() {
SignSpecVO vo = new SignSpecVO();
vo.setAlgorithm(properties.getAlgorithm());
vo.setAllowedAlgorithms(properties.getAllowedAlgorithms());
vo.setMode(properties.resolveMode().name());
vo.setAppIds(properties.getAppIds());
vo.setExpireSeconds(properties.getExpireSeconds());
vo.setNonceEnabled(properties.isNonceEnabled());
vo.setNonceExpireSeconds(properties.getNonceExpireSeconds());
vo.setMaxBodySignSize(properties.getMaxBodySignSize());
vo.setIgnoreUrls(properties.getIgnoreUrls());
vo.setHeaders(List.of(
new SignSpecVO.HeaderSpec("请求 " + SignConstants.HEADER_APP_ID, false,
"应用标识,默认 " + SignConstants.DEFAULT_APP_ID),
new SignSpecVO.HeaderSpec("请求 " + SignConstants.HEADER_TIMESTAMP, true,
"毫秒级时间戳,与服务端时间偏差不超过 " + properties.getExpireSeconds() + " 秒"),
new SignSpecVO.HeaderSpec("请求 " + SignConstants.HEADER_NONCE, true,
"一次性随机串(建议 UUID),窗口内不可重复"),
new SignSpecVO.HeaderSpec("请求 " + SignConstants.HEADER_SIGN, true,
"签名值:对请求待签名原文用客户端私钥加签后 Base64"),
new SignSpecVO.HeaderSpec("请求 " + SignConstants.HEADER_SIGN_ALGORITHM, false,
"签名算法,默认取服务端配置:" + properties.getAlgorithm()),
new SignSpecVO.HeaderSpec("响应 " + SignConstants.HEADER_SIGN_TIMESTAMP, false,
"服务端签名时间戳,前端用于拼接响应待签名原文"),
new SignSpecVO.HeaderSpec("响应 " + SignConstants.HEADER_SIGN_NONCE, false,
"服务端签名随机串,前端用于拼接响应待签名原文"),
new SignSpecVO.HeaderSpec("响应 " + SignConstants.HEADER_SIGN, false,
"服务端签名值,前端用服务端公钥验签"),
new SignSpecVO.HeaderSpec("响应 " + SignConstants.HEADER_SIGN_ALGORITHM, false,
"服务端本次使用的签名算法")));
vo.setRequestCanonicalRule(List.of(
"第 1 行:HTTP 方法,大写(GET / POST)",
"第 2 行:请求路径,含 context-path,不含协议、域名与查询串",
"第 3 行:查询串,key=value 整串按字典序升序(value 保留原编码值),以 & 连接;无参数则留空行",
"第 4 行:Content-Type 的媒体类型部分,小写且不含 charset 参数(如 application/json);无请求体则留空行",
"第 5 行:时间戳,与请求头 " + SignConstants.HEADER_TIMESTAMP + " 完全一致",
"第 6 行:随机串,与请求头 " + SignConstants.HEADER_NONCE + " 完全一致",
"第 7 行:应用标识,与请求头 " + SignConstants.HEADER_APP_ID + " 完全一致",
"第 8 行:请求体原文,即前端实际发出的字符串(务必先 JSON.stringify 得到字符串再发送,"
+ "并按同一字符串参与签名);文件上传等不参与签名的场景留空行",
"各行以 \\n 连接,共 8 行,末尾不加换行;请求体必须放在最后一行"));
vo.setResponseCanonicalRule(List.of(
"第 1 行:响应头 " + SignConstants.HEADER_SIGN_TIMESTAMP + " 的值",
"第 2 行:响应头 " + SignConstants.HEADER_SIGN_NONCE + " 的值",
"第 3 行:响应体原文,直接取前端拿到的响应文本,禁止解析后再序列化",
"各行以 \\n 连接,且末尾保留一个换行",
"验签值取自响应头 " + SignConstants.HEADER_SIGN + ",用服务端公钥验证",
"注意:不要用 JSON.parse + JSON.stringify 重建响应体再验签,"
+ "服务端输出的数值(如 0.00)会被 JavaScript 归一化为 0 而导致验签失败"));
String requestCanonical = SignCanonicalBuilder.buildRequestCanonical(
"POST",
"/store/import/submit",
SignCanonicalBuilder.sortQuery("pageNum=1&pageSize=10"),
"application/json",
String.valueOf(SAMPLE_TIMESTAMP),
"3f2504e0-4f89-11d3-9a0c-0305e82c3301",
SignConstants.DEFAULT_APP_ID,
SAMPLE_BODY);
String responseCanonical = SignCanonicalBuilder.buildResponseCanonical(
SAMPLE_TIMESTAMP, SAMPLE_NONCE, SAMPLE_BODY);
String responseSign = keyManager.isResponseSignAvailable()
? RsaSignUtils.sign(responseCanonical, keyManager.getServerPrivateKey(), properties.getAlgorithm())
: null;
SignSpecVO.Sample sample = new SignSpecVO.Sample();
sample.setRequestCanonical(requestCanonical);
sample.setRequestCanonicalRemark("示意请求:POST /store/import/submit?pageNum=1&pageSize=10,"
+ "Content-Type: application/json,请求体为 " + SAMPLE_BODY);
sample.setResponseBody(SAMPLE_BODY);
sample.setResponseCanonical(responseCanonical);
sample.setResponseCanonicalSign(responseSign);
sample.setResponseCanonicalAlgorithm(properties.getAlgorithm());
sample.setServerPublicKey(keyManager.getServerPublicKeyBase64());
sample.setServerPublicKeyPem(keyManager.getServerPublicKeyPem());
vo.setSample(sample);
return Result.success(vo);
}
}
package com.youjia.framework.sign;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.youjia.common.core.Result;
import com.youjia.common.core.ResultCode;
import com.youjia.common.exception.BusinessException;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.ObjectProvider;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerExecutionChain;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping;
import org.springframework.web.util.ContentCachingResponseWrapper;
import java.io.IOException;
/**
* 接口签名过滤器:请求方向验签 + 响应方向加签。
*
* <p><b>请求方向</b>(前端加签 → 服务端验签):读取签名头并验签,失败时立即返回统一响应结构,不再进入业务逻辑。</p>
*
* <p><b>响应方向</b>(服务端加签 → 前端验签):缓存业务写出的响应体,用服务端私钥对其原文加签,
* 签名值通过响应头 {@code X-Sign} 等返回,不修改响应体结构,前端只需对收到的原始文本验签即可。</p>
*
* <p>过滤规则:仅处理 GET / POST;命中 {@code youjia.api-sign.ignore-urls} 或标注
* {@link ApiSignIgnore} 的接口直接放行。</p>
*/
@Slf4j
@Component
@Order(Ordered.HIGHEST_PRECEDENCE + 100)
@ConditionalOnProperty(prefix = "youjia.api-sign", name = "enabled", havingValue = "true", matchIfMissing = true)
@RequiredArgsConstructor
public class ApiSignFilter extends OncePerRequestFilter {
private final ApiSignProperties properties;
private final ApiSignService apiSignService;
private final ObjectMapper objectMapper;
private final ObjectProvider<RequestMappingHandlerMapping> handlerMappingProvider;
@Override
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
throws ServletException, IOException {
ApiSignIgnore annotation = resolveAnnotation(request);
boolean verifyRequest = needVerifyRequest(request, annotation);
boolean signResponse = needSignResponse(request, annotation);
if (!verifyRequest && !signResponse) {
chain.doFilter(request, response);
return;
}
HttpServletRequest chainRequest = request;
byte[] cachedBody = null;
if (verifyRequest) {
try {
RepeatableReadRequestWrapper wrapper =
new RepeatableReadRequestWrapper(request, properties.getMaxBodySignSize());
chainRequest = wrapper;
cachedBody = wrapper.getCachedBody();
} catch (IOException e) {
log.warn("接口签名:读取请求体失败 -> {} {}", request.getMethod(), request.getRequestURI(), e);
writeError(response, ResultCode.FAIL.getCode(), "请求体读取失败");
return;
}
}
ContentCachingResponseWrapper cachingResponse = null;
HttpServletResponse chainResponse = response;
if (signResponse) {
cachingResponse = new ContentCachingResponseWrapper(response);
chainResponse = cachingResponse;
}
try {
if (verifyRequest) {
apiSignService.verifyRequest(chainRequest, cachedBody);
}
} catch (BusinessException e) {
writeError(chainResponse, e.getCode(), e.getMessage());
finishResponse(cachingResponse, response);
return;
} catch (RuntimeException e) {
log.error("接口签名:签名校验异常 -> {} {}", request.getMethod(), request.getRequestURI(), e);
writeError(chainResponse, ResultCode.FAIL.getCode(), "签名校验异常,请稍后重试");
finishResponse(cachingResponse, response);
return;
}
chain.doFilter(chainRequest, chainResponse);
finishResponse(cachingResponse, response);
}
/* ==================================================================
* 过滤判定
* ================================================================== */
private boolean needVerifyRequest(HttpServletRequest request, ApiSignIgnore annotation) {
if (!properties.isEnabled() || !properties.isVerifyRequest() || annotation != null) {
return false;
}
if (!supportedMethod(request) || isIgnoredUrl(request)) {
return false;
}
// 宽松模式 + 未携带任何签名头:直接放行且不包装请求体,保持与接入前一致的行为
if (properties.resolveMode() == SignModeEnum.LENIENT && !hasSignHeader(request)) {
log.warn("接口签名:宽松模式下放行未签名请求 -> {} {}",
request.getMethod(), request.getRequestURI());
return false;
}
return true;
}
private boolean needSignResponse(HttpServletRequest request, ApiSignIgnore annotation) {
if (!properties.isEnabled() || !properties.isSignResponse()) {
return false;
}
if (annotation != null && annotation.response()) {
return false;
}
return supportedMethod(request) && !isIgnoredUrl(request);
}
private boolean supportedMethod(HttpServletRequest request) {
String method = request.getMethod();
return HttpMethod.GET.matches(method) || HttpMethod.POST.matches(method);
}
private boolean isIgnoredUrl(HttpServletRequest request) {
return ApiSignUrlMatcher.isIgnored(properties.getIgnoreUrls(),
request.getRequestURI(), request.getContextPath());
}
private boolean hasSignHeader(HttpServletRequest request) {
return isNotBlank(request.getHeader(SignConstants.HEADER_SIGN))
|| isNotBlank(request.getHeader(SignConstants.HEADER_TIMESTAMP))
|| isNotBlank(request.getHeader(SignConstants.HEADER_NONCE));
}
/** 解析处理器上的 {@link ApiSignIgnore}(方法优先于类) */
private ApiSignIgnore resolveAnnotation(HttpServletRequest request) {
RequestMappingHandlerMapping mapping = handlerMappingProvider.getIfAvailable();
if (mapping == null) {
return null;
}
try {
HandlerExecutionChain chain = mapping.getHandler(request);
if (chain == null || !(chain.getHandler() instanceof HandlerMethod handlerMethod)) {
return null;
}
ApiSignIgnore annotation = handlerMethod.getMethodAnnotation(ApiSignIgnore.class);
return annotation != null ? annotation : handlerMethod.getBeanType().getAnnotation(ApiSignIgnore.class);
} catch (Exception e) {
// 未匹配到处理器(404 等)交由后续链路返回标准错误
return null;
}
}
/* ==================================================================
* 响应处理
* ================================================================== */
/** 对缓存到的响应体加签并写回真实响应 */
private void finishResponse(ContentCachingResponseWrapper cachingResponse, HttpServletResponse response)
throws IOException {
if (cachingResponse == null) {
return;
}
if (!response.isCommitted()) {
byte[] body = cachingResponse.getContentAsByteArray();
if (signableResponse(body, response.getContentType())) {
ApiSignService.ResponseSignature signature = apiSignService.signResponseBody(body);
if (signature != null) {
response.setHeader(SignConstants.HEADER_SIGN_TIMESTAMP, String.valueOf(signature.timestamp()));
response.setHeader(SignConstants.HEADER_SIGN_NONCE, signature.nonce());
response.setHeader(SignConstants.HEADER_SIGN, signature.sign());
response.setHeader(SignConstants.HEADER_SIGN_ALGORITHM, signature.algorithm());
}
}
}
cachingResponse.copyBodyToResponse();
}
/**
* 是否对该响应加签:仅 JSON 文本响应、非空且不超过体积上限。
*
* <p>文件导出等二进制响应不加签(其完整性由下载链路的校验机制保障)。</p>
*/
private boolean signableResponse(byte[] body, String contentType) {
if (body == null || body.length == 0) {
return false;
}
long limit = properties.getMaxBodySignSize();
if (limit > 0 && body.length > limit) {
log.debug("接口签名:响应体 {} 字节超过加签上限 {} 字节,跳过响应加签", body.length, limit);
return false;
}
return contentType != null && contentType.toLowerCase().contains("json");
}
/** 直接输出统一错误响应(过滤器早于 DispatcherServlet,需自行写出响应体) */
private void writeError(HttpServletResponse response, Integer code, String message) throws IOException {
Result<Void> result = Result.build(code, message, null);
response.setStatus(HttpServletResponse.SC_OK);
response.setContentType(MediaType.APPLICATION_JSON_VALUE);
response.setCharacterEncoding("UTF-8");
response.getWriter().write(objectMapper.writeValueAsString(result));
response.getWriter().flush();
}
private boolean isNotBlank(String value) {
return value != null && !value.isBlank();
}
}
package com.youjia.framework.sign;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* 免签名标记:标注在 Controller 类或方法上,默认同时跳过请求验签与响应加签。
*
* <p>适用于公钥下发、健康检查、开放查询、文件直链下载等无需签名保护的接口。
* 若只希望跳过请求验签、但仍对响应加签,可标注 {@code @ApiSignIgnore(response = false)}。</p>
*
* <p>示例:</p>
* <pre>
* &#64;ApiSignIgnore
* &#64;GetMapping("/open/config")
* public Result&lt;ConfigVO&gt; config() { ... }
* </pre>
*/
@Documented
@Target({ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface ApiSignIgnore {
/** 是否跳过响应加签,默认跳过 */
boolean response() default true;
}
package com.youjia.framework.sign;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import java.util.ArrayList;
import java.util.List;
/**
* 接口签名配置(前缀 {@code youjia.api-sign})。
*
* <p>典型配置:</p>
* <pre>
* youjia:
* api-sign:
* enabled: true
* mode: STRICT
* verify-request: true
* sign-response: true
* algorithm: SHA256withRSA
* expire-seconds: 300
* key-directory: ./keys
* auto-generate-key-pair: true
* </pre>
*/
@Data
@ConfigurationProperties(prefix = "youjia.api-sign")
public class ApiSignProperties {
/** 总开关:关闭后既不验签也不加签 */
private boolean enabled = true;
/** 校验模式:STRICT / LENIENT */
private String mode = SignModeEnum.STRICT.name();
/** 是否校验前端请求签名 */
private boolean verifyRequest = true;
/** 是否对响应体加签 */
private boolean signResponse = true;
/** 签名算法:SHA256withRSA / SHA1withRSA / MD5withRSA */
private String algorithm = SignConstants.ALGORITHM_SHA256_RSA;
/** 允许的签名算法白名单,防止前端降级算法攻击 */
private List<String> allowedAlgorithms = new ArrayList<>(List.of(
SignConstants.ALGORITHM_SHA256_RSA,
SignConstants.ALGORITHM_SHA1_RSA));
/** 允许接入的应用标识(请求头 X-App-Id) */
private List<String> appIds = new ArrayList<>(List.of(SignConstants.DEFAULT_APP_ID));
/** 请求时间戳有效窗口(秒),双向容忍客户端与服务端的时间偏差 */
private long expireSeconds = SignConstants.DEFAULT_EXPIRE_SECONDS;
/** 是否开启 nonce 防重放 */
private boolean nonceEnabled = true;
/** nonce 存活时长(秒) */
private long nonceExpireSeconds = SignConstants.DEFAULT_NONCE_EXPIRE_SECONDS;
/** 参与签名的请求体上限(字节),超过该值待签名原文中的请求体按空串处理 */
private long maxBodySignSize = SignConstants.DEFAULT_MAX_BODY_SIGN_SIZE;
/** 免签名 URL 白名单,支持 Ant 风格;同时兼容「含 context-path」与「不含 context-path」两种写法 */
private List<String> ignoreUrls = new ArrayList<>(List.of(
"/doc.html",
"/webjars/**",
"/v3/api-docs/**",
"/swagger-ui/**",
"/swagger-resources/**",
"/favicon.ico",
"/error",
"/system/sign/**"));
/** 客户端公钥(验请求签名用),支持 Base64 单行 / PEM 全文 */
private String clientPublicKey;
/** 客户端公钥文件路径,支持 classpath: / file: / 相对路径(优先于 clientPublicKey) */
private String clientPublicKeyPath;
/** 服务端私钥(签响应用),支持 Base64 单行 / PEM 全文 */
private String serverPrivateKey;
/** 服务端私钥文件路径 */
private String serverPrivateKeyPath;
/** 服务端公钥(下发给前端验签用) */
private String serverPublicKey;
/** 服务端公钥文件路径 */
private String serverPublicKeyPath;
/** 密钥文件目录:未显式配置密钥时,从该目录加载;为空时若开启自动生成则生成到该目录 */
private String keyDirectory = SignConstants.DEFAULT_KEY_DIRECTORY;
/** 密钥缺失时是否自动生成密钥对(仅建议开发 / 联调环境开启) */
private boolean autoGenerateKeyPair = true;
/** 密钥长度 */
private int keySize = SignConstants.DEFAULT_KEY_SIZE;
public SignModeEnum resolveMode() {
return SignModeEnum.of(mode);
}
}
package com.youjia.framework.sign;
import com.youjia.common.core.ResultCode;
import com.youjia.common.exception.BusinessException;
import jakarta.servlet.http.HttpServletRequest;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.ObjectProvider;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.time.Duration;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.ConcurrentHashMap;
/**
* 接口签名服务:请求验签、响应加签与防重放。
*
* <p>请求验签流程:读取签名头 → 校验必填 → 校验应用标识 → 校验时间戳窗口 → 校验算法白名单 →
* 验签 → 校验 nonce 防重放。任一环节失败均抛出业务异常,由过滤器统一输出错误响应。</p>
*
* <p>响应加签:对「服务端最终写出的响应文本」直接加签,签名值随响应头返回,不侵入响应体结构。</p>
*
* <p>防重放优先使用 Redis({@code SETNX + TTL});Redis 不可用时降级为服务端本地缓存,单机部署下同样有效。</p>
*/
@Slf4j
@Component
@RequiredArgsConstructor
public class ApiSignService {
private final ApiSignProperties properties;
private final ApiSignKeyManager keyManager;
private final ObjectProvider<StringRedisTemplate> redisTemplateProvider;
/** Redis 不可用时的本地 nonce 缓存:key -> 过期时间戳(毫秒) */
private final Map<String, Long> localNonceCache = new ConcurrentHashMap<>();
/* ==================================================================
* 请求验签
* ================================================================== */
/**
* 校验请求签名。
*
* @param request 请求对象
* @param cachedBody 已缓存的请求体(null 表示请求体不参与签名,原文按空串处理)
*/
public void verifyRequest(HttpServletRequest request, byte[] cachedBody) {
String appId = request.getHeader(SignConstants.HEADER_APP_ID);
String timestamp = request.getHeader(SignConstants.HEADER_TIMESTAMP);
String nonce = request.getHeader(SignConstants.HEADER_NONCE);
String sign = request.getHeader(SignConstants.HEADER_SIGN);
String algorithmHeader = request.getHeader(SignConstants.HEADER_SIGN_ALGORITHM);
boolean missingAll = isBlank(sign) && isBlank(timestamp) && isBlank(nonce);
if (missingAll) {
if (properties.resolveMode() == SignModeEnum.LENIENT) {
log.warn("接口签名:请求未携带签名头,当前为宽松模式已放行 -> {} {}",
request.getMethod(), request.getRequestURI());
return;
}
throw new BusinessException(ResultCode.SIGN_MISSING);
}
if (isBlank(sign) || isBlank(timestamp) || isBlank(nonce)) {
throw new BusinessException(ResultCode.SIGN_MISSING,
"签名请求头不完整,需同时提供 X-Timestamp / X-Nonce / X-Sign");
}
String resolvedAppId = isBlank(appId) ? SignConstants.DEFAULT_APP_ID : appId.trim();
List<String> appIds = properties.getAppIds();
if (appIds != null && !appIds.isEmpty() && !appIds.contains(resolvedAppId)) {
throw new BusinessException(ResultCode.SIGN_INVALID, "应用标识未授权:" + resolvedAppId);
}
long requestTime;
try {
requestTime = Long.parseLong(timestamp.trim());
} catch (NumberFormatException e) {
throw new BusinessException(ResultCode.SIGN_INVALID, "时间戳格式不正确,应为毫秒级数字");
}
if (Math.abs(System.currentTimeMillis() - requestTime) > properties.getExpireSeconds() * 1000L) {
throw new BusinessException(ResultCode.SIGN_EXPIRED,
"请求已过期,允许的时间偏差为 " + properties.getExpireSeconds() + " 秒");
}
String algorithm = resolveAlgorithm(algorithmHeader);
if (!keyManager.isRequestVerifyAvailable()) {
throw new BusinessException(ResultCode.SIGN_KEY_NOT_CONFIGURED,
"服务端未配置客户端公钥,无法校验请求签名");
}
String canonical = buildRequestCanonical(request, timestamp, nonce, resolvedAppId, cachedBody);
if (!RsaSignUtils.verify(canonical, sign, keyManager.getClientPublicKey(), algorithm)) {
log.warn("接口签名:{} {} 验签失败(appId={}, timestamp={}, nonce={})",
request.getMethod(), request.getRequestURI(), resolvedAppId, timestamp, nonce);
log.debug("接口签名:待签名原文为\n{}", canonical);
throw new BusinessException(ResultCode.SIGN_INVALID);
}
if (properties.isNonceEnabled() && isReplay(resolvedAppId, nonce.trim())) {
throw new BusinessException(ResultCode.SIGN_REPLAY);
}
log.debug("接口签名:{} {} 验签通过(appId={})", request.getMethod(), request.getRequestURI(), resolvedAppId);
}
/** 构建请求方向待签名原文 */
public String buildRequestCanonical(HttpServletRequest request, String timestamp, String nonce,
String appId, byte[] cachedBody) {
return SignCanonicalBuilder.buildRequestCanonical(
request.getMethod(),
request.getRequestURI(),
SignCanonicalBuilder.sortQuery(request.getQueryString()),
normalizeContentType(request.getContentType()),
timestamp,
nonce,
appId,
bodyText(request, cachedBody));
}
/* ==================================================================
* 响应加签
* ================================================================== */
/**
* 对响应体原文加签。
*
* @param body 服务端即将写出的响应体字节(UTF-8 文本)
* @return 签名结果;服务端私钥缺失时返回 null
*/
public ResponseSignature signResponseBody(byte[] body) {
if (!keyManager.isResponseSignAvailable()) {
return null;
}
long timestamp = System.currentTimeMillis();
String nonce = UUID.randomUUID().toString().replace("-", "");
String canonical = SignCanonicalBuilder.buildResponseCanonical(
timestamp, nonce, new String(body == null ? new byte[0] : body, StandardCharsets.UTF_8));
String sign = RsaSignUtils.sign(canonical, keyManager.getServerPrivateKey(), properties.getAlgorithm());
return new ResponseSignature(timestamp, nonce, sign, properties.getAlgorithm());
}
/** 响应签名结果 */
public record ResponseSignature(long timestamp, String nonce, String sign, String algorithm) {
}
/* ==================================================================
* 内部方法
* ================================================================== */
private String resolveAlgorithm(String algorithmHeader) {
String algorithm = isBlank(algorithmHeader) ? properties.getAlgorithm() : algorithmHeader.trim();
List<String> allowed = properties.getAllowedAlgorithms();
if (allowed != null && !allowed.isEmpty()
&& allowed.stream().noneMatch(item -> item.equalsIgnoreCase(algorithm))) {
throw new BusinessException(ResultCode.SIGN_ALGORITHM_UNSUPPORTED, "不支持的签名算法:" + algorithm);
}
if (!RsaSignUtils.isAlgorithmSupported(algorithm)) {
throw new BusinessException(ResultCode.SIGN_ALGORITHM_UNSUPPORTED, "不支持的签名算法:" + algorithm);
}
return algorithm;
}
/** 请求体原文;未缓存(multipart / 超出上限)时返回空串 */
private String bodyText(HttpServletRequest request, byte[] cachedBody) {
if (cachedBody == null || cachedBody.length == 0) {
return "";
}
String encoding = request.getCharacterEncoding();
Charset charset = isBlank(encoding) ? StandardCharsets.UTF_8 : Charset.forName(encoding);
return new String(cachedBody, charset);
}
/** Content-Type 规范化为「小写媒体类型」,去掉 charset 等参数,降低前后端拼接差异 */
private String normalizeContentType(String contentType) {
if (contentType == null || contentType.isBlank()) {
return "";
}
int index = contentType.indexOf(';');
String mediaType = index < 0 ? contentType : contentType.substring(0, index);
return mediaType.trim().toLowerCase();
}
/** nonce 防重放:已使用过返回 true */
private boolean isReplay(String appId, String nonce) {
String key = SignConstants.NONCE_KEY_PREFIX + appId + ":" + nonce;
long ttlSeconds = Math.max(1, properties.getNonceExpireSeconds());
StringRedisTemplate redisTemplate = redisTemplateProvider.getIfAvailable();
if (redisTemplate != null) {
try {
Boolean first = redisTemplate.opsForValue()
.setIfAbsent(key, "1", Duration.ofSeconds(ttlSeconds));
return !Boolean.TRUE.equals(first);
} catch (Exception e) {
log.warn("接口签名:Redis 防重放不可用,已降级为本地缓存 -> {}", e.getMessage());
}
}
long now = System.currentTimeMillis();
localNonceCache.entrySet().removeIf(entry -> entry.getValue() < now);
return localNonceCache.putIfAbsent(key, now + ttlSeconds * 1000L) != null;
}
private static boolean isBlank(String value) {
return value == null || value.isBlank();
}
}
package com.youjia.framework.sign;
import org.springframework.util.AntPathMatcher;
import java.util.List;
/**
* 签名白名单匹配工具。
*
* <p>同时支持「含 context-path 的完整路径」(如 {@code /api/store/listing/page})与
* 「去掉 context-path 的接口路径」(如 {@code /store/listing/page})两种写法,
* 避免配置时反复试错。</p>
*/
public final class ApiSignUrlMatcher {
private static final AntPathMatcher MATCHER = new AntPathMatcher();
private ApiSignUrlMatcher() {
}
/** 请求路径是否命中免签名白名单 */
public static boolean isIgnored(List<String> patterns, String requestUri, String contextPath) {
if (patterns == null || patterns.isEmpty() || requestUri == null) {
return false;
}
String relativePath = stripContextPath(requestUri, contextPath);
for (String pattern : patterns) {
if (pattern == null || pattern.isBlank()) {
continue;
}
String target = pattern.trim();
if (MATCHER.match(target, requestUri) || MATCHER.match(target, relativePath)) {
return true;
}
}
return false;
}
/** 去掉 context-path;context-path 为「/」或空时原样返回 */
public static String stripContextPath(String requestUri, String contextPath) {
if (requestUri == null) {
return "";
}
if (contextPath == null || contextPath.isBlank() || "/".equals(contextPath)) {
return requestUri;
}
String prefix = contextPath.endsWith("/") ? contextPath.substring(0, contextPath.length() - 1) : contextPath;
if (requestUri.startsWith(prefix) && requestUri.length() >= prefix.length()) {
String rest = requestUri.substring(prefix.length());
return rest.startsWith("/") ? rest : "/" + rest;
}
return requestUri;
}
}
package com.youjia.framework.sign;
import jakarta.servlet.ReadListener;
import jakarta.servlet.ServletInputStream;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletRequestWrapper;
import org.springframework.http.MediaType;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PushbackInputStream;
import java.io.SequenceInputStream;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
/**
* 可重复读请求包装器。
*
* <p>签名校验需要读取原始请求体,而 {@code @RequestBody} 只能消费一次输入流,因此在此统一包装:</p>
* <ul>
* <li>普通请求:读取上限内的字节用于计算摘要,并向下游提供完整的可重复读流;</li>
* <li>超大请求:仅缓存前缀,余量以流式拼接继续向下游提供,避免大报文占用内存;</li>
* <li>文件上传(multipart/form-data):不缓存请求体,下游读取原始流(该场景请求体不参与签名)。</li>
* </ul>
*/
public class RepeatableReadRequestWrapper extends HttpServletRequestWrapper {
/** 已缓存的请求体(null 表示请求体不参与签名,按空串摘要处理) */
private final byte[] cachedBody;
/** 供下游读取的完整请求体流;null 表示直接使用原始流 */
private final InputStream bodyStream;
public RepeatableReadRequestWrapper(HttpServletRequest request, long maxCacheSize) throws IOException {
super(request);
if (isMultipart(request)) {
this.cachedBody = null;
this.bodyStream = null;
return;
}
int limit = maxCacheSize <= 0 || maxCacheSize > Integer.MAX_VALUE
? Integer.MAX_VALUE
: (int) maxCacheSize;
InputStream source = request.getInputStream();
if (limit == Integer.MAX_VALUE) {
byte[] all = readAll(source);
this.cachedBody = all;
this.bodyStream = new ByteArrayInputStream(all);
return;
}
byte[] prefix = readAtMost(source, limit);
int probe = -1;
if (prefix.length == limit && limit > 0) {
probe = source.read();
}
if (probe < 0) {
this.cachedBody = prefix;
this.bodyStream = new ByteArrayInputStream(prefix);
} else {
PushbackInputStream remainder = new PushbackInputStream(source, 1);
remainder.unread(probe);
this.cachedBody = null;
this.bodyStream = new SequenceInputStream(new ByteArrayInputStream(prefix), remainder);
}
}
/** 参与签名计算的请求体;返回 null 表示按空串摘要处理 */
public byte[] getCachedBody() {
return cachedBody;
}
@Override
public ServletInputStream getInputStream() throws IOException {
if (bodyStream == null) {
return super.getInputStream();
}
return new DelegatingServletInputStream(bodyStream);
}
@Override
public BufferedReader getReader() throws IOException {
Charset charset = Charset.forName(
getCharacterEncoding() == null ? StandardCharsets.UTF_8.name() : getCharacterEncoding());
return new BufferedReader(new InputStreamReader(getInputStream(), charset));
}
private static boolean isMultipart(HttpServletRequest request) {
String contentType = request.getContentType();
return contentType != null && contentType.toLowerCase().startsWith(MediaType.MULTIPART_FORM_DATA_VALUE);
}
private static byte[] readAll(InputStream in) throws IOException {
ByteArrayOutputStream out = new ByteArrayOutputStream(1024);
byte[] buffer = new byte[8192];
int len;
while ((len = in.read(buffer)) > 0) {
out.write(buffer, 0, len);
}
return out.toByteArray();
}
private static byte[] readAtMost(InputStream in, int max) throws IOException {
ByteArrayOutputStream out = new ByteArrayOutputStream(Math.min(max, 8192));
byte[] buffer = new byte[4096];
int total = 0;
while (total < max) {
int len = in.read(buffer, 0, Math.min(buffer.length, max - total));
if (len < 0) {
break;
}
out.write(buffer, 0, len);
total += len;
}
return out.toByteArray();
}
/** ServletInputStream 适配器:把普通输入流包装为容器可识别的请求体流 */
private static class DelegatingServletInputStream extends ServletInputStream {
private final InputStream source;
private boolean finished;
DelegatingServletInputStream(InputStream source) {
this.source = source;
}
@Override
public int read() throws IOException {
int value = source.read();
if (value == -1) {
finished = true;
}
return value;
}
@Override
public int read(byte[] b, int off, int len) throws IOException {
int value = source.read(b, off, len);
if (value == -1) {
finished = true;
}
return value;
}
@Override
public int available() throws IOException {
return source.available();
}
@Override
public void close() throws IOException {
source.close();
}
@Override
public boolean isFinished() {
return finished;
}
@Override
public boolean isReady() {
return true;
}
@Override
public void setReadListener(ReadListener readListener) {
throw new UnsupportedOperationException("异步读取未启用");
}
}
}
package com.youjia.framework.sign;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import java.util.Objects;
/**
* 待签名原文(规范化字符串)构建器。
*
* <p>前后端必须使用完全一致的拼接规则,否则验签必然失败。规则如下:</p>
*
* <p><b>请求方向(前端加签 → 服务端验签)8 行,以 {@code \n} 连接,末尾不加换行:</b></p>
* <pre>
* 1 HTTP 方法(大写,GET / POST)
* 2 请求路径(含 context-path,不含协议、域名与查询串),如 /store/listing/page
* 3 查询串(key 按字典序升序、value 保留原编码值、key=value 以 &amp; 连接;无参数则为空行)
* 4 Content-Type 的媒体类型部分(小写、不含 charset 等参数,如 application/json;无请求体则为空行)
* 5 时间戳(毫秒,与请求头 X-Timestamp 一致)
* 6 随机串(与请求头 X-Nonce 一致)
* 7 应用标识(与请求头 X-App-Id 一致)
* 8 请求体原文(前端实际发出的字符串;multipart 上传或超出上限的场景为空行)
* </pre>
*
* <p>请求体放在最后一行,且前面 7 个字段均不可能包含换行(路径与查询串取编码后的原始形式,
* 请求头值本身不允许换行),因此拼接结果不会产生歧义。</p>
*
* <p><b>响应方向(服务端加签 → 前端验签)</b>,以 {@code \n} 连接,<b>末尾保留一个换行</b>:</p>
* <pre>
* 1 签名时间戳(响应头 X-Sign-Timestamp,毫秒)
* 2 签名随机串(响应头 X-Sign-Nonce)
* 3 响应体原文(前端拿到的原始响应文本,不做任何解析与再序列化)
* </pre>
*
* <p>响应方向之所以直接签原始文本,是为了绕开 JSON 数值精度与序列化差异
* (例如服务端输出 {@code 0.00} 而前端 {@code JSON.stringify} 得到 {@code 0})导致的验签失败。</p>
*/
public final class SignCanonicalBuilder {
/** 字段分隔符 */
public static final String SEPARATOR = "\n";
private SignCanonicalBuilder() {
}
/** 构建请求方向待签名原文 */
public static String buildRequestCanonical(String method,
String requestUri,
String sortedQuery,
String contentType,
String timestamp,
String nonce,
String appId,
String body) {
return join(
normalize(method).toUpperCase(),
normalize(requestUri),
normalize(sortedQuery),
normalize(contentType),
normalize(timestamp),
normalize(nonce),
normalize(appId),
normalize(body));
}
/** 构建响应方向待签名原文 */
public static String buildResponseCanonical(long timestamp, String nonce, String body) {
return timestamp + SEPARATOR + normalize(nonce) + SEPARATOR + normalize(body) + SEPARATOR;
}
/**
* 查询串规范化:按 {@code key=value} 整串字典序升序排列,value 保留原始编码值。
*
* <p>例如 {@code b=2&amp;a=1} 将被规范化为 {@code a=1&amp;b=2};无参数时返回空串。</p>
*/
public static String sortQuery(String rawQuery) {
if (rawQuery == null || rawQuery.isBlank()) {
return "";
}
List<String> pairs = new ArrayList<>(Arrays.asList(rawQuery.split("&")));
pairs.removeIf(pair -> pair.isEmpty());
pairs.sort(Comparator.naturalOrder());
return String.join("&", pairs);
}
private static String join(String... parts) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < parts.length; i++) {
if (i > 0) {
sb.append(SEPARATOR);
}
sb.append(Objects.requireNonNullElse(parts[i], ""));
}
return sb.toString();
}
private static String normalize(String value) {
return value == null ? "" : value;
}
}
package com.youjia.framework.sign;
/**
* 接口签名常量:请求头名、默认参数、Redis Key 前缀。
*
* <p>签名方案为 RSA 非对称加签,双向覆盖:</p>
* <ul>
* <li>请求方向:前端持「客户端私钥」加签,服务端用「客户端公钥」验签;</li>
* <li>响应方向:服务端持「服务端私钥」加签,前端用「服务端公钥」验签。</li>
* </ul>
*/
public final class SignConstants {
private SignConstants() {
}
/* ---------------- 请求头 ---------------- */
/** 应用标识(区分多个前端接入方) */
public static final String HEADER_APP_ID = "X-App-Id";
/** 请求时间戳(毫秒) */
public static final String HEADER_TIMESTAMP = "X-Timestamp";
/** 请求随机串(配合时间戳做防重放) */
public static final String HEADER_NONCE = "X-Nonce";
/** 签名值(Base64) */
public static final String HEADER_SIGN = "X-Sign";
/** 前端使用的签名算法(可选,留空取服务端默认算法) */
public static final String HEADER_SIGN_ALGORITHM = "X-Sign-Algorithm";
/** 响应签名时间戳(毫秒),参与响应验签原文 */
public static final String HEADER_SIGN_TIMESTAMP = "X-Sign-Timestamp";
/** 响应签名随机串,参与响应验签原文 */
public static final String HEADER_SIGN_NONCE = "X-Sign-Nonce";
/* ---------------- 默认值 ---------------- */
/** 默认接入方标识 */
public static final String DEFAULT_APP_ID = "youjia-web";
/** 推荐算法:SHA-256 + RSA */
public static final String ALGORITHM_SHA256_RSA = "SHA256withRSA";
/** 兼容算法:SHA-1 + RSA */
public static final String ALGORITHM_SHA1_RSA = "SHA1withRSA";
/** 兼容算法:MD5 + RSA(仅历史系统对接,不推荐) */
public static final String ALGORITHM_MD5_RSA = "MD5withRSA";
/** 默认密钥长度 */
public static final int DEFAULT_KEY_SIZE = 2048;
/** 默认密钥文件目录 */
public static final String DEFAULT_KEY_DIRECTORY = "./keys";
/** 默认时间戳有效窗口(秒) */
public static final long DEFAULT_EXPIRE_SECONDS = 300L;
/** 默认 nonce 存活时长(秒) */
public static final long DEFAULT_NONCE_EXPIRE_SECONDS = 300L;
/** 默认参与签名的请求体上限(字节),超过则待签名原文中的请求体按空串处理 */
public static final long DEFAULT_MAX_BODY_SIGN_SIZE = 2 * 1024 * 1024L;
/** 防重放 Key 前缀 */
public static final String NONCE_KEY_PREFIX = "youjia:sign:nonce:";
/* ---------------- 密钥文件名 ---------------- */
/** 服务端私钥文件名(服务端保留,用于响应加签) */
public static final String FILE_SERVER_PRIVATE = "server_private.pem";
/** 服务端公钥文件名(交付前端,用于响应验签) */
public static final String FILE_SERVER_PUBLIC = "server_public.pem";
/** 客户端私钥文件名(交付前端,用于请求加签;服务端不加载) */
public static final String FILE_CLIENT_PRIVATE = "client_private.pem";
/** 客户端公钥文件名(服务端保留,用于请求验签) */
public static final String FILE_CLIENT_PUBLIC = "client_public.pem";
/** classpath / 文件路径前缀 */
public static final String PREFIX_CLASSPATH = "classpath:";
/** 文件路径前缀 */
public static final String PREFIX_FILE = "file:";
}
package com.youjia.framework.sign;
import lombok.Getter;
/**
* 接口签名校验模式。
*/
@Getter
public enum SignModeEnum {
/**
* 严格模式:未携带签名请求头一律拦截。前端全量接入后应使用该模式。
*/
STRICT("严格模式,未携带签名一律拦截"),
/**
* 宽松模式:未携带签名请求头时放行并打印告警,一旦携带则必须验签通过。
* 用于前后端联调过渡期,避免前端改造未完成时接口全部不可用。
*/
LENIENT("宽松模式,未携带签名放行、携带则严格校验");
private final String desc;
SignModeEnum(String desc) {
this.desc = desc;
}
public static SignModeEnum of(String value) {
if (value == null || value.isBlank()) {
return STRICT;
}
for (SignModeEnum item : values()) {
if (item.name().equalsIgnoreCase(value.trim())) {
return item;
}
}
return STRICT;
}
}
package com.youjia.framework.sign.vo;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;
import java.util.List;
/**
* 服务端签名公钥视图:交付前端用于「响应验签」。
*/
@Data
@Schema(description = "服务端签名公钥(前端用于响应验签)")
public class SignPublicKeyVO {
@Schema(description = "服务端当前使用的签名算法")
private String algorithm;
@Schema(description = "允许的签名算法白名单")
private List<String> allowedAlgorithms;
@Schema(description = "密钥长度(位)")
private Integer keySize;
@Schema(description = "允许接入的应用标识(请求头 X-App-Id)")
private List<String> appIds;
@Schema(description = "请求时间戳有效窗口(秒)")
private Long expireSeconds;
@Schema(description = "是否开启 nonce 防重放")
private Boolean nonceEnabled;
@Schema(description = "服务端公钥(单行 Base64,X.509)")
private String publicKey;
@Schema(description = "服务端公钥(PEM 文本,便于直接落盘为 .pem 文件)")
private String publicKeyPem;
@Schema(description = "服务端当前时间戳(毫秒),可用于校准客户端时钟偏差")
private Long serverTime;
}
package com.youjia.framework.sign.vo;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Data;
import java.util.List;
/**
* 接口签名对接规范视图:一次性向前端暴露参数、请求头、待签名原文规则与现成示例。
*
* <p>前端实现完成后,可用 {@link Sample#getResponseCanonical()} 与
* {@link Sample#getResponseCanonicalSign()} 立即自测验签函数是否正确,
* 用 {@link Sample#getRequestCanonical()} 逐字节比对自己的原文拼接结果。</p>
*/
@Data
@Schema(description = "接口签名对接规范")
public class SignSpecVO {
@Schema(description = "服务端当前签名算法")
private String algorithm;
@Schema(description = "允许的签名算法白名单")
private List<String> allowedAlgorithms;
@Schema(description = "校验模式:STRICT 严格 / LENIENT 宽松")
private String mode;
@Schema(description = "允许接入的应用标识")
private List<String> appIds;
@Schema(description = "请求时间戳有效窗口(秒)")
private Long expireSeconds;
@Schema(description = "是否开启 nonce 防重放")
private Boolean nonceEnabled;
@Schema(description = "nonce 存活时长(秒)")
private Long nonceExpireSeconds;
@Schema(description = "参与签名的请求体上限(字节),超过则按空串摘要处理")
private Long maxBodySignSize;
@Schema(description = "免签名白名单")
private List<String> ignoreUrls;
@Schema(description = "签名请求头说明")
private List<HeaderSpec> headers;
@Schema(description = "请求方向待签名原文规则(8 行)")
private List<String> requestCanonicalRule;
@Schema(description = "响应方向待签名原文规则(4 行)")
private List<String> responseCanonicalRule;
@Schema(description = "现成示例,便于前端自测")
private Sample sample;
@Data
@Schema(description = "签名请求头说明")
public static class HeaderSpec {
@Schema(description = "请求头名称")
private String name;
@Schema(description = "是否必填")
private Boolean required;
@Schema(description = "含义说明")
private String description;
public HeaderSpec(String name, Boolean required, String description) {
this.name = name;
this.required = required;
this.description = description;
}
}
@Data
@Schema(description = "签名示例")
public static class Sample {
@Schema(description = "请求方向待签名原文示例(前端据此校验自己的拼接实现)")
private String requestCanonical;
@Schema(description = "请求示例说明")
private String requestCanonicalRemark;
@Schema(description = "响应体示例原文")
private String responseBody;
@Schema(description = "响应方向待签名原文示例")
private String responseCanonical;
@Schema(description = "响应方向示例签名值(Base64),用服务端公钥验签应通过")
private String responseCanonicalSign;
@Schema(description = "响应方向示例签名算法")
private String responseCanonicalAlgorithm;
@Schema(description = "服务端公钥(单行 Base64)")
private String serverPublicKey;
@Schema(description = "服务端公钥(PEM)")
private String serverPublicKeyPem;
}
}
package com.youjia.framework.util;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.util.StringUtils;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
/**
* Web 相关工具。
*/
public final class WebUtils {
private static final String UNKNOWN = "unknown";
private static final String[] IP_HEADERS = {
"X-Forwarded-For", "X-Real-IP", "Proxy-Client-IP", "WL-Proxy-Client-IP"
};
private WebUtils() {
}
/**
* 获取客户端真实 IP(多级代理场景取第一个非 unknown 值)。
*/
public static String getClientIp() {
ServletRequestAttributes attributes =
(ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
if (attributes == null) {
return null;
}
HttpServletRequest request = attributes.getRequest();
for (String header : IP_HEADERS) {
String ip = request.getHeader(header);
if (StringUtils.hasText(ip) && !UNKNOWN.equalsIgnoreCase(ip)) {
int index = ip.indexOf(',');
return index > 0 ? ip.substring(0, index).trim() : ip.trim();
}
}
return request.getRemoteAddr();
}
}
<?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>com.youjia</groupId>
<artifactId>YouJia</artifactId>
<version>1.0.0-SNAPSHOT</version>
</parent>
<artifactId>youjia-module-store</artifactId>
<name>youjia-module-store</name>
<description>门店上架模块:导入校验、单级审批、门店列表与变更历史</description>
<dependencies>
<dependency>
<groupId>com.youjia</groupId>
<artifactId>youjia-framework</artifactId>
</dependency>
<!-- 系统设置作为业务主线的支撑基座:复用组织数据域与账号能力 -->
<dependency>
<groupId>com.youjia</groupId>
<artifactId>youjia-module-system</artifactId>
</dependency>
<!-- Excel 导入导出 -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>easyexcel</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
</dependencies>
</project>
package com.youjia.store.constant;
import java.util.List;
/**
* 门店上架导入模板常量(《【优加】门店上架模版-V1.0.1.xlsx》:21 列 / 3 分组)。
*/
public final class StoreTemplateConstants {
private StoreTemplateConstants() {
}
/** 模板版本号,与模板内嵌标记比对 */
public static final String TEMPLATE_VERSION = "v1.0.1";
/** 模板文件名 */
public static final String TEMPLATE_FILE_NAME = "【优加】门店上架模版-V1.0.1.xlsx";
/** 单文件大小上限:10MB */
public static final long MAX_FILE_SIZE = 10L * 1024 * 1024;
/** 单文件行数上限:2000 行 */
public static final int MAX_ROW_COUNT = 2000;
/** 允许的文件扩展名 */
public static final List<String> ALLOWED_EXTENSIONS = List.of("xlsx", "xls");
/** 分组表头(三组横向合并) */
public static final List<String> GROUP_HEADERS = List.of("门店信息", "商务政策", "运营成本");
/** 表头行数:第 1 行为分组表头,第 2 行为 21 列字段名,数据从第 3 行开始 */
public static final int HEAD_ROW_NUMBER = 2;
/**
* 21 列字段名,顺序与模板完全一致(L2 表头级校验基准)。
*/
public static final List<String> COLUMNS = List.of(
"*门店名称",
"*门店商户号",
"*业务场景",
"*产品分类",
"*管理层市场费1计算模式",
"*管理层市场费1计算方式",
"*管理层市场费1",
"*管理层市场费2计算模式",
"*管理层市场费2计算方式",
"*管理层市场费2",
"*一线阳光是否开启线上积分",
"*一线阳光计算模式",
"*一线阳光计算方式",
"*一线阳光激励费",
"*一线阳光2是否开启线上积分",
"*一线阳光2计算模式",
"*一线阳光2计算方式",
"*一线阳光2激励费",
"*装修、设备总投入",
"*当月产生(房租、水电、耗材等)",
"*人工成本"
);
/** 门店名称长度上限(字符数) */
public static final int MAX_STORE_NAME_LENGTH = 50;
/** 门店商户号长度上限(字符数) */
public static final int MAX_MERCHANT_NO_LENGTH = 32;
/** 打回原因长度上限 */
public static final int MAX_REASON_LENGTH = 200;
/** 备注长度上限 */
public static final int MAX_REMARK_LENGTH = 200;
/** 数值列小数位上限 */
public static final int MAX_SCALE = 2;
}
package com.youjia.store.controller;
import com.youjia.common.core.PageResult;
import com.youjia.common.core.Result;
import com.youjia.store.dto.StoreApprovalActionDTO;
import com.youjia.store.dto.StoreApprovalTaskQueryDTO;
import com.youjia.store.dto.StoreBatchApprovalDTO;
import com.youjia.store.service.StoreApprovalService;
import com.youjia.store.vo.StoreApprovalTaskVO;
import com.youjia.store.vo.StoreListingDetailVO;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.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;
/**
* 门店审批(P05 / P06)。三个页签筛选条件一致。
*
* <p>权限码:{@code store:approve:view / store:approve:pass / store:approve:reject}</p>
*/
@Tag(name = "门店上架 · 门店审批")
@RestController
@RequestMapping("/store/approval")
@RequiredArgsConstructor
public class StoreApprovalController {
private final StoreApprovalService storeApprovalService;
@Operation(summary = "待我审批")
@GetMapping("/pending")
public Result<PageResult<StoreApprovalTaskVO>> pending(StoreApprovalTaskQueryDTO query) {
return Result.success(storeApprovalService.pagePending(query));
}
@Operation(summary = "我已办")
@GetMapping("/done")
public Result<PageResult<StoreApprovalTaskVO>> done(StoreApprovalTaskQueryDTO query) {
return Result.success(storeApprovalService.pageDone(query));
}
@Operation(summary = "我发起的")
@GetMapping("/mine")
public Result<PageResult<StoreApprovalTaskVO>> mine(StoreApprovalTaskQueryDTO query) {
return Result.success(storeApprovalService.pageMine(query));
}
@Operation(summary = "审批详情(审批态与只读态共用)")
@GetMapping("/{listingId}")
public Result<StoreListingDetailVO> detail(@PathVariable Long listingId) {
return Result.success(storeApprovalService.detail(listingId));
}
@Operation(summary = "审批通过(一次处置该门店该业务场景下全部产品分类)")
@PostMapping("/pass")
public Result<Void> pass(@Valid @RequestBody StoreApprovalActionDTO dto) {
storeApprovalService.pass(dto);
return Result.success();
}
@Operation(summary = "审批打回(原因必填)")
@PostMapping("/reject")
public Result<Void> reject(@Valid @RequestBody StoreApprovalActionDTO dto) {
storeApprovalService.reject(dto);
return Result.success();
}
@Operation(summary = "批量审批(仅支持批量通过)")
@PostMapping("/batch-pass")
public Result<Void> batchPass(@Valid @RequestBody StoreBatchApprovalDTO dto) {
storeApprovalService.batchPass(dto);
return Result.success();
}
@Operation(summary = "撤回(发起人,仅待审批)")
@PostMapping("/{listingId}/revoke")
public Result<Void> revoke(@PathVariable Long listingId) {
storeApprovalService.revoke(listingId);
return Result.success();
}
@Operation(summary = "重新提交(已打回 / 已撤回,同一记录流转)")
@PostMapping("/{listingId}/resubmit")
public Result<Void> resubmit(@PathVariable Long listingId) {
storeApprovalService.resubmit(listingId);
return Result.success();
}
@Operation(summary = "作废(已撤回 → 已作废,终态留档)")
@PostMapping("/{listingId}/void")
public Result<Void> voidListing(@PathVariable Long listingId) {
storeApprovalService.voidListing(listingId);
return Result.success();
}
}
package com.youjia.store.controller;
import com.youjia.common.core.Result;
import com.youjia.store.dto.StoreImportFailExportDTO;
import com.youjia.store.dto.StoreImportSubmitDTO;
import com.youjia.store.service.StoreImportService;
import com.youjia.store.vo.StoreImportCheckVO;
import com.youjia.store.vo.StoreImportSpecVO;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import org.springframework.http.MediaType;
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.RequestPart;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
/**
* 导入门店信息(P03,四步向导)。全部接口仅使用 GET / POST 两种请求方式。
*
* <p>权限码:{@code store:import:view / store:import:template / store:import:upload / store:import:submit}</p>
*/
@Tag(name = "门店上架 · 导入门店信息")
@RestController
@RequestMapping("/store/import")
@RequiredArgsConstructor
public class StoreImportController {
private final StoreImportService storeImportService;
@Operation(summary = "导入规范与字典(列分组、文件级限制、五级校验说明、枚举字典)")
@GetMapping("/spec")
public Result<StoreImportSpecVO> spec() {
return Result.success(storeImportService.spec());
}
@Operation(summary = "下载导入模板(V1.0.1 / 21 列,含示例 12 行)")
@GetMapping("/template")
public void template(HttpServletResponse response) {
storeImportService.writeTemplate(response);
}
@Operation(summary = "上传文件并执行五级校验")
@PostMapping(value = "/check", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
public Result<StoreImportCheckVO> check(@RequestPart("file") MultipartFile file) {
return Result.success(storeImportService.check(file));
}
@Operation(summary = "下载校验失败明细(xlsx)")
@PostMapping("/fail-export")
public void failExport(@Valid @RequestBody StoreImportFailExportDTO dto, HttpServletResponse response) {
storeImportService.writeFailDetail(dto, response);
}
@Operation(summary = "确认数据并提交审批(单次导入 1 家门店)")
@PostMapping("/submit")
public Result<Long> submit(@Valid @RequestBody StoreImportSubmitDTO dto) {
return Result.success("已提交审批", storeImportService.submit(dto));
}
}
package com.youjia.store.controller;
import com.youjia.common.core.PageResult;
import com.youjia.common.core.Result;
import com.youjia.store.dto.StoreListingQueryDTO;
import com.youjia.store.entity.StoreChangeLog;
import com.youjia.store.service.StoreListingService;
import com.youjia.store.vo.StoreListingDetailVO;
import com.youjia.store.vo.StoreListingVO;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
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;
/**
* 门店列表(P07 / P08)。仅展示审批通过(已生效)的门店数据。
*
* <p>权限码:{@code store:list:view / store:list:export}</p>
*/
@Tag(name = "门店上架 · 门店列表")
@RestController
@RequestMapping("/store/listing")
@RequiredArgsConstructor
public class StoreListingController {
private final StoreListingService storeListingService;
@Operation(summary = "门店列表分页(仅已生效数据)")
@GetMapping("/page")
public Result<PageResult<StoreListingVO>> page(StoreListingQueryDTO query) {
return Result.success(storeListingService.page(query));
}
@Operation(summary = "门店详情(5 页签数据)")
@GetMapping("/{listingId}")
public Result<StoreListingDetailVO> detail(@PathVariable Long listingId) {
return Result.success(storeListingService.detail(listingId));
}
@Operation(summary = "变更历史")
@GetMapping("/{listingId}/changes")
public Result<List<StoreChangeLog>> changes(@PathVariable Long listingId) {
return Result.success(storeListingService.changeHistory(listingId));
}
@Operation(summary = "导出门店列表(受数据域限制)")
@GetMapping("/export")
public void export(StoreListingQueryDTO query, HttpServletResponse response) {
storeListingService.export(query, response);
}
}
package com.youjia.store.dto;
import io.swagger.v3.oas.annotations.media.Schema;
import jakarta.validation.constraints.NotNull;
import jakarta.validation.constraints.Size;
import lombok.Getter;
import lombok.Setter;
/**
* 审批处置入参:通过 / 打回。
*/
@Getter
@Setter
@Schema(description = "审批处置入参")
public class StoreApprovalActionDTO {
@Schema(description = "门店上架记录 ID")
@NotNull(message = "记录 ID 不能为空")
private Long listingId;
@Schema(description = "打回原因,打回时必填")
@Size(max = 200, message = "打回原因长度不能超过 200")
private String reason;
}
package com.youjia.store.dto;
import com.youjia.common.core.PageQuery;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.Setter;
/**
* 门店审批页签查询条件。三个页签筛选条件完全一致。
*/
@Getter
@Setter
@EqualsAndHashCode(callSuper = true)
@Schema(description = "门店审批查询条件")
public class StoreApprovalTaskQueryDTO extends PageQuery {
@Schema(description = "门店名称 / 商户号,模糊匹配")
private String keyword;
@Schema(description = "产品分类")
private String productCategory;
@Schema(description = "业务场景")
private String businessScene;
@Schema(description = "提交人")
private String submitUserName;
}
package com.youjia.store.dto;
import io.swagger.v3.oas.annotations.media.Schema;
import jakarta.validation.constraints.NotEmpty;
import lombok.Getter;
import lombok.Setter;
import java.util.List;
/**
* 批量审批入参:仅支持批量「通过」,逐条记录独立流转、互不影响。
*/
@Getter
@Setter
@Schema(description = "批量审批入参")
public class StoreBatchApprovalDTO {
@Schema(description = "勾选的门店上架记录 ID 列表,至少 1 条")
@NotEmpty(message = "请至少勾选一条记录")
private List<Long> listingIds;
}
package com.youjia.store.dto;
import com.youjia.store.vo.StoreImportFailVO;
import io.swagger.v3.oas.annotations.media.Schema;
import jakarta.validation.constraints.NotEmpty;
import lombok.Getter;
import lombok.Setter;
import java.util.ArrayList;
import java.util.List;
/**
* 下载失败明细入参。
*
* <p>与 {@code /store/import/submit} 保持一致的无状态设计:由前端回传第 2 步校验结果中的失败明细,
* 服务端按标准模板结构生成 xlsx,不额外缓存解析结果。</p>
*/
@Getter
@Setter
@Schema(description = "下载失败明细入参")
public class StoreImportFailExportDTO {
@Schema(description = "门店名称(用于文件名与表头)")
private String storeName;
@Schema(description = "门店商户号")
private String merchantNo;
@Schema(description = "业务场景")
private String businessScene;
@Schema(description = "校验失败明细")
@NotEmpty(message = "失败明细不能为空")
private List<StoreImportFailVO> failures = new ArrayList<>();
}
package com.youjia.store.dto;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Getter;
import lombok.Setter;
import java.math.BigDecimal;
/**
* 校验通过并完成系统转译后的产品分类行(同时作为提交审批的入参)。
*/
@Getter
@Setter
@Schema(description = "校验通过的产品分类行")
public class StoreImportRowDTO {
@Schema(description = "产品分类(已转译为系统字典标准名)")
private String productCategory;
private String marketFee1CalcMode;
private String marketFee1CalcWay;
private BigDecimal marketFee1Value;
private String marketFee1Unit;
private String marketFee2CalcMode;
private String marketFee2CalcWay;
private BigDecimal marketFee2Value;
private String marketFee2Unit;
@Schema(description = "一线阳光是否开启线上积分:1-是 0-否")
private Integer sunshine1OnlinePoint;
private String sunshine1CalcMode;
private String sunshine1CalcWay;
private BigDecimal sunshine1Value;
private String sunshine1Unit;
@Schema(description = "一线阳光2是否开启线上积分:1-是 0-否")
private Integer sunshine2OnlinePoint;
private String sunshine2CalcMode;
private String sunshine2CalcWay;
private BigDecimal sunshine2Value;
private String sunshine2Unit;
}
package com.youjia.store.dto;
import io.swagger.v3.oas.annotations.media.Schema;
import jakarta.validation.Valid;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.NotEmpty;
import jakarta.validation.constraints.NotNull;
import jakarta.validation.constraints.Size;
import lombok.Getter;
import lombok.Setter;
import java.math.BigDecimal;
import java.util.List;
/**
* 提交审批入参。一次提交 = 一家门店的一个业务场景。
*/
@Getter
@Setter
@Schema(description = "提交审批入参")
public class StoreImportSubmitDTO {
@Schema(description = "所属组织 ID,决定数据可见范围")
@NotNull(message = "所属组织不能为空")
private Long orgId;
@Schema(description = "门店名称")
@NotBlank(message = "门店名称不能为空")
@Size(max = 50, message = "门店名称长度不能超过 50")
private String storeName;
@Schema(description = "门店商户号")
@NotBlank(message = "门店商户号不能为空")
@Size(max = 32, message = "门店商户号长度不能超过 32")
private String merchantNo;
@Schema(description = "业务场景")
@NotBlank(message = "业务场景不能为空")
private String businessScene;
@Schema(description = "装修、设备总投入")
private BigDecimal costDecoration;
@Schema(description = "当月产生费用")
private BigDecimal costMonthly;
@Schema(description = "人工成本")
private BigDecimal costLabor;
@Schema(description = "备注")
@Size(max = 200, message = "备注长度不能超过 200")
private String remark;
@Schema(description = "产品分类行(校验通过行)")
@NotEmpty(message = "至少需要一行产品分类数据")
@Valid
private List<StoreImportRowDTO> rows;
}
package com.youjia.store.dto;
import com.youjia.common.core.PageQuery;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.Setter;
import java.time.LocalDate;
/**
* 门店列表查询条件(4 项)。
*/
@Getter
@Setter
@EqualsAndHashCode(callSuper = true)
@Schema(description = "门店列表查询条件")
public class StoreListingQueryDTO extends PageQuery {
@Schema(description = "门店名称,模糊匹配")
private String storeName;
@Schema(description = "门店商户号,模糊匹配")
private String merchantNo;
@Schema(description = "业务场景")
private String businessScene;
@Schema(description = "上架时间起(含)")
private LocalDate startDate;
@Schema(description = "上架时间止(含)")
private LocalDate endDate;
}
package com.youjia.store.entity;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import com.youjia.common.entity.BaseEntity;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.Setter;
import java.time.LocalDateTime;
/**
* 审批留痕(store_approval_log)。
*
* <p>每次动作记录「操作人 / 角色 / 动作 / 时间 / 原因 / 操作前后状态 / IP」,
* 仅追加、不可编辑或删除。</p>
*/
@Getter
@Setter
@EqualsAndHashCode(callSuper = true)
@TableName("store_approval_log")
@Schema(description = "审批留痕")
public class StoreApprovalLog extends BaseEntity {
@TableId(value = "log_id", type = IdType.AUTO)
private Long logId;
@Schema(description = "门店上架记录 ID")
private Long listingId;
@Schema(description = "动作:SUBMIT / PASS / REJECT / REVOKE / RESUBMIT / VOID / BATCH_PASS")
private String action;
@Schema(description = "操作人 ID")
private Long operatorId;
@Schema(description = "操作人姓名")
private String operatorName;
@Schema(description = "操作人角色")
private String operatorRole;
@Schema(description = "操作前状态")
private String preStatus;
@Schema(description = "操作后状态")
private String postStatus;
@Schema(description = "原因 / 审批意见")
private String reason;
@Schema(description = "操作时间")
private LocalDateTime operateTime;
@Schema(description = "操作 IP")
private String operateIp;
}
package com.youjia.store.entity;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import com.youjia.common.entity.BaseEntity;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.Setter;
import java.time.LocalDateTime;
/**
* 门店变更历史(store_change_log)。按时间倒序展示:版本号、变更字段(前值 → 新值)、变更人、生效时间。
*/
@Getter
@Setter
@EqualsAndHashCode(callSuper = true)
@TableName("store_change_log")
@Schema(description = "门店变更历史")
public class StoreChangeLog extends BaseEntity {
@TableId(value = "change_id", type = IdType.AUTO)
private Long changeId;
@Schema(description = "门店上架记录 ID")
private Long listingId;
@Schema(description = "版本号")
private Integer versionNo;
@Schema(description = "变更字段")
private String changeField;
@Schema(description = "变更前值")
private String beforeValue;
@Schema(description = "变更后值")
private String afterValue;
@Schema(description = "变更人 ID")
private Long changeUserId;
@Schema(description = "变更人姓名")
private String changeUserName;
@Schema(description = "生效时间")
private LocalDateTime effectiveTime;
}
package com.youjia.store.entity;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import com.baomidou.mybatisplus.annotation.Version;
import com.youjia.common.entity.BaseEntity;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.Setter;
import java.math.BigDecimal;
import java.time.LocalDateTime;
/**
* 门店上架记录(store_listing)。
*
* <p>一条记录 = 一家门店的一个业务场景,内部再细分到 N 个产品分类行
* (见 {@link StoreListingItem})。唯一项 = 门店商户号 + 业务场景。</p>
*/
@Getter
@Setter
@EqualsAndHashCode(callSuper = true)
@TableName("store_listing")
@Schema(description = "门店上架记录(门店 × 业务场景)")
public class StoreListing extends BaseEntity {
@TableId(value = "listing_id", type = IdType.AUTO)
private Long listingId;
@Schema(description = "门店名称(营业执照全称,全系统唯一)")
private String storeName;
@Schema(description = "门店商户号")
private String merchantNo;
@Schema(description = "业务场景:售后会员权益升级 / 售前延保")
private String businessScene;
@Schema(description = "产品分类数")
private Integer categoryCount;
@Schema(description = "装修、设备总投入(门店维度)")
private BigDecimal costDecoration;
@Schema(description = "当月产生费用(门店维度)")
private BigDecimal costMonthly;
@Schema(description = "人工成本(门店维度,按人力成本维度合并填写)")
private BigDecimal costLabor;
@Schema(description = "运营成本合计 = 装修设备 + 当月产生 + 人工成本")
private BigDecimal costTotal;
@Schema(description = "状态:PENDING / APPROVED / REJECTED / REVOKED / VOID")
private String status;
@Schema(description = "所属组织 ID,决定数据可见范围")
private Long orgId;
@Schema(description = "提交人 ID")
private Long submitUserId;
@Schema(description = "提交人姓名")
private String submitUserName;
@Schema(description = "提交时间")
private LocalDateTime submitTime;
@Schema(description = "审批人 ID")
private Long approveUserId;
@Schema(description = "审批人姓名")
private String approveUserName;
@Schema(description = "审批时间")
private LocalDateTime approveTime;
@Schema(description = "打回原因(打回时必填)")
private String rejectReason;
@Schema(description = "生效时间(审批通过时写入)")
private LocalDateTime effectiveTime;
@Schema(description = "变更次数")
private Integer changeCount;
@Schema(description = "备注")
private String remark;
@Version
@Schema(description = "乐观锁版本号")
private Integer version;
}
package com.youjia.store.entity;
import com.baomidou.mybatisplus.annotation.IdType;
import com.baomidou.mybatisplus.annotation.TableId;
import com.baomidou.mybatisplus.annotation.TableName;
import com.youjia.common.entity.BaseEntity;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.EqualsAndHashCode;
import lombok.Getter;
import lombok.Setter;
import java.math.BigDecimal;
/**
* 门店上架 · 产品分类明细(store_listing_item)。
*
* <p>一行 = 一个产品分类;管理层市场费与一线阳光激励各支持 1 / 2 两组政策。</p>
*/
@Getter
@Setter
@EqualsAndHashCode(callSuper = true)
@TableName("store_listing_item")
@Schema(description = "门店上架 · 产品分类明细")
public class StoreListingItem extends BaseEntity {
@TableId(value = "item_id", type = IdType.AUTO)
private Long itemId;
@Schema(description = "所属门店上架记录 ID")
private Long listingId;
@Schema(description = "产品分类")
private String productCategory;
/* ---------------- 管理层市场费 ---------------- */
@Schema(description = "管理层市场费1计算模式")
private String marketFee1CalcMode;
@Schema(description = "管理层市场费1计算方式")
private String marketFee1CalcWay;
@Schema(description = "管理层市场费1数值")
private BigDecimal marketFee1Value;
@Schema(description = "管理层市场费1单位:RATIO-比例,AMOUNT-金额")
private String marketFee1Unit;
@Schema(description = "管理层市场费2计算模式")
private String marketFee2CalcMode;
@Schema(description = "管理层市场费2计算方式")
private String marketFee2CalcWay;
@Schema(description = "管理层市场费2数值")
private BigDecimal marketFee2Value;
@Schema(description = "管理层市场费2单位")
private String marketFee2Unit;
/* ---------------- 一线阳光激励 ---------------- */
@Schema(description = "一线阳光是否开启线上积分:1-是 0-否")
private Integer sunshine1OnlinePoint;
@Schema(description = "一线阳光计算模式")
private String sunshine1CalcMode;
@Schema(description = "一线阳光计算方式")
private String sunshine1CalcWay;
@Schema(description = "一线阳光激励费")
private BigDecimal sunshine1Value;
@Schema(description = "一线阳光激励费单位")
private String sunshine1Unit;
@Schema(description = "一线阳光2是否开启线上积分:1-是 0-否")
private Integer sunshine2OnlinePoint;
@Schema(description = "一线阳光2计算模式")
private String sunshine2CalcMode;
@Schema(description = "一线阳光2计算方式")
private String sunshine2CalcWay;
@Schema(description = "一线阳光2激励费")
private BigDecimal sunshine2Value;
@Schema(description = "一线阳光2激励费单位")
private String sunshine2Unit;
}
package com.youjia.store.excel;
import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.alibaba.excel.metadata.data.ReadCellData;
import com.youjia.store.constant.StoreTemplateConstants;
import lombok.Getter;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
/**
* 导入文件读取监听器:收集表头(L2 表头级校验)与数据行。
*/
@Getter
public class StoreImportExcelListener extends AnalysisEventListener<StoreImportExcelRow> {
/** 表头行集合:列序号 -> 列名(分组表头行 + 字段名行) */
private final List<Map<Integer, String>> headRows = new ArrayList<>();
/** 数据行,按文件顺序 */
private final List<StoreImportExcelRow> rows = new ArrayList<>();
/** 数据行在文件中的物理行号(含表头偏移,用于失败明细定位) */
private final List<Integer> rowIndexes = new ArrayList<>();
@Override
public void invokeHeadMap(Map<Integer, String> headMap, AnalysisContext context) {
this.headRows.add(new LinkedHashMap<>(headMap));
}
@Override
public void invokeHead(Map<Integer, ReadCellData<?>> headMap, AnalysisContext context) {
Map<Integer, String> row = new LinkedHashMap<>();
headMap.forEach((index, cell) -> row.put(index, cell.getStringValue()));
this.headRows.add(row);
}
@Override
public void invoke(StoreImportExcelRow data, AnalysisContext context) {
rows.add(data);
rowIndexes.add(context.readRowHolder().getRowIndex() + 1);
}
@Override
public void doAfterAllAnalysed(AnalysisContext context) {
// 数据已在 invoke 中收集,无需额外处理
}
/**
* 取字段名行:优先返回与系统模板 21 列列名完全一致的那一行;
* 若不存在,则退化为列数匹配的行,供 L2 校验报告差异。
*/
public Map<Integer, String> getFieldHeadRow() {
for (Map<Integer, String> row : headRows) {
boolean matched = true;
for (int i = 0; i < StoreTemplateConstants.COLUMNS.size(); i++) {
if (!StoreTemplateConstants.COLUMNS.get(i).equals(row.get(i))) {
matched = false;
break;
}
}
if (matched) {
return row;
}
}
return headRows.stream()
.filter(row -> row.size() == StoreTemplateConstants.COLUMNS.size())
.findFirst()
.orElse(headRows.isEmpty() ? new LinkedHashMap<>() : headRows.get(headRows.size() - 1));
}
}
package com.youjia.store.excel;
import com.alibaba.excel.annotation.ExcelIgnoreUnannotated;
import com.alibaba.excel.annotation.ExcelProperty;
import lombok.Data;
/**
* 导入模板行模型(21 列,按列序号定位)。
*
* <p>全部按 String 读取:模板中数值列允许带「%」、千分位与货币符号,
* 由校验器统一解析为「数值 + 单位」的二元组后再落库。</p>
*/
@Data
@ExcelIgnoreUnannotated
public class StoreImportExcelRow {
@ExcelProperty(value = "*门店名称", index = 0)
private String storeName;
@ExcelProperty(value = "*门店商户号", index = 1)
private String merchantNo;
@ExcelProperty(value = "*业务场景", index = 2)
private String businessScene;
@ExcelProperty(value = "*产品分类", index = 3)
private String productCategory;
@ExcelProperty(value = "*管理层市场费1计算模式", index = 4)
private String marketFee1CalcMode;
@ExcelProperty(value = "*管理层市场费1计算方式", index = 5)
private String marketFee1CalcWay;
@ExcelProperty(value = "*管理层市场费1", index = 6)
private String marketFee1Value;
@ExcelProperty(value = "*管理层市场费2计算模式", index = 7)
private String marketFee2CalcMode;
@ExcelProperty(value = "*管理层市场费2计算方式", index = 8)
private String marketFee2CalcWay;
@ExcelProperty(value = "*管理层市场费2", index = 9)
private String marketFee2Value;
@ExcelProperty(value = "*一线阳光是否开启线上积分", index = 10)
private String sunshine1OnlinePoint;
@ExcelProperty(value = "*一线阳光计算模式", index = 11)
private String sunshine1CalcMode;
@ExcelProperty(value = "*一线阳光计算方式", index = 12)
private String sunshine1CalcWay;
@ExcelProperty(value = "*一线阳光激励费", index = 13)
private String sunshine1Value;
@ExcelProperty(value = "*一线阳光2是否开启线上积分", index = 14)
private String sunshine2OnlinePoint;
@ExcelProperty(value = "*一线阳光2计算模式", index = 15)
private String sunshine2CalcMode;
@ExcelProperty(value = "*一线阳光2计算方式", index = 16)
private String sunshine2CalcWay;
@ExcelProperty(value = "*一线阳光2激励费", index = 17)
private String sunshine2Value;
@ExcelProperty(value = "*装修、设备总投入", index = 18)
private String costDecoration;
@ExcelProperty(value = "*当月产生(房租、水电、耗材等)", index = 19)
private String costMonthly;
@ExcelProperty(value = "*人工成本", index = 20)
private String costLabor;
}
package com.youjia.store.excel;
import com.alibaba.excel.annotation.ExcelProperty;
import com.alibaba.excel.annotation.write.style.ColumnWidth;
import lombok.Data;
import java.math.BigDecimal;
import java.time.LocalDateTime;
/**
* 门店列表导出模型(仅「已生效」数据,受数据域限制)。
*/
@Data
public class StoreListingExcelRow {
@ExcelProperty("门店名称")
@ColumnWidth(38)
private String storeName;
@ExcelProperty("门店商户号")
@ColumnWidth(18)
private String merchantNo;
@ExcelProperty("业务场景")
@ColumnWidth(22)
private String businessScene;
@ExcelProperty("上架时间")
@ColumnWidth(22)
private LocalDateTime effectiveTime;
@ExcelProperty("变更次数")
@ColumnWidth(12)
private Integer changeCount;
@ExcelProperty("运营成本合计(元)")
@ColumnWidth(18)
private BigDecimal costTotal;
}
package com.youjia.store.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.youjia.store.entity.StoreApprovalLog;
import org.apache.ibatis.annotations.Mapper;
/**
* 审批留痕 Mapper。
*/
@Mapper
public interface StoreApprovalLogMapper extends BaseMapper<StoreApprovalLog> {
}
package com.youjia.store.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.youjia.store.entity.StoreChangeLog;
import org.apache.ibatis.annotations.Mapper;
/**
* 门店变更历史 Mapper。
*/
@Mapper
public interface StoreChangeLogMapper extends BaseMapper<StoreChangeLog> {
}
package com.youjia.store.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.youjia.store.entity.StoreListingItem;
import org.apache.ibatis.annotations.Mapper;
/**
* 门店上架产品分类明细 Mapper。
*/
@Mapper
public interface StoreListingItemMapper extends BaseMapper<StoreListingItem> {
}
package com.youjia.store.mapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.youjia.store.entity.StoreListing;
import org.apache.ibatis.annotations.Mapper;
/**
* 门店上架记录 Mapper。
*/
@Mapper
public interface StoreListingMapper extends BaseMapper<StoreListing> {
}
package com.youjia.store.service;
import com.youjia.common.core.PageResult;
import com.youjia.store.dto.StoreApprovalActionDTO;
import com.youjia.store.dto.StoreApprovalTaskQueryDTO;
import com.youjia.store.dto.StoreBatchApprovalDTO;
import com.youjia.store.vo.StoreApprovalTaskVO;
import com.youjia.store.vo.StoreListingDetailVO;
/**
* 门店审批服务(单级审批:提交 → 优加财务经理 → 生效)。
*/
public interface StoreApprovalService {
/** 待我审批 */
PageResult<StoreApprovalTaskVO> pagePending(StoreApprovalTaskQueryDTO query);
/** 我已办 */
PageResult<StoreApprovalTaskVO> pageDone(StoreApprovalTaskQueryDTO query);
/** 我发起的 */
PageResult<StoreApprovalTaskVO> pageMine(StoreApprovalTaskQueryDTO query);
/** 审批详情(审批态与只读态共用同一份渲染) */
StoreListingDetailVO detail(Long listingId);
/** 审批通过:一次处置该门店该业务场景下全部产品分类,通过后即刻写入门店列表 */
void pass(StoreApprovalActionDTO dto);
/** 审批打回:打回原因必填,退回该场景下全部产品分类 */
void reject(StoreApprovalActionDTO dto);
/** 批量审批:仅支持批量通过,逐条独立流转 */
void batchPass(StoreBatchApprovalDTO dto);
/** 发起人撤回(仅「待审批」可撤回) */
void revoke(Long listingId);
/** 重新提交(「已打回 / 已撤回」→「待审批」,同一记录流转不新建) */
void resubmit(Long listingId);
/** 作废(「已撤回」→「已作废」,终态留档) */
void voidListing(Long listingId);
}
package com.youjia.store.service;
import com.youjia.store.dto.StoreImportFailExportDTO;
import com.youjia.store.dto.StoreImportSubmitDTO;
import com.youjia.store.vo.StoreImportCheckVO;
import com.youjia.store.vo.StoreImportSpecVO;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.web.multipart.MultipartFile;
/**
* 门店信息导入服务(导入向导第 1 ~ 4 步)。
*/
public interface StoreImportService {
/**
* 导入规范与字典:模板结构、文件级限制、五级校验说明与全部枚举字典。
*
* <p>供导入页「查看导入规范」以及审批 / 列表页的筛选下拉使用,前端不再硬编码枚举。</p>
*/
StoreImportSpecVO spec();
/**
* 下载《【优加】门店上架模版-V1.0.1.xlsx》:首行三组横向合并的分组表头,
* 第二行 21 列字段名,数据从第 3 行开始(示例 2 个业务场景 × 6 个产品分类,共 12 行)。
*/
void writeTemplate(HttpServletResponse response);
/**
* 上传文件并执行五级校验。
*/
StoreImportCheckVO check(MultipartFile file);
/**
* 下载校验失败明细(xlsx)。
*/
void writeFailDetail(StoreImportFailExportDTO dto, HttpServletResponse response);
/**
* 提交审批:创建门店上架记录(门店 × 业务场景)+ 产品分类明细 + 审批留痕,状态置为「待审批」。
*
* @return 门店上架记录 ID
*/
Long submit(StoreImportSubmitDTO dto);
}
package com.youjia.store.service;
import com.youjia.common.core.PageResult;
import com.youjia.store.dto.StoreListingQueryDTO;
import com.youjia.store.entity.StoreChangeLog;
import com.youjia.store.vo.StoreListingDetailVO;
import com.youjia.store.vo.StoreListingVO;
import jakarta.servlet.http.HttpServletResponse;
import java.util.List;
/**
* 门店列表服务。列表仅展示状态为「已生效」的门店数据。
*/
public interface StoreListingService {
PageResult<StoreListingVO> page(StoreListingQueryDTO query);
StoreListingDetailVO detail(Long listingId);
List<StoreChangeLog> changeHistory(Long listingId);
/**
* 导出当前筛选结果(受数据域限制),上限 5 万行。
*/
void export(StoreListingQueryDTO query, HttpServletResponse response);
}
package com.youjia.store.service.impl;
import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.youjia.common.core.PageResult;
import com.youjia.common.core.ResultCode;
import com.youjia.common.enums.StoreStatusEnum;
import com.youjia.common.exception.BusinessException;
import com.youjia.framework.security.CurrentUserHolder;
import com.youjia.store.dto.StoreListingQueryDTO;
import com.youjia.store.entity.StoreChangeLog;
import com.youjia.store.entity.StoreListing;
import com.youjia.store.excel.StoreListingExcelRow;
import com.youjia.store.mapper.StoreChangeLogMapper;
import com.youjia.store.mapper.StoreListingMapper;
import com.youjia.store.service.StoreListingService;
import com.youjia.store.support.StoreListingAssembler;
import com.youjia.store.vo.StoreListingDetailVO;
import com.youjia.store.vo.StoreListingVO;
import com.youjia.system.support.DataScopeHelper;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.time.LocalTime;
import java.util.List;
/**
* 门店列表服务实现。
*/
@Slf4j
@Service
@RequiredArgsConstructor
public class StoreListingServiceImpl implements StoreListingService {
private static final long EXPORT_MAX_ROWS = 50_000L;
private final StoreListingMapper storeListingMapper;
private final StoreChangeLogMapper storeChangeLogMapper;
private final StoreListingAssembler storeListingAssembler;
private final DataScopeHelper dataScopeHelper;
@Override
public PageResult<StoreListingVO> page(StoreListingQueryDTO query) {
Page<StoreListing> page = storeListingMapper.selectPage(
new Page<>(query.getCurrent(), query.getSize()), buildWrapper(query));
List<StoreListingVO> records = page.getRecords().stream()
.map(storeListingAssembler::toListVO).toList();
return PageResult.of(records, page.getTotal(), page.getCurrent(), page.getSize());
}
@Override
public StoreListingDetailVO detail(Long listingId) {
StoreListing listing = requireListing(listingId);
return storeListingAssembler.toDetailVO(listing);
}
@Override
public List<StoreChangeLog> changeHistory(Long listingId) {
requireListing(listingId);
return storeChangeLogMapper.selectList(new LambdaQueryWrapper<StoreChangeLog>()
.eq(StoreChangeLog::getListingId, listingId)
.orderByDesc(StoreChangeLog::getVersionNo));
}
@Override
public void export(StoreListingQueryDTO query, HttpServletResponse response) {
LambdaQueryWrapper<StoreListing> wrapper = buildWrapper(query).last("limit " + EXPORT_MAX_ROWS);
List<StoreListingExcelRow> rows = storeListingMapper.selectList(wrapper).stream()
.map(this::toExcelRow).toList();
try {
response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
response.setCharacterEncoding(StandardCharsets.UTF_8.name());
String fileName = URLEncoder.encode("优加门店上架列表.xlsx", StandardCharsets.UTF_8);
response.setHeader("Content-Disposition", "attachment;filename*=utf-8''" + fileName);
EasyExcel.write(response.getOutputStream(), StoreListingExcelRow.class)
.sheet("门店列表")
.doWrite(rows);
} catch (IOException e) {
throw new BusinessException(ResultCode.FAIL, "导出失败:" + e.getMessage());
}
// 说明:超过 5 万行时应改为异步生成 + 企业微信推送下载链接
}
// ------------------------------------------------------------ 私有方法
private LambdaQueryWrapper<StoreListing> buildWrapper(StoreListingQueryDTO query) {
LambdaQueryWrapper<StoreListing> wrapper = new LambdaQueryWrapper<StoreListing>()
// 门店列表仅展示「已生效」数据
.eq(StoreListing::getStatus, StoreStatusEnum.APPROVED.getCode())
.like(StringUtils.hasText(query.getStoreName()), StoreListing::getStoreName, query.getStoreName())
.like(StringUtils.hasText(query.getMerchantNo()), StoreListing::getMerchantNo, query.getMerchantNo())
.eq(StringUtils.hasText(query.getBusinessScene()), StoreListing::getBusinessScene, query.getBusinessScene())
.ge(query.getStartDate() != null, StoreListing::getEffectiveTime,
query.getStartDate() == null ? null : query.getStartDate().atStartOfDay())
.le(query.getEndDate() != null, StoreListing::getEffectiveTime,
query.getEndDate() == null ? null : query.getEndDate().atTime(LocalTime.MAX))
.orderByDesc(StoreListing::getEffectiveTime);
List<Long> visibleOrgIds = dataScopeHelper.resolveVisibleOrgIds();
if (visibleOrgIds != null) {
wrapper.in(StoreListing::getOrgId, visibleOrgIds.isEmpty() ? List.of(-1L) : visibleOrgIds);
}
if (dataScopeHelper.isSelfOnly()) {
wrapper.eq(StoreListing::getSubmitUserId, CurrentUserHolder.getUserId());
}
return wrapper;
}
private StoreListing requireListing(Long listingId) {
StoreListing listing = storeListingMapper.selectById(listingId);
if (listing == null) {
throw new BusinessException(ResultCode.STORE_LISTING_NOT_FOUND);
}
return listing;
}
private StoreListingExcelRow toExcelRow(StoreListing listing) {
StoreListingExcelRow row = new StoreListingExcelRow();
row.setStoreName(listing.getStoreName());
row.setMerchantNo(listing.getMerchantNo());
row.setBusinessScene(listing.getBusinessScene());
row.setEffectiveTime(listing.getEffectiveTime());
row.setChangeCount(listing.getChangeCount());
row.setCostTotal(listing.getCostTotal());
return row;
}
}
package com.youjia.store.support;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.youjia.common.enums.StoreStatusEnum;
import com.youjia.store.entity.StoreApprovalLog;
import com.youjia.store.entity.StoreChangeLog;
import com.youjia.store.entity.StoreListing;
import com.youjia.store.entity.StoreListingItem;
import com.youjia.store.mapper.StoreApprovalLogMapper;
import com.youjia.store.mapper.StoreChangeLogMapper;
import com.youjia.store.mapper.StoreListingItemMapper;
import com.youjia.store.vo.StoreApprovalTaskVO;
import com.youjia.store.vo.StoreListingDetailVO;
import com.youjia.store.vo.StoreListingVO;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;
import java.time.Duration;
import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;
/**
* 门店上架记录装配器:把实体转成视图对象,集中处理明细 / 留痕 / 变更历史的组装。
*/
@Component
@RequiredArgsConstructor
public class StoreListingAssembler {
private static final long WARNING_HOURS = 24L;
private static final long DANGER_HOURS = 48L;
private final StoreListingItemMapper storeListingItemMapper;
private final StoreChangeLogMapper storeChangeLogMapper;
private final StoreApprovalLogMapper storeApprovalLogMapper;
public StoreListingVO toListVO(StoreListing listing) {
StoreListingVO vo = new StoreListingVO();
vo.setListingId(listing.getListingId());
vo.setStoreName(listing.getStoreName());
vo.setMerchantNo(listing.getMerchantNo());
vo.setBusinessScene(listing.getBusinessScene());
vo.setEffectiveTime(listing.getEffectiveTime());
vo.setChangeCount(listing.getChangeCount());
vo.setCostTotal(listing.getCostTotal());
return vo;
}
public StoreApprovalTaskVO toTaskVO(StoreListing listing) {
StoreApprovalTaskVO vo = new StoreApprovalTaskVO();
vo.setListingId(listing.getListingId());
vo.setStoreName(listing.getStoreName());
vo.setMerchantNo(listing.getMerchantNo());
vo.setBusinessScene(listing.getBusinessScene());
vo.setCategoryCount(listing.getCategoryCount());
vo.setCostTotal(listing.getCostTotal());
vo.setSubmitUserName(listing.getSubmitUserName());
vo.setSubmitTime(listing.getSubmitTime());
vo.setStatus(listing.getStatus());
vo.setRejectReason(listing.getRejectReason());
vo.setStatusLabel(StoreStatusEnum.of(listing.getStatus())
.map(StoreStatusEnum::getDesc).orElse(listing.getStatus()));
vo.setProductCategories(listItems(listing.getListingId()).stream()
.map(StoreListingItem::getProductCategory).collect(Collectors.toList()));
// 「我已办」列:单级审批下审批时间 / 意见即本人动作的留痕
vo.setHandleTime(listing.getApproveTime());
if (StoreStatusEnum.APPROVED.getCode().equals(listing.getStatus())) {
vo.setMyAction("PASS");
vo.setMyActionLabel("通过");
vo.setHandleOpinion("审批通过");
} else if (StoreStatusEnum.REJECTED.getCode().equals(listing.getStatus())) {
vo.setMyAction("REJECT");
vo.setMyActionLabel("打回");
vo.setHandleOpinion(listing.getRejectReason());
}
if (listing.getSubmitTime() != null) {
long hours = Duration.between(listing.getSubmitTime(), LocalDateTime.now()).toHours();
vo.setPendingHours(hours);
if (hours > DANGER_HOURS) {
vo.setTimeoutLevel("DANGER");
} else if (hours > WARNING_HOURS) {
vo.setTimeoutLevel("WARNING");
} else {
vo.setTimeoutLevel("NORMAL");
}
} else {
vo.setTimeoutLevel("NORMAL");
}
vo.setActionable(StoreStatusEnum.PENDING.getCode().equals(listing.getStatus()));
return vo;
}
public StoreListingDetailVO toDetailVO(StoreListing listing) {
StoreListingDetailVO vo = new StoreListingDetailVO();
vo.setListingId(listing.getListingId());
vo.setStoreName(listing.getStoreName());
vo.setMerchantNo(listing.getMerchantNo());
vo.setBusinessScene(listing.getBusinessScene());
vo.setCategoryCount(listing.getCategoryCount());
vo.setStatus(listing.getStatus());
vo.setStatusLabel(StoreStatusEnum.of(listing.getStatus())
.map(StoreStatusEnum::getDesc).orElse(listing.getStatus()));
vo.setEffectiveTime(listing.getEffectiveTime());
vo.setSubmitTime(listing.getSubmitTime());
vo.setSubmitUserName(listing.getSubmitUserName());
vo.setApproveTime(listing.getApproveTime());
vo.setApproveUserName(listing.getApproveUserName());
vo.setRejectReason(listing.getRejectReason());
vo.setCostDecoration(listing.getCostDecoration());
vo.setCostMonthly(listing.getCostMonthly());
vo.setCostLabor(listing.getCostLabor());
vo.setCostTotal(listing.getCostTotal());
vo.setItems(listItems(listing.getListingId()));
vo.setChangeHistory(storeChangeLogMapper.selectList(new LambdaQueryWrapper<StoreChangeLog>()
.eq(StoreChangeLog::getListingId, listing.getListingId())
.orderByDesc(StoreChangeLog::getVersionNo)));
vo.setApprovalLogs(storeApprovalLogMapper.selectList(new LambdaQueryWrapper<StoreApprovalLog>()
.eq(StoreApprovalLog::getListingId, listing.getListingId())
.orderByAsc(StoreApprovalLog::getOperateTime)));
return vo;
}
public List<StoreListingItem> listItems(Long listingId) {
return storeListingItemMapper.selectList(new LambdaQueryWrapper<StoreListingItem>()
.eq(StoreListingItem::getListingId, listingId)
.orderByAsc(StoreListingItem::getItemId));
}
}
package com.youjia.store.vo;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
/**
* 通用字典选项(业务场景 / 产品分类 / 计算模式 / 计算方式 / 是否开启线上积分)。
*
* <p>同时服务于「导入门店信息」页的取值说明与「门店审批」「门店列表」页的筛选下拉,
* 避免前端硬编码枚举、与后端字典漂移。</p>
*/
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
@Schema(description = "字典选项")
public class DictOptionVO {
@Schema(description = "选项值(落库值,与枚举名一致)")
private String value;
@Schema(description = "选项文案(页面展示,与模板单元格取值一致)")
private String label;
@Schema(description = "附加说明,如计算方式的数值口径 RATIO / AMOUNT")
private String extra;
}
package com.youjia.store.vo;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
import java.util.ArrayList;
import java.util.List;
/**
* 模板分组表头(首行三组横向合并)。
*/
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
@Schema(description = "模板分组表头")
public class HeaderGroupVO {
@Schema(description = "分组名称:门店信息 / 商务政策 / 运营成本")
private String groupName;
@Schema(description = "该分组下的列数")
private Integer columnCount;
@Schema(description = "该分组下的字段名(含 * 前缀)")
private List<String> columns = new ArrayList<>();
}
package com.youjia.store.vo;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Getter;
import lombok.Setter;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
/**
* 门店审批待办 / 已办 / 我发起的 列表视图。
*
* <p>一行 = 一个门店 × 一个业务场景;同一门店的多个业务场景拆为多条独立待办、独立审批。</p>
*/
@Getter
@Setter
@Schema(description = "门店审批列表视图")
public class StoreApprovalTaskVO {
private Long listingId;
private String storeName;
private String merchantNo;
@Schema(description = "该记录覆盖的全部产品分类")
private List<String> productCategories = new ArrayList<>();
private Integer categoryCount;
private String businessScene;
private BigDecimal costTotal;
private String submitUserName;
private LocalDateTime submitTime;
@Schema(description = "停留时长(小时)")
private Long pendingHours;
@Schema(description = "停留时长预警:NORMAL / WARNING(>24h) / DANGER(>48h)")
private String timeoutLevel;
private String status;
private String statusLabel;
private String rejectReason;
@Schema(description = "「我已办」我的动作编码:PASS-通过 REJECT-打回")
private String myAction;
@Schema(description = "「我已办」我的动作文案")
private String myActionLabel;
@Schema(description = "「我已办」处理时间(取审批时间)")
private LocalDateTime handleTime;
@Schema(description = "「我已办」处理意见(打回时取打回原因)")
private String handleOpinion;
@Schema(description = "当前登录人是否可处置(数据域内且状态为待审批)")
private Boolean actionable;
}
package com.youjia.store.vo;
import com.youjia.store.dto.StoreImportRowDTO;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Getter;
import lombok.Setter;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
/**
* 导入校验结果(第 2 步「数据校验」返回)。
*/
@Getter
@Setter
@Schema(description = "导入校验结果")
public class StoreImportCheckVO {
@Schema(description = "模板版本")
private String templateVersion;
@Schema(description = "表头是否通过 L2 校验")
private Boolean headerValid = Boolean.TRUE;
@Schema(description = "表头差异说明")
private String headerMessage;
@Schema(description = "共解析行数")
private Integer totalRows = 0;
@Schema(description = "通过行数")
private Integer passRows = 0;
@Schema(description = "失败行数")
private Integer failRows = 0;
@Schema(description = "门店名称")
private String storeName;
@Schema(description = "门店商户号")
private String merchantNo;
@Schema(description = "业务场景")
private String businessScene;
@Schema(description = "装修、设备总投入")
private BigDecimal costDecoration;
@Schema(description = "当月产生费用")
private BigDecimal costMonthly;
@Schema(description = "人工成本")
private BigDecimal costLabor;
@Schema(description = "运营成本合计")
private BigDecimal costTotal;
@Schema(description = "失败明细")
private List<StoreImportFailVO> failures = new ArrayList<>();
@Schema(description = "通过行(系统转译后,可编辑后再提交)")
private List<StoreImportRowDTO> previewRows = new ArrayList<>();
}
package com.youjia.store.vo;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;
/**
* 校验失败明细行。
*
* <p>一行失败明细对应一个失败层级,供「校验失败明细」表格的「校验层级」列展示。</p>
*/
@Getter
@Setter
@NoArgsConstructor
@AllArgsConstructor
@Schema(description = "校验失败明细")
public class StoreImportFailVO {
@Schema(description = "文件中的物理行号,L5 全表拦截时为空")
private Integer rowIndex;
private String storeName;
private String merchantNo;
private String productCategory;
@Schema(description = "校验层级编码:L3-单元格级 L4-业务级 L5-重复上架级")
private String levelCode;
@Schema(description = "校验层级文案:如「L4 业务级」")
private String levelLabel;
@Schema(description = "失败原因")
private String reason;
public StoreImportFailVO(Integer rowIndex, String storeName, String merchantNo,
String productCategory, String reason) {
this.rowIndex = rowIndex;
this.storeName = storeName;
this.merchantNo = merchantNo;
this.productCategory = productCategory;
this.reason = reason;
}
public StoreImportFailVO level(String levelCode, String levelLabel) {
this.levelCode = levelCode;
this.levelLabel = levelLabel;
return this;
}
}
package com.youjia.store.vo;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Getter;
import lombok.Setter;
import java.util.ArrayList;
import java.util.List;
/**
* 导入规范与字典(P03「查看导入规范」按钮 + 各页筛选下拉数据源)。
*
* <p>由单个接口一次性下发模板结构、文件级限制与全部枚举字典,前端无需硬编码。</p>
*/
@Getter
@Setter
@Schema(description = "导入规范与字典")
public class StoreImportSpecVO {
@Schema(description = "模板版本")
private String templateVersion;
@Schema(description = "模板文件名")
private String templateFileName;
@Schema(description = "总列数")
private Integer totalColumns;
@Schema(description = "表头行数(分组表头 1 行 + 字段名 1 行)")
private Integer headRowNumber = 2;
@Schema(description = "单文件大小上限(字节)")
private Long maxFileSize;
@Schema(description = "单文件行数上限")
private Integer maxRowCount;
@Schema(description = "允许的文件扩展名")
private List<String> allowedExtensions = new ArrayList<>();
@Schema(description = "数值列小数位上限")
private Integer maxScale;
@Schema(description = "分组表头与列清单")
private List<HeaderGroupVO> groups = new ArrayList<>();
@Schema(description = "业务场景字典")
private List<DictOptionVO> businessScenes = new ArrayList<>();
@Schema(description = "产品分类字典")
private List<DictOptionVO> productCategories = new ArrayList<>();
@Schema(description = "计算模式字典")
private List<DictOptionVO> calcModes = new ArrayList<>();
@Schema(description = "计算方式字典(extra 标注数值口径 RATIO / AMOUNT)")
private List<DictOptionVO> calcWays = new ArrayList<>();
@Schema(description = "是否开启线上积分字典")
private List<DictOptionVO> onlinePointFlags = new ArrayList<>();
@Schema(description = "五级校验说明")
private List<String> validationRules = new ArrayList<>();
}
package com.youjia.store.vo;
import com.youjia.store.entity.StoreApprovalLog;
import com.youjia.store.entity.StoreChangeLog;
import com.youjia.store.entity.StoreListingItem;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Getter;
import lombok.Setter;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
/**
* 门店详情视图(5 页签:门店信息 / 产品与场景 / 市场与激励 / 运营成本 / 变更历史)。
*/
@Getter
@Setter
@Schema(description = "门店详情视图")
public class StoreListingDetailVO {
private Long listingId;
private String storeName;
private String merchantNo;
private String businessScene;
private Integer categoryCount;
private String status;
private String statusLabel;
private LocalDateTime effectiveTime;
private LocalDateTime submitTime;
private String submitUserName;
private LocalDateTime approveTime;
private String approveUserName;
private String rejectReason;
private BigDecimal costDecoration;
private BigDecimal costMonthly;
private BigDecimal costLabor;
private BigDecimal costTotal;
@Schema(description = "产品与场景 · 逐行列出全部产品分类")
private List<StoreListingItem> items = new ArrayList<>();
@Schema(description = "变更历史")
private List<StoreChangeLog> changeHistory = new ArrayList<>();
@Schema(description = "审批留痕,仅追加不可删除")
private List<StoreApprovalLog> approvalLogs = new ArrayList<>();
}
package com.youjia.store.vo;
import io.swagger.v3.oas.annotations.media.Schema;
import lombok.Getter;
import lombok.Setter;
import java.math.BigDecimal;
import java.time.LocalDateTime;
/**
* 门店列表视图(仅「已生效」数据)。
*/
@Getter
@Setter
@Schema(description = "门店列表视图")
public class StoreListingVO {
private Long listingId;
private String storeName;
private String merchantNo;
private String businessScene;
@Schema(description = "上架时间(取生效时间)")
private LocalDateTime effectiveTime;
@Schema(description = "变更次数")
private Integer changeCount;
private BigDecimal costTotal;
}
<?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>com.youjia</groupId>
<artifactId>YouJia</artifactId>
<version>1.0.0-SNAPSHOT</version>
</parent>
<artifactId>youjia-module-system</artifactId>
<name>youjia-module-system</name>
<description>系统设置模块:账号、角色、菜单权限、组织与数据域</description>
<dependencies>
<dependency>
<groupId>com.youjia</groupId>
<artifactId>youjia-framework</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
</dependencies>
</project>
package com.youjia.system.controller;
import com.youjia.common.core.Result;
import com.youjia.system.service.SysMenuService;
import com.youjia.system.vo.TreeNodeVO;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
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;
/**
* 菜单 / 权限(后台维护,本期不提供管理界面)。
*/
@Tag(name = "系统设置 · 菜单权限")
@RestController
@RequestMapping("/system/menu")
@RequiredArgsConstructor
public class SysMenuController {
private final SysMenuService sysMenuService;
@Operation(summary = "全量菜单树(权限矩阵数据源)")
@GetMapping("/tree")
public Result<List<TreeNodeVO>> tree() {
return Result.success(sysMenuService.listMenuTree());
}
@Operation(summary = "指定用户可见的菜单树")
@GetMapping("/tree/user/{userId}")
public Result<List<TreeNodeVO>> treeByUser(@PathVariable Long userId) {
return Result.success(sysMenuService.listMenuTreeByUser(userId));
}
}
package com.youjia.system.controller;
import com.youjia.common.core.Result;
import com.youjia.system.service.SysOrgService;
import com.youjia.system.vo.TreeNodeVO;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
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;
/**
* 组织(后台维护,本期不提供管理界面)。
*/
@Tag(name = "系统设置 · 组织")
@RestController
@RequestMapping("/system/org")
@RequiredArgsConstructor
public class SysOrgController {
private final SysOrgService sysOrgService;
@Operation(summary = "组织树")
@GetMapping("/tree")
public Result<List<TreeNodeVO>> tree() {
return Result.success(sysOrgService.listOrgTree());
}
@Operation(summary = "组织及全部下级组织 ID(数据域「本部门及下级」使用)")
@GetMapping("/{orgId}/children")
public Result<List<Long>> children(@PathVariable Long orgId) {
return Result.success(sysOrgService.listSelfAndChildOrgIds(orgId));
}
}
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!