diff --git a/.gitignore b/.gitignore index da60ae44..c327c544 100644 --- a/.gitignore +++ b/.gitignore @@ -1,6 +1,4 @@ # Created by .ignore support plugin (hsz.mobi) -### Example sysUserDetails template template -### Example sysUserDetails template # IntelliJ project files .idea @@ -12,9 +10,5 @@ target logs .history - -docker/*/data/ -docker/minio/config -docker/xxljob/logs application-youlai.yml /uploadFile/ diff --git a/README.en.md b/README.en.md index 03ce7b65..8542c13e 100644 --- a/README.en.md +++ b/README.en.md @@ -1,356 +1,251 @@
- - -# youlai-boot youlai-boot - - +# youlai-boot youlai-boot **Enterprise-grade permission management backend based on Spring Boot** - - [![Spring Boot](https://img.shields.io/badge/Spring%20Boot-4.0.5-6DB33F?logo=spring-boot)](https://spring.io/projects/spring-boot) - [![JDK](https://img.shields.io/badge/JDK-17%2B-007396?logo=openjdk)](https://openjdk.org/) - [![License](https://img.shields.io/badge/License-Apache%202.0-blue?logo=apache)](LICENSE) - [![Gitee Star](https://gitee.com/youlaiorg/youlai-boot/badge/star.svg)](https://gitee.com/youlaiorg/youlai-boot/stargazers) - [![GitHub Star](https://img.shields.io/github/stars/youlaitech/youlai-boot?style=social)](https://github.com/youlaitech/youlai-boot) - [![GitCode Star](https://gitcode.com/youlai/youlai-boot/star/badge.svg)](https://gitcode.com/youlai/youlai-boot/stargazers) - -
- - -![](./docs/images/rainbow.png "rainbow.png") - - +

rainbow

- - -[![Live Preview](https://img.shields.io/badge/Live%20Preview-2D8CF0?style=for-the-badge&logo=google-chrome&logoColor=white)](https://vue.youlai.tech) - -[![Mobile Preview](https://img.shields.io/badge/Mobile%20Preview-19BE6B?style=for-the-badge&logo=android&logoColor=white)](https://app.youlai.tech) - -[![Documentation](https://img.shields.io/badge/Documentation-8B5CF6?style=for-the-badge&logo=gitbook&logoColor=white)](https://www.youlai.tech/docs/server/spring-boot/) - -[![简体中文](https://img.shields.io/badge/简体中文-00B4D8?style=for-the-badge&logo=google-translate&logoColor=white)](./README.md) - - +[![Live Preview](https://img.shields.io/badge/Live%20Preview-2D8CF0?style=for-the-badge\&logo=google-chrome\&logoColor=white)](https://vue.youlai.tech) +[![Mobile Preview](https://img.shields.io/badge/Mobile%20Preview-19BE6B?style=for-the-badge\&logo=android\&logoColor=white)](https://app.youlai.tech) +[![Documentation](https://img.shields.io/badge/Documentation-8B5CF6?style=for-the-badge\&logo=gitbook\&logoColor=white)](https://www.youlai.tech/docs/server/spring-boot/) +[![简体中文](https://img.shields.io/badge/简体中文-00B4D8?style=for-the-badge\&logo=google-translate\&logoColor=white)](./README.md)
- - ## Introduction - - **youlai-boot** is an enterprise-grade permission management backend built on Spring Boot. It ships with the frontend [vue3-element-admin](https://gitee.com/youlaiorg/vue3-element-admin) and the mobile app [youlai-app](https://gitee.com/youlaiorg/youlai-app), and is one of **7 language implementations** (Java / Node.js / Go / Python / PHP / C# / Rust) that share the same API specification and database schema. It is suitable for learning, reference, and secondary development of enterprise admin systems. - - ## Core Features - - -- 🔐 **Security** — Spring Security + JWT/Redis dual-session model, token renewal, multi-device mutual exclusion +- 🔐 **Security** — Spring Security + JWT/Redis dual-session token model, token renewal, multi-device mutual exclusion - 🛡️ **Fine-grained permissions** — 5-level RBAC: data → menu → button → API → field - ⚡ **Code generator** — one-click generation of full-stack CRUD code -- 📦 **Complete modules** — users, roles, menus, departments, dictionaries, files, scheduled tasks, message center, operation logs +- 📦 **Complete modules** — users, roles, menus, departments, dictionaries, files (OSS/RustFS/local), scheduled tasks, message center, operation logs + +- 🔀 **Workflow** — Flowable approval flows: online BPMN design, conditional gateways, role-based approval, rejection & rollback - 🌐 **Multi-tenant SaaS** — data isolation + tenant config, with a standalone [youlai-boot-tenant](https://gitee.com/youlaiorg/youlai-boot-tenant) edition - 🔌 **Real-time communication** — SSE push: online user count, dictionary sync, notification broadcast - - ## System Preview - - **PC** - - - - - - - - - - - - - - -
PC Preview 1PC Preview 2
PC Preview 3PC Preview 4
PC Preview 5PC Preview 6
- - **Mobile** - - - - - - - - -
App Preview 1App Preview 2App Preview 3App Preview 4
- - ## Quick Start - - **Requirements**: JDK 17+ · MySQL 8.0+ · Redis 6.0+ +1. Clone the project: + ```bash + git clone https://gitee.com/youlaiorg/youlai-boot.git + ``` -1. Clone: `git clone https://gitee.com/youlaiorg/youlai-boot.git` +2. Import the database: -2. Import database: `sql/youlai-admin.sql` + ```bash + # Base schema (required) + sql/youlai-admin.sql -3. Adjust config (optional, a read-only online data source is configured by default): `src/main/resources/application-dev.yml` + # Optional extensions: safe to skip, run after the base schema + sql/extensions/dynamic-form.sql # Dynamic Form + sql/extensions/workflow.sql # Workflow (Flowable demo processes & demo accounts, not engine tables) + ``` -4. Start and visit http://localhost:8000/doc.html +3. Adjust config (optional, a read-only online data source is configured by default): + ```bash + src/main/resources/application-dev.yml + ``` +4. Start the service: -Default credentials: `admin` / `123456` + **Option 1: Run in IDEA (recommended)** + Open the project in IDEA, wait for Maven dependencies to download, then run the application class `YouLaiBootApplication`. + **Option 2: Command line** + ```bash + mvn spring-boot:run + ``` -Detailed guide: https://www.youlai.tech/docs/server/spring-boot/quick-start.html - - - -## Tech Stack - - - -| Tech | Version | Description | - -|:-----|:--------|:------------| - -| Spring Boot | 4.0.5 | Core framework | - -| Spring Security | 6.x | Auth & authorization | - -| MyBatis-Plus | 3.5.15 | ORM | - -| Druid | 1.2.24 | Connection pool | - -| Redis + Redisson | 6.0+ / 4.1.0 | Cache · Session · Distributed lock | - -| Caffeine | 2.9.3 | Local cache | - -| XXL-Job | 3.2.0 | Distributed scheduled tasks | - -| Knife4j | 4.5.0 | API docs | - -| MapStruct | 1.6.3 | Object mapping | - -| MinIO | 8.5.10 | Object storage | - + Once started, visit . If the API docs open, the backend is running properly. +5. Start the frontend (optional): + For a visual admin UI, start the companion frontend [vue3-element-admin](https://gitee.com/youlaiorg/vue3-element-admin), visit , and log in with `admin` / `123456`. +> For more details, see the official docs: [Quick Start](https://www.youlai.tech/docs/server/spring-boot/quick-start.html) · [Deployment Guide](https://www.youlai.tech/docs/server/spring-boot/deploy.html) ## Directory Structure - - -``` - +``` youlai-boot/ - -├── docker/ # Docker orchestration - ├── docs/ # Docs and image assets - ├── sql/ # Database init scripts - ├── src/ # Source code - -│ ├── auth/ # Auth module (login/logout/token/captcha) - +│ ├── auth/ # Auth module +│ │ ├── password/ # Username/password login (with captcha) +│ │ ├── sms/ # SMS verification code login +│ │ ├── qrcode/ # QR code login +│ │ ├── wxma/ # WeChat Mini Program login +│ │ └── session/ # Session management (logout / token renewal) │ ├── codegen/ # Code generator - │ ├── common/ # Common module (constants/enums/exceptions/response/utils) - -│ ├── config/ # Configuration (Security/Redis/Captcha/OSS/Email etc.) - +│ ├── config/ # Configuration (Security/Redis/MyBatis/API docs/CORS/scheduling etc.) │ ├── framework/ # Infrastructure layer - │ │ ├── mybatis/ # MyBatis-Plus config - -│ │ ├── security/ # Spring Security (filters/token/utils) - +│ │ ├── security/ # Spring Security +│ │ │ ├── config/ # Security config and properties +│ │ │ ├── filter/ # Token authentication filter +│ │ │ ├── handler/ # Authentication / authorization failure handlers +│ │ │ ├── model/ # Security model (SecurityUser / token / data scope) +│ │ │ ├── port/ # Auth & permission ports (implemented by system) +│ │ │ ├── service/ # User details and permission service +│ │ │ ├── token/ # Token management (JWT / Redis dual mode) +│ │ │ └── util/ # Security utilities │ │ └── web/ # Web layer (global exception/CORS/rate limit) - +│ ├── module/ # Business extension modules +│ │ ├── form/ # Dynamic Form +│ │ └── workflow/ # Workflow │ ├── support/ # Capability services - -│ │ ├── file/ # File storage (MinIO/Alibaba Cloud OSS/local) - +│ │ ├── file/ # File storage (RustFS/Alibaba Cloud OSS/local) │ │ ├── mail/ # Email service - │ │ ├── sms/ # SMS service - │ │ └── sse/ # SSE push - -│ └── system/ # Business (user/role/menu/dept/dict etc.) - +│ └── system/ # System business (user/role/menu/dept/dict etc.) +├── docker-compose.yml # One-click middleware orchestration (MySQL/Redis/RustFS/Xxl-Job) └── pom.xml # Maven dependency management - -``` - - +``` ## Ecosystem - - **Frontend** - - -| Project | Stack | Description | - -|:-----|:------|:------------| - -| [vue3-element-admin](https://gitee.com/youlaiorg/vue3-element-admin) | Vue 3 + Element Plus | PC admin frontend (recommended) | - -| [youlai-app](https://gitee.com/youlaiorg/youlai-app) | Vue 3 + UniApp | Mobile App | - - +| Project | Stack | Description | Status | +|:-----|:------|:------------|:---| +| [vue3-element-admin](https://gitee.com/youlaiorg/vue3-element-admin) | Vue 3 + Element Plus | PC admin frontend (recommended) | ✅️ | +| [youlai-app](https://gitee.com/youlaiorg/youlai-app) | Vue 3 + UniApp | Mobile App | ✅️ | **Backend** +| Project | Stack | Description | Status | +|:-----|:------|:------------|:---| +| [youlai-boot](https://gitee.com/youlaiorg/youlai-boot) | Spring Boot + MyBatis-Plus | Java (recommended) | ✅️ | +| [youlai-nest](https://gitee.com/youlaiorg/youlai-nest) | NestJS + TypeORM | Node.js | ✅️ | +| [youlai-gin](https://gitee.com/youlaiorg/youlai-gin) | Go + Gorm | Go | ✅️ | +| [youlai-django](https://gitee.com/youlaiorg/youlai-django) | Django + DRF | Python | ✅️ | +| [youlai-fastapi](https://gitee.com/youlaiorg/youlai-fastapi) | FastAPI + SQLAlchemy | Python | ✅️ | +| [youlai-think](https://gitee.com/youlaiorg/youlai-think) | ThinkPHP + ThinkORM | PHP | ✅️ | +| [youlai-aspnet](https://gitee.com/youlaiorg/youlai-aspnet) | ASP.NET Core + EF Core | C# | ✅️ | +| [youlai-axum](https://gitee.com/youlaiorg/youlai-axum) | Axum + SeaORM | Rust | ✅️ | +| [youlai-laravel](https://gitee.com/youlaiorg/youlai-laravel) | Laravel + Eloquent | PHP | ❌️ | +> The nine backends share the same **RESTful API specification** and **database schema**, so the frontend can switch seamlessly. -| Project | Stack | Description | -| [youlai-boot](https://gitee.com/youlaiorg/youlai-boot) | Spring Boot + MyBatis-Plus | Java (recommended) | -| [youlai-nest](https://gitee.com/youlaiorg/youlai-nest) | NestJS + TypeORM | Node.js | -| [youlai-gin](https://gitee.com/youlaiorg/youlai-gin) | Go + Gorm | Go | -| [youlai-django](https://gitee.com/youlaiorg/youlai-django) | Django + DRF | Python | -| [youlai-fastapi](https://gitee.com/youlaiorg/youlai-fastapi) | FastAPI + SQLAlchemy | Python | -| [youlai-think](https://gitee.com/youlaiorg/youlai-think) | ThinkPHP + ThinkORM | PHP | -| [youlai-aspnet](https://gitee.com/youlaiorg/youlai-aspnet) | ASP.NET Core + EF Core | C# | -| [youlai-axum](https://gitee.com/youlaiorg/youlai-axum) | Axum + SeaORM | Rust | -> **youlai-boot** also provides the following variants and branches: [Multi-Tenant](https://gitee.com/youlaiorg/youlai-boot-tenant) · [MyBatis-Flex](https://gitee.com/youlaiorg/youlai-boot-flex) · [Spring Boot 3](https://gitee.com/youlaiorg/youlai-boot/tree/spring-boot-3) · [PostgreSQL](https://gitee.com/youlaiorg/youlai-boot/tree/db-pg) · [Multi-Module](https://gitee.com/youlaiorg/youlai-boot/tree/multi-module) +**Derived Editions** -> +| Project | Based on | Type | Description | Status | +|:-----|:-----|:---|:------------|:---| +| [youlai-boot-tenant](https://gitee.com/youlaiorg/youlai-boot-tenant) | youlai-boot | Standalone repo | Multi-tenant SaaS with tenant isolation & config | ✅️ | +| [youlai-boot-flex](https://gitee.com/youlaiorg/youlai-boot-flex) | youlai-boot | Standalone repo | Built on MyBatis-Flex | ✅️ | +| [youlai-boot (db-pg)](https://gitee.com/youlaiorg/youlai-boot/tree/db-pg) | youlai-boot | Branch | PostgreSQL database branch | ✅️ | +| [youlai-boot (multi-module)](https://gitee.com/youlaiorg/youlai-boot/tree/multi-module) | youlai-boot | Branch | Multi-module project split | ✅️ | +| [youlai-nest (multi-tenant)](https://gitee.com/youlaiorg/youlai-nest/tree/multi-tenant) | youlai-nest | Branch | Multi-tenant SaaS with tenant isolation & config | ✅️ | +| [youlai-boot (spring-boot-3)](https://gitee.com/youlaiorg/youlai-boot/tree/spring-boot-3) | youlai-boot | Branch | Spring Boot 3 compatible branch | ❌️ | -> The eight backends share the same **RESTful API specification** and **database schema**, so the frontend can switch seamlessly. +## Optional Extensions +**Workflow (disabled by default)** +Two steps to enable: -## Documentation +1. Import the demo data (demo processes & demo accounts): + ```bash + sql/extensions/workflow.sql + ``` + The ACT_* engine tables do not need to be imported — Flowable creates them automatically on startup (existing tables are left untouched). -| Resource | Link | +2. Enable it in `application-{profile}.yml`: -|:-----|:-----| + ```yaml + workflow: + enabled: true + ``` -| 📖 Full docs site | [www.youlai.tech](https://www.youlai.tech/) | + The Flowable engine switches (process / idm / eventregistry) follow `workflow.enabled` via placeholders in the same `application-{profile}.yml`, no extra maintenance needed. -| 🖥️ PC live preview | [vue.youlai.tech](https://vue.youlai.tech) | +**Multi-tenant** -| 📱 Mobile live preview | [app.youlai.tech](https://app.youlai.tech) | +For tenant isolation and tenant configuration, use the standalone repo [youlai-boot-tenant](https://gitee.com/youlaiorg/youlai-boot-tenant). -| 🔗 Apifox API docs | [apifox.com](https://www.apifox.cn/apidoc/shared-195e783f-4d85-4235-a038-eec696de4ea5) | - -| 🔗 Local API docs | [localhost:8000/doc.html](http://localhost:8000/doc.html) | - - - -## License - - - -Released under the [Apache License 2.0](LICENSE); free for commercial use. - - - ---- +## License & Support +This project is open-sourced under the [Apache License 2.0](LICENSE) and free for commercial use. Feel free to submit [issues](https://gitee.com/youlaiorg/youlai-boot/issues) or feedback, and pull requests are always welcome. +For technical support, business cooperation, secondary development, project customization, or private deployment, contact the author on WeChat (QR codes below). - - - - - - - -
- Official WeChat Account
- Official WeChat Account -
     - Mini Program
- Mini Program -
     - Add author on WeChat
- Add author on WeChat -
- -

Technical discussion · Feedback · Business cooperation

- diff --git a/README.md b/README.md index ed6e6ee7..5069b361 100644 --- a/README.md +++ b/README.md @@ -17,10 +17,10 @@
-[![在线预览](https://img.shields.io/badge/在线预览-2D8CF0?style=for-the-badge&logo=google-chrome&logoColor=white)](https://vue.youlai.tech) -[![移动端预览](https://img.shields.io/badge/移动端预览-19BE6B?style=for-the-badge&logo=android&logoColor=white)](https://app.youlai.tech) -[![阅读文档](https://img.shields.io/badge/阅读文档-8B5CF6?style=for-the-badge&logo=gitbook&logoColor=white)](https://www.youlai.tech/docs/server/spring-boot/) -[![English](https://img.shields.io/badge/English-00B4D8?style=for-the-badge&logo=google-translate&logoColor=white)](./README.en.md) +[![在线预览](https://img.shields.io/badge/在线预览-2D8CF0?style=for-the-badge\&logo=google-chrome\&logoColor=white)](https://vue.youlai.tech) +[![移动端预览](https://img.shields.io/badge/移动端预览-19BE6B?style=for-the-badge\&logo=android\&logoColor=white)](https://app.youlai.tech) +[![阅读文档](https://img.shields.io/badge/阅读文档-8B5CF6?style=for-the-badge\&logo=gitbook\&logoColor=white)](https://www.youlai.tech/docs/server/spring-boot/) +[![English](https://img.shields.io/badge/English-00B4D8?style=for-the-badge\&logo=google-translate\&logoColor=white)](./README.en.md)
@@ -31,10 +31,17 @@ ## 核心特性 - 🔐 **安全体系** — Spring Security + JWT/Redis Token 双会话模式、令牌续期、多端互斥 + - 🛡️ **细粒度权限** — RBAC 五级:数据 → 菜单 → 按钮 → 接口 → 字段 + - ⚡ **代码生成器** — 一键生成前后端 CRUD 代码 -- 📦 **模块齐全** — 用户、角色、菜单、部门、字典、文件、定时任务、消息中心、操作日志 + +- 📦 **模块齐全** — 用户、角色、菜单、部门、字典、文件(OSS/RustFS/本地)、定时任务、消息中心、操作日志 + +- 🔀 **工作流** — Flowable 审批流:BPMN 在线设计、条件网关、角色审批、驳回回退 + - 🌐 **多租户 SaaS** — 数据隔离 + 租户配置,独立 [youlai-boot-tenant](https://gitee.com/youlaiorg/youlai-boot-tenant) 版本 + - 🔌 **实时通信** — SSE 推送:在线用户数、字典同步、通知广播 ## 系统预览 @@ -50,9 +57,9 @@ PC预览3 PC预览4 - - PC预览3 - PC预览4 + + PC预览5 + PC预览6 @@ -72,16 +79,24 @@ **环境要求**:JDK 17+ · MySQL 8.0+ · Redis 6.0+ 1. 克隆项目: + ```bash git clone https://gitee.com/youlaiorg/youlai-boot.git ``` 2. 导入数据库: + ```bash + # 基础库(必装) sql/youlai-admin.sql + + # 可选扩展:不装不影响基础功能,需在基础库之后执行 + sql/extensions/dynamic-form.sql # 动态表单 + sql/extensions/workflow.sql # 工作流(Flowable 演示流程与演示账号,非引擎表) ``` 3. 修改配置(可选,默认已配置线上只读数据源): + ```bash src/main/resources/application-dev.yml ``` @@ -92,39 +107,58 @@ 用 IDEA 打开项目,等待 Maven 依赖下载完成,运行启动类 `YouLaiBootApplication` 即可。 **方式二:命令行启动** + ```bash mvn spring-boot:run ``` - 启动后访问 [http://localhost:8000/doc.html](http://localhost:8000/doc.html),能打开接口文档即说明后端已正常运行。 + 启动后访问 ,能打开接口文档即说明后端已正常运行。 5. 启动前端(可选): - 如需可视化操作界面,启动配套前端 [vue3-element-admin](https://gitee.com/youlaiorg/vue3-element-admin),访问 [http://localhost:3000](http://localhost:3000),使用 `admin` / `123456` 登录。 + 如需可视化操作界面,启动配套前端 [vue3-element-admin](https://gitee.com/youlaiorg/vue3-element-admin),访问 ,使用 `admin` / `123456` 登录。 > 更多内容详见官方文档:[快速开始](https://www.youlai.tech/docs/server/spring-boot/quick-start.html) · [部署指南](https://www.youlai.tech/docs/server/spring-boot/deploy.html) + ## 目录结构 ``` youlai-boot/ -├── docker/ # Docker 部署编排 ├── docs/ # 项目文档与图片资源 ├── sql/ # 数据库初始化脚本 ├── src/ # 源码目录 -│ ├── auth/ # 认证模块(登录/登出/令牌/验证码) +│ ├── auth/ # 认证模块 +│ │ ├── password/ # 账号密码登录(含图形验证码) +│ │ ├── sms/ # 短信验证码登录 +│ │ ├── qrcode/ # 扫码登录 +│ │ ├── wxma/ # 微信小程序登录 +│ │ └── session/ # 登录态管理(登出 / 刷新令牌) │ ├── codegen/ # 代码生成器 │ ├── common/ # 公共模块(常量/枚举/异常/统一响应/工具类) -│ ├── config/ # 配置类(Security/Redis/Captcha/OSS/邮件等) +│ ├── config/ # 配置类(Security/Redis/MyBatis/接口文档/跨域/定时任务等) │ ├── framework/ # 基础设施层 │ │ ├── mybatis/ # MyBatis-Plus 配置 -│ │ ├── security/ # Spring Security(过滤器/Token/工具类) +│ │ ├── security/ # Spring Security +│ │ │ ├── config/ # 安全配置与配置属性 +│ │ │ ├── filter/ # Token 认证过滤器 +│ │ │ ├── handler/ # 认证 / 授权失败处理器 +│ │ │ ├── model/ # 安全模型(SecurityUser / 令牌 / 数据范围) +│ │ │ ├── port/ # 认证与权限端口(由 system 提供实现) +│ │ │ ├── service/ # 用户详情与权限服务 +│ │ │ ├── token/ # Token 管理(JWT / Redis 双模式) +│ │ │ └── util/ # 安全工具类 │ │ └── web/ # Web 层(全局异常/跨域/限流) +│ ├── module/ # 业务扩展模块 +│ │ ├── form/ # 动态表单 +│ │ └── workflow/ # 工作流 │ ├── support/ # 能力服务 -│ │ ├── file/ # 文件存储(MinIO/阿里云OSS/本地) +│ │ ├── ai/ # AI 对话(代码生成/动态表单/工作流辅助,默认关闭) +│ │ ├── file/ # 文件存储(RustFS/阿里云OSS/本地) │ │ ├── mail/ # 邮件服务 │ │ ├── sms/ # 短信服务 │ │ └── sse/ # SSE 消息推送 │ └── system/ # 系统业务(用户/角色/菜单/部门/字典等) +├── docker-compose.yml # 中间件一键编排(MySQL/Redis/RustFS/Xxl-Job) └── pom.xml # Maven 依赖管理 ``` @@ -132,37 +166,64 @@ youlai-boot/ **前端** -| 项目 | 技术栈 | 说明 | 更新状态 | -|:-----|:-------|:-----|:---------| -| [vue3-element-admin](https://gitee.com/youlaiorg/vue3-element-admin) | Vue 3 + Element Plus | PC 管理前端(主推) | ✅️ | -| [youlai-app](https://gitee.com/youlaiorg/youlai-app) | Vue 3 + UniApp | 移动端 App | ✅️ | +| 项目 | 技术栈 | 说明 | 更新状态 | +| :------------------------------------------------------------------- | :------------------- | :---------- | :--- | +| [vue3-element-admin](https://gitee.com/youlaiorg/vue3-element-admin) | Vue 3 + Element Plus | PC 管理前端(主推) | ✅️ | +| [youlai-app](https://gitee.com/youlaiorg/youlai-app) | Vue 3 + UniApp | 移动端 App | ✅️ | **后端** -| 项目 | 技术栈 | 说明 | 更新状态 | -|:-----|:-------|:-----|:---------| -| [youlai-boot](https://gitee.com/youlaiorg/youlai-boot) | Spring Boot + MyBatis-Plus | Java(主推) | ✅️ | -| [youlai-nest](https://gitee.com/youlaiorg/youlai-nest) | NestJS + TypeORM | Node.js | ✅️ | -| [youlai-gin](https://gitee.com/youlaiorg/youlai-gin) | Go + Gorm | Go | ✅️ | -| [youlai-django](https://gitee.com/youlaiorg/youlai-django) | Django + DRF | Python | ✅️ | -| [youlai-fastapi](https://gitee.com/youlaiorg/youlai-fastapi) | FastAPI + SQLAlchemy | Python | ✅️ | -| [youlai-laravel](https://gitee.com/youlaiorg/youlai-laravel) | Laravel + Eloquent | PHP | ✅️ | -| [youlai-think](https://gitee.com/youlaiorg/youlai-think) | ThinkPHP + ThinkORM | PHP | ✅️ | -| [youlai-aspnet](https://gitee.com/youlaiorg/youlai-aspnet) | ASP.NET Core + EF Core | C# | ✅️ | -| [youlai-axum](https://gitee.com/youlaiorg/youlai-axum) | Axum + SeaORM | Rust | ✅️ | +| 项目 | 技术栈 | 说明 | 更新状态 | +| :----------------------------------------------------------- | :------------------------- | :------- | :--- | +| [youlai-boot](https://gitee.com/youlaiorg/youlai-boot) | Spring Boot + MyBatis-Plus | Java(主推) | ✅️ | +| [youlai-nest](https://gitee.com/youlaiorg/youlai-nest) | NestJS + TypeORM | Node.js | ✅️ | +| [youlai-gin](https://gitee.com/youlaiorg/youlai-gin) | Go + Gorm | Go | ✅️ | +| [youlai-django](https://gitee.com/youlaiorg/youlai-django) | Django + DRF | Python | ✅️ | +| [youlai-fastapi](https://gitee.com/youlaiorg/youlai-fastapi) | FastAPI + SQLAlchemy | Python | ✅️ | +| [youlai-think](https://gitee.com/youlaiorg/youlai-think) | ThinkPHP + ThinkORM | PHP | ✅️ | +| [youlai-aspnet](https://gitee.com/youlaiorg/youlai-aspnet) | ASP.NET Core + EF Core | C# | ✅️ | +| [youlai-axum](https://gitee.com/youlaiorg/youlai-axum) | Axum + SeaORM | Rust | ✅️ | +| [youlai-laravel](https://gitee.com/youlaiorg/youlai-laravel) | Laravel + Eloquent | PHP | ❌️ | > 九种后端共享同一套 **RESTful API 规范** 和 **数据库结构**,前端可无缝切换。 **衍生版本** -| 项目 | 基于 | 类型 | 说明 | 更新状态 | -|:-----|:-----|:-----|:-----|:---------| -| [youlai-boot-tenant](https://gitee.com/youlaiorg/youlai-boot-tenant) | youlai-boot | 独立仓库 | 多租户 SaaS,租户隔离与租户配置 | ✅️ | -| [youlai-boot-flex](https://gitee.com/youlaiorg/youlai-boot-flex) | youlai-boot | 独立仓库 | 改用 MyBatis-Flex | ✅️ | -| [youlai-boot (db-pg)](https://gitee.com/youlaiorg/youlai-boot/tree/db-pg) | youlai-boot | 分支 | PostgreSQL 数据库分支 | ✅️ | -| [youlai-boot (multi-module)](https://gitee.com/youlaiorg/youlai-boot/tree/multi-module) | youlai-boot | 分支 | 多模块工程拆分 | ✅️ | -| [youlai-boot (spring-boot-3)](https://gitee.com/youlaiorg/youlai-boot/tree/spring-boot-3) | youlai-boot | 分支 | Spring Boot 3 兼容分支 | ✅️ | -| [youlai-nest (multi-tenant)](https://gitee.com/youlaiorg/youlai-nest/tree/multi-tenant) | youlai-nest | 分支 | 多租户 SaaS,租户隔离与租户配置 | ✅️ | +| 项目 | 基于 | 类型 | 说明 | 更新状态 | +| :---------------------------------------------------------------------------------------- | :---------- | :--- | :----------------- | :--- | +| [youlai-boot-tenant](https://gitee.com/youlaiorg/youlai-boot-tenant) | youlai-boot | 独立仓库 | 多租户 SaaS,租户隔离与租户配置 | ✅️ | +| [youlai-boot-flex](https://gitee.com/youlaiorg/youlai-boot-flex) | youlai-boot | 独立仓库 | 改用 MyBatis-Flex | ✅️ | +| [youlai-boot (db-pg)](https://gitee.com/youlaiorg/youlai-boot/tree/db-pg) | youlai-boot | 分支 | PostgreSQL 数据库分支 | ✅️ | +| [youlai-boot (multi-module)](https://gitee.com/youlaiorg/youlai-boot/tree/multi-module) | youlai-boot | 分支 | 多模块工程拆分 | ✅️ | +| [youlai-nest (multi-tenant)](https://gitee.com/youlaiorg/youlai-nest/tree/multi-tenant) | youlai-nest | 分支 | 多租户 SaaS,租户隔离与租户配置 | ✅️ | +| [youlai-boot (spring-boot-3)](https://gitee.com/youlaiorg/youlai-boot/tree/spring-boot-3) | youlai-boot | 分支 | Spring Boot 3 兼容分支 | ❌️ | + +## 可选扩展 + +**工作流(默认关闭)** + +两步开启: + +1. 导入演示数据(演示流程与演示账号): + + ```bash + sql/extensions/workflow.sql + ``` + + ACT_* 引擎表无需导入,启动时由 Flowable 自动创建(已存在则不重复处理)。 + +2. 在 `application-{profile}.yml` 中开启: + + ```yaml + workflow: + enabled: true + ``` + + Flowable 引擎开关(process / idm / eventregistry)在 `application.yml` 中以占位符跟随 `workflow.enabled`,无需单独维护;只改上面一处即可。 + +**多租户** + +需要租户隔离与租户配置,使用独立仓库 [youlai-boot-tenant](https://gitee.com/youlaiorg/youlai-boot-tenant)。 ## 技术合作 diff --git a/docker-compose.yml b/docker-compose.yml new file mode 100644 index 00000000..82d78484 --- /dev/null +++ b/docker-compose.yml @@ -0,0 +1,73 @@ +# Docker Compose 一键安装中间件 MySQL、Redis、RustFS、Xxl-Job +# +# 安装:docker compose up -d +# 卸载:docker compose down(加 -v 同时删除数据卷) +# +# 说明: +# - name 固定项目名,容器统一管理和卸载,避免与其他项目冲突 +# - 中间件配置全部内联于 command 参数,无需外部配置文件 +# - 数据持久化使用命名卷(docker volume 统一管理),不污染项目目录 +# - 对象存储使用 RustFS(S3 协议兼容) + +name: youlai-boot + +services: + mysql: + image: mysql:8.0.29 + container_name: mysql + restart: unless-stopped + # 等价于原 my.cnf 的 utf8mb4 字符集设置(MySQL 8 其余项与默认值一致) + command: --character-set-server=utf8mb4 --collation-server=utf8mb4_0900_ai_ci + environment: + - TZ=Asia/Shanghai + - LANG=en_US.UTF-8 + - MYSQL_ROOT_PASSWORD=123456 + volumes: + - youlai-mysql-data:/var/lib/mysql + ports: + - 3306:3306 + + redis: + image: redis:7.2.3 + container_name: redis + restart: unless-stopped + # --protected-mode no 允许远程连接(原 redis.conf 唯一非默认项) + command: redis-server --requirepass 123456 --appendonly no --protected-mode no + environment: + - TZ=Asia/Shanghai + volumes: + - youlai-redis-data:/data + ports: + - 6379:6379 + + rustfs: + image: rustfs/rustfs:latest + container_name: rustfs + restart: unless-stopped + environment: + - TZ=Asia/Shanghai + - LANG=en_US.UTF-8 + - RUSTFS_ACCESS_KEY=rustfs-admin + - RUSTFS_SECRET_KEY=rustfs-admin + volumes: + - youlai-rustfs-data:/data + ports: + - 9000:9000 + - 9001:9001 + + xxl-job-admin: + image: xuxueli/xxl-job-admin:3.4.2 + container_name: xxl-job-admin + restart: unless-stopped + environment: + PARAMS: '--spring.datasource.url=jdbc:mysql://mysql:3306/xxl_job?useUnicode=true&characterEncoding=UTF-8&autoReconnect=true&serverTimezone=Asia/Shanghai --spring.datasource.username=root --spring.datasource.password=123456 --spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver' + volumes: + - youlai-xxljob-logs:/data/applogs + ports: + - 8080:8080 + +volumes: + youlai-mysql-data: + youlai-redis-data: + youlai-rustfs-data: + youlai-xxljob-logs: diff --git a/docker/docker-compose.yml b/docker/docker-compose.yml deleted file mode 100644 index 4e7c2841..00000000 --- a/docker/docker-compose.yml +++ /dev/null @@ -1,69 +0,0 @@ -# 创建一个名为 "youlai-boot" 的桥接网络,在同一个网络中的容器可以通过容器名互相访问 -networks: - youlai-boot: - driver: bridge - -services: - mysql: - image: mysql:8.0.29 - container_name: mysql - restart: unless-stopped # 重启策略:除非手动停止容器,否则自动重启 - environment: - - TZ=Asia/Shanghai - - LANG= en_US.UTF-8 - - MYSQL_ROOT_PASSWORD=123456 #设置 root 用户的密码 - volumes: - - ./mysql/conf/my.cnf:/etc/my.cnf # 挂载 my.cnf 文件到容器的指定路径 - - ./mysql/data:/var/lib/mysql # 持久化 MySQL 数据 - - ../sql:/docker-entrypoint-initdb.d # 初始化 SQL 脚本目录 - ports: - - 3306:3306 - networks: - - youlai-boot # 加入 "youlai-boot" 网络 - - redis: - image: redis:7.2.3 - container_name: redis - restart: unless-stopped - command: redis-server /etc/redis/redis.conf --requirepass 123456 --appendonly no # 启动 Redis 服务并添加密码为:123456,默认不开启 Redis AOF 方式持久化配置 - environment: - - TZ=Asia/Shanghai - volumes: - - ./redis/data:/data - - ./redis/config/redis.conf:/etc/redis/redis.conf - ports: - - 6379:6379 - networks: - - youlai-boot - - minio: - image: minio/minio:RELEASE.2024-07-16T23-46-41Z - container_name: minio - restart: unless-stopped - command: server /data --console-address ":9001" - ports: - - 9000:9000 - - 9001:9001 - environment: - - TZ=Asia/Shanghai - - LANG=en_US.UTF-8 - - MINIO_ROOT_USER=minioadmin - - MINIO_ROOT_PASSWORD=minioadmin - volumes: - - ./minio/data:/data - - ./minio/config:/root/.minio - networks: - - youlai-boot - - xxl-job-admin: - image: xuxueli/xxl-job-admin:2.4.0 - container_name: xxl-job-admin - restart: unless-stopped - environment: - PARAMS: '--spring.datasource.url=jdbc:mysql://mysql:3306/xxl_job?useUnicode=true&characterEncoding=UTF-8&autoReconnect=true&serverTimezone=Asia/Shanghai --spring.datasource.username=root --spring.datasource.password=123456 --spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver' - volumes: - - ./xxljob/logs:/data/applogs - ports: - - 8080:8080 - networks: - - youlai-boot diff --git a/docker/minio/README.md b/docker/minio/README.md deleted file mode 100644 index e69de29b..00000000 diff --git a/docker/mysql/conf/my.cnf b/docker/mysql/conf/my.cnf deleted file mode 100644 index 73981f81..00000000 --- a/docker/mysql/conf/my.cnf +++ /dev/null @@ -1,20 +0,0 @@ - - -[mysqld] -# 字符集与排序规则 -character-set-server = utf8mb4 # 服务端默认字符集 -collation-server = utf8mb4_0900_ai_ci # 服务端默认排序规则 - -# 网络与路径 -datadir = /var/lib/mysql # 数据文件存放的目录 -bind-address = 0.0.0.0 # 允许远程连接,默认 127.0.0.1 只允许本地连接 -port = 3306 # 显式指定端口(默认3306可不写) - -# 客户端字符集同步(避免乱码) -init_connect = 'SET NAMES utf8mb4' # 连接初始化时设置字符集 - -[client] -default-character-set = utf8mb4 # 客户端默认字符集 - -[mysql] -default-character-set = utf8mb4 # MySQL 命令行工具字符集 diff --git a/docker/redis/config/redis.conf b/docker/redis/config/redis.conf deleted file mode 100644 index 272c8486..00000000 --- a/docker/redis/config/redis.conf +++ /dev/null @@ -1,2297 +0,0 @@ -# 下载地址: http://download.redis.io/redis-stable/redis.conf -# https://github.com/redis/redis/blob/7.2/redis.conf -# Redis configuration file example. -# -# Note that in order to read the configuration file, Redis must be -# started with the file path as first argument: -# -# ./redis-server /path/to/redis.conf - -# Note on units: when memory size is needed, it is possible to specify -# it in the usual form of 1k 5GB 4M and so forth: -# -# 1k => 1000 bytes -# 1kb => 1024 bytes -# 1m => 1000000 bytes -# 1mb => 1024*1024 bytes -# 1g => 1000000000 bytes -# 1gb => 1024*1024*1024 bytes -# -# units are case insensitive so 1GB 1Gb 1gB are all the same. - -################################## INCLUDES ################################### - -# Include one or more other config files here. This is useful if you -# have a standard template that goes to all Redis servers but also need -# to customize a few per-server settings. Include files can include -# other files, so use this wisely. -# -# Note that option "include" won't be rewritten by command "CONFIG REWRITE" -# from admin or Redis Sentinel. Since Redis always uses the last processed -# line as value of a configuration directive, you'd better put includes -# at the beginning of this file to avoid overwriting config change at runtime. -# -# If instead you are interested in using includes to override configuration -# options, it is better to use include as the last line. -# -# Included paths may contain wildcards. All files matching the wildcards will -# be included in alphabetical order. -# Note that if an include path contains a wildcards but no files match it when -# the server is started, the include statement will be ignored and no error will -# be emitted. It is safe, therefore, to include wildcard files from empty -# directories. -# -# include /path/to/local.conf -# include /path/to/other.conf -# include /path/to/fragments/*.conf -# - -################################## MODULES ##################################### - -# Load modules at startup. If the server is not able to load modules -# it will abort. It is possible to use multiple loadmodule directives. -# -# loadmodule /path/to/my_module.so -# loadmodule /path/to/other_module.so - -################################## NETWORK ##################################### - -# By default, if no "bind" configuration directive is specified, Redis listens -# for connections from all available network interfaces on the host machine. -# It is possible to listen to just one or multiple selected interfaces using -# the "bind" configuration directive, followed by one or more IP addresses. -# Each address can be prefixed by "-", which means that redis will not fail to -# start if the address is not available. Being not available only refers to -# addresses that does not correspond to any network interface. Addresses that -# are already in use will always fail, and unsupported protocols will always BE -# silently skipped. -# -# Examples: -# -# bind 192.168.1.100 10.0.0.1 # listens on two specific IPv4 addresses -# bind 127.0.0.1 ::1 # listens on loopback IPv4 and IPv6 -# bind * -::* # like the default, all available interfaces -# -# ~~~ WARNING ~~~ If the computer running Redis is directly exposed to the -# internet, binding to all the interfaces is dangerous and will expose the -# instance to everybody on the internet. So by default we uncomment the -# following bind directive, that will force Redis to listen only on the -# IPv4 and IPv6 (if available) loopback interface addresses (this means Redis -# will only be able to accept client connections from the same host that it is -# running on). -# -# IF YOU ARE SURE YOU WANT YOUR INSTANCE TO LISTEN TO ALL THE INTERFACES -# COMMENT OUT THE FOLLOWING LINE. -# -# You will also need to set a password unless you explicitly disable protected -# mode. -# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ -#bind 127.0.0.1 -::1 - -# By default, outgoing connections (from replica to master, from Sentinel to -# instances, cluster bus, etc.) are not bound to a specific local address. In -# most cases, this means the operating system will handle that based on routing -# and the interface through which the connection goes out. -# -# Using bind-source-addr it is possible to configure a specific address to bind -# to, which may also affect how the connection gets routed. -# -# Example: -# -# bind-source-addr 10.0.0.1 - -# Protected mode is a layer of security protection, in order to avoid that -# Redis instances left open on the internet are accessed and exploited. -# -# When protected mode is on and the default user has no password, the server -# only accepts local connections from the IPv4 address (127.0.0.1), IPv6 address -# (::1) or Unix domain sockets. -# -# By default protected mode is enabled. You should disable it only if -# you are sure you want clients from other hosts to connect to Redis -# even if no authentication is configured. -protected-mode no - -# Redis uses default hardened security configuration directives to reduce the -# attack surface on innocent users. Therefore, several sensitive configuration -# directives are immutable, and some potentially-dangerous commands are blocked. -# -# Configuration directives that control files that Redis writes to (e.g., 'dir' -# and 'dbfilename') and that aren't usually modified during runtime -# are protected by making them immutable. -# -# Commands that can increase the attack surface of Redis and that aren't usually -# called by users are blocked by default. -# -# These can be exposed to either all connections or just local ones by setting -# each of the configs listed below to either of these values: -# -# no - Block for any connection (remain immutable) -# yes - Allow for any connection (no protection) -# local - Allow only for local connections. Ones originating from the -# IPv4 address (127.0.0.1), IPv6 address (::1) or Unix domain sockets. -# -# enable-protected-configs no -# enable-debug-command no -# enable-business-command no - -# Accept connections on the specified port, default is 6379 (IANA #815344). -# If port 0 is specified Redis will not listen on a TCP socket. -port 6379 - -# TCP listen() backlog. -# -# In high requests-per-second environments you need a high backlog in order -# to avoid slow clients connection issues. Note that the Linux kernel -# will silently truncate it to the value of /proc/sys/net/core/somaxconn so -# make sure to raise both the value of somaxconn and tcp_max_syn_backlog -# in order to get the desired effect. -tcp-backlog 511 - -# Unix socket. -# -# Specify the path for the Unix socket that will be used to listen for -# incoming connections. There is no default, so Redis will not listen -# on a unix socket when not specified. -# -# unixsocket /run/redis.sock -# unixsocketperm 700 - -# Close the connection after a client is idle for N seconds (0 to disable) -timeout 0 - -# TCP keepalive. -# -# If non-zero, use SO_KEEPALIVE to send TCP ACKs to clients in absence -# of communication. This is useful for two reasons: -# -# 1) Detect dead peers. -# 2) Force network equipment in the middle to consider the connection to be -# alive. -# -# On Linux, the specified value (in seconds) is the period used to send ACKs. -# Note that to close the connection the double of the time is needed. -# On other kernels the period depends on the kernel configuration. -# -# A reasonable value for this option is 300 seconds, which is the new -# Redis default starting with Redis 3.2.1. -tcp-keepalive 300 - -# Apply OS-specific mechanism to mark the listening socket with the specified -# ID, to support advanced routing and filtering capabilities. -# -# On Linux, the ID represents a connection mark. -# On FreeBSD, the ID represents a socket cookie ID. -# On OpenBSD, the ID represents a route table ID. -# -# The default value is 0, which implies no marking is required. -# socket-mark-id 0 - -################################# TLS/SSL ##################################### - -# By default, TLS/SSL is disabled. To enable it, the "tls-port" configuration -# directive can be used to define TLS-listening ports. To enable TLS on the -# default port, use: -# -# port 0 -# tls-port 6379 - -# Configure a X.509 certificate and private key to use for authenticating the -# server to connected clients, masters or cluster peers. These files should be -# PEM formatted. -# -# tls-cert-file redis.crt -# tls-key-file redis.key -# -# If the key file is encrypted using a passphrase, it can be included here -# as well. -# -# tls-key-file-pass secret - -# Normally Redis uses the same certificate for both server functions (accepting -# connections) and client functions (replicating from a master, establishing -# cluster bus connections, etc.). -# -# Sometimes certificates are issued with attributes that designate them as -# client-only or server-only certificates. In that case it may be desired to use -# different certificates for incoming (server) and outgoing (client) -# connections. To do that, use the following directives: -# -# tls-client-cert-file client.crt -# tls-client-key-file client.key -# -# If the key file is encrypted using a passphrase, it can be included here -# as well. -# -# tls-client-key-file-pass secret - -# Configure a DH parameters file to enable Diffie-Hellman (DH) key exchange, -# required by older versions of OpenSSL (<3.0). Newer versions do not require -# this configuration and recommend against it. -# -# tls-dh-params-file redis.dh - -# Configure a CA certificate(s) bundle or directory to authenticate TLS/SSL -# clients and peers. Redis requires an explicit configuration of at least one -# of these, and will not implicitly use the system wide configuration. -# -# tls-ca-cert-file ca.crt -# tls-ca-cert-dir /etc/ssl/certs - -# By default, clients (including replica servers) on a TLS port are required -# to authenticate using valid client side certificates. -# -# If "no" is specified, client certificates are not required and not accepted. -# If "optional" is specified, client certificates are accepted and must be -# valid if provided, but are not required. -# -# tls-auth-clients no -# tls-auth-clients optional - -# By default, a Redis replica does not attempt to establish a TLS connection -# with its master. -# -# Use the following directive to enable TLS on replication links. -# -# tls-replication yes - -# By default, the Redis Cluster bus uses a plain TCP connection. To enable -# TLS for the bus protocol, use the following directive: -# -# tls-cluster yes - -# By default, only TLSv1.2 and TLSv1.3 are enabled and it is highly recommended -# that older formally deprecated versions are kept disabled to reduce the attack surface. -# You can explicitly specify TLS versions to support. -# Allowed values are case insensitive and include "TLSv1", "TLSv1.1", "TLSv1.2", -# "TLSv1.3" (OpenSSL >= 1.1.1) or any combination. -# To enable only TLSv1.2 and TLSv1.3, use: -# -# tls-protocols "TLSv1.2 TLSv1.3" - -# Configure allowed ciphers. See the ciphers(1ssl) manpage for more information -# about the syntax of this string. -# -# Note: this configuration applies only to <= TLSv1.2. -# -# tls-ciphers DEFAULT:!MEDIUM - -# Configure allowed TLSv1.3 ciphersuites. See the ciphers(1ssl) manpage for more -# information about the syntax of this string, and specifically for TLSv1.3 -# ciphersuites. -# -# tls-ciphersuites TLS_CHACHA20_POLY1305_SHA256 - -# When choosing a cipher, use the server's preference instead of the client -# preference. By default, the server follows the client's preference. -# -# tls-prefer-server-ciphers yes - -# By default, TLS session caching is enabled to allow faster and less expensive -# reconnections by clients that support it. Use the following directive to disable -# caching. -# -# tls-session-caching no - -# Change the default number of TLS sessions cached. A zero value sets the cache -# to unlimited size. The default size is 20480. -# -# tls-session-cache-size 5000 - -# Change the default timeout of cached TLS sessions. The default timeout is 300 -# seconds. -# -# tls-session-cache-timeout 60 - -################################# GENERAL ##################################### - -# By default Redis does not run as a daemon. Use 'yes' if you need it. -# Note that Redis will write a pid file in /var/run/redis.pid when daemonized. -# When Redis is supervised by upstart or systemd, this parameter has no impact. -daemonize no - -# If you run Redis from upstart or systemd, Redis can interact with your -# supervision tree. Options: -# supervised no - no supervision interaction -# supervised upstart - signal upstart by putting Redis into SIGSTOP mode -# requires "expect stop" in your upstart job config -# supervised systemd - signal systemd by writing READY=1 to $NOTIFY_SOCKET -# on startup, and updating Redis status on a regular -# basis. -# supervised auto - detect upstart or systemd method based on -# UPSTART_JOB or NOTIFY_SOCKET environment variables -# Note: these supervision methods only signal "process is ready." -# They do not enable continuous pings back to your supervisor. -# -# The default is "no". To run under upstart/systemd, you can simply uncomment -# the line below: -# -# supervised auto - -# If a pid file is specified, Redis writes it where specified at startup -# and removes it at exit. -# -# When the server runs non daemonized, no pid file is created if none is -# specified in the configuration. When the server is daemonized, the pid file -# is used even if not specified, defaulting to "/var/run/redis.pid". -# -# Creating a pid file is best effort: if Redis is not able to create it -# nothing bad happens, the server will start and run normally. -# -# Note that on modern Linux systems "/run/redis.pid" is more conforming -# and should be used instead. -pidfile /var/run/redis_6379.pid - -# Specify the server verbosity level. -# This can be one of: -# debug (a lot of information, useful for development/testing) -# verbose (many rarely useful info, but not a mess like the debug level) -# notice (moderately verbose, what you want in production probably) -# warning (only very important / critical messages are logged) -# nothing (nothing is logged) -loglevel notice - -# Specify the log file name. Also the empty string can be used to force -# Redis to log on the standard output. Note that if you use standard -# output for logging but daemonize, logs will be sent to /dev/null -logfile "" - -# To enable logging to the system logger, just set 'syslog-enabled' to yes, -# and optionally update the other syslog parameters to suit your needs. -# syslog-enabled no - -# Specify the syslog identity. -# syslog-ident redis - -# Specify the syslog facility. Must be USER or between LOCAL0-LOCAL7. -# syslog-facility local0 - -# To disable the built in crash log, which will possibly produce cleaner core -# dumps when they are needed, uncomment the following: -# -# crash-log-enabled no - -# To disable the fast memory check that's run as part of the crash log, which -# will possibly let redis terminate sooner, uncomment the following: -# -# crash-memcheck-enabled no - -# Set the number of databases. The default database is DB 0, you can select -# a different one on a per-connection basis using SELECT where -# dbid is a number between 0 and 'databases'-1 -databases 16 - -# By default Redis shows an ASCII art logo only when started to log to the -# standard output and if the standard output is a TTY and syslog logging is -# disabled. Basically this means that normally a logo is displayed only in -# interactive sessions. -# -# However it is possible to force the pre-4.0 behavior and always show a -# ASCII art logo in startup logs by setting the following option to yes. -always-show-logo no - -# By default, Redis modifies the process title (as seen in 'top' and 'ps') to -# provide some runtime information. It is possible to disable this and leave -# the process name as executed by setting the following to no. -set-proc-title yes - -# When changing the process title, Redis uses the following template to construct -# the modified title. -# -# Template variables are specified in curly brackets. The following variables are -# supported: -# -# {title} Name of process as executed if parent, or type of child process. -# {listen-addr} Bind address or '*' followed by TCP or TLS port listening on, or -# Unix socket if only that's available. -# {server-mode} Special mode, i.e. "[sentinel]" or "[cluster]". -# {port} TCP port listening on, or 0. -# {tls-port} TLS port listening on, or 0. -# {unixsocket} Unix domain socket listening on, or "". -# {config-file} Name of configuration file used. -# -proc-title-template "{title} {listen-addr} {server-mode}" - -# Set the local environment which is used for string comparison operations, and -# also affect the performance of Lua scripts. Empty String indicates the locale -# is derived from the environment variables. -locale-collate "" - -################################ SNAPSHOTTING ################################ - -# Save the DB to disk. -# -# save [ ...] -# -# Redis will save the DB if the given number of seconds elapsed and it -# surpassed the given number of write operations against the DB. -# -# Snapshotting can be completely disabled with a single empty string argument -# as in following example: -# -# save "" -# -# Unless specified otherwise, by default Redis will save the DB: -# * After 3600 seconds (an hour) if at least 1 change was performed -# * After 300 seconds (5 minutes) if at least 100 changes were performed -# * After 60 seconds if at least 10000 changes were performed -# -# You can set these explicitly by uncommenting the following line. -# -# save 3600 1 300 100 60 10000 - -# By default Redis will stop accepting writes if RDB snapshots are enabled -# (at least one save point) and the latest background save failed. -# This will make the user aware (in a hard way) that data is not persisting -# on disk properly, otherwise chances are that no one will notice and some -# disaster will happen. -# -# If the background saving process will start working again Redis will -# automatically allow writes again. -# -# However if you have setup your proper monitoring of the Redis server -# and persistence, you may want to disable this feature so that Redis will -# continue to work as usual even if there are problems with disk, -# permissions, and so forth. -stop-writes-on-bgsave-error yes - -# Compress string objects using LZF when dump .rdb databases? -# By default compression is enabled as it's almost always a win. -# If you want to save some CPU in the saving child set it to 'no' but -# the dataset will likely be bigger if you have compressible values or keys. -rdbcompression yes - -# Since version 5 of RDB a CRC64 checksum is placed at the end of the file. -# This makes the format more resistant to corruption but there is a performance -# hit to pay (around 10%) when saving and loading RDB files, so you can disable it -# for maximum performances. -# -# RDB files created with checksum disabled have a checksum of zero that will -# tell the loading code to skip the check. -rdbchecksum yes - -# Enables or disables full sanitization checks for ziplist and listpack etc when -# loading an RDB or RESTORE payload. This reduces the chances of a assertion or -# crash later on while processing commands. -# Options: -# no - Never perform full sanitization -# yes - Always perform full sanitization -# clients - Perform full sanitization only for user connections. -# Excludes: RDB files, RESTORE commands received from the master -# connection, and client connections which have the -# skip-sanitize-payload ACL flag. -# The default should be 'clients' but since it currently affects cluster -# resharding via MIGRATE, it is temporarily set to 'no' by default. -# -# sanitize-dump-payload no - -# The filename where to dump the DB -dbfilename dump.rdb - -# Remove RDB files used by replication in instances without persistence -# enabled. By default this option is disabled, however there are environments -# where for regulations or other security concerns, RDB files persisted on -# disk by masters in order to feed replicas, or stored on disk by replicas -# in order to load them for the initial synchronization, should be deleted -# ASAP. Note that this option ONLY WORKS in instances that have both AOF -# and RDB persistence disabled, otherwise is completely ignored. -# -# An alternative (and sometimes better) way to obtain the same effect is -# to use diskless replication on both master and replicas instances. However -# in the case of replicas, diskless is not always an option. -rdb-del-sync-files no - -# The working directory. -# -# The DB will be written inside this directory, with the filename specified -# above using the 'dbfilename' configuration directive. -# -# The Append Only File will also be created inside this directory. -# -# Note that you must specify a directory here, not a file name. -dir ./ - -################################# REPLICATION ################################# - -# Master-Replica replication. Use replicaof to make a Redis instance a copy of -# another Redis server. A few things to understand ASAP about Redis replication. -# -# +------------------+ +---------------+ -# | Master | ---> | Replica | -# | (receive writes) | | (exact copy) | -# +------------------+ +---------------+ -# -# 1) Redis replication is asynchronous, but you can configure a master to -# stop accepting writes if it appears to be not connected with at least -# a given number of replicas. -# 2) Redis replicas are able to perform a partial resynchronization with the -# master if the replication link is lost for a relatively small amount of -# time. You may want to configure the replication backlog size (see the next -# sections of this file) with a sensible value depending on your needs. -# 3) Replication is automatic and does not need user intervention. After a -# network partition replicas automatically try to reconnect to masters -# and resynchronize with them. -# -# replicaof - -# If the master is password protected (using the "requirepass" configuration -# directive below) it is possible to tell the replica to authenticate before -# starting the replication synchronization process, otherwise the master will -# refuse the replica request. -# -# masterauth -# -# However this is not enough if you are using Redis ACLs (for Redis version -# 6 or greater), and the default user is not capable of running the PSYNC -# command and/or other commands needed for replication. In this case it's -# better to configure a special user to use with replication, and specify the -# masteruser configuration as such: -# -# masteruser -# -# When masteruser is specified, the replica will authenticate against its -# master using the new AUTH form: AUTH . - -# When a replica loses its connection with the master, or when the replication -# is still in progress, the replica can act in two different ways: -# -# 1) if replica-serve-stale-data is set to 'yes' (the default) the replica will -# still reply to client requests, possibly with out of date data, or the -# data set may just be empty if this is the first synchronization. -# -# 2) If replica-serve-stale-data is set to 'no' the replica will reply with error -# "MASTERDOWN Link with MASTER is down and replica-serve-stale-data is set to 'no'" -# to all data access commands, excluding commands such as: -# INFO, REPLICAOF, AUTH, SHUTDOWN, REPLCONF, ROLE, CONFIG, SUBSCRIBE, -# UNSUBSCRIBE, PSUBSCRIBE, PUNSUBSCRIBE, PUBLISH, PUBSUB, COMMAND, POST, -# HOST and LATENCY. -# -replica-serve-stale-data yes - -# You can configure a replica instance to accept writes or not. Writing against -# a replica instance may be useful to store some ephemeral data (because data -# written on a replica will be easily deleted after resync with the master) but -# may also cause problems if clients are writing to it because of a -# misconfiguration. -# -# Since Redis 2.6 by default replicas are read-only. -# -# Note: read only replicas are not designed to be exposed to untrusted clients -# on the internet. It's just a protection layer against misuse of the instance. -# Still a read only replica exports by default all the administrative commands -# such as CONFIG, DEBUG, and so forth. To a limited extent you can improve -# security of read only replicas using 'rename-command' to shadow all the -# administrative / dangerous commands. -replica-read-only yes - -# Replication SYNC strategy: disk or socket. -# -# New replicas and reconnecting replicas that are not able to continue the -# replication process just receiving differences, need to do what is called a -# "full synchronization". An RDB file is transmitted from the master to the -# replicas. -# -# The transmission can happen in two different ways: -# -# 1) Disk-backed: The Redis master creates a new process that writes the RDB -# file on disk. Later the file is transferred by the parent -# process to the replicas incrementally. -# 2) Diskless: The Redis master creates a new process that directly writes the -# RDB file to replica sockets, without touching the disk at all. -# -# With disk-backed replication, while the RDB file is generated, more replicas -# can be queued and served with the RDB file as soon as the current child -# producing the RDB file finishes its work. With diskless replication instead -# once the transfer starts, new replicas arriving will be queued and a new -# transfer will start when the current one terminates. -# -# When diskless replication is used, the master waits a configurable amount of -# time (in seconds) before starting the transfer in the hope that multiple -# replicas will arrive and the transfer can be parallelized. -# -# With slow disks and fast (large bandwidth) networks, diskless replication -# works better. -repl-diskless-sync yes - -# When diskless replication is enabled, it is possible to configure the delay -# the server waits in order to spawn the child that transfers the RDB via socket -# to the replicas. -# -# This is important since once the transfer starts, it is not possible to serve -# new replicas arriving, that will be queued for the next RDB transfer, so the -# server waits a delay in order to let more replicas arrive. -# -# The delay is specified in seconds, and by default is 5 seconds. To disable -# it entirely just set it to 0 seconds and the transfer will start ASAP. -repl-diskless-sync-delay 5 - -# When diskless replication is enabled with a delay, it is possible to let -# the replication start before the maximum delay is reached if the maximum -# number of replicas expected have connected. Default of 0 means that the -# maximum is not defined and Redis will wait the full delay. -repl-diskless-sync-max-replicas 0 - -# ----------------------------------------------------------------------------- -# WARNING: Since in this setup the replica does not immediately store an RDB on -# disk, it may cause data loss during failovers. RDB diskless load + Redis -# modules not handling I/O reads may cause Redis to abort in case of I/O errors -# during the initial synchronization stage with the master. -# ----------------------------------------------------------------------------- -# -# Replica can load the RDB it reads from the replication link directly from the -# socket, or store the RDB to a file and read that file after it was completely -# received from the master. -# -# In many cases the disk is slower than the network, and storing and loading -# the RDB file may increase replication time (and even increase the master's -# Copy on Write memory and replica buffers). -# However, when parsing the RDB file directly from the socket, in order to avoid -# data loss it's only safe to flush the current dataset when the new dataset is -# fully loaded in memory, resulting in higher memory usage. -# For this reason we have the following options: -# -# "disabled" - Don't use diskless load (store the rdb file to the disk first) -# "swapdb" - Keep current db contents in RAM while parsing the data directly -# from the socket. Replicas in this mode can keep serving current -# dataset while replication is in progress, except for cases where -# they can't recognize master as having a data set from same -# replication history. -# Note that this requires sufficient memory, if you don't have it, -# you risk an OOM kill. -# "on-empty-db" - Use diskless load only when current dataset is empty. This is -# safer and avoid having old and new dataset loaded side by side -# during replication. -repl-diskless-load disabled - -# Master send PINGs to its replicas in a predefined interval. It's possible to -# change this interval with the repl_ping_replica_period option. The default -# value is 10 seconds. -# -# repl-ping-replica-period 10 - -# The following option sets the replication timeout for: -# -# 1) Bulk transfer I/O during SYNC, from the point of view of replica. -# 2) Master timeout from the point of view of replicas (data, pings). -# 3) Replica timeout from the point of view of masters (REPLCONF ACK pings). -# -# It is important to make sure that this value is greater than the value -# specified for repl-ping-replica-period otherwise a timeout will be detected -# every time there is low traffic between the master and the replica. The default -# value is 60 seconds. -# -# repl-timeout 60 - -# Disable TCP_NODELAY on the replica socket after SYNC? -# -# If you select "yes" Redis will use a smaller number of TCP packets and -# less bandwidth to send data to replicas. But this can add a delay for -# the data to appear on the replica side, up to 40 milliseconds with -# Linux kernels using a default configuration. -# -# If you select "no" the delay for data to appear on the replica side will -# be reduced but more bandwidth will be used for replication. -# -# By default we optimize for low latency, but in very high traffic conditions -# or when the master and replicas are many hops away, turning this to "yes" may -# be a good idea. -repl-disable-tcp-nodelay no - -# Set the replication backlog size. The backlog is a buffer that accumulates -# replica data when replicas are disconnected for some time, so that when a -# replica wants to reconnect again, often a full resync is not needed, but a -# partial resync is enough, just passing the portion of data the replica -# missed while disconnected. -# -# The bigger the replication backlog, the longer the replica can endure the -# disconnect and later be able to perform a partial resynchronization. -# -# The backlog is only allocated if there is at least one replica connected. -# -# repl-backlog-size 1mb - -# After a master has no connected replicas for some time, the backlog will be -# freed. The following option configures the amount of seconds that need to -# elapse, starting from the time the last replica disconnected, for the backlog -# buffer to be freed. -# -# Note that replicas never free the backlog for timeout, since they may be -# promoted to masters later, and should be able to correctly "partially -# resynchronize" with other replicas: hence they should always accumulate backlog. -# -# A value of 0 means to never release the backlog. -# -# repl-backlog-ttl 3600 - -# The replica priority is an integer number published by Redis in the INFO -# output. It is used by Redis Sentinel in order to select a replica to promote -# into a master if the master is no longer working correctly. -# -# A replica with a low priority number is considered better for promotion, so -# for instance if there are three replicas with priority 10, 100, 25 Sentinel -# will pick the one with priority 10, that is the lowest. -# -# However a special priority of 0 marks the replica as not able to perform the -# role of master, so a replica with priority of 0 will never be selected by -# Redis Sentinel for promotion. -# -# By default the priority is 100. -replica-priority 100 - -# The propagation error behavior controls how Redis will behave when it is -# unable to handle a command being processed in the replication stream from a master -# or processed while reading from an AOF file. Errors that occur during propagation -# are unexpected, and can cause data inconsistency. However, there are edge cases -# in earlier versions of Redis where it was possible for the server to replicate or persist -# commands that would fail on future versions. For this reason the default behavior -# is to ignore such errors and continue processing commands. -# -# If an application wants to ensure there is no data divergence, this configuration -# should be set to 'panic' instead. The value can also be set to 'panic-on-replicas' -# to only panic when a replica encounters an error on the replication stream. One of -# these two panic values will become the default value in the future once there are -# sufficient safety mechanisms in place to prevent false positive crashes. -# -# propagation-error-behavior ignore - -# Replica ignore disk write errors controls the behavior of a replica when it is -# unable to persist a write command received from its master to disk. By default, -# this configuration is set to 'no' and will crash the replica in this condition. -# It is not recommended to change this default, however in order to be compatible -# with older versions of Redis this config can be toggled to 'yes' which will just -# log a warning and execute the write command it got from the master. -# -# replica-ignore-disk-write-errors no - -# ----------------------------------------------------------------------------- -# By default, Redis Sentinel includes all replicas in its reports. A replica -# can be excluded from Redis Sentinel's announcements. An unannounced replica -# will be ignored by the 'sentinel replicas ' command and won't be -# exposed to Redis Sentinel's clients. -# -# This option does not change the behavior of replica-priority. Even with -# replica-announced set to 'no', the replica can be promoted to master. To -# prevent this behavior, set replica-priority to 0. -# -# replica-announced yes - -# It is possible for a master to stop accepting writes if there are less than -# N replicas connected, having a lag less or equal than M seconds. -# -# The N replicas need to be in "online" state. -# -# The lag in seconds, that must be <= the specified value, is calculated from -# the last ping received from the replica, that is usually sent every second. -# -# This option does not GUARANTEE that N replicas will accept the write, but -# will limit the window of exposure for lost writes in case not enough replicas -# are available, to the specified number of seconds. -# -# For example to require at least 3 replicas with a lag <= 10 seconds use: -# -# min-replicas-to-write 3 -# min-replicas-max-lag 10 -# -# Setting one or the other to 0 disables the feature. -# -# By default min-replicas-to-write is set to 0 (feature disabled) and -# min-replicas-max-lag is set to 10. - -# A Redis master is able to list the address and port of the attached -# replicas in different ways. For example the "INFO replication" section -# offers this information, which is used, among other tools, by -# Redis Sentinel in order to discover replica instances. -# Another place where this info is available is in the output of the -# "ROLE" command of a master. -# -# The listed IP address and port normally reported by a replica is -# obtained in the following way: -# -# IP: The address is auto detected by checking the peer address -# of the socket used by the replica to connect with the master. -# -# Port: The port is communicated by the replica during the replication -# handshake, and is normally the port that the replica is using to -# listen for connections. -# -# However when port forwarding or Network Address Translation (NAT) is -# used, the replica may actually be reachable via different IP and port -# pairs. The following two options can be used by a replica in order to -# report to its master a specific set of IP and port, so that both INFO -# and ROLE will report those values. -# -# There is no need to use both the options if you need to override just -# the port or the IP address. -# -# replica-announce-ip 5.5.5.5 -# replica-announce-port 1234 - -############################### KEYS TRACKING ################################# - -# Redis implements server assisted support for client side caching of values. -# This is implemented using an invalidation table that remembers, using -# a radix key indexed by key name, what clients have which keys. In turn -# this is used in order to send invalidation messages to clients. Please -# check this page to understand more about the feature: -# -# https://redis.io/topics/client-side-caching -# -# When tracking is enabled for a client, all the read only queries are assumed -# to be cached: this will force Redis to store information in the invalidation -# table. When keys are modified, such information is flushed away, and -# invalidation messages are sent to the clients. However if the workload is -# heavily dominated by reads, Redis could use more and more memory in order -# to track the keys fetched by many clients. -# -# For this reason it is possible to configure a maximum fill value for the -# invalidation table. By default it is set to 1M of keys, and once this limit -# is reached, Redis will start to evict keys in the invalidation table -# even if they were not modified, just to reclaim memory: this will in turn -# force the clients to invalidate the cached values. Basically the table -# maximum size is a trade off between the memory you want to spend server -# side to track information about who cached what, and the ability of clients -# to retain cached objects in memory. -# -# If you set the value to 0, it means there are no limits, and Redis will -# retain as many keys as needed in the invalidation table. -# In the "stats" INFO section, you can find information about the number of -# keys in the invalidation table at every given moment. -# -# Note: when key tracking is used in broadcasting mode, no memory is used -# in the server side so this setting is useless. -# -# tracking-table-max-keys 1000000 - -################################## SECURITY ################################### - -# Warning: since Redis is pretty fast, an outside user can try up to -# 1 million passwords per second against a modern box. This means that you -# should use very strong passwords, otherwise they will be very easy to break. -# Note that because the password is really a platform secret between the client -# and the server, and should not be memorized by any human, the password -# can be easily a long string from /dev/urandom or whatever, so by using a -# long and unguessable password no brute force attack will be possible. - -# Redis ACL users are defined in the following format: -# -# user ... acl rules ... -# -# For example: -# -# user worker +@list +@connection ~jobs:* on >ffa9203c493aa99 -# -# The special username "default" is used for new connections. If this user -# has the "nopass" rule, then new connections will be immediately authenticated -# as the "default" user without the need of any password provided via the -# AUTH command. Otherwise if the "default" user is not flagged with "nopass" -# the connections will start in not authenticated state, and will require -# AUTH (or the HELLO command AUTH option) in order to be authenticated and -# start to work. -# -# The ACL rules that describe what a user can do are the following: -# -# on Enable the user: it is possible to authenticate as this user. -# off Disable the user: it's no longer possible to authenticate -# with this user, however the already authenticated connections -# will still work. -# skip-sanitize-payload RESTORE dump-payload sanitization is skipped. -# sanitize-payload RESTORE dump-payload is sanitized (default). -# + Allow the execution of that command. -# May be used with `|` for allowing subcommands (e.g "+config|get") -# - Disallow the execution of that command. -# May be used with `|` for blocking subcommands (e.g "-config|set") -# +@ Allow the execution of all the commands in such category -# with valid categories are like @admin, @set, @sortedset, ... -# and so forth, see the full list in the server.c file where -# the Redis command table is described and defined. -# The special category @all means all the commands, but currently -# present in the server, and that will be loaded in the future -# via modules. -# +|first-arg Allow a specific first argument of an otherwise -# disabled command. It is only supported on commands with -# no sub-commands, and is not allowed as negative form -# like -SELECT|1, only additive starting with "+". This -# feature is deprecated and may be removed in the future. -# allcommands Alias for +@all. Note that it implies the ability to execute -# all the future commands loaded via the modules system. -# nocommands Alias for -@all. -# ~ Add a pattern of keys that can be mentioned as part of -# commands. For instance ~* allows all the keys. The pattern -# is a glob-style pattern like the one of KEYS. -# It is possible to specify multiple patterns. -# %R~ Add key read pattern that specifies which keys can be read -# from. -# %W~ Add key write pattern that specifies which keys can be -# written to. -# allkeys Alias for ~* -# resetkeys Flush the list of allowed keys patterns. -# & Add a glob-style pattern of Pub/Sub channels that can be -# accessed by the user. It is possible to specify multiple channel -# patterns. -# allchannels Alias for &* -# resetchannels Flush the list of allowed channel patterns. -# > Add this password to the list of valid password for the user. -# For example >mypass will add "mypass" to the list. -# This directive clears the "nopass" flag (see later). -# < Remove this password from the list of valid passwords. -# nopass All the set passwords of the user are removed, and the user -# is flagged as requiring no password: it means that every -# password will work against this user. If this directive is -# used for the default user, every new connection will be -# immediately authenticated with the default user without -# any explicit AUTH command required. Note that the "resetpass" -# directive will clear this condition. -# resetpass Flush the list of allowed passwords. Moreover removes the -# "nopass" status. After "resetpass" the user has no associated -# passwords and there is no way to authenticate without adding -# some password (or setting it as "nopass" later). -# reset Performs the following actions: resetpass, resetkeys, resetchannels, -# allchannels (if acl-pubsub-default is set), off, clearselectors, -@all. -# The user returns to the same state it has immediately after its creation. -# () Create a new selector with the options specified within the -# parentheses and attach it to the user. Each option should be -# space separated. The first character must be ( and the last -# character must be ). -# clearselectors Remove all of the currently attached selectors. -# Note this does not change the "root" user permissions, -# which are the permissions directly applied onto the -# user (outside the parentheses). -# -# ACL rules can be specified in any order: for instance you can start with -# passwords, then flags, or key patterns. However note that the additive -# and subtractive rules will CHANGE MEANING depending on the ordering. -# For instance see the following example: -# -# user alice on +@all -DEBUG ~* >somepassword -# -# This will allow "alice" to use all the commands with the handler of the -# DEBUG command, since +@all added all the commands to the set of the commands -# alice can use, and later DEBUG was removed. However if we invert the order -# of two ACL rules the result will be different: -# -# user alice on -DEBUG +@all ~* >somepassword -# -# Now DEBUG was removed when alice had yet no commands in the set of allowed -# commands, later all the commands are added, so the user will be able to -# execute everything. -# -# Basically ACL rules are processed left-to-right. -# -# The following is a list of command categories and their meanings: -# * keyspace - Writing or reading from keys, databases, or their metadata -# in a type agnostic way. Includes DEL, RESTORE, DUMP, RENAME, EXISTS, DBSIZE, -# KEYS, EXPIRE, TTL, FLUSHALL, etc. Commands that may modify the keyspace, -# key or metadata will also have `write` category. Commands that only read -# the keyspace, key or metadata will have the `read` category. -# * read - Reading from keys (values or metadata). Note that commands that don't -# interact with keys, will not have either `read` or `write`. -# * write - Writing to keys (values or metadata) -# * admin - Administrative commands. Normal applications will never need to use -# these. Includes REPLICAOF, CONFIG, DEBUG, SAVE, MONITOR, ACL, SHUTDOWN, etc. -# * dangerous - Potentially dangerous (each should be considered with care for -# various reasons). This includes FLUSHALL, MIGRATE, RESTORE, SORT, KEYS, -# CLIENT, DEBUG, INFO, CONFIG, SAVE, REPLICAOF, etc. -# * connection - Commands affecting the connection or other connections. -# This includes AUTH, SELECT, COMMAND, CLIENT, ECHO, PING, etc. -# * blocking - Potentially blocking the connection until released by another -# command. -# * fast - Fast O(1) commands. May loop on the number of arguments, but not the -# number of elements in the key. -# * slow - All commands that are not Fast. -# * pubsub - PUBLISH / SUBSCRIBE related -# * transaction - WATCH / MULTI / EXEC related commands. -# * scripting - Scripting related. -# * set - Data type: sets related. -# * sortedset - Data type: zsets related. -# * list - Data type: lists related. -# * hash - Data type: hashes related. -# * string - Data type: strings related. -# * bitmap - Data type: bitmaps related. -# * hyperloglog - Data type: hyperloglog related. -# * geo - Data type: geo related. -# * stream - Data type: streams related. -# -# For more information about ACL configuration please refer to -# the Redis web site at https://redis.io/topics/acl - -# ACL LOG -# -# The ACL Log tracks failed commands and authentication events associated -# with ACLs. The ACL Log is useful to troubleshoot failed commands blocked -# by ACLs. The ACL Log is stored in memory. You can reclaim memory with -# ACL LOG RESET. Define the maximum entry length of the ACL Log below. -acllog-max-len 128 - -# Using an external ACL file -# -# Instead of configuring users here in this file, it is possible to use -# a stand-alone file just listing users. The two methods cannot be mixed: -# if you configure users here and at the same time you activate the external -# ACL file, the server will refuse to start. -# -# The format of the external ACL user file is exactly the same as the -# format that is used inside redis.conf to describe users. -# -# aclfile /etc/redis/users.acl - -# IMPORTANT NOTE: starting with Redis 6 "requirepass" is just a compatibility -# layer on top of the new ACL system. The option effect will be just setting -# the password for the default user. Clients will still authenticate using -# AUTH as usually, or more explicitly with AUTH default -# if they follow the new protocol: both will work. -# -# The requirepass is not compatible with aclfile option and the ACL LOAD -# command, these will cause requirepass to be ignored. -# -# requirepass foobared - -# New users are initialized with restrictive permissions by default, via the -# equivalent of this ACL rule 'off resetkeys -@all'. Starting with Redis 6.2, it -# is possible to manage access to Pub/Sub channels with ACL rules as well. The -# default Pub/Sub channels permission if new users is controlled by the -# acl-pubsub-default configuration directive, which accepts one of these values: -# -# allchannels: grants access to all Pub/Sub channels -# resetchannels: revokes access to all Pub/Sub channels -# -# From Redis 7.0, acl-pubsub-default defaults to 'resetchannels' permission. -# -# acl-pubsub-default resetchannels - -# Command renaming (DEPRECATED). -# -# ------------------------------------------------------------------------ -# WARNING: avoid using this option if possible. Instead use ACLs to remove -# commands from the default user, and put them only in some admin user you -# create for administrative purposes. -# ------------------------------------------------------------------------ -# -# It is possible to change the name of dangerous commands in a platform -# environment. For instance the CONFIG command may be renamed into something -# hard to guess so that it will still be available for internal-use tools -# but not available for general clients. -# -# Example: -# -# rename-command CONFIG b840fc02d524045429941cc15f59e41cb7be6c52 -# -# It is also possible to completely kill a command by renaming it into -# an empty string: -# -# rename-command CONFIG "" -# -# Please note that changing the name of commands that are logged into the -# AOF file or transmitted to replicas may cause problems. - -################################### CLIENTS #################################### - -# Set the max number of connected clients at the same time. By default -# this limit is set to 10000 clients, however if the Redis server is not -# able to configure the process file limit to allow for the specified limit -# the max number of allowed clients is set to the current file limit -# minus 32 (as Redis reserves a few file descriptors for internal uses). -# -# Once the limit is reached Redis will close all the new connections sending -# an error 'max number of clients reached'. -# -# IMPORTANT: When Redis Cluster is used, the max number of connections is also -# platform with the cluster bus: every node in the cluster will use two -# connections, one incoming and another outgoing. It is important to size the -# limit accordingly in case of very large clusters. -# -# maxclients 10000 - -############################## MEMORY MANAGEMENT ################################ - -# Set a memory usage limit to the specified amount of bytes. -# When the memory limit is reached Redis will try to remove keys -# according to the eviction policy selected (see maxmemory-policy). -# -# If Redis can't remove keys according to the policy, or if the policy is -# set to 'noeviction', Redis will start to reply with errors to commands -# that would use more memory, like SET, LPUSH, and so on, and will continue -# to reply to read-only commands like GET. -# -# This option is usually useful when using Redis as an LRU or LFU cache, or to -# set a hard memory limit for an instance (using the 'noeviction' policy). -# -# WARNING: If you have replicas attached to an instance with maxmemory on, -# the size of the output buffers needed to feed the replicas are subtracted -# from the used memory count, so that network problems / resyncs will -# not trigger a loop where keys are evicted, and in turn the output -# buffer of replicas is full with DELs of keys evicted triggering the deletion -# of more keys, and so forth until the database is completely emptied. -# -# In short... if you have replicas attached it is suggested that you set a lower -# limit for maxmemory so that there is some free RAM on the system for replica -# output buffers (but this is not needed if the policy is 'noeviction'). -# -# maxmemory - -# MAXMEMORY POLICY: how Redis will select what to remove when maxmemory -# is reached. You can select one from the following behaviors: -# -# volatile-lru -> Evict using approximated LRU, only keys with an expire set. -# allkeys-lru -> Evict any key using approximated LRU. -# volatile-lfu -> Evict using approximated LFU, only keys with an expire set. -# allkeys-lfu -> Evict any key using approximated LFU. -# volatile-random -> Remove a random key having an expire set. -# allkeys-random -> Remove a random key, any key. -# volatile-ttl -> Remove the key with the nearest expire time (minor TTL) -# noeviction -> Don't evict anything, just return an error on write operations. -# -# LRU means Least Recently Used -# LFU means Least Frequently Used -# -# Both LRU, LFU and volatile-ttl are implemented using approximated -# randomized algorithms. -# -# Note: with any of the above policies, when there are no suitable keys for -# eviction, Redis will return an error on write operations that require -# more memory. These are usually commands that create new keys, add data or -# modify existing keys. A few examples are: SET, INCR, HSET, LPUSH, SUNIONSTORE, -# SORT (due to the STORE argument), and EXEC (if the transaction includes any -# command that requires memory). -# -# The default is: -# -# maxmemory-policy noeviction - -# LRU, LFU and minimal TTL algorithms are not precise algorithms but approximated -# algorithms (in order to save memory), so you can tune it for speed or -# accuracy. By default Redis will check five keys and pick the one that was -# used least recently, you can change the sample size using the following -# configuration directive. -# -# The default of 5 produces good enough results. 10 Approximates very closely -# true LRU but costs more CPU. 3 is faster but not very accurate. -# -# maxmemory-samples 5 - -# Eviction processing is designed to function well with the default setting. -# If there is an unusually large amount of write traffic, this value may need to -# be increased. Decreasing this value may reduce latency at the risk of -# eviction processing effectiveness -# 0 = minimum latency, 10 = default, 100 = process without regard to latency -# -# maxmemory-eviction-tenacity 10 - -# Starting from Redis 5, by default a replica will ignore its maxmemory setting -# (unless it is promoted to master after a failover or manually). It means -# that the eviction of keys will be just handled by the master, sending the -# DEL commands to the replica as keys evict in the master side. -# -# This behavior ensures that masters and replicas stay consistent, and is usually -# what you want, however if your replica is writable, or you want the replica -# to have a different memory setting, and you are sure all the writes performed -# to the replica are idempotent, then you may change this default (but be sure -# to understand what you are doing). -# -# Note that since the replica by default does not evict, it may end using more -# memory than the one set via maxmemory (there are certain buffers that may -# be larger on the replica, or data structures may sometimes take more memory -# and so forth). So make sure you monitor your replicas and make sure they -# have enough memory to never hit a real out-of-memory condition before the -# master hits the configured maxmemory setting. -# -# replica-ignore-maxmemory yes - -# Redis reclaims expired keys in two ways: upon access when those keys are -# found to be expired, and also in background, in what is called the -# "active expire key". The key space is slowly and interactively scanned -# looking for expired keys to reclaim, so that it is possible to free memory -# of keys that are expired and will never be accessed again in a short time. -# -# The default effort of the expire cycle will try to avoid having more than -# ten percent of expired keys still in memory, and will try to avoid consuming -# more than 25% of total memory and to add latency to the system. However -# it is possible to increase the expire "effort" that is normally set to -# "1", to a greater value, up to the value "10". At its maximum value the -# system will use more CPU, longer cycles (and technically may introduce -# more latency), and will tolerate less already expired keys still present -# in the system. It's a tradeoff between memory, CPU and latency. -# -# active-expire-effort 1 - -############################# LAZY FREEING #################################### - -# Redis has two primitives to delete keys. One is called DEL and is a blocking -# deletion of the object. It means that the server stops processing new commands -# in order to reclaim all the memory associated with an object in a synchronous -# way. If the key deleted is associated with a small object, the time needed -# in order to execute the DEL command is very small and comparable to most other -# O(1) or O(log_N) commands in Redis. However if the key is associated with an -# aggregated value containing millions of elements, the server can block for -# a long time (even seconds) in order to complete the operation. -# -# For the above reasons Redis also offers non blocking deletion primitives -# such as UNLINK (non blocking DEL) and the ASYNC option of FLUSHALL and -# FLUSHDB commands, in order to reclaim memory in background. Those commands -# are executed in constant time. Another thread will incrementally free the -# object in the background as fast as possible. -# -# DEL, UNLINK and ASYNC option of FLUSHALL and FLUSHDB are user-controlled. -# It's up to the design of the application to understand when it is a good -# idea to use one or the other. However the Redis server sometimes has to -# delete keys or flush the whole database as a side effect of other operations. -# Specifically Redis deletes objects independently of a user call in the -# following scenarios: -# -# 1) On eviction, because of the maxmemory and maxmemory policy configurations, -# in order to make room for new data, without going over the specified -# memory limit. -# 2) Because of expire: when a key with an associated time to live (see the -# EXPIRE command) must be deleted from memory. -# 3) Because of a side effect of a command that stores data on a key that may -# already exist. For example the RENAME command may delete the old key -# content when it is replaced with another one. Similarly SUNIONSTORE -# or SORT with STORE option may delete existing keys. The SET command -# itself removes any old content of the specified key in order to replace -# it with the specified string. -# 4) During replication, when a replica performs a full resynchronization with -# its master, the content of the whole database is removed in order to -# load the RDB file just transferred. -# -# In all the above cases the default is to delete objects in a blocking way, -# like if DEL was called. However you can configure each case specifically -# in order to instead release memory in a non-blocking way like if UNLINK -# was called, using the following configuration directives. - -lazyfree-lazy-eviction no -lazyfree-lazy-expire no -lazyfree-lazy-server-del no -replica-lazy-flush no - -# It is also possible, for the case when to replace the user code DEL calls -# with UNLINK calls is not easy, to modify the default behavior of the DEL -# command to act exactly like UNLINK, using the following configuration -# directive: - -lazyfree-lazy-user-del no - -# FLUSHDB, FLUSHALL, SCRIPT FLUSH and FUNCTION FLUSH support both asynchronous and synchronous -# deletion, which can be controlled by passing the [SYNC|ASYNC] flags into the -# commands. When neither flag is passed, this directive will be used to determine -# if the data should be deleted asynchronously. - -lazyfree-lazy-user-flush no - -################################ THREADED I/O ################################# - -# Redis is mostly single threaded, however there are certain threaded -# operations such as UNLINK, slow I/O accesses and other things that are -# performed on side threads. -# -# Now it is also possible to handle Redis clients socket reads and writes -# in different I/O threads. Since especially writing is so slow, normally -# Redis users use pipelining in order to speed up the Redis performances per -# core, and spawn multiple instances in order to scale more. Using I/O -# threads it is possible to easily speedup two times Redis without resorting -# to pipelining nor sharding of the instance. -# -# By default threading is disabled, we suggest enabling it only in machines -# that have at least 4 or more cores, leaving at least one spare core. -# Using more than 8 threads is unlikely to help much. We also recommend using -# threaded I/O only if you actually have performance problems, with Redis -# instances being able to use a quite big percentage of CPU time, otherwise -# there is no point in using this feature. -# -# So for instance if you have a four cores boxes, try to use 2 or 3 I/O -# threads, if you have a 8 cores, try to use 6 threads. In order to -# enable I/O threads use the following configuration directive: -# -# io-threads 4 -# -# Setting io-threads to 1 will just use the main thread as usual. -# When I/O threads are enabled, we only use threads for writes, that is -# to thread the write(2) syscall and transfer the client buffers to the -# socket. However it is also possible to enable threading of reads and -# protocol parsing using the following configuration directive, by setting -# it to yes: -# -# io-threads-do-reads no -# -# Usually threading reads doesn't help much. -# -# NOTE 1: This configuration directive cannot be changed at runtime via -# CONFIG SET. Also, this feature currently does not work when SSL is -# enabled. -# -# NOTE 2: If you want to test the Redis speedup using redis-benchmark, make -# sure you also run the benchmark itself in threaded mode, using the -# --threads option to match the number of Redis threads, otherwise you'll not -# be able to notice the improvements. - -############################ KERNEL OOM CONTROL ############################## - -# On Linux, it is possible to hint the kernel OOM killer on what processes -# should be killed first when out of memory. -# -# Enabling this feature makes Redis actively control the oom_score_adj value -# for all its processes, depending on their role. The default scores will -# attempt to have background child processes killed before all others, and -# replicas killed before masters. -# -# Redis supports these options: -# -# no: Don't make changes to oom-score-adj (default). -# yes: Alias to "relative" see below. -# absolute: Values in oom-score-adj-values are written as is to the kernel. -# relative: Values are used relative to the initial value of oom_score_adj when -# the server starts and are then clamped to a range of -1000 to 1000. -# Because typically the initial value is 0, they will often match the -# absolute values. -oom-score-adj no - -# When oom-score-adj is used, this directive controls the specific values used -# for master, replica and background child processes. Values range -2000 to -# 2000 (higher means more likely to be killed). -# -# Unprivileged processes (not root, and without CAP_SYS_RESOURCE capabilities) -# can freely increase their value, but not decrease it below its initial -# settings. This means that setting oom-score-adj to "relative" and setting the -# oom-score-adj-values to positive values will always succeed. -oom-score-adj-values 0 200 800 - - -#################### KERNEL transparent hugepage CONTROL ###################### - -# Usually the kernel Transparent Huge Pages control is set to "madvise" or -# or "never" by default (/sys/kernel/mm/transparent_hugepage/enabled), in which -# case this config has no effect. On systems in which it is set to "always", -# redis will attempt to disable it specifically for the redis process in order -# to avoid latency problems specifically with fork(2) and CoW. -# If for some reason you prefer to keep it enabled, you can set this config to -# "no" and the kernel global to "always". - -disable-thp yes - -############################## APPEND ONLY MODE ############################### - -# By default Redis asynchronously dumps the dataset on disk. This mode is -# good enough in many applications, but an issue with the Redis process or -# a power outage may result into a few minutes of writes lost (depending on -# the configured save points). -# -# The Append Only File is an alternative persistence mode that provides -# much better durability. For instance using the default data fsync policy -# (see later in the config file) Redis can lose just one second of writes in a -# dramatic event like a server power outage, or a single write if something -# wrong with the Redis process itself happens, but the operating system is -# still running correctly. -# -# AOF and RDB persistence can be enabled at the same time without problems. -# If the AOF is enabled on startup Redis will load the AOF, that is the file -# with the better durability guarantees. -# -# Please check https://redis.io/topics/persistence for more information. - -appendonly no - -# The base name of the append only file. -# -# Redis 7 and newer use a set of append-only files to persist the dataset -# and changes applied to it. There are two basic types of files in use: -# -# - Base files, which are a snapshot representing the complete state of the -# dataset at the time the file was created. Base files can be either in -# the form of RDB (binary serialized) or AOF (textual commands). -# - Incremental files, which contain additional commands that were applied -# to the dataset following the previous file. -# -# In addition, manifest files are used to track the files and the order in -# which they were created and should be applied. -# -# Append-only file names are created by Redis following a specific pattern. -# The file name's prefix is based on the 'appendfilename' configuration -# parameter, followed by additional information about the sequence and type. -# -# For example, if appendfilename is set to appendonly.aof, the following file -# names could be derived: -# -# - appendonly.aof.1.base.rdb as a base file. -# - appendonly.aof.1.incr.aof, appendonly.aof.2.incr.aof as incremental files. -# - appendonly.aof.manifest as a manifest file. - -appendfilename "appendonly.aof" - -# For convenience, Redis stores all persistent append-only files in a dedicated -# directory. The name of the directory is determined by the appenddirname -# configuration parameter. - -appenddirname "appendonlydir" - -# The fsync() call tells the Operating System to actually write data on disk -# instead of waiting for more data in the output buffer. Some OS will really flush -# data on disk, some other OS will just try to do it ASAP. -# -# Redis supports three different modes: -# -# no: don't fsync, just let the OS flush the data when it wants. Faster. -# always: fsync after every write to the append only log. Slow, Safest. -# everysec: fsync only one time every second. Compromise. -# -# The default is "everysec", as that's usually the right compromise between -# speed and data safety. It's up to you to understand if you can relax this to -# "no" that will let the operating system flush the output buffer when -# it wants, for better performances (but if you can live with the idea of -# some data loss consider the default persistence mode that's snapshotting), -# or on the contrary, use "always" that's very slow but a bit safer than -# everysec. -# -# More details please check the following article: -# http://antirez.com/post/redis-persistence-demystified.html -# -# If unsure, use "everysec". - -# appendfsync always -appendfsync everysec -# appendfsync no - -# When the AOF fsync policy is set to always or everysec, and a background -# saving process (a background save or AOF log background rewriting) is -# performing a lot of I/O against the disk, in some Linux configurations -# Redis may block too long on the fsync() call. Note that there is no fix for -# this currently, as even performing fsync in a different thread will block -# our synchronous write(2) call. -# -# In order to mitigate this problem it's possible to use the following option -# that will prevent fsync() from being called in the main process while a -# BGSAVE or BGREWRITEAOF is in progress. -# -# This means that while another child is saving, the durability of Redis is -# the same as "appendfsync no". In practical terms, this means that it is -# possible to lose up to 30 seconds of log in the worst scenario (with the -# default Linux settings). -# -# If you have latency problems turn this to "yes". Otherwise leave it as -# "no" that is the safest pick from the point of view of durability. - -no-appendfsync-on-rewrite no - -# Automatic rewrite of the append only file. -# Redis is able to automatically rewrite the log file implicitly calling -# BGREWRITEAOF when the AOF log size grows by the specified percentage. -# -# This is how it works: Redis remembers the size of the AOF file after the -# latest rewrite (if no rewrite has happened since the restart, the size of -# the AOF at startup is used). -# -# This base size is compared to the current size. If the current size is -# bigger than the specified percentage, the rewrite is triggered. Also -# you need to specify a minimal size for the AOF file to be rewritten, this -# is useful to avoid rewriting the AOF file even if the percentage increase -# is reached but it is still pretty small. -# -# Specify a percentage of zero in order to disable the automatic AOF -# rewrite feature. - -auto-aof-rewrite-percentage 100 -auto-aof-rewrite-min-size 64mb - -# An AOF file may be found to be truncated at the end during the Redis -# startup process, when the AOF data gets loaded back into memory. -# This may happen when the system where Redis is running -# crashes, especially when an ext4 filesystem is mounted without the -# data=ordered option (however this can't happen when Redis itself -# crashes or aborts but the operating system still works correctly). -# -# Redis can either exit with an error when this happens, or load as much -# data as possible (the default now) and start if the AOF file is found -# to be truncated at the end. The following option controls this behavior. -# -# If aof-load-truncated is set to yes, a truncated AOF file is loaded and -# the Redis server starts emitting a log to inform the user of the event. -# Otherwise if the option is set to no, the server aborts with an error -# and refuses to start. When the option is set to no, the user requires -# to fix the AOF file using the "redis-check-aof" utility before to restart -# the server. -# -# Note that if the AOF file will be found to be corrupted in the middle -# the server will still exit with an error. This option only applies when -# Redis will try to read more data from the AOF file but not enough bytes -# will be found. -aof-load-truncated yes - -# Redis can create append-only base files in either RDB or AOF formats. Using -# the RDB format is always faster and more efficient, and disabling it is only -# supported for backward compatibility purposes. -aof-use-rdb-preamble yes - -# Redis supports recording timestamp annotations in the AOF to support restoring -# the data from a specific point-in-time. However, using this capability changes -# the AOF format in a way that may not be compatible with existing AOF parsers. -aof-timestamp-enabled no - -################################ SHUTDOWN ##################################### - -# Maximum time to wait for replicas when shutting down, in seconds. -# -# During shut down, a grace period allows any lagging replicas to catch up with -# the latest replication offset before the master exists. This period can -# prevent data loss, especially for deployments without configured disk backups. -# -# The 'shutdown-timeout' value is the grace period's duration in seconds. It is -# only applicable when the instance has replicas. To disable the feature, set -# the value to 0. -# -# shutdown-timeout 10 - -# When Redis receives a SIGINT or SIGTERM, shutdown is initiated and by default -# an RDB snapshot is written to disk in a blocking operation if save points are configured. -# The options used on signaled shutdown can include the following values: -# default: Saves RDB snapshot only if save points are configured. -# Waits for lagging replicas to catch up. -# save: Forces a DB saving operation even if no save points are configured. -# nosave: Prevents DB saving operation even if one or more save points are configured. -# now: Skips waiting for lagging replicas. -# force: Ignores any errors that would normally prevent the server from exiting. -# -# Any combination of values is allowed as long as "save" and "nosave" are not set simultaneously. -# Example: "nosave force now" -# -# shutdown-on-sigint default -# shutdown-on-sigterm default - -################ NON-DETERMINISTIC LONG BLOCKING COMMANDS ##################### - -# Maximum time in milliseconds for EVAL scripts, functions and in some cases -# modules' commands before Redis can start processing or rejecting other clients. -# -# If the maximum execution time is reached Redis will start to reply to most -# commands with a BUSY error. -# -# In this state Redis will only allow a handful of commands to be executed. -# For instance, SCRIPT KILL, FUNCTION KILL, SHUTDOWN NOSAVE and possibly some -# business specific 'allow-busy' commands. -# -# SCRIPT KILL and FUNCTION KILL will only be able to stop a script that did not -# yet call any write commands, so SHUTDOWN NOSAVE may be the only way to stop -# the server in the case a write command was already issued by the script when -# the user doesn't want to wait for the natural termination of the script. -# -# The default is 5 seconds. It is possible to set it to 0 or a negative value -# to disable this mechanism (uninterrupted execution). Note that in the past -# this config had a different name, which is now an alias, so both of these do -# the same: -# lua-time-limit 5000 -# busy-reply-threshold 5000 - -################################ REDIS CLUSTER ############################### - -# Normal Redis instances can't be part of a Redis Cluster; only nodes that are -# started as cluster nodes can. In order to start a Redis instance as a -# cluster node enable the cluster support uncommenting the following: -# -# cluster-enabled yes - -# Every cluster node has a cluster configuration file. This file is not -# intended to be edited by hand. It is created and updated by Redis nodes. -# Every Redis Cluster node requires a different cluster configuration file. -# Make sure that instances running in the same system do not have -# overlapping cluster configuration file names. -# -# cluster-config-file nodes-6379.conf - -# Cluster node timeout is the amount of milliseconds a node must be unreachable -# for it to be considered in failure state. -# Most other internal time limits are a multiple of the node timeout. -# -# cluster-node-timeout 15000 - -# The cluster port is the port that the cluster bus will listen for inbound connections on. When set -# to the default value, 0, it will be bound to the command port + 10000. Setting this value requires -# you to specify the cluster bus port when executing cluster meet. -# cluster-port 0 - -# A replica of a failing master will avoid to start a failover if its data -# looks too old. -# -# There is no simple way for a replica to actually have an exact measure of -# its "data age", so the following two checks are performed: -# -# 1) If there are multiple replicas able to failover, they exchange messages -# in order to try to give an advantage to the replica with the best -# replication offset (more data from the master processed). -# Replicas will try to get their rank by offset, and apply to the start -# of the failover a delay proportional to their rank. -# -# 2) Every single replica computes the time of the last interaction with -# its master. This can be the last ping or command received (if the master -# is still in the "connected" state), or the time that elapsed since the -# disconnection with the master (if the replication link is currently down). -# If the last interaction is too old, the replica will not try to failover -# at all. -# -# The point "2" can be tuned by user. Specifically a replica will not perform -# the failover if, since the last interaction with the master, the time -# elapsed is greater than: -# -# (node-timeout * cluster-replica-validity-factor) + repl-ping-replica-period -# -# So for example if node-timeout is 30 seconds, and the cluster-replica-validity-factor -# is 10, and assuming a default repl-ping-replica-period of 10 seconds, the -# replica will not try to failover if it was not able to talk with the master -# for longer than 310 seconds. -# -# A large cluster-replica-validity-factor may allow replicas with too old data to failover -# a master, while a too small value may prevent the cluster from being able to -# elect a replica at all. -# -# For maximum availability, it is possible to set the cluster-replica-validity-factor -# to a value of 0, which means, that replicas will always try to failover the -# master regardless of the last time they interacted with the master. -# (However they'll always try to apply a delay proportional to their -# offset rank). -# -# Zero is the only value able to guarantee that when all the partitions heal -# the cluster will always be able to continue. -# -# cluster-replica-validity-factor 10 - -# Cluster replicas are able to migrate to orphaned masters, that are masters -# that are left without working replicas. This improves the cluster ability -# to resist to failures as otherwise an orphaned master can't be failed over -# in case of failure if it has no working replicas. -# -# Replicas migrate to orphaned masters only if there are still at least a -# given number of other working replicas for their old master. This number -# is the "migration barrier". A migration barrier of 1 means that a replica -# will migrate only if there is at least 1 other working replica for its master -# and so forth. It usually reflects the number of replicas you want for every -# master in your cluster. -# -# Default is 1 (replicas migrate only if their masters remain with at least -# one replica). To disable migration just set it to a very large value or -# set cluster-allow-replica-migration to 'no'. -# A value of 0 can be set but is useful only for debugging and dangerous -# in production. -# -# cluster-migration-barrier 1 - -# Turning off this option allows to use less automatic cluster configuration. -# It both disables migration to orphaned masters and migration from masters -# that became empty. -# -# Default is 'yes' (allow automatic migrations). -# -# cluster-allow-replica-migration yes - -# By default Redis Cluster nodes stop accepting queries if they detect there -# is at least a hash slot uncovered (no available node is serving it). -# This way if the cluster is partially down (for example a range of hash slots -# are no longer covered) all the cluster becomes, eventually, unavailable. -# It automatically returns available as soon as all the slots are covered again. -# -# However sometimes you want the subset of the cluster which is working, -# to continue to accept queries for the part of the key space that is still -# covered. In order to do so, just set the cluster-require-full-coverage -# option to no. -# -# cluster-require-full-coverage yes - -# This option, when set to yes, prevents replicas from trying to failover its -# master during master failures. However the replica can still perform a -# manual failover, if forced to do so. -# -# This is useful in different scenarios, especially in the case of multiple -# data center operations, where we want one side to never be promoted if not -# in the case of a total DC failure. -# -# cluster-replica-no-failover no - -# This option, when set to yes, allows nodes to serve read traffic while the -# cluster is in a down state, as long as it believes it owns the slots. -# -# This is useful for two cases. The first case is for when an application -# doesn't require consistency of data during node failures or network partitions. -# One example of this is a cache, where as long as the node has the data it -# should be able to serve it. -# -# The second use case is for configurations that don't meet the recommended -# three shards but want to enable cluster mode and scale later. A -# master outage in a 1 or 2 shard configuration causes a read/write outage to the -# entire cluster without this option set, with it set there is only a write outage. -# Without a quorum of masters, slot ownership will not change automatically. -# -# cluster-allow-reads-when-down no - -# This option, when set to yes, allows nodes to serve pubsub shard traffic while -# the cluster is in a down state, as long as it believes it owns the slots. -# -# This is useful if the application would like to use the pubsub feature even when -# the cluster global stable state is not OK. If the application wants to make sure only -# one shard is serving a given channel, this feature should be kept as yes. -# -# cluster-allow-pubsubshard-when-down yes - -# Cluster link send buffer limit is the limit on the memory usage of an individual -# cluster bus link's send buffer in bytes. Cluster links would be freed if they exceed -# this limit. This is to primarily prevent send buffers from growing unbounded on links -# toward slow peers (E.g. PubSub messages being piled up). -# This limit is disabled by default. Enable this limit when 'mem_cluster_links' INFO field -# and/or 'send-buffer-allocated' entries in the 'CLUSTER LINKS` command output continuously increase. -# Minimum limit of 1gb is recommended so that cluster link buffer can fit in at least a single -# PubSub message by default. (client-query-buffer-limit default value is 1gb) -# -# cluster-link-sendbuf-limit 0 - -# Clusters can configure their announced hostname using this config. This is a common use case for -# applications that need to use TLS Server Name Indication (SNI) or dealing with DNS based -# routing. By default this value is only shown as additional metadata in the CLUSTER SLOTS -# command, but can be changed using 'cluster-preferred-endpoint-type' config. This value is -# communicated along the clusterbus to all nodes, setting it to an empty string will remove -# the hostname and also propagate the removal. -# -# cluster-announce-hostname "" - -# Clusters can configure an optional nodename to be used in addition to the node ID for -# debugging and admin information. This name is broadcasted between nodes, so will be used -# in addition to the node ID when reporting cross node events such as node failures. -# cluster-announce-human-nodename "" - -# Clusters can advertise how clients should connect to them using either their IP address, -# a user defined hostname, or by declaring they have no endpoint. Which endpoint is -# shown as the preferred endpoint is set by using the cluster-preferred-endpoint-type -# config with values 'ip', 'hostname', or 'unknown-endpoint'. This value controls how -# the endpoint returned for MOVED/ASKING requests as well as the first field of CLUSTER SLOTS. -# If the preferred endpoint type is set to hostname, but no announced hostname is set, a '?' -# will be returned instead. -# -# When a cluster advertises itself as having an unknown endpoint, it's indicating that -# the server doesn't know how clients can reach the cluster. This can happen in certain -# networking situations where there are multiple possible routes to the node, and the -# server doesn't know which one the client took. In this case, the server is expecting -# the client to reach out on the same endpoint it used for making the last request, but use -# the port provided in the response. -# -# cluster-preferred-endpoint-type ip - -# In order to setup your cluster make sure to read the documentation -# available at https://redis.io web site. - -########################## CLUSTER DOCKER/NAT support ######################## - -# In certain deployments, Redis Cluster nodes address discovery fails, because -# addresses are NAT-ted or because ports are forwarded (the typical case is -# Docker and other containers). -# -# In order to make Redis Cluster working in such environments, a static -# configuration where each node knows its public address is needed. The -# following four options are used for this scope, and are: -# -# * cluster-announce-ip -# * cluster-announce-port -# * cluster-announce-tls-port -# * cluster-announce-bus-port -# -# Each instructs the node about its address, client ports (for connections -# without and with TLS) and cluster message bus port. The information is then -# published in the header of the bus packets so that other nodes will be able to -# correctly map the address of the node publishing the information. -# -# If tls-cluster is set to yes and cluster-announce-tls-port is omitted or set -# to zero, then cluster-announce-port refers to the TLS port. Note also that -# cluster-announce-tls-port has no effect if tls-cluster is set to no. -# -# If the above options are not used, the normal Redis Cluster auto-detection -# will be used instead. -# -# Note that when remapped, the bus port may not be at the fixed offset of -# clients port + 10000, so you can specify any port and bus-port depending -# on how they get remapped. If the bus-port is not set, a fixed offset of -# 10000 will be used as usual. -# -# Example: -# -# cluster-announce-ip 10.1.1.5 -# cluster-announce-tls-port 6379 -# cluster-announce-port 0 -# cluster-announce-bus-port 6380 - -################################## SLOW LOG ################################### - -# The Redis Slow Log is a system to log queries that exceeded a specified -# execution time. The execution time does not include the I/O operations -# like talking with the client, sending the reply and so forth, -# but just the time needed to actually execute the command (this is the only -# stage of command execution where the thread is blocked and can not serve -# other requests in the meantime). -# -# You can configure the slow log with two parameters: one tells Redis -# what is the execution time, in microseconds, to exceed in order for the -# command to get logged, and the other parameter is the length of the -# slow log. When a new command is logged the oldest one is removed from the -# queue of logged commands. - -# The following time is expressed in microseconds, so 1000000 is equivalent -# to one second. Note that a negative number disables the slow log, while -# a value of zero forces the logging of every command. -slowlog-log-slower-than 10000 - -# There is no limit to this length. Just be aware that it will consume memory. -# You can reclaim memory used by the slow log with SLOWLOG RESET. -slowlog-max-len 128 - -################################ LATENCY MONITOR ############################## - -# The Redis latency monitoring subsystem samples different operations -# at runtime in order to collect data related to possible sources of -# latency of a Redis instance. -# -# Via the LATENCY command this information is available to the user that can -# print graphs and obtain reports. -# -# The system only logs operations that were performed in a time equal or -# greater than the amount of milliseconds specified via the -# latency-monitor-threshold configuration directive. When its value is set -# to zero, the latency monitor is turned off. -# -# By default latency monitoring is disabled since it is mostly not needed -# if you don't have latency issues, and collecting data has a performance -# impact, that while very small, can be measured under big load. Latency -# monitoring can easily be enabled at runtime using the command -# "CONFIG SET latency-monitor-threshold " if needed. -latency-monitor-threshold 0 - -################################ LATENCY TRACKING ############################## - -# The Redis extended latency monitoring tracks the per command latencies and enables -# exporting the percentile distribution via the INFO latencystats command, -# and cumulative latency distributions (histograms) via the LATENCY command. -# -# By default, the extended latency monitoring is enabled since the overhead -# of keeping track of the command latency is very small. -# latency-tracking yes - -# By default the exported latency percentiles via the INFO latencystats command -# are the p50, p99, and p999. -# latency-tracking-info-percentiles 50 99 99.9 - -############################# EVENT NOTIFICATION ############################## - -# Redis can notify Pub/Sub clients about events happening in the key space. -# This feature is documented at https://redis.io/topics/notifications -# -# For instance if keyspace events notification is enabled, and a client -# performs a DEL operation on key "foo" stored in the Database 0, two -# messages will be published via Pub/Sub: -# -# PUBLISH __keyspace@0__:foo del -# PUBLISH __keyevent@0__:del foo -# -# It is possible to select the events that Redis will notify among a set -# of classes. Every class is identified by a single character: -# -# K Keyspace events, published with __keyspace@__ prefix. -# E Keyevent events, published with __keyevent@__ prefix. -# g Generic commands (non-type specific) like DEL, EXPIRE, RENAME, ... -# $ String commands -# l List commands -# s Set commands -# h Hash commands -# z Sorted set commands -# x Expired events (events generated every time a key expires) -# e Evicted events (events generated when a key is evicted for maxmemory) -# n New key events (Note: not included in the 'A' class) -# t Stream commands -# d Module key type events -# m Key-miss events (Note: It is not included in the 'A' class) -# A Alias for g$lshzxetd, so that the "AKE" string means all the events -# (Except key-miss events which are excluded from 'A' due to their -# unique nature). -# -# The "notify-keyspace-events" takes as argument a string that is composed -# of zero or multiple characters. The empty string means that notifications -# are disabled. -# -# Example: to enable list and generic events, from the point of view of the -# event name, use: -# -# notify-keyspace-events Elg -# -# Example 2: to get the stream of the expired keys subscribing to channel -# name __keyevent@0__:expired use: -# -# notify-keyspace-events Ex -# -# By default all notifications are disabled because most users don't need -# this feature and the feature has some overhead. Note that if you don't -# specify at least one of K or E, no events will be delivered. -notify-keyspace-events "" - -############################### ADVANCED CONFIG ############################### - -# Hashes are encoded using a memory efficient data structure when they have a -# small number of entries, and the biggest entry does not exceed a given -# threshold. These thresholds can be configured using the following directives. -hash-max-listpack-entries 512 -hash-max-listpack-value 64 - -# Lists are also encoded in a special way to save a lot of space. -# The number of entries allowed per internal list node can be specified -# as a fixed maximum size or a maximum number of elements. -# For a fixed maximum size, use -5 through -1, meaning: -# -5: max size: 64 Kb <-- not recommended for normal workloads -# -4: max size: 32 Kb <-- not recommended -# -3: max size: 16 Kb <-- probably not recommended -# -2: max size: 8 Kb <-- good -# -1: max size: 4 Kb <-- good -# Positive numbers mean store up to _exactly_ that number of elements -# per list node. -# The highest performing option is usually -2 (8 Kb size) or -1 (4 Kb size), -# but if your use case is unique, adjust the settings as necessary. -list-max-listpack-size -2 - -# Lists may also be compressed. -# Compress depth is the number of quicklist ziplist nodes from *each* side of -# the list to *exclude* from compression. The head and tail of the list -# are always uncompressed for fast push/pop operations. Settings are: -# 0: disable all list compression -# 1: depth 1 means "don't start compressing until after 1 node into the list, -# going from either the head or tail" -# So: [head]->node->node->...->node->[tail] -# [head], [tail] will always be uncompressed; inner nodes will compress. -# 2: [head]->[next]->node->node->...->node->[prev]->[tail] -# 2 here means: don't compress head or head->next or tail->prev or tail, -# but compress all nodes between them. -# 3: [head]->[next]->[next]->node->node->...->node->[prev]->[prev]->[tail] -# etc. -list-compress-depth 0 - -# Sets have a special encoding when a set is composed -# of just strings that happen to be integers in radix 10 in the range -# of 64 bit signed integers. -# The following configuration setting sets the limit in the size of the -# set in order to use this special memory saving encoding. -set-max-intset-entries 512 - -# Sets containing non-integer values are also encoded using a memory efficient -# data structure when they have a small number of entries, and the biggest entry -# does not exceed a given threshold. These thresholds can be configured using -# the following directives. -set-max-listpack-entries 128 -set-max-listpack-value 64 - -# Similarly to hashes and lists, sorted sets are also specially encoded in -# order to save a lot of space. This encoding is only used when the length and -# elements of a sorted set are below the following limits: -zset-max-listpack-entries 128 -zset-max-listpack-value 64 - -# HyperLogLog sparse representation bytes limit. The limit includes the -# 16 bytes header. When a HyperLogLog using the sparse representation crosses -# this limit, it is converted into the dense representation. -# -# A value greater than 16000 is totally useless, since at that point the -# dense representation is more memory efficient. -# -# The suggested value is ~ 3000 in order to have the benefits of -# the space efficient encoding without slowing down too much PFADD, -# which is O(N) with the sparse encoding. The value can be raised to -# ~ 10000 when CPU is not a concern, but space is, and the data set is -# composed of many HyperLogLogs with cardinality in the 0 - 15000 range. -hll-sparse-max-bytes 3000 - -# Streams macro node max size / items. The stream data structure is a radix -# tree of big nodes that encode multiple items inside. Using this configuration -# it is possible to configure how big a single node can be in bytes, and the -# maximum number of items it may contain before switching to a new node when -# appending new stream entries. If any of the following settings are set to -# zero, the limit is ignored, so for instance it is possible to set just a -# max entries limit by setting max-bytes to 0 and max-entries to the desired -# value. -stream-node-max-bytes 4096 -stream-node-max-entries 100 - -# Active rehashing uses 1 millisecond every 100 milliseconds of CPU time in -# order to help rehashing the main Redis hash table (the one mapping top-level -# keys to values). The hash table implementation Redis uses (see dict.c) -# performs a lazy rehashing: the more operation you run into a hash table -# that is rehashing, the more rehashing "steps" are performed, so if the -# server is idle the rehashing is never complete and some more memory is used -# by the hash table. -# -# The default is to use this millisecond 10 times every second in order to -# actively rehash the main dictionaries, freeing memory when possible. -# -# If unsure: -# use "activerehashing no" if you have hard latency requirements and it is -# not a good thing in your environment that Redis can reply from time to time -# to queries with 2 milliseconds delay. -# -# use "activerehashing yes" if you don't have such hard requirements but -# want to free memory asap when possible. -activerehashing yes - -# The client output buffer limits can be used to force disconnection of clients -# that are not reading data from the server fast enough for some reason (a -# common reason is that a Pub/Sub client can't consume messages as fast as the -# publisher can produce them). -# -# The limit can be set differently for the three different classes of clients: -# -# normal -> normal clients including MONITOR clients -# replica -> replica clients -# pubsub -> clients subscribed to at least one pubsub channel or pattern -# -# The syntax of every client-output-buffer-limit directive is the following: -# -# client-output-buffer-limit -# -# A client is immediately disconnected once the hard limit is reached, or if -# the soft limit is reached and remains reached for the specified number of -# seconds (continuously). -# So for instance if the hard limit is 32 megabytes and the soft limit is -# 16 megabytes / 10 seconds, the client will get disconnected immediately -# if the size of the output buffers reach 32 megabytes, but will also get -# disconnected if the client reaches 16 megabytes and continuously overcomes -# the limit for 10 seconds. -# -# By default normal clients are not limited because they don't receive data -# without asking (in a push way), but just after a request, so only -# asynchronous clients may create a scenario where data is requested faster -# than it can read. -# -# Instead there is a default limit for pubsub and replica clients, since -# subscribers and replicas receive data in a push fashion. -# -# Note that it doesn't make sense to set the replica clients output buffer -# limit lower than the repl-backlog-size config (partial sync will succeed -# and then replica will get disconnected). -# Such a configuration is ignored (the size of repl-backlog-size will be used). -# This doesn't have memory consumption implications since the replica client -# will share the backlog buffers memory. -# -# Both the hard or the soft limit can be disabled by setting them to zero. -client-output-buffer-limit normal 0 0 0 -client-output-buffer-limit replica 256mb 64mb 60 -client-output-buffer-limit pubsub 32mb 8mb 60 - -# Client query buffers accumulate new commands. They are limited to a fixed -# amount by default in order to avoid that a protocol desynchronization (for -# instance due to a bug in the client) will lead to unbound memory usage in -# the query buffer. However you can configure it here if you have very special -# needs, such us huge multi/exec requests or alike. -# -# client-query-buffer-limit 1gb - -# In some scenarios client connections can hog up memory leading to OOM -# errors or data eviction. To avoid this we can cap the accumulated memory -# used by all client connections (all pubsub and normal clients). Once we -# reach that limit connections will be dropped by the server freeing up -# memory. The server will attempt to drop the connections using the most -# memory first. We call this mechanism "client eviction". -# -# Client eviction is configured using the maxmemory-clients setting as follows: -# 0 - client eviction is disabled (default) -# -# A memory value can be used for the client eviction threshold, -# for example: -# maxmemory-clients 1g -# -# A percentage value (between 1% and 100%) means the client eviction threshold -# is based on a percentage of the maxmemory setting. For example to set client -# eviction at 5% of maxmemory: -# maxmemory-clients 5% - -# In the Redis protocol, bulk requests, that are, elements representing single -# strings, are normally limited to 512 mb. However you can change this limit -# here, but must be 1mb or greater -# -# proto-max-bulk-len 512mb - -# Redis calls an internal function to perform many background tasks, like -# closing connections of clients in timeout, purging expired keys that are -# never requested, and so forth. -# -# Not all tasks are performed with the same frequency, but Redis checks for -# tasks to perform according to the specified "hz" value. -# -# By default "hz" is set to 10. Raising the value will use more CPU when -# Redis is idle, but at the same time will make Redis more responsive when -# there are many keys expiring at the same time, and timeouts may be -# handled with more precision. -# -# The range is between 1 and 500, however a value over 100 is usually not -# a good idea. Most users should use the default of 10 and raise this up to -# 100 only in environments where very low latency is required. -hz 10 - -# Normally it is useful to have an HZ value which is proportional to the -# number of clients connected. This is useful in order, for instance, to -# avoid too many clients are processed for each background task invocation -# in order to avoid latency spikes. -# -# Since the default HZ value by default is conservatively set to 10, Redis -# offers, and enables by default, the ability to use an adaptive HZ value -# which will temporarily raise when there are many connected clients. -# -# When dynamic HZ is enabled, the actual configured HZ will be used -# as a baseline, but multiples of the configured HZ value will be actually -# used as needed once more clients are connected. In this way an idle -# instance will use very little CPU time while a busy instance will be -# more responsive. -dynamic-hz yes - -# When a child rewrites the AOF file, if the following option is enabled -# the file will be fsync-ed every 4 MB of data generated. This is useful -# in order to commit the file to the disk more incrementally and avoid -# big latency spikes. -aof-rewrite-incremental-fsync yes - -# When redis saves RDB file, if the following option is enabled -# the file will be fsync-ed every 4 MB of data generated. This is useful -# in order to commit the file to the disk more incrementally and avoid -# big latency spikes. -rdb-save-incremental-fsync yes - -# Redis LFU eviction (see maxmemory setting) can be tuned. However it is a good -# idea to start with the default settings and only change them after investigating -# how to improve the performances and how the keys LFU change over time, which -# is possible to inspect via the OBJECT FREQ command. -# -# There are two tunable parameters in the Redis LFU implementation: the -# counter logarithm factor and the counter decay time. It is important to -# understand what the two parameters mean before changing them. -# -# The LFU counter is just 8 bits per key, it's maximum value is 255, so Redis -# uses a probabilistic increment with logarithmic behavior. Given the value -# of the old counter, when a key is accessed, the counter is incremented in -# this way: -# -# 1. A random number R between 0 and 1 is extracted. -# 2. A probability P is calculated as 1/(old_value*lfu_log_factor+1). -# 3. The counter is incremented only if R < P. -# -# The default lfu-log-factor is 10. This is a table of how the frequency -# counter changes with a different number of accesses with different -# logarithmic factors: -# -# +--------+------------+------------+------------+------------+------------+ -# | factor | 100 hits | 1000 hits | 100K hits | 1M hits | 10M hits | -# +--------+------------+------------+------------+------------+------------+ -# | 0 | 104 | 255 | 255 | 255 | 255 | -# +--------+------------+------------+------------+------------+------------+ -# | 1 | 18 | 49 | 255 | 255 | 255 | -# +--------+------------+------------+------------+------------+------------+ -# | 10 | 10 | 18 | 142 | 255 | 255 | -# +--------+------------+------------+------------+------------+------------+ -# | 100 | 8 | 11 | 49 | 143 | 255 | -# +--------+------------+------------+------------+------------+------------+ -# -# NOTE: The above table was obtained by running the following commands: -# -# redis-benchmark -n 1000000 incr foo -# redis-cli object freq foo -# -# NOTE 2: The counter initial value is 5 in order to give new objects a chance -# to accumulate hits. -# -# The counter decay time is the time, in minutes, that must elapse in order -# for the key counter to be decremented. -# -# The default value for the lfu-decay-time is 1. A special value of 0 means we -# will never decay the counter. -# -# lfu-log-factor 10 -# lfu-decay-time 1 - -########################### ACTIVE DEFRAGMENTATION ####################### -# -# What is active defragmentation? -# ------------------------------- -# -# Active (online) defragmentation allows a Redis server to compact the -# spaces left between small allocations and deallocations of data in memory, -# thus allowing to reclaim back memory. -# -# Fragmentation is a natural process that happens with every allocator (but -# less so with Jemalloc, fortunately) and certain workloads. Normally a server -# restart is needed in order to lower the fragmentation, or at least to flush -# away all the data and create it again. However thanks to this feature -# implemented by Oran Agra for Redis 4.0 this process can happen at runtime -# in a "hot" way, while the server is running. -# -# Basically when the fragmentation is over a certain level (see the -# configuration options below) Redis will start to create new copies of the -# values in contiguous memory regions by exploiting certain specific Jemalloc -# features (in order to understand if an allocation is causing fragmentation -# and to allocate it in a better place), and at the same time, will release the -# old copies of the data. This process, repeated incrementally for all the keys -# will cause the fragmentation to drop back to normal values. -# -# Important things to understand: -# -# 1. This feature is disabled by default, and only works if you compiled Redis -# to use the copy of Jemalloc we ship with the source code of Redis. -# This is the default with Linux builds. -# -# 2. You never need to enable this feature if you don't have fragmentation -# issues. -# -# 3. Once you experience fragmentation, you can enable this feature when -# needed with the command "CONFIG SET activedefrag yes". -# -# The configuration parameters are able to fine tune the behavior of the -# defragmentation process. If you are not sure about what they mean it is -# a good idea to leave the defaults untouched. - -# Active defragmentation is disabled by default -# activedefrag no - -# Minimum amount of fragmentation waste to start active defrag -# active-defrag-ignore-bytes 100mb - -# Minimum percentage of fragmentation to start active defrag -# active-defrag-threshold-lower 10 - -# Maximum percentage of fragmentation at which we use maximum effort -# active-defrag-threshold-upper 100 - -# Minimal effort for defrag in CPU percentage, to be used when the lower -# threshold is reached -# active-defrag-cycle-min 1 - -# Maximal effort for defrag in CPU percentage, to be used when the upper -# threshold is reached -# active-defrag-cycle-max 25 - -# Maximum number of set/hash/zset/list fields that will be processed from -# the main dictionary scan -# active-defrag-max-scan-fields 1000 - -# Jemalloc background thread for purging will be enabled by default -jemalloc-bg-thread yes - -# It is possible to pin different threads and processes of Redis to specific -# CPUs in your system, in order to maximize the performances of the server. -# This is useful both in order to pin different Redis threads in different -# CPUs, but also in order to make sure that multiple Redis instances running -# in the same host will be pinned to different CPUs. -# -# Normally you can do this using the "taskset" command, however it is also -# possible to this via Redis configuration directly, both in Linux and FreeBSD. -# -# You can pin the server/IO threads, bio threads, aof rewrite child process, and -# the bgsave child process. The syntax to specify the cpu list is the same as -# the taskset command: -# -# Set redis server/io threads to cpu affinity 0,2,4,6: -# server_cpulist 0-7:2 -# -# Set bio threads to cpu affinity 1,3: -# bio_cpulist 1,3 -# -# Set aof rewrite child process to cpu affinity 8,9,10,11: -# aof_rewrite_cpulist 8-11 -# -# Set bgsave child process to cpu affinity 1,10,11 -# bgsave_cpulist 1,10-11 - -# In some cases redis will emit warnings and even refuse to start if it detects -# that the system is in bad state, it is possible to suppress these warnings -# by setting the following config which takes a space delimited list of warnings -# to suppress -# -# ignore-warnings ARM64-COW-BUG diff --git a/docker/run.md b/docker/run.md deleted file mode 100644 index 1ee1fe5e..00000000 --- a/docker/run.md +++ /dev/null @@ -1,16 +0,0 @@ - -# Docker Compose 安装中间件 MySQL、Redis、Minio、Xxl-Job - -## 安装 - -```bash -docker-compose -f ./docker-compose.yml -p youlai-boot up -d -``` - -- p youlai-boot 指定命名空间,避免与其他容器冲突,这里方便管理,统一管理和卸载 - -## 卸载 -```bash -docker-compose -f ./docker-compose.yml -p youlai-boot down -``` - diff --git a/docker/xxljob/README.md b/docker/xxljob/README.md deleted file mode 100644 index e69de29b..00000000 diff --git a/pom.xml b/pom.xml index 239ba78e..bf4a57b0 100644 --- a/pom.xml +++ b/pom.xml @@ -6,7 +6,7 @@ com.youlai youlai-boot - 4.6.0 + 4.12.0 基于 Java 17 + SpringBoot 4 + Spring Security 构建的权限管理系统。 @@ -20,11 +20,12 @@ 17 17 - 5.8.41 + 5.8.47 + + 8.0.0 9.1.0 1.2.24 - 3.5.15 4.5.0 @@ -33,13 +34,13 @@ 1.6.3 0.2.0 - 3.2.0 + 3.4.2 1.3.0 - 8.5.10 4.12.0 + 2.54.2 3.16.3 @@ -62,13 +63,30 @@ 2.14.5 + + 1.3.0 + 4.8.1.B 1.2.5 + 2.0.0 + + + + + org.springframework.ai + spring-ai-bom + ${spring-ai.version} + pom + import + + + + org.projectlombok @@ -122,6 +140,13 @@ test + + com.tngtech.archunit + archunit-junit5 + ${archunit.version} + test + + org.springframework.boot spring-boot-starter-security @@ -209,6 +234,17 @@ spring-boot-starter-validation + + + org.springframework.ai + spring-ai-starter-model-openai + + + + org.springframework.ai + spring-ai-client-chat + + org.springframework.boot spring-boot-starter-mail @@ -228,7 +264,6 @@ ${druid.version} - com.baomidou mybatis-plus-spring-boot4-starter @@ -285,11 +320,11 @@ ${fastexcel.version} - + - io.minio - minio - ${minio.version} + software.amazon.awssdk + s3 + ${aws-sdk-s3.version} @@ -386,6 +421,13 @@ taos-jdbcdriver 3.5.1 + + + + org.flowable + flowable-spring-boot-starter-process + ${flowable.version} + diff --git a/sql/extensions/dynamic-form.sql b/sql/extensions/dynamic-form.sql new file mode 100644 index 00000000..7e5d7f4f --- /dev/null +++ b/sql/extensions/dynamic-form.sql @@ -0,0 +1,128 @@ +# 动态表单模块(可选扩展) +# Copyright (c) 2026-present, youlai.tech + +-- ---------------------------------------------------------------------------- +-- 动态表单模块扩展脚本(全量执行,可重复运行) +-- 前置:请先执行 ../youlai-admin.sql(本脚本向 sys_menu/sys_role_menu 插入数据) +-- ---------------------------------------------------------------------------- +USE youlai_admin; + +SET NAMES utf8mb4; +SET FOREIGN_KEY_CHECKS = 0; + +-- ---------------------------- +-- 表结构:form_definition +-- ---------------------------- +DROP TABLE IF EXISTS `form_definition`; +CREATE TABLE `form_definition` ( + `id` bigint NOT NULL AUTO_INCREMENT COMMENT '主键', + `form_key` varchar(64) NOT NULL COMMENT '表单唯一标识(业务编码,如 employee_onboarding)', + `form_name` varchar(100) NOT NULL COMMENT '表单名称', + `description` varchar(255) DEFAULT NULL COMMENT '表单描述', + `form_json` json NOT NULL COMMENT '表单规则(form-create rule 数组)', + `options_json` json DEFAULT NULL COMMENT '表单全局配置(labelPosition/size/submitBtn 等)', + `status` tinyint NOT NULL DEFAULT 0 COMMENT '状态(0草稿 1已发布 -1已停用)', + `is_public` tinyint NOT NULL DEFAULT 0 COMMENT '是否允许匿名公开访问(0否 1是)', + `category` varchar(16) NOT NULL DEFAULT 'normal' COMMENT '表单类型(normal通用表单 workflow审批表单)', + `menu_id` bigint DEFAULT NULL COMMENT '生成的访问菜单ID(NULL未生成,幂等防重复)', + `version` int NOT NULL DEFAULT 1 COMMENT '版本号,每次发布+1', + `create_time` datetime NOT NULL COMMENT '创建时间', + `update_time` datetime NOT NULL COMMENT '更新时间', + `create_by` bigint DEFAULT NULL COMMENT '创建人ID', + `update_by` bigint DEFAULT NULL COMMENT '更新人ID', + `is_deleted` tinyint NOT NULL DEFAULT 0 COMMENT '逻辑删除(0未删 1已删)', + PRIMARY KEY (`id`), + KEY `idx_form_key` (`form_key`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='表单定义表'; + +-- ---------------------------- +-- 表结构:form_data +-- ---------------------------- +DROP TABLE IF EXISTS `form_data`; +CREATE TABLE `form_data` ( + `id` bigint NOT NULL AUTO_INCREMENT COMMENT '主键', + `form_id` bigint NOT NULL COMMENT '表单定义ID', + `form_version` int NOT NULL COMMENT '表单版本(提交时快照)', + `data_json` json NOT NULL COMMENT '表单数据(field -> value 映射)', + `create_by` bigint DEFAULT NULL COMMENT '提交人ID(匿名提交为空)', + `update_by` bigint DEFAULT NULL COMMENT '修改人ID(数据修正时记录)', + `create_time` datetime NOT NULL COMMENT '提交时间', + `update_time` datetime NOT NULL COMMENT '更新时间', + `is_deleted` tinyint NOT NULL DEFAULT 0 COMMENT '逻辑删除(0未删 1已删)', + PRIMARY KEY (`id`), + KEY `idx_form_id` (`form_id`), + KEY `idx_create_by` (`create_by`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='表单数据表'; + +-- ---------------------------- +-- 表结构:form_snapshot +-- ---------------------------- +-- 版本快照表:发布时固化规则,数据回显按提交时版本加载, +-- 防止表单定义变更(字段删除/改名)导致历史数据回显漂移; +-- 快照只增不改,update_time 仅因实体继承 BaseEntity 保留列,无业务语义 +DROP TABLE IF EXISTS `form_snapshot`; +CREATE TABLE `form_snapshot` ( + `id` bigint NOT NULL AUTO_INCREMENT COMMENT '主键', + `form_id` bigint NOT NULL COMMENT '表单定义ID', + `version` int NOT NULL COMMENT '版本号(发布时递增后的值)', + `form_json` json NOT NULL COMMENT '表单规则快照(form-create rule 数组)', + `options_json` json DEFAULT NULL COMMENT '表单全局配置快照', + `create_time` datetime NOT NULL COMMENT '创建时间', + `update_time` datetime NOT NULL COMMENT '更新时间', + `is_deleted` tinyint NOT NULL DEFAULT 0 COMMENT '逻辑删除(0未删 1已删)', + PRIMARY KEY (`id`), + KEY `idx_form_version` (`form_id`, `version`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='表单版本快照表'; + +-- ---------------------------- +-- 菜单(扩展段顶级 ID=8,基础段 1-7 见 youlai-admin.sql) +-- 顶级目录 route_path 为 /dynamic-form,子菜单 component 指向 views/dynamic-form 下的视图且 route_path 只填当前段 +-- ---------------------------- +-- params 携 {"badge":"NEW"}:挂顶级"动态表单"一级可见(二级折叠态角标不可见),宣传期过后清空 params 即消失 +INSERT IGNORE INTO `sys_menu` (`id`, `parent_id`, `tree_path`, `name`, `type`, `route_name`, `route_path`, `component`, `perm`, `keep_alive`, `visible`, `sort`, `icon`, `redirect`, `create_time`, `update_time`, `params`) VALUES (8, 0, '0', '动态表单', 'C', '', '/dynamic-form', 'Layout', NULL, NULL, 1, 8, 'el-icon-Document', '/dynamic-form/definition', now(), now(), '{\"badge\":\"NEW\"}'); +INSERT IGNORE INTO `sys_menu` (`id`, `parent_id`, `tree_path`, `name`, `type`, `route_name`, `route_path`, `component`, `perm`, `keep_alive`, `visible`, `sort`, `icon`, `redirect`, `create_time`, `update_time`, `params`) VALUES (801, 8, '0,8', '表单列表', 'M', 'FormDefinition', 'definition', 'dynamic-form/index', NULL, 1, 1, 1, 'el-icon-List', NULL, now(), now(), NULL); +INSERT IGNORE INTO `sys_menu` (`id`, `parent_id`, `tree_path`, `name`, `type`, `route_name`, `route_path`, `component`, `perm`, `keep_alive`, `visible`, `sort`, `icon`, `redirect`, `create_time`, `update_time`, `params`) VALUES (80101, 801, '0,8,801', '表单查询', 'B', NULL, '', NULL, 'form:definition:list', NULL, 1, 1, '', NULL, now(), now(), NULL); +INSERT IGNORE INTO `sys_menu` (`id`, `parent_id`, `tree_path`, `name`, `type`, `route_name`, `route_path`, `component`, `perm`, `keep_alive`, `visible`, `sort`, `icon`, `redirect`, `create_time`, `update_time`, `params`) VALUES (80102, 801, '0,8,801', '表单新增', 'B', NULL, '', NULL, 'form:definition:create', NULL, 1, 2, '', NULL, now(), now(), NULL); +INSERT IGNORE INTO `sys_menu` (`id`, `parent_id`, `tree_path`, `name`, `type`, `route_name`, `route_path`, `component`, `perm`, `keep_alive`, `visible`, `sort`, `icon`, `redirect`, `create_time`, `update_time`, `params`) VALUES (80103, 801, '0,8,801', '表单修改', 'B', NULL, '', NULL, 'form:definition:update', NULL, 1, 3, '', NULL, now(), now(), NULL); +INSERT IGNORE INTO `sys_menu` (`id`, `parent_id`, `tree_path`, `name`, `type`, `route_name`, `route_path`, `component`, `perm`, `keep_alive`, `visible`, `sort`, `icon`, `redirect`, `create_time`, `update_time`, `params`) VALUES (80104, 801, '0,8,801', '表单删除', 'B', NULL, '', NULL, 'form:definition:delete', NULL, 1, 4, '', NULL, now(), now(), NULL); +-- 表单设计器(隐藏菜单,visible=0,列表"设计"按钮携 id 跳转) +INSERT IGNORE INTO `sys_menu` (`id`, `parent_id`, `tree_path`, `name`, `type`, `route_name`, `route_path`, `component`, `perm`, `keep_alive`, `visible`, `sort`, `icon`, `redirect`, `create_time`, `update_time`, `params`) VALUES (803, 8, '0,8', '表单设计器', 'M', 'FormDesigner', 'designer', 'dynamic-form/designer', NULL, 1, 0, 3, '', NULL, now(), now(), NULL); +-- 表单预览(隐藏菜单,visible=0,设计器"预览"按钮携 id 跳转,运行态真预览) +INSERT IGNORE INTO `sys_menu` (`id`, `parent_id`, `tree_path`, `name`, `type`, `route_name`, `route_path`, `component`, `perm`, `keep_alive`, `visible`, `sort`, `icon`, `redirect`, `create_time`, `update_time`, `params`) VALUES (804, 8, '0,8', '表单预览', 'M', 'FormPreview', 'preview', 'dynamic-form/preview', NULL, 1, 0, 4, '', NULL, now(), now(), NULL); +-- 表单数据(隐藏菜单,visible=0,列表"数据"按钮携 formKey 跳转) +INSERT IGNORE INTO `sys_menu` (`id`, `parent_id`, `tree_path`, `name`, `type`, `route_name`, `route_path`, `component`, `perm`, `keep_alive`, `visible`, `sort`, `icon`, `redirect`, `create_time`, `update_time`, `params`) VALUES (802, 8, '0,8', '表单数据', 'M', 'FormData', 'data', 'dynamic-form/data', NULL, 1, 0, 2, '', NULL, now(), now(), NULL); +INSERT IGNORE INTO `sys_menu` (`id`, `parent_id`, `tree_path`, `name`, `type`, `route_name`, `route_path`, `component`, `perm`, `keep_alive`, `visible`, `sort`, `icon`, `redirect`, `create_time`, `update_time`, `params`) VALUES (80201, 802, '0,8,802', '数据查询', 'B', NULL, '', NULL, 'form:data:list', NULL, 1, 1, '', NULL, now(), now(), NULL); +INSERT IGNORE INTO `sys_menu` (`id`, `parent_id`, `tree_path`, `name`, `type`, `route_name`, `route_path`, `component`, `perm`, `keep_alive`, `visible`, `sort`, `icon`, `redirect`, `create_time`, `update_time`, `params`) VALUES (80202, 802, '0,8,802', '数据删除', 'B', NULL, '', NULL, 'form:data:delete', NULL, 1, 2, '', NULL, now(), now(), NULL); + +-- ---------------------------- +-- 示例表单入口(预置双入口:内嵌菜单 + 公开外链;与 saveFormMenu 生成的结构完全一致—— +-- type=M、component=dynamic-form/render、route_path=formKey、params 携 formKey、 +-- route_name 遵循 FormRender+驼峰(formKey) 全局唯一约束,防发布向导重复生成) +-- ---------------------------- +INSERT IGNORE INTO `sys_menu` (`id`, `parent_id`, `tree_path`, `name`, `type`, `route_name`, `route_path`, `component`, `perm`, `keep_alive`, `visible`, `sort`, `icon`, `redirect`, `create_time`, `update_time`, `params`) VALUES (805, 8, '0,8', '表单示例', 'C', '', 'sample', 'Layout', NULL, NULL, 1, 5, 'el-icon-Files', '/dynamic-form/sample/open_source_survey', now(), now(), NULL); +INSERT IGNORE INTO `sys_menu` (`id`, `parent_id`, `tree_path`, `name`, `type`, `route_name`, `route_path`, `component`, `perm`, `keep_alive`, `visible`, `sort`, `icon`, `redirect`, `create_time`, `update_time`, `params`) VALUES (80501, 805, '0,8,805', '开源项目问卷收集', 'M', 'FormRenderOpenSourceSurvey', 'open_source_survey', 'dynamic-form/render', NULL, NULL, 1, 1, 'el-icon-Tickets', NULL, now(), now(), '{"formKey":"open_source_survey"}'); +INSERT IGNORE INTO `sys_menu` (`id`, `parent_id`, `tree_path`, `name`, `type`, `route_name`, `route_path`, `component`, `perm`, `keep_alive`, `visible`, `sort`, `icon`, `redirect`, `create_time`, `update_time`, `params`) VALUES (80502, 805, '0,8,805', '活动报名表', 'M', 'FormRenderActivityRegistration', 'activity_registration', 'dynamic-form/render', NULL, NULL, 1, 2, 'el-icon-Calendar', NULL, now(), now(), '{"formKey":"activity_registration"}'); +INSERT IGNORE INTO `sys_menu` (`id`, `parent_id`, `tree_path`, `name`, `type`, `route_name`, `route_path`, `component`, `perm`, `keep_alive`, `visible`, `sort`, `icon`, `redirect`, `create_time`, `update_time`, `params`) VALUES (80503, 805, '0,8,805', '意见反馈', 'M', 'FormRenderFeedback', 'feedback', 'dynamic-form/render', NULL, NULL, 1, 3, 'el-icon-ChatLineRound', NULL, now(), now(), '{"formKey":"feedback"}'); + +-- ---------------------------- +-- 系统管理员角色授权(role_id=2) +-- ---------------------------- +INSERT IGNORE INTO `sys_role_menu` VALUES (2, 8), (2, 801), (2, 80101), (2, 80102), (2, 80103), (2, 80104), (2, 802), (2, 80201), (2, 80202), (2, 803), (2, 804), (2, 805), (2, 80501), (2, 80502), (2, 80503); + +-- ---------------------------- +-- 预置示例表单(开箱即用,覆盖常用组件类型;ID 段 1001-1003,避开用户自建的自增 ID) +-- 已发布(status=1)+ 双入口预置: +-- 内嵌:菜单 80501/80502/80503(动态表单 > 表单示例),menu_id 已回填,发布向导"入口管理"可直接改挂载/角色 +-- 外链:is_public=1,匿名访问 /f/{form_key}(问卷/报名/反馈天然适合对外收集) +-- ---------------------------- +INSERT IGNORE INTO `form_definition` (`id`, `form_key`, `form_name`, `description`, `form_json`, `options_json`, `status`, `is_public`, `menu_id`, `version`, `create_time`, `update_time`, `create_by`, `update_by`, `is_deleted`) VALUES +(1001, 'open_source_survey', '开源项目问卷收集', '面向社区的开源项目推荐与信息收集问卷', '[{"type":"input","field":"project_name","title":"项目名称","info":"","props":{"placeholder":"如 vue3-element-admin"},"validate":[{"required":true,"message":"请输入项目名称"}]},{"type":"input","field":"repo_url","title":"项目地址","info":"","props":{"placeholder":"https://github.com/xxx/xxx"},"validate":[{"required":true,"message":"请输入项目地址"}]},{"type":"select","field":"category","title":"项目领域","info":"","props":{},"options":[{"label":"前端","value":"frontend"},{"label":"后端","value":"backend"},{"label":"移动端","value":"mobile"},{"label":"AI 与大模型","value":"ai"},{"label":"开发工具","value":"tools"},{"label":"其他","value":"other"}],"validate":[{"required":true,"message":"请选择项目领域"}]},{"type":"radio","field":"license","title":"开源协议","info":"","options":[{"label":"MIT","value":"MIT"},{"label":"Apache-2.0","value":"Apache-2.0"},{"label":"GPLv3","value":"GPLv3"},{"label":"其他","value":"other"}]},{"type":"select","field":"stars","title":"Star 数量级","info":"","props":{},"options":[{"label":"100 以内","value":"lt100"},{"label":"100 ~ 1k","value":"100to1k"},{"label":"1k ~ 10k","value":"1kto10k"},{"label":"10k 以上","value":"gt10k"}]},{"type":"textarea","field":"recommend","title":"推荐理由","info":"","props":{"placeholder":"一句话说说它解决了什么问题"},"validate":[{"required":true,"message":"请填写推荐理由"}]},{"type":"input","field":"contact","title":"联系邮箱","info":"","props":{"placeholder":"选填,便于回访"}}]', '{"labelPosition":"right","size":"default"}', 1, 1, 80501, 1, now(), now(), NULL, NULL, 0), +(1002, 'activity_registration', '活动报名表', '线下活动/聚会报名登记,含场次选择与用餐需求', '[{"type":"input","field":"name","title":"姓名","info":"","props":{},"validate":[{"required":true,"message":"请输入姓名"}]},{"type":"input","field":"phone","title":"手机号码","info":"","props":{"placeholder":"用于接收活动通知"},"validate":[{"required":true,"message":"请输入手机号码"}]},{"type":"radio","field":"gender","title":"性别","info":"","options":[{"label":"男","value":"male"},{"label":"女","value":"female"}]},{"type":"checkbox","field":"sessions","title":"参加场次","info":"","options":[{"label":"主论坛","value":"main"},{"label":"工作坊 A","value":"workshop_a"},{"label":"工作坊 B","value":"workshop_b"},{"label":"晚间交流","value":"evening"}]},{"type":"inputNumber","field":"attendees","title":"同行人数","info":"","props":{"min":0,"max":10}},{"type":"radio","field":"dinner","title":"用餐需求","info":"","options":[{"label":"正常","value":"normal"},{"label":"素食","value":"vegetarian"},{"label":"无需用餐","value":"none"}]},{"type":"textarea","field":"remark","title":"备注","info":"","props":{"placeholder":"选填"}}]', '{"labelPosition":"right","size":"default"}', 1, 1, 80502, 1, now(), now(), NULL, NULL, 0), +(1003, 'feedback', '意见反馈', '产品/系统通用意见反馈表,含满意度评分', '[{"type":"select","field":"type","title":"反馈类型","info":"","props":{},"options":[{"label":"功能建议","value":"feature"},{"label":"问题报告","value":"bug"},{"label":"体验吐槽","value":"ux"},{"label":"其他","value":"other"}],"validate":[{"required":true,"message":"请选择反馈类型"}]},{"type":"rate","field":"rating","title":"整体满意度","info":"","props":{}},{"type":"textarea","field":"content","title":"反馈内容","info":"","props":{"placeholder":"请具体描述你的建议或遇到的问题"},"validate":[{"required":true,"message":"请填写反馈内容"}]},{"type":"input","field":"contact","title":"联系方式","info":"","props":{"placeholder":"选填,便于跟进回复"}}]', '{"labelPosition":"right","size":"default"}', 1, 1, 80503, 1, now(), now(), NULL, NULL, 0); + +-- 预置表单版本快照(已发布语义 = 固化 v1 规则,防止后续编辑定义导致历史数据回显漂移) +INSERT IGNORE INTO `form_snapshot` (`id`, `form_id`, `version`, `form_json`, `options_json`, `create_time`, `update_time`, `is_deleted`) VALUES +(1001, 1001, 1, (SELECT `form_json` FROM `form_definition` WHERE `id` = 1001), (SELECT `options_json` FROM `form_definition` WHERE `id` = 1001), now(), now(), 0), +(1002, 1002, 1, (SELECT `form_json` FROM `form_definition` WHERE `id` = 1002), (SELECT `options_json` FROM `form_definition` WHERE `id` = 1002), now(), now(), 0), +(1003, 1003, 1, (SELECT `form_json` FROM `form_definition` WHERE `id` = 1003), (SELECT `options_json` FROM `form_definition` WHERE `id` = 1003), now(), now(), 0); + diff --git a/sql/extensions/workflow.sql b/sql/extensions/workflow.sql new file mode 100644 index 00000000..279e223d --- /dev/null +++ b/sql/extensions/workflow.sql @@ -0,0 +1,82 @@ +# 工作流模块(可选扩展) +# Copyright (c) 2026-present, youlai.tech + +-- ---------------------------------------------------------------------------- +-- 工作流模块扩展脚本(全量执行,可重复运行) +-- 前置:先执行 ../youlai-admin.sql 与 dynamic-form.sql +-- 引擎表(ACT_*)由 Flowable 按 flowable.database-schema-update 策略自动创建,本脚本不含建表 +-- ---------------------------------------------------------------------------- + +USE youlai_admin; + +SET NAMES utf8mb4; +SET FOREIGN_KEY_CHECKS = 0; + +-- ---------------------------- +-- 菜单(顶级 ID=9,顺延动态表单 ID=8) +-- ---------------------------- +INSERT IGNORE INTO `sys_menu` (`id`, `parent_id`, `tree_path`, `name`, `type`, `route_name`, `route_path`, `component`, `perm`, `keep_alive`, `visible`, `sort`, `icon`, `redirect`, `create_time`, `update_time`, `params`) VALUES (9, 0, '0', '工作流', 'C', '', '/workflow', 'Layout', NULL, NULL, 1, 9, 'el-icon-Connection', '/workflow/launch', now(), now(), '{\"badge\":\"NEW\"}'); +INSERT IGNORE INTO `sys_menu` (`id`, `parent_id`, `tree_path`, `name`, `type`, `route_name`, `route_path`, `component`, `perm`, `keep_alive`, `visible`, `sort`, `icon`, `redirect`, `create_time`, `update_time`, `params`) VALUES (901, 9, '0,9', '流程设计', 'M', 'WorkflowModel', 'model', 'workflow/model', NULL, NULL, 1, 1, 'el-icon-Coin', NULL, now(), now(), NULL); +INSERT IGNORE INTO `sys_menu` (`id`, `parent_id`, `tree_path`, `name`, `type`, `route_name`, `route_path`, `component`, `perm`, `keep_alive`, `visible`, `sort`, `icon`, `redirect`, `create_time`, `update_time`, `params`) VALUES (90101, 901, '0,9,901', '流程查询', 'B', NULL, '', NULL, 'workflow:model:list', NULL, 1, 1, '', NULL, now(), now(), NULL); +INSERT IGNORE INTO `sys_menu` (`id`, `parent_id`, `tree_path`, `name`, `type`, `route_name`, `route_path`, `component`, `perm`, `keep_alive`, `visible`, `sort`, `icon`, `redirect`, `create_time`, `update_time`, `params`) VALUES (90102, 901, '0,9,901', '流程新增', 'B', NULL, '', NULL, 'workflow:model:create', NULL, 1, 2, '', NULL, now(), now(), NULL); +INSERT IGNORE INTO `sys_menu` (`id`, `parent_id`, `tree_path`, `name`, `type`, `route_name`, `route_path`, `component`, `perm`, `keep_alive`, `visible`, `sort`, `icon`, `redirect`, `create_time`, `update_time`, `params`) VALUES (90103, 901, '0,9,901', '流程修改', 'B', NULL, '', NULL, 'workflow:model:update', NULL, 1, 3, '', NULL, now(), now(), NULL); +INSERT IGNORE INTO `sys_menu` (`id`, `parent_id`, `tree_path`, `name`, `type`, `route_name`, `route_path`, `component`, `perm`, `keep_alive`, `visible`, `sort`, `icon`, `redirect`, `create_time`, `update_time`, `params`) VALUES (90104, 901, '0,9,901', '流程删除', 'B', NULL, '', NULL, 'workflow:model:delete', NULL, 1, 4, '', NULL, now(), now(), NULL); +INSERT IGNORE INTO `sys_menu` (`id`, `parent_id`, `tree_path`, `name`, `type`, `route_name`, `route_path`, `component`, `perm`, `keep_alive`, `visible`, `sort`, `icon`, `redirect`, `create_time`, `update_time`, `params`) VALUES (90105, 901, '0,9,901', '流程发布', 'B', NULL, '', NULL, 'workflow:model:deploy', NULL, 1, 5, '', NULL, now(), now(), NULL); +INSERT IGNORE INTO `sys_menu` (`id`, `parent_id`, `tree_path`, `name`, `type`, `route_name`, `route_path`, `component`, `perm`, `keep_alive`, `visible`, `sort`, `icon`, `redirect`, `create_time`, `update_time`, `params`) VALUES (90106, 901, '0,9,901', '流程重置', 'B', NULL, '', NULL, 'workflow:model:reset', NULL, 1, 6, '', NULL, now(), now(), NULL); +-- 流程启停:启用开关走 definition:update,删除复用 model:delete +INSERT IGNORE INTO `sys_menu` (`id`, `parent_id`, `tree_path`, `name`, `type`, `route_name`, `route_path`, `component`, `perm`, `keep_alive`, `visible`, `sort`, `icon`, `redirect`, `create_time`, `update_time`, `params`) VALUES (90107, 901, '0,9,901', '流程启停', 'B', NULL, '', NULL, 'workflow:definition:update', NULL, 1, 7, '', NULL, now(), now(), NULL); +-- 流程设计器(隐藏菜单,列表"设计"按钮跳转) +INSERT IGNORE INTO `sys_menu` (`id`, `parent_id`, `tree_path`, `name`, `type`, `route_name`, `route_path`, `component`, `perm`, `keep_alive`, `visible`, `sort`, `icon`, `redirect`, `create_time`, `update_time`, `params`) VALUES (902, 9, '0,9', '流程设计器', 'M', 'WorkflowDesigner', 'designer', 'workflow/designer', NULL, 1, 0, 2, '', NULL, now(), now(), NULL); + +-- 发起/审批中心仅登录校验,不设按钮权限 +-- 审批中心 = 待办/已办/我发起 三个页签 +INSERT IGNORE INTO `sys_menu` (`id`, `parent_id`, `tree_path`, `name`, `type`, `route_name`, `route_path`, `component`, `perm`, `keep_alive`, `visible`, `sort`, `icon`, `redirect`, `create_time`, `update_time`, `params`) VALUES (904, 9, '0,9', '发起流程', 'M', 'WorkflowLaunch', 'launch', 'workflow/launch', NULL, NULL, 1, 4, 'el-icon-Promotion', NULL, now(), now(), NULL); +INSERT IGNORE INTO `sys_menu` (`id`, `parent_id`, `tree_path`, `name`, `type`, `route_name`, `route_path`, `component`, `perm`, `keep_alive`, `visible`, `sort`, `icon`, `redirect`, `create_time`, `update_time`, `params`) VALUES (905, 9, '0,9', '审批中心', 'M', 'WorkflowTask', 'task', 'workflow/task/index', NULL, NULL, 1, 5, 'el-icon-Stamp', NULL, now(), now(), NULL); +INSERT IGNORE INTO `sys_menu` (`id`, `parent_id`, `tree_path`, `name`, `type`, `route_name`, `route_path`, `component`, `perm`, `keep_alive`, `visible`, `sort`, `icon`, `redirect`, `create_time`, `update_time`, `params`) VALUES (90501, 905, '0,9,905', '终止流程', 'B', NULL, '', NULL, 'workflow:instance:terminate', NULL, 1, 1, '', NULL, now(), now(), NULL); + +-- ---------------------------- +-- 系统管理员角色授权(role_id=2) +-- ---------------------------- +INSERT IGNORE INTO `sys_role_menu` VALUES (2, 9), (2, 901), (2, 90101), (2, 90102), (2, 90103), (2, 90104), (2, 90105), (2, 90106), (2, 90107), (2, 902), (2, 904), (2, 905), (2, 90501); + +-- ---------------------------- +-- 演示角色与用户(ID 段 8-10,顺延 youlai-admin.sql 预置 1-7;密码 123456) +-- 审批环节按 BPMN candidateGroups 绑定专用角色,不依赖 ADMIN +-- ---------------------------- +INSERT IGNORE INTO `sys_role` VALUES (8, '总经理', 'GENERAL_MANAGER', 8, 1, 4, NULL, now(), NULL, now(), 0); +INSERT IGNORE INTO `sys_role` VALUES (9, '财务', 'FINANCE', 9, 1, 4, NULL, now(), NULL, now(), 0); +INSERT IGNORE INTO `sys_role` VALUES (10, '行政', 'ADMINISTRATION', 10, 1, 4, NULL, now(), NULL, now(), 0); + +INSERT IGNORE INTO `sys_user` VALUES (8, 'manager', '总经理', 1, '$2a$10$xVWsNOhHrCxh5UbpCE7/HuJ.PAOKcYAqRxD2CO2nVnJS.IAXkr5aq', 1, 'https://foruda.gitee.com/images/1723603502796844527/03cdca2a_716974.gif', '18812345684', 1, 'manager@youlaitech.com', now(), NULL, now(), NULL, 0); +INSERT IGNORE INTO `sys_user` VALUES (9, 'finance', '财务专员', 2, '$2a$10$xVWsNOhHrCxh5UbpCE7/HuJ.PAOKcYAqRxD2CO2nVnJS.IAXkr5aq', 1, 'https://foruda.gitee.com/images/1723603502796844527/03cdca2a_716974.gif', '18812345685', 1, 'finance@youlaitech.com', now(), NULL, now(), NULL, 0); +INSERT IGNORE INTO `sys_user` VALUES (10, 'clerk', '行政专员', 2, '$2a$10$xVWsNOhHrCxh5UbpCE7/HuJ.PAOKcYAqRxD2CO2nVnJS.IAXkr5aq', 1, 'https://foruda.gitee.com/images/1723603502796844527/03cdca2a_716974.gif', '18812345686', 1, 'clerk@youlaitech.com', now(), NULL, now(), NULL, 0); + +INSERT IGNORE INTO `sys_user_role` VALUES (8, 8), (9, 9), (10, 10); + +-- ---------------------------- +-- 演示角色的工作流菜单授权(不含流程设计等管理菜单) +-- ---------------------------- +INSERT IGNORE INTO `sys_role_menu` VALUES (4, 9), (4, 904), (4, 905); +INSERT IGNORE INTO `sys_role_menu` VALUES (5, 9), (5, 904), (5, 905); +INSERT IGNORE INTO `sys_role_menu` VALUES (6, 9), (6, 904), (6, 905); +INSERT IGNORE INTO `sys_role_menu` VALUES (8, 9), (8, 904), (8, 905); +INSERT IGNORE INTO `sys_role_menu` VALUES (9, 9), (9, 904), (9, 905); +INSERT IGNORE INTO `sys_role_menu` VALUES (10, 9), (10, 904), (10, 905); + +-- ---------------------------- +-- 演示流程的发起表单(依赖动态表单扩展) +-- form_key 与 BPMN 开始节点 flowable:formKey 一一对应 +-- ID 段 1004-1007 顺延 dynamic-form.sql 预置的 1001-1003 +-- ---------------------------- +INSERT IGNORE INTO `form_definition` (`id`, `form_key`, `form_name`, `description`, `form_json`, `options_json`, `status`, `is_public`, `category`, `menu_id`, `version`, `create_time`, `update_time`, `create_by`, `update_by`, `is_deleted`) VALUES +(1004, 'leave_apply', '请假申请', '演示流程"请假审批"的发起表单,天数超过 3 天自动流转总经理审批', '[{"type":"select","field":"leave_type","title":"请假类型","info":"","props":{},"options":[{"label":"事假","value":"personal"},{"label":"病假","value":"sick"},{"label":"年假","value":"annual"},{"label":"调休","value":"compensatory"}],"validate":[{"required":true,"message":"请选择请假类型"}]},{"type":"inputNumber","field":"days","title":"请假天数","info":"","props":{"min":0.5,"max":30,"precision":1},"validate":[{"required":true,"message":"请输入请假天数"}]},{"type":"datePicker","field":"start_date","title":"开始日期","info":"","props":{"valueFormat":"YYYY-MM-DD"},"validate":[{"required":true,"message":"请选择开始日期"}]},{"type":"datePicker","field":"end_date","title":"结束日期","info":"","props":{"valueFormat":"YYYY-MM-DD"},"validate":[{"required":true,"message":"请选择结束日期"}]},{"type":"textarea","field":"reason","title":"请假事由","info":"","props":{"placeholder":"请简要说明请假事由"},"validate":[{"required":true,"message":"请填写请假事由"}]}]', '{"labelPosition":"right","size":"default"}', 1, 0, 'workflow', NULL, 1, now(), now(), NULL, NULL, 0), +(1005, 'expense_apply', '报销申请', '演示流程"报销审批"的发起表单,金额超过 5000 元自动流转总经理审批', '[{"type":"select","field":"expense_type","title":"报销类型","info":"","props":{},"options":[{"label":"差旅费","value":"travel"},{"label":"办公费","value":"office"},{"label":"招待费","value":"hospitality"},{"label":"培训费","value":"training"}],"validate":[{"required":true,"message":"请选择报销类型"}]},{"type":"inputNumber","field":"amount","title":"报销金额(元)","info":"","props":{"min":0,"max":1000000,"precision":2},"validate":[{"required":true,"message":"请输入报销金额"}]},{"type":"datePicker","field":"expense_date","title":"费用发生日期","info":"","props":{"valueFormat":"YYYY-MM-DD"},"validate":[{"required":true,"message":"请选择费用发生日期"}]},{"type":"textarea","field":"reason","title":"报销说明","info":"","props":{"placeholder":"请简要说明费用用途"},"validate":[{"required":true,"message":"请填写报销说明"}]}]', '{"labelPosition":"right","size":"default"}', 1, 0, 'workflow', NULL, 1, now(), now(), NULL, NULL, 0), +(1006, 'purchase_apply', '采购申请', '演示流程"采购申请"的发起表单,金额超过 1 万元流转总经理审批,通过后回退发起人执行采购', '[{"type":"input","field":"item_name","title":"采购物品","info":"","props":{"placeholder":"请输入采购物品名称"},"validate":[{"required":true,"message":"请填写采购物品"}]},{"type":"inputNumber","field":"quantity","title":"采购数量","info":"","props":{"min":1,"precision":0},"validate":[{"required":true,"message":"请输入采购数量"}]},{"type":"inputNumber","field":"amount","title":"预估金额(元)","info":"","props":{"min":0,"precision":2},"validate":[{"required":true,"message":"请输入预估金额"}]},{"type":"textarea","field":"reason","title":"采购事由","info":"","props":{"placeholder":"请简要说明采购背景与用途"},"validate":[{"required":true,"message":"请填写采购事由"}]}]', '{"labelPosition":"right","size":"default"}', 1, 0, 'workflow', NULL, 1, now(), now(), NULL, NULL, 0), +(1007, 'seal_apply', '用章申请', '演示流程"用章申请"的发起表单,部门领导与行政两级审批', '[{"type":"select","field":"seal_type","title":"印章类型","info":"","props":{},"options":[{"label":"公章","value":"official"},{"label":"合同章","value":"contract"},{"label":"财务章","value":"finance"},{"label":"法人章","value":"legal"}],"validate":[{"required":true,"message":"请选择印章类型"}]},{"type":"datePicker","field":"usage_date","title":"用章日期","info":"","props":{"valueFormat":"YYYY-MM-DD"},"validate":[{"required":true,"message":"请选择用章日期"}]},{"type":"textarea","field":"usage","title":"用章事由","info":"","props":{"placeholder":"请说明用章文件及事由"},"validate":[{"required":true,"message":"请填写用章事由"}]}]', '{"labelPosition":"right","size":"default"}', 1, 0, 'workflow', NULL, 1, now(), now(), NULL, NULL, 0); + +-- 预置表单版本快照(固化 v1 规则,防止编辑定义后历史数据回显漂移) +INSERT IGNORE INTO `form_snapshot` (`id`, `form_id`, `version`, `form_json`, `options_json`, `create_time`, `update_time`, `is_deleted`) VALUES +(1004, 1004, 1, (SELECT `form_json` FROM `form_definition` WHERE `id` = 1004), (SELECT `options_json` FROM `form_definition` WHERE `id` = 1004), now(), now(), 0), +(1005, 1005, 1, (SELECT `form_json` FROM `form_definition` WHERE `id` = 1005), (SELECT `options_json` FROM `form_definition` WHERE `id` = 1005), now(), now(), 0), +(1006, 1006, 1, (SELECT `form_json` FROM `form_definition` WHERE `id` = 1006), (SELECT `options_json` FROM `form_definition` WHERE `id` = 1006), now(), now(), 0), +(1007, 1007, 1, (SELECT `form_json` FROM `form_definition` WHERE `id` = 1007), (SELECT `options_json` FROM `form_definition` WHERE `id` = 1007), now(), now(), 0); diff --git a/sql/youlai-admin.sql b/sql/youlai-admin.sql index f8f0da5a..778a1eb6 100644 --- a/sql/youlai-admin.sql +++ b/sql/youlai-admin.sql @@ -18,7 +18,7 @@ SET NAMES utf8mb4; # 设置字符集 SET FOREIGN_KEY_CHECKS = 0; # 关闭外键检查,加快导入速度 -- ---------------------------- --- Table structure for sys_dept +-- 表结构:sys_dept -- ---------------------------- DROP TABLE IF EXISTS `sys_dept`; CREATE TABLE `sys_dept` ( @@ -39,76 +39,78 @@ CREATE TABLE `sys_dept` ( ) ENGINE = InnoDB CHARACTER SET = utf8mb4 COMMENT = '部门管理表'; -- ---------------------------- --- Records of sys_dept +-- 表数据:sys_dept -- ---------------------------- INSERT INTO `sys_dept` VALUES (1, '有来技术', 'YOULAI', 0, '0', 1, 1, 1, NULL, 1, now(), 0); INSERT INTO `sys_dept` VALUES (2, '研发部门', 'RD001', 1, '0,1', 1, 1, 2, NULL, 2, now(), 0); INSERT INTO `sys_dept` VALUES (3, '测试部门', 'QA001', 1, '0,1', 1, 1, 2, NULL, 2, now(), 0); -- ---------------------------- --- Table structure for sys_dict +-- 表结构:sys_dict -- ---------------------------- DROP TABLE IF EXISTS `sys_dict`; CREATE TABLE `sys_dict` ( - `id` bigint NOT NULL AUTO_INCREMENT COMMENT '主键 ', - `dict_code` varchar(50) COMMENT '类型编码', - `name` varchar(50) COMMENT '类型名称', - `status` tinyint(1) DEFAULT '0' COMMENT '状态(0:正常;1:禁用)', + `id` bigint NOT NULL AUTO_INCREMENT COMMENT '主键', + `dict_code` varchar(50) COMMENT '字典编码', + `name` varchar(50) COMMENT '字典名称', + `status` tinyint(1) DEFAULT '0' COMMENT '状态(1-启用 0-停用)', `remark` varchar(255) COMMENT '备注', `create_time` datetime COMMENT '创建时间', `create_by` bigint COMMENT '创建人ID', `update_time` datetime COMMENT '更新时间', `update_by` bigint COMMENT '修改人ID', - `is_deleted` tinyint DEFAULT '0' COMMENT '是否删除(1-删除,0-未删除)', + `is_deleted` tinyint DEFAULT '0' COMMENT '逻辑删除(1-已删除 0-未删除)', PRIMARY KEY (`id`) USING BTREE, KEY `idx_dict_code` (`dict_code`) -) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='数据字典类型表'; +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='字典表'; -- ---------------------------- --- Records of sys_dict +-- 表数据:sys_dict -- ---------------------------- -INSERT INTO `sys_dict` VALUES (1, 'gender', '性别', 1, NULL, now() , 1,now(), 1,0); -INSERT INTO `sys_dict` VALUES (2, 'notice_type', '通知类型', 1, NULL, now(), 1,now(), 1,0); -INSERT INTO `sys_dict` VALUES (3, 'notice_level', '通知级别', 1, NULL, now(), 1,now(), 1,0); +INSERT INTO `sys_dict` VALUES (1, 'gender', '性别', 1, NULL, now(), 1, now(), 1, 0); +INSERT INTO `sys_dict` VALUES (2, 'notice_type', '通知类型', 1, NULL, now(), 1, now(), 1, 0); +INSERT INTO `sys_dict` VALUES (3, 'notice_level', '通知级别', 1, NULL, now(), 1, now(), 1, 0); -- ---------------------------- --- Table structure for sys_dict_item +-- 表结构:sys_dict_item -- ---------------------------- DROP TABLE IF EXISTS `sys_dict_item`; CREATE TABLE `sys_dict_item` ( `id` bigint NOT NULL AUTO_INCREMENT COMMENT '主键', - `dict_code` varchar(50) COMMENT '关联字典编码,与sys_dict表中的dict_code对应', + `dict_code` varchar(50) COMMENT '字典编码,与 sys_dict.dict_code 对应', `value` varchar(50) COMMENT '字典项值', `label` varchar(100) COMMENT '字典项标签', - `tag_type` varchar(50) COMMENT '标签类型,用于前端样式展示(如success、warning等)', - `status` tinyint DEFAULT '0' COMMENT '状态(1-正常,0-禁用)', + `tag_type` varchar(50) COMMENT '标签样式(primary-主要 success-成功 warning-警告 danger-危险 info-信息,空为无样式)', + `status` tinyint DEFAULT '0' COMMENT '状态(1-启用 0-停用)', `sort` int DEFAULT '0' COMMENT '排序', `remark` varchar(255) COMMENT '备注', `create_time` datetime COMMENT '创建时间', `create_by` bigint COMMENT '创建人ID', `update_time` datetime COMMENT '更新时间', `update_by` bigint COMMENT '修改人ID', - PRIMARY KEY (`id`) USING BTREE -) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='数据字典项表'; + `is_deleted` tinyint DEFAULT '0' COMMENT '逻辑删除(1-已删除 0-未删除)', + PRIMARY KEY (`id`) USING BTREE, + KEY `idx_dict_code` (`dict_code`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='字典项表'; -- ---------------------------- --- Records of sys_dict_item +-- 表数据:sys_dict_item -- ---------------------------- -INSERT INTO `sys_dict_item` VALUES (1, 'gender', '1', '男', 'primary', 1, 1, NULL, now(), 1,now(),1); -INSERT INTO `sys_dict_item` VALUES (2, 'gender', '2', '女', 'danger', 1, 2, NULL, now(), 1,now(),1); -INSERT INTO `sys_dict_item` VALUES (3, 'gender', '0', '保密', 'info', 1, 3, NULL, now(), 1,now(),1); -INSERT INTO `sys_dict_item` VALUES (4, 'notice_type', '1', '系统升级', 'success', 1, 1, '', now(), 1,now(),1); -INSERT INTO `sys_dict_item` VALUES (5, 'notice_type', '2', '系统维护', 'primary', 1, 2, '', now(), 1,now(),1); -INSERT INTO `sys_dict_item` VALUES (6, 'notice_type', '3', '安全警告', 'danger', 1, 3, '', now(), 1,now(),1); -INSERT INTO `sys_dict_item` VALUES (7, 'notice_type', '4', '假期通知', 'success', 1, 4, '', now(), 1,now(),1); -INSERT INTO `sys_dict_item` VALUES (8, 'notice_type', '5', '公司新闻', 'primary', 1, 5, '', now(), 1,now(),1); -INSERT INTO `sys_dict_item` VALUES (9, 'notice_type', '99', '其他', 'info', 1, 99, '', now(), 1,now(),1); -INSERT INTO `sys_dict_item` VALUES (10, 'notice_level', 'L', '低', 'info', 1, 1, '', now(), 1,now(),1); -INSERT INTO `sys_dict_item` VALUES (11, 'notice_level', 'M', '中', 'warning', 1, 2, '', now(), 1,now(),1); -INSERT INTO `sys_dict_item` VALUES (12, 'notice_level', 'H', '高', 'danger', 1, 3, '', now(), 1,now(),1); +INSERT INTO `sys_dict_item` VALUES (1, 'gender', '1', '男', 'primary', 1, 1, NULL, now(), 1, now(), 1, 0); +INSERT INTO `sys_dict_item` VALUES (2, 'gender', '2', '女', 'danger', 1, 2, NULL, now(), 1, now(), 1, 0); +INSERT INTO `sys_dict_item` VALUES (3, 'gender', '0', '保密', 'info', 1, 3, NULL, now(), 1, now(), 1, 0); +INSERT INTO `sys_dict_item` VALUES (4, 'notice_type', '1', '系统升级', 'success', 1, 1, '', now(), 1, now(), 1, 0); +INSERT INTO `sys_dict_item` VALUES (5, 'notice_type', '2', '系统维护', 'primary', 1, 2, '', now(), 1, now(), 1, 0); +INSERT INTO `sys_dict_item` VALUES (6, 'notice_type', '3', '安全警告', 'danger', 1, 3, '', now(), 1, now(), 1, 0); +INSERT INTO `sys_dict_item` VALUES (7, 'notice_type', '4', '假期通知', 'success', 1, 4, '', now(), 1, now(), 1, 0); +INSERT INTO `sys_dict_item` VALUES (8, 'notice_type', '5', '公司新闻', 'primary', 1, 5, '', now(), 1, now(), 1, 0); +INSERT INTO `sys_dict_item` VALUES (9, 'notice_type', '99', '其他', 'info', 1, 99, '', now(), 1, now(), 1, 0); +INSERT INTO `sys_dict_item` VALUES (10, 'notice_level', 'L', '低', 'info', 1, 1, '', now(), 1, now(), 1, 0); +INSERT INTO `sys_dict_item` VALUES (11, 'notice_level', 'M', '中', 'warning', 1, 2, '', now(), 1, now(), 1, 0); +INSERT INTO `sys_dict_item` VALUES (12, 'notice_level', 'H', '高', 'danger', 1, 3, '', now(), 1, now(), 1, 0); -- ---------------------------- --- Table structure for sys_menu +-- 表结构:sys_menu -- ---------------------------- DROP TABLE IF EXISTS `sys_menu`; CREATE TABLE `sys_menu` ( @@ -122,7 +124,6 @@ CREATE TABLE `sys_menu` ( `component` varchar(128) COMMENT '组件路径(组件页面完整路径,相对于 src/views/,缺省后缀 .vue)', `external_url` varchar(512) COMMENT '外链地址', `perm` varchar(128) COMMENT '【按钮】权限标识', - `always_show` tinyint DEFAULT 0 COMMENT '【目录】只有一个子路由是否始终显示(1-是 0-否)', `keep_alive` tinyint DEFAULT 0 COMMENT '【菜单】是否开启页面缓存(1-是 0-否)', `visible` tinyint(1) DEFAULT 1 COMMENT '显示状态(1-显示 0-隐藏)', `sort` int DEFAULT 0 COMMENT '排序', @@ -135,118 +136,122 @@ CREATE TABLE `sys_menu` ( ) ENGINE = InnoDB CHARACTER SET = utf8mb4 COMMENT = '系统菜单表'; -- ---------------------------- --- Records of sys_menu +-- 表数据:sys_menu -- ---------------------------- --- 顶级目录(1-9):系统/代码生成/文档/接口文档/组件/演示/多级/路由 -INSERT INTO `sys_menu` (`id`, `parent_id`, `tree_path`, `name`, `type`, `route_name`, `route_path`, `component`, `perm`, `always_show`, `keep_alive`, `visible`, `sort`, `icon`, `redirect`, `create_time`, `update_time`, `params`) VALUES (1, 0, '0', '系统管理', 'C', '', '/system', 'Layout', NULL, NULL, NULL, 1, 1, 'system', '/system/user', now(), now(), NULL); -INSERT INTO `sys_menu` (`id`, `parent_id`, `tree_path`, `name`, `type`, `route_name`, `route_path`, `component`, `perm`, `always_show`, `keep_alive`, `visible`, `sort`, `icon`, `redirect`, `create_time`, `update_time`, `params`) VALUES (2, 0, '0', '代码生成', 'C', '', '/codegen', 'Layout', NULL, NULL, NULL, 1, 2, 'code', '/codegen/index', now(), now(), NULL); -INSERT INTO `sys_menu` (`id`, `parent_id`, `tree_path`, `name`, `type`, `route_name`, `route_path`, `component`, `perm`, `always_show`, `keep_alive`, `visible`, `sort`, `icon`, `redirect`, `create_time`, `update_time`, `params`) VALUES (4, 0, '0', '平台文档', 'C', '', '/doc', 'Layout', NULL, NULL, NULL, 1, 4, 'document', '', now(), now(), NULL); -INSERT INTO `sys_menu` (`id`, `parent_id`, `tree_path`, `name`, `type`, `route_name`, `route_path`, `component`, `perm`, `always_show`, `keep_alive`, `visible`, `sort`, `icon`, `redirect`, `create_time`, `update_time`, `params`) VALUES (5, 0, '0', '接口文档', 'C', '', '/api', 'Layout', NULL, NULL, NULL, 1, 5, 'api', '', now(), now(), NULL); -INSERT INTO `sys_menu` (`id`, `parent_id`, `tree_path`, `name`, `type`, `route_name`, `route_path`, `component`, `perm`, `always_show`, `keep_alive`, `visible`, `sort`, `icon`, `redirect`, `create_time`, `update_time`, `params`) VALUES (6, 0, '0', '组件封装', 'C', '', '/component', 'Layout', NULL, NULL, NULL, 1, 6, 'menu', '', now(), now(), NULL); -INSERT INTO `sys_menu` (`id`, `parent_id`, `tree_path`, `name`, `type`, `route_name`, `route_path`, `component`, `perm`, `always_show`, `keep_alive`, `visible`, `sort`, `icon`, `redirect`, `create_time`, `update_time`, `params`) VALUES (7, 0, '0', '功能演示', 'C', '', '/function', 'Layout', NULL, NULL, NULL, 1, 7, 'menu', '', now(), now(), NULL); -INSERT INTO `sys_menu` (`id`, `parent_id`, `tree_path`, `name`, `type`, `route_name`, `route_path`, `component`, `perm`, `always_show`, `keep_alive`, `visible`, `sort`, `icon`, `redirect`, `create_time`, `update_time`, `params`) VALUES (8, 0, '0', '多级菜单', 'C', NULL, '/multi-level', 'Layout', NULL, 1, NULL, 1, 8, 'cascader', '', now(), now(), NULL); -INSERT INTO `sys_menu` (`id`, `parent_id`, `tree_path`, `name`, `type`, `route_name`, `route_path`, `component`, `perm`, `always_show`, `keep_alive`, `visible`, `sort`, `icon`, `redirect`, `create_time`, `update_time`, `params`) VALUES (9, 0, '0', '路由参数', 'C', '', '/route-param', 'Layout', NULL, NULL, NULL, 1, 9, 'el-icon-ElementPlus', '', now(), now(), NULL); +-- 扩展段 8-99 由 sql/extensions/ 脚本占用:动态表单(8,dynamic-form.sql)/工作流(9,workflow.sql),新扩展模块从 10 领号顺延 +-- ID 规则:子 ID = 父 ID × 100 + 两位序号(如 10101 即用户管理 101 的第 1 个按钮),tree_path 与 ID 同构可机器校验 +INSERT INTO `sys_menu` (`id`, `parent_id`, `tree_path`, `name`, `type`, `route_name`, `route_path`, `component`, `perm`, `keep_alive`, `visible`, `sort`, `icon`, `redirect`, `create_time`, `update_time`, `params`) VALUES (1, 0, '0', '系统管理', 'C', '', '/system', 'Layout', NULL, NULL, 1, 1, 'system', '/system/user', now(), now(), NULL); +-- 数据大屏走站内外链:E 型新标签页模式,external_url 填站内路径(前端按当前站点补全域名),指向布局外的独立全屏页 +INSERT INTO `sys_menu` (`id`, `parent_id`, `tree_path`, `name`, `type`, `route_name`, `route_path`, `component`, `external_url`, `perm`, `keep_alive`, `visible`, `sort`, `icon`, `redirect`, `create_time`, `update_time`, `params`) VALUES (2, 0, '0', '数据大屏', 'E', NULL, NULL, NULL, '/data-screen', NULL, NULL, 1, 2, 'el-icon-Monitor', NULL, now(), now(), NULL); +INSERT INTO `sys_menu` (`id`, `parent_id`, `tree_path`, `name`, `type`, `route_name`, `route_path`, `component`, `perm`, `keep_alive`, `visible`, `sort`, `icon`, `redirect`, `create_time`, `update_time`, `params`) VALUES (3, 0, '0', '代码生成', 'M', 'Codegen', '/codegen', 'codegen/index', NULL, 1, 1, 3, 'code', NULL, now(), now(), NULL); -- 系统管理 -INSERT INTO `sys_menu` (`id`, `parent_id`, `tree_path`, `name`, `type`, `route_name`, `route_path`, `component`, `perm`, `always_show`, `keep_alive`, `visible`, `sort`, `icon`, `redirect`, `create_time`, `update_time`, `params`) VALUES (210, 1, '0,1', '用户管理', 'M', 'User', 'user', 'system/user/index', NULL, NULL, 1, 1, 1, 'el-icon-User', NULL, now(), now(), NULL); -INSERT INTO `sys_menu` (`id`, `parent_id`, `tree_path`, `name`, `type`, `route_name`, `route_path`, `component`, `perm`, `always_show`, `keep_alive`, `visible`, `sort`, `icon`, `redirect`, `create_time`, `update_time`, `params`) VALUES (2101, 210, '0,1,210', '用户查询', 'B', NULL, '', NULL, 'sys:user:list', NULL, NULL, 1, 1, '', NULL, now(), now(), NULL); -INSERT INTO `sys_menu` (`id`, `parent_id`, `tree_path`, `name`, `type`, `route_name`, `route_path`, `component`, `perm`, `always_show`, `keep_alive`, `visible`, `sort`, `icon`, `redirect`, `create_time`, `update_time`, `params`) VALUES (2102, 210, '0,1,210', '用户新增', 'B', NULL, '', NULL, 'sys:user:create', NULL, NULL, 1, 2, '', NULL, now(), now(), NULL); -INSERT INTO `sys_menu` (`id`, `parent_id`, `tree_path`, `name`, `type`, `route_name`, `route_path`, `component`, `perm`, `always_show`, `keep_alive`, `visible`, `sort`, `icon`, `redirect`, `create_time`, `update_time`, `params`) VALUES (2103, 210, '0,1,210', '用户编辑', 'B', NULL, '', NULL, 'sys:user:update', NULL, NULL, 1, 3, '', NULL, now(), now(), NULL); -INSERT INTO `sys_menu` (`id`, `parent_id`, `tree_path`, `name`, `type`, `route_name`, `route_path`, `component`, `perm`, `always_show`, `keep_alive`, `visible`, `sort`, `icon`, `redirect`, `create_time`, `update_time`, `params`) VALUES (2104, 210, '0,1,210', '用户删除', 'B', NULL, '', NULL, 'sys:user:delete', NULL, NULL, 1, 4, '', NULL, now(), now(), NULL); -INSERT INTO `sys_menu` (`id`, `parent_id`, `tree_path`, `name`, `type`, `route_name`, `route_path`, `component`, `perm`, `always_show`, `keep_alive`, `visible`, `sort`, `icon`, `redirect`, `create_time`, `update_time`, `params`) VALUES (2105, 210, '0,1,210', '重置密码', 'B', NULL, '', NULL, 'sys:user:reset-password', NULL, NULL, 1, 5, '', NULL, now(), now(), NULL); -INSERT INTO `sys_menu` (`id`, `parent_id`, `tree_path`, `name`, `type`, `route_name`, `route_path`, `component`, `perm`, `always_show`, `keep_alive`, `visible`, `sort`, `icon`, `redirect`, `create_time`, `update_time`, `params`) VALUES (2106, 210, '0,1,210', '用户导入', 'B', NULL, '', NULL, 'sys:user:import', NULL, NULL, 1, 6, '', NULL, now(), now(), NULL); -INSERT INTO `sys_menu` (`id`, `parent_id`, `tree_path`, `name`, `type`, `route_name`, `route_path`, `component`, `perm`, `always_show`, `keep_alive`, `visible`, `sort`, `icon`, `redirect`, `create_time`, `update_time`, `params`) VALUES (2107, 210, '0,1,210', '用户导出', 'B', NULL, '', NULL, 'sys:user:export', NULL, NULL, 1, 7, '', NULL, now(), now(), NULL); +INSERT INTO `sys_menu` (`id`, `parent_id`, `tree_path`, `name`, `type`, `route_name`, `route_path`, `component`, `perm`, `keep_alive`, `visible`, `sort`, `icon`, `redirect`, `create_time`, `update_time`, `params`) VALUES (101, 1, '0,1', '用户管理', 'M', 'User', 'user', 'system/user/index', NULL, 1, 1, 1, 'el-icon-User', NULL, now(), now(), NULL); +INSERT INTO `sys_menu` (`id`, `parent_id`, `tree_path`, `name`, `type`, `route_name`, `route_path`, `component`, `perm`, `keep_alive`, `visible`, `sort`, `icon`, `redirect`, `create_time`, `update_time`, `params`) VALUES (10101, 101, '0,1,101', '用户查询', 'B', NULL, '', NULL, 'sys:user:list', NULL, 1, 1, '', NULL, now(), now(), NULL); +INSERT INTO `sys_menu` (`id`, `parent_id`, `tree_path`, `name`, `type`, `route_name`, `route_path`, `component`, `perm`, `keep_alive`, `visible`, `sort`, `icon`, `redirect`, `create_time`, `update_time`, `params`) VALUES (10102, 101, '0,1,101', '用户新增', 'B', NULL, '', NULL, 'sys:user:create', NULL, 1, 2, '', NULL, now(), now(), NULL); +INSERT INTO `sys_menu` (`id`, `parent_id`, `tree_path`, `name`, `type`, `route_name`, `route_path`, `component`, `perm`, `keep_alive`, `visible`, `sort`, `icon`, `redirect`, `create_time`, `update_time`, `params`) VALUES (10103, 101, '0,1,101', '用户编辑', 'B', NULL, '', NULL, 'sys:user:update', NULL, 1, 3, '', NULL, now(), now(), NULL); +INSERT INTO `sys_menu` (`id`, `parent_id`, `tree_path`, `name`, `type`, `route_name`, `route_path`, `component`, `perm`, `keep_alive`, `visible`, `sort`, `icon`, `redirect`, `create_time`, `update_time`, `params`) VALUES (10104, 101, '0,1,101', '用户删除', 'B', NULL, '', NULL, 'sys:user:delete', NULL, 1, 4, '', NULL, now(), now(), NULL); +INSERT INTO `sys_menu` (`id`, `parent_id`, `tree_path`, `name`, `type`, `route_name`, `route_path`, `component`, `perm`, `keep_alive`, `visible`, `sort`, `icon`, `redirect`, `create_time`, `update_time`, `params`) VALUES (10105, 101, '0,1,101', '重置密码', 'B', NULL, '', NULL, 'sys:user:reset-password', NULL, 1, 5, '', NULL, now(), now(), NULL); +INSERT INTO `sys_menu` (`id`, `parent_id`, `tree_path`, `name`, `type`, `route_name`, `route_path`, `component`, `perm`, `keep_alive`, `visible`, `sort`, `icon`, `redirect`, `create_time`, `update_time`, `params`) VALUES (10106, 101, '0,1,101', '用户导入', 'B', NULL, '', NULL, 'sys:user:import', NULL, 1, 6, '', NULL, now(), now(), NULL); +INSERT INTO `sys_menu` (`id`, `parent_id`, `tree_path`, `name`, `type`, `route_name`, `route_path`, `component`, `perm`, `keep_alive`, `visible`, `sort`, `icon`, `redirect`, `create_time`, `update_time`, `params`) VALUES (10107, 101, '0,1,101', '用户导出', 'B', NULL, '', NULL, 'sys:user:export', NULL, 1, 7, '', NULL, now(), now(), NULL); -INSERT INTO `sys_menu` (`id`, `parent_id`, `tree_path`, `name`, `type`, `route_name`, `route_path`, `component`, `perm`, `always_show`, `keep_alive`, `visible`, `sort`, `icon`, `redirect`, `create_time`, `update_time`, `params`) VALUES (220, 1, '0,1', '角色管理', 'M', 'Role', 'role', 'system/role/index', NULL, NULL, 1, 1, 2, 'role', NULL, now(), now(), NULL); -INSERT INTO `sys_menu` (`id`, `parent_id`, `tree_path`, `name`, `type`, `route_name`, `route_path`, `component`, `perm`, `always_show`, `keep_alive`, `visible`, `sort`, `icon`, `redirect`, `create_time`, `update_time`, `params`) VALUES (2201, 220, '0,1,220', '角色查询', 'B', NULL, '', NULL, 'sys:role:list', NULL, NULL, 1, 1, '', NULL, now(), now(), NULL); -INSERT INTO `sys_menu` (`id`, `parent_id`, `tree_path`, `name`, `type`, `route_name`, `route_path`, `component`, `perm`, `always_show`, `keep_alive`, `visible`, `sort`, `icon`, `redirect`, `create_time`, `update_time`, `params`) VALUES (2202, 220, '0,1,220', '角色新增', 'B', NULL, '', NULL, 'sys:role:create', NULL, NULL, 1, 2, '', NULL, now(), now(), NULL); -INSERT INTO `sys_menu` (`id`, `parent_id`, `tree_path`, `name`, `type`, `route_name`, `route_path`, `component`, `perm`, `always_show`, `keep_alive`, `visible`, `sort`, `icon`, `redirect`, `create_time`, `update_time`, `params`) VALUES (2203, 220, '0,1,220', '角色编辑', 'B', NULL, '', NULL, 'sys:role:update', NULL, NULL, 1, 3, '', NULL, now(), now(), NULL); -INSERT INTO `sys_menu` (`id`, `parent_id`, `tree_path`, `name`, `type`, `route_name`, `route_path`, `component`, `perm`, `always_show`, `keep_alive`, `visible`, `sort`, `icon`, `redirect`, `create_time`, `update_time`, `params`) VALUES (2204, 220, '0,1,220', '角色删除', 'B', NULL, '', NULL, 'sys:role:delete', NULL, NULL, 1, 4, '', NULL, now(), now(), NULL); -INSERT INTO `sys_menu` (`id`, `parent_id`, `tree_path`, `name`, `type`, `route_name`, `route_path`, `component`, `perm`, `always_show`, `keep_alive`, `visible`, `sort`, `icon`, `redirect`, `create_time`, `update_time`, `params`) VALUES (2205, 220, '0,1,220', '角色分配权限', 'B', NULL, '', NULL, 'sys:role:assign', NULL, NULL, 1, 5, '', NULL, now(), now(), NULL); +INSERT INTO `sys_menu` (`id`, `parent_id`, `tree_path`, `name`, `type`, `route_name`, `route_path`, `component`, `perm`, `keep_alive`, `visible`, `sort`, `icon`, `redirect`, `create_time`, `update_time`, `params`) VALUES (102, 1, '0,1', '角色管理', 'M', 'Role', 'role', 'system/role/index', NULL, 1, 1, 2, 'role', NULL, now(), now(), NULL); +INSERT INTO `sys_menu` (`id`, `parent_id`, `tree_path`, `name`, `type`, `route_name`, `route_path`, `component`, `perm`, `keep_alive`, `visible`, `sort`, `icon`, `redirect`, `create_time`, `update_time`, `params`) VALUES (10201, 102, '0,1,102', '角色查询', 'B', NULL, '', NULL, 'sys:role:list', NULL, 1, 1, '', NULL, now(), now(), NULL); +INSERT INTO `sys_menu` (`id`, `parent_id`, `tree_path`, `name`, `type`, `route_name`, `route_path`, `component`, `perm`, `keep_alive`, `visible`, `sort`, `icon`, `redirect`, `create_time`, `update_time`, `params`) VALUES (10202, 102, '0,1,102', '角色新增', 'B', NULL, '', NULL, 'sys:role:create', NULL, 1, 2, '', NULL, now(), now(), NULL); +INSERT INTO `sys_menu` (`id`, `parent_id`, `tree_path`, `name`, `type`, `route_name`, `route_path`, `component`, `perm`, `keep_alive`, `visible`, `sort`, `icon`, `redirect`, `create_time`, `update_time`, `params`) VALUES (10203, 102, '0,1,102', '角色编辑', 'B', NULL, '', NULL, 'sys:role:update', NULL, 1, 3, '', NULL, now(), now(), NULL); +INSERT INTO `sys_menu` (`id`, `parent_id`, `tree_path`, `name`, `type`, `route_name`, `route_path`, `component`, `perm`, `keep_alive`, `visible`, `sort`, `icon`, `redirect`, `create_time`, `update_time`, `params`) VALUES (10204, 102, '0,1,102', '角色删除', 'B', NULL, '', NULL, 'sys:role:delete', NULL, 1, 4, '', NULL, now(), now(), NULL); +INSERT INTO `sys_menu` (`id`, `parent_id`, `tree_path`, `name`, `type`, `route_name`, `route_path`, `component`, `perm`, `keep_alive`, `visible`, `sort`, `icon`, `redirect`, `create_time`, `update_time`, `params`) VALUES (10205, 102, '0,1,102', '角色分配权限', 'B', NULL, '', NULL, 'sys:role:assign', NULL, 1, 5, '', NULL, now(), now(), NULL); -INSERT INTO `sys_menu` (`id`, `parent_id`, `tree_path`, `name`, `type`, `route_name`, `route_path`, `component`, `perm`, `always_show`, `keep_alive`, `visible`, `sort`, `icon`, `redirect`, `create_time`, `update_time`, `params`) VALUES (230, 1, '0,1', '菜单管理', 'M', 'SysMenu', 'menu', 'system/menu/index', NULL, NULL, 1, 1, 3, 'menu', NULL, now(), now(), NULL); -INSERT INTO `sys_menu` (`id`, `parent_id`, `tree_path`, `name`, `type`, `route_name`, `route_path`, `component`, `perm`, `always_show`, `keep_alive`, `visible`, `sort`, `icon`, `redirect`, `create_time`, `update_time`, `params`) VALUES (2301, 230, '0,1,230', '菜单查询', 'B', NULL, '', NULL, 'sys:menu:list', NULL, NULL, 1, 1, '', NULL, now(), now(), NULL); -INSERT INTO `sys_menu` (`id`, `parent_id`, `tree_path`, `name`, `type`, `route_name`, `route_path`, `component`, `perm`, `always_show`, `keep_alive`, `visible`, `sort`, `icon`, `redirect`, `create_time`, `update_time`, `params`) VALUES (2302, 230, '0,1,230', '菜单新增', 'B', NULL, '', NULL, 'sys:menu:create', NULL, NULL, 1, 2, '', NULL, now(), now(), NULL); -INSERT INTO `sys_menu` (`id`, `parent_id`, `tree_path`, `name`, `type`, `route_name`, `route_path`, `component`, `perm`, `always_show`, `keep_alive`, `visible`, `sort`, `icon`, `redirect`, `create_time`, `update_time`, `params`) VALUES (2303, 230, '0,1,230', '菜单编辑', 'B', NULL, '', NULL, 'sys:menu:update', NULL, NULL, 1, 3, '', NULL, now(), now(), NULL); -INSERT INTO `sys_menu` (`id`, `parent_id`, `tree_path`, `name`, `type`, `route_name`, `route_path`, `component`, `perm`, `always_show`, `keep_alive`, `visible`, `sort`, `icon`, `redirect`, `create_time`, `update_time`, `params`) VALUES (2304, 230, '0,1,230', '菜单删除', 'B', NULL, '', NULL, 'sys:menu:delete', NULL, NULL, 1, 4, '', NULL, now(), now(), NULL); +INSERT INTO `sys_menu` (`id`, `parent_id`, `tree_path`, `name`, `type`, `route_name`, `route_path`, `component`, `perm`, `keep_alive`, `visible`, `sort`, `icon`, `redirect`, `create_time`, `update_time`, `params`) VALUES (103, 1, '0,1', '菜单管理', 'M', 'SysMenu', 'menu', 'system/menu/index', NULL, 1, 1, 3, 'menu', NULL, now(), now(), NULL); +INSERT INTO `sys_menu` (`id`, `parent_id`, `tree_path`, `name`, `type`, `route_name`, `route_path`, `component`, `perm`, `keep_alive`, `visible`, `sort`, `icon`, `redirect`, `create_time`, `update_time`, `params`) VALUES (10301, 103, '0,1,103', '菜单查询', 'B', NULL, '', NULL, 'sys:menu:list', NULL, 1, 1, '', NULL, now(), now(), NULL); +INSERT INTO `sys_menu` (`id`, `parent_id`, `tree_path`, `name`, `type`, `route_name`, `route_path`, `component`, `perm`, `keep_alive`, `visible`, `sort`, `icon`, `redirect`, `create_time`, `update_time`, `params`) VALUES (10302, 103, '0,1,103', '菜单新增', 'B', NULL, '', NULL, 'sys:menu:create', NULL, 1, 2, '', NULL, now(), now(), NULL); +INSERT INTO `sys_menu` (`id`, `parent_id`, `tree_path`, `name`, `type`, `route_name`, `route_path`, `component`, `perm`, `keep_alive`, `visible`, `sort`, `icon`, `redirect`, `create_time`, `update_time`, `params`) VALUES (10303, 103, '0,1,103', '菜单编辑', 'B', NULL, '', NULL, 'sys:menu:update', NULL, 1, 3, '', NULL, now(), now(), NULL); +INSERT INTO `sys_menu` (`id`, `parent_id`, `tree_path`, `name`, `type`, `route_name`, `route_path`, `component`, `perm`, `keep_alive`, `visible`, `sort`, `icon`, `redirect`, `create_time`, `update_time`, `params`) VALUES (10304, 103, '0,1,103', '菜单删除', 'B', NULL, '', NULL, 'sys:menu:delete', NULL, 1, 4, '', NULL, now(), now(), NULL); -INSERT INTO `sys_menu` (`id`, `parent_id`, `tree_path`, `name`, `type`, `route_name`, `route_path`, `component`, `perm`, `always_show`, `keep_alive`, `visible`, `sort`, `icon`, `redirect`, `create_time`, `update_time`, `params`) VALUES (240, 1, '0,1', '部门管理', 'M', 'Dept', 'dept', 'system/dept/index', NULL, NULL, 1, 1, 4, 'tree', NULL, now(), now(), NULL); -INSERT INTO `sys_menu` (`id`, `parent_id`, `tree_path`, `name`, `type`, `route_name`, `route_path`, `component`, `perm`, `always_show`, `keep_alive`, `visible`, `sort`, `icon`, `redirect`, `create_time`, `update_time`, `params`) VALUES (2401, 240, '0,1,240', '部门查询', 'B', NULL, '', NULL, 'sys:dept:list', NULL, NULL, 1, 1, '', NULL, now(), now(), NULL); -INSERT INTO `sys_menu` (`id`, `parent_id`, `tree_path`, `name`, `type`, `route_name`, `route_path`, `component`, `perm`, `always_show`, `keep_alive`, `visible`, `sort`, `icon`, `redirect`, `create_time`, `update_time`, `params`) VALUES (2402, 240, '0,1,240', '部门新增', 'B', NULL, '', NULL, 'sys:dept:create', NULL, NULL, 1, 2, '', NULL, now(), now(), NULL); -INSERT INTO `sys_menu` (`id`, `parent_id`, `tree_path`, `name`, `type`, `route_name`, `route_path`, `component`, `perm`, `always_show`, `keep_alive`, `visible`, `sort`, `icon`, `redirect`, `create_time`, `update_time`, `params`) VALUES (2403, 240, '0,1,240', '部门编辑', 'B', NULL, '', NULL, 'sys:dept:update', NULL, NULL, 1, 3, '', NULL, now(), now(), NULL); -INSERT INTO `sys_menu` (`id`, `parent_id`, `tree_path`, `name`, `type`, `route_name`, `route_path`, `component`, `perm`, `always_show`, `keep_alive`, `visible`, `sort`, `icon`, `redirect`, `create_time`, `update_time`, `params`) VALUES (2404, 240, '0,1,240', '部门删除', 'B', NULL, '', NULL, 'sys:dept:delete', NULL, NULL, 1, 4, '', NULL, now(), now(), NULL); +INSERT INTO `sys_menu` (`id`, `parent_id`, `tree_path`, `name`, `type`, `route_name`, `route_path`, `component`, `perm`, `keep_alive`, `visible`, `sort`, `icon`, `redirect`, `create_time`, `update_time`, `params`) VALUES (104, 1, '0,1', '部门管理', 'M', 'Dept', 'dept', 'system/dept/index', NULL, 1, 1, 4, 'tree', NULL, now(), now(), NULL); +INSERT INTO `sys_menu` (`id`, `parent_id`, `tree_path`, `name`, `type`, `route_name`, `route_path`, `component`, `perm`, `keep_alive`, `visible`, `sort`, `icon`, `redirect`, `create_time`, `update_time`, `params`) VALUES (10401, 104, '0,1,104', '部门查询', 'B', NULL, '', NULL, 'sys:dept:list', NULL, 1, 1, '', NULL, now(), now(), NULL); +INSERT INTO `sys_menu` (`id`, `parent_id`, `tree_path`, `name`, `type`, `route_name`, `route_path`, `component`, `perm`, `keep_alive`, `visible`, `sort`, `icon`, `redirect`, `create_time`, `update_time`, `params`) VALUES (10402, 104, '0,1,104', '部门新增', 'B', NULL, '', NULL, 'sys:dept:create', NULL, 1, 2, '', NULL, now(), now(), NULL); +INSERT INTO `sys_menu` (`id`, `parent_id`, `tree_path`, `name`, `type`, `route_name`, `route_path`, `component`, `perm`, `keep_alive`, `visible`, `sort`, `icon`, `redirect`, `create_time`, `update_time`, `params`) VALUES (10403, 104, '0,1,104', '部门编辑', 'B', NULL, '', NULL, 'sys:dept:update', NULL, 1, 3, '', NULL, now(), now(), NULL); +INSERT INTO `sys_menu` (`id`, `parent_id`, `tree_path`, `name`, `type`, `route_name`, `route_path`, `component`, `perm`, `keep_alive`, `visible`, `sort`, `icon`, `redirect`, `create_time`, `update_time`, `params`) VALUES (10404, 104, '0,1,104', '部门删除', 'B', NULL, '', NULL, 'sys:dept:delete', NULL, 1, 4, '', NULL, now(), now(), NULL); -INSERT INTO `sys_menu` (`id`, `parent_id`, `tree_path`, `name`, `type`, `route_name`, `route_path`, `component`, `perm`, `always_show`, `keep_alive`, `visible`, `sort`, `icon`, `redirect`, `create_time`, `update_time`, `params`) VALUES (250, 1, '0,1', '字典管理', 'M', 'Dict', 'dict', 'system/dict/index', NULL, NULL, 1, 1, 5, 'dict', NULL, now(), now(), NULL); -INSERT INTO `sys_menu` (`id`, `parent_id`, `tree_path`, `name`, `type`, `route_name`, `route_path`, `component`, `perm`, `always_show`, `keep_alive`, `visible`, `sort`, `icon`, `redirect`, `create_time`, `update_time`, `params`) VALUES (2501, 250, '0,1,250', '字典查询', 'B', NULL, '', NULL, 'sys:dict:list', NULL, NULL, 1, 1, '', NULL, now(), now(), NULL); -INSERT INTO `sys_menu` (`id`, `parent_id`, `tree_path`, `name`, `type`, `route_name`, `route_path`, `component`, `perm`, `always_show`, `keep_alive`, `visible`, `sort`, `icon`, `redirect`, `create_time`, `update_time`, `params`) VALUES (2502, 250, '0,1,250', '字典新增', 'B', NULL, '', NULL, 'sys:dict:create', NULL, NULL, 1, 2, '', NULL, now(), now(), NULL); -INSERT INTO `sys_menu` (`id`, `parent_id`, `tree_path`, `name`, `type`, `route_name`, `route_path`, `component`, `perm`, `always_show`, `keep_alive`, `visible`, `sort`, `icon`, `redirect`, `create_time`, `update_time`, `params`) VALUES (2503, 250, '0,1,250', '字典编辑', 'B', NULL, '', NULL, 'sys:dict:update', NULL, NULL, 1, 3, '', NULL, now(), now(), NULL); -INSERT INTO `sys_menu` (`id`, `parent_id`, `tree_path`, `name`, `type`, `route_name`, `route_path`, `component`, `perm`, `always_show`, `keep_alive`, `visible`, `sort`, `icon`, `redirect`, `create_time`, `update_time`, `params`) VALUES (2504, 250, '0,1,250', '字典删除', 'B', NULL, '', NULL, 'sys:dict:delete', NULL, NULL, 1, 4, '', NULL, now(), now(), NULL); +INSERT INTO `sys_menu` (`id`, `parent_id`, `tree_path`, `name`, `type`, `route_name`, `route_path`, `component`, `perm`, `keep_alive`, `visible`, `sort`, `icon`, `redirect`, `create_time`, `update_time`, `params`) VALUES (105, 1, '0,1', '字典管理', 'M', 'Dict', 'dict', 'system/dict/index', NULL, 1, 1, 5, 'dict', NULL, now(), now(), NULL); +INSERT INTO `sys_menu` (`id`, `parent_id`, `tree_path`, `name`, `type`, `route_name`, `route_path`, `component`, `perm`, `keep_alive`, `visible`, `sort`, `icon`, `redirect`, `create_time`, `update_time`, `params`) VALUES (10501, 105, '0,1,105', '字典查询', 'B', NULL, '', NULL, 'sys:dict:list', NULL, 1, 1, '', NULL, now(), now(), NULL); +INSERT INTO `sys_menu` (`id`, `parent_id`, `tree_path`, `name`, `type`, `route_name`, `route_path`, `component`, `perm`, `keep_alive`, `visible`, `sort`, `icon`, `redirect`, `create_time`, `update_time`, `params`) VALUES (10502, 105, '0,1,105', '字典新增', 'B', NULL, '', NULL, 'sys:dict:create', NULL, 1, 2, '', NULL, now(), now(), NULL); +INSERT INTO `sys_menu` (`id`, `parent_id`, `tree_path`, `name`, `type`, `route_name`, `route_path`, `component`, `perm`, `keep_alive`, `visible`, `sort`, `icon`, `redirect`, `create_time`, `update_time`, `params`) VALUES (10503, 105, '0,1,105', '字典编辑', 'B', NULL, '', NULL, 'sys:dict:update', NULL, 1, 3, '', NULL, now(), now(), NULL); +INSERT INTO `sys_menu` (`id`, `parent_id`, `tree_path`, `name`, `type`, `route_name`, `route_path`, `component`, `perm`, `keep_alive`, `visible`, `sort`, `icon`, `redirect`, `create_time`, `update_time`, `params`) VALUES (10504, 105, '0,1,105', '字典删除', 'B', NULL, '', NULL, 'sys:dict:delete', NULL, 1, 4, '', NULL, now(), now(), NULL); +-- 字典项已并入字典管理页(左右分栏同屏),不设独立菜单,仅保留按钮权限 +INSERT INTO `sys_menu` (`id`, `parent_id`, `tree_path`, `name`, `type`, `route_name`, `route_path`, `component`, `perm`, `keep_alive`, `visible`, `sort`, `icon`, `redirect`, `create_time`, `update_time`, `params`) VALUES (10505, 105, '0,1,105', '字典项查询', 'B', NULL, '', NULL, 'sys:dict-item:list', NULL, 1, 5, '', NULL, now(), now(), NULL); +INSERT INTO `sys_menu` (`id`, `parent_id`, `tree_path`, `name`, `type`, `route_name`, `route_path`, `component`, `perm`, `keep_alive`, `visible`, `sort`, `icon`, `redirect`, `create_time`, `update_time`, `params`) VALUES (10506, 105, '0,1,105', '字典项新增', 'B', NULL, '', NULL, 'sys:dict-item:create', NULL, 1, 6, '', NULL, now(), now(), NULL); +INSERT INTO `sys_menu` (`id`, `parent_id`, `tree_path`, `name`, `type`, `route_name`, `route_path`, `component`, `perm`, `keep_alive`, `visible`, `sort`, `icon`, `redirect`, `create_time`, `update_time`, `params`) VALUES (10507, 105, '0,1,105', '字典项编辑', 'B', NULL, '', NULL, 'sys:dict-item:update', NULL, 1, 7, '', NULL, now(), now(), NULL); +INSERT INTO `sys_menu` (`id`, `parent_id`, `tree_path`, `name`, `type`, `route_name`, `route_path`, `component`, `perm`, `keep_alive`, `visible`, `sort`, `icon`, `redirect`, `create_time`, `update_time`, `params`) VALUES (10508, 105, '0,1,105', '字典项删除', 'B', NULL, '', NULL, 'sys:dict-item:delete', NULL, 1, 8, '', NULL, now(), now(), NULL); -INSERT INTO `sys_menu` (`id`, `parent_id`, `tree_path`, `name`, `type`, `route_name`, `route_path`, `component`, `perm`, `always_show`, `keep_alive`, `visible`, `sort`, `icon`, `redirect`, `create_time`, `update_time`, `params`) VALUES (251, 1, '0,1', '字典项', 'M', 'DictItem', 'dict-item', 'system/dict/dict-item', NULL, 0, 1, 0, 6, '', NULL, now(), now(), NULL); -INSERT INTO `sys_menu` (`id`, `parent_id`, `tree_path`, `name`, `type`, `route_name`, `route_path`, `component`, `perm`, `always_show`, `keep_alive`, `visible`, `sort`, `icon`, `redirect`, `create_time`, `update_time`, `params`) VALUES (2511, 251, '0,1,251', '字典项查询', 'B', NULL, '', NULL, 'sys:dict-item:list', NULL, NULL, 1, 1, '', NULL, now(), now(), NULL); -INSERT INTO `sys_menu` (`id`, `parent_id`, `tree_path`, `name`, `type`, `route_name`, `route_path`, `component`, `perm`, `always_show`, `keep_alive`, `visible`, `sort`, `icon`, `redirect`, `create_time`, `update_time`, `params`) VALUES (2512, 251, '0,1,251', '字典项新增', 'B', NULL, '', NULL, 'sys:dict-item:create', NULL, NULL, 1, 2, '', NULL, now(), now(), NULL); -INSERT INTO `sys_menu` (`id`, `parent_id`, `tree_path`, `name`, `type`, `route_name`, `route_path`, `component`, `perm`, `always_show`, `keep_alive`, `visible`, `sort`, `icon`, `redirect`, `create_time`, `update_time`, `params`) VALUES (2513, 251, '0,1,251', '字典项编辑', 'B', NULL, '', NULL, 'sys:dict-item:update', NULL, NULL, 1, 3, '', NULL, now(), now(), NULL); -INSERT INTO `sys_menu` (`id`, `parent_id`, `tree_path`, `name`, `type`, `route_name`, `route_path`, `component`, `perm`, `always_show`, `keep_alive`, `visible`, `sort`, `icon`, `redirect`, `create_time`, `update_time`, `params`) VALUES (2514, 251, '0,1,251', '字典项删除', 'B', NULL, '', NULL, 'sys:dict-item:delete', NULL, NULL, 1, 4, '', NULL, now(), now(), NULL); +INSERT INTO `sys_menu` (`id`, `parent_id`, `tree_path`, `name`, `type`, `route_name`, `route_path`, `component`, `perm`, `keep_alive`, `visible`, `sort`, `icon`, `redirect`, `create_time`, `update_time`, `params`) VALUES (107, 1, '0,1', '系统日志', 'M', 'Log', 'log', 'system/log/index', NULL, 1, 1, 7, 'document', NULL, now(), now(), NULL); +INSERT INTO `sys_menu` (`id`, `parent_id`, `tree_path`, `name`, `type`, `route_name`, `route_path`, `component`, `perm`, `keep_alive`, `visible`, `sort`, `icon`, `redirect`, `create_time`, `update_time`, `params`) VALUES (10701, 107, '0,1,107', '日志查询', 'B', NULL, '', NULL, 'sys:log:list', NULL, 1, 1, '', NULL, now(), now(), NULL); -INSERT INTO `sys_menu` (`id`, `parent_id`, `tree_path`, `name`, `type`, `route_name`, `route_path`, `component`, `perm`, `always_show`, `keep_alive`, `visible`, `sort`, `icon`, `redirect`, `create_time`, `update_time`, `params`) VALUES (260, 1, '0,1', '系统日志', 'M', 'Log', 'log', 'system/log/index', NULL, 0, 1, 1, 7, 'document', NULL, now(), now(), NULL); -INSERT INTO `sys_menu` (`id`, `parent_id`, `tree_path`, `name`, `type`, `route_name`, `route_path`, `component`, `perm`, `always_show`, `keep_alive`, `visible`, `sort`, `icon`, `redirect`, `create_time`, `update_time`, `params`) VALUES (2601, 260, '0,1,260', '日志查询', 'B', NULL, '', NULL, 'sys:log:list', NULL, NULL, 1, 1, '', NULL, now(), now(), NULL); +INSERT INTO `sys_menu` (`id`, `parent_id`, `tree_path`, `name`, `type`, `route_name`, `route_path`, `component`, `perm`, `keep_alive`, `visible`, `sort`, `icon`, `redirect`, `create_time`, `update_time`, `params`) VALUES (108, 1, '0,1', '系统配置', 'M', 'Config', 'config', 'system/config/index', NULL, 1, 1, 8, 'setting', NULL, now(), now(), NULL); +INSERT INTO `sys_menu` (`id`, `parent_id`, `tree_path`, `name`, `type`, `route_name`, `route_path`, `component`, `perm`, `keep_alive`, `visible`, `sort`, `icon`, `redirect`, `create_time`, `update_time`, `params`) VALUES (10801, 108, '0,1,108', '系统配置查询', 'B', NULL, '', NULL, 'sys:config:list', 1, 1, 1, '', NULL, now(), now(), NULL); +INSERT INTO `sys_menu` (`id`, `parent_id`, `tree_path`, `name`, `type`, `route_name`, `route_path`, `component`, `perm`, `keep_alive`, `visible`, `sort`, `icon`, `redirect`, `create_time`, `update_time`, `params`) VALUES (10802, 108, '0,1,108', '系统配置新增', 'B', NULL, '', NULL, 'sys:config:create', 1, 1, 2, '', NULL, now(), now(), NULL); +INSERT INTO `sys_menu` (`id`, `parent_id`, `tree_path`, `name`, `type`, `route_name`, `route_path`, `component`, `perm`, `keep_alive`, `visible`, `sort`, `icon`, `redirect`, `create_time`, `update_time`, `params`) VALUES (10803, 108, '0,1,108', '系统配置修改', 'B', NULL, '', NULL, 'sys:config:update', 1, 1, 3, '', NULL, now(), now(), NULL); +INSERT INTO `sys_menu` (`id`, `parent_id`, `tree_path`, `name`, `type`, `route_name`, `route_path`, `component`, `perm`, `keep_alive`, `visible`, `sort`, `icon`, `redirect`, `create_time`, `update_time`, `params`) VALUES (10804, 108, '0,1,108', '系统配置删除', 'B', NULL, '', NULL, 'sys:config:delete', 1, 1, 4, '', NULL, now(), now(), NULL); +INSERT INTO `sys_menu` (`id`, `parent_id`, `tree_path`, `name`, `type`, `route_name`, `route_path`, `component`, `perm`, `keep_alive`, `visible`, `sort`, `icon`, `redirect`, `create_time`, `update_time`, `params`) VALUES (10805, 108, '0,1,108', '系统配置刷新', 'B', NULL, '', NULL, 'sys:config:refresh', 1, 1, 5, '', NULL, now(), now(), NULL); -INSERT INTO `sys_menu` (`id`, `parent_id`, `tree_path`, `name`, `type`, `route_name`, `route_path`, `component`, `perm`, `always_show`, `keep_alive`, `visible`, `sort`, `icon`, `redirect`, `create_time`, `update_time`, `params`) VALUES (270, 1, '0,1', '系统配置', 'M', 'Config', 'config', 'system/config/index', NULL, 0, 1, 1, 8, 'setting', NULL, now(), now(), NULL); -INSERT INTO `sys_menu` (`id`, `parent_id`, `tree_path`, `name`, `type`, `route_name`, `route_path`, `component`, `perm`, `always_show`, `keep_alive`, `visible`, `sort`, `icon`, `redirect`, `create_time`, `update_time`, `params`) VALUES (2701, 270, '0,1,270', '系统配置查询', 'B', NULL, '', NULL, 'sys:config:list', 0, 1, 1, 1, '', NULL, now(), now(), NULL); -INSERT INTO `sys_menu` (`id`, `parent_id`, `tree_path`, `name`, `type`, `route_name`, `route_path`, `component`, `perm`, `always_show`, `keep_alive`, `visible`, `sort`, `icon`, `redirect`, `create_time`, `update_time`, `params`) VALUES (2702, 270, '0,1,270', '系统配置新增', 'B', NULL, '', NULL, 'sys:config:create', 0, 1, 1, 2, '', NULL, now(), now(), NULL); -INSERT INTO `sys_menu` (`id`, `parent_id`, `tree_path`, `name`, `type`, `route_name`, `route_path`, `component`, `perm`, `always_show`, `keep_alive`, `visible`, `sort`, `icon`, `redirect`, `create_time`, `update_time`, `params`) VALUES (2703, 270, '0,1,270', '系统配置修改', 'B', NULL, '', NULL, 'sys:config:update', 0, 1, 1, 3, '', NULL, now(), now(), NULL); -INSERT INTO `sys_menu` (`id`, `parent_id`, `tree_path`, `name`, `type`, `route_name`, `route_path`, `component`, `perm`, `always_show`, `keep_alive`, `visible`, `sort`, `icon`, `redirect`, `create_time`, `update_time`, `params`) VALUES (2704, 270, '0,1,270', '系统配置删除', 'B', NULL, '', NULL, 'sys:config:delete', 0, 1, 1, 4, '', NULL, now(), now(), NULL); -INSERT INTO `sys_menu` (`id`, `parent_id`, `tree_path`, `name`, `type`, `route_name`, `route_path`, `component`, `perm`, `always_show`, `keep_alive`, `visible`, `sort`, `icon`, `redirect`, `create_time`, `update_time`, `params`) VALUES (2705, 270, '0,1,270', '系统配置刷新', 'B', NULL, '', NULL, 'sys:config:refresh', 0, 1, 1, 5, '', NULL, now(), now(), NULL); +INSERT INTO `sys_menu` (`id`, `parent_id`, `tree_path`, `name`, `type`, `route_name`, `route_path`, `component`, `perm`, `keep_alive`, `visible`, `sort`, `icon`, `redirect`, `create_time`, `update_time`, `params`) VALUES (109, 1, '0,1', '通知公告', 'M', 'Notice', 'notice', 'system/notice/index', NULL, NULL, 1, 9, '', NULL, now(), now(), NULL); +INSERT INTO `sys_menu` (`id`, `parent_id`, `tree_path`, `name`, `type`, `route_name`, `route_path`, `component`, `perm`, `keep_alive`, `visible`, `sort`, `icon`, `redirect`, `create_time`, `update_time`, `params`) VALUES (10901, 109, '0,1,109', '通知查询', 'B', NULL, '', NULL, 'sys:notice:list', NULL, 1, 1, '', NULL, now(), now(), NULL); +INSERT INTO `sys_menu` (`id`, `parent_id`, `tree_path`, `name`, `type`, `route_name`, `route_path`, `component`, `perm`, `keep_alive`, `visible`, `sort`, `icon`, `redirect`, `create_time`, `update_time`, `params`) VALUES (10902, 109, '0,1,109', '通知新增', 'B', NULL, '', NULL, 'sys:notice:create', NULL, 1, 2, '', NULL, now(), now(), NULL); +INSERT INTO `sys_menu` (`id`, `parent_id`, `tree_path`, `name`, `type`, `route_name`, `route_path`, `component`, `perm`, `keep_alive`, `visible`, `sort`, `icon`, `redirect`, `create_time`, `update_time`, `params`) VALUES (10903, 109, '0,1,109', '通知编辑', 'B', NULL, '', NULL, 'sys:notice:update', NULL, 1, 3, '', NULL, now(), now(), NULL); +INSERT INTO `sys_menu` (`id`, `parent_id`, `tree_path`, `name`, `type`, `route_name`, `route_path`, `component`, `perm`, `keep_alive`, `visible`, `sort`, `icon`, `redirect`, `create_time`, `update_time`, `params`) VALUES (10904, 109, '0,1,109', '通知删除', 'B', NULL, '', NULL, 'sys:notice:delete', NULL, 1, 4, '', NULL, now(), now(), NULL); +INSERT INTO `sys_menu` (`id`, `parent_id`, `tree_path`, `name`, `type`, `route_name`, `route_path`, `component`, `perm`, `keep_alive`, `visible`, `sort`, `icon`, `redirect`, `create_time`, `update_time`, `params`) VALUES (10905, 109, '0,1,109', '通知发布', 'B', NULL, '', NULL, 'sys:notice:publish', 1, 1, 5, '', NULL, now(), now(), NULL); +INSERT INTO `sys_menu` (`id`, `parent_id`, `tree_path`, `name`, `type`, `route_name`, `route_path`, `component`, `perm`, `keep_alive`, `visible`, `sort`, `icon`, `redirect`, `create_time`, `update_time`, `params`) VALUES (10906, 109, '0,1,109', '通知撤回', 'B', NULL, '', NULL, 'sys:notice:revoke', 1, 1, 6, '', NULL, now(), now(), NULL); -INSERT INTO `sys_menu` (`id`, `parent_id`, `tree_path`, `name`, `type`, `route_name`, `route_path`, `component`, `perm`, `always_show`, `keep_alive`, `visible`, `sort`, `icon`, `redirect`, `create_time`, `update_time`, `params`) VALUES (280, 1, '0,1', '通知公告', 'M', 'Notice', 'notice', 'system/notice/index', NULL, NULL, NULL, 1, 9, '', NULL, now(), now(), NULL); -INSERT INTO `sys_menu` (`id`, `parent_id`, `tree_path`, `name`, `type`, `route_name`, `route_path`, `component`, `perm`, `always_show`, `keep_alive`, `visible`, `sort`, `icon`, `redirect`, `create_time`, `update_time`, `params`) VALUES (2801, 280, '0,1,280', '通知查询', 'B', NULL, '', NULL, 'sys:notice:list', NULL, NULL, 1, 1, '', NULL, now(), now(), NULL); -INSERT INTO `sys_menu` (`id`, `parent_id`, `tree_path`, `name`, `type`, `route_name`, `route_path`, `component`, `perm`, `always_show`, `keep_alive`, `visible`, `sort`, `icon`, `redirect`, `create_time`, `update_time`, `params`) VALUES (2802, 280, '0,1,280', '通知新增', 'B', NULL, '', NULL, 'sys:notice:create', NULL, NULL, 1, 2, '', NULL, now(), now(), NULL); -INSERT INTO `sys_menu` (`id`, `parent_id`, `tree_path`, `name`, `type`, `route_name`, `route_path`, `component`, `perm`, `always_show`, `keep_alive`, `visible`, `sort`, `icon`, `redirect`, `create_time`, `update_time`, `params`) VALUES (2803, 280, '0,1,280', '通知编辑', 'B', NULL, '', NULL, 'sys:notice:update', NULL, NULL, 1, 3, '', NULL, now(), now(), NULL); -INSERT INTO `sys_menu` (`id`, `parent_id`, `tree_path`, `name`, `type`, `route_name`, `route_path`, `component`, `perm`, `always_show`, `keep_alive`, `visible`, `sort`, `icon`, `redirect`, `create_time`, `update_time`, `params`) VALUES (2804, 280, '0,1,280', '通知删除', 'B', NULL, '', NULL, 'sys:notice:delete', NULL, NULL, 1, 4, '', NULL, now(), now(), NULL); -INSERT INTO `sys_menu` (`id`, `parent_id`, `tree_path`, `name`, `type`, `route_name`, `route_path`, `component`, `perm`, `always_show`, `keep_alive`, `visible`, `sort`, `icon`, `redirect`, `create_time`, `update_time`, `params`) VALUES (2805, 280, '0,1,280', '通知发布', 'B', NULL, '', NULL, 'sys:notice:publish', 0, 1, 1, 5, '', NULL, now(), now(), NULL); -INSERT INTO `sys_menu` (`id`, `parent_id`, `tree_path`, `name`, `type`, `route_name`, `route_path`, `component`, `perm`, `always_show`, `keep_alive`, `visible`, `sort`, `icon`, `redirect`, `create_time`, `update_time`, `params`) VALUES (2806, 280, '0,1,280', '通知撤回', 'B', NULL, '', NULL, 'sys:notice:revoke', 0, 1, 1, 6, '', NULL, now(), now(), NULL); +-- 实战文档双形态置顶(内嵌 iframe + 外链新标签),直观演示系统对两种外链打开方式的支持 --- 代码生成 -INSERT INTO `sys_menu` (`id`, `parent_id`, `tree_path`, `name`, `type`, `route_name`, `route_path`, `component`, `perm`, `always_show`, `keep_alive`, `visible`, `sort`, `icon`, `redirect`, `create_time`, `update_time`, `params`) VALUES (310, 2, '0,2', '代码生成', 'M', 'Codegen', 'codegen', 'codegen/index', NULL, NULL, 1, 1, 1, 'code', NULL, now(), now(), NULL); +-- ============================ 通用组件(顶级 ID=4) ============================ +-- 前端模板招牌能力聚合,独立顶级便于访客沉淀组件库;按用途三分组:基础/表单/表格 +-- 物理目录 views/demo/component(基础与表单)与 views/demo/table(表格)一一对应 +INSERT INTO `sys_menu` (`id`, `parent_id`, `tree_path`, `name`, `type`, `route_name`, `route_path`, `component`, `perm`, `keep_alive`, `visible`, `sort`, `icon`, `redirect`, `create_time`, `update_time`, `params`) VALUES (4, 0, '0', '通用组件', 'C', '', '/component', 'Layout', NULL, NULL, 1, 4, 'el-icon-SetUp', '/component/basic/icon-demo', now(), now(), NULL); --- 平台文档 -INSERT INTO `sys_menu` (`id`, `parent_id`, `tree_path`, `name`, `type`, `route_name`, `route_path`, `component`, `external_url`, `perm`, `always_show`, `keep_alive`, `visible`, `sort`, `icon`, `redirect`, `create_time`, `update_time`, `params`) VALUES (501, 4, '0,4', '平台文档(外链)', 'E', NULL, NULL, NULL, 'https://juejin.cn/post/7228990409909108793', NULL, NULL, NULL, 1, 1, 'document', '', now(), now(), NULL); -INSERT INTO `sys_menu` (`id`, `parent_id`, `tree_path`, `name`, `type`, `route_name`, `route_path`, `component`, `external_url`, `perm`, `always_show`, `keep_alive`, `visible`, `sort`, `icon`, `redirect`, `create_time`, `update_time`, `params`) VALUES (502, 4, '0,4', '后端文档', 'E', NULL, NULL, NULL, 'https://youlai.blog.csdn.net/article/details/145178880', NULL, NULL, NULL, 1, 2, 'document', '', now(), now(), NULL); -INSERT INTO `sys_menu` (`id`, `parent_id`, `tree_path`, `name`, `type`, `route_name`, `route_path`, `component`, `external_url`, `perm`, `always_show`, `keep_alive`, `visible`, `sort`, `icon`, `redirect`, `create_time`, `update_time`, `params`) VALUES (503, 4, '0,4', '移动端文档', 'E', NULL, NULL, NULL, 'https://youlai.blog.csdn.net/article/details/143222890', NULL, NULL, NULL, 1, 3, 'document', '', now(), now(), NULL); -INSERT INTO `sys_menu` (`id`, `parent_id`, `tree_path`, `name`, `type`, `route_name`, `route_path`, `component`, `external_url`, `perm`, `always_show`, `keep_alive`, `visible`, `sort`, `icon`, `redirect`, `create_time`, `update_time`, `params`) VALUES (504, 4, '0,4', '内部文档', 'E', 'InternalDoc', 'internal-doc', 'iframe', 'https://juejin.cn/post/7228990409909108793', NULL, NULL, 1, 1, 4, 'document', '', now(), now(), NULL); +-- 基础组件(不依附表单/表格场景的通用 UI 能力) +INSERT INTO `sys_menu` (`id`, `parent_id`, `tree_path`, `name`, `type`, `route_name`, `route_path`, `component`, `perm`, `keep_alive`, `visible`, `sort`, `icon`, `redirect`, `create_time`, `update_time`, `params`) VALUES (401, 4, '0,4', '基础组件', 'C', '', 'basic', 'Layout', NULL, NULL, 1, 1, 'el-icon-Brush', '', now(), now(), NULL); +INSERT INTO `sys_menu` (`id`, `parent_id`, `tree_path`, `name`, `type`, `route_name`, `route_path`, `component`, `perm`, `keep_alive`, `visible`, `sort`, `icon`, `redirect`, `create_time`, `update_time`, `params`) VALUES (40101, 401, '0,4,401', 'Icons', 'M', 'IconDemo', 'icon-demo', 'demo/component/icons', NULL, 1, 1, 1, 'el-icon-Notification', '', now(), now(), NULL); +INSERT INTO `sys_menu` (`id`, `parent_id`, `tree_path`, `name`, `type`, `route_name`, `route_path`, `component`, `perm`, `keep_alive`, `visible`, `sort`, `icon`, `redirect`, `create_time`, `update_time`, `params`) VALUES (40102, 401, '0,4,401', '拖拽组件', 'M', 'Drag', 'drag', 'demo/component/drag', NULL, NULL, 1, 2, '', '', now(), now(), NULL); +INSERT INTO `sys_menu` (`id`, `parent_id`, `tree_path`, `name`, `type`, `route_name`, `route_path`, `component`, `perm`, `keep_alive`, `visible`, `sort`, `icon`, `redirect`, `create_time`, `update_time`, `params`) VALUES (40103, 401, '0,4,401', '滚动文本', 'M', 'TextScroll', 'text-scroll', 'demo/component/text-scroll', NULL, NULL, 1, 3, '', '', now(), now(), NULL); +INSERT INTO `sys_menu` (`id`, `parent_id`, `tree_path`, `name`, `type`, `route_name`, `route_path`, `component`, `perm`, `keep_alive`, `visible`, `sort`, `icon`, `redirect`, `create_time`, `update_time`, `params`) VALUES (40104, 401, '0,4,401', '字典实时同步', 'M', 'DictSync', 'dict-sync', 'demo/component/dict-sync', NULL, NULL, 1, 4, '', '', now(), now(), NULL); --- 接口文档 -INSERT INTO `sys_menu` (`id`, `parent_id`, `tree_path`, `name`, `type`, `route_name`, `route_path`, `component`, `external_url`, `perm`, `always_show`, `keep_alive`, `visible`, `sort`, `icon`, `redirect`, `create_time`, `update_time`, `params`) VALUES (601, 5, '0,5', 'Apifox', 'E', 'Apifox', 'apifox', 'iframe', 'https://www.apifox.cn/apidoc/shared-195e783f-4d85-4235-a038-eec696de4ea5', NULL, NULL, 1, 1, 1, 'api', '', now(), now(), NULL); +-- 表单组件(数据录入场景) +INSERT INTO `sys_menu` (`id`, `parent_id`, `tree_path`, `name`, `type`, `route_name`, `route_path`, `component`, `perm`, `keep_alive`, `visible`, `sort`, `icon`, `redirect`, `create_time`, `update_time`, `params`) VALUES (402, 4, '0,4', '表单组件', 'C', '', 'form', 'Layout', NULL, NULL, 1, 2, 'el-icon-EditPen', '', now(), now(), NULL); +INSERT INTO `sys_menu` (`id`, `parent_id`, `tree_path`, `name`, `type`, `route_name`, `route_path`, `component`, `perm`, `keep_alive`, `visible`, `sort`, `icon`, `redirect`, `create_time`, `update_time`, `params`) VALUES (40201, 402, '0,4,402', '富文本编辑器', 'M', 'WangEditor', 'wang-editor', 'demo/component/wang-editor', NULL, 1, 1, 1, '', '', now(), now(), NULL); +INSERT INTO `sys_menu` (`id`, `parent_id`, `tree_path`, `name`, `type`, `route_name`, `route_path`, `component`, `perm`, `keep_alive`, `visible`, `sort`, `icon`, `redirect`, `create_time`, `update_time`, `params`) VALUES (40202, 402, '0,4,402', '图片上传', 'M', 'Upload', 'upload', 'demo/component/upload', NULL, 1, 1, 2, '', '', now(), now(), NULL); +INSERT INTO `sys_menu` (`id`, `parent_id`, `tree_path`, `name`, `type`, `route_name`, `route_path`, `component`, `perm`, `keep_alive`, `visible`, `sort`, `icon`, `redirect`, `create_time`, `update_time`, `params`) VALUES (40203, 402, '0,4,402', '图标选择器', 'M', 'DemoIconSelect', 'icon-select', 'demo/component/icon-select', NULL, 1, 1, 3, '', '', now(), now(), NULL); +INSERT INTO `sys_menu` (`id`, `parent_id`, `tree_path`, `name`, `type`, `route_name`, `route_path`, `component`, `perm`, `keep_alive`, `visible`, `sort`, `icon`, `redirect`, `create_time`, `update_time`, `params`) VALUES (40204, 402, '0,4,402', '字典组件', 'M', 'DictDemo', 'dict-demo', 'demo/component/dictionary', NULL, 1, 1, 4, '', '', now(), now(), NULL); +INSERT INTO `sys_menu` (`id`, `parent_id`, `tree_path`, `name`, `type`, `route_name`, `route_path`, `component`, `perm`, `keep_alive`, `visible`, `sort`, `icon`, `redirect`, `create_time`, `update_time`, `params`) VALUES (40205, 402, '0,4,402', '列表选择器', 'M', 'TableSelect', 'table-select', 'demo/component/table-select/index', NULL, 1, 1, 5, '', '', now(), now(), NULL); --- 组件封装 -INSERT INTO `sys_menu` (`id`, `parent_id`, `tree_path`, `name`, `type`, `route_name`, `route_path`, `component`, `perm`, `always_show`, `keep_alive`, `visible`, `sort`, `icon`, `redirect`, `create_time`, `update_time`, `params`) VALUES (701, 6, '0,6', '富文本编辑器', 'M', 'WangEditor', 'wang-editor', 'demo/wang-editor', NULL, NULL, 1, 1, 2, '', '', now(), now(), NULL); -INSERT INTO `sys_menu` (`id`, `parent_id`, `tree_path`, `name`, `type`, `route_name`, `route_path`, `component`, `perm`, `always_show`, `keep_alive`, `visible`, `sort`, `icon`, `redirect`, `create_time`, `update_time`, `params`) VALUES (702, 6, '0,6', '图片上传', 'M', 'Upload', 'upload', 'demo/upload', NULL, NULL, 1, 1, 3, '', '', now(), now(), NULL); -INSERT INTO `sys_menu` (`id`, `parent_id`, `tree_path`, `name`, `type`, `route_name`, `route_path`, `component`, `perm`, `always_show`, `keep_alive`, `visible`, `sort`, `icon`, `redirect`, `create_time`, `update_time`, `params`) VALUES (703, 6, '0,6', '图标选择器', 'M', 'DemoIconSelect', 'icon-select', 'demo/icon-select', NULL, NULL, 1, 1, 4, '', '', now(), now(), NULL); -INSERT INTO `sys_menu` (`id`, `parent_id`, `tree_path`, `name`, `type`, `route_name`, `route_path`, `component`, `perm`, `always_show`, `keep_alive`, `visible`, `sort`, `icon`, `redirect`, `create_time`, `update_time`, `params`) VALUES (704, 6, '0,6', '字典组件', 'M', 'DictDemo', 'dict-demo', 'demo/dictionary', NULL, NULL, 1, 1, 4, '', '', now(), now(), NULL); -INSERT INTO `sys_menu` (`id`, `parent_id`, `tree_path`, `name`, `type`, `route_name`, `route_path`, `component`, `perm`, `always_show`, `keep_alive`, `visible`, `sort`, `icon`, `redirect`, `create_time`, `update_time`, `params`) VALUES (705, 6, '0,6', '增删改查', 'M', 'Curd', 'curd', 'demo/curd/index', NULL, NULL, 1, 1, 0, '', '', now(), now(), NULL); -INSERT INTO `sys_menu` (`id`, `parent_id`, `tree_path`, `name`, `type`, `route_name`, `route_path`, `component`, `perm`, `always_show`, `keep_alive`, `visible`, `sort`, `icon`, `redirect`, `create_time`, `update_time`, `params`) VALUES (706, 6, '0,6', '列表选择器', 'M', 'TableSelect', 'table-select', 'demo/table-select/index', NULL, NULL, 1, 1, 1, '', '', now(), now(), NULL); -INSERT INTO `sys_menu` (`id`, `parent_id`, `tree_path`, `name`, `type`, `route_name`, `route_path`, `component`, `perm`, `always_show`, `keep_alive`, `visible`, `sort`, `icon`, `redirect`, `create_time`, `update_time`, `params`) VALUES (707, 6, '0,6', '拖拽组件', 'M', 'Drag', 'drag', 'demo/drag', NULL, NULL, NULL, 1, 5, '', '', now(), now(), NULL); -INSERT INTO `sys_menu` (`id`, `parent_id`, `tree_path`, `name`, `type`, `route_name`, `route_path`, `component`, `perm`, `always_show`, `keep_alive`, `visible`, `sort`, `icon`, `redirect`, `create_time`, `update_time`, `params`) VALUES (708, 6, '0,6', '滚动文本', 'M', 'TextScroll', 'text-scroll', 'demo/text-scroll', NULL, NULL, NULL, 1, 6, '', '', now(), now(), NULL); -INSERT INTO `sys_menu` (`id`, `parent_id`, `tree_path`, `name`, `type`, `route_name`, `route_path`, `component`, `perm`, `always_show`, `keep_alive`, `visible`, `sort`, `icon`, `redirect`, `create_time`, `update_time`, `params`) VALUES (709, 6, '0,6', '自适应表格操作列', 'M', 'AutoOperationColumn', 'operation-column', 'demo/auto-operation-column', NULL, NULL, 1, 1, 1, '', '', now(), now(), NULL); +-- 表格组件(数据展示场景,物理目录 views/demo/table 与之对应) +INSERT INTO `sys_menu` (`id`, `parent_id`, `tree_path`, `name`, `type`, `route_name`, `route_path`, `component`, `perm`, `keep_alive`, `visible`, `sort`, `icon`, `redirect`, `create_time`, `update_time`, `params`) VALUES (403, 4, '0,4', '表格组件', 'C', '', 'table', 'Layout', NULL, NULL, 1, 3, 'el-icon-Grid', '', now(), now(), NULL); +INSERT INTO `sys_menu` (`id`, `parent_id`, `tree_path`, `name`, `type`, `route_name`, `route_path`, `component`, `perm`, `keep_alive`, `visible`, `sort`, `icon`, `redirect`, `create_time`, `update_time`, `params`) VALUES (40301, 403, '0,4,403', '增删改查', 'M', 'Crud', 'crud', 'demo/table/crud/index', NULL, 1, 1, 1, '', '', now(), now(), NULL); +INSERT INTO `sys_menu` (`id`, `parent_id`, `tree_path`, `name`, `type`, `route_name`, `route_path`, `component`, `perm`, `keep_alive`, `visible`, `sort`, `icon`, `redirect`, `create_time`, `update_time`, `params`) VALUES (40302, 403, '0,4,403', 'CRUD单文件', 'M', 'CrudSingle', 'crud-single', 'demo/table/crud-single', NULL, 1, 1, 2, 'el-icon-Reading', '', now(), now(), NULL); +INSERT INTO `sys_menu` (`id`, `parent_id`, `tree_path`, `name`, `type`, `route_name`, `route_path`, `component`, `perm`, `keep_alive`, `visible`, `sort`, `icon`, `redirect`, `create_time`, `update_time`, `params`) VALUES (40303, 403, '0,4,403', 'VxeTable', 'M', 'VxeTable', 'vxe-table', 'demo/table/vxe-table/index', NULL, 1, 1, 3, 'el-icon-MagicStick', '', now(), now(), NULL); +INSERT INTO `sys_menu` (`id`, `parent_id`, `tree_path`, `name`, `type`, `route_name`, `route_path`, `component`, `perm`, `keep_alive`, `visible`, `sort`, `icon`, `redirect`, `create_time`, `update_time`, `params`) VALUES (40304, 403, '0,4,403', '自适应表格操作列', 'M', 'AutoOperationColumn', 'operation-column', 'demo/table/auto-operation-column', NULL, 1, 1, 4, '', '', now(), now(), NULL); --- 功能演示 -INSERT INTO `sys_menu` (`id`, `parent_id`, `tree_path`, `name`, `type`, `route_name`, `route_path`, `component`, `perm`, `always_show`, `keep_alive`, `visible`, `sort`, `icon`, `redirect`, `create_time`, `update_time`, `params`) VALUES (801, 7, '0,7', 'Icons', 'M', 'IconDemo', 'icon-demo', 'demo/icons', NULL, NULL, 1, 1, 2, 'el-icon-Notification', '', now(), now(), NULL); -INSERT INTO `sys_menu` (`id`, `parent_id`, `tree_path`, `name`, `type`, `route_name`, `route_path`, `component`, `perm`, `always_show`, `keep_alive`, `visible`, `sort`, `icon`, `redirect`, `create_time`, `update_time`, `params`) VALUES (802, 7, '0,7', '字典实时同步', 'M', 'DictSync', 'dict-sync', 'demo/dict-sync', NULL, NULL, NULL, 1, 3, '', '', now(), now(), NULL); -INSERT INTO `sys_menu` (`id`, `parent_id`, `tree_path`, `name`, `type`, `route_name`, `route_path`, `component`, `perm`, `always_show`, `keep_alive`, `visible`, `sort`, `icon`, `redirect`, `create_time`, `update_time`, `params`) VALUES (803, 7, '0,7', 'VxeTable', 'M', 'VxeTable', 'vxe-table', 'demo/vxe-table/index', NULL, NULL, 1, 1, 4, 'el-icon-MagicStick', '', now(), now(), NULL); -INSERT INTO `sys_menu` (`id`, `parent_id`, `tree_path`, `name`, `type`, `route_name`, `route_path`, `component`, `perm`, `always_show`, `keep_alive`, `visible`, `sort`, `icon`, `redirect`, `create_time`, `update_time`, `params`) VALUES (804, 7, '0,7', 'CURD单文件', 'M', 'CurdSingle', 'curd-single', 'demo/curd-single', NULL, NULL, 1, 1, 5, 'el-icon-Reading', '', now(), now(), NULL); +-- ============================ 多级菜单(顶级 ID=5) ============================ +-- 独立顶级,直观演示菜单驱动动态路由的嵌套能力,避免折叠导致顶级菜单不可见 +-- 物理目录 views/demo/route/multi-level 与之对应 +INSERT INTO `sys_menu` (`id`, `parent_id`, `tree_path`, `name`, `type`, `route_name`, `route_path`, `component`, `perm`, `keep_alive`, `visible`, `sort`, `icon`, `redirect`, `create_time`, `update_time`, `params`) VALUES (5, 0, '0', '多级菜单', 'C', '', '/multi-level', 'Layout', NULL, NULL, 1, 5, 'el-icon-Guide', '/multi-level/level-one/level-two/level-three-a', now(), now(), NULL); +INSERT INTO `sys_menu` (`id`, `parent_id`, `tree_path`, `name`, `type`, `route_name`, `route_path`, `component`, `perm`, `keep_alive`, `visible`, `sort`, `icon`, `redirect`, `create_time`, `update_time`, `params`) VALUES (501, 5, '0,5', '一级菜单', 'C', '', 'level-one', 'Layout', NULL, NULL, 1, 1, '', NULL, now(), now(), NULL); +INSERT INTO `sys_menu` (`id`, `parent_id`, `tree_path`, `name`, `type`, `route_name`, `route_path`, `component`, `perm`, `keep_alive`, `visible`, `sort`, `icon`, `redirect`, `create_time`, `update_time`, `params`) VALUES (50101, 501, '0,5,501', '二级菜单', 'C', '', 'level-two', 'Layout', NULL, NULL, 1, 1, '', NULL, now(), now(), NULL); +INSERT INTO `sys_menu` (`id`, `parent_id`, `tree_path`, `name`, `type`, `route_name`, `route_path`, `component`, `perm`, `keep_alive`, `visible`, `sort`, `icon`, `redirect`, `create_time`, `update_time`, `params`) VALUES (5010101, 50101, '0,5,501,50101', '三级菜单 A', 'M', 'MultiLevelLevelThreeA', 'level-three-a', 'demo/route/multi-level/level-one/level-two/level-three-a/index', NULL, 1, 1, 1, '', '', now(), now(), NULL); +INSERT INTO `sys_menu` (`id`, `parent_id`, `tree_path`, `name`, `type`, `route_name`, `route_path`, `component`, `perm`, `keep_alive`, `visible`, `sort`, `icon`, `redirect`, `create_time`, `update_time`, `params`) VALUES (5010102, 50101, '0,5,501,50101', '三级菜单 B', 'M', 'MultiLevelLevelThreeB', 'level-three-b', 'demo/route/multi-level/level-one/level-two/level-three-b/index', NULL, 1, 1, 2, '', '', now(), now(), NULL); --- 多级菜单示例 -INSERT INTO `sys_menu` (`id`, `parent_id`, `tree_path`, `name`, `type`, `route_name`, `route_path`, `component`, `perm`, `always_show`, `keep_alive`, `visible`, `sort`, `icon`, `redirect`, `create_time`, `update_time`, `params`) VALUES (910, 8, '0,8', '一级菜单', 'C', NULL, 'level-one', 'Layout', NULL, 1, NULL, 1, 1, '', '', now(), now(), NULL); -INSERT INTO `sys_menu` (`id`, `parent_id`, `tree_path`, `name`, `type`, `route_name`, `route_path`, `component`, `perm`, `always_show`, `keep_alive`, `visible`, `sort`, `icon`, `redirect`, `create_time`, `update_time`, `params`) VALUES (911, 910, '0,8,910', '二级菜单', 'C', NULL, 'level-two', 'Layout', NULL, 0, NULL, 1, 1, '', NULL, now(), now(), NULL); -INSERT INTO `sys_menu` (`id`, `parent_id`, `tree_path`, `name`, `type`, `route_name`, `route_path`, `component`, `perm`, `always_show`, `keep_alive`, `visible`, `sort`, `icon`, `redirect`, `create_time`, `update_time`, `params`) VALUES (912, 911, '0,8,910,911', '三级菜单 A', 'M', 'MultiLevelLevelThreeA', 'level-three-a', 'demo/multi-level/level-one/level-two/level-three-a/index', NULL, 0, 1, 1, 1, '', '', now(), now(), NULL); -INSERT INTO `sys_menu` (`id`, `parent_id`, `tree_path`, `name`, `type`, `route_name`, `route_path`, `component`, `perm`, `always_show`, `keep_alive`, `visible`, `sort`, `icon`, `redirect`, `create_time`, `update_time`, `params`) VALUES (913, 911, '0,8,910,911', '三级菜单 B', 'M', 'MultiLevelLevelThreeB', 'level-three-b', 'demo/multi-level/level-one/level-two/level-three-b/index', NULL, 0, 1, 1, 2, '', '', now(), now(), NULL); - --- 路由参数 -INSERT INTO `sys_menu` (`id`, `parent_id`, `tree_path`, `name`, `type`, `route_name`, `route_path`, `component`, `perm`, `always_show`, `keep_alive`, `visible`, `sort`, `icon`, `redirect`, `create_time`, `update_time`, `params`) VALUES (1001, 9, '0,9', '参数(type=1)', 'M', 'RouteParamType1', 'route-param-type1', 'demo/route-param', NULL, 0, 1, 1, 1, 'el-icon-Star', NULL, now(), now(), '{\"type\": \"1\"}'); -INSERT INTO `sys_menu` (`id`, `parent_id`, `tree_path`, `name`, `type`, `route_name`, `route_path`, `component`, `perm`, `always_show`, `keep_alive`, `visible`, `sort`, `icon`, `redirect`, `create_time`, `update_time`, `params`) VALUES (1002, 9, '0,9', '参数(type=2)', 'M', 'RouteParamType2', 'route-param-type2', 'demo/route-param', NULL, 0, 1, 1, 2, 'el-icon-StarFilled', NULL, now(), now(), '{\"type\": \"2\"}'); +-- ============================ 路由示例(顶级 ID=6) ============================ +-- 路由层能力演示:传参(页内切换)、页面缓存、页面跳转、内嵌页面(iframe)、外部链接(E 型新标签) +INSERT INTO `sys_menu` (`id`, `parent_id`, `tree_path`, `name`, `type`, `route_name`, `route_path`, `component`, `perm`, `keep_alive`, `visible`, `sort`, `icon`, `redirect`, `create_time`, `update_time`, `params`) VALUES (6, 0, '0', '路由示例', 'C', '', '/route-example', 'Layout', NULL, NULL, 1, 6, 'el-icon-Share', '/route-example/route-param', now(), now(), NULL); +INSERT INTO `sys_menu` (`id`, `parent_id`, `tree_path`, `name`, `type`, `route_name`, `route_path`, `component`, `perm`, `keep_alive`, `visible`, `sort`, `icon`, `redirect`, `create_time`, `update_time`, `params`) VALUES (601, 6, '0,6', '路由参数', 'M', 'RouteParam', 'route-param', 'demo/route/route-param', NULL, 1, 1, 1, 'el-icon-Star', NULL, now(), now(), NULL); +INSERT INTO `sys_menu` (`id`, `parent_id`, `tree_path`, `name`, `type`, `route_name`, `route_path`, `component`, `perm`, `keep_alive`, `visible`, `sort`, `icon`, `redirect`, `create_time`, `update_time`, `params`) VALUES (602, 6, '0,6', '页面缓存', 'M', 'RouteCache', 'cache', 'demo/route/cache/index', NULL, 1, 1, 2, 'el-icon-Stopwatch', NULL, now(), now(), NULL); +INSERT INTO `sys_menu` (`id`, `parent_id`, `tree_path`, `name`, `type`, `route_name`, `route_path`, `component`, `perm`, `keep_alive`, `visible`, `sort`, `icon`, `redirect`, `create_time`, `update_time`, `params`) VALUES (603, 6, '0,6', '页面跳转', 'M', 'RouteNavigate', 'navigate', 'demo/route/navigate/index', NULL, 1, 1, 3, 'el-icon-Position', NULL, now(), now(), NULL); +INSERT INTO `sys_menu` (`id`, `parent_id`, `tree_path`, `name`, `type`, `route_name`, `route_path`, `component`, `external_url`, `perm`, `keep_alive`, `visible`, `sort`, `icon`, `redirect`, `create_time`, `update_time`, `params`) VALUES (604, 6, '0,6', '内嵌页面', 'E', 'PracticeDoc', 'iframe', 'iframe', 'https://www.apifox.cn/apidoc/shared-195e783f-4d85-4235-a038-eec696de4ea5', NULL, 1, 1, 4, 'el-icon-Document', '', now(), now(), NULL); +INSERT INTO `sys_menu` (`id`, `parent_id`, `tree_path`, `name`, `type`, `route_name`, `route_path`, `component`, `external_url`, `perm`, `keep_alive`, `visible`, `sort`, `icon`, `redirect`, `create_time`, `update_time`, `params`) VALUES (605, 6, '0,6', '外部链接', 'E', NULL, NULL, NULL, 'https://juejin.cn/post/7228990409909108793', NULL, NULL, 1, 5, 'el-icon-Link', '', now(), now(), NULL); -- ---------------------------- --- Table structure for sys_role +-- 表结构:sys_role -- ---------------------------- DROP TABLE IF EXISTS `sys_role`; CREATE TABLE `sys_role` ( @@ -267,7 +272,7 @@ CREATE TABLE `sys_role` ( ) ENGINE = InnoDB CHARACTER SET = utf8mb4 COMMENT = '系统角色表'; -- ---------------------------- --- Records of sys_role +-- 表数据:sys_role -- ---------------------------- INSERT INTO `sys_role` VALUES (1, '超级管理员', 'ROOT', 1, 1, 1, NULL, now(), NULL, now(), 0); INSERT INTO `sys_role` VALUES (2, '系统管理员', 'ADMIN', 2, 1, 1, NULL, now(), NULL, NULL, 0); @@ -278,7 +283,7 @@ INSERT INTO `sys_role` VALUES (6, '普通员工', 'EMPLOYEE', 6, 1, 4, NULL, now INSERT INTO `sys_role` VALUES (7, '自定义权限用户', 'CUSTOM_USER', 7, 1, 5, NULL, now(), NULL, now(), 0); -- ---------------------------- --- Table structure for sys_role_menu +-- 表结构:sys_role_menu -- ---------------------------- DROP TABLE IF EXISTS `sys_role_menu`; CREATE TABLE `sys_role_menu` ( @@ -288,7 +293,7 @@ CREATE TABLE `sys_role_menu` ( ) ENGINE = InnoDB CHARACTER SET = utf8mb4 COMMENT = '角色菜单关联表'; -- ---------------------------- --- Table structure for sys_role_dept +-- 表结构:sys_role_dept -- ---------------------------- DROP TABLE IF EXISTS `sys_role_dept`; CREATE TABLE `sys_role_dept` ( @@ -298,56 +303,49 @@ CREATE TABLE `sys_role_dept` ( ) ENGINE = InnoDB CHARACTER SET = utf8mb4 COMMENT = '角色部门关联表'; -- ---------------------------- --- Records of sys_role_dept +-- 表数据:sys_role_dept -- ---------------------------- INSERT IGNORE INTO `sys_role_dept` VALUES (7, 1); INSERT IGNORE INTO `sys_role_dept` VALUES (7, 2); -- ============================================ --- 系统管理员角色菜单权限(role_id=2) --- 顶级目录 -INSERT INTO `sys_role_menu` VALUES (2, 1), (2, 2), (2, 4), (2, 5), (2, 6), (2, 7), (2, 8), (2, 9); +-- 系统管理员角色菜单权限(role_id=2,基础段顶级 1-6 全量) +INSERT INTO `sys_role_menu` VALUES (2, 1), (2, 2), (2, 3), (2, 4), (2, 5), (2, 6); -- 系统管理 -INSERT INTO `sys_role_menu` VALUES (2, 210), (2, 2101), (2, 2102), (2, 2103), (2, 2104), (2, 2105), (2, 2106), (2, 2107); -INSERT INTO `sys_role_menu` VALUES (2, 220), (2, 2201), (2, 2202), (2, 2203), (2, 2204), (2, 2205); -INSERT INTO `sys_role_menu` VALUES (2, 230), (2, 2301), (2, 2302), (2, 2303), (2, 2304); -INSERT INTO `sys_role_menu` VALUES (2, 240), (2, 2401), (2, 2402), (2, 2403), (2, 2404); -INSERT INTO `sys_role_menu` VALUES (2, 250), (2, 2501), (2, 2502), (2, 2503), (2, 2504); -INSERT INTO `sys_role_menu` VALUES (2, 251), (2, 2511), (2, 2512), (2, 2513), (2, 2514); -INSERT INTO `sys_role_menu` VALUES (2, 260), (2, 2601); -INSERT INTO `sys_role_menu` VALUES (2, 270), (2, 2701), (2, 2702), (2, 2703), (2, 2704), (2, 2705); -INSERT INTO `sys_role_menu` VALUES (2, 280), (2, 2801), (2, 2802), (2, 2803), (2, 2804), (2, 2805), (2, 2806); +INSERT INTO `sys_role_menu` VALUES (2, 101), (2, 10101), (2, 10102), (2, 10103), (2, 10104), (2, 10105), (2, 10106), (2, 10107); +INSERT INTO `sys_role_menu` VALUES (2, 102), (2, 10201), (2, 10202), (2, 10203), (2, 10204), (2, 10205); +INSERT INTO `sys_role_menu` VALUES (2, 103), (2, 10301), (2, 10302), (2, 10303), (2, 10304); +INSERT INTO `sys_role_menu` VALUES (2, 104), (2, 10401), (2, 10402), (2, 10403), (2, 10404); +INSERT INTO `sys_role_menu` VALUES (2, 105), (2, 10501), (2, 10502), (2, 10503), (2, 10504), (2, 10505), (2, 10506), (2, 10507), (2, 10508); +INSERT INTO `sys_role_menu` VALUES (2, 107), (2, 10701); +INSERT INTO `sys_role_menu` VALUES (2, 108), (2, 10801), (2, 10802), (2, 10803), (2, 10804), (2, 10805); +INSERT INTO `sys_role_menu` VALUES (2, 109), (2, 10901), (2, 10902), (2, 10903), (2, 10904), (2, 10905), (2, 10906); INSERT IGNORE INTO `sys_role_menu` VALUES (4, 1); -INSERT IGNORE INTO `sys_role_menu` VALUES (4, 210), (4, 2101), (4, 2102), (4, 2103), (4, 2104), (4, 2105), (4, 2106), (4, 2107); -INSERT IGNORE INTO `sys_role_menu` VALUES (4, 220), (4, 2201), (4, 2202), (4, 2203), (4, 2204), (4, 2205); +INSERT IGNORE INTO `sys_role_menu` VALUES (4, 101), (4, 10101), (4, 10102), (4, 10103), (4, 10104), (4, 10105), (4, 10106), (4, 10107); +INSERT IGNORE INTO `sys_role_menu` VALUES (4, 102), (4, 10201), (4, 10202), (4, 10203), (4, 10204), (4, 10205); INSERT IGNORE INTO `sys_role_menu` VALUES (5, 1); -INSERT IGNORE INTO `sys_role_menu` VALUES (5, 210), (5, 2101), (5, 2102), (5, 2103), (5, 2104), (5, 2105), (5, 2106), (5, 2107); -INSERT IGNORE INTO `sys_role_menu` VALUES (5, 220), (5, 2201), (5, 2202), (5, 2203), (5, 2204), (5, 2205); +INSERT IGNORE INTO `sys_role_menu` VALUES (5, 101), (5, 10101), (5, 10102), (5, 10103), (5, 10104), (5, 10105), (5, 10106), (5, 10107); +INSERT IGNORE INTO `sys_role_menu` VALUES (5, 102), (5, 10201), (5, 10202), (5, 10203), (5, 10204), (5, 10205); INSERT IGNORE INTO `sys_role_menu` VALUES (6, 1); -INSERT IGNORE INTO `sys_role_menu` VALUES (6, 210), (6, 2101), (6, 2102), (6, 2103), (6, 2104), (6, 2105), (6, 2106), (6, 2107); -INSERT IGNORE INTO `sys_role_menu` VALUES (6, 220), (6, 2201), (6, 2202), (6, 2203), (6, 2204), (6, 2205); +INSERT IGNORE INTO `sys_role_menu` VALUES (6, 101), (6, 10101), (6, 10102), (6, 10103), (6, 10104), (6, 10105), (6, 10106), (6, 10107); +INSERT IGNORE INTO `sys_role_menu` VALUES (6, 102), (6, 10201), (6, 10202), (6, 10203), (6, 10204), (6, 10205); INSERT IGNORE INTO `sys_role_menu` VALUES (7, 1); -INSERT IGNORE INTO `sys_role_menu` VALUES (7, 210), (7, 2101), (7, 2102), (7, 2103), (7, 2104), (7, 2105), (7, 2106), (7, 2107); -INSERT IGNORE INTO `sys_role_menu` VALUES (7, 220), (7, 2201), (7, 2202), (7, 2203), (7, 2204), (7, 2205); --- 代码生成 -INSERT INTO `sys_role_menu` VALUES (2, 310); --- 平台文档 -INSERT INTO `sys_role_menu` VALUES (2, 501), (2, 502), (2, 503), (2, 504); --- 接口文档 -INSERT INTO `sys_role_menu` VALUES (2, 601); --- 组件封装 -INSERT INTO `sys_role_menu` VALUES (2, 701), (2, 702), (2, 703), (2, 704), (2, 705), (2, 706), (2, 707), (2, 708), (2, 709); --- 功能演示 / 多级菜单 -INSERT INTO `sys_role_menu` VALUES (2, 801), (2, 802), (2, 803), (2, 804), (2, 910), (2, 911), (2, 912), (2, 913); --- 路由参数 -INSERT INTO `sys_role_menu` VALUES (2, 1001), (2, 1002); +INSERT IGNORE INTO `sys_role_menu` VALUES (7, 101), (7, 10101), (7, 10102), (7, 10103), (7, 10104), (7, 10105), (7, 10106), (7, 10107); +INSERT IGNORE INTO `sys_role_menu` VALUES (7, 102), (7, 10201), (7, 10202), (7, 10203), (7, 10204), (7, 10205); +-- 通用组件(401 基础 / 402 表单 / 403 表格) +INSERT INTO `sys_role_menu` VALUES (2, 401), (2, 40101), (2, 40102), (2, 40103), (2, 40104); +INSERT INTO `sys_role_menu` VALUES (2, 402), (2, 40201), (2, 40202), (2, 40203), (2, 40204), (2, 40205); +INSERT INTO `sys_role_menu` VALUES (2, 403), (2, 40301), (2, 40302), (2, 40303), (2, 40304); +-- 多级菜单 / 路由示例 +INSERT INTO `sys_role_menu` VALUES (2, 501), (2, 50101), (2, 5010101), (2, 5010102); +INSERT INTO `sys_role_menu` VALUES (2, 601), (2, 602), (2, 603), (2, 604), (2, 605); -- ---------------------------- --- Table structure for sys_user +-- 表结构:sys_user -- ---------------------------- DROP TABLE IF EXISTS `sys_user`; CREATE TABLE `sys_user` ( @@ -370,9 +368,9 @@ CREATE TABLE `sys_user` ( ) ENGINE = InnoDB CHARACTER SET = utf8mb4 COMMENT = '系统用户表'; -- ---------------------------- --- Records of sys_user +-- 表数据:sys_user -- ---------------------------- -INSERT INTO `sys_user` VALUES (1, 'root', '有来技术', 0, '$2a$10$xVWsNOhHrCxh5UbpCE7/HuJ.PAOKcYAqRxD2CO2nVnJS.IAXkr5aq', NULL, 'https://foruda.gitee.com/images/1723603502796844527/03cdca2a_716974.gif', '18812345677', 1, 'youlaitech@163.com', now(), NULL, now(), NULL, 0); +INSERT INTO `sys_user` VALUES (1, 'youlai', '有来技术', 0, '$2a$10$xVWsNOhHrCxh5UbpCE7/HuJ.PAOKcYAqRxD2CO2nVnJS.IAXkr5aq', NULL, 'https://foruda.gitee.com/images/1723603502796844527/03cdca2a_716974.gif', '18812345677', 1, 'youlaitech@163.com', now(), NULL, now(), NULL, 0); INSERT INTO `sys_user` VALUES (2, 'admin', '系统管理员', 1, '$2a$10$xVWsNOhHrCxh5UbpCE7/HuJ.PAOKcYAqRxD2CO2nVnJS.IAXkr5aq', 1, 'https://foruda.gitee.com/images/1723603502796844527/03cdca2a_716974.gif', '18888888888', 1, 'youlaitech@163.com', now(), NULL, now(), NULL, 0); INSERT INTO `sys_user` VALUES (3, 'test', '测试小用户', 1, '$2a$10$xVWsNOhHrCxh5UbpCE7/HuJ.PAOKcYAqRxD2CO2nVnJS.IAXkr5aq', 3, 'https://foruda.gitee.com/images/1723603502796844527/03cdca2a_716974.gif', '18812345679', 1, 'youlaitech@163.com', now(), NULL, now(), NULL, 0); INSERT INTO `sys_user` VALUES (4, 'dept_manager', '部门主管', 1, '$2a$10$xVWsNOhHrCxh5UbpCE7/HuJ.PAOKcYAqRxD2CO2nVnJS.IAXkr5aq', 1, 'https://foruda.gitee.com/images/1723603502796844527/03cdca2a_716974.gif', '18812345680', 1, 'manager@youlaitech.com', now(), NULL, now(), NULL, 0); @@ -381,7 +379,7 @@ INSERT INTO `sys_user` VALUES (6, 'employee', '普通员工', 1, '$2a$10$xVWsNOh INSERT INTO `sys_user` VALUES (7, 'custom_user', '自定义权限用户', 1, '$2a$10$xVWsNOhHrCxh5UbpCE7/HuJ.PAOKcYAqRxD2CO2nVnJS.IAXkr5aq', 3, 'https://foruda.gitee.com/images/1723603502796844527/03cdca2a_716974.gif', '18812345683', 1, 'custom@youlaitech.com', now(), NULL, now(), NULL, 0); -- ---------------------------- --- Table structure for sys_user_role +-- 表结构:sys_user_role -- ---------------------------- DROP TABLE IF EXISTS `sys_user_role`; CREATE TABLE `sys_user_role` ( @@ -391,7 +389,7 @@ CREATE TABLE `sys_user_role` ( ) ENGINE = InnoDB CHARACTER SET = utf8mb4 COMMENT = '用户角色关联表'; -- ---------------------------- --- Records of sys_user_role +-- 表数据:sys_user_role -- ---------------------------- INSERT IGNORE INTO `sys_user_role` VALUES (1, 1); INSERT IGNORE INTO `sys_user_role` VALUES (2, 2); @@ -403,7 +401,7 @@ INSERT IGNORE INTO `sys_user_role` VALUES (7, 7); -- ---------------------------- --- Table structure for sys_log +-- 表结构:sys_log -- ---------------------------- DROP TABLE IF EXISTS `sys_log`; CREATE TABLE `sys_log` ( @@ -433,7 +431,7 @@ CREATE TABLE `sys_log` ( ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='系统操作日志表'; -- ---------------------------- --- Table structure for gen_table +-- 表结构:gen_table -- ---------------------------- DROP TABLE IF EXISTS `gen_table`; CREATE TABLE `gen_table` ( @@ -446,7 +444,7 @@ CREATE TABLE `gen_table` ( `author` varchar(50) NOT NULL COMMENT '作者', `parent_menu_id` bigint COMMENT '上级菜单ID,对应sys_menu的id ', `remove_table_prefix` varchar(20) COMMENT '要移除的表前缀,如: sys_', - `page_type` varchar(20) COMMENT '页面类型(classic|curd)', + `page_type` varchar(20) COMMENT '页面类型(classic|crud)', `create_time` datetime COMMENT '创建时间', `update_time` datetime COMMENT '更新时间', `is_deleted` tinyint(4) DEFAULT 0 COMMENT '是否删除', @@ -455,7 +453,7 @@ CREATE TABLE `gen_table` ( ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='代码生成配置表'; -- ---------------------------- --- Table structure for gen_table_column +-- 表结构:gen_table_column -- ---------------------------- DROP TABLE IF EXISTS `gen_table_column`; CREATE TABLE `gen_table_column` ( @@ -564,7 +562,7 @@ INSERT INTO `sys_user_notice` VALUES (8, 8, 2, 1, NULL, now(), now(), 0); INSERT INTO `sys_user_notice` VALUES (9, 9, 2, 0, NULL, now(), now(), 0); INSERT INTO `sys_user_notice` VALUES (10, 10, 2, 1, NULL, now(), now(), 0); --- root 用户 (user_id=1) 绑定全部通知,5 条未读展示红点效果 +-- youlai 用户 (user_id=1) 绑定全部通知,5 条未读展示红点效果 INSERT INTO `sys_user_notice` VALUES (11, 1, 1, 0, NULL, now(), now(), 0); INSERT INTO `sys_user_notice` VALUES (12, 2, 1, 1, NULL, now(), now(), 0); INSERT INTO `sys_user_notice` VALUES (13, 3, 1, 0, NULL, now(), now(), 0); @@ -588,7 +586,7 @@ INSERT INTO `sys_user_notice` VALUES (28, 9, 3, 1, NULL, now(), now(), 0); INSERT INTO `sys_user_notice` VALUES (29, 10, 3, 0, NULL, now(), now(), 0); -- ---------------------------- --- Table structure for sys_user_social +-- 表结构:sys_user_social -- ---------------------------- DROP TABLE IF EXISTS `sys_user_social`; CREATE TABLE `sys_user_social` ( diff --git a/src/main/java/com/youlai/boot/auth/enums/CaptchaTypeEnum.java b/src/main/java/com/youlai/boot/auth/enums/CaptchaTypeEnum.java deleted file mode 100644 index ab9972a6..00000000 --- a/src/main/java/com/youlai/boot/auth/enums/CaptchaTypeEnum.java +++ /dev/null @@ -1,14 +0,0 @@ -package com.youlai.boot.auth.enums; - -/** - * EasyCaptcha 验证码类型 - * - * @author haoxr - * @since 2.5.1 - */ -public enum CaptchaTypeEnum { - CIRCLE, - GIF, - LINE, - SHEAR -} diff --git a/src/main/java/com/youlai/boot/auth/model/dto/QrCodeLoginContext.java b/src/main/java/com/youlai/boot/auth/model/dto/QrCodeLoginContext.java deleted file mode 100644 index 357b67d6..00000000 --- a/src/main/java/com/youlai/boot/auth/model/dto/QrCodeLoginContext.java +++ /dev/null @@ -1,40 +0,0 @@ -package com.youlai.boot.auth.model.dto; - -import lombok.Data; - -/** - * 扫码登录票据上下文,序列化为 JSON 存入 Redis - * - * @author Ray.Hao - * @since 4.5.0 - */ -@Data -public class QrCodeLoginContext { - - /** 票据,UUID 无连字符 */ - private String ticket; - - /** 状态枚举名,取 {@link com.youlai.boot.auth.enums.QrCodeLoginStatusEnum#name()} */ - private String status; - - /** 扫码用户 ID,scan 时写入 */ - private Long userId; - - /** 用户原始昵称(未脱敏),status 接口返回时脱敏 */ - private String nickname; - - /** 用户头像 URL */ - private String avatar; - - /** 创建时间戳(毫秒) */ - private Long createdAt; - - /** 扫码时间戳(毫秒) */ - private Long scannedAt; - - /** 确认时间戳(毫秒) */ - private Long confirmedAt; - - /** generate 时的 PC 端 IP */ - private String clientIp; -} diff --git a/src/main/java/com/youlai/boot/config/CaptchaConfig.java b/src/main/java/com/youlai/boot/auth/password/config/CaptchaConfig.java similarity index 91% rename from src/main/java/com/youlai/boot/config/CaptchaConfig.java rename to src/main/java/com/youlai/boot/auth/password/config/CaptchaConfig.java index d5a68e1f..75d25261 100644 --- a/src/main/java/com/youlai/boot/config/CaptchaConfig.java +++ b/src/main/java/com/youlai/boot/auth/password/config/CaptchaConfig.java @@ -1,9 +1,8 @@ -package com.youlai.boot.config; +package com.youlai.boot.auth.password.config; import cn.hutool.captcha.generator.CodeGenerator; import cn.hutool.captcha.generator.MathGenerator; import cn.hutool.captcha.generator.RandomGenerator; -import com.youlai.boot.config.property.CaptchaProperties; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @@ -13,8 +12,8 @@ import java.awt.*; /** * 验证码自动装配配置 * - * @author haoxr - * @since 2023/11/24 + * @author Ray.Hao + * @since 1.0.0 */ @Configuration public class CaptchaConfig { diff --git a/src/main/java/com/youlai/boot/config/property/CaptchaProperties.java b/src/main/java/com/youlai/boot/auth/password/config/CaptchaProperties.java similarity index 55% rename from src/main/java/com/youlai/boot/config/property/CaptchaProperties.java rename to src/main/java/com/youlai/boot/auth/password/config/CaptchaProperties.java index 4067d51e..7e7bda1c 100644 --- a/src/main/java/com/youlai/boot/config/property/CaptchaProperties.java +++ b/src/main/java/com/youlai/boot/auth/password/config/CaptchaProperties.java @@ -1,11 +1,11 @@ -package com.youlai.boot.config.property; +package com.youlai.boot.auth.password.config; import lombok.Data; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.stereotype.Component; /** - * 验证码 属性配置 + * 验证码配置属性 * * @author Ray.Hao * @since 2023/11/24 @@ -15,43 +15,27 @@ import org.springframework.stereotype.Component; @Data public class CaptchaProperties { - /** - * 验证码类型 circle-圆圈干扰验证码|gif-Gif验证码|line-干扰线验证码|shear-扭曲干扰验证码 - */ + // 验证码类型 circle-圆圈干扰验证码|gif-Gif验证码|line-干扰线验证码|shear-扭曲干扰验证码 private String type; - /** - * 验证码图片宽度 - */ + // 验证码图片宽度 private int width; - /** - * 验证码图片高度 - */ + // 验证码图片高度 private int height; - /** - * 干扰线数量 - */ + // 干扰线数量 private int interfereCount; - /** - * 文本透明度 - */ + // 文本透明度 private Float textAlpha; - /** - * 验证码过期时间,单位:秒 - */ + // 验证码过期时间,单位:秒 private Long expireSeconds; - /** - * 验证码字符配置 - */ + // 验证码字符配置 private CodeProperties code; - /** - * 验证码字体 - */ + // 验证码字体 private FontProperties font; /** @@ -59,13 +43,9 @@ public class CaptchaProperties { */ @Data public static class CodeProperties { - /** - * 验证码字符类型 math-算术|random-随机字符串 - */ + // 验证码字符类型 math-算术|random-随机字符串 private String type; - /** - * 验证码字符长度,type=算术时,表示运算位数(1:个位数 2:十位数);type=随机字符时,表示字符个数 - */ + // 验证码字符长度,type=算术时,表示运算位数(1:个位数 2:十位数);type=随机字符时,表示字符个数 private int length; } @@ -74,17 +54,11 @@ public class CaptchaProperties { */ @Data public static class FontProperties { - /** - * 字体名称 - */ + // 字体名称 private String name; - /** - * 字体样式 0-普通|1-粗体|2-斜体 - */ + // 字体样式 0-普通|1-粗体|2-斜体 private int weight; - /** - * 字体大小 - */ + // 字体大小 private int size; } diff --git a/src/main/java/com/youlai/boot/auth/password/controller/PasswordAuthController.java b/src/main/java/com/youlai/boot/auth/password/controller/PasswordAuthController.java new file mode 100644 index 00000000..d0e74cb4 --- /dev/null +++ b/src/main/java/com/youlai/boot/auth/password/controller/PasswordAuthController.java @@ -0,0 +1,52 @@ +package com.youlai.boot.auth.password.controller; + +import com.youlai.boot.auth.password.model.form.LoginForm; +import com.youlai.boot.auth.password.model.vo.CaptchaVO; +import com.youlai.boot.auth.password.service.PasswordAuthService; +import com.youlai.boot.common.annotation.Log; +import com.youlai.boot.common.enums.ActionTypeEnum; +import com.youlai.boot.common.enums.LogModuleEnum; +import com.youlai.boot.common.result.Result; +import com.youlai.boot.framework.security.model.AuthenticationToken; +import com.youlai.boot.framework.web.ratelimit.RateLimit; +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.PostMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RestController; + +/** + * 账号密码认证接口 + * + * @author Ray.Hao + * @since 4.8.0 + */ +@Tag(name = "01.认证中心") +@RestController +@RequestMapping("/api/v1/auth") +@RequiredArgsConstructor +public class PasswordAuthController { + + private final PasswordAuthService passwordAuthService; + + @Operation(summary = "获取验证码") + @GetMapping("/captcha") + public Result getCaptcha() { + CaptchaVO captcha = passwordAuthService.getCaptcha(); + return Result.success(captcha); + } + + @Operation(summary = "账号密码登录") + @PostMapping("/login") + @Log(module = LogModuleEnum.LOGIN, value = ActionTypeEnum.LOGIN) + @RateLimit + public Result login(@RequestBody @Valid LoginForm request) { + AuthenticationToken authenticationToken = passwordAuthService.login(request.getUsername(), request.getPassword()); + return Result.success(authenticationToken); + } + +} diff --git a/src/main/java/com/youlai/boot/auth/password/enums/CaptchaTypeEnum.java b/src/main/java/com/youlai/boot/auth/password/enums/CaptchaTypeEnum.java new file mode 100644 index 00000000..fdcc70f5 --- /dev/null +++ b/src/main/java/com/youlai/boot/auth/password/enums/CaptchaTypeEnum.java @@ -0,0 +1,22 @@ +package com.youlai.boot.auth.password.enums; + +/** + * 验证码类型 + * + * @author Ray.Hao + * @since 2.5.1 + */ +public enum CaptchaTypeEnum { + + /** 圆圈干扰验证码 */ + CIRCLE, + + /** Gif 动画验证码 */ + GIF, + + /** 干扰线验证码 */ + LINE, + + /** 扭曲干扰验证码 */ + SHEAR +} diff --git a/src/main/java/com/youlai/boot/auth/exception/CaptchaException.java b/src/main/java/com/youlai/boot/auth/password/exception/CaptchaException.java similarity index 79% rename from src/main/java/com/youlai/boot/auth/exception/CaptchaException.java rename to src/main/java/com/youlai/boot/auth/password/exception/CaptchaException.java index 78702000..5e484b00 100644 --- a/src/main/java/com/youlai/boot/auth/exception/CaptchaException.java +++ b/src/main/java/com/youlai/boot/auth/password/exception/CaptchaException.java @@ -1,12 +1,10 @@ -package com.youlai.boot.auth.exception; +package com.youlai.boot.auth.password.exception; import com.youlai.boot.common.result.ResultCode; import lombok.Getter; /** * 图形验证码校验失败时抛出的异常。 - *

- * 携带 {@link ResultCode} 用于统一错误响应。 * * @author Ray.Hao * @since 3.1.0 diff --git a/src/main/java/com/youlai/boot/auth/security/filter/CaptchaValidationFilter.java b/src/main/java/com/youlai/boot/auth/password/filter/CaptchaValidationFilter.java similarity index 93% rename from src/main/java/com/youlai/boot/auth/security/filter/CaptchaValidationFilter.java rename to src/main/java/com/youlai/boot/auth/password/filter/CaptchaValidationFilter.java index 34f569ab..36e93e68 100644 --- a/src/main/java/com/youlai/boot/auth/security/filter/CaptchaValidationFilter.java +++ b/src/main/java/com/youlai/boot/auth/password/filter/CaptchaValidationFilter.java @@ -1,13 +1,13 @@ -package com.youlai.boot.auth.security.filter; +package com.youlai.boot.auth.password.filter; import cn.hutool.core.util.StrUtil; import cn.hutool.json.JSONObject; import cn.hutool.json.JSONUtil; +import com.youlai.boot.auth.password.exception.CaptchaException; +import com.youlai.boot.auth.password.service.CaptchaService; import com.youlai.boot.common.constant.SecurityConstants; import com.youlai.boot.common.result.ResultCode; import com.youlai.boot.framework.web.util.ResponseWriter; -import com.youlai.boot.auth.exception.CaptchaException; -import com.youlai.boot.auth.service.CaptchaService; import jakarta.servlet.FilterChain; import jakarta.servlet.ServletException; import jakarta.servlet.ServletInputStream; @@ -29,9 +29,9 @@ import java.io.InputStreamReader; import java.nio.charset.StandardCharsets; /** - * 图形验证码校验过滤器。 - *

- * 归使用方,因为验证码规则(哪些接口需要验证码、验证码类型)因项目而异。 + * 图形验证码校验过滤器 + * + * @author Ray.Hao */ public class CaptchaValidationFilter extends OncePerRequestFilter { diff --git a/src/main/java/com/youlai/boot/auth/model/req/LoginReq.java b/src/main/java/com/youlai/boot/auth/password/model/form/LoginForm.java similarity index 84% rename from src/main/java/com/youlai/boot/auth/model/req/LoginReq.java rename to src/main/java/com/youlai/boot/auth/password/model/form/LoginForm.java index bb8c9002..c60c1289 100644 --- a/src/main/java/com/youlai/boot/auth/model/req/LoginReq.java +++ b/src/main/java/com/youlai/boot/auth/password/model/form/LoginForm.java @@ -1,15 +1,17 @@ -package com.youlai.boot.auth.model.req; +package com.youlai.boot.auth.password.model.form; import io.swagger.v3.oas.annotations.media.Schema; import jakarta.validation.constraints.NotBlank; import lombok.Data; /** - * 登录请求参数 + * 账号密码登录请求参数 + * + * @author Ray.Hao */ @Schema(description = "登录请求参数") @Data -public class LoginReq { +public class LoginForm { @Schema(description = "用户名", requiredMode = Schema.RequiredMode.REQUIRED, example = "admin") @NotBlank(message = "用户名不能为空") diff --git a/src/main/java/com/youlai/boot/auth/model/resp/CaptchaInfo.java b/src/main/java/com/youlai/boot/auth/password/model/vo/CaptchaVO.java similarity index 82% rename from src/main/java/com/youlai/boot/auth/model/resp/CaptchaInfo.java rename to src/main/java/com/youlai/boot/auth/password/model/vo/CaptchaVO.java index 8897c982..e4189e4f 100644 --- a/src/main/java/com/youlai/boot/auth/model/resp/CaptchaInfo.java +++ b/src/main/java/com/youlai/boot/auth/password/model/vo/CaptchaVO.java @@ -1,4 +1,4 @@ -package com.youlai.boot.auth.model.resp; +package com.youlai.boot.auth.password.model.vo; import io.swagger.v3.oas.annotations.media.Schema; import lombok.AllArgsConstructor; @@ -8,13 +8,15 @@ import lombok.NoArgsConstructor; /** * 验证码信息 + * + * @author Ray.Hao */ @Data @Builder @NoArgsConstructor @AllArgsConstructor @Schema(description = "验证码信息") -public class CaptchaInfo { +public class CaptchaVO { @Schema(description = "验证码缓存ID") private String captchaId; diff --git a/src/main/java/com/youlai/boot/auth/service/CaptchaService.java b/src/main/java/com/youlai/boot/auth/password/service/CaptchaService.java similarity index 89% rename from src/main/java/com/youlai/boot/auth/service/CaptchaService.java rename to src/main/java/com/youlai/boot/auth/password/service/CaptchaService.java index 4ce21b58..ec188074 100644 --- a/src/main/java/com/youlai/boot/auth/service/CaptchaService.java +++ b/src/main/java/com/youlai/boot/auth/password/service/CaptchaService.java @@ -1,16 +1,16 @@ -package com.youlai.boot.auth.service; +package com.youlai.boot.auth.password.service; import cn.hutool.captcha.AbstractCaptcha; import cn.hutool.captcha.CaptchaUtil; import cn.hutool.captcha.generator.CodeGenerator; import cn.hutool.core.util.IdUtil; import cn.hutool.core.util.StrUtil; +import com.youlai.boot.auth.password.config.CaptchaProperties; +import com.youlai.boot.auth.password.enums.CaptchaTypeEnum; +import com.youlai.boot.auth.password.exception.CaptchaException; +import com.youlai.boot.auth.password.model.vo.CaptchaVO; import com.youlai.boot.common.constant.RedisConstants; -import com.youlai.boot.auth.enums.CaptchaTypeEnum; import com.youlai.boot.common.result.ResultCode; -import com.youlai.boot.config.property.CaptchaProperties; -import com.youlai.boot.auth.exception.CaptchaException; -import com.youlai.boot.auth.model.resp.CaptchaInfo; import lombok.RequiredArgsConstructor; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.stereotype.Service; @@ -35,8 +35,10 @@ public class CaptchaService { /** * 生成验证码 + * + * @return 验证码ID与图片Base64 */ - public CaptchaInfo generate() { + public CaptchaVO generate() { String captchaType = captchaProperties.getType(); int width = captchaProperties.getWidth(); int height = captchaProperties.getHeight(); @@ -71,7 +73,7 @@ public class CaptchaService { TimeUnit.SECONDS ); - return CaptchaInfo.builder() + return CaptchaVO.builder() .captchaId(captchaId) .captchaBase64(imageBase64Data) .build(); diff --git a/src/main/java/com/youlai/boot/auth/password/service/PasswordAuthService.java b/src/main/java/com/youlai/boot/auth/password/service/PasswordAuthService.java new file mode 100644 index 00000000..c405219c --- /dev/null +++ b/src/main/java/com/youlai/boot/auth/password/service/PasswordAuthService.java @@ -0,0 +1,58 @@ +package com.youlai.boot.auth.password.service; + +import com.youlai.boot.auth.password.model.vo.CaptchaVO; +import com.youlai.boot.framework.security.model.AuthenticationToken; +import com.youlai.boot.framework.security.token.TokenManager; +import lombok.RequiredArgsConstructor; +import org.springframework.security.authentication.AuthenticationManager; +import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; +import org.springframework.security.core.Authentication; +import org.springframework.security.core.context.SecurityContextHolder; +import org.springframework.stereotype.Service; + +/** + * 账号密码登录服务 + * + * @author Ray.Hao + * @since 4.8.0 + */ +@Service +@RequiredArgsConstructor +public class PasswordAuthService { + + private final AuthenticationManager authenticationManager; + private final TokenManager tokenManager; + private final CaptchaService captchaService; + + /** + * 用户名密码登录 + * + * @param username 用户名 + * @param password 密码 + * @return 访问令牌 + */ + public AuthenticationToken login(String username, String password) { + // 1. 创建用于密码认证的令牌(未认证) + UsernamePasswordAuthenticationToken authenticationToken = + new UsernamePasswordAuthenticationToken(username.trim(), password); + + // 2. 执行认证(认证中) + Authentication authentication = authenticationManager.authenticate(authenticationToken); + + // 3. 认证成功后生成 JWT 令牌,并存入 Security 上下文,供登录日志 AOP 使用(已认证) + AuthenticationToken authenticationTokenResponse = + tokenManager.generateToken(authentication); + SecurityContextHolder.getContext().setAuthentication(authentication); + return authenticationTokenResponse; + } + + /** + * 获取验证码 + * + * @return 验证码ID与图片Base64 + */ + public CaptchaVO getCaptcha() { + return captchaService.generate(); + } + +} diff --git a/src/main/java/com/youlai/boot/auth/controller/QrCodeAuthController.java b/src/main/java/com/youlai/boot/auth/qrcode/controller/QrCodeAuthController.java similarity index 71% rename from src/main/java/com/youlai/boot/auth/controller/QrCodeAuthController.java rename to src/main/java/com/youlai/boot/auth/qrcode/controller/QrCodeAuthController.java index 221ef724..6307e60c 100644 --- a/src/main/java/com/youlai/boot/auth/controller/QrCodeAuthController.java +++ b/src/main/java/com/youlai/boot/auth/qrcode/controller/QrCodeAuthController.java @@ -1,14 +1,14 @@ -package com.youlai.boot.auth.controller; +package com.youlai.boot.auth.qrcode.controller; -import com.youlai.boot.auth.model.req.QrCodeTicketReq; -import com.youlai.boot.auth.model.resp.QrCodeGenerateResp; -import com.youlai.boot.auth.model.resp.QrCodeStatusResp; -import com.youlai.boot.auth.service.QrCodeLoginService; -import com.youlai.boot.common.util.IPUtils; -import com.youlai.boot.common.annotation.RateLimit; +import com.youlai.boot.auth.qrcode.model.form.QrCodeTicketForm; +import com.youlai.boot.auth.qrcode.model.vo.QrCodeGenerateVO; +import com.youlai.boot.auth.qrcode.model.vo.QrCodeStatusVO; +import com.youlai.boot.auth.qrcode.service.QrCodeLoginService; import com.youlai.boot.common.result.Result; import com.youlai.boot.framework.security.model.AuthenticationToken; import com.youlai.boot.framework.security.util.SecurityUtils; +import com.youlai.boot.framework.web.ratelimit.RateLimit; +import com.youlai.boot.framework.web.util.IPUtils; import io.swagger.v3.oas.annotations.Operation; import io.swagger.v3.oas.annotations.tags.Tag; import jakarta.servlet.http.HttpServletRequest; @@ -24,9 +24,6 @@ import org.springframework.web.bind.annotation.RestController; /** * 扫码登录认证接口 * - *

generate/status/login 不需要登录态(PC 端未登录),由 Security 配置放行; - * scan/confirm/cancel 需要 APP 端登录态,当前用户 ID 从 Security 上下文获取。

- * * @author Ray.Hao * @since 4.5.0 */ @@ -44,7 +41,7 @@ public class QrCodeAuthController { @Operation(summary = "[扫码]生成扫码登录票据") @PostMapping("/generate") @RateLimit(limit = 30, window = 60) - public Result generate(HttpServletRequest request) { + public Result generate(HttpServletRequest request) { return Result.success(qrCodeLoginService.generate(IPUtils.getIpAddr(request))); } @@ -54,7 +51,7 @@ public class QrCodeAuthController { @Operation(summary = "[扫码]查询扫码状态") @GetMapping("/status") @RateLimit(limit = 60, window = 60) - public Result status(@RequestParam String ticket) { + public Result status(@RequestParam String ticket) { return Result.success(qrCodeLoginService.status(ticket)); } @@ -63,7 +60,7 @@ public class QrCodeAuthController { */ @Operation(summary = "[扫码]APP 标记已扫码") @PostMapping("/scan") - public Result scan(@RequestBody @Valid QrCodeTicketReq form) { + public Result scan(@RequestBody @Valid QrCodeTicketForm form) { return Result.success(qrCodeLoginService.scan(form.getTicket(), SecurityUtils.getUserId())); } @@ -72,7 +69,7 @@ public class QrCodeAuthController { */ @Operation(summary = "[扫码]APP 确认登录") @PostMapping("/confirm") - public Result confirm(@RequestBody @Valid QrCodeTicketReq form) { + public Result confirm(@RequestBody @Valid QrCodeTicketForm form) { return Result.success(qrCodeLoginService.confirm(form.getTicket(), SecurityUtils.getUserId())); } @@ -81,7 +78,7 @@ public class QrCodeAuthController { */ @Operation(summary = "[扫码]APP 取消登录") @PostMapping("/cancel") - public Result cancel(@RequestBody @Valid QrCodeTicketReq form) { + public Result cancel(@RequestBody @Valid QrCodeTicketForm form) { return Result.success(qrCodeLoginService.cancel(form.getTicket(), SecurityUtils.getUserId())); } @@ -90,7 +87,7 @@ public class QrCodeAuthController { */ @Operation(summary = "[扫码]PC 端换取会话令牌") @PostMapping("/login") - public Result login(@RequestBody @Valid QrCodeTicketReq form) { + public Result login(@RequestBody @Valid QrCodeTicketForm form) { return Result.success(qrCodeLoginService.login(form.getTicket())); } } diff --git a/src/main/java/com/youlai/boot/auth/enums/QrCodeLoginStatusEnum.java b/src/main/java/com/youlai/boot/auth/qrcode/enums/QrCodeLoginStatusEnum.java similarity index 92% rename from src/main/java/com/youlai/boot/auth/enums/QrCodeLoginStatusEnum.java rename to src/main/java/com/youlai/boot/auth/qrcode/enums/QrCodeLoginStatusEnum.java index 181bca5d..94c6d37e 100644 --- a/src/main/java/com/youlai/boot/auth/enums/QrCodeLoginStatusEnum.java +++ b/src/main/java/com/youlai/boot/auth/qrcode/enums/QrCodeLoginStatusEnum.java @@ -1,4 +1,4 @@ -package com.youlai.boot.auth.enums; +package com.youlai.boot.auth.qrcode.enums; /** * 扫码登录票据状态 diff --git a/src/main/java/com/youlai/boot/auth/qrcode/model/context/QrCodeLoginContext.java b/src/main/java/com/youlai/boot/auth/qrcode/model/context/QrCodeLoginContext.java new file mode 100644 index 00000000..c6607add --- /dev/null +++ b/src/main/java/com/youlai/boot/auth/qrcode/model/context/QrCodeLoginContext.java @@ -0,0 +1,40 @@ +package com.youlai.boot.auth.qrcode.model.context; + +import lombok.Data; + +/** + * 扫码登录票据上下文,序列化为 JSON 存入 Redis + * + * @author Ray.Hao + * @since 4.5.0 + */ +@Data +public class QrCodeLoginContext { + + // 票据,UUID 无连字符 + private String ticket; + + // 状态枚举名,取 {@link com.youlai.boot.auth.qrcode.enums.QrCodeLoginStatusEnum#name()} + private String status; + + // 扫码用户 ID,scan 时写入 + private Long userId; + + // 用户原始昵称(未脱敏),status 接口返回时脱敏 + private String nickname; + + // 用户头像 URL + private String avatar; + + // 创建时间戳(毫秒) + private Long createdAt; + + // 扫码时间戳(毫秒) + private Long scannedAt; + + // 确认时间戳(毫秒) + private Long confirmedAt; + + // generate 时的 PC 端 IP + private String clientIp; +} diff --git a/src/main/java/com/youlai/boot/auth/model/req/QrCodeTicketReq.java b/src/main/java/com/youlai/boot/auth/qrcode/model/form/QrCodeTicketForm.java similarity index 77% rename from src/main/java/com/youlai/boot/auth/model/req/QrCodeTicketReq.java rename to src/main/java/com/youlai/boot/auth/qrcode/model/form/QrCodeTicketForm.java index 9e8e86d1..a847b159 100644 --- a/src/main/java/com/youlai/boot/auth/model/req/QrCodeTicketReq.java +++ b/src/main/java/com/youlai/boot/auth/qrcode/model/form/QrCodeTicketForm.java @@ -1,4 +1,4 @@ -package com.youlai.boot.auth.model.req; +package com.youlai.boot.auth.qrcode.model.form; import jakarta.validation.constraints.NotBlank; import lombok.Data; @@ -10,7 +10,7 @@ import lombok.Data; * @since 4.5.0 */ @Data -public class QrCodeTicketReq { +public class QrCodeTicketForm { @NotBlank(message = "票据不能为空") private String ticket; diff --git a/src/main/java/com/youlai/boot/auth/model/resp/QrCodeGenerateResp.java b/src/main/java/com/youlai/boot/auth/qrcode/model/vo/QrCodeGenerateVO.java similarity index 83% rename from src/main/java/com/youlai/boot/auth/model/resp/QrCodeGenerateResp.java rename to src/main/java/com/youlai/boot/auth/qrcode/model/vo/QrCodeGenerateVO.java index dc830b15..5982b0dd 100644 --- a/src/main/java/com/youlai/boot/auth/model/resp/QrCodeGenerateResp.java +++ b/src/main/java/com/youlai/boot/auth/qrcode/model/vo/QrCodeGenerateVO.java @@ -1,4 +1,4 @@ -package com.youlai.boot.auth.model.resp; +package com.youlai.boot.auth.qrcode.model.vo; import io.swagger.v3.oas.annotations.media.Schema; import lombok.Builder; @@ -13,7 +13,7 @@ import lombok.Data; @Data @Builder @Schema(description = "扫码票据生成结果") -public class QrCodeGenerateResp { +public class QrCodeGenerateVO { @Schema(description = "票据") private String ticket; diff --git a/src/main/java/com/youlai/boot/auth/model/resp/QrCodeStatusResp.java b/src/main/java/com/youlai/boot/auth/qrcode/model/vo/QrCodeStatusVO.java similarity index 90% rename from src/main/java/com/youlai/boot/auth/model/resp/QrCodeStatusResp.java rename to src/main/java/com/youlai/boot/auth/qrcode/model/vo/QrCodeStatusVO.java index b2ea3a2d..d3ef62b7 100644 --- a/src/main/java/com/youlai/boot/auth/model/resp/QrCodeStatusResp.java +++ b/src/main/java/com/youlai/boot/auth/qrcode/model/vo/QrCodeStatusVO.java @@ -1,4 +1,4 @@ -package com.youlai.boot.auth.model.resp; +package com.youlai.boot.auth.qrcode.model.vo; import io.swagger.v3.oas.annotations.media.Schema; import lombok.Builder; @@ -13,7 +13,7 @@ import lombok.Data; @Data @Builder @Schema(description = "扫码登录状态") -public class QrCodeStatusResp { +public class QrCodeStatusVO { @Schema(description = "票据") private String ticket; diff --git a/src/main/java/com/youlai/boot/auth/service/QrCodeLoginService.java b/src/main/java/com/youlai/boot/auth/qrcode/service/QrCodeLoginService.java similarity index 90% rename from src/main/java/com/youlai/boot/auth/service/QrCodeLoginService.java rename to src/main/java/com/youlai/boot/auth/qrcode/service/QrCodeLoginService.java index cd807d75..c11621e8 100644 --- a/src/main/java/com/youlai/boot/auth/service/QrCodeLoginService.java +++ b/src/main/java/com/youlai/boot/auth/qrcode/service/QrCodeLoginService.java @@ -1,14 +1,14 @@ -package com.youlai.boot.auth.service; +package com.youlai.boot.auth.qrcode.service; import cn.hutool.core.util.IdUtil; import cn.hutool.core.util.StrUtil; -import com.youlai.boot.auth.enums.QrCodeLoginStatusEnum; -import com.youlai.boot.auth.model.dto.QrCodeLoginContext; -import com.youlai.boot.auth.model.resp.QrCodeGenerateResp; -import com.youlai.boot.auth.model.resp.QrCodeStatusResp; +import com.youlai.boot.auth.qrcode.enums.QrCodeLoginStatusEnum; +import com.youlai.boot.auth.qrcode.model.context.QrCodeLoginContext; +import com.youlai.boot.auth.qrcode.model.vo.QrCodeGenerateVO; +import com.youlai.boot.auth.qrcode.model.vo.QrCodeStatusVO; import com.youlai.boot.common.constant.RedisConstants; -import com.youlai.boot.common.result.ResultCode; import com.youlai.boot.common.exception.TokenInvalidException; +import com.youlai.boot.common.result.ResultCode; import com.youlai.boot.framework.security.model.AuthenticationToken; import com.youlai.boot.framework.security.model.SecurityUser; import com.youlai.boot.framework.security.model.SecurityUserDetails; @@ -35,16 +35,13 @@ import java.util.concurrent.TimeUnit; @Slf4j public class QrCodeLoginService { - /** 票据默认有效期(秒) */ + // 票据默认有效期(秒) private static final int DEFAULT_EXPIRE_SECONDS = 300; - /** 状态流转时若 Redis 剩余 TTL 小于该值,补足到此值 */ + // 状态流转时若 Redis 剩余 TTL 小于该值,补足到此值 private static final int MIN_REMAIN_SECONDS = 30; - /** - * 从 Redis 读回的值可能是不带类型信息的 Map(序列化器以 Object.class 存储), - * 用它把 Map 转回强类型上下文对象。JsonMapper 线程安全,复用单例。 - */ + // 从 Redis 读回的值可能是不带类型信息的 Map(序列化器以 Object.class 存储), private static final JsonMapper JSON_MAPPER = JsonMapper.builder().build(); private final RedisTemplate redisTemplate; @@ -54,7 +51,7 @@ public class QrCodeLoginService { /** * 生成扫码票据,写入 Redis 后返回 ticket 和有效期 */ - public QrCodeGenerateResp generate(String clientIp) { + public QrCodeGenerateVO generate(String clientIp) { String ticket = IdUtil.fastSimpleUUID(); QrCodeLoginContext ctx = new QrCodeLoginContext(); ctx.setTicket(ticket); @@ -62,7 +59,7 @@ public class QrCodeLoginService { ctx.setCreatedAt(System.currentTimeMillis()); ctx.setClientIp(clientIp); save(ctx, DEFAULT_EXPIRE_SECONDS); - return QrCodeGenerateResp.builder() + return QrCodeGenerateVO.builder() .ticket(ticket) .expireSeconds(DEFAULT_EXPIRE_SECONDS) .build(); @@ -71,7 +68,7 @@ public class QrCodeLoginService { /** * PC 端轮询扫码状态,未登录调用 */ - public QrCodeStatusResp status(String ticket) { + public QrCodeStatusVO status(String ticket) { QrCodeLoginContext ctx = loadOrThrow(ticket); return toResp(ctx, remainingSeconds(ticket)); } @@ -79,7 +76,7 @@ public class QrCodeLoginService { /** * APP 端标记已扫码,需已登录。WAITING → SCANNED */ - public QrCodeStatusResp scan(String ticket, Long userId) { + public QrCodeStatusVO scan(String ticket, Long userId) { QrCodeLoginContext ctx = loadOrThrow(ticket); requireStatus(ctx, QrCodeLoginStatusEnum.WAITING); fillUserInfo(ctx, userId); @@ -92,7 +89,7 @@ public class QrCodeLoginService { /** * APP 端确认登录,需扫码本人操作。SCANNED → CONFIRMED */ - public QrCodeStatusResp confirm(String ticket, Long userId) { + public QrCodeStatusVO confirm(String ticket, Long userId) { QrCodeLoginContext ctx = loadOrThrow(ticket); requireStatus(ctx, QrCodeLoginStatusEnum.SCANNED); requireSameUser(ctx, userId); @@ -105,7 +102,7 @@ public class QrCodeLoginService { /** * APP 端取消登录,仅流程中的票据可取消 */ - public QrCodeStatusResp cancel(String ticket, Long userId) { + public QrCodeStatusVO cancel(String ticket, Long userId) { QrCodeLoginContext ctx = loadOrThrow(ticket); QrCodeLoginStatusEnum current = QrCodeLoginStatusEnum.valueOf(ctx.getStatus()); // 只有还在流程中的票据(等待扫码 / 已扫码 / 已确认)允许取消 @@ -223,7 +220,7 @@ public class QrCodeLoginService { /** * 上下文转前端 VO,昵称脱敏、用户信息仅在扫码后暴露 */ - private QrCodeStatusResp toResp(QrCodeLoginContext ctx, int expireSeconds) { + private QrCodeStatusVO toResp(QrCodeLoginContext ctx, int expireSeconds) { QrCodeLoginStatusEnum status = QrCodeLoginStatusEnum.valueOf(ctx.getStatus()); String nickname = null; String avatar = null; @@ -233,7 +230,7 @@ public class QrCodeLoginService { nickname = maskNickname(ctx.getNickname()); avatar = ctx.getAvatar(); } - return QrCodeStatusResp.builder() + return QrCodeStatusVO.builder() .ticket(ctx.getTicket()) .status(status.name()) .nickname(nickname) diff --git a/src/main/java/com/youlai/boot/auth/service/AuthService.java b/src/main/java/com/youlai/boot/auth/service/AuthService.java deleted file mode 100644 index acca88df..00000000 --- a/src/main/java/com/youlai/boot/auth/service/AuthService.java +++ /dev/null @@ -1,143 +0,0 @@ -package com.youlai.boot.auth.service; - -import cn.hutool.core.util.StrUtil; -import com.youlai.boot.common.constant.RedisConstants; -import com.youlai.boot.auth.model.resp.CaptchaInfo; -import com.youlai.boot.framework.security.model.AuthenticationToken; -import com.youlai.boot.framework.security.token.TokenManager; -import com.youlai.boot.auth.security.token.SmsAuthenticationToken; -import com.youlai.boot.framework.security.util.SecurityUtils; -import com.youlai.boot.support.sms.SmsTypeEnum; -import com.youlai.boot.support.sms.SmsService; -import lombok.RequiredArgsConstructor; -import lombok.extern.slf4j.Slf4j; -import org.springframework.data.redis.core.RedisTemplate; -import org.springframework.security.authentication.AuthenticationManager; -import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; -import org.springframework.security.core.Authentication; -import org.springframework.security.core.context.SecurityContextHolder; -import org.springframework.stereotype.Service; - -import java.util.HashMap; -import java.util.Map; -import java.util.concurrent.TimeUnit; - -/** - * 认证服务 - * - * @author Ray.Hao - * @since 2.4.0 - */ -@Service -@RequiredArgsConstructor -@Slf4j -public class AuthService { - - private final AuthenticationManager authenticationManager; - private final TokenManager tokenManager; - - private final SmsService smsService; - private final RedisTemplate redisTemplate; - private final CaptchaService captchaService; - - /** - * 用户名密码登录 - * - * @param username 用户名 - * @param password 密码 - * @return 访问令牌 - */ - public AuthenticationToken login(String username, String password) { - // 1. 创建用于密码认证的令牌(未认证) - UsernamePasswordAuthenticationToken authenticationToken = - new UsernamePasswordAuthenticationToken(username.trim(), password); - - // 2. 执行认证(认证中) - // 说明:这里的认证流程由 Spring Security 提供的 AuthenticationManager 执行。 - // 默认情况下会委托给 DaoAuthenticationProvider: - // 1) retrieveUser(...):内部通过 UserDetailsService.loadUserByUsername(...) 获取用户信息(本项目为 SecurityUserDetailsService 实现) - // 2) additionalAuthenticationChecks(...):对比请求密码与用户存储密码(由 PasswordEncoder 完成匹配) - // 认证通过后返回已认证的 Authentication(principal 为 SecurityUserDetails,authorities 为角色/权限集合)。 - Authentication authentication = authenticationManager.authenticate(authenticationToken); - - // 3. 认证成功后生成 JWT 令牌,并存入 Security 上下文,供登录日志 AOP 使用(已认证) - AuthenticationToken authenticationTokenResponse = - tokenManager.generateToken(authentication); - SecurityContextHolder.getContext().setAuthentication(authentication); - return authenticationTokenResponse; - } - - /** - * 发送登录短信验证码 - * - * @param mobile 手机号 - */ - public void sendSmsCode(String mobile) { - - // 随机生成4位验证码 - // String code = String.valueOf((int) ((Math.random() * 9 + 1) * 1000)); - // TODO 为了方便测试,验证码固定为 1234,实际开发中在配置了厂商短信服务后,可以使用上面的随机验证码 - String code = "1234"; - - // 发送短信验证码 - Map templateParams = new HashMap<>(); - templateParams.put("code", code); - try { - smsService.send(mobile, SmsTypeEnum.LOGIN, templateParams); - } catch (Exception e) { - log.error("发送短信验证码失败", e); - } - // 缓存验证码至Redis,用于登录校验 - redisTemplate.opsForValue().set(StrUtil.format(RedisConstants.Captcha.SMS_LOGIN_CODE, mobile), code, 5, TimeUnit.MINUTES); - } - - /** - * 短信验证码登录 - * - * @param mobile 手机号 - * @param code 验证码 - * @return 访问令牌 - */ - public AuthenticationToken loginBySms(String mobile, String code) { - // 1. 创建用户短信验证码认证的令牌(未认证) - SmsAuthenticationToken smsAuthenticationToken = new SmsAuthenticationToken(mobile, code); - - // 2. 执行认证(认证中) - Authentication authentication = authenticationManager.authenticate(smsAuthenticationToken); - - // 3. 认证成功后生成 JWT 令牌,并存入 Security 上下文,供登录日志 AOP 使用(已认证) - AuthenticationToken authenticationToken = tokenManager.generateToken(authentication); - SecurityContextHolder.getContext().setAuthentication(authentication); - return authenticationToken; - } - - /** - * 注销登录 - */ - public void logout() { - String token = SecurityUtils.getAccessToken(); - if (StrUtil.isNotBlank(token)) { - tokenManager.invalidateToken(token); - // 清除Security上下文 - SecurityContextHolder.clearContext(); - } - } - - /** - * 获取验证码 - */ - public CaptchaInfo getCaptcha() { - return captchaService.generate(); - } - - /** - * 刷新token - * - * @param refreshToken 刷新令牌 - * @return 新的访问令牌 - */ - public AuthenticationToken refreshToken(String refreshToken) { - return tokenManager.refreshToken(refreshToken); - } - -} diff --git a/src/main/java/com/youlai/boot/auth/controller/AuthController.java b/src/main/java/com/youlai/boot/auth/session/controller/AuthSessionController.java similarity index 52% rename from src/main/java/com/youlai/boot/auth/controller/AuthController.java rename to src/main/java/com/youlai/boot/auth/session/controller/AuthSessionController.java index f29a684a..e26b13b0 100644 --- a/src/main/java/com/youlai/boot/auth/controller/AuthController.java +++ b/src/main/java/com/youlai/boot/auth/session/controller/AuthSessionController.java @@ -1,64 +1,40 @@ -package com.youlai.boot.auth.controller; +package com.youlai.boot.auth.session.controller; -import com.youlai.boot.auth.model.req.LoginReq; +import com.youlai.boot.auth.session.service.AuthSessionService; +import com.youlai.boot.common.annotation.Log; import com.youlai.boot.common.enums.ActionTypeEnum; import com.youlai.boot.common.enums.LogModuleEnum; import com.youlai.boot.common.result.Result; -import com.youlai.boot.auth.service.AuthService; -import com.youlai.boot.common.annotation.Log; -import com.youlai.boot.common.annotation.RateLimit; -import com.youlai.boot.auth.model.resp.CaptchaInfo; import com.youlai.boot.framework.security.model.AuthenticationToken; import io.swagger.v3.oas.annotations.Operation; import io.swagger.v3.oas.annotations.Parameter; import io.swagger.v3.oas.annotations.tags.Tag; -import jakarta.validation.Valid; import lombok.RequiredArgsConstructor; -import lombok.extern.slf4j.Slf4j; import org.springframework.web.bind.annotation.DeleteMapping; -import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PostMapping; -import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; /** - * 认证控制层 + * 登录态管理接口 * * @author Ray.Hao - * @since 0.0.1 + * @since 4.8.0 */ @Tag(name = "01.认证中心") @RestController @RequestMapping("/api/v1/auth") @RequiredArgsConstructor -@Slf4j -public class AuthController { +public class AuthSessionController { - private final AuthService authService; - - @Operation(summary = "获取验证码") - @GetMapping("/captcha") - public Result getCaptcha() { - CaptchaInfo captcha = authService.getCaptcha(); - return Result.success(captcha); - } - - @Operation(summary = "账号密码登录") - @PostMapping("/login") - @Log(module = LogModuleEnum.LOGIN, value = ActionTypeEnum.LOGIN) - @RateLimit - public Result login(@RequestBody @Valid LoginReq request) { - AuthenticationToken authenticationToken = authService.login(request.getUsername(), request.getPassword()); - return Result.success(authenticationToken); - } + private final AuthSessionService authSessionService; @Operation(summary = "退出登录") @DeleteMapping("/logout") @Log(module = LogModuleEnum.LOGIN, value = ActionTypeEnum.LOGOUT) public Result logout() { - authService.logout(); + authSessionService.logout(); return Result.success(); } @@ -67,7 +43,7 @@ public class AuthController { public Result refreshToken( @Parameter(description = "刷新令牌", example = "xxx.xxx.xxx") @RequestParam String refreshToken ) { - AuthenticationToken authenticationToken = authService.refreshToken(refreshToken); + AuthenticationToken authenticationToken = authSessionService.refreshToken(refreshToken); return Result.success(authenticationToken); } diff --git a/src/main/java/com/youlai/boot/auth/session/service/AuthSessionService.java b/src/main/java/com/youlai/boot/auth/session/service/AuthSessionService.java new file mode 100644 index 00000000..845da193 --- /dev/null +++ b/src/main/java/com/youlai/boot/auth/session/service/AuthSessionService.java @@ -0,0 +1,45 @@ +package com.youlai.boot.auth.session.service; + +import cn.hutool.core.util.StrUtil; +import com.youlai.boot.framework.security.model.AuthenticationToken; +import com.youlai.boot.framework.security.token.TokenManager; +import com.youlai.boot.framework.security.util.SecurityUtils; +import lombok.RequiredArgsConstructor; +import org.springframework.security.core.context.SecurityContextHolder; +import org.springframework.stereotype.Service; + +/** + * 登录态服务 + * + * @author Ray.Hao + * @since 4.8.0 + */ +@Service +@RequiredArgsConstructor +public class AuthSessionService { + + private final TokenManager tokenManager; + + /** + * 注销登录 + */ + public void logout() { + String token = SecurityUtils.getAccessToken(); + if (StrUtil.isNotBlank(token)) { + tokenManager.invalidateToken(token); + // 清除Security上下文 + SecurityContextHolder.clearContext(); + } + } + + /** + * 刷新令牌 + * + * @param refreshToken 刷新令牌 + * @return 新的访问令牌 + */ + public AuthenticationToken refreshToken(String refreshToken) { + return tokenManager.refreshToken(refreshToken); + } + +} diff --git a/src/main/java/com/youlai/boot/auth/controller/SmsAuthController.java b/src/main/java/com/youlai/boot/auth/sms/controller/SmsAuthController.java similarity index 82% rename from src/main/java/com/youlai/boot/auth/controller/SmsAuthController.java rename to src/main/java/com/youlai/boot/auth/sms/controller/SmsAuthController.java index 8eba7c72..466e2536 100644 --- a/src/main/java/com/youlai/boot/auth/controller/SmsAuthController.java +++ b/src/main/java/com/youlai/boot/auth/sms/controller/SmsAuthController.java @@ -1,17 +1,16 @@ -package com.youlai.boot.auth.controller; +package com.youlai.boot.auth.sms.controller; -import com.youlai.boot.auth.service.AuthService; +import com.youlai.boot.auth.sms.service.SmsAuthService; +import com.youlai.boot.common.annotation.Log; import com.youlai.boot.common.enums.ActionTypeEnum; import com.youlai.boot.common.enums.LogModuleEnum; import com.youlai.boot.common.result.Result; -import com.youlai.boot.common.annotation.Log; -import com.youlai.boot.common.annotation.RateLimit; import com.youlai.boot.framework.security.model.AuthenticationToken; +import com.youlai.boot.framework.web.ratelimit.RateLimit; import io.swagger.v3.oas.annotations.Operation; import io.swagger.v3.oas.annotations.Parameter; import io.swagger.v3.oas.annotations.tags.Tag; import lombok.RequiredArgsConstructor; -import lombok.extern.slf4j.Slf4j; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; @@ -27,10 +26,9 @@ import org.springframework.web.bind.annotation.RestController; @RestController @RequestMapping("/api/v1/auth/sms") @RequiredArgsConstructor -@Slf4j public class SmsAuthController { - private final AuthService authService; + private final SmsAuthService smsAuthService; @Operation(summary = "[短信]发送登录短信验证码") @PostMapping("/code") @@ -38,7 +36,7 @@ public class SmsAuthController { public Result sendCode( @Parameter(description = "手机号", example = "18888888888") @RequestParam String mobile ) { - authService.sendSmsCode(mobile); + smsAuthService.sendSmsCode(mobile); return Result.success(); } @@ -49,7 +47,7 @@ public class SmsAuthController { @Parameter(description = "手机号", example = "18888888888") @RequestParam String mobile, @Parameter(description = "验证码", example = "123456") @RequestParam String code ) { - AuthenticationToken loginResult = authService.loginBySms(mobile, code); + AuthenticationToken loginResult = smsAuthService.loginBySms(mobile, code); return Result.success(loginResult); } diff --git a/src/main/java/com/youlai/boot/auth/exception/SmsCaptchaException.java b/src/main/java/com/youlai/boot/auth/sms/exception/SmsCaptchaException.java similarity index 86% rename from src/main/java/com/youlai/boot/auth/exception/SmsCaptchaException.java rename to src/main/java/com/youlai/boot/auth/sms/exception/SmsCaptchaException.java index a49e50f8..809153de 100644 --- a/src/main/java/com/youlai/boot/auth/exception/SmsCaptchaException.java +++ b/src/main/java/com/youlai/boot/auth/sms/exception/SmsCaptchaException.java @@ -1,4 +1,4 @@ -package com.youlai.boot.auth.exception; +package com.youlai.boot.auth.sms.exception; import org.springframework.security.core.AuthenticationException; diff --git a/src/main/java/com/youlai/boot/auth/security/provider/SmsAuthenticationProvider.java b/src/main/java/com/youlai/boot/auth/sms/provider/SmsAuthenticationProvider.java similarity index 88% rename from src/main/java/com/youlai/boot/auth/security/provider/SmsAuthenticationProvider.java rename to src/main/java/com/youlai/boot/auth/sms/provider/SmsAuthenticationProvider.java index 3423a033..b92853f4 100644 --- a/src/main/java/com/youlai/boot/auth/security/provider/SmsAuthenticationProvider.java +++ b/src/main/java/com/youlai/boot/auth/sms/provider/SmsAuthenticationProvider.java @@ -1,13 +1,13 @@ -package com.youlai.boot.auth.security.provider; +package com.youlai.boot.auth.sms.provider; import cn.hutool.core.util.ObjectUtil; import cn.hutool.core.util.StrUtil; +import com.youlai.boot.auth.sms.exception.SmsCaptchaException; +import com.youlai.boot.auth.sms.token.SmsAuthenticationToken; import com.youlai.boot.common.constant.RedisConstants; import com.youlai.boot.framework.security.model.SecurityUser; import com.youlai.boot.framework.security.model.SecurityUserDetails; import com.youlai.boot.framework.security.port.UserAuthenticationPort; -import com.youlai.boot.auth.exception.SmsCaptchaException; -import com.youlai.boot.auth.security.token.SmsAuthenticationToken; import lombok.extern.slf4j.Slf4j; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.security.authentication.AuthenticationProvider; @@ -18,15 +18,6 @@ import org.springframework.security.core.userdetails.UsernameNotFoundException; /** * 短信验证码认证 Provider - *

- * 认证流程: - *

    - *
  1. 根据手机号查询用户信息
  2. - *
  3. 校验用户状态
  4. - *
  5. 校验短信验证码(与 Redis 缓存比对)
  6. - *
  7. 验证成功后删除验证码
  8. - *
  9. 返回已认证的 Authentication
  10. - *
* * @author Ray.Hao * @since 2.17.0 diff --git a/src/main/java/com/youlai/boot/auth/sms/service/SmsAuthService.java b/src/main/java/com/youlai/boot/auth/sms/service/SmsAuthService.java new file mode 100644 index 00000000..bbbd371b --- /dev/null +++ b/src/main/java/com/youlai/boot/auth/sms/service/SmsAuthService.java @@ -0,0 +1,81 @@ +package com.youlai.boot.auth.sms.service; + +import cn.hutool.core.util.StrUtil; +import com.youlai.boot.auth.sms.token.SmsAuthenticationToken; +import com.youlai.boot.common.constant.RedisConstants; +import com.youlai.boot.framework.security.model.AuthenticationToken; +import com.youlai.boot.framework.security.token.TokenManager; +import com.youlai.boot.support.sms.SmsTypeEnum; +import com.youlai.boot.support.sms.service.SmsService; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.data.redis.core.RedisTemplate; +import org.springframework.security.authentication.AuthenticationManager; +import org.springframework.security.core.Authentication; +import org.springframework.security.core.context.SecurityContextHolder; +import org.springframework.stereotype.Service; + +import java.util.HashMap; +import java.util.Map; +import java.util.concurrent.TimeUnit; + +/** + * 短信验证码登录服务 + * + * @author Ray.Hao + * @since 4.8.0 + */ +@Service +@RequiredArgsConstructor +@Slf4j +public class SmsAuthService { + + private final AuthenticationManager authenticationManager; + private final TokenManager tokenManager; + + private final SmsService smsService; + private final RedisTemplate redisTemplate; + + /** + * 发送登录短信验证码 + * + * @param mobile 手机号 + */ + public void sendSmsCode(String mobile) { + + // TODO 固定验证码 1234 便于测试,接入短信厂商后改为随机生成 + String code = "1234"; + + // 发送短信验证码 + Map templateParams = new HashMap<>(); + templateParams.put("code", code); + try { + smsService.send(mobile, SmsTypeEnum.LOGIN, templateParams); + } catch (Exception e) { + log.error("发送短信验证码失败", e); + } + // 缓存验证码至Redis,用于登录校验 + redisTemplate.opsForValue().set(StrUtil.format(RedisConstants.Captcha.SMS_LOGIN_CODE, mobile), code, 5, TimeUnit.MINUTES); + } + + /** + * 短信验证码登录 + * + * @param mobile 手机号 + * @param code 验证码 + * @return 访问令牌 + */ + public AuthenticationToken loginBySms(String mobile, String code) { + // 1. 创建用户短信验证码认证的令牌(未认证) + SmsAuthenticationToken smsAuthenticationToken = new SmsAuthenticationToken(mobile, code); + + // 2. 执行认证(认证中) + Authentication authentication = authenticationManager.authenticate(smsAuthenticationToken); + + // 3. 认证成功后生成 JWT 令牌,并存入 Security 上下文,供登录日志 AOP 使用(已认证) + AuthenticationToken authenticationToken = tokenManager.generateToken(authentication); + SecurityContextHolder.getContext().setAuthentication(authentication); + return authenticationToken; + } + +} diff --git a/src/main/java/com/youlai/boot/auth/security/token/SmsAuthenticationToken.java b/src/main/java/com/youlai/boot/auth/sms/token/SmsAuthenticationToken.java similarity index 88% rename from src/main/java/com/youlai/boot/auth/security/token/SmsAuthenticationToken.java rename to src/main/java/com/youlai/boot/auth/sms/token/SmsAuthenticationToken.java index e04de05f..84e9d787 100644 --- a/src/main/java/com/youlai/boot/auth/security/token/SmsAuthenticationToken.java +++ b/src/main/java/com/youlai/boot/auth/sms/token/SmsAuthenticationToken.java @@ -1,4 +1,4 @@ -package com.youlai.boot.auth.security.token; +package com.youlai.boot.auth.sms.token; import org.springframework.security.authentication.AbstractAuthenticationToken; import org.springframework.security.core.GrantedAuthority; @@ -9,8 +9,6 @@ import java.util.Collection; /** * 短信验证码认证 Token。 - *

- * 未认证:principal=手机号,credentials=验证码;已认证:principal=SecurityUserDetails,credentials=null。 * * @author Ray.Hao * @since 2.20.0 diff --git a/src/main/java/com/youlai/boot/config/WxMaConfig.java b/src/main/java/com/youlai/boot/auth/wxma/config/WxMaConfig.java similarity index 75% rename from src/main/java/com/youlai/boot/config/WxMaConfig.java rename to src/main/java/com/youlai/boot/auth/wxma/config/WxMaConfig.java index 1093044b..28b80b74 100644 --- a/src/main/java/com/youlai/boot/config/WxMaConfig.java +++ b/src/main/java/com/youlai/boot/auth/wxma/config/WxMaConfig.java @@ -1,10 +1,8 @@ -package com.youlai.boot.config; +package com.youlai.boot.auth.wxma.config; import cn.binarywang.wx.miniapp.api.WxMaService; import cn.binarywang.wx.miniapp.api.impl.WxMaServiceImpl; import cn.binarywang.wx.miniapp.config.impl.WxMaDefaultConfigImpl; -import com.youlai.boot.config.property.WxMaProperties; -import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @@ -12,12 +10,17 @@ import org.springframework.context.annotation.Configuration; * 微信小程序配置 * * @author Ray.Hao - * @since 2024/01/01 + * @since 1.0.0 */ @Configuration -@EnableConfigurationProperties(WxMaProperties.class) public class WxMaConfig { + /** + * 微信小程序客户端,用于调用 jscode2session、手机号解析等接口 + * + * @param properties 小程序 appid 与密钥 + * @return WxMaService + */ @Bean public WxMaService wxMaService(WxMaProperties properties) { WxMaDefaultConfigImpl config = new WxMaDefaultConfigImpl(); diff --git a/src/main/java/com/youlai/boot/config/property/WxMaProperties.java b/src/main/java/com/youlai/boot/auth/wxma/config/WxMaProperties.java similarity index 61% rename from src/main/java/com/youlai/boot/config/property/WxMaProperties.java rename to src/main/java/com/youlai/boot/auth/wxma/config/WxMaProperties.java index d4333c17..88f6fbfa 100644 --- a/src/main/java/com/youlai/boot/config/property/WxMaProperties.java +++ b/src/main/java/com/youlai/boot/auth/wxma/config/WxMaProperties.java @@ -1,16 +1,22 @@ -package com.youlai.boot.config.property; +package com.youlai.boot.auth.wxma.config; import lombok.Data; import org.springframework.boot.context.properties.ConfigurationProperties; +import org.springframework.stereotype.Component; /** * 微信小程序配置属性 + * + * @author Ray.Hao */ @Data +@Component @ConfigurationProperties(prefix = "wx.miniapp") public class WxMaProperties { + // 小程序 appid private String appid; + // 小程序 appsecret private String secret; } diff --git a/src/main/java/com/youlai/boot/auth/controller/WxMaAuthController.java b/src/main/java/com/youlai/boot/auth/wxma/controller/WxMaAuthController.java similarity index 67% rename from src/main/java/com/youlai/boot/auth/controller/WxMaAuthController.java rename to src/main/java/com/youlai/boot/auth/wxma/controller/WxMaAuthController.java index 1cb64564..105ce860 100644 --- a/src/main/java/com/youlai/boot/auth/controller/WxMaAuthController.java +++ b/src/main/java/com/youlai/boot/auth/wxma/controller/WxMaAuthController.java @@ -1,28 +1,26 @@ -package com.youlai.boot.auth.controller; +package com.youlai.boot.auth.wxma.controller; -import com.youlai.boot.auth.model.req.WxMaBindMobileReq; -import com.youlai.boot.auth.model.req.WxMaPhoneLoginReq; -import com.youlai.boot.auth.model.resp.WxMaLoginResp; -import com.youlai.boot.auth.service.WxMaAuthService; +import com.youlai.boot.auth.wxma.model.form.WxMaBindMobileForm; +import com.youlai.boot.auth.wxma.model.form.WxMaPhoneLoginForm; +import com.youlai.boot.auth.wxma.model.vo.WxMaLoginVO; +import com.youlai.boot.auth.wxma.service.WxMaAuthService; import com.youlai.boot.common.annotation.Log; -import com.youlai.boot.common.annotation.RateLimit; import com.youlai.boot.common.enums.ActionTypeEnum; import com.youlai.boot.common.enums.LogModuleEnum; import com.youlai.boot.common.result.Result; import com.youlai.boot.framework.security.model.AuthenticationToken; +import com.youlai.boot.framework.web.ratelimit.RateLimit; import io.swagger.v3.oas.annotations.Operation; import io.swagger.v3.oas.annotations.Parameter; import io.swagger.v3.oas.annotations.tags.Tag; +import jakarta.validation.Valid; import lombok.RequiredArgsConstructor; -import lombok.extern.slf4j.Slf4j; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; -import jakarta.validation.Valid; - /** * 微信小程序认证控制层 * @@ -33,60 +31,36 @@ import jakarta.validation.Valid; @RestController @RequestMapping("/api/v1/auth/wxma") @RequiredArgsConstructor -@Slf4j public class WxMaAuthController { private final WxMaAuthService wxMaAuthService; - /** - * 静默登录 - *

- * 适用场景:个人小程序、无需手机号的登录场景 - *

    - *
  • 已绑定手机号的用户:直接返回 token,登录成功
  • - *
  • 未绑定手机号的用户:返回 openid,需调用绑定手机号接口
  • - *
- */ @Operation(summary = "[小程序]静默登录", description = "通过微信 code 登录,已绑定用户直接返回 token,未绑定用户返回 openid 需绑定手机号") @PostMapping("/silent-login") @Log(module = LogModuleEnum.LOGIN, value = ActionTypeEnum.LOGIN) @RateLimit - public Result silentLogin( + public Result silentLogin( @Parameter(description = "微信登录凭证(wx.login 获取)", required = true, example = "0xxx") @RequestParam String code ) { - WxMaLoginResp result = wxMaAuthService.silentLogin(code); + WxMaLoginVO result = wxMaAuthService.silentLogin(code); return Result.success(result); } - /** - * 手机号快捷登录 - *

- * 适用场景:企业认证小程序(已开通手机号快捷登录权限) - *

- * 一步完成登录,无需绑定流程,自动创建新用户 - */ @Operation(summary = "[小程序]手机号快捷登录", description = "同时使用微信 code 和手机号授权 code 登录,适用于企业认证小程序") @PostMapping("/phone-login") @Log(module = LogModuleEnum.LOGIN, value = ActionTypeEnum.LOGIN) @RateLimit - public Result phoneLogin(@Valid @RequestBody WxMaPhoneLoginReq req) { + public Result phoneLogin(@Valid @RequestBody WxMaPhoneLoginForm req) { AuthenticationToken result = wxMaAuthService.phoneLogin(req.getLoginCode(), req.getPhoneCode()); return Result.success(result); } - /** - * 绑定手机号 - *

- * 适用场景:静默登录后未绑定手机号的用户 - *

- * 绑定成功后自动完成登录 - */ @Operation(summary = "[小程序]绑定手机号", description = "为静默登录用户绑定手机号,绑定成功后自动登录") @PostMapping("/bind-mobile") @Log(module = LogModuleEnum.LOGIN, value = ActionTypeEnum.LOGIN) @RateLimit - public Result bindMobile(@Valid @RequestBody WxMaBindMobileReq req) { + public Result bindMobile(@Valid @RequestBody WxMaBindMobileForm req) { AuthenticationToken result = wxMaAuthService.bindMobile(req.getOpenid(), req.getMobile(), req.getSmsCode()); return Result.success(result); } diff --git a/src/main/java/com/youlai/boot/common/exception/MobileNotBoundException.java b/src/main/java/com/youlai/boot/auth/wxma/exception/MobileNotBoundException.java similarity index 83% rename from src/main/java/com/youlai/boot/common/exception/MobileNotBoundException.java rename to src/main/java/com/youlai/boot/auth/wxma/exception/MobileNotBoundException.java index 48c50ac3..94b60fbe 100644 --- a/src/main/java/com/youlai/boot/common/exception/MobileNotBoundException.java +++ b/src/main/java/com/youlai/boot/auth/wxma/exception/MobileNotBoundException.java @@ -1,11 +1,9 @@ -package com.youlai.boot.common.exception; +package com.youlai.boot.auth.wxma.exception; import org.springframework.security.core.AuthenticationException; /** * 微信小程序登录时手机号未绑定异常。 - *

- * 携带 openid 和 sessionKey 供前端引导用户完成手机号绑定。 * * @author Ray.Hao * @since 3.1.0 @@ -13,6 +11,7 @@ import org.springframework.security.core.AuthenticationException; public class MobileNotBoundException extends AuthenticationException { private final String openid; + private final String sessionKey; public MobileNotBoundException(String openid, String sessionKey) { diff --git a/src/main/java/com/youlai/boot/auth/model/req/WxMaBindMobileReq.java b/src/main/java/com/youlai/boot/auth/wxma/model/form/WxMaBindMobileForm.java similarity index 87% rename from src/main/java/com/youlai/boot/auth/model/req/WxMaBindMobileReq.java rename to src/main/java/com/youlai/boot/auth/wxma/model/form/WxMaBindMobileForm.java index 2dfea5c2..bb7c353f 100644 --- a/src/main/java/com/youlai/boot/auth/model/req/WxMaBindMobileReq.java +++ b/src/main/java/com/youlai/boot/auth/wxma/model/form/WxMaBindMobileForm.java @@ -1,4 +1,4 @@ -package com.youlai.boot.auth.model.req; +package com.youlai.boot.auth.wxma.model.form; import io.swagger.v3.oas.annotations.media.Schema; import jakarta.validation.constraints.NotBlank; @@ -6,10 +6,12 @@ import lombok.Data; /** * 微信小程序绑定手机号请求 + * + * @author Ray.Hao */ @Schema(description = "微信小程序绑定手机号请求") @Data -public class WxMaBindMobileReq { +public class WxMaBindMobileForm { @NotBlank(message = "openid 不能为空") @Schema(description = "微信用户唯一标识", example = "oVBkZ0aYgDMDIywRdgPW8-joxXc4") diff --git a/src/main/java/com/youlai/boot/auth/model/req/WxMaPhoneLoginReq.java b/src/main/java/com/youlai/boot/auth/wxma/model/form/WxMaPhoneLoginForm.java similarity index 85% rename from src/main/java/com/youlai/boot/auth/model/req/WxMaPhoneLoginReq.java rename to src/main/java/com/youlai/boot/auth/wxma/model/form/WxMaPhoneLoginForm.java index 0fa3041b..f8c568dd 100644 --- a/src/main/java/com/youlai/boot/auth/model/req/WxMaPhoneLoginReq.java +++ b/src/main/java/com/youlai/boot/auth/wxma/model/form/WxMaPhoneLoginForm.java @@ -1,4 +1,4 @@ -package com.youlai.boot.auth.model.req; +package com.youlai.boot.auth.wxma.model.form; import io.swagger.v3.oas.annotations.media.Schema; import jakarta.validation.constraints.NotBlank; @@ -6,10 +6,12 @@ import lombok.Data; /** * 微信小程序手机号快捷登录请求 + * + * @author Ray.Hao */ @Schema(description = "微信小程序手机号快捷登录请求") @Data -public class WxMaPhoneLoginReq { +public class WxMaPhoneLoginForm { @NotBlank(message = "微信登录凭证不能为空") @Schema(description = "微信登录凭证(wx.login 获取)", example = "0xxx") diff --git a/src/main/java/com/youlai/boot/auth/model/resp/WxMaLoginResp.java b/src/main/java/com/youlai/boot/auth/wxma/model/vo/WxMaLoginVO.java similarity index 90% rename from src/main/java/com/youlai/boot/auth/model/resp/WxMaLoginResp.java rename to src/main/java/com/youlai/boot/auth/wxma/model/vo/WxMaLoginVO.java index 5e168d8a..62552565 100644 --- a/src/main/java/com/youlai/boot/auth/model/resp/WxMaLoginResp.java +++ b/src/main/java/com/youlai/boot/auth/wxma/model/vo/WxMaLoginVO.java @@ -1,4 +1,4 @@ -package com.youlai.boot.auth.model.resp; +package com.youlai.boot.auth.wxma.model.vo; import io.swagger.v3.oas.annotations.media.Schema; import lombok.AllArgsConstructor; @@ -8,13 +8,15 @@ import lombok.NoArgsConstructor; /** * 微信小程序登录响应 + * + * @author Ray.Hao */ @Data @Builder @NoArgsConstructor @AllArgsConstructor @Schema(description = "微信小程序登录响应") -public class WxMaLoginResp { +public class WxMaLoginVO { @Schema(description = "是否新用户") private Boolean isNewUser; diff --git a/src/main/java/com/youlai/boot/auth/security/provider/WxMaAuthenticationProvider.java b/src/main/java/com/youlai/boot/auth/wxma/provider/WxMaAuthenticationProvider.java similarity index 94% rename from src/main/java/com/youlai/boot/auth/security/provider/WxMaAuthenticationProvider.java rename to src/main/java/com/youlai/boot/auth/wxma/provider/WxMaAuthenticationProvider.java index 7ebfc92c..4f90cc79 100644 --- a/src/main/java/com/youlai/boot/auth/security/provider/WxMaAuthenticationProvider.java +++ b/src/main/java/com/youlai/boot/auth/wxma/provider/WxMaAuthenticationProvider.java @@ -1,14 +1,14 @@ -package com.youlai.boot.auth.security.provider; +package com.youlai.boot.auth.wxma.provider; import cn.binarywang.wx.miniapp.api.WxMaService; import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult; import cn.hutool.core.util.ObjectUtil; +import com.youlai.boot.auth.wxma.exception.MobileNotBoundException; +import com.youlai.boot.auth.wxma.token.WxMaAuthenticationToken; import com.youlai.boot.common.enums.SocialPlatformEnum; import com.youlai.boot.framework.security.model.SecurityUser; import com.youlai.boot.framework.security.model.SecurityUserDetails; import com.youlai.boot.framework.security.port.UserAuthenticationPort; -import com.youlai.boot.common.exception.MobileNotBoundException; -import com.youlai.boot.auth.security.token.WxMaAuthenticationToken; import com.youlai.boot.system.model.entity.UserSocial; import com.youlai.boot.system.service.UserSocialService; import lombok.RequiredArgsConstructor; @@ -22,6 +22,8 @@ import org.springframework.security.core.userdetails.UsernameNotFoundException; /** * 微信小程序认证 Provider + * + * @author Ray.Hao */ @Slf4j @RequiredArgsConstructor diff --git a/src/main/java/com/youlai/boot/auth/service/WxMaAuthService.java b/src/main/java/com/youlai/boot/auth/wxma/service/WxMaAuthService.java similarity index 88% rename from src/main/java/com/youlai/boot/auth/service/WxMaAuthService.java rename to src/main/java/com/youlai/boot/auth/wxma/service/WxMaAuthService.java index aff402bb..b4f2128e 100644 --- a/src/main/java/com/youlai/boot/auth/service/WxMaAuthService.java +++ b/src/main/java/com/youlai/boot/auth/wxma/service/WxMaAuthService.java @@ -1,22 +1,22 @@ -package com.youlai.boot.auth.service; +package com.youlai.boot.auth.wxma.service; import cn.binarywang.wx.miniapp.api.WxMaService; import cn.binarywang.wx.miniapp.bean.WxMaJscode2SessionResult; import cn.binarywang.wx.miniapp.bean.WxMaPhoneNumberInfo; import cn.hutool.core.util.IdUtil; import cn.hutool.core.util.StrUtil; -import com.youlai.boot.auth.model.resp.WxMaLoginResp; +import com.youlai.boot.auth.wxma.exception.MobileNotBoundException; +import com.youlai.boot.auth.wxma.model.vo.WxMaLoginVO; +import com.youlai.boot.auth.wxma.token.WxMaAuthenticationToken; import com.youlai.boot.common.constant.RedisConstants; +import com.youlai.boot.common.enums.SocialPlatformEnum; import com.youlai.boot.framework.security.model.AuthenticationToken; import com.youlai.boot.framework.security.model.SecurityUserDetails; import com.youlai.boot.framework.security.token.TokenManager; -import com.youlai.boot.common.exception.MobileNotBoundException; -import com.youlai.boot.auth.security.token.WxMaAuthenticationToken; -import com.youlai.boot.common.enums.SocialPlatformEnum; import com.youlai.boot.system.model.entity.SysUser; -import com.youlai.boot.system.service.UserSocialService; -import com.youlai.boot.system.service.UserService; import com.youlai.boot.system.service.UserRoleService; +import com.youlai.boot.system.service.UserService; +import com.youlai.boot.system.service.UserSocialService; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.springframework.data.redis.core.RedisTemplate; @@ -51,22 +51,18 @@ public class WxMaAuthService { /** * 静默登录 - *

- * 通过微信登录凭证(code)获取用户唯一标识(openid), - * 如果用户已绑定手机号则直接登录成功,否则返回需绑定手机号的提示。 - *

* * @param code 微信登录凭证(wx.login 获取) * @return 登录结果(成功返回 token,需绑定返回 openid) */ - public WxMaLoginResp silentLogin(String code) { + public WxMaLoginVO silentLogin(String code) { WxMaAuthenticationToken token = new WxMaAuthenticationToken(code); try { Authentication authentication = authenticationManager.authenticate(token); AuthenticationToken authToken = tokenManager.generateToken(authentication); SecurityContextHolder.getContext().setAuthentication(authentication); - return WxMaLoginResp.builder() + return WxMaLoginVO.builder() .isNewUser(false) .needBindMobile(false) .accessToken(authToken.getAccessToken()) @@ -75,7 +71,7 @@ public class WxMaAuthService { .expiresIn(authToken.getExpiresIn()) .build(); } catch (MobileNotBoundException e) { - return WxMaLoginResp.builder() + return WxMaLoginVO.builder() .isNewUser(true) .needBindMobile(true) .openid(e.getOpenid()) @@ -85,10 +81,6 @@ public class WxMaAuthService { /** * 手机号快捷登录 - *

- * 同时使用微信登录凭证和手机号授权凭证, - * 一步完成用户注册/登录,无需额外绑定流程。 - *

* * @param loginCode 微信登录凭证(wx.login 获取) * @param phoneCode 手机号授权凭证(getPhoneNumber 事件获取) @@ -117,14 +109,10 @@ public class WxMaAuthService { /** * 绑定手机号 - *

- * 为已静默登录但未绑定手机号的用户绑定手机号, - * 绑定成功后自动完成登录。 - *

* - * @param openid 微信用户唯一标识 - * @param mobile 手机号码 - * @param smsCode 短信验证码 + * @param openid 微信用户唯一标识 + * @param mobile 手机号码 + * @param smsCode 短信验证码 * @return 认证令牌 */ @Transactional(rollbackFor = Exception.class) @@ -194,9 +182,6 @@ public class WxMaAuthService { /** * 创建新用户 - *

- * 新用户默认分配 GUEST(访问游客)角色 - *

*/ private SysUser createNewUser(String mobile) { SysUser user = new SysUser(); diff --git a/src/main/java/com/youlai/boot/auth/security/token/WxMaAuthenticationToken.java b/src/main/java/com/youlai/boot/auth/wxma/token/WxMaAuthenticationToken.java similarity index 91% rename from src/main/java/com/youlai/boot/auth/security/token/WxMaAuthenticationToken.java rename to src/main/java/com/youlai/boot/auth/wxma/token/WxMaAuthenticationToken.java index 7d21d92c..24014e61 100644 --- a/src/main/java/com/youlai/boot/auth/security/token/WxMaAuthenticationToken.java +++ b/src/main/java/com/youlai/boot/auth/wxma/token/WxMaAuthenticationToken.java @@ -1,4 +1,4 @@ -package com.youlai.boot.auth.security.token; +package com.youlai.boot.auth.wxma.token; import org.springframework.security.authentication.AbstractAuthenticationToken; import org.springframework.security.core.GrantedAuthority; @@ -9,8 +9,6 @@ import java.util.Collection; /** * 微信小程序认证 Token。 - *

- * 未认证:principal=微信code;已认证:principal=SecurityUserDetails。 * * @author Ray.Hao * @since 4.0.0 diff --git a/src/main/java/com/youlai/boot/client/service/impl/ClientClientFileService.java b/src/main/java/com/youlai/boot/client/service/impl/ClientClientFileService.java index e56e44c0..ba9a6e05 100644 --- a/src/main/java/com/youlai/boot/client/service/impl/ClientClientFileService.java +++ b/src/main/java/com/youlai/boot/client/service/impl/ClientClientFileService.java @@ -32,7 +32,7 @@ import java.time.LocalDateTime; @RequiredArgsConstructor public class ClientClientFileService implements ClientFileService { - @Value("${file-storage.local.path}") + @Value("${storage.local.path}") private String storagePath; /** diff --git a/src/main/java/com/youlai/boot/client/service/impl/ClientUserServiceImpl.java b/src/main/java/com/youlai/boot/client/service/impl/ClientUserServiceImpl.java index b62b3c98..4f66929f 100644 --- a/src/main/java/com/youlai/boot/client/service/impl/ClientUserServiceImpl.java +++ b/src/main/java/com/youlai/boot/client/service/impl/ClientUserServiceImpl.java @@ -21,9 +21,9 @@ import com.youlai.boot.framework.security.model.RoleDataScope; import com.youlai.boot.framework.security.model.SecurityUser; import com.youlai.boot.framework.security.token.TokenManager; import com.youlai.boot.framework.security.util.SecurityUtils; -import com.youlai.boot.support.mail.EmailService; -import com.youlai.boot.support.sms.SmsService; +import com.youlai.boot.support.mail.service.EmailService; import com.youlai.boot.support.sms.SmsTypeEnum; +import com.youlai.boot.support.sms.service.SmsService; import com.youlai.boot.system.enums.DictCodeEnum; import com.youlai.boot.system.model.entity.DictItem; import com.youlai.boot.system.model.entity.Role; @@ -91,9 +91,6 @@ public class ClientUserServiceImpl extends ServiceImpl page = new Page<>(pageNum, pageSize); - boolean isRoot = SecurityUtils.isRoot(); - queryParams.setIsRoot(isRoot); - // 查询数据 return this.baseMapper.getUserPage(page, queryParams); } @@ -249,9 +246,6 @@ public class ClientUserServiceImpl extends ServiceImpl listExportUsers(UserQuery queryParams) { - boolean isRoot = SecurityUtils.isRoot(); - queryParams.setIsRoot(isRoot); - List exportUsers = this.baseMapper.listExportUsers(queryParams); if (CollectionUtil.isNotEmpty(exportUsers)) { //获取性别的字典项 diff --git a/src/main/java/com/youlai/boot/codegen/controller/CodegenController.java b/src/main/java/com/youlai/boot/codegen/controller/CodegenController.java index 7e589f1a..77d4433c 100644 --- a/src/main/java/com/youlai/boot/codegen/controller/CodegenController.java +++ b/src/main/java/com/youlai/boot/codegen/controller/CodegenController.java @@ -1,12 +1,14 @@ package com.youlai.boot.codegen.controller; import com.baomidou.mybatisplus.extension.plugins.pagination.Page; +import com.youlai.boot.common.exception.BusinessException; import com.youlai.boot.common.result.PageResult; import com.youlai.boot.common.result.Result; -import com.youlai.boot.codegen.config.CodegenProperties; +import com.youlai.boot.codegen.property.CodegenProperties; import com.youlai.boot.common.enums.ActionTypeEnum; import com.youlai.boot.common.enums.LogModuleEnum; import com.youlai.boot.codegen.service.CodegenService; +import com.youlai.boot.codegen.model.form.AiFillConfigForm; import com.youlai.boot.codegen.model.form.GenConfigForm; import com.youlai.boot.codegen.model.query.TableQuery; import com.youlai.boot.codegen.model.vo.CodegenPreviewVO; @@ -17,6 +19,7 @@ import io.swagger.v3.oas.annotations.Operation; import io.swagger.v3.oas.annotations.Parameter; import io.swagger.v3.oas.annotations.tags.Tag; import jakarta.servlet.ServletOutputStream; +import jakarta.validation.Valid; import jakarta.servlet.http.HttpServletResponse; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; @@ -47,7 +50,7 @@ public class CodegenController { @Operation(summary = "获取数据表分页列表") @GetMapping("/table") public PageResult getTablePage( - TableQuery queryParams + @Valid TableQuery queryParams ) { Page result = codegenService.getTablePage(queryParams); return PageResult.success(result); @@ -65,14 +68,14 @@ public class CodegenController { @Operation(summary = "保存代码生成配置") @PostMapping("/{tableName}/config") @Log(module = LogModuleEnum.CODEGEN, value = ActionTypeEnum.UPDATE) - public Result saveGenConfig(@RequestBody GenConfigForm formData) { + public Result saveGenConfig(@RequestBody @Valid GenConfigForm formData) { genTableService.saveGenConfig(formData); return Result.success(); } @Operation(summary = "删除代码生成配置") @DeleteMapping("/{tableName}/config") - public Result deleteGenConfig( + public Result deleteGenConfig( @Parameter(description = "表名", example = "sys_user") @PathVariable String tableName ) { genTableService.deleteGenConfig(tableName); @@ -106,7 +109,19 @@ public class CodegenController { outputStream.flush(); } catch (IOException e) { log.error("Error while writing the zip file1 to response", e); - throw new RuntimeException("Failed to write the zip file1 to response", e); + throw new BusinessException("代码生成压缩包响应写入失败", e); } } + + // AI 辅助:未开启 AI 时调用返回业务异常 + + @Operation(summary = "AI 填充代码生成配置") + @PostMapping("/{tableName}/ai-config") + public Result fillConfig( + @Parameter(description = "表名", example = "sys_user") @PathVariable String tableName, + @RequestBody(required = false) @Valid AiFillConfigForm form + ) { + String requirement = form == null ? null : form.getRequirement(); + return Result.success(genTableService.aiFillConfig(tableName, requirement)); + } } diff --git a/src/main/java/com/youlai/boot/codegen/enums/JavaTypeEnum.java b/src/main/java/com/youlai/boot/codegen/enums/JavaTypeEnum.java index 0ee49a10..9c167fe2 100644 --- a/src/main/java/com/youlai/boot/codegen/enums/JavaTypeEnum.java +++ b/src/main/java/com/youlai/boot/codegen/enums/JavaTypeEnum.java @@ -93,15 +93,15 @@ public enum JavaTypeEnum { if (columnType == null) { return ""; } - // Handle values like: varchar(255), bigint unsigned, INT + // 处理 varchar(255)、bigint unsigned、INT 等列类型写法 String normalized = columnType.trim().toLowerCase(); int parenIndex = normalized.indexOf('('); if (parenIndex > -1) { normalized = normalized.substring(0, parenIndex); } - // Remove modifiers + // 去除修饰符 normalized = normalized.replace("unsigned", "").replace("zerofill", "").trim(); - // Collapse repeated spaces + // 合并连续空格 normalized = normalized.replaceAll("\\s+", " "); return normalized; } diff --git a/src/main/java/com/youlai/boot/codegen/model/entity/GenTable.java b/src/main/java/com/youlai/boot/codegen/model/entity/GenTable.java index 51f5f289..b1ed8614 100644 --- a/src/main/java/com/youlai/boot/codegen/model/entity/GenTable.java +++ b/src/main/java/com/youlai/boot/codegen/model/entity/GenTable.java @@ -17,49 +17,31 @@ import lombok.Setter; @Setter public class GenTable extends BaseEntity { - /** - * 表名 - */ + // 表名 private String tableName; - /** - * 包名 - */ + // 包名 private String packageName; - /** - * 模块名 - */ + // 模块名 private String moduleName; - /** - * 实体类名 - */ + // 实体类名 private String entityName; - /** - * 业务名 - */ + // 业务名 private String businessName; - /** - * 父菜单ID - */ + // 父菜单ID private Long parentMenuId; - /** - * 作者 - */ + // 作者 private String author; - /** - * 页面类型 classic|curd - */ + // 页面类型 classic|crud private String pageType; - /** - * 要移除的表前缀,如: sys_ - */ + // 要移除的表前缀,如: sys_ private String removeTablePrefix; } diff --git a/src/main/java/com/youlai/boot/codegen/model/entity/GenTableColumn.java b/src/main/java/com/youlai/boot/codegen/model/entity/GenTableColumn.java index a2640747..ff4100c7 100644 --- a/src/main/java/com/youlai/boot/codegen/model/entity/GenTableColumn.java +++ b/src/main/java/com/youlai/boot/codegen/model/entity/GenTableColumn.java @@ -22,86 +22,54 @@ import lombok.Setter; public class GenTableColumn extends BaseEntity { - /** - * 关联的表配置ID - */ + // 关联的表配置ID private Long tableId; - /** - * 列名 - */ + // 列名 private String columnName; - /** - * 列类型 - */ + // 列类型 private String columnType; - /** - * 字段长度 - */ + // 字段长度 private Long maxLength; - /** - * 字段名称 - */ + // 字段名称 private String fieldName; - /** - * 字段排序 - */ + // 字段排序 private Integer fieldSort; - /** - * 字段类型 - */ + // 字段类型 private String fieldType; - /** - * 字段描述 - */ + // 字段描述 private String fieldComment; - /** - * 表单类型 - */ + // 表单类型 private FormTypeEnum formType; - /** - * 查询方式 - */ + // 查询方式 private QueryTypeEnum queryType; - /** - * 是否在列表显示 - */ + // 是否在列表显示 private Integer isShowInList; - /** - * 是否在表单显示 - */ + // 是否在表单显示 private Integer isShowInForm; - /** - * 是否在查询条件显示 - */ + // 是否在查询条件显示 private Integer isShowInQuery; - /** - * 是否必填 - */ + // 是否必填 private Integer isRequired; - /** - * TypeScript类型 - */ + // TypeScript类型 @TableField(exist = false) @JsonIgnore private String tsType; - /** - * 字典类型 - */ + // 字典类型 private String dictType; } diff --git a/src/main/java/com/youlai/boot/codegen/model/form/AiFillConfigForm.java b/src/main/java/com/youlai/boot/codegen/model/form/AiFillConfigForm.java new file mode 100644 index 00000000..b444604b --- /dev/null +++ b/src/main/java/com/youlai/boot/codegen/model/form/AiFillConfigForm.java @@ -0,0 +1,18 @@ +package com.youlai.boot.codegen.model.form; + +import io.swagger.v3.oas.annotations.media.Schema; +import lombok.Data; + +/** + * AI 填充生成配置入参 + * + * @author Ray.Hao + * @since 0.1.0 + */ +@Schema(description = "AI 填充生成配置入参") +@Data +public class AiFillConfigForm { + + @Schema(description = "补充需求描述,可为空", example = "状态字段用下拉框,创建时间不出现在表单") + private String requirement; +} diff --git a/src/main/java/com/youlai/boot/codegen/model/form/GenConfigForm.java b/src/main/java/com/youlai/boot/codegen/model/form/GenConfigForm.java index 5e584e0d..db1ab797 100644 --- a/src/main/java/com/youlai/boot/codegen/model/form/GenConfigForm.java +++ b/src/main/java/com/youlai/boot/codegen/model/form/GenConfigForm.java @@ -3,6 +3,8 @@ package com.youlai.boot.codegen.model.form; import com.youlai.boot.codegen.enums.FormTypeEnum; import com.youlai.boot.codegen.enums.QueryTypeEnum; import io.swagger.v3.oas.annotations.media.Schema; +import jakarta.validation.constraints.NotBlank; +import jakarta.validation.constraints.Pattern; import lombok.Data; import java.util.List; @@ -17,28 +19,36 @@ import java.util.List; @Data public class GenConfigForm { - @Schema(description = "主键",example = "1") + @Schema(description = "主键", example = "1") private Long id; - @Schema(description = "表名",example = "sys_user") + @Schema(description = "表名", example = "sys_user") + @NotBlank(message = "表名不能为空") private String tableName; - @Schema(description = "业务名",example = "用户") + @Schema(description = "业务名", example = "用户") + @NotBlank(message = "业务名不能为空") private String businessName; - @Schema(description = "模块名",example = "system") + @Schema(description = "模块名", example = "system") + @NotBlank(message = "模块名不能为空") + @Pattern(regexp = "[a-zA-Z][a-zA-Z0-9_]*", message = "模块名只能包含字母、数字和下划线,且以字母开头") private String moduleName; - @Schema(description = "包名",example = "com.youlai") + @Schema(description = "包名", example = "com.youlai") + @NotBlank(message = "包名不能为空") + @Pattern(regexp = "([a-zA-Z_][a-zA-Z0-9_]*\\.)*[a-zA-Z_][a-zA-Z0-9_]*", message = "包名格式不正确") private String packageName; - @Schema(description = "实体名",example = "User") + @Schema(description = "实体名", example = "User") + @NotBlank(message = "实体名不能为空") + @Pattern(regexp = "[a-zA-Z][a-zA-Z0-9]*", message = "实体名只能包含字母和数字,且以字母开头") private String entityName; - @Schema(description = "作者",example = "youlaitech") + @Schema(description = "作者", example = "youlaitech") private String author; - @Schema(description = "上级菜单ID",example = "1") + @Schema(description = "上级菜单ID", example = "1") private Long parentMenuId; @Schema(description = "字段配置列表") @@ -50,7 +60,7 @@ public class GenConfigForm { @Schema(description = "前端应用名") private String frontendAppName; - @Schema(description = "页面类型 classic|curd", example = "classic") + @Schema(description = "页面类型 classic|crud", example = "classic") private String pageType; @Schema(description = "要移除的表前缀,如: sys_", example = "sys_") diff --git a/src/main/java/com/youlai/boot/codegen/model/query/TablePageQuery.java b/src/main/java/com/youlai/boot/codegen/model/query/TablePageQuery.java index 51b88c96..119fefbe 100644 --- a/src/main/java/com/youlai/boot/codegen/model/query/TablePageQuery.java +++ b/src/main/java/com/youlai/boot/codegen/model/query/TablePageQuery.java @@ -22,9 +22,7 @@ public class TablePageQuery extends BaseQuery { @Schema(description="关键字(表名)") private String keywords; - /** - * 排除的表名 - */ + // 排除的表名 @JsonIgnore private List excludeTables; diff --git a/src/main/java/com/youlai/boot/codegen/model/query/TableQuery.java b/src/main/java/com/youlai/boot/codegen/model/query/TableQuery.java index 031aa2cc..32c0b2d0 100644 --- a/src/main/java/com/youlai/boot/codegen/model/query/TableQuery.java +++ b/src/main/java/com/youlai/boot/codegen/model/query/TableQuery.java @@ -22,9 +22,7 @@ public class TableQuery extends BaseQuery { @Schema(description="关键字(表名)") private String keywords; - /** - * 排除的表名 - */ + // 排除的表名 @JsonIgnore private List excludeTables; diff --git a/src/main/java/com/youlai/boot/codegen/model/vo/GenConfigAiVO.java b/src/main/java/com/youlai/boot/codegen/model/vo/GenConfigAiVO.java new file mode 100644 index 00000000..afcdfd7f --- /dev/null +++ b/src/main/java/com/youlai/boot/codegen/model/vo/GenConfigAiVO.java @@ -0,0 +1,55 @@ +package com.youlai.boot.codegen.model.vo; + +import lombok.Data; + +import java.util.List; + +/** + * AI 推断的代码生成配置 + * + * @author Ray.Hao + * @since 0.1.0 + */ +@Data +public class GenConfigAiVO { + + // 业务名 + private String businessName; + + // 字段配置列表 + private List fieldConfigs; + + /** + * AI 推断的字段配置 + */ + @Data + public static class FieldAiVO { + + // 列名,须与入参一致 + private String columnName; + + // 字段描述 + private String fieldComment; + + // 表单类型枚举名 + private String formType; + + // 查询类型枚举名 + private String queryType; + + // 是否必填 + private Integer isRequired; + + // 是否在列表显示 + private Integer isShowInList; + + // 是否在表单显示 + private Integer isShowInForm; + + // 是否在查询条件显示 + private Integer isShowInQuery; + + // 字典类型编码 + private String dictType; + } +} diff --git a/src/main/java/com/youlai/boot/codegen/config/CodegenProperties.java b/src/main/java/com/youlai/boot/codegen/property/CodegenProperties.java similarity index 59% rename from src/main/java/com/youlai/boot/codegen/config/CodegenProperties.java rename to src/main/java/com/youlai/boot/codegen/property/CodegenProperties.java index 5f327996..67ae9736 100644 --- a/src/main/java/com/youlai/boot/codegen/config/CodegenProperties.java +++ b/src/main/java/com/youlai/boot/codegen/property/CodegenProperties.java @@ -1,10 +1,9 @@ -package com.youlai.boot.codegen.config; +package com.youlai.boot.codegen.property; import cn.hutool.core.io.file.FileNameUtil; import cn.hutool.core.map.MapUtil; import lombok.Data; import org.springframework.boot.context.properties.ConfigurationProperties; -import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.stereotype.Component; import java.util.List; @@ -17,40 +16,27 @@ import java.util.Map; * @since 2.11.0 */ @Component -@EnableConfigurationProperties(CodegenProperties.class) @ConfigurationProperties(prefix = "codegen") @Data public class CodegenProperties { - /** - * 默认配置 - */ + // 默认配置 private DefaultConfig defaultConfig ; - /** - * 模板配置 - */ + // 模板配置 private Map templateConfigs = MapUtil.newHashMap(true); - /** - * 后端应用名 - */ + // 后端应用名 private String backendAppName; - /** - * 前端应用名 - */ + // 前端应用名 private String frontendAppName; - /** - * 下载文件名 - */ + // 下载文件名 private String downloadFileName; - /** - * 排除数据表 - */ + // 排除数据表 private List excludeTables; /** @@ -59,19 +45,13 @@ public class CodegenProperties { @Data public static class TemplateConfig { - /** - * 模板路径 (e.g. /templates/codegen/controller.java.vm) - */ + // 模板路径,相对模板根 classpath:codegen (e.g. backend/controller.java.vm) private String templatePath; - /** - * 子包名 (e.g. controller/service/mapper/model) - */ + // 子包名 (e.g. controller/service/mapper/model) private String subpackageName; - /** - * 文件扩展名,如 .java - */ + // 文件扩展名,如 .java private String extension = FileNameUtil.EXT_JAVA; } @@ -82,17 +62,13 @@ public class CodegenProperties { @Data public static class DefaultConfig { - /** - * 作者 (e.g. Ray) - */ + // 作者 (e.g. Ray) private String author; - /** - * 默认模块名(e.g. system) - */ + // 默认模块名(e.g. system) private String moduleName; } -} +} \ No newline at end of file diff --git a/src/main/java/com/youlai/boot/codegen/service/GenTableService.java b/src/main/java/com/youlai/boot/codegen/service/GenTableService.java index 44dbaa7c..934f705a 100644 --- a/src/main/java/com/youlai/boot/codegen/service/GenTableService.java +++ b/src/main/java/com/youlai/boot/codegen/service/GenTableService.java @@ -36,4 +36,13 @@ public interface GenTableService extends IService { */ void deleteGenConfig(String tableName); + /** + * 用 AI 推断代码生成配置,未推断出的字段沿用原有默认值 + * + * @param tableName 表名 + * @param requirement 补充需求描述,可为空 + * @return 回填了 AI 推断结果的配置 + */ + GenConfigForm aiFillConfig(String tableName, String requirement); + } diff --git a/src/main/java/com/youlai/boot/codegen/service/impl/CodegenServiceImpl.java b/src/main/java/com/youlai/boot/codegen/service/impl/CodegenServiceImpl.java index cd9a9e1a..37f88c40 100644 --- a/src/main/java/com/youlai/boot/codegen/service/impl/CodegenServiceImpl.java +++ b/src/main/java/com/youlai/boot/codegen/service/impl/CodegenServiceImpl.java @@ -12,7 +12,7 @@ import cn.hutool.extra.template.TemplateUtil; import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; import com.baomidou.mybatisplus.extension.plugins.pagination.Page; import com.youlai.boot.codegen.enums.JavaTypeEnum; -import com.youlai.boot.codegen.config.CodegenProperties; +import com.youlai.boot.codegen.property.CodegenProperties; import com.youlai.boot.codegen.service.GenTableService; import com.youlai.boot.codegen.service.GenTableColumnService; import com.youlai.boot.codegen.service.CodegenService; @@ -38,10 +38,6 @@ import java.util.zip.ZipOutputStream; /** * 代码生成服务实现类。 * - *

- * 根据代码生成配置({@link CodegenProperties})与表/字段元数据,渲染模板并提供预览与下载能力。 - *

- * * @author Ray * @since 2.10.0 */ @@ -85,10 +81,10 @@ public class CodegenServiceImpl implements CodegenService { return templateConfig.getTemplatePath(); } if ("API".equals(templateName)) { - return "codegen/frontend/js/api.js.vm"; + return "frontend/js/api.js.vm"; } if ("VIEW".equals(templateName)) { - return "codegen/frontend/js/index.js.vue.vm"; + return "frontend/js/index.js.vue.vm"; } return templateConfig.getTemplatePath(); } @@ -155,12 +151,8 @@ public class CodegenServiceImpl implements CodegenService { String effectiveTemplatePath = resolveFrontendTemplatePath(templateName, templateConfig, frontendType); String extension = resolveFrontendExtension(templateName, templateConfig, frontendType); - - /* 1. 生成文件名 UserController */ - // User Role Menu Dept + /* 1. 生成文件名 */ String entityName = genTable.getEntityName(); - // Controller Service Mapper Entity - // .java .ts .vue // 文件名 UserController.java String fileName = getFileName(entityName, templateName, extension); @@ -211,8 +203,6 @@ public class CodegenServiceImpl implements CodegenService { /** * 生成文件名。 * - *

部分模板需要使用约定的命名规则(例如前端 API 文件)。

- * * @param entityName 实体名(例如 User) * @param templateName 模板名(例如 Entity、Controller、API) * @param extension 文件后缀(例如 .java、.ts) @@ -352,14 +342,14 @@ public class CodegenServiceImpl implements CodegenService { bindMap.put("hasBigDecimal", hasBigDecimal); bindMap.put("hasRequiredField", hasRequiredField); - TemplateEngine templateEngine = TemplateUtil.createEngine(new TemplateConfig("templates", TemplateConfig.ResourceMode.CLASSPATH)); - // 根据 ui 选择不同的前端页面模板:默认 index.vue.vm;封装版使用 index.curd.vue.vm + TemplateEngine templateEngine = TemplateUtil.createEngine(new TemplateConfig("codegen", TemplateConfig.ResourceMode.CLASSPATH)); + // 根据 ui 选择不同的前端页面模板:默认 index.vue.vm;封装版使用 index.crud.vue.vm String path = templatePath; - if ("curd".equalsIgnoreCase(pageType)) { + if ("crud".equalsIgnoreCase(pageType)) { if (path.endsWith("index.js.vue.vm")) { - path = path.replace("index.js.vue.vm", "index.curd.js.vue.vm"); + path = path.replace("index.js.vue.vm", "index.crud.js.vue.vm"); } else if (path.endsWith("index.vue.vm")) { - path = path.replace("index.vue.vm", "index.curd.vue.vm"); + path = path.replace("index.vue.vm", "index.crud.vue.vm"); } } Template template = templateEngine.getTemplate(path); @@ -389,7 +379,7 @@ public class CodegenServiceImpl implements CodegenService { } catch (IOException e) { log.error("Error while generating zip for code download", e); - throw new RuntimeException("Failed to generate code zip file1", e); + throw new BusinessException("代码生成压缩包失败", e); } } diff --git a/src/main/java/com/youlai/boot/codegen/service/impl/GenTableServiceImpl.java b/src/main/java/com/youlai/boot/codegen/service/impl/GenTableServiceImpl.java index 6df5b3d5..f00a0c04 100644 --- a/src/main/java/com/youlai/boot/codegen/service/impl/GenTableServiceImpl.java +++ b/src/main/java/com/youlai/boot/codegen/service/impl/GenTableServiceImpl.java @@ -3,6 +3,7 @@ package com.youlai.boot.codegen.service.impl; import cn.hutool.core.collection.CollectionUtil; import cn.hutool.core.lang.Assert; import cn.hutool.core.util.StrUtil; +import cn.hutool.json.JSONUtil; import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import com.youlai.boot.YouLaiBootApplication; @@ -11,7 +12,7 @@ import com.youlai.boot.codegen.enums.FormTypeEnum; import com.youlai.boot.codegen.enums.JavaTypeEnum; import com.youlai.boot.codegen.enums.QueryTypeEnum; import com.youlai.boot.common.exception.BusinessException; -import com.youlai.boot.codegen.config.CodegenProperties; +import com.youlai.boot.codegen.property.CodegenProperties; import com.youlai.boot.codegen.converter.CodegenConverter; import com.youlai.boot.codegen.mapper.DatabaseMapper; import com.youlai.boot.codegen.mapper.GenTableMapper; @@ -20,17 +21,26 @@ import com.youlai.boot.codegen.model.vo.TableMetaVO; import com.youlai.boot.codegen.model.entity.GenTable; import com.youlai.boot.codegen.model.entity.GenTableColumn; import com.youlai.boot.codegen.model.form.GenConfigForm; +import com.youlai.boot.codegen.model.vo.GenConfigAiVO; import com.youlai.boot.codegen.service.GenTableService; import com.youlai.boot.codegen.service.GenTableColumnService; +import com.youlai.boot.support.ai.AiChatService; +import com.youlai.boot.support.ai.PromptLoader; +import com.youlai.boot.system.model.dto.MenuCreateDTO; import com.youlai.boot.system.service.MenuService; import lombok.RequiredArgsConstructor; import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Service; import java.util.ArrayList; +import java.util.Arrays; import java.util.Comparator; +import java.util.LinkedHashMap; import java.util.List; +import java.util.Map; import java.util.Objects; +import java.util.function.Function; +import java.util.stream.Collectors; /** * 数据库服务实现类 @@ -42,10 +52,15 @@ import java.util.Objects; @RequiredArgsConstructor public class GenTableServiceImpl extends ServiceImpl implements GenTableService { + // 系统提示词名称,对应 resources/prompts 下的相对路径 + private static final String SYSTEM_PROMPT_PATH = "codegen/system.md"; + private final DatabaseMapper databaseMapper; private final CodegenProperties codegenProperties; private final GenTableColumnService genTableColumnService; private final CodegenConverter codegenConverter; + private final AiChatService aiChatService; + private final PromptLoader promptLoader; @Value("${spring.profiles.active}") private String springProfilesActive; @@ -188,7 +203,13 @@ public class GenTableServiceImpl extends ServiceImpl i // 如果选择上级菜单且当前环境不是生产环境,则保存菜单 Long parentMenuId = formData.getParentMenuId(); if (parentMenuId != null && !EnvEnum.PROD.getValue().equals(springProfilesActive)) { - menuService.addMenuForCodegen(parentMenuId, genTable); + MenuCreateDTO dto = new MenuCreateDTO( + genTable.getBusinessName(), + genTable.getEntityName(), + genTable.getModuleName(), + genTable.getTableName() + ); + menuService.addMenuForCodegen(parentMenuId, dto); } List genTableColumns = codegenConverter.toGenTableColumn(formData.getFieldConfigs()); @@ -222,6 +243,137 @@ public class GenTableServiceImpl extends ServiceImpl i } } + //--------------------------------------------------- + // AI 辅助:未开启 AI 时调用返回业务异常 + //--------------------------------------------------- + /** + * 用 AI 推断代码生成配置 + * + * @param tableName 表名 eg: sys_user + * @param requirement 补充需求描述,可为空 + * @return 回填了 AI 推断结果的配置 + */ + @Override + public GenConfigForm aiFillConfig(String tableName, String requirement) { + GenConfigForm config = getGenTableFormData(tableName); + String systemPrompt = promptLoader.render(SYSTEM_PROMPT_PATH, buildAiPromptVariables()); + GenConfigAiVO aiConfig = aiChatService.chatEntity(systemPrompt, buildAiUserPrompt(config, requirement), GenConfigAiVO.class); + + if (StrUtil.isNotBlank(aiConfig.getBusinessName())) { + config.setBusinessName(aiConfig.getBusinessName().trim()); + } + applyAiFieldConfigs(config, aiConfig.getFieldConfigs()); + return config; + } + + /** + * 构造系统提示词的变量值,表单类型与查询类型清单取自枚举,新增枚举值无需改动提示词 + * + * @return 变量值 + */ + private Map buildAiPromptVariables() { + String formTypes = Arrays.stream(FormTypeEnum.values()) + .map(type -> type.name() + "(" + type.getLabel() + ")") + .collect(Collectors.joining("|")); + String queryTypes = Arrays.stream(QueryTypeEnum.values()) + .map(Enum::name) + .collect(Collectors.joining("|")); + return Map.of("formTypes", formTypes, "queryTypes", queryTypes); + } + + /** + * 按列名匹配回填字段配置 + * + * @param config 原配置 + * @param aiFields AI 返回的字段列表 + */ + private void applyAiFieldConfigs(GenConfigForm config, List aiFields) { + if (CollectionUtil.isEmpty(aiFields) || CollectionUtil.isEmpty(config.getFieldConfigs())) { + return; + } + Map aiFieldMap = aiFields.stream() + .filter(field -> StrUtil.isNotBlank(field.getColumnName())) + .collect(Collectors.toMap(GenConfigAiVO.FieldAiVO::getColumnName, Function.identity(), + (existing, replacement) -> existing, LinkedHashMap::new)); + + config.getFieldConfigs().forEach(field -> { + GenConfigAiVO.FieldAiVO aiField = aiFieldMap.get(field.getColumnName()); + if (aiField == null) { + return; + } + if (StrUtil.isNotBlank(aiField.getFieldComment())) { + field.setFieldComment(aiField.getFieldComment().trim()); + } + if (StrUtil.isNotBlank(aiField.getDictType())) { + field.setDictType(aiField.getDictType().trim()); + } + field.setFormType(parseAiEnum(aiField.getFormType(), FormTypeEnum::valueOf, field.getFormType())); + field.setQueryType(parseAiEnum(aiField.getQueryType(), QueryTypeEnum::valueOf, field.getQueryType())); + field.setIsRequired(resolveAiValue(aiField.getIsRequired(), field.getIsRequired())); + field.setIsShowInList(resolveAiValue(aiField.getIsShowInList(), field.getIsShowInList())); + field.setIsShowInForm(resolveAiValue(aiField.getIsShowInForm(), field.getIsShowInForm())); + field.setIsShowInQuery(resolveAiValue(aiField.getIsShowInQuery(), field.getIsShowInQuery())); + }); + } + + /** + * 解析枚举名,非法或未给出时沿用原值 + * + * @param name 枚举名 + * @param parser 枚举解析器 + * @param fallback 原值 + * @return 枚举或原值 + */ + private T parseAiEnum(String name, Function parser, T fallback) { + if (StrUtil.isBlank(name)) { + return fallback; + } + try { + return parser.apply(name.trim()); + } catch (IllegalArgumentException e) { + return fallback; + } + } + + /** + * AI 值缺失时沿用原值 + * + * @param aiValue AI 值 + * @param fallback 原值 + * @return 生效值 + */ + private T resolveAiValue(T aiValue, T fallback) { + return aiValue != null ? aiValue : fallback; + } + + /** + * 构造用户提示词 + * + * @param config 当前配置 + * @param requirement 补充需求描述 + * @return 用户提示词 + */ + private String buildAiUserPrompt(GenConfigForm config, String requirement) { + List> columns = new ArrayList<>(); + if (CollectionUtil.isNotEmpty(config.getFieldConfigs())) { + config.getFieldConfigs().forEach(field -> { + Map column = new LinkedHashMap<>(); + column.put("columnName", field.getColumnName()); + column.put("columnType", field.getColumnType()); + column.put("fieldComment", field.getFieldComment()); + column.put("isRequired", field.getIsRequired()); + columns.add(column); + }); + } + return """ + 表名:%s + 当前业务名:%s + 补充说明:%s + 字段列表: + %s + """.formatted(config.getTableName(), config.getBusinessName(), + StrUtil.blankToDefault(requirement, "无"), JSONUtil.toJsonStr(columns)); + } } diff --git a/src/main/java/com/youlai/boot/common/annotation/RateLimit.java b/src/main/java/com/youlai/boot/common/annotation/RateLimit.java deleted file mode 100644 index e7e73424..00000000 --- a/src/main/java/com/youlai/boot/common/annotation/RateLimit.java +++ /dev/null @@ -1,30 +0,0 @@ -package com.youlai.boot.common.annotation; - -import java.lang.annotation.*; - -/** - * 接口限流 - *

标注在 Controller 方法上,基于 Redis 滑动窗口实现

- * - * @author Ray.Hao - * @since 4.3.1 - */ -@Target(ElementType.METHOD) -@Retention(RetentionPolicy.RUNTIME) -@Documented -public @interface RateLimit { - - /** - * 窗口内允许的最大请求数。 - *

- * {@code <=0} 时使用全局默认值 {@code rate-limit.default-limit}。 - */ - int limit() default 0; - - /** - * 滑动窗口大小(秒)。 - *

- * {@code <=0} 时使用全局默认值 {@code rate-limit.default-window}。 - */ - int window() default 0; -} diff --git a/src/main/java/com/youlai/boot/common/annotation/RepeatSubmit.java b/src/main/java/com/youlai/boot/common/annotation/RepeatSubmit.java deleted file mode 100644 index 053f1320..00000000 --- a/src/main/java/com/youlai/boot/common/annotation/RepeatSubmit.java +++ /dev/null @@ -1,27 +0,0 @@ -package com.youlai.boot.common.annotation; - - -import java.lang.annotation.*; - -/** - * 防止重复提交注解 - *

- * 该注解用于方法上,防止在指定时间内的重复提交。 默认时间为5秒。 - * - * @author Ray.Hao - * @since 2.3.0 - */ -@Target(ElementType.METHOD) -@Retention(RetentionPolicy.RUNTIME) -@Documented -@Inherited -public @interface RepeatSubmit { - - /** - * 锁过期时间(秒) - *

- * 默认5秒内不允许重复提交 - */ - int expire() default 5; - -} diff --git a/src/main/java/com/youlai/boot/common/aspect/RepeatSubmitAspect.java b/src/main/java/com/youlai/boot/common/aspect/RepeatSubmitAspect.java deleted file mode 100644 index 04722c38..00000000 --- a/src/main/java/com/youlai/boot/common/aspect/RepeatSubmitAspect.java +++ /dev/null @@ -1,99 +0,0 @@ -package com.youlai.boot.common.aspect; - -import cn.hutool.core.util.StrUtil; -import cn.hutool.crypto.digest.DigestUtil; -import cn.hutool.json.JSONUtil; -import com.youlai.boot.common.constant.RedisConstants; -import com.youlai.boot.common.constant.SecurityConstants; -import com.youlai.boot.common.result.ResultCode; -import com.youlai.boot.common.exception.BusinessException; -import com.youlai.boot.common.annotation.RepeatSubmit; -import com.youlai.boot.common.util.IPUtils; -import jakarta.servlet.http.HttpServletRequest; -import lombok.RequiredArgsConstructor; -import lombok.extern.slf4j.Slf4j; -import org.aspectj.lang.ProceedingJoinPoint; -import org.aspectj.lang.annotation.Around; -import org.aspectj.lang.annotation.Aspect; -import org.aspectj.lang.annotation.Pointcut; -import org.redisson.api.RLock; -import org.redisson.api.RedissonClient; -import org.springframework.http.HttpHeaders; -import org.springframework.stereotype.Component; -import org.springframework.web.context.request.RequestContextHolder; -import org.springframework.web.context.request.ServletRequestAttributes; - -import java.util.concurrent.TimeUnit; - -/** - * 防重复提交切面 - * - * @author Ray.Hao - * @since 4.3.1 - */ -@Aspect -@Component -@RequiredArgsConstructor -@Slf4j -public class RepeatSubmitAspect { - - private final RedissonClient redissonClient; - - @Pointcut("@annotation(repeatSubmit)") - public void repeatSubmitPointCut(RepeatSubmit repeatSubmit) { - } - - @Around(value = "repeatSubmitPointCut(repeatSubmit)", argNames = "pjp,repeatSubmit") - public Object handleRepeatSubmit(ProceedingJoinPoint pjp, RepeatSubmit repeatSubmit) throws Throwable { - String lockKey = buildLockKey(pjp); - - int expire = repeatSubmit.expire(); - - // Redis 不可用时 Fail-Open:跳过防重复提交检查,放行请求 - try { - RLock lock = redissonClient.getLock(lockKey); - boolean locked = lock.tryLock(0, expire, TimeUnit.SECONDS); - if (!locked) { - throw new BusinessException(ResultCode.DUPLICATE_SUBMISSION); - } - } catch (BusinessException e) { - throw e; - } catch (Exception e) { - log.warn("防重复提交 Redis 异常,Fail-Open 放行 lockKey={}", lockKey, e); - } - return pjp.proceed(); - } - - /** - * 生成防重复提交锁的 key - *

- * key 由「用户标识 + 接口(method:URI) + 请求体哈希」组成:只有同一用户在同一接口提交 - * 完全相同的请求体才视为重复提交;若仅按 method:URI 生成,同一接口的不同提交 - * (如新增菜单与新增目录)会在窗口内被误判为重复。 - */ - private String buildLockKey(ProceedingJoinPoint pjp) { - HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest(); - String userIdentifier = getUserIdentifier(request); - String requestIdentifier = StrUtil.join(":", request.getMethod(), request.getRequestURI()); - String bodyHash = DigestUtil.sha256Hex(JSONUtil.toJsonStr(pjp.getArgs())); - return StrUtil.format(RedisConstants.Lock.RESUBMIT, userIdentifier, requestIdentifier + ":" + bodyHash); - } - - /** - * 获取用户唯一标识 - * 1. 从请求头中获取 Token,使用 SHA-256 加密 Token 作为用户唯一标识 - * 2. 如果 Token 为空,使用 IP 作为用户唯一标识 - */ - private String getUserIdentifier(HttpServletRequest request) { - String userIdentifier; - String tokenHeader = request.getHeader(HttpHeaders.AUTHORIZATION); - if (StrUtil.isNotBlank(tokenHeader) && tokenHeader.startsWith(SecurityConstants.BEARER_TOKEN_PREFIX)) { - String rawToken = tokenHeader.substring(SecurityConstants.BEARER_TOKEN_PREFIX.length()); - userIdentifier = DigestUtil.sha256Hex(rawToken); - } else { - userIdentifier = IPUtils.getIpAddr(request); - } - return userIdentifier; - } - -} diff --git a/src/main/java/com/youlai/boot/common/base/BaseEntity.java b/src/main/java/com/youlai/boot/common/base/BaseEntity.java index 67f898f6..48c81ace 100644 --- a/src/main/java/com/youlai/boot/common/base/BaseEntity.java +++ b/src/main/java/com/youlai/boot/common/base/BaseEntity.java @@ -14,9 +14,6 @@ import java.time.LocalDateTime; /** * 基础实体类 * - *

包含主键和创建/更新时间,适用于所有实体(含关联表)

- *

审计字段(createBy/updateBy)和逻辑删除字段(isDeleted)由需要的实体自行声明

- * * @author Ray.Hao * @since 4.3.1 */ @@ -26,22 +23,16 @@ public class BaseEntity implements Serializable { @Serial private static final long serialVersionUID = 1L; - /** - * 主键ID - */ + // 主键ID @TableId(type = IdType.AUTO) private Long id; - /** - * 创建时间 - */ + // 创建时间 @TableField(fill = FieldFill.INSERT) @JsonInclude(value = JsonInclude.Include.NON_NULL) private LocalDateTime createTime; - /** - * 更新时间 - */ + // 更新时间 @TableField(fill = FieldFill.INSERT_UPDATE) @JsonInclude(value = JsonInclude.Include.NON_NULL) private LocalDateTime updateTime; diff --git a/src/main/java/com/youlai/boot/common/base/BaseQuery.java b/src/main/java/com/youlai/boot/common/base/BaseQuery.java index 7548937d..697d1c72 100644 --- a/src/main/java/com/youlai/boot/common/base/BaseQuery.java +++ b/src/main/java/com/youlai/boot/common/base/BaseQuery.java @@ -2,6 +2,8 @@ package com.youlai.boot.common.base; import com.youlai.boot.common.annotation.ValidField; 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; @@ -21,16 +23,20 @@ public class BaseQuery implements Serializable { private static final long serialVersionUID = 1L; @Schema(description = "页码", requiredMode = Schema.RequiredMode.NOT_REQUIRED, example = "1") + @Min(value = 1, message = "页码不能小于 1") private Integer pageNum = 1; @Schema(description = "每页记录数", requiredMode = Schema.RequiredMode.NOT_REQUIRED, example = "10") + @Min(value = 1, message = "每页记录数不能小于 1") + @Max(value = 200, message = "每页记录数不能超过 200") private Integer pageSize = 10; @Schema(description = "排序字段", requiredMode = Schema.RequiredMode.NOT_REQUIRED) @ValidField(allowedValues = {"create_time", "update_time"}) private String sortBy; - @Schema(description = "排序方式(正序:ASC;反序:DESC)", requiredMode = Schema.RequiredMode.NOT_REQUIRED) + @Schema(description = "排序方式(正序:asc;反序:desc,不区分大小写)", requiredMode = Schema.RequiredMode.NOT_REQUIRED) + @ValidField(allowedValues = {"asc", "desc", "ASC", "DESC"}) private String order; public boolean isPaged() { diff --git a/src/main/java/com/youlai/boot/common/constant/JwtClaimConstants.java b/src/main/java/com/youlai/boot/common/constant/JwtClaimConstants.java index 45fcf0b5..6e46cacf 100644 --- a/src/main/java/com/youlai/boot/common/constant/JwtClaimConstants.java +++ b/src/main/java/com/youlai/boot/common/constant/JwtClaimConstants.java @@ -2,47 +2,28 @@ package com.youlai.boot.common.constant; /** * JWT Claims声明常量 - *

- * JWT Claims 属于 Payload 的一部分,包含了一些实体(通常指的用户)的状态和额外的元数据。 * * @author haoxr * @since 2023/11/24 */ public interface JwtClaimConstants { - /** - * 令牌类型 - */ + // 令牌类型 String TOKEN_TYPE = "tokenType"; - /** - * 用户ID - */ + // 用户ID String USER_ID = "userId"; - /** - * 部门ID - */ + // 部门ID String DEPT_ID = "deptId"; - /** - * 数据权限列表 - *

- * 存储用户所有角色的数据权限范围,用于实现多角色权限合并(并集策略) - */ + // 数据权限列表 String DATA_SCOPES = "dataScopes"; - /** - * 角色编码集合(不带 ROLE_ 前缀) - */ + // 角色编码集合(不带 ROLE_ 前缀) String ROLES = "roles"; - /** - * Token 版本号 - *

- * 用于用户级会话失效,当用户修改密码、被禁用、强制下线时递增版本号, - * 使该用户之前签发的所有 Token 失效。 - */ + // Token 版本号 String TOKEN_VERSION = "tokenVersion"; /** diff --git a/src/main/java/com/youlai/boot/common/constant/RedisConstants.java b/src/main/java/com/youlai/boot/common/constant/RedisConstants.java index f098d788..e1e5f442 100644 --- a/src/main/java/com/youlai/boot/common/constant/RedisConstants.java +++ b/src/main/java/com/youlai/boot/common/constant/RedisConstants.java @@ -12,10 +12,10 @@ public interface RedisConstants { * 限流相关键 */ interface RateLimit { - /** 接口级限流 Key(示例:rate_limit:api:{user}:{uri}) */ - String API = "rate_limit:{}:{}:{}"; + // 接口级限流 Key(示例:rate_limit:api:{user}:{uri}) + String API = "rate_limit:api:{}:{}"; - /** IP 全局限流 Key(示例:rate_limit:ip:192.168.1.100) */ + // IP 全局限流 Key(示例:rate_limit:ip:192.168.1.100) String IP = "rate_limit:ip:{}"; } @@ -74,4 +74,14 @@ public interface RedisConstants { String ONLINE = "device:online:{}"; } + /** + * 表单模块 + */ + interface Form { + // 已发布表单渲染规则(formKey -> FormRenderVO,发布/停用/改规则/删除时主动失效) + String RENDER_RULE = "form:render:{}"; + // 公开表单匿名提交计数(formKey:ip 维度滑动窗口,防刷限流) + String PUBLIC_SUBMIT_COUNT = "form:public:submit:{}:{}"; + } + } diff --git a/src/main/java/com/youlai/boot/common/constant/SecurityConstants.java b/src/main/java/com/youlai/boot/common/constant/SecurityConstants.java index 3301a297..8082b2f0 100644 --- a/src/main/java/com/youlai/boot/common/constant/SecurityConstants.java +++ b/src/main/java/com/youlai/boot/common/constant/SecurityConstants.java @@ -8,18 +8,12 @@ package com.youlai.boot.common.constant; */ public interface SecurityConstants { - /** - * 登录路径 - */ + // 登录路径 String LOGIN_PATH = "/api/v1/auth/login"; - /** - * JWT Token 前缀 - */ + // JWT Token 前缀 String BEARER_TOKEN_PREFIX = "Bearer "; - /** - * 角色前缀,用于区分 authorities 角色和权限, ROLE_* 角色 、没有前缀的是权限 - */ + // 角色前缀,用于区分 authorities 角色和权限, ROLE_* 角色 、没有前缀的是权限 String ROLE_PREFIX = "ROLE_"; } diff --git a/src/main/java/com/youlai/boot/common/constant/SystemConstants.java b/src/main/java/com/youlai/boot/common/constant/SystemConstants.java index 9933de48..97544d7e 100644 --- a/src/main/java/com/youlai/boot/common/constant/SystemConstants.java +++ b/src/main/java/com/youlai/boot/common/constant/SystemConstants.java @@ -8,19 +8,13 @@ package com.youlai.boot.common.constant; */ public interface SystemConstants { - /** - * 根节点ID - */ + // 根节点ID Long ROOT_NODE_ID = 0L; - /** - * 系统默认密码 - */ + // 系统默认密码 String DEFAULT_PASSWORD = "123456"; - /** - * 超级管理员角色编码 - */ + // 超级管理员角色编码 String ROOT_ROLE_CODE = "ROOT"; } diff --git a/src/main/java/com/youlai/boot/common/enums/DataScopeEnum.java b/src/main/java/com/youlai/boot/common/enums/DataScopeEnum.java index 37a2636a..0f135e19 100644 --- a/src/main/java/com/youlai/boot/common/enums/DataScopeEnum.java +++ b/src/main/java/com/youlai/boot/common/enums/DataScopeEnum.java @@ -5,9 +5,6 @@ import lombok.Getter; /** * 数据权限枚举 - *

- * 多角色数据权限合并策略:取并集(OR),即用户能看到所有角色权限范围内的数据。 - * 如果任一角色是 ALL,则直接跳过数据权限过滤。 * * @author Ray.Hao * @since 2.3.0 @@ -37,8 +34,6 @@ public enum DataScopeEnum implements IBaseEnum { /** * 自定义部门数据 - 可查看指定部门的数据 - *

- * 需要配合 sys_role_dept 表使用,存储角色可访问的部门ID列表 */ CUSTOM(5, "自定义部门数据"); diff --git a/src/main/java/com/youlai/boot/common/enums/LogModuleEnum.java b/src/main/java/com/youlai/boot/common/enums/LogModuleEnum.java index d812d6a9..7f8389c6 100644 --- a/src/main/java/com/youlai/boot/common/enums/LogModuleEnum.java +++ b/src/main/java/com/youlai/boot/common/enums/LogModuleEnum.java @@ -27,6 +27,8 @@ public enum LogModuleEnum implements IBaseEnum { NOTICE(9, "通知公告"), LOG(10, "日志管理"), CODEGEN(11, "代码生成"), + FORM(12, "动态表单"), + WORKFLOW(13, "工作流"), DEVICE(15, "设备SN管理"), MOBILE(16, "移动设备管理"), OTHER(99, "其他"); diff --git a/src/main/java/com/youlai/boot/common/enums/SocialPlatformEnum.java b/src/main/java/com/youlai/boot/common/enums/SocialPlatformEnum.java index 973b57f4..02708922 100644 --- a/src/main/java/com/youlai/boot/common/enums/SocialPlatformEnum.java +++ b/src/main/java/com/youlai/boot/common/enums/SocialPlatformEnum.java @@ -6,8 +6,6 @@ import lombok.Getter; /** * 第三方登录平台类型枚举。 - *

- * value 作为 MyBatis-Plus 枚举值持久化到数据库。 * * @author Ray.Hao * @since 2.17.0 diff --git a/src/main/java/com/youlai/boot/common/exception/DataPermissionException.java b/src/main/java/com/youlai/boot/common/exception/DataPermissionException.java index 1598e2b1..b16b3215 100644 --- a/src/main/java/com/youlai/boot/common/exception/DataPermissionException.java +++ b/src/main/java/com/youlai/boot/common/exception/DataPermissionException.java @@ -4,8 +4,6 @@ import lombok.Getter; /** * 数据权限异常 - *

- * 当数据权限拦截器拼接SQL条件失败时抛出,属于系统级异常,非业务异常。 * * @author zc * @since 2.0.0 diff --git a/src/main/java/com/youlai/boot/common/result/ExcelResult.java b/src/main/java/com/youlai/boot/common/result/ExcelResult.java index d9d6590a..ec858e90 100644 --- a/src/main/java/com/youlai/boot/common/result/ExcelResult.java +++ b/src/main/java/com/youlai/boot/common/result/ExcelResult.java @@ -14,24 +14,16 @@ import java.util.List; @Data public class ExcelResult { - /** - * 响应码,来确定是否导入成功 - */ + // 响应码,来确定是否导入成功 private String code; - /** - * 有效条数 - */ + // 有效条数 private Integer validCount; - /** - * 无效条数 - */ + // 无效条数 private Integer invalidCount; - /** - * 错误提示信息 - */ + // 错误提示信息 private List messageList; public ExcelResult() { diff --git a/src/main/java/com/youlai/boot/common/result/PageResult.java b/src/main/java/com/youlai/boot/common/result/PageResult.java index 72fee0b1..b9df6bf0 100644 --- a/src/main/java/com/youlai/boot/common/result/PageResult.java +++ b/src/main/java/com/youlai/boot/common/result/PageResult.java @@ -24,8 +24,6 @@ public class PageResult implements Serializable { /** * 构建分页结果(MyBatis-Plus {@link IPage})。 - * - *

data 为当前页记录列表;page 提供分页元信息。

*/ public static PageResult success(IPage page) { PageResult result = new PageResult<>(); @@ -46,8 +44,6 @@ public class PageResult implements Serializable { /** * 构建列表结果(无分页)。 - * - *

page 置为 null,用于与分页返回区分。

*/ public static PageResult success(List list) { PageResult result = new PageResult<>(); diff --git a/src/main/java/com/youlai/boot/common/result/ResultCode.java b/src/main/java/com/youlai/boot/common/result/ResultCode.java index 0b5dd569..5341ad53 100644 --- a/src/main/java/com/youlai/boot/common/result/ResultCode.java +++ b/src/main/java/com/youlai/boot/common/result/ResultCode.java @@ -4,48 +4,6 @@ import java.io.Serializable; /** * 响应码枚举 - *

- * 参考《阿里巴巴 Java 开发手册》错误码设计建议: - * 00000 表示成功。 - * A**** 表示用户端错误(如参数错误、认证失败等)。 - * B**** 表示当前系统执行出错(如系统超时等)。 - * C**** 表示调用第三方服务出错(如中间件、数据库等外部依赖)。 - *

- * 错误码位数与号段说明: - * - 错误码为字符串类型,共 5 位:错误产生来源(A/B/C) + 四位数字编号。 - * - 四位数字编号范围 0001~9999,大类之间建议按步长 100 预留号段(如 A0200、A0300、A0400)。 - * - 错误码后三位编号与 HTTP 状态码无关。 - *

- * 说明: - * - 本项目仅保留实际使用的错误码,并在 A/B/C 各保留少量示例,避免枚举无限膨胀。 - * - 如需扩展业务错误码,建议在对应宏观分类下按场景划分号段并保持全局唯一。 - *

- * 附表(节选):错误码列表(示例/项目使用项) - *

- * | 错误码 | 中文描述             | 说明             |
- * |-------|----------------------|------------------|
- * | 00000 | 成功                 | 正常执行后的返回 |
- * | A0001 | 用户端错误           | 一级宏观错误码   |
- * | A0100 | 用户注册错误         | 二级宏观错误码   |
- * | A0101 | 用户未同意隐私协议   | 二级宏观错误码   |
- * | A0200 | 用户登录异常         | 二级宏观错误码   |
- * | A0201 | 用户账户不存在       | 二级宏观错误码   |
- * | A0202 | 用户账户被冻结       | 二级宏观错误码   |
- * | A0230 | 访问令牌无效或已过期 | 令牌校验失败     |
- * | A0241 | 用户验证码尝试次数超限 | 二级宏观错误码   |
- * | A0300 | 访问权限异常         | 二级宏观错误码   |
- * | A0301 | 访问未授权           | 二级宏观错误码   |
- * | A0400 | 用户请求参数错误     | 二级宏观错误码   |
- * | A0410 | 请求必填参数为空     | 二级宏观错误码   |
- * | A0500 | 用户请求服务异常     | 二级宏观错误码   |
- * | A0502 | 请求并发数超出限制   | 二级宏观错误码   |
- * | A0506 | 请勿重复提交         | 二级宏观错误码   |
- * | B0001 | 系统执行出错         | 一级宏观错误码   |
- * | B0100 | 系统执行超时         | 二级宏观错误码   |
- * | C0001 | 调用第三方服务出错   | 一级宏观错误码   |
- * | C0113 | 接口不存在           | 二级宏观错误码   |
- * | C0300 | 数据库服务出错       | 二级宏观错误码   |
- * 
* * @author Ray.Hao * @since 4.3.1 diff --git a/src/main/java/com/youlai/boot/config/JacksonConfig.java b/src/main/java/com/youlai/boot/config/JacksonConfig.java index 7384c892..638e8aa6 100644 --- a/src/main/java/com/youlai/boot/config/JacksonConfig.java +++ b/src/main/java/com/youlai/boot/config/JacksonConfig.java @@ -15,11 +15,6 @@ import java.util.TimeZone; /** * Jackson 全局序列化配置 * - *

本项目的统一序列化策略: - *
- 统一时区 GMT+8 统一日期格式 yyyy-MM-dd HH:mm:ss - *
- Long/BigInteger 序列化为字符串,避免前端精度丢失 - *
- 禁用 WRITE_DATES_AS_TIMESTAMPS,避免日期输出为时间戳

- * * @author Ray.Hao * @since 2026/1/12 */ @@ -28,9 +23,6 @@ public class JacksonConfig { /** * 全局 JsonMapper - * - *

由 Spring Boot 自动装配到 Jackson 相关的 HttpMessageConverter 中,作为全局 JSON 序列化/反序列化 - * 行为的唯一入口。

*/ @Bean public JsonMapper objectMapper() { diff --git a/src/main/java/com/youlai/boot/config/OpenApiConfig.java b/src/main/java/com/youlai/boot/config/OpenApiConfig.java index 3fdcb10a..2fb197e6 100644 --- a/src/main/java/com/youlai/boot/config/OpenApiConfig.java +++ b/src/main/java/com/youlai/boot/config/OpenApiConfig.java @@ -1,7 +1,7 @@ package com.youlai.boot.config; import cn.hutool.core.util.ArrayUtil; -import com.youlai.boot.config.property.SecurityProperties; +import com.youlai.boot.framework.security.config.SecurityProperties; import io.swagger.v3.oas.models.Components; import io.swagger.v3.oas.models.OpenAPI; import io.swagger.v3.oas.models.info.Contact; @@ -78,12 +78,12 @@ public class OpenApiConfig { if (openApi.getPaths() != null) { openApi.getPaths().forEach((path, pathItem) -> { - // 忽略认证的请求无需携带 Authorization - String[] ignoreUrls = securityProperties.getIgnoreUrls(); - if (ArrayUtil.isNotEmpty(ignoreUrls)) { - // Ant 匹配忽略的路径,不添加Authorization + // 匿名放行的请求无需携带 Authorization + String[] permitAllUrls = securityProperties.getPermitAllUrls(); + if (ArrayUtil.isNotEmpty(permitAllUrls)) { + // Ant 匹配放行路径,不添加Authorization AntPathMatcher antPathMatcher = new AntPathMatcher(); - if (Stream.of(ignoreUrls).anyMatch(ignoreUrl -> antPathMatcher.match(ignoreUrl, path))) { + if (Stream.of(permitAllUrls).anyMatch(permitAllUrl -> antPathMatcher.match(permitAllUrl, path))) { return; } } diff --git a/src/main/java/com/youlai/boot/config/RedisCacheConfig.java b/src/main/java/com/youlai/boot/config/RedisCacheConfig.java index 9be08f3c..bd8883d9 100644 --- a/src/main/java/com/youlai/boot/config/RedisCacheConfig.java +++ b/src/main/java/com/youlai/boot/config/RedisCacheConfig.java @@ -22,13 +22,11 @@ import org.springframework.data.redis.serializer.RedisSerializer; @EnableCaching @EnableConfigurationProperties(CacheProperties.class) @Configuration -@ConditionalOnProperty(name = "spring.cache.enabled") // xxl.job.enabled = true 才会自动装配 +@ConditionalOnProperty(name = "spring.cache.enabled") // 未配置视为关闭 public class RedisCacheConfig { /** * 自定义 RedisCacheManager - *

- * 修改 Redis 序列化方式,默认 JdkSerializationRedisSerializer * * @param redisConnectionFactory {@link RedisConnectionFactory} * @param cacheProperties {@link CacheProperties} diff --git a/src/main/java/com/youlai/boot/config/SecurityConfig.java b/src/main/java/com/youlai/boot/config/SecurityConfig.java index a1c86078..4456f63b 100644 --- a/src/main/java/com/youlai/boot/config/SecurityConfig.java +++ b/src/main/java/com/youlai/boot/config/SecurityConfig.java @@ -2,21 +2,21 @@ package com.youlai.boot.config; import cn.binarywang.wx.miniapp.api.WxMaService; import cn.hutool.core.util.ArrayUtil; -import com.youlai.boot.framework.security.filter.MobileApiSignatureFilter; -import com.youlai.boot.auth.service.CaptchaService; -import com.youlai.boot.config.property.SecurityProperties; +import com.youlai.boot.auth.password.service.CaptchaService; import com.youlai.boot.device.service.DeviceService; import com.youlai.boot.framework.security.authorization.ClientAccessAuthorizationManager; +import com.youlai.boot.framework.security.config.SecurityProperties; +import com.youlai.boot.framework.security.filter.MobileApiSignatureFilter; import com.youlai.boot.framework.security.filter.TokenAuthenticationFilter; +import com.youlai.boot.framework.security.handler.JsonAccessDeniedHandler; +import com.youlai.boot.framework.security.handler.JsonAuthenticationEntryPoint; import com.youlai.boot.framework.security.port.UserAuthenticationPort; import com.youlai.boot.framework.security.service.SecurityUserDetailsService; import com.youlai.boot.framework.security.signature.DeviceSignatureVerifier; import com.youlai.boot.framework.security.token.TokenManager; -import com.youlai.boot.auth.security.filter.CaptchaValidationFilter; -import com.youlai.boot.auth.security.handler.JsonAccessDeniedHandler; -import com.youlai.boot.auth.security.handler.JsonAuthenticationEntryPoint; -import com.youlai.boot.auth.security.provider.SmsAuthenticationProvider; -import com.youlai.boot.auth.security.provider.WxMaAuthenticationProvider; +import com.youlai.boot.auth.password.filter.CaptchaValidationFilter; +import com.youlai.boot.auth.sms.provider.SmsAuthenticationProvider; +import com.youlai.boot.auth.wxma.provider.WxMaAuthenticationProvider; import com.youlai.boot.system.service.UserSocialService; import lombok.RequiredArgsConstructor; import org.springframework.context.annotation.Bean; @@ -28,7 +28,6 @@ import org.springframework.security.authentication.dao.DaoAuthenticationProvider import org.springframework.security.config.annotation.method.configuration.EnableMethodSecurity; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; -import org.springframework.security.config.annotation.web.configuration.WebSecurityCustomizer; import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer; import org.springframework.security.config.annotation.web.configurers.HeadersConfigurer; import org.springframework.security.config.http.SessionCreationPolicy; @@ -40,10 +39,7 @@ import org.springframework.security.web.access.intercept.AuthorizationFilter; import jakarta.servlet.DispatcherType; /** - * Spring Security 配置类。 - *

- * 归使用方(auth 模块),安全规则(放行路径、CORS、Provider 装配、响应格式) - * 因项目而异,不应由框架层强制装配。 + * Spring Security 配置类 * * @author Ray.Hao * @since 4.3.1 @@ -69,9 +65,9 @@ public class SecurityConfig { .authorizeHttpRequests(requestMatcherRegistry -> { // ASYNC 分发(SSE 超时/完成后的异步 dispatch)无 Authorization 头,直接放行 requestMatcherRegistry.dispatcherTypeMatchers(DispatcherType.ASYNC).permitAll(); - String[] ignoreUrls = securityProperties.getIgnoreUrls(); - if (ArrayUtil.isNotEmpty(ignoreUrls)) { - requestMatcherRegistry.requestMatchers(ignoreUrls).permitAll(); + String[] permitAllUrls = securityProperties.getPermitAllUrls(); + if (ArrayUtil.isNotEmpty(permitAllUrls)) { + requestMatcherRegistry.requestMatchers(permitAllUrls).permitAll(); } // 移动设备专用接口路径(需要设备签名验证,但不需要用户登录) @@ -109,16 +105,6 @@ public class SecurityConfig { .build(); } - @Bean - public WebSecurityCustomizer webSecurityCustomizer() { - return (web) -> { - String[] unsecuredUrls = securityProperties.getUnsecuredUrls(); - if (ArrayUtil.isNotEmpty(unsecuredUrls)) { - web.ignoring().requestMatchers(unsecuredUrls); - } - }; - } - @Bean public DaoAuthenticationProvider daoAuthenticationProvider() { DaoAuthenticationProvider provider = new DaoAuthenticationProvider(userDetailsService); diff --git a/src/main/java/com/youlai/boot/config/XxlJobConfig.java b/src/main/java/com/youlai/boot/config/XxlJobConfig.java index 0852a6cc..909b677d 100644 --- a/src/main/java/com/youlai/boot/config/XxlJobConfig.java +++ b/src/main/java/com/youlai/boot/config/XxlJobConfig.java @@ -8,7 +8,6 @@ import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; /** - * xxl-job config * * @author xuxueli 2017-04-28 */ diff --git a/src/main/java/com/youlai/boot/config/property/RateLimitProperties.java b/src/main/java/com/youlai/boot/config/property/RateLimitProperties.java deleted file mode 100644 index 72d03b26..00000000 --- a/src/main/java/com/youlai/boot/config/property/RateLimitProperties.java +++ /dev/null @@ -1,57 +0,0 @@ -package com.youlai.boot.config.property; - -import lombok.Data; -import org.springframework.boot.context.properties.ConfigurationProperties; -import org.springframework.stereotype.Component; - -import java.time.Duration; - -/** - * 限流配置 - *

对应 application.yml 中的 {@code rate-limit} 配置节点。

- * - * @author Ray.Hao - * @since 4.3.1 - */ -@Data -@Component -@ConfigurationProperties(prefix = "rate-limit") -public class RateLimitProperties { - - /** - * @RateLimit 注解未显式指定 limit 时的默认阈值(窗口内最大请求数) - */ - private int defaultLimit = 5; - - /** - * @RateLimit 注解未显式指定 window 时的默认窗口大小,支持 60s / 1m / 500ms 等 Duration 写法 - */ - private Duration defaultWindow = Duration.ofSeconds(60); - - /** - * IP 全局限流配置 - */ - private Ip ip = new Ip(); - - @Data - public static class Ip { - - /** - * 是否启用 IP 全局限流。 - * 建议生产环境开启,开发/测试环境酌情关闭。 - */ - private boolean enabled = true; - - /** - * 窗口内最大请求数(默认 1000) - */ - private int limit = 1000; - - /** - * 滑动窗口大小,支持 60s / 1m / 500ms 等 Duration 写法(默认 60s) - */ - private Duration window = Duration.ofSeconds(60); - - } - -} diff --git a/src/main/java/com/youlai/boot/config/property/SecurityProperties.java b/src/main/java/com/youlai/boot/config/property/SecurityProperties.java deleted file mode 100644 index e52e0888..00000000 --- a/src/main/java/com/youlai/boot/config/property/SecurityProperties.java +++ /dev/null @@ -1,130 +0,0 @@ -package com.youlai.boot.config.property; - -import jakarta.validation.constraints.Min; -import jakarta.validation.constraints.NotEmpty; -import jakarta.validation.constraints.NotNull; -import jakarta.validation.constraints.Pattern; -import lombok.Data; -import org.springframework.boot.context.properties.ConfigurationProperties; -import org.springframework.stereotype.Component; -import org.springframework.validation.annotation.Validated; - -/** - * 安全模块配置属性类 - * - *

映射 application.yml 中 security 前缀的安全相关配置

- * - * @author Ray.Hao - * @since 2024/4/18 - */ -@Data -@Component -@Validated -@ConfigurationProperties(prefix = "security") -public class SecurityProperties { - - /** - * 会话管理配置 - */ - private SessionConfig session; - - /** - * 安全白名单路径(完全绕过安全过滤器) - *

示例值:/api/v1/auth/login/**, /ws/** - */ - @NotEmpty - private String[] ignoreUrls; - - /** - * 非安全端点路径(允许匿名访问的API) - *

示例值:/doc.html, /v3/api-docs/** - */ - @NotEmpty - private String[] unsecuredUrls; - - /** - * 会话配置嵌套类 - */ - @Data - public static class SessionConfig { - /** - * 认证策略类型 - *

    - *
  • jwt - 基于JWT的无状态认证
  • - *
  • redis-token - 基于Redis的有状态认证
  • - *
- */ - @NotNull(message = "会话类型不能为空") - @Pattern(regexp = "jwt|redis-token", message = "会话类型只能是 jwt 或 redis-token") - private String type; - - /** - * 访问令牌有效期(单位:秒) - *

默认值:3600(1小时)

- *

-1 表示永不过期

- */ - @Min(-1) - private Integer accessTokenTimeToLive = 3600; - - /** - * 刷新令牌有效期(单位:秒) - *

默认值:604800(7天)

- *

-1 表示永不过期

- */ - @Min(-1) - private Integer refreshTokenTimeToLive = 604800; - - /** - * 家属客户端访问令牌有效期(单位:秒) - *

为 client 端单独配置,与管理后台(sys_user)区分;未配置时回退到 {@link #accessTokenTimeToLive}。

- *

-1 表示永不过期

- */ - @Min(-1) - private Integer clientAccessTokenTimeToLive = -1; - - /** - * 家属客户端刷新令牌有效期(单位:秒) - *

为 client 端单独配置,与管理后台(sys_user)区分;未配置时回退到 {@link #refreshTokenTimeToLive}。

- *

-1 表示永不过期

- */ - @Min(-1) - private Integer clientRefreshTokenTimeToLive = -1; - - /** - * JWT 配置项 - */ - private JwtConfig jwt; - - /** - * Redis令牌配置项 - */ - private RedisTokenConfig redisToken; - } - - /** - * JWT 配置嵌套类 - */ - @Data - public static class JwtConfig { - /** - * JWT签名密钥 - *

HS256算法要求至少32个字符

- *

示例:SecretKey012345678901234567890123456789

- */ - @NotNull - private String secretKey; - } - - /** - * Redis令牌配置嵌套类 - */ - @Data - public static class RedisTokenConfig { - /** - * 是否允许多设备同时登录 - *

true - 允许同一账户多设备登录(默认)

- *

false - 新登录会使旧令牌失效

- */ - private Boolean allowMultiLogin = true; - } -} diff --git a/src/main/java/com/youlai/boot/framework/mybatis/MetaFieldFillHandler.java b/src/main/java/com/youlai/boot/framework/mybatis/MetaFieldFillHandler.java index cc8fe5c5..20bf973e 100644 --- a/src/main/java/com/youlai/boot/framework/mybatis/MetaFieldFillHandler.java +++ b/src/main/java/com/youlai/boot/framework/mybatis/MetaFieldFillHandler.java @@ -10,9 +10,6 @@ import java.time.LocalDateTime; /** * MyBatis-Plus 字段自动填充 * - *

自动填充 createTime/updateTime(时间戳)和 createBy/updateBy(操作人ID)

- *

实体字段需标注 {@code @TableField(fill = FieldFill.INSERT)} 或 {@code FieldFill.INSERT_UPDATE} 才会触发

- * * @author Ray.Hao * @since 3.0.0 */ diff --git a/src/main/java/com/youlai/boot/framework/mybatis/MyDataPermissionHandler.java b/src/main/java/com/youlai/boot/framework/mybatis/MyDataPermissionHandler.java index 38ac05db..14dc08d6 100644 --- a/src/main/java/com/youlai/boot/framework/mybatis/MyDataPermissionHandler.java +++ b/src/main/java/com/youlai/boot/framework/mybatis/MyDataPermissionHandler.java @@ -24,12 +24,6 @@ import java.util.List; /** * 数据权限处理器 - *

- * 支持多角色数据权限合并(并集策略): - * - 如果任一角色是 ALL,则跳过数据权限过滤 - * - 否则用 OR 连接各角色的数据权限条件 - *

- * 使用 JSQLParser 构建 SQL 条件,避免字符串拼接,提高代码安全性和可读性。 * * @author Ray.Hao * @since 2021/12/10 @@ -108,8 +102,6 @@ public class MyDataPermissionHandler implements DataPermissionHandler { /** * 使用并集策略进行数据权限过滤 - *

- * 多个角色的数据权限通过 OR 连接,实现并集效果 * * @param annotation 数据权限注解 * @param dataScopes 数据权限列表 @@ -158,8 +150,6 @@ public class MyDataPermissionHandler implements DataPermissionHandler { /** * 构建单个角色的数据权限SQL条件 - *

- * 使用 JSQLParser 构建 Expression,避免字符串拼接 * * @param deptAlias 部门表别名 * @param deptIdColumnName 部门ID字段名 @@ -221,8 +211,6 @@ public class MyDataPermissionHandler implements DataPermissionHandler { /** * 构建部门及子部门数据权限条件 - *

- * SQL: dept_id IN (SELECT id FROM sys_dept WHERE id = ? OR FIND_IN_SET(?, tree_path)) * * @param deptColumn 部门列 * @param deptId 部门ID @@ -230,8 +218,7 @@ public class MyDataPermissionHandler implements DataPermissionHandler { */ @SneakyThrows private Expression buildDeptAndSubExpression(Column deptColumn, Long deptId) { - // 使用字符串解析,避免不同 JSqlParser 版本下 InExpression/ItemsList 渲染差异导致 SQL 语法错误 - // SQL: dept_id IN (SELECT id FROM sys_dept WHERE id = ? OR FIND_IN_SET(?, tree_path)) + // 直接拼 SQL 字符串解析,规避 JSqlParser 版本间表达式渲染差异 String columnName = deptColumn.toString(); String sql = columnName + " IN (SELECT " + DEPT_ID_COLUMN + " FROM " + DEPT_TABLE + " WHERE " + DEPT_ID_COLUMN + " = " + deptId + @@ -241,8 +228,6 @@ public class MyDataPermissionHandler implements DataPermissionHandler { /** * 构建自定义部门数据权限条件 - *

- * SQL: dept_id IN (?, ?, ...) * * @param deptColumn 部门列 * @param customDeptIds 自定义部门ID列表 diff --git a/src/main/java/com/youlai/boot/config/PasswordEncoderConfig.java b/src/main/java/com/youlai/boot/framework/security/config/PasswordEncoderConfig.java similarity index 91% rename from src/main/java/com/youlai/boot/config/PasswordEncoderConfig.java rename to src/main/java/com/youlai/boot/framework/security/config/PasswordEncoderConfig.java index 3e6e0e0b..6ee0f46d 100644 --- a/src/main/java/com/youlai/boot/config/PasswordEncoderConfig.java +++ b/src/main/java/com/youlai/boot/framework/security/config/PasswordEncoderConfig.java @@ -1,4 +1,4 @@ -package com.youlai.boot.config; +package com.youlai.boot.framework.security.config; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; diff --git a/src/main/java/com/youlai/boot/framework/security/config/SecurityProperties.java b/src/main/java/com/youlai/boot/framework/security/config/SecurityProperties.java new file mode 100644 index 00000000..552c1689 --- /dev/null +++ b/src/main/java/com/youlai/boot/framework/security/config/SecurityProperties.java @@ -0,0 +1,87 @@ +package com.youlai.boot.framework.security.config; + +import jakarta.validation.Valid; +import jakarta.validation.constraints.Min; +import jakarta.validation.constraints.NotEmpty; +import jakarta.validation.constraints.NotNull; +import jakarta.validation.constraints.Pattern; +import lombok.Data; +import org.springframework.boot.context.properties.ConfigurationProperties; +import org.springframework.validation.annotation.Validated; +import org.springframework.stereotype.Component; + +/** + * 安全模块配置属性类 + * + * @author Ray.Hao + * @since 2024/4/18 + */ +@Data +@Validated +@Component +@ConfigurationProperties(prefix = "security") +public class SecurityProperties { + + // 令牌策略配置 + @Valid + @NotNull(message = "令牌策略配置不能为空") + private TokenConfig token; + + // 匿名放行路径(仍经过安全过滤器链,仅跳过认证与授权判断,保留安全响应头) + @NotEmpty + private String[] permitAllUrls; + + /** + * 令牌策略嵌套类 + */ + @Data + public static class TokenConfig { + // 令牌策略类型 + @NotNull(message = "令牌类型不能为空") + @Pattern(regexp = "jwt|redis-token", message = "令牌类型只能是 jwt 或 redis-token") + private String type; + + // 访问令牌有效期(单位:秒) + @Min(-1) + private Integer accessTokenTimeToLive = 3600; + + // 刷新令牌有效期(单位:秒) + @Min(-1) + private Integer refreshTokenTimeToLive = 604800; + + // 家属客户端访问令牌有效期(单位:秒),未配置时回退到 accessTokenTimeToLive + @Min(-1) + private Integer clientAccessTokenTimeToLive = -1; + + // 家属客户端刷新令牌有效期(单位:秒),未配置时回退到 refreshTokenTimeToLive + @Min(-1) + private Integer clientRefreshTokenTimeToLive = -1; + + // JWT 配置项(type 为 jwt 时必填) + @Valid + private JwtConfig jwt; + + // Redis令牌配置项(type 为 redis-token 时使用) + @Valid + private RedisTokenConfig redisToken; + } + + /** + * JWT 配置嵌套类 + */ + @Data + public static class JwtConfig { + // JWT签名密钥 + @NotNull(message = "JWT 密钥不能为空") + private String secretKey; + } + + /** + * Redis令牌配置嵌套类 + */ + @Data + public static class RedisTokenConfig { + // 是否允许多设备同时登录 + private Boolean allowMultiLogin = true; + } +} diff --git a/src/main/java/com/youlai/boot/framework/security/filter/TokenAuthenticationFilter.java b/src/main/java/com/youlai/boot/framework/security/filter/TokenAuthenticationFilter.java index c4298f35..ef134da1 100644 --- a/src/main/java/com/youlai/boot/framework/security/filter/TokenAuthenticationFilter.java +++ b/src/main/java/com/youlai/boot/framework/security/filter/TokenAuthenticationFilter.java @@ -18,13 +18,6 @@ import java.io.IOException; /** * Token 认证过滤器。 - *

- * 仅负责解析 Token 和填充 {@link SecurityContextHolder}。 - * 无效 Token 抛出 {@link AuthenticationException},由使用方的 - * {@code AuthenticationEntryPoint} 统一处理响应格式。 - *

- * 必须注册在 {@code ExceptionTranslationFilter} 之后(即 {@code AuthorizationFilter} 之前), - * 这样抛出的异常才能被 {@code ExceptionTranslationFilter} 捕获。 * * @author wangtao * @since 2025/3/6 diff --git a/src/main/java/com/youlai/boot/auth/security/handler/JsonAccessDeniedHandler.java b/src/main/java/com/youlai/boot/framework/security/handler/JsonAccessDeniedHandler.java similarity index 83% rename from src/main/java/com/youlai/boot/auth/security/handler/JsonAccessDeniedHandler.java rename to src/main/java/com/youlai/boot/framework/security/handler/JsonAccessDeniedHandler.java index 3124829f..b80fe234 100644 --- a/src/main/java/com/youlai/boot/auth/security/handler/JsonAccessDeniedHandler.java +++ b/src/main/java/com/youlai/boot/framework/security/handler/JsonAccessDeniedHandler.java @@ -1,4 +1,4 @@ -package com.youlai.boot.auth.security.handler; +package com.youlai.boot.framework.security.handler; import com.youlai.boot.common.result.ResultCode; import com.youlai.boot.framework.web.util.ResponseWriter; @@ -9,9 +9,7 @@ import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; /** - * 无权限访问处理器。 - *

- * 归使用方,因为 JSON 响应格式因项目而异。 + * 无权限访问处理器 * * @author Ray.Hao * @since 2.0.0 diff --git a/src/main/java/com/youlai/boot/auth/security/handler/JsonAuthenticationEntryPoint.java b/src/main/java/com/youlai/boot/framework/security/handler/JsonAuthenticationEntryPoint.java similarity index 87% rename from src/main/java/com/youlai/boot/auth/security/handler/JsonAuthenticationEntryPoint.java rename to src/main/java/com/youlai/boot/framework/security/handler/JsonAuthenticationEntryPoint.java index 0a265125..791c9126 100644 --- a/src/main/java/com/youlai/boot/auth/security/handler/JsonAuthenticationEntryPoint.java +++ b/src/main/java/com/youlai/boot/framework/security/handler/JsonAuthenticationEntryPoint.java @@ -1,4 +1,4 @@ -package com.youlai.boot.auth.security.handler; +package com.youlai.boot.framework.security.handler; import com.youlai.boot.common.result.ResultCode; import com.youlai.boot.framework.web.util.ResponseWriter; @@ -14,9 +14,7 @@ import jakarta.servlet.http.HttpServletResponse; import java.io.IOException; /** - * 统一处理 Spring Security 认证失败响应。 - *

- * 归使用方,因为 JSON 响应格式(Result 结构、错误码)因项目而异。 + * 统一处理 Spring Security 认证失败响应 * * @author Ray.Hao * @since 2.0.0 diff --git a/src/main/java/com/youlai/boot/framework/security/model/RoleDataScope.java b/src/main/java/com/youlai/boot/framework/security/model/RoleDataScope.java index 2fbcb6ba..26f2c6ff 100644 --- a/src/main/java/com/youlai/boot/framework/security/model/RoleDataScope.java +++ b/src/main/java/com/youlai/boot/framework/security/model/RoleDataScope.java @@ -9,8 +9,6 @@ import java.util.List; /** * 角色数据权限信息 - *

- * 用于存储单个角色的数据权限范围信息,支持多角色数据权限合并(并集策略) * * @author Ray.Hao * @since 3.0.0 @@ -22,20 +20,13 @@ public class RoleDataScope implements Serializable { private static final long serialVersionUID = 1L; - /** - * 角色编码 - */ + // 角色编码 private String roleCode; - /** - * 数据权限范围值 - * 1-所有数据 2-部门及子部门数据 3-本部门数据 4-本人数据 5-自定义部门数据 - */ + // 数据权限范围值 private Integer dataScope; - /** - * 自定义部门ID列表(仅当 dataScope=5 时有效) - */ + // 自定义部门ID列表(仅当 dataScope=5 时有效) private List customDeptIds; /** diff --git a/src/main/java/com/youlai/boot/framework/security/model/SecurityUser.java b/src/main/java/com/youlai/boot/framework/security/model/SecurityUser.java index 394897b5..8b9b3509 100644 --- a/src/main/java/com/youlai/boot/framework/security/model/SecurityUser.java +++ b/src/main/java/com/youlai/boot/framework/security/model/SecurityUser.java @@ -7,9 +7,6 @@ import java.util.Set; /** * 安全模块用户数据 POJO。 - *

- * 作为端口接口的返回类型,承载用户认证所需的全部数据。 - * 纯 JDK 类型,无 system 模块依赖,可直接序列化。 * * @author Ray.Hao * @since 2025/12/16 @@ -17,51 +14,31 @@ import java.util.Set; @Data public class SecurityUser { - /** - * 用户ID - */ + // 用户ID private Long userId; - /** - * 用户名 - */ + // 用户名 private String username; - /** - * 昵称 - */ + // 昵称 private String nickname; - /** - * 部门ID - */ + // 部门ID private Long deptId; - /** - * 密码(加密后) - */ + // 密码(加密后) private String password; - /** - * 状态(1:启用 其它:禁用) - */ + // 状态(1:启用 其它:禁用) private Integer status; - /** - * 头像 URL - */ + // 头像 URL private String avatar; - /** - * 角色编码集合 - */ + // 角色编码集合 private Set roles; - /** - * 数据权限列表 - *

- * 存储用户所有角色的数据权限范围,用于实现多角色权限合并(并集策略) - */ + // 数据权限列表 private List dataScopes; /** diff --git a/src/main/java/com/youlai/boot/framework/security/model/SecurityUserDetails.java b/src/main/java/com/youlai/boot/framework/security/model/SecurityUserDetails.java index 754b7ece..b026c03c 100644 --- a/src/main/java/com/youlai/boot/framework/security/model/SecurityUserDetails.java +++ b/src/main/java/com/youlai/boot/framework/security/model/SecurityUserDetails.java @@ -14,10 +14,6 @@ import java.util.stream.Collectors; /** * Spring Security 用户认证对象。 - *

- * 实现 {@link UserDetails},封装用户标识、角色、数据权限等认证信息。 - * {@link #roles} 字段存储角色编码(不带 ROLE_ 前缀), - * {@link #getAuthorities()} 运行时补前缀并转为 {@link SimpleGrantedAuthority}。 * * @author Ray.Hao * @version 3.0.0 @@ -26,39 +22,25 @@ import java.util.stream.Collectors; @NoArgsConstructor public class SecurityUserDetails implements UserDetails { - /** - * 用户ID - */ + // 用户ID private Long userId; - /** - * 用户名 - */ + // 用户名 private String username; - /** - * 密码 - */ + // 密码 private String password; - /** - * 账号是否启用(true:启用 false:禁用) - */ + // 账号是否启用(true:启用 false:禁用) private Boolean enabled; - /** - * 部门ID - */ + // 部门ID private Long deptId; - /** - * 数据权限列表 - */ + // 数据权限列表 private List dataScopes; - /** - * 角色编码集合(不带 ROLE_ 前缀) - */ + // 角色编码集合(不带 ROLE_ 前缀) private Set roles; /** diff --git a/src/main/java/com/youlai/boot/framework/security/port/PermissionPort.java b/src/main/java/com/youlai/boot/framework/security/port/PermissionPort.java index 9417eded..79fdfc80 100644 --- a/src/main/java/com/youlai/boot/framework/security/port/PermissionPort.java +++ b/src/main/java/com/youlai/boot/framework/security/port/PermissionPort.java @@ -4,11 +4,8 @@ import java.util.Set; /** * 权限查询端口。 - *

- * 由 system 模块提供适配器实现,framework 层通过此接口获取角色权限集合, - * 不直接依赖 system 模块的 {@code RoleMenuService}。 * - * @see com.youlai.boot.system.security.adapter.PermissionAdapter + * @see com.youlai.boot.system.adapter.security.PermissionAdapter */ public interface PermissionPort { diff --git a/src/main/java/com/youlai/boot/framework/security/port/UserAuthenticationPort.java b/src/main/java/com/youlai/boot/framework/security/port/UserAuthenticationPort.java index 82acea2c..dd6ec4fe 100644 --- a/src/main/java/com/youlai/boot/framework/security/port/UserAuthenticationPort.java +++ b/src/main/java/com/youlai/boot/framework/security/port/UserAuthenticationPort.java @@ -5,11 +5,8 @@ import com.youlai.boot.framework.security.model.SecurityUser; /** * 用户认证信息查询端口。 - *

- * 由 system 模块提供适配器实现,framework 层通过此接口获取认证数据, - * 不直接依赖 system 模块的 {@code UserService} / {@code UserSocialService}。 * - * @see com.youlai.boot.system.security.adapter.UserAuthenticationAdapter + * @see com.youlai.boot.system.adapter.security.UserAuthenticationAdapter */ public interface UserAuthenticationPort { diff --git a/src/main/java/com/youlai/boot/framework/security/service/PermissionService.java b/src/main/java/com/youlai/boot/framework/security/service/PermissionService.java index ef7cc446..074fd1ea 100644 --- a/src/main/java/com/youlai/boot/framework/security/service/PermissionService.java +++ b/src/main/java/com/youlai/boot/framework/security/service/PermissionService.java @@ -13,9 +13,6 @@ import java.util.Set; /** * Spring Security 权限校验组件。 - *

- * 用于 SpEL 表达式:{@code @PreAuthorize("@ss.hasPerm('sys:user:create')")}。 - * 通过 {@link PermissionPort} 查询角色权限,不直接依赖 system 模块。 * * @author Ray.Hao * @since 0.0.1 diff --git a/src/main/java/com/youlai/boot/framework/security/service/SecurityUserDetailsService.java b/src/main/java/com/youlai/boot/framework/security/service/SecurityUserDetailsService.java index 9b998c22..1dc4ced6 100644 --- a/src/main/java/com/youlai/boot/framework/security/service/SecurityUserDetailsService.java +++ b/src/main/java/com/youlai/boot/framework/security/service/SecurityUserDetailsService.java @@ -12,8 +12,6 @@ import org.springframework.stereotype.Service; /** * 系统用户认证 DetailsService。 - *

- * 通过 {@link UserAuthenticationPort} 获取认证信息,不直接依赖 system 模块。 * * @author Ray.Hao * @since 2021/10/19 diff --git a/src/main/java/com/youlai/boot/framework/security/token/JwtTokenManager.java b/src/main/java/com/youlai/boot/framework/security/token/JwtTokenManager.java index 54bf431e..ce101fbe 100644 --- a/src/main/java/com/youlai/boot/framework/security/token/JwtTokenManager.java +++ b/src/main/java/com/youlai/boot/framework/security/token/JwtTokenManager.java @@ -14,7 +14,7 @@ import com.youlai.boot.common.constant.JwtClaimConstants; import com.youlai.boot.common.constant.RedisConstants; import com.youlai.boot.common.constant.SecurityConstants; import com.youlai.boot.common.result.ResultCode; -import com.youlai.boot.config.property.SecurityProperties; +import com.youlai.boot.framework.security.config.SecurityProperties; import com.youlai.boot.common.exception.TokenInvalidException; import com.youlai.boot.framework.security.model.AuthenticationToken; import com.youlai.boot.framework.security.model.RoleDataScope; @@ -33,20 +33,18 @@ import java.util.stream.Collectors; /** * JWT Token 管理器。 - *

- * 基于 JWT 的无状态认证,支持 Access + Refresh 双令牌、Token 撤销(jti 黑名单)、 - * 用户级会话失效(tokenVersion)、多角色数据权限存储。 - *

- * JWT claims 中存储角色编码(不带 ROLE_ 前缀),解析后由 {@link SecurityUserDetails#getAuthorities()} 运行时补前缀。 * * @author Ray.Hao * @since 2024/11/15 */ -@ConditionalOnProperty(value = "security.session.type", havingValue = "jwt") +@ConditionalOnProperty(value = "security.token.type", havingValue = "jwt") @Slf4j @Service public class JwtTokenManager implements TokenManager { + // 允许的签名算法,防止 alg:none 等算法降级攻击 + private static final String ALLOWED_ALGORITHM = "HS256"; + private final SecurityProperties securityProperties; private final RedisTemplate redisTemplate; private final byte[] secretKey; @@ -54,7 +52,7 @@ public class JwtTokenManager implements TokenManager { public JwtTokenManager(SecurityProperties securityProperties, RedisTemplate redisTemplate) { this.securityProperties = securityProperties; this.redisTemplate = redisTemplate; - this.secretKey = securityProperties.getSession().getJwt().getSecretKey().getBytes(); + this.secretKey = securityProperties.getToken().getJwt().getSecretKey().getBytes(); } @Override @@ -82,10 +80,10 @@ public class JwtTokenManager implements TokenManager { private int resolveAccessTtl(SecurityUserDetails userDetails) { if (ClientTypeConstants.CLIENT.equals(userDetails.getClientType())) { return resolveTtl( - securityProperties.getSession().getClientAccessTokenTimeToLive(), - securityProperties.getSession().getAccessTokenTimeToLive()); + securityProperties.getToken().getClientAccessTokenTimeToLive(), + securityProperties.getToken().getAccessTokenTimeToLive()); } - return securityProperties.getSession().getAccessTokenTimeToLive(); + return securityProperties.getToken().getAccessTokenTimeToLive(); } /** @@ -95,10 +93,10 @@ public class JwtTokenManager implements TokenManager { private int resolveRefreshTtl(SecurityUserDetails userDetails) { if (ClientTypeConstants.CLIENT.equals(userDetails.getClientType())) { return resolveTtl( - securityProperties.getSession().getClientRefreshTokenTimeToLive(), - securityProperties.getSession().getRefreshTokenTimeToLive()); + securityProperties.getToken().getClientRefreshTokenTimeToLive(), + securityProperties.getToken().getRefreshTokenTimeToLive()); } - return securityProperties.getSession().getRefreshTokenTimeToLive(); + return securityProperties.getToken().getRefreshTokenTimeToLive(); } /** @@ -112,6 +110,9 @@ public class JwtTokenManager implements TokenManager { @Override public Authentication parseToken(String token) { JWT jwt = JWTUtil.parseToken(token); + if (!isAlgorithmAllowed(jwt) || !jwt.setKey(secretKey).verify()) { + throw new TokenInvalidException(ResultCode.ACCESS_TOKEN_INVALID); + } JSONObject payloads = jwt.getPayloads(); SecurityUserDetails userDetails = new SecurityUserDetails(); userDetails.setUserId(payloads.getLong(JwtClaimConstants.USER_ID)); @@ -170,6 +171,9 @@ public class JwtTokenManager implements TokenManager { private boolean validateToken(String token, boolean validateRefreshToken) { try { JWT jwt = JWTUtil.parseToken(token); + if (!isAlgorithmAllowed(jwt)) { + return false; + } boolean isValid = jwt.setKey(secretKey).validate(0); if (!isValid) { @@ -226,6 +230,9 @@ public class JwtTokenManager implements TokenManager { token = token.substring(SecurityConstants.BEARER_TOKEN_PREFIX.length()); } JWT jwt = JWTUtil.parseToken(token); + if (!isAlgorithmAllowed(jwt) || !jwt.setKey(secretKey).verify()) { + return; + } JSONObject payloads = jwt.getPayloads(); String jti = payloads.getStr(JWTPayload.JWT_ID); Integer expirationAt = payloads.getInt(JWTPayload.EXPIRES_AT); @@ -347,4 +354,15 @@ public class JwtTokenManager implements TokenManager { redisTemplate.opsForValue().set(revokedJtiKey, Boolean.TRUE); } } + + /** + * 校验 JWT 头部算法是否在允许的白名单中,防止 alg:none 等算法降级攻击 + * + * @param jwt JWT 对象 + * @return 是否允许 + */ + private boolean isAlgorithmAllowed(JWT jwt) { + Object algorithm = jwt.getHeader("alg"); + return algorithm != null && ALLOWED_ALGORITHM.equals(algorithm.toString()); + } } diff --git a/src/main/java/com/youlai/boot/framework/security/token/RedisTokenManager.java b/src/main/java/com/youlai/boot/framework/security/token/RedisTokenManager.java index 07937d01..0ae0f707 100644 --- a/src/main/java/com/youlai/boot/framework/security/token/RedisTokenManager.java +++ b/src/main/java/com/youlai/boot/framework/security/token/RedisTokenManager.java @@ -5,7 +5,7 @@ import cn.hutool.core.util.StrUtil; import com.youlai.boot.common.constant.RedisConstants; import com.youlai.boot.common.constant.SecurityConstants; import com.youlai.boot.common.result.ResultCode; -import com.youlai.boot.config.property.SecurityProperties; +import com.youlai.boot.framework.security.config.SecurityProperties; import com.youlai.boot.common.exception.TokenInvalidException; import com.youlai.boot.framework.security.model.AuthenticationToken; import com.youlai.boot.framework.security.model.SecurityUserDetails; @@ -22,16 +22,11 @@ import java.util.concurrent.TimeUnit; /** * Redis Token 管理器。 - *

- * 基于 Redis 的有状态 Token 认证,支持 Access + Refresh 双令牌、 - * 单/多设备登录控制、用户级会话失效。 - *

- * 直接存取 {@link SecurityUserDetails}(password 置 null),无需 UserSession 中间层。 * * @author Ray.Hao * @since 2024/11/15 */ -@ConditionalOnProperty(value = "security.session.type", havingValue = "redis-token") +@ConditionalOnProperty(value = "security.token.type", havingValue = "redis-token") @Service public class RedisTokenManager implements TokenManager { @@ -62,7 +57,7 @@ public class RedisTokenManager implements TokenManager { return AuthenticationToken.builder() .accessToken(accessToken) .refreshToken(refreshToken) - .expiresIn(securityProperties.getSession().getAccessTokenTimeToLive()) + .expiresIn(securityProperties.getToken().getAccessTokenTimeToLive()) .build(); } @@ -102,7 +97,7 @@ public class RedisTokenManager implements TokenManager { String newAccessToken = IdUtil.fastSimpleUUID(); storeAccessToken(newAccessToken, sessionUser); - int accessTtl = securityProperties.getSession().getAccessTokenTimeToLive(); + int accessTtl = securityProperties.getToken().getAccessTokenTimeToLive(); return AuthenticationToken.builder() .accessToken(newAccessToken) .refreshToken(refreshToken) @@ -152,16 +147,16 @@ public class RedisTokenManager implements TokenManager { private void storeTokensInRedis(String accessToken, String refreshToken, SecurityUserDetails sessionUser) { setRedisValue(formatTokenKey(accessToken), sessionUser, - securityProperties.getSession().getAccessTokenTimeToLive()); + securityProperties.getToken().getAccessTokenTimeToLive()); String refreshTokenKey = StrUtil.format(RedisConstants.Auth.REFRESH_TOKEN_USER, refreshToken); setRedisValue(refreshTokenKey, sessionUser, - securityProperties.getSession().getRefreshTokenTimeToLive()); + securityProperties.getToken().getRefreshTokenTimeToLive()); setRedisValue(StrUtil.format(RedisConstants.Auth.USER_REFRESH_TOKEN, sessionUser.getUserId()), - refreshToken, securityProperties.getSession().getRefreshTokenTimeToLive()); + refreshToken, securityProperties.getToken().getRefreshTokenTimeToLive()); } private void handleSingleDeviceLogin(Long userId, String accessToken) { - Boolean allowMultiLogin = securityProperties.getSession().getRedisToken().getAllowMultiLogin(); + Boolean allowMultiLogin = securityProperties.getToken().getRedisToken().getAllowMultiLogin(); String userAccessKey = StrUtil.format(RedisConstants.Auth.USER_ACCESS_TOKEN, userId); if (!allowMultiLogin) { Object oldAccessTokenValue = redisTemplate.opsForValue().get(userAccessKey); @@ -169,14 +164,14 @@ public class RedisTokenManager implements TokenManager { redisTemplate.delete(formatTokenKey(oldAccessToken)); } } - setRedisValue(userAccessKey, accessToken, securityProperties.getSession().getAccessTokenTimeToLive()); + setRedisValue(userAccessKey, accessToken, securityProperties.getToken().getAccessTokenTimeToLive()); } private void storeAccessToken(String newAccessToken, SecurityUserDetails sessionUser) { setRedisValue(StrUtil.format(RedisConstants.Auth.ACCESS_TOKEN_USER, newAccessToken), sessionUser, - securityProperties.getSession().getAccessTokenTimeToLive()); + securityProperties.getToken().getAccessTokenTimeToLive()); String userAccessKey = StrUtil.format(RedisConstants.Auth.USER_ACCESS_TOKEN, sessionUser.getUserId()); - setRedisValue(userAccessKey, newAccessToken, securityProperties.getSession().getAccessTokenTimeToLive()); + setRedisValue(userAccessKey, newAccessToken, securityProperties.getToken().getAccessTokenTimeToLive()); } private String formatTokenKey(String token) { diff --git a/src/main/java/com/youlai/boot/framework/security/token/TokenManager.java b/src/main/java/com/youlai/boot/framework/security/token/TokenManager.java index 7aef032e..81d80a5d 100644 --- a/src/main/java/com/youlai/boot/framework/security/token/TokenManager.java +++ b/src/main/java/com/youlai/boot/framework/security/token/TokenManager.java @@ -6,8 +6,6 @@ import org.springframework.security.core.Authentication; /** * Token 管理器 - *

- * 用于生成、解析、校验、刷新 Token * * @author Ray.Hao * @since 2.16.0 @@ -60,8 +58,6 @@ public interface TokenManager { * @param token Token */ default void invalidateToken(String token) { - // 默认实现可以是空的,或者抛出不支持的操作异常 - // throw new UnsupportedOperationException("Not implemented"); } /** diff --git a/src/main/java/com/youlai/boot/framework/security/util/SecurityUtils.java b/src/main/java/com/youlai/boot/framework/security/util/SecurityUtils.java index d4f28d3c..3a25ad59 100644 --- a/src/main/java/com/youlai/boot/framework/security/util/SecurityUtils.java +++ b/src/main/java/com/youlai/boot/framework/security/util/SecurityUtils.java @@ -64,8 +64,6 @@ public class SecurityUtils { /** * 获取角色编码集合,不带 ROLE_ 前缀。 - *

- * 直接从 {@link SecurityUserDetails#getRoles()} 取值,不做 stripping 和过滤。 */ public static Set getRoles() { return getUser().map(SecurityUserDetails::getRoles).orElse(Set.of()); diff --git a/src/main/java/com/youlai/boot/framework/web/filter/IpRateLimitFilter.java b/src/main/java/com/youlai/boot/framework/web/filter/IpRateLimitFilter.java index 09219484..50d8e993 100644 --- a/src/main/java/com/youlai/boot/framework/web/filter/IpRateLimitFilter.java +++ b/src/main/java/com/youlai/boot/framework/web/filter/IpRateLimitFilter.java @@ -3,9 +3,9 @@ package com.youlai.boot.framework.web.filter; import cn.hutool.core.util.StrUtil; import com.youlai.boot.common.constant.RedisConstants; import com.youlai.boot.common.result.ResultCode; -import com.youlai.boot.common.util.IPUtils; -import com.youlai.boot.config.property.RateLimitProperties; -import com.youlai.boot.framework.web.ratelimit.SlidingWindowScript; +import com.youlai.boot.framework.web.util.IPUtils; +import com.youlai.boot.framework.web.ratelimit.RateLimitProperties; +import com.youlai.boot.framework.web.ratelimit.RedisSlidingWindowRateLimiter; import com.youlai.boot.framework.web.util.ResponseWriter; import jakarta.servlet.FilterChain; import jakarta.servlet.ServletException; @@ -15,7 +15,6 @@ import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.springframework.core.Ordered; import org.springframework.core.annotation.Order; -import org.springframework.data.redis.core.RedisTemplate; import org.springframework.stereotype.Component; import org.springframework.web.filter.OncePerRequestFilter; @@ -23,24 +22,6 @@ import java.io.IOException; /** * IP 全局限流过滤器 - *

- * 在所有请求进入 Controller 之前,按 IP 维度做滑动窗口限流。 - * 与 {@code @RateLimit} 注解级限流叠加:先过 IP 全局,再过接口级。 - *

- * - *

限流维度

- *
{@code
- *   Key: rate_limit:ip:{clientIp}
- *   默认: 1000 req / 60s(可通过 rate-limit.ip.* 配置)
- * }
- * - *

响应头

- * - * - * - * - * - *
X-RateLimit-Limit窗口内最大允许请求数
X-RateLimit-Remaining窗口内剩余可用请求数
X-RateLimit-Reset窗口重置时间(Unix 秒)
Retry-After超限时建议重试等待秒数(仅 429)
* * @author Ray.Hao * @since 4.4.0 @@ -51,7 +32,7 @@ import java.io.IOException; @Slf4j public class IpRateLimitFilter extends OncePerRequestFilter { - private final RedisTemplate redisTemplate; + private final RedisSlidingWindowRateLimiter rateLimiter; private final RateLimitProperties rateLimitProperties; @Override @@ -70,14 +51,8 @@ public class IpRateLimitFilter extends OncePerRequestFilter { String key = StrUtil.format(RedisConstants.RateLimit.IP, ip); long windowMs = ipConfig.getWindow().toMillis(); - // 执行滑动窗口计数(Lua 原子操作);Redis 异常时 Fail-Open 放行 - Long count; - try { - count = SlidingWindowScript.execute(redisTemplate, key, windowMs); - } catch (Exception e) { - log.warn("IP 限流 Redis 异常,Fail-Open 放行 ip={}", ip, e); - count = null; - } + // limiter 内部已统一 Fail-Open:Redis 异常返回 null,按未计数放行 + Long count = rateLimiter.count(key, windowMs); int limit = ipConfig.getLimit(); int current = count != null ? count.intValue() : 0; diff --git a/src/main/java/com/youlai/boot/framework/web/filter/RequestLogFilter.java b/src/main/java/com/youlai/boot/framework/web/filter/RequestLogFilter.java index f9ca070a..fd992b0b 100644 --- a/src/main/java/com/youlai/boot/framework/web/filter/RequestLogFilter.java +++ b/src/main/java/com/youlai/boot/framework/web/filter/RequestLogFilter.java @@ -1,9 +1,9 @@ package com.youlai.boot.framework.web.filter; -import com.youlai.boot.common.util.IPUtils; +import com.youlai.boot.framework.web.util.IPUtils; import jakarta.servlet.http.HttpServletRequest; import lombok.extern.slf4j.Slf4j; -import org.springframework.context.annotation.Configuration; +import org.springframework.stereotype.Component; import org.springframework.web.filter.CommonsRequestLoggingFilter; /** @@ -12,7 +12,7 @@ import org.springframework.web.filter.CommonsRequestLoggingFilter; * @author haoxr * @since 2023/03/03 */ -@Configuration +@Component @Slf4j public class RequestLogFilter extends CommonsRequestLoggingFilter { diff --git a/src/main/java/com/youlai/boot/framework/web/log/OperationLog.java b/src/main/java/com/youlai/boot/framework/web/log/OperationLog.java new file mode 100644 index 00000000..db9ee85d --- /dev/null +++ b/src/main/java/com/youlai/boot/framework/web/log/OperationLog.java @@ -0,0 +1,52 @@ +package com.youlai.boot.framework.web.log; + +import com.youlai.boot.common.enums.ActionTypeEnum; +import com.youlai.boot.common.enums.LogModuleEnum; + +import java.time.LocalDateTime; + +/** + * 操作日志载荷 + * + * @author Ray.Hao + * @since 4.7.0 + */ +public record OperationLog( + /** 模块 */ + LogModuleEnum module, + /** 操作类型 */ + ActionTypeEnum actionType, + /** 操作标题 */ + String title, + /** 自定义日志内容 */ + String content, + /** 操作人 ID */ + Long operatorId, + /** 操作人名称 */ + String operatorName, + /** 请求路径 */ + String requestUri, + /** 请求方式 */ + String requestMethod, + /** IP 地址 */ + String ip, + /** 省份 */ + String province, + /** 城市 */ + String city, + /** 设备 */ + String device, + /** 操作系统 */ + String os, + /** 浏览器 */ + String browser, + /** 状态:0 失败 1 成功 */ + Integer status, + /** 错误信息 */ + String errorMsg, + /** 执行时间(毫秒) */ + Integer executionTime, + /** 操作时间 */ + LocalDateTime createTime +) { +} diff --git a/src/main/java/com/youlai/boot/common/aspect/LogAspect.java b/src/main/java/com/youlai/boot/framework/web/log/OperationLogAspect.java similarity index 72% rename from src/main/java/com/youlai/boot/common/aspect/LogAspect.java rename to src/main/java/com/youlai/boot/framework/web/log/OperationLogAspect.java index 270e08c6..4e7af041 100644 --- a/src/main/java/com/youlai/boot/common/aspect/LogAspect.java +++ b/src/main/java/com/youlai/boot/framework/web/log/OperationLogAspect.java @@ -1,4 +1,4 @@ -package com.youlai.boot.common.aspect; +package com.youlai.boot.framework.web.log; import cn.hutool.core.util.StrUtil; import cn.hutool.http.useragent.UserAgent; @@ -6,10 +6,8 @@ import cn.hutool.http.useragent.UserAgentUtil; import com.youlai.boot.common.annotation.Log; import com.youlai.boot.common.enums.ActionTypeEnum; import com.youlai.boot.common.enums.LogModuleEnum; -import com.youlai.boot.common.util.IPUtils; +import com.youlai.boot.framework.web.util.IPUtils; import com.youlai.boot.framework.security.util.SecurityUtils; -import com.youlai.boot.system.model.entity.SysLog; -import com.youlai.boot.system.service.LogService; import jakarta.servlet.http.HttpServletRequest; import lombok.extern.slf4j.Slf4j; import org.aspectj.lang.ProceedingJoinPoint; @@ -27,26 +25,25 @@ import java.util.concurrent.Executor; /** * 操作日志切面 - *

@Log 标注的方法执行后异步写入 sys_log 表

* * @author Ray.Hao - * @since 0.0.1 + * @since 4.7.0 */ @Aspect @Component @Slf4j -public class LogAspect { +public class OperationLogAspect { private static final int MAX_ERROR_MSG_LENGTH = 2000; - private final LogService logService; + private final OperationLogPort operationLogPort; private final Executor operationLogExecutor; - public LogAspect( - LogService logService, + public OperationLogAspect( + OperationLogPort operationLogPort, @Qualifier("operationLogExecutor") Executor operationLogExecutor ) { - this.logService = logService; + this.operationLogPort = operationLogPort; this.operationLogExecutor = operationLogExecutor; } @@ -76,13 +73,13 @@ public class LogAspect { } finally { long elapsed = System.currentTimeMillis() - start; try { - SysLog entity = buildEntity(logAnnotation, elapsed, failure, userId, username); - if (entity != null) { + OperationLog operationLog = buildOperationLog(logAnnotation, elapsed, failure, userId, username); + if (operationLog != null) { operationLogExecutor.execute(() -> { try { - logService.save(entity); + operationLogPort.record(operationLog); } catch (Exception e) { - log.error("保存操作日志失败 title={} uri={}", entity.getTitle(), entity.getRequestUri(), e); + log.error("保存操作日志失败 title={} uri={}", operationLog.title(), operationLog.requestUri(), e); } }); } @@ -92,7 +89,7 @@ public class LogAspect { } } - private SysLog buildEntity(Log ann, long elapsed, Throwable failure, Long userId, String username) { + private OperationLog buildOperationLog(Log ann, long elapsed, Throwable failure, Long userId, String username) { ServletRequestAttributes attrs = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes(); if (attrs == null) return null; @@ -103,31 +100,32 @@ public class LogAspect { LogModuleEnum module = ann.module(); ActionTypeEnum action = ann.value(); - SysLog entity = new SysLog(); - entity.setModule(module); - entity.setActionType(action); - entity.setTitle(StrUtil.blankToDefault(ann.title(), module.getLabel() + "-" + action.getLabel())); - entity.setContent(ann.content()); // 设备类接口无登录用户,userId 为 null;兜底为常量为保证日志可落库 - entity.setOperatorId(userId != null ? userId : UNKNOWN_OPERATOR_ID); + Long operatorId = userId != null ? userId : UNKNOWN_OPERATOR_ID; // 无用户时尝试用设备SN标识操作来源 - entity.setOperatorName(username != null ? username : resolveDeviceSn(req)); - entity.setRequestUri(req.getRequestURI()); - entity.setRequestMethod(req.getMethod()); - entity.setIp(ip); - entity.setDevice(getDevice(ua)); - entity.setOs(getOs(ua)); - entity.setBrowser(getBrowser(ua)); - entity.setStatus(failure == null ? 1 : 0); - entity.setErrorMsg(failure == null ? null : truncate(failure.getMessage(), MAX_ERROR_MSG_LENGTH)); - entity.setExecutionTime((int) Math.min(elapsed, Integer.MAX_VALUE)); - entity.setCreateTime(LocalDateTime.now()); - + String operatorName = username != null ? username : resolveDeviceSn(req); IpRegion region = parseRegion(ip); - entity.setProvince(region.province); - entity.setCity(region.city); - return entity; + return new OperationLog( + module, + action, + StrUtil.blankToDefault(ann.title(), module.getLabel() + "-" + action.getLabel()), + ann.content(), + operatorId, + operatorName, + req.getRequestURI(), + req.getMethod(), + ip, + region.province(), + region.city(), + getDevice(ua), + getOs(ua), + getBrowser(ua), + failure == null ? 1 : 0, + failure == null ? null : truncate(failure.getMessage(), MAX_ERROR_MSG_LENGTH), + (int) Math.min(elapsed, Integer.MAX_VALUE), + LocalDateTime.now() + ); } private IpRegion parseRegion(String ip) { diff --git a/src/main/java/com/youlai/boot/framework/web/log/OperationLogPort.java b/src/main/java/com/youlai/boot/framework/web/log/OperationLogPort.java new file mode 100644 index 00000000..53709f82 --- /dev/null +++ b/src/main/java/com/youlai/boot/framework/web/log/OperationLogPort.java @@ -0,0 +1,17 @@ +package com.youlai.boot.framework.web.log; + +/** + * 操作日志落库端口 + * + * @author Ray.Hao + * @since 4.7.0 + */ +public interface OperationLogPort { + + /** + * 记录操作日志 + * + * @param operationLog 操作日志载荷 + */ + void record(OperationLog operationLog); +} diff --git a/src/main/java/com/youlai/boot/framework/web/ratelimit/RateLimit.java b/src/main/java/com/youlai/boot/framework/web/ratelimit/RateLimit.java new file mode 100644 index 00000000..5ed95f94 --- /dev/null +++ b/src/main/java/com/youlai/boot/framework/web/ratelimit/RateLimit.java @@ -0,0 +1,29 @@ +package com.youlai.boot.framework.web.ratelimit; + +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; + +/** + * 接口限流注解 + * + * @author Ray.Hao + * @since 4.3.1 + */ +@Target(ElementType.METHOD) +@Retention(RetentionPolicy.RUNTIME) +@Documented +public @interface RateLimit { + + /** + * 窗口内允许的最大请求数。 + */ + int limit() default 0; + + /** + * 滑动窗口大小(秒)。 + */ + int window() default 0; +} diff --git a/src/main/java/com/youlai/boot/common/aspect/RateLimitAspect.java b/src/main/java/com/youlai/boot/framework/web/ratelimit/RateLimitAspect.java similarity index 80% rename from src/main/java/com/youlai/boot/common/aspect/RateLimitAspect.java rename to src/main/java/com/youlai/boot/framework/web/ratelimit/RateLimitAspect.java index b11b5377..621edb3a 100644 --- a/src/main/java/com/youlai/boot/common/aspect/RateLimitAspect.java +++ b/src/main/java/com/youlai/boot/framework/web/ratelimit/RateLimitAspect.java @@ -1,15 +1,12 @@ -package com.youlai.boot.common.aspect; +package com.youlai.boot.framework.web.ratelimit; import cn.hutool.core.util.StrUtil; import cn.hutool.crypto.digest.DigestUtil; -import com.youlai.boot.common.annotation.RateLimit; import com.youlai.boot.common.constant.RedisConstants; import com.youlai.boot.common.constant.SecurityConstants; -import com.youlai.boot.common.result.ResultCode; -import com.youlai.boot.common.util.IPUtils; -import com.youlai.boot.config.property.RateLimitProperties; import com.youlai.boot.common.exception.RateLimitException; -import com.youlai.boot.framework.web.ratelimit.SlidingWindowScript; +import com.youlai.boot.common.result.ResultCode; +import com.youlai.boot.framework.web.util.IPUtils; import jakarta.servlet.http.HttpServletRequest; import jakarta.servlet.http.HttpServletResponse; import lombok.RequiredArgsConstructor; @@ -17,7 +14,6 @@ import lombok.extern.slf4j.Slf4j; import org.aspectj.lang.ProceedingJoinPoint; import org.aspectj.lang.annotation.Around; import org.aspectj.lang.annotation.Aspect; -import org.springframework.data.redis.core.RedisTemplate; import org.springframework.http.HttpHeaders; import org.springframework.stereotype.Component; import org.springframework.web.context.request.RequestContextHolder; @@ -25,16 +21,6 @@ import org.springframework.web.context.request.ServletRequestAttributes; /** * 接口级限流切面 - *

- * 对标注了 {@link RateLimit} 的 Controller 方法做 Redis 滑动窗口计数。 - * 超阈值抛出 {@link BusinessException}(A0502),全局异常处理器统一返回 JSON。 - *

- * - *

升级历史

- *
    - *
  • 4.3.1 — 初始版本:固定窗口计数器
  • - *
  • 4.4.0 — 升级为滑动窗口 + X-RateLimit-* 渐进式响应头
  • - *
* * @author Ray.Hao * @since 4.3.1 @@ -45,7 +31,7 @@ import org.springframework.web.context.request.ServletRequestAttributes; @Slf4j public class RateLimitAspect { - private final RedisTemplate redisTemplate; + private final RedisSlidingWindowRateLimiter rateLimiter; private final RateLimitProperties rateLimitProperties; @Around("@annotation(rateLimit)") @@ -59,7 +45,8 @@ public class RateLimitAspect { ? rateLimit.window() * 1000L : rateLimitProperties.getDefaultWindow().toMillis(); - Long count = SlidingWindowScript.execute(redisTemplate, key, windowMs); + // limiter 内部已统一 Fail-Open:Redis 异常返回 null,按未计数放行 + Long count = rateLimiter.count(key, windowMs); int current = count != null ? count.intValue() : 0; setRateLimitHeaders(request, limit, current, windowMs); diff --git a/src/main/java/com/youlai/boot/framework/web/ratelimit/RateLimitProperties.java b/src/main/java/com/youlai/boot/framework/web/ratelimit/RateLimitProperties.java new file mode 100644 index 00000000..06c2b35b --- /dev/null +++ b/src/main/java/com/youlai/boot/framework/web/ratelimit/RateLimitProperties.java @@ -0,0 +1,43 @@ +package com.youlai.boot.framework.web.ratelimit; + +import lombok.Data; +import org.springframework.boot.context.properties.ConfigurationProperties; +import org.springframework.stereotype.Component; + +import java.time.Duration; + +/** + * 限流配置 + * + * @author Ray.Hao + * @since 4.3.1 + */ +@Data +@Component +@ConfigurationProperties(prefix = "rate-limit") +public class RateLimitProperties { + + // / + private int defaultLimit = 5; + + // / + private Duration defaultWindow = Duration.ofSeconds(60); + + // IP 全局限流配置 + private Ip ip = new Ip(); + + @Data + public static class Ip { + + // 是否启用 IP 全局限流。 + private boolean enabled = true; + + // 窗口内最大请求数(默认 1000) + private int limit = 1000; + + // 滑动窗口大小,支持 60s / 1m / 500ms 等 Duration 写法(默认 60s) + private Duration window = Duration.ofSeconds(60); + + } + +} diff --git a/src/main/java/com/youlai/boot/framework/web/ratelimit/RedisSlidingWindowRateLimiter.java b/src/main/java/com/youlai/boot/framework/web/ratelimit/RedisSlidingWindowRateLimiter.java new file mode 100644 index 00000000..5c27bb91 --- /dev/null +++ b/src/main/java/com/youlai/boot/framework/web/ratelimit/RedisSlidingWindowRateLimiter.java @@ -0,0 +1,64 @@ +package com.youlai.boot.framework.web.ratelimit; + +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.data.redis.core.RedisTemplate; +import org.springframework.data.redis.core.script.DefaultRedisScript; +import org.springframework.stereotype.Component; + +import java.util.List; +import java.util.UUID; + +/** + * Redis 滑动窗口限流器 + * + * @author Ray.Hao + * @since 4.4.0 + */ +@Component +@RequiredArgsConstructor +@Slf4j +public class RedisSlidingWindowRateLimiter { + + private final RedisTemplate redisTemplate; + + private static final DefaultRedisScript SCRIPT; + + static { + SCRIPT = new DefaultRedisScript<>(); + SCRIPT.setScriptText( + "local key = KEYS[1] " + + "local now = tonumber(ARGV[1]) " + + "local window = tonumber(ARGV[2]) " + + "local member = ARGV[3] " + + "redis.call('ZREMRANGEBYSCORE', key, 0, now - window) " + + "redis.call('ZADD', key, now, member) " + + "redis.call('PEXPIRE', key, window + 1000) " + + "return redis.call('ZCARD', key)" + ); + SCRIPT.setResultType(Long.class); + } + + /** + * 记录一次请求并返回窗口内计数 + * + * @param key 限流 Key(如 {@code rate_limit:ip:192.168.1.1}) + * @param windowMs 窗口大小(毫秒) + * @return 当前窗口内请求数(包含本次);Redis 异常时返回 null,调用方按 Fail-Open 放行 + */ + public Long count(String key, long windowMs) { + try { + // 传 Long 而非 String,避免 Jackson 序列化器加双引号导致 Lua tonumber() 返回 nil + return redisTemplate.execute( + SCRIPT, + List.of(key), + System.currentTimeMillis(), + windowMs, + UUID.randomUUID().toString() + ); + } catch (Exception e) { + log.warn("限流 Redis 异常,本次未计数(Fail-Open) key={}", key, e); + return null; + } + } +} diff --git a/src/main/java/com/youlai/boot/framework/web/ratelimit/SlidingWindowScript.java b/src/main/java/com/youlai/boot/framework/web/ratelimit/SlidingWindowScript.java index fafe61ad..13cc472f 100644 --- a/src/main/java/com/youlai/boot/framework/web/ratelimit/SlidingWindowScript.java +++ b/src/main/java/com/youlai/boot/framework/web/ratelimit/SlidingWindowScript.java @@ -8,16 +8,6 @@ import java.util.UUID; /** * 滑动窗口限流 Lua 脚本(共享工具) - *

- * 基于 Redis Sorted Set 实现原子化的滑动窗口计数: - *

    - *
  1. ZREMRANGEBYSCORE 清除窗口外旧请求
  2. - *
  3. ZADD 添加当前请求
  4. - *
  5. ZCARD 统计窗口内请求数
  6. - *
  7. PEXPIRE 设置 Key 过期(窗口 + 1s 冗余)
  8. - *
- * 一次网络往返完成全部操作,避免多次 Redis 调用之间的竞态条件。 - *

* * @author Ray.Hao * @since 4.4.0 diff --git a/src/main/java/com/youlai/boot/framework/web/repeatsubmit/RepeatSubmit.java b/src/main/java/com/youlai/boot/framework/web/repeatsubmit/RepeatSubmit.java new file mode 100644 index 00000000..838f9d5c --- /dev/null +++ b/src/main/java/com/youlai/boot/framework/web/repeatsubmit/RepeatSubmit.java @@ -0,0 +1,29 @@ +package com.youlai.boot.framework.web.repeatsubmit; + +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; + +/** + * 防重复提交注解 + * + * @author Ray.Hao + * @since 2.3.0 + */ +@Target(ElementType.METHOD) +@Retention(RetentionPolicy.RUNTIME) +@Documented +public @interface RepeatSubmit { + + /** + * 防重占位过期时间(秒) + */ + int expire() default 5; + + /** + * 请求标识 SpEL 表达式(可选) + */ + String key() default ""; +} diff --git a/src/main/java/com/youlai/boot/framework/web/repeatsubmit/RepeatSubmitAspect.java b/src/main/java/com/youlai/boot/framework/web/repeatsubmit/RepeatSubmitAspect.java new file mode 100644 index 00000000..f3b42d11 --- /dev/null +++ b/src/main/java/com/youlai/boot/framework/web/repeatsubmit/RepeatSubmitAspect.java @@ -0,0 +1,125 @@ +package com.youlai.boot.framework.web.repeatsubmit; + +import cn.hutool.core.util.StrUtil; +import cn.hutool.crypto.digest.DigestUtil; +import cn.hutool.json.JSONUtil; +import com.youlai.boot.common.constant.RedisConstants; +import com.youlai.boot.common.constant.SecurityConstants; +import com.youlai.boot.common.exception.BusinessException; +import com.youlai.boot.common.result.ResultCode; +import com.youlai.boot.framework.web.util.IPUtils; +import jakarta.servlet.ServletRequest; +import jakarta.servlet.ServletResponse; +import jakarta.servlet.http.HttpServletRequest; +import lombok.RequiredArgsConstructor; +import org.aspectj.lang.ProceedingJoinPoint; +import org.aspectj.lang.annotation.Around; +import org.aspectj.lang.annotation.Aspect; +import org.aspectj.lang.annotation.Pointcut; +import org.aspectj.lang.reflect.MethodSignature; +import org.redisson.api.RBucket; +import org.redisson.api.RedissonClient; +import org.springframework.context.expression.MethodBasedEvaluationContext; +import org.springframework.core.DefaultParameterNameDiscoverer; +import org.springframework.core.ParameterNameDiscoverer; +import org.springframework.expression.ExpressionParser; +import org.springframework.expression.spel.standard.SpelExpressionParser; +import org.springframework.http.HttpHeaders; +import org.springframework.stereotype.Component; +import org.springframework.validation.BindingResult; +import org.springframework.web.context.request.RequestContextHolder; +import org.springframework.web.context.request.ServletRequestAttributes; +import org.springframework.web.multipart.MultipartFile; + +import java.lang.reflect.Method; +import java.time.Duration; +import java.util.Arrays; +import java.util.List; + +/** + * 防重复提交切面 + * + * @author Ray.Hao + * @since 4.3.1 + */ +@Aspect +@Component +@RequiredArgsConstructor +public class RepeatSubmitAspect { + + private final RedissonClient redissonClient; + + private static final ExpressionParser SPEL_PARSER = new SpelExpressionParser(); + private static final ParameterNameDiscoverer PARAMETER_NAME_DISCOVERER = new DefaultParameterNameDiscoverer(); + + // 生成请求指纹时排除的参数类型,这些对象序列化结果不稳定或无业务含义 + private static final List> EXCLUDED_PARAM_TYPES = + List.of(ServletRequest.class, ServletResponse.class, MultipartFile.class, BindingResult.class); + + @Pointcut("@annotation(repeatSubmit)") + public void repeatSubmitPointCut(RepeatSubmit repeatSubmit) { + } + + @Around(value = "repeatSubmitPointCut(repeatSubmit)", argNames = "pjp,repeatSubmit") + public Object handleRepeatSubmit(ProceedingJoinPoint pjp, RepeatSubmit repeatSubmit) throws Throwable { + String lockKey = buildLockKey(pjp, repeatSubmit); + + RBucket bucket = redissonClient.getBucket(lockKey); + boolean acquired = bucket.setIfAbsent("1", Duration.ofSeconds(repeatSubmit.expire())); + if (!acquired) { + throw new BusinessException(ResultCode.DUPLICATE_SUBMISSION); + } + return pjp.proceed(); + } + + /** + * 生成防重占位的 key + */ + private String buildLockKey(ProceedingJoinPoint pjp, RepeatSubmit repeatSubmit) { + HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest(); + String userIdentifier = getUserIdentifier(request); + String requestIdentifier = StrUtil.join(":", request.getMethod(), request.getRequestURI()); + String requestFingerprint = StrUtil.isNotBlank(repeatSubmit.key()) + ? DigestUtil.sha256Hex(evaluateKey(pjp, repeatSubmit.key())) + : DigestUtil.sha256Hex(JSONUtil.toJsonStr(filterArgs(pjp))); + return StrUtil.format(RedisConstants.Lock.RESUBMIT, userIdentifier, requestIdentifier + ":" + requestFingerprint); + } + + /** + * 过滤掉不可稳定序列化的参数后再生成指纹 + */ + private Object[] filterArgs(ProceedingJoinPoint pjp) { + return Arrays.stream(pjp.getArgs()) + .filter(arg -> arg == null || EXCLUDED_PARAM_TYPES.stream().noneMatch(type -> type.isInstance(arg))) + .toArray(); + } + + /** + * 解析注解上的 SpEL key 表达式,方法参数可直接引用 + */ + private String evaluateKey(ProceedingJoinPoint pjp, String spel) { + Method method = ((MethodSignature) pjp.getSignature()).getMethod(); + MethodBasedEvaluationContext context = new MethodBasedEvaluationContext( + pjp.getTarget(), method, pjp.getArgs(), PARAMETER_NAME_DISCOVERER); + Object value = SPEL_PARSER.parseExpression(spel).getValue(context); + return value != null ? value.toString() : ""; + } + + /** + * 获取用户唯一标识 + * 1. 从请求头中获取 Token,使用 SHA-256 加密 Token 作为用户唯一标识 + * 2. 如果 Token 为空,使用 IP 作为用户唯一标识 + */ + private String getUserIdentifier(HttpServletRequest request) { + String userIdentifier; + String tokenHeader = request.getHeader(HttpHeaders.AUTHORIZATION); + if (StrUtil.isNotBlank(tokenHeader) && tokenHeader.startsWith(SecurityConstants.BEARER_TOKEN_PREFIX)) { + String rawToken = tokenHeader.substring(SecurityConstants.BEARER_TOKEN_PREFIX.length()); + userIdentifier = DigestUtil.sha256Hex(rawToken); + } else { + userIdentifier = IPUtils.getIpAddr(request); + } + return userIdentifier; + } + +} diff --git a/src/main/java/com/youlai/boot/common/util/IPUtils.java b/src/main/java/com/youlai/boot/framework/web/util/IPUtils.java similarity index 89% rename from src/main/java/com/youlai/boot/common/util/IPUtils.java rename to src/main/java/com/youlai/boot/framework/web/util/IPUtils.java index ae1480cc..c52683a7 100644 --- a/src/main/java/com/youlai/boot/common/util/IPUtils.java +++ b/src/main/java/com/youlai/boot/framework/web/util/IPUtils.java @@ -1,4 +1,4 @@ -package com.youlai.boot.common.util; +package com.youlai.boot.framework.web.util; import cn.hutool.core.util.StrUtil; import jakarta.annotation.PostConstruct; @@ -17,12 +17,6 @@ import java.nio.file.StandardCopyOption; /** * IP工具类 - *

- * 获取客户端IP地址和IP地址对应的地理位置信息 - *

- * 使用Nginx等反向代理软件, 则不能通过request.getRemoteAddr()获取IP地址 - * 如果使用了多级反向代理的话,X-Forwarded-For的值并不止一个,而是一串IP地址,X-Forwarded-For中第一个非unknown的有效IP字符串,则为真实IP地址 - *

* * @author Ray * @since 2.10.0 @@ -31,7 +25,7 @@ import java.nio.file.StandardCopyOption; @Component public class IPUtils { - private static final String DB_PATH = "/data/ip2region.xdb"; + private static final String DB_PATH = "/ip2region/ip2region.xdb"; private static Searcher searcher; @PostConstruct diff --git a/src/main/java/com/youlai/boot/framework/web/util/ResponseWriter.java b/src/main/java/com/youlai/boot/framework/web/util/ResponseWriter.java index 118ea7ed..16ce427b 100644 --- a/src/main/java/com/youlai/boot/framework/web/util/ResponseWriter.java +++ b/src/main/java/com/youlai/boot/framework/web/util/ResponseWriter.java @@ -13,7 +13,6 @@ import java.nio.charset.StandardCharsets; /** * 响应写入器 - *

用于过滤器、Security处理器等场景统一写入HTTP响应

*/ @Slf4j public final class ResponseWriter { diff --git a/src/main/java/com/youlai/boot/module/form/controller/FormController.java b/src/main/java/com/youlai/boot/module/form/controller/FormController.java new file mode 100644 index 00000000..552fd6aa --- /dev/null +++ b/src/main/java/com/youlai/boot/module/form/controller/FormController.java @@ -0,0 +1,254 @@ +package com.youlai.boot.module.form.controller; + +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; +import com.youlai.boot.common.annotation.Log; +import com.youlai.boot.framework.web.repeatsubmit.RepeatSubmit; +import com.youlai.boot.common.enums.ActionTypeEnum; +import com.youlai.boot.common.enums.LogModuleEnum; +import com.youlai.boot.common.result.PageResult; +import com.youlai.boot.common.result.Result; +import com.youlai.boot.common.exception.BusinessException; +import com.youlai.boot.common.model.Option; +import com.youlai.boot.framework.web.util.IPUtils; +import com.youlai.boot.module.form.model.form.FormAiGenerateForm; +import com.youlai.boot.module.form.model.form.FormDefinitionForm; +import com.youlai.boot.module.form.model.form.FormMenuForm; +import com.youlai.boot.module.form.model.query.FormDataPageQuery; +import com.youlai.boot.module.form.model.query.FormDefinitionPageQuery; +import com.youlai.boot.module.form.model.vo.FormDataVO; +import com.youlai.boot.module.form.model.vo.FormDefinitionPageVO; +import com.youlai.boot.module.form.model.vo.FormMenuVO; +import com.youlai.boot.module.form.model.vo.FormRenderVO; +import com.youlai.boot.module.form.service.FormDataService; +import com.youlai.boot.module.form.service.FormDefinitionService; +import io.swagger.v3.oas.annotations.Operation; +import io.swagger.v3.oas.annotations.Parameter; +import io.swagger.v3.oas.annotations.tags.Tag; +import jakarta.servlet.http.HttpServletRequest; +import jakarta.validation.Valid; +import lombok.RequiredArgsConstructor; +import org.springframework.security.access.prepost.PreAuthorize; +import org.springframework.web.bind.annotation.*; + +import java.util.Arrays; +import java.util.List; +import java.util.Map; + +/** + * 表单控制层(表单定义、访问菜单、表单数据) + * + * @author Ray.Hao + * @since 4.9.0 + */ +@Tag(name = "12.表单接口") +@RestController +@RequestMapping("/api/v1/forms") +@RequiredArgsConstructor +public class FormController { + + private final FormDefinitionService formDefinitionService; + private final FormDataService formDataService; + + @Operation(summary = "表单定义分页列表") + @GetMapping + @Log(module = LogModuleEnum.FORM, value = ActionTypeEnum.LIST) + public PageResult getFormDefinitionPage( + @Valid FormDefinitionPageQuery queryParams + ) { + Page result = formDefinitionService.getFormDefinitionPage(queryParams); + return PageResult.success(result); + } + + @Operation(summary = "获取审批表单下拉选项(工作流设计器绑定表单用)") + @GetMapping("/options") + public Result>> listWorkflowFormOptions() { + return Result.success(formDefinitionService.listWorkflowFormOptions()); + } + + @Operation(summary = "获取表单定义表单数据") + @GetMapping("/{formId}/form") + public Result getFormDefinitionForm( + @Parameter(description = "表单ID") @PathVariable Long formId + ) { + FormDefinitionForm formData = formDefinitionService.getFormDefinitionForm(formId); + return Result.success(formData); + } + + @Operation(summary = "新增表单定义") + @PostMapping + @PreAuthorize("@ss.hasPerm('form:definition:create')") + @RepeatSubmit + @Log(module = LogModuleEnum.FORM, value = ActionTypeEnum.INSERT) + public Result saveFormDefinition(@Valid @RequestBody FormDefinitionForm formData) { + boolean result = formDefinitionService.saveFormDefinition(formData); + return Result.judge(result); + } + + @Operation(summary = "修改表单定义") + @PutMapping("/{formId}") + @PreAuthorize("@ss.hasPerm('form:definition:update')") + @Log(module = LogModuleEnum.FORM, value = ActionTypeEnum.UPDATE) + public Result updateFormDefinition( + @Parameter(description = "表单ID") @PathVariable Long formId, + @RequestBody @Valid FormDefinitionForm formData + ) { + boolean result = formDefinitionService.updateFormDefinition(formId, formData); + return Result.judge(result); + } + + @Operation(summary = "删除表单定义") + @DeleteMapping("/{ids}") + @PreAuthorize("@ss.hasPerm('form:definition:delete')") + @Log(module = LogModuleEnum.FORM, value = ActionTypeEnum.DELETE) + public Result removeFormDefinition( + @Parameter(description = "表单ID,多个以英文逗号(,)拼接") @PathVariable String ids + ) { + formDefinitionService.removeFormDefinition(Arrays.stream(ids.split(",")).map(Long::valueOf).toList()); + return Result.success(); + } + + @Operation(summary = "发布表单") + @PutMapping("/{formId}/publish") + @PreAuthorize("@ss.hasPerm('form:definition:update')") + @Log(module = LogModuleEnum.FORM, value = ActionTypeEnum.UPDATE) + public Result publishFormDefinition( + @Parameter(description = "表单ID") @PathVariable Long formId + ) { + boolean result = formDefinitionService.publishFormDefinition(formId); + return Result.judge(result); + } + + @Operation(summary = "停用表单") + @PutMapping("/{formId}/disable") + @PreAuthorize("@ss.hasPerm('form:definition:update')") + @Log(module = LogModuleEnum.FORM, value = ActionTypeEnum.UPDATE) + public Result disableFormDefinition( + @Parameter(description = "表单ID") @PathVariable Long formId + ) { + boolean result = formDefinitionService.disableFormDefinition(formId); + return Result.judge(result); + } + + @Operation(summary = "获取表单渲染规则") + @GetMapping("/{formKey}/render") + public Result getFormRender( + @Parameter(description = "表单唯一标识") @PathVariable String formKey + ) { + FormRenderVO renderVO = formDefinitionService.getFormRender(formKey); + return Result.success(renderVO); + } + + //--------------------------------------------------- + // 表单菜单相关接口(发布向导) + //--------------------------------------------------- + @Operation(summary = "获取表单菜单配置(向导回显)") + @GetMapping("/{formId}/menu") + public Result getFormMenu( + @Parameter(description = "表单ID") @PathVariable Long formId + ) { + FormMenuVO menuVO = formDefinitionService.getFormMenu(formId); + return Result.success(menuVO); + } + + @Operation(summary = "生成表单访问菜单") + @PostMapping("/{formId}/menu") + @PreAuthorize("@ss.hasPerm('form:definition:update')") + @RepeatSubmit + @Log(module = LogModuleEnum.FORM, value = ActionTypeEnum.INSERT) + public Result saveFormMenu( + @Parameter(description = "表单ID") @PathVariable Long formId, + @Valid @RequestBody FormMenuForm menuForm + ) { + boolean result = formDefinitionService.saveFormMenu(formId, menuForm); + return Result.judge(result); + } + + //--------------------------------------------------- + // 公开表单相关接口(匿名,Security 白名单 + Service 校验 is_public + IP 限流) + //--------------------------------------------------- + @Operation(summary = "获取公开表单渲染规则(匿名)") + @GetMapping("/public/{formKey}/render") + public Result getPublicFormRender( + @Parameter(description = "表单唯一标识") @PathVariable String formKey + ) { + FormRenderVO renderVO = formDefinitionService.getPublicFormRender(formKey); + return Result.success(renderVO); + } + + @Operation(summary = "匿名提交公开表单数据") + @PostMapping("/public/{formKey}/data") + @RepeatSubmit + public Result savePublicFormData( + @Parameter(description = "表单唯一标识") @PathVariable String formKey, + @RequestBody Map data, + HttpServletRequest request + ) { + boolean result = formDataService.savePublicFormData(formKey, data, IPUtils.getIpAddr(request)); + return Result.judge(result); + } + + //--------------------------------------------------- + // 表单数据相关接口 + //--------------------------------------------------- + @Operation(summary = "表单数据分页列表") + @GetMapping("/{formKey}/data") + @PreAuthorize("@ss.hasPerm('form:data:list')") + @Log(module = LogModuleEnum.FORM, value = ActionTypeEnum.LIST) + public PageResult getFormDataPage( + @Parameter(description = "表单唯一标识") @PathVariable String formKey, + @Valid FormDataPageQuery queryParams + ) { + Page result = formDataService.getFormDataPage(formKey, queryParams); + return PageResult.success(result); + } + + @Operation(summary = "提交表单数据") + @PostMapping("/{formKey}/data") + @RepeatSubmit + @Log(module = LogModuleEnum.FORM, value = ActionTypeEnum.INSERT) + public Result saveFormData( + @Parameter(description = "表单唯一标识") @PathVariable String formKey, + @RequestBody Map data + ) { + boolean result = formDataService.saveFormData(formKey, data); + return Result.judge(result); + } + + @Operation(summary = "获取表单数据详情(只读回显)") + @GetMapping("/{formKey}/data/{dataId}") + @PreAuthorize("@ss.hasPerm('form:data:list')") + public Result getFormDataDetail( + @Parameter(description = "表单唯一标识") @PathVariable String formKey, + @Parameter(description = "数据ID") @PathVariable Long dataId + ) { + FormDataVO dataVO = formDataService.getFormDataDetail(dataId); + // 直查数据详情时明确提示;工作流回显场景由服务层调用方自行降级 + if (dataVO == null) { + throw new BusinessException("表单数据不存在"); + } + return Result.success(dataVO); + } + + @Operation(summary = "删除表单数据") + @DeleteMapping("/{formKey}/data/{ids}") + @PreAuthorize("@ss.hasPerm('form:data:delete')") + @Log(module = LogModuleEnum.FORM, value = ActionTypeEnum.DELETE) + public Result removeFormData( + @Parameter(description = "表单唯一标识") @PathVariable String formKey, + @Parameter(description = "数据ID,多个以英文逗号(,)拼接") @PathVariable String ids + ) { + formDataService.removeFormData(Arrays.stream(ids.split(",")).map(Long::valueOf).toList()); + return Result.success(); + } + + //--------------------------------------------------- + // AI 辅助接口(未开启 AI 时调用返回业务异常) + //--------------------------------------------------- + + @Operation(summary = "AI 生成表单规则") + @PostMapping("/ai-generate") + public Result generateRule(@RequestBody @Valid FormAiGenerateForm form) { + return Result.success(formDefinitionService.aiGenerateRule(form.getDescription())); + } + +} diff --git a/src/main/java/com/youlai/boot/module/form/converter/FormConverter.java b/src/main/java/com/youlai/boot/module/form/converter/FormConverter.java new file mode 100644 index 00000000..94a5bc22 --- /dev/null +++ b/src/main/java/com/youlai/boot/module/form/converter/FormConverter.java @@ -0,0 +1,24 @@ +package com.youlai.boot.module.form.converter; + +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; +import com.youlai.boot.module.form.model.entity.FormDefinition; +import com.youlai.boot.module.form.model.form.FormDefinitionForm; +import com.youlai.boot.module.form.model.vo.FormDefinitionPageVO; +import org.mapstruct.Mapper; + +/** + * 表单定义 对象转换器 + * + * @author Ray.Hao + * @since 4.9.0 + */ +@Mapper(componentModel = "spring") +public interface FormConverter { + + Page toPageVo(Page page); + + FormDefinitionForm toForm(FormDefinition entity); + + FormDefinition toEntity(FormDefinitionForm form); + +} diff --git a/src/main/java/com/youlai/boot/module/form/enums/FormCategoryEnum.java b/src/main/java/com/youlai/boot/module/form/enums/FormCategoryEnum.java new file mode 100644 index 00000000..ec20a96c --- /dev/null +++ b/src/main/java/com/youlai/boot/module/form/enums/FormCategoryEnum.java @@ -0,0 +1,50 @@ +package com.youlai.boot.module.form.enums; + +import com.baomidou.mybatisplus.annotation.EnumValue; +import com.fasterxml.jackson.annotation.JsonValue; +import com.youlai.boot.common.base.IBaseEnum; +import io.swagger.v3.oas.annotations.media.Schema; +import lombok.Getter; + +/** + * 表单类型枚举 + * + * @author Ray.Hao + * @since 4.9.0 + */ +@Schema(enumAsRef = true) +@Getter +public enum FormCategoryEnum implements IBaseEnum { + + /** + * 通用表单:公开收集 / 菜单入口,与流程无关 + */ + NORMAL("normal", "普通表单"), + + /** + * 工作流表单:可被工作流绑定为发起 / 办理表单 + */ + WORKFLOW("workflow", "工作流表单"); + + @EnumValue + private final String value; + + @JsonValue + private final String label; + + FormCategoryEnum(String value, String label) { + this.value = value; + this.label = label; + } + + @Override + public String getValue() { + return this.value; + } + + @Override + public String getLabel() { + return this.label; + } + +} \ No newline at end of file diff --git a/src/main/java/com/youlai/boot/module/form/enums/FormStatusEnum.java b/src/main/java/com/youlai/boot/module/form/enums/FormStatusEnum.java new file mode 100644 index 00000000..169ad7f9 --- /dev/null +++ b/src/main/java/com/youlai/boot/module/form/enums/FormStatusEnum.java @@ -0,0 +1,44 @@ +package com.youlai.boot.module.form.enums; + +import com.baomidou.mybatisplus.annotation.EnumValue; +import com.fasterxml.jackson.annotation.JsonValue; +import com.youlai.boot.common.base.IBaseEnum; +import io.swagger.v3.oas.annotations.media.Schema; +import lombok.Getter; + +/** + * 表单状态枚举 + * + * @author Ray.Hao + * @since 4.9.0 + */ +@Schema(enumAsRef = true) +@Getter +public enum FormStatusEnum implements IBaseEnum { + + DRAFT(0, "草稿"), + PUBLISHED(1, "已发布"), + DISABLED(-1, "已停用"); + + @EnumValue + private final Integer value; + + @JsonValue + private final String label; + + FormStatusEnum(Integer value, String label) { + this.value = value; + this.label = label; + } + + @Override + public Integer getValue() { + return this.value; + } + + @Override + public String getLabel() { + return this.label; + } + +} diff --git a/src/main/java/com/youlai/boot/module/form/mapper/FormDataMapper.java b/src/main/java/com/youlai/boot/module/form/mapper/FormDataMapper.java new file mode 100644 index 00000000..16b67a0b --- /dev/null +++ b/src/main/java/com/youlai/boot/module/form/mapper/FormDataMapper.java @@ -0,0 +1,29 @@ +package com.youlai.boot.module.form.mapper; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; +import com.youlai.boot.module.form.model.entity.FormData; +import com.youlai.boot.module.form.model.query.FormDataPageQuery; +import com.youlai.boot.module.form.model.vo.FormDataVO; +import org.apache.ibatis.annotations.Mapper; + +/** + * 表单数据 访问层 + * + * @author Ray.Hao + * @since 4.9.0 + */ +@Mapper +public interface FormDataMapper extends BaseMapper { + + /** + * 表单数据分页列表(联查提交人昵称) + * + * @param page 分页参数 + * @param formId 表单定义ID + * @param queryParams 查询参数 + * @return 表单数据分页列表 + */ + Page getFormDataPage(Page page, Long formId, FormDataPageQuery queryParams); + +} diff --git a/src/main/java/com/youlai/boot/module/form/mapper/FormDefinitionMapper.java b/src/main/java/com/youlai/boot/module/form/mapper/FormDefinitionMapper.java new file mode 100644 index 00000000..39196b94 --- /dev/null +++ b/src/main/java/com/youlai/boot/module/form/mapper/FormDefinitionMapper.java @@ -0,0 +1,28 @@ +package com.youlai.boot.module.form.mapper; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; +import com.youlai.boot.module.form.model.entity.FormDefinition; +import com.youlai.boot.module.form.model.query.FormDefinitionPageQuery; +import com.youlai.boot.module.form.model.vo.FormDefinitionPageVO; +import org.apache.ibatis.annotations.Mapper; + +/** + * 表单定义 访问层 + * + * @author Ray.Hao + * @since 4.9.0 + */ +@Mapper +public interface FormDefinitionMapper extends BaseMapper { + + /** + * 表单定义分页列表 + * + * @param page 分页参数 + * @param queryParams 查询参数 + * @return 表单定义分页列表 + */ + Page getFormDefinitionPage(Page page, FormDefinitionPageQuery queryParams); + +} diff --git a/src/main/java/com/youlai/boot/module/form/mapper/FormSnapshotMapper.java b/src/main/java/com/youlai/boot/module/form/mapper/FormSnapshotMapper.java new file mode 100644 index 00000000..a16e2505 --- /dev/null +++ b/src/main/java/com/youlai/boot/module/form/mapper/FormSnapshotMapper.java @@ -0,0 +1,16 @@ +package com.youlai.boot.module.form.mapper; + +import com.baomidou.mybatisplus.core.mapper.BaseMapper; +import com.youlai.boot.module.form.model.entity.FormSnapshot; +import org.apache.ibatis.annotations.Mapper; + +/** + * 表单版本快照访问层 + * + * @author Ray.Hao + * @since 4.9.0 + */ +@Mapper +public interface FormSnapshotMapper extends BaseMapper { + +} diff --git a/src/main/java/com/youlai/boot/module/form/model/entity/FormData.java b/src/main/java/com/youlai/boot/module/form/model/entity/FormData.java new file mode 100644 index 00000000..ae21d684 --- /dev/null +++ b/src/main/java/com/youlai/boot/module/form/model/entity/FormData.java @@ -0,0 +1,41 @@ +package com.youlai.boot.module.form.model.entity; + +import com.baomidou.mybatisplus.annotation.FieldFill; +import com.baomidou.mybatisplus.annotation.TableField; +import com.baomidou.mybatisplus.annotation.TableName; +import com.youlai.boot.common.base.BaseEntity; +import lombok.Data; +import lombok.EqualsAndHashCode; + +/** + * 表单数据实体 + * + * @author Ray.Hao + * @since 4.9.0 + */ +@EqualsAndHashCode(callSuper = true) +@TableName("form_data") +@Data +public class FormData extends BaseEntity { + + // 表单定义ID + private Long formId; + + // 表单版本(提交时快照,用于追溯该数据由哪版规则产出) + private Integer formVersion; + + // 表单数据(field -> value 映射的 JSON 字符串) + private String dataJson; + + // 提交人ID(匿名提交为空) + @TableField(fill = FieldFill.INSERT) + private Long createBy; + + // 修改人ID(数据修正时记录) + @TableField(fill = FieldFill.INSERT_UPDATE) + private Long updateBy; + + // 逻辑删除标识(0未删除 1已删除) + private Integer isDeleted; + +} diff --git a/src/main/java/com/youlai/boot/module/form/model/entity/FormDefinition.java b/src/main/java/com/youlai/boot/module/form/model/entity/FormDefinition.java new file mode 100644 index 00000000..dc87969e --- /dev/null +++ b/src/main/java/com/youlai/boot/module/form/model/entity/FormDefinition.java @@ -0,0 +1,65 @@ +package com.youlai.boot.module.form.model.entity; + +import com.baomidou.mybatisplus.annotation.FieldFill; +import com.baomidou.mybatisplus.annotation.FieldStrategy; +import com.baomidou.mybatisplus.annotation.TableField; +import com.baomidou.mybatisplus.annotation.TableName; +import com.youlai.boot.common.base.BaseEntity; +import lombok.Data; +import lombok.EqualsAndHashCode; + +/** + * 表单定义实体 + * + * @author Ray.Hao + * @since 4.9.0 + */ +@EqualsAndHashCode(callSuper = true) +@TableName("form_definition") +@Data +public class FormDefinition extends BaseEntity { + + // 表单唯一标识(业务编码,创建后不可修改) + private String formKey; + + // 表单名称 + private String formName; + + // 表单描述 + @TableField(updateStrategy = FieldStrategy.ALWAYS) + private String description; + + // 表单规则(form-create rule 数组 JSON 字符串) + private String formJson; + + // 表单全局配置 JSON 字符串(labelPosition/size/submitBtn 等) + @TableField(updateStrategy = FieldStrategy.ALWAYS) + private String optionsJson; + + // 状态(0草稿 1已发布 -1已停用) + private Integer status; + + // 是否允许匿名公开访问(0否 1是) + private Integer isPublic; + + // 表单类型(normal通用表单 workflow审批表单) + private String category; + + // 生成的访问菜单ID(NULL未生成,幂等防重复) + private Long menuId; + + // 版本号,每次发布+1 + private Integer version; + + // 创建人ID + @TableField(fill = FieldFill.INSERT) + private Long createBy; + + // 更新人ID + @TableField(fill = FieldFill.INSERT_UPDATE) + private Long updateBy; + + // 逻辑删除标识(0未删除 1已删除) + private Integer isDeleted; + +} diff --git a/src/main/java/com/youlai/boot/module/form/model/entity/FormSnapshot.java b/src/main/java/com/youlai/boot/module/form/model/entity/FormSnapshot.java new file mode 100644 index 00000000..211de018 --- /dev/null +++ b/src/main/java/com/youlai/boot/module/form/model/entity/FormSnapshot.java @@ -0,0 +1,34 @@ +package com.youlai.boot.module.form.model.entity; + +import com.baomidou.mybatisplus.annotation.TableName; +import com.youlai.boot.common.base.BaseEntity; +import lombok.Data; +import lombok.EqualsAndHashCode; + +/** + * 表单版本快照实体 + * + * @author Ray.Hao + * @since 4.9.0 + */ +@EqualsAndHashCode(callSuper = true) +@TableName("form_snapshot") +@Data +public class FormSnapshot extends BaseEntity { + + // 表单定义ID + private Long formId; + + // 版本号(发布时递增后的值) + private Integer version; + + // 表单规则快照(form-create rule 数组 JSON 字符串) + private String formJson; + + // 表单全局配置快照 JSON 字符串 + private String optionsJson; + + // 逻辑删除标识(0未删除 1已删除) + private Integer isDeleted; + +} diff --git a/src/main/java/com/youlai/boot/module/form/model/form/FormAiGenerateForm.java b/src/main/java/com/youlai/boot/module/form/model/form/FormAiGenerateForm.java new file mode 100644 index 00000000..bc63a4d7 --- /dev/null +++ b/src/main/java/com/youlai/boot/module/form/model/form/FormAiGenerateForm.java @@ -0,0 +1,20 @@ +package com.youlai.boot.module.form.model.form; + +import io.swagger.v3.oas.annotations.media.Schema; +import jakarta.validation.constraints.NotBlank; +import lombok.Data; + +/** + * AI 生成表单入参 + * + * @author Ray.Hao + * @since 0.1.0 + */ +@Schema(description = "AI 生成表单入参") +@Data +public class FormAiGenerateForm { + + @Schema(description = "表单需求描述", example = "请假申请:姓名、请假类型、起止日期、请假事由(必填)、附件") + @NotBlank(message = "需求描述不能为空") + private String description; +} diff --git a/src/main/java/com/youlai/boot/module/form/model/form/FormDefinitionForm.java b/src/main/java/com/youlai/boot/module/form/model/form/FormDefinitionForm.java new file mode 100644 index 00000000..fbe7f06b --- /dev/null +++ b/src/main/java/com/youlai/boot/module/form/model/form/FormDefinitionForm.java @@ -0,0 +1,50 @@ +package com.youlai.boot.module.form.model.form; + +import io.swagger.v3.oas.annotations.media.Schema; +import jakarta.validation.constraints.NotBlank; +import jakarta.validation.constraints.Pattern; +import jakarta.validation.constraints.Size; +import lombok.Data; + +/** + * 表单定义表单对象 + * + * @author Ray.Hao + * @since 4.9.0 + */ +@Schema(description = "表单定义") +@Data +public class FormDefinitionForm { + + @Schema(description = "表单ID", example = "1") + private Long id; + + @Schema(description = "表单唯一标识(创建后不可修改)", example = "employee_onboarding") + @NotBlank(message = "表单标识不能为空") + @Size(max = 64, message = "表单标识长度不能超过64个字符") + @Pattern(regexp = "^[a-z][a-z0-9_]*$", message = "表单标识须以小写字母开头,仅含小写字母、数字、下划线") + private String formKey; + + @Schema(description = "表单名称", example = "新员工入职信息采集") + @NotBlank(message = "表单名称不能为空") + @Size(max = 100, message = "表单名称长度不能超过100个字符") + private String formName; + + @Schema(description = "表单描述") + @Size(max = 255, message = "表单描述长度不能超过255个字符") + private String description; + + @Schema(description = "表单规则(form-create rule 数组 JSON 字符串,由设计器产出)") + private String formJson; + + @Schema(description = "表单全局配置 JSON 字符串") + private String optionsJson; + + @Schema(description = "是否允许匿名公开访问(0否 1是),公开访问总开关") + private Integer isPublic; + + @Schema(description = "表单类型(normal通用表单 workflow工作流表单,缺省normal)", example = "normal") + @Pattern(regexp = "^(normal|workflow)$", message = "表单类型不合法") + private String category; + +} diff --git a/src/main/java/com/youlai/boot/module/form/model/form/FormMenuForm.java b/src/main/java/com/youlai/boot/module/form/model/form/FormMenuForm.java new file mode 100644 index 00000000..f7c8df4c --- /dev/null +++ b/src/main/java/com/youlai/boot/module/form/model/form/FormMenuForm.java @@ -0,0 +1,31 @@ +package com.youlai.boot.module.form.model.form; + +import io.swagger.v3.oas.annotations.media.Schema; +import jakarta.validation.constraints.NotBlank; +import jakarta.validation.constraints.Size; +import lombok.Data; + +import java.util.List; + +/** + * 表单菜单发布表单对象(发布向导"入口配置"步骤提交) + * + * @author Ray.Hao + * @since 4.9.0 + */ +@Schema(description = "表单菜单发布对象") +@Data +public class FormMenuForm { + + @Schema(description = "菜单名称(侧边栏展示)", example = "入职信息采集") + @NotBlank(message = "菜单名称不能为空") + @Size(max = 50, message = "菜单名称长度不能超过50个字符") + private String menuName; + + @Schema(description = "上级菜单ID(须为目录类型;为空时自动使用/创建默认目录\"表单中心\")", example = "11") + private Long parentId; + + @Schema(description = "可见角色ID列表(ROOT 角色无需授权,天然全量可见)") + private List roleIds; + +} diff --git a/src/main/java/com/youlai/boot/module/form/model/query/FormDataPageQuery.java b/src/main/java/com/youlai/boot/module/form/model/query/FormDataPageQuery.java new file mode 100644 index 00000000..577a3c37 --- /dev/null +++ b/src/main/java/com/youlai/boot/module/form/model/query/FormDataPageQuery.java @@ -0,0 +1,19 @@ +package com.youlai.boot.module.form.model.query; + +import com.youlai.boot.common.base.BaseQuery; +import io.swagger.v3.oas.annotations.media.Schema; +import lombok.Data; +import lombok.EqualsAndHashCode; + +/** + * 表单数据分页查询对象 + * + * @author Ray.Hao + * @since 4.9.0 + */ +@Data +@EqualsAndHashCode(callSuper = false) +@Schema(description = "表单数据分页查询对象") +public class FormDataPageQuery extends BaseQuery { + +} diff --git a/src/main/java/com/youlai/boot/module/form/model/query/FormDefinitionPageQuery.java b/src/main/java/com/youlai/boot/module/form/model/query/FormDefinitionPageQuery.java new file mode 100644 index 00000000..4f00d428 --- /dev/null +++ b/src/main/java/com/youlai/boot/module/form/model/query/FormDefinitionPageQuery.java @@ -0,0 +1,28 @@ +package com.youlai.boot.module.form.model.query; + +import com.youlai.boot.common.base.BaseQuery; +import io.swagger.v3.oas.annotations.media.Schema; +import lombok.Data; +import lombok.EqualsAndHashCode; + +/** + * 表单定义分页查询对象 + * + * @author Ray.Hao + * @since 4.9.0 + */ +@Data +@EqualsAndHashCode(callSuper = false) +@Schema(description = "表单定义分页查询对象") +public class FormDefinitionPageQuery extends BaseQuery { + + @Schema(description = "关键字(表单名称/标识)") + private String keywords; + + @Schema(description = "状态(0草稿 1已发布 -1已停用)") + private Integer status; + + @Schema(description = "表单类型(normal通用表单 workflow审批表单)") + private String category; + +} diff --git a/src/main/java/com/youlai/boot/module/form/model/vo/FormDataVO.java b/src/main/java/com/youlai/boot/module/form/model/vo/FormDataVO.java new file mode 100644 index 00000000..1496cd0d --- /dev/null +++ b/src/main/java/com/youlai/boot/module/form/model/vo/FormDataVO.java @@ -0,0 +1,46 @@ +package com.youlai.boot.module.form.model.vo; + +import com.fasterxml.jackson.annotation.JsonFormat; +import io.swagger.v3.oas.annotations.media.Schema; +import lombok.Getter; +import lombok.Setter; + +import java.time.LocalDateTime; + +/** + * 表单数据VO(分页行与详情回显共用:数据只读,无独立表单对象) + * + * @author Ray.Hao + * @since 4.9.0 + */ +@Schema(description = "表单数据对象") +@Getter +@Setter +public class FormDataVO { + + @Schema(description = "数据ID") + private Long id; + + @Schema(description = "表单版本(提交时快照)") + private Integer formVersion; + + @Schema(description = "表单数据(field -> value 映射的 JSON 字符串)") + private String dataJson; + + @Schema(description = "回显规则(提交时版本的快照,严格回显用;仅详情接口填充)") + private String formJson; + + @Schema(description = "回显全局配置(提交时版本的快照;仅详情接口填充)") + private String optionsJson; + + @Schema(description = "提交人ID(匿名提交为空)") + private Long createBy; + + @Schema(description = "提交人昵称(匿名提交为空)") + private String createByName; + + @Schema(description = "提交时间") + @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8") + private LocalDateTime createTime; + +} diff --git a/src/main/java/com/youlai/boot/module/form/model/vo/FormDefinitionPageVO.java b/src/main/java/com/youlai/boot/module/form/model/vo/FormDefinitionPageVO.java new file mode 100644 index 00000000..2c393075 --- /dev/null +++ b/src/main/java/com/youlai/boot/module/form/model/vo/FormDefinitionPageVO.java @@ -0,0 +1,47 @@ +package com.youlai.boot.module.form.model.vo; + +import io.swagger.v3.oas.annotations.media.Schema; +import lombok.Getter; +import lombok.Setter; + +import java.time.LocalDateTime; + +/** + * 表单定义分页VO + * + * @author Ray.Hao + * @since 4.9.0 + */ +@Schema(description = "表单定义分页对象") +@Getter +@Setter +public class FormDefinitionPageVO { + + @Schema(description = "表单ID") + private Long id; + + @Schema(description = "表单唯一标识") + private String formKey; + + @Schema(description = "表单名称") + private String formName; + + @Schema(description = "表单描述") + private String description; + + @Schema(description = "状态(0草稿 1已发布 -1已停用)") + private Integer status; + + @Schema(description = "版本号") + private Integer version; + + @Schema(description = "是否允许匿名公开访问(0否 1是)") + private Integer isPublic; + + @Schema(description = "表单类型(normal通用表单 workflow审批表单)") + private String category; + + @Schema(description = "创建时间") + private LocalDateTime createTime; + +} diff --git a/src/main/java/com/youlai/boot/module/form/model/vo/FormMenuVO.java b/src/main/java/com/youlai/boot/module/form/model/vo/FormMenuVO.java new file mode 100644 index 00000000..b1de85d9 --- /dev/null +++ b/src/main/java/com/youlai/boot/module/form/model/vo/FormMenuVO.java @@ -0,0 +1,32 @@ +package com.youlai.boot.module.form.model.vo; + +import io.swagger.v3.oas.annotations.media.Schema; +import lombok.Getter; +import lombok.Setter; + +import java.util.List; + +/** + * 表单菜单配置VO(发布向导回显已生成的菜单) + * + * @author Ray.Hao + * @since 4.9.0 + */ +@Schema(description = "表单菜单配置对象") +@Getter +@Setter +public class FormMenuVO { + + @Schema(description = "菜单ID") + private Long menuId; + + @Schema(description = "菜单名称") + private String menuName; + + @Schema(description = "上级菜单ID") + private Long parentId; + + @Schema(description = "可见角色ID列表") + private List roleIds; + +} diff --git a/src/main/java/com/youlai/boot/module/form/model/vo/FormRenderVO.java b/src/main/java/com/youlai/boot/module/form/model/vo/FormRenderVO.java new file mode 100644 index 00000000..5ef35561 --- /dev/null +++ b/src/main/java/com/youlai/boot/module/form/model/vo/FormRenderVO.java @@ -0,0 +1,33 @@ +package com.youlai.boot.module.form.model.vo; + +import io.swagger.v3.oas.annotations.media.Schema; +import lombok.Getter; +import lombok.Setter; + +/** + * 表单渲染VO(渲染端按 formKey 加载的已发布规则) + * + * @author Ray.Hao + * @since 4.9.0 + */ +@Schema(description = "表单渲染对象") +@Getter +@Setter +public class FormRenderVO { + + @Schema(description = "表单唯一标识") + private String formKey; + + @Schema(description = "表单名称") + private String formName; + + @Schema(description = "表单版本号") + private Integer version; + + @Schema(description = "表单规则(form-create rule 数组 JSON 字符串)") + private String formJson; + + @Schema(description = "表单全局配置 JSON 字符串") + private String optionsJson; + +} diff --git a/src/main/java/com/youlai/boot/module/form/service/FormDataService.java b/src/main/java/com/youlai/boot/module/form/service/FormDataService.java new file mode 100644 index 00000000..437844ec --- /dev/null +++ b/src/main/java/com/youlai/boot/module/form/service/FormDataService.java @@ -0,0 +1,77 @@ +package com.youlai.boot.module.form.service; + +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; +import com.youlai.boot.module.form.model.query.FormDataPageQuery; +import com.youlai.boot.module.form.model.vo.FormDataVO; + +import java.util.List; +import java.util.Map; + +/** + * 表单数据业务接口 + * + * @author Ray.Hao + * @since 4.9.0 + */ +public interface FormDataService { + + /** + * 提交表单数据(仅已发布表单可提交,提交时快照表单版本) + * + * @param formKey 表单唯一标识 + * @param data 表单数据(field -> value 映射) + * @return 是否提交成功 + */ + boolean saveFormData(String formKey, Map data); + + /** + * 提交表单数据并返回数据ID + * + * @param formKey 表单唯一标识 + * @param data 表单数据(field -> value 映射) + * @return 表单数据ID + */ + Long saveFormDataReturnId(String formKey, Map data); + + /** + * 匿名提交公开表单数据(公开分享链接入口) + * + * @param formKey 表单唯一标识 + * @param data 表单数据(field -> value 映射) + * @param ip 提交方 IP(限流维度) + * @return 是否提交成功 + */ + boolean savePublicFormData(String formKey, Map data, String ip); + + /** + * 表单数据分页列表 + * + * @param formKey 表单唯一标识 + * @param queryParams 查询参数 + * @return 表单数据分页列表 + */ + Page getFormDataPage(String formKey, FormDataPageQuery queryParams); + + /** + * 获取表单数据详情(只读回显) + * + * @param dataId 数据ID + * @return 表单数据详情 + */ + FormDataVO getFormDataDetail(Long dataId); + + /** + * 按表单标识删除全部提交数据(演示数据重置用) + * + * @param formKey 表单唯一标识 + */ + void removeByFormKey(String formKey); + + /** + * 批量删除表单数据 + * + * @param ids 数据ID列表 + */ + void removeFormData(List ids); + +} diff --git a/src/main/java/com/youlai/boot/module/form/service/FormDefinitionService.java b/src/main/java/com/youlai/boot/module/form/service/FormDefinitionService.java new file mode 100644 index 00000000..9b5f7080 --- /dev/null +++ b/src/main/java/com/youlai/boot/module/form/service/FormDefinitionService.java @@ -0,0 +1,143 @@ +package com.youlai.boot.module.form.service; + +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; +import com.youlai.boot.common.model.Option; +import com.youlai.boot.module.form.model.entity.FormDefinition; +import com.youlai.boot.module.form.model.form.FormDefinitionForm; +import com.youlai.boot.module.form.model.form.FormMenuForm; +import com.youlai.boot.module.form.model.query.FormDefinitionPageQuery; +import com.youlai.boot.module.form.model.vo.FormDefinitionPageVO; +import com.youlai.boot.module.form.model.vo.FormMenuVO; +import com.youlai.boot.module.form.model.vo.FormRenderVO; + +import java.util.List; + +/** + * 表单定义业务接口 + * + * @author Ray.Hao + * @since 4.9.0 + */ +public interface FormDefinitionService { + + /** + * 表单定义分页列表 + * + * @param queryParams 查询参数 + * @return 表单定义分页列表 + */ + Page getFormDefinitionPage(FormDefinitionPageQuery queryParams); + + /** + * 按主键查询表单定义(供模块内回退取规则等场景) + * + * @param id 表单ID + * @return 表单定义实体;不存在返回 null + */ + FormDefinition getFormDefinition(Long id); + + /** + * 获取表单定义表单数据(编辑回显) + * + * @param id 表单ID + * @return 表单定义表单数据 + */ + FormDefinitionForm getFormDefinitionForm(Long id); + + /** + * 新增表单定义(初始为草稿态) + * + * @param formData 表单定义表单数据 + * @return 是否新增成功 + */ + boolean saveFormDefinition(FormDefinitionForm formData); + + /** + * 修改表单定义 + * + * @param id 表单ID + * @param formData 表单定义表单数据 + * @return 是否修改成功 + */ + boolean updateFormDefinition(Long id, FormDefinitionForm formData); + + /** + * 批量删除表单定义 + * + * @param ids 表单ID列表 + */ + void removeFormDefinition(List ids); + + /** + * 发布表单(版本号+1,固化版本快照,刷新渲染缓存) + * + * @param id 表单ID + * @return 是否发布成功 + */ + boolean publishFormDefinition(Long id); + + /** + * 停用表单(清渲染缓存,已发出去的入口立即失效) + * + * @param id 表单ID + * @return 是否停用成功 + */ + boolean disableFormDefinition(Long id); + + /** + * 按 formKey 获取已发布表单的渲染规则(Redis 缓存) + * + * @param formKey 表单唯一标识 + * @return 表单渲染数据 + */ + FormRenderVO getFormRender(String formKey); + + /** + * 按 formKey 获取公开表单的渲染规则(匿名接口) + * + * @param formKey 表单唯一标识 + * @return 表单渲染数据 + */ + FormRenderVO getPublicFormRender(String formKey); + + /** + * 按 formKey 查询表单定义(任意状态:已停用表单的历史数据仍可查看) + * + * @param formKey 表单唯一标识 + * @return 表单定义实体 + */ + FormDefinition getByFormKey(String formKey); + + /** + * 生成表单访问菜单并授权可见角色(幂等:已生成时更新原菜单) + * + * @param formId 表单ID + * @param menuForm 菜单发布参数 + * @return 是否生成成功 + */ + boolean saveFormMenu(Long formId, FormMenuForm menuForm); + + /** + * 获取表单已生成的菜单配置(发布向导回显) + * + * @param formId 表单ID + * @return 菜单配置;未生成过返回 null + */ + FormMenuVO getFormMenu(Long formId); + + /** + * 审批表单下拉选项(供工作流设计器绑定表单) + * + * @return 审批表单下拉选项列表 + */ + List> listWorkflowFormOptions(); + + /** + * 用 AI 把需求描述转成 form-create 规则,产出经结构校验后才返回 + * + * @param description 需求描述 + * @return 通过结构校验的 form-create rule JSON 字符串 + */ + String aiGenerateRule(String description); + +} diff --git a/src/main/java/com/youlai/boot/module/form/service/impl/FormDataServiceImpl.java b/src/main/java/com/youlai/boot/module/form/service/impl/FormDataServiceImpl.java new file mode 100644 index 00000000..7c144fa1 --- /dev/null +++ b/src/main/java/com/youlai/boot/module/form/service/impl/FormDataServiceImpl.java @@ -0,0 +1,224 @@ +package com.youlai.boot.module.form.service.impl; + +import cn.hutool.core.util.StrUtil; +import cn.hutool.json.JSONUtil; +import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; +import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; +import com.youlai.boot.common.constant.RedisConstants; +import com.youlai.boot.common.exception.BusinessException; +import com.youlai.boot.module.form.enums.FormStatusEnum; +import com.youlai.boot.module.form.mapper.FormDataMapper; +import com.youlai.boot.module.form.mapper.FormSnapshotMapper; +import com.youlai.boot.module.form.model.entity.FormData; +import com.youlai.boot.module.form.model.entity.FormDefinition; +import com.youlai.boot.module.form.model.entity.FormSnapshot; +import com.youlai.boot.module.form.model.query.FormDataPageQuery; +import com.youlai.boot.module.form.model.vo.FormDataVO; +import com.youlai.boot.module.form.service.FormDataService; +import com.youlai.boot.module.form.service.FormDefinitionService; +import com.youlai.boot.module.form.util.FormRuleValidator; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.data.redis.core.RedisTemplate; +import org.springframework.stereotype.Service; + +import java.time.Duration; +import java.util.List; +import java.util.Map; + +/** + * 表单数据业务实现类 + * + * @author Ray.Hao + * @since 4.9.0 + */ +@Service +@RequiredArgsConstructor +@Slf4j +public class FormDataServiceImpl extends ServiceImpl implements FormDataService { + + private final FormDefinitionService formDefinitionService; + private final FormSnapshotMapper formSnapshotMapper; + private final RedisTemplate redisTemplate; + + // 公开表单单 IP 提交上限(次/分钟):匿名接口防刷阈值 + private static final int PUBLIC_SUBMIT_LIMIT = 10; + + // 公开表单限流窗口:1 分钟 + private static final Duration PUBLIC_SUBMIT_WINDOW = Duration.ofMinutes(1); + + /** + * 提交表单数据 + * + * @param formKey 表单唯一标识 + * @param data 表单数据(field -> value 映射) + */ + @Override + public boolean saveFormData(String formKey, Map data) { + return this.saveFormDataReturnId(formKey, data) != null; + } + + /** + * 提交表单数据并返回数据ID + * + * @param formKey 表单唯一标识 + * @param data 表单数据(field -> value 映射) + */ + @Override + public Long saveFormDataReturnId(String formKey, Map data) { + FormDefinition form = formDefinitionService.getByFormKey(formKey); + if (!FormStatusEnum.PUBLISHED.getValue().equals(form.getStatus())) { + throw new BusinessException("表单未发布或已停用"); + } + return this.persistFormData(form, data); + } + + /** + * 匿名提交公开表单数据 + * + * @param formKey 表单唯一标识 + * @param data 表单数据(field -> value 映射) + * @param ip 提交方 IP(限流维度) + */ + @Override + public boolean savePublicFormData(String formKey, Map data, String ip) { + FormDefinition form = formDefinitionService.getByFormKey(formKey); + if (!FormStatusEnum.PUBLISHED.getValue().equals(form.getStatus()) + || !Integer.valueOf(1).equals(form.getIsPublic())) { + throw new BusinessException("表单不存在或未开放公开访问"); + } + checkPublicSubmitLimit(formKey, ip); + log.info("公开表单匿名提交 formKey={} ip={}", formKey, ip); + return this.persistFormData(form, data) != null; + } + + /** + * 数据落库(登录/匿名提交共用) + * + * @param form 表单定义 + * @param data 提交数据 + * @return 数据ID(落库失败为 null) + */ + private Long persistFormData(FormDefinition form, Map data) { + Map filteredData = FormRuleValidator.validateAndFilter(form.getFormJson(), data); + + FormData entity = new FormData(); + entity.setFormId(form.getId()); + entity.setFormVersion(form.getVersion()); + entity.setDataJson(JSONUtil.toJsonStr(filteredData)); + return this.save(entity) ? entity.getId() : null; + } + + /** + * 公开表单按 formKey + IP 限流(固定窗口计数) + * + * @param formKey 表单唯一标识 + * @param ip 提交方 IP + */ + private void checkPublicSubmitLimit(String formKey, String ip) { + String key = StrUtil.format(RedisConstants.Form.PUBLIC_SUBMIT_COUNT, formKey, ip); + try { + Long count = redisTemplate.opsForValue().increment(key); + if (count != null) { + // 首次计数时设置过期,窗口结束后自动清零 + if (count == 1) { + redisTemplate.expire(key, PUBLIC_SUBMIT_WINDOW); + } + if (count > PUBLIC_SUBMIT_LIMIT) { + throw new BusinessException("提交过于频繁,请稍后再试"); + } + } + } catch (BusinessException e) { + throw e; + } catch (Exception e) { + log.warn("公开表单限流 Redis 异常,Fail-Open 放行 formKey={} ip={}", formKey, ip, e); + } + } + + /** + * 表单数据分页列表 + * + * @param formKey 表单唯一标识 + * @param queryParams 查询参数 + */ + @Override + public Page getFormDataPage(String formKey, FormDataPageQuery queryParams) { + FormDefinition form = formDefinitionService.getByFormKey(formKey); + int pageNum = queryParams.getPageNum(); + int pageSize = queryParams.getPageSize(); + return this.baseMapper.getFormDataPage(new Page<>(pageNum, pageSize), form.getId(), queryParams); + } + + /** + * 获取表单数据详情(只读回显) + * + * @param dataId 数据ID + */ + @Override + public FormDataVO getFormDataDetail(Long dataId) { + FormData entity = this.getById(dataId); + if (entity == null) { + return null; + } + FormDataVO vo = new FormDataVO(); + vo.setId(entity.getId()); + vo.setFormVersion(entity.getFormVersion()); + vo.setDataJson(entity.getDataJson()); + vo.setCreateBy(entity.getCreateBy()); + vo.setCreateTime(entity.getCreateTime()); + this.fillRuleSnapshot(vo, entity.getFormId(), entity.getFormVersion()); + return vo; + } + + /** + * 填充回显规则:命中版本快照用快照规则,否则回退当前定义 + * + * @param vo 数据详情 VO + * @param formId 表单定义ID + * @param version 提交时版本 + */ + private void fillRuleSnapshot(FormDataVO vo, Long formId, Integer version) { + FormSnapshot snapshot = formSnapshotMapper.selectOne(new LambdaQueryWrapper() + .eq(FormSnapshot::getFormId, formId) + .eq(FormSnapshot::getVersion, version) + .last("LIMIT 1") + ); + if (snapshot != null) { + vo.setFormJson(snapshot.getFormJson()); + vo.setOptionsJson(snapshot.getOptionsJson()); + return; + } + FormDefinition form = formDefinitionService.getFormDefinition(formId); + if (form != null) { + vo.setFormJson(form.getFormJson()); + vo.setOptionsJson(form.getOptionsJson()); + } + } + + /** + * 批量删除表单数据 + * + * @param ids 数据ID列表 + */ + @Override + public void removeFormData(List ids) { + this.removeByIds(ids); + } + + /** + * 按表单标识删除全部提交数据(演示数据重置用) + * + * @param formKey 表单唯一标识 + */ + @Override + public void removeByFormKey(String formKey) { + FormDefinition form = formDefinitionService.getByFormKey(formKey); + if (form == null) { + return; + } + this.remove(new LambdaQueryWrapper() + .eq(FormData::getFormId, form.getId())); + } + +} diff --git a/src/main/java/com/youlai/boot/module/form/service/impl/FormDefinitionServiceImpl.java b/src/main/java/com/youlai/boot/module/form/service/impl/FormDefinitionServiceImpl.java new file mode 100644 index 00000000..9a0171cd --- /dev/null +++ b/src/main/java/com/youlai/boot/module/form/service/impl/FormDefinitionServiceImpl.java @@ -0,0 +1,608 @@ +package com.youlai.boot.module.form.service.impl; + +import cn.hutool.core.bean.BeanUtil; +import cn.hutool.core.collection.CollectionUtil; +import cn.hutool.core.lang.Assert; +import cn.hutool.core.util.StrUtil; +import cn.hutool.json.JSONUtil; +import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; +import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper; +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; +import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; +import com.youlai.boot.common.constant.RedisConstants; +import com.youlai.boot.common.exception.BusinessException; +import com.youlai.boot.common.model.KeyValue; +import com.youlai.boot.common.model.Option; +import com.youlai.boot.module.form.converter.FormConverter; +import com.youlai.boot.module.form.enums.FormCategoryEnum; +import com.youlai.boot.module.form.enums.FormStatusEnum; +import com.youlai.boot.module.form.mapper.FormDataMapper; +import com.youlai.boot.module.form.mapper.FormDefinitionMapper; +import com.youlai.boot.module.form.mapper.FormSnapshotMapper; +import com.youlai.boot.module.form.model.entity.FormData; +import com.youlai.boot.module.form.model.entity.FormDefinition; +import com.youlai.boot.module.form.model.entity.FormSnapshot; +import com.youlai.boot.module.form.model.form.FormDefinitionForm; +import com.youlai.boot.module.form.model.form.FormMenuForm; +import com.youlai.boot.module.form.model.query.FormDefinitionPageQuery; +import com.youlai.boot.module.form.model.vo.FormDefinitionPageVO; +import com.youlai.boot.module.form.model.vo.FormMenuVO; +import com.youlai.boot.module.form.model.vo.FormRenderVO; +import com.youlai.boot.module.form.service.FormDefinitionService; +import com.youlai.boot.module.form.util.FormRuleValidator; +import com.youlai.boot.module.workflow.service.WorkflowModelService; +import com.youlai.boot.support.ai.AiChatService; +import com.youlai.boot.support.ai.PromptLoader; +import com.youlai.boot.system.enums.MenuTypeEnum; +import com.youlai.boot.system.model.entity.Menu; +import com.youlai.boot.system.model.entity.RoleMenu; +import com.youlai.boot.system.model.form.MenuForm; +import com.youlai.boot.system.service.MenuService; +import com.youlai.boot.system.service.RoleMenuService; +import lombok.RequiredArgsConstructor; +import org.springframework.beans.factory.ObjectProvider; +import org.springframework.data.redis.core.RedisTemplate; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +import java.util.Arrays; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.concurrent.TimeUnit; +import java.util.stream.Collectors; + +/** + * 表单定义业务实现类 + * + * @author Ray.Hao + * @since 4.9.0 + */ +@Service +@RequiredArgsConstructor +public class FormDefinitionServiceImpl extends ServiceImpl implements FormDefinitionService { + + // 系统提示词名称,对应 resources/prompts 下的相对路径 + private static final String SYSTEM_PROMPT_PATH = "form/system.md"; + + private final FormConverter formConverter; + private final RedisTemplate redisTemplate; + private final MenuService menuService; + private final RoleMenuService roleMenuService; + private final FormSnapshotMapper formSnapshotMapper; + private final FormDataMapper formDataMapper; + private final ObjectProvider workflowModelServiceProvider; + private final AiChatService aiChatService; + private final PromptLoader promptLoader; + + // 默认挂载目录名称:发布向导未显式选目录时自动使用/创建 + private static final String DEFAULT_CATALOG_NAME = "表单中心"; + + // 表单管理目录名称(顶级,dynamic-form.sql 预置):"表单中心"默认挂载其下,顶级入口聚合 + private static final String FORM_ADMIN_CATALOG_NAME = "动态表单"; + + // 渲染缓存兜底 TTL:事件驱动清缓存外再设过期,防 DB 更新与删缓存间应用重启导致脏缓存永续 + private static final long RENDER_CACHE_TTL_MINUTES = 30; + + /** + * 表单定义分页列表 + * + * @param queryParams 查询参数 + */ + @Override + public Page getFormDefinitionPage(FormDefinitionPageQuery queryParams) { + int pageNum = queryParams.getPageNum(); + int pageSize = queryParams.getPageSize(); + return this.baseMapper.getFormDefinitionPage(new Page<>(pageNum, pageSize), queryParams); + } + + /** + * 按主键查询表单定义 + * + * @param id 表单ID + */ + @Override + public FormDefinition getFormDefinition(Long id) { + return this.getById(id); + } + + /** + * 获取表单定义表单数据 + * + * @param id 表单ID + */ + @Override + public FormDefinitionForm getFormDefinitionForm(Long id) { + FormDefinition entity = this.getById(id); + if (entity == null) { + throw new BusinessException("表单不存在"); + } + return formConverter.toForm(entity); + } + + /** + * 新增表单定义 + * + * @param formData 表单定义表单数据 + */ + @Override + public boolean saveFormDefinition(FormDefinitionForm formData) { + // 校验 formKey 唯一(逻辑删除查询默认过滤,同 key 删除后可重建) + String formKey = formData.getFormKey(); + long count = this.count(new LambdaQueryWrapper() + .eq(FormDefinition::getFormKey, formKey) + ); + Assert.isTrue(count == 0, "表单标识已存在"); + + FormDefinition entity = formConverter.toEntity(formData); + // 新表单初始为草稿态;规则未设计时空数组占位,设计器打开为空白画布 + entity.setStatus(FormStatusEnum.DRAFT.getValue()); + entity.setVersion(1); + // 类型缺省为普通表单,须显式选择审批表单才可被工作流绑定 + if (StrUtil.isBlank(entity.getCategory())) { + entity.setCategory(FormCategoryEnum.NORMAL.getValue()); + } + if (entity.getFormJson() == null) { + entity.setFormJson("[]"); + } + return this.save(entity); + } + + /** + * 修改表单定义 + * + * @param id 表单ID + * @param formData 表单定义表单数据 + */ + @Override + public boolean updateFormDefinition(Long id, FormDefinitionForm formData) { + FormDefinition entity = this.getById(id); + if (entity == null) { + throw new BusinessException("表单不存在"); + } + // formKey 为 null 表示部分更新未携带该字段(如设计器仅保存规则),不视为修改; + // 显式传入不同标识才拒绝,防止已发布表单的业务编码被越权变更 + if (formData.getFormKey() != null && !formData.getFormKey().equals(entity.getFormKey())) { + throw new BusinessException("表单标识创建后不可修改"); + } + + FormDefinition updateEntity = new FormDefinition(); + updateEntity.setId(id); + // 仅草稿态允许修改元数据 + if (FormStatusEnum.DRAFT.getValue().equals(entity.getStatus())) { + updateEntity.setFormName(formData.getFormName()); + updateEntity.setDescription(formData.getDescription()); + // 类型亦属元数据:草稿态可改,已发布后固定(防止流程绑定后类型被改走导致流程表单失联) + updateEntity.setCategory(formData.getCategory()); + } + updateEntity.setFormJson(formData.getFormJson()); + updateEntity.setOptionsJson(formData.getOptionsJson()); + // 公开开关是访问控制而非身份元数据,任意状态可切换(发布向导/编辑弹窗均可操作) + updateEntity.setIsPublic(formData.getIsPublic()); + + boolean result = this.updateById(updateEntity); + // 已发布表单规则/公开开关变更直接影响渲染端,需清缓存即时生效 + if (result && FormStatusEnum.PUBLISHED.getValue().equals(entity.getStatus())) { + this.evictRenderCache(entity.getFormKey()); + } + return result; + } + + /** + * 批量删除表单定义 + * + * @param ids 表单ID列表 + */ + @Override + @Transactional(rollbackFor = Exception.class) + public void removeFormDefinition(List ids) { + List forms = this.listByIds(ids); + this.checkProcessReferences(forms); + this.removeByIds(ids); + for (FormDefinition form : forms) { + // 级联删除已生成的访问菜单(deleteMenu 内部同步清理其角色授权并刷新权限缓存) + if (form.getMenuId() != null) { + menuService.deleteMenu(form.getMenuId()); + } + // 同步清理提交数据与版本快照,防止孤儿数据与死链接 + formDataMapper.delete(new LambdaQueryWrapper() + .eq(FormData::getFormId, form.getId())); + formSnapshotMapper.delete(new LambdaQueryWrapper() + .eq(FormSnapshot::getFormId, form.getId())); + // 已发布表单的渲染缓存一并清除,防止删除后仍可渲染 + if (FormStatusEnum.PUBLISHED.getValue().equals(form.getStatus())) { + this.evictRenderCache(form.getFormKey()); + } + } + } + + /** + * 校验表单是否被流程引用 + * + * @param forms 待删除表单 + */ + private void checkProcessReferences(List forms) { + // 工作流未启用时无流程服务,跳过校验 + WorkflowModelService workflowModelService = workflowModelServiceProvider.getIfAvailable(); + if (workflowModelService == null || forms.isEmpty()) { + return; + } + Map> references = workflowModelService.getFormReferences( + forms.stream().map(FormDefinition::getFormKey).collect(Collectors.toSet())); + List blocked = forms.stream() + .filter(form -> references.containsKey(form.getFormKey())) + .map(form -> StrUtil.format("表单【{}】被流程【{}】引用", form.getFormName(), + String.join("、", references.get(form.getFormKey())))) + .toList(); + if (!blocked.isEmpty()) { + throw new BusinessException(String.join(";", blocked) + ",请先解除流程绑定后删除"); + } + } + + /** + * 发布表单 + * + * @param id 表单ID + */ + @Override + @Transactional(rollbackFor = Exception.class) + public boolean publishFormDefinition(Long id) { + FormDefinition entity = this.getById(id); + if (entity == null) { + throw new BusinessException("表单不存在"); + } + boolean result = this.update(new LambdaUpdateWrapper() + .eq(FormDefinition::getId, id) + .set(FormDefinition::getStatus, FormStatusEnum.PUBLISHED.getValue()) + .setSql("version = version + 1") + ); + if (result) { + FormDefinition published = this.getById(id); + // 固化版本快照:数据回显按提交时版本加载,防止规则变更(字段删除/改名)导致历史数据漂移 + FormSnapshot snapshot = new FormSnapshot(); + snapshot.setFormId(id); + snapshot.setVersion(published.getVersion()); + snapshot.setFormJson(published.getFormJson()); + snapshot.setOptionsJson(published.getOptionsJson()); + formSnapshotMapper.insert(snapshot); + this.evictRenderCache(published.getFormKey()); + } + return result; + } + + /** + * 停用表单 + * + * @param id 表单ID + */ + @Override + public boolean disableFormDefinition(Long id) { + FormDefinition entity = this.getById(id); + if (entity == null) { + throw new BusinessException("表单不存在"); + } + FormDefinition updateEntity = new FormDefinition(); + updateEntity.setId(id); + updateEntity.setStatus(FormStatusEnum.DISABLED.getValue()); + boolean result = this.updateById(updateEntity); + if (result) { + this.evictRenderCache(entity.getFormKey()); + } + return result; + } + + /** + * 按 formKey 获取已发布表单的渲染规则 + * + * @param formKey 表单唯一标识 + */ + @Override + public FormRenderVO getFormRender(String formKey) { + String cacheKey = StrUtil.format(RedisConstants.Form.RENDER_RULE, formKey); + Object cached = redisTemplate.opsForValue().get(cacheKey); + if (cached instanceof FormRenderVO renderVO) { + return renderVO; + } + if (cached != null) { + // Redis JSON 序列化读回为无类型 Map,转换为 VO + return BeanUtil.toBean(cached, FormRenderVO.class); + } + + FormDefinition entity = this.getOne(new LambdaQueryWrapper() + .eq(FormDefinition::getFormKey, formKey) + .eq(FormDefinition::getStatus, FormStatusEnum.PUBLISHED.getValue()) + .last("LIMIT 1") + ); + if (entity == null) { + throw new BusinessException("表单不存在或未发布"); + } + redisTemplate.opsForValue().set(cacheKey, toRenderVO(entity), RENDER_CACHE_TTL_MINUTES, TimeUnit.MINUTES); + return toRenderVO(entity); + } + + /** + * 清除表单渲染缓存 + * + * @param formKey 表单唯一标识 + */ + private void evictRenderCache(String formKey) { + redisTemplate.delete(StrUtil.format(RedisConstants.Form.RENDER_RULE, formKey)); + } + + /** + * 组装表单渲染 VO + * + * @param entity 表单定义实体 + */ + private FormRenderVO toRenderVO(FormDefinition entity) { + FormRenderVO renderVO = new FormRenderVO(); + renderVO.setFormKey(entity.getFormKey()); + renderVO.setFormName(entity.getFormName()); + renderVO.setVersion(entity.getVersion()); + renderVO.setFormJson(entity.getFormJson()); + renderVO.setOptionsJson(entity.getOptionsJson()); + return renderVO; + } + + /** + * 按 formKey 获取公开表单的渲染规则(匿名接口) + * + * @param formKey 表单唯一标识 + */ + @Override + public FormRenderVO getPublicFormRender(String formKey) { + FormDefinition entity = this.getOne(new LambdaQueryWrapper() + .eq(FormDefinition::getFormKey, formKey) + .eq(FormDefinition::getStatus, FormStatusEnum.PUBLISHED.getValue()) + .eq(FormDefinition::getIsPublic, 1) + .last("LIMIT 1") + ); + if (entity == null) { + throw new BusinessException("表单不存在或未开放公开访问"); + } + return toRenderVO(entity); + } + + /** + * 按 formKey 查询表单定义 + * + * @param formKey 表单唯一标识 + */ + @Override + public FormDefinition getByFormKey(String formKey) { + FormDefinition form = this.getOne(new LambdaQueryWrapper() + .eq(FormDefinition::getFormKey, formKey) + .last("LIMIT 1") + ); + if (form == null) { + throw new BusinessException("表单不存在"); + } + return form; + } + + /** + * 生成表单访问菜单并授权可见角色 + * + * @param formId 表单ID + * @param menuForm 菜单发布参数 + */ + @Override + @Transactional(rollbackFor = Exception.class) + public boolean saveFormMenu(Long formId, FormMenuForm menuForm) { + FormDefinition form = this.getById(formId); + if (form == null) { + throw new BusinessException("表单不存在"); + } + // 上级菜单必须为目录类型:挂到菜单/按钮下构树异常;根级菜单不套 Layout,得到无侧边栏的孤立页 + // parentId 为空 = 走默认目录"表单中心"(懒创建:首个表单发布时才建目录,避免空目录在侧边栏成点不开的孤菜单) + Menu parentMenu; + if (menuForm.getParentId() == null) { + parentMenu = this.ensureDefaultCatalog(); + } else { + parentMenu = menuService.getById(menuForm.getParentId()); + if (parentMenu == null) { + throw new BusinessException("上级菜单不存在"); + } + if (!MenuTypeEnum.CATALOG.getValue().equals(parentMenu.getType())) { + throw new BusinessException("上级菜单必须为目录类型"); + } + } + + // 组装菜单:类型 M,指向通用承载页;已生成过时携带原菜单ID走更新语义(幂等) + String routeName = "FormRender" + StrUtil.upperFirst(StrUtil.toCamelCase(form.getFormKey(), '_')); + MenuForm menuFormData = new MenuForm(); + menuFormData.setId(form.getMenuId()); + menuFormData.setParentId(parentMenu.getId()); + menuFormData.setName(menuForm.getMenuName()); + menuFormData.setType(MenuTypeEnum.MENU.getValue()); + menuFormData.setRouteName(routeName); + menuFormData.setRoutePath(form.getFormKey()); + menuFormData.setComponent("dynamic-form/render"); + menuFormData.setParams(List.of(new KeyValue("formKey", form.getFormKey()))); + menuFormData.setVisible(1); + menuFormData.setSort(1); + // keepAlive 不开启:多个表单菜单共用 render 组件,组件级缓存会导致切换表单时回显错乱 + boolean result = menuService.saveMenu(menuFormData); + if (!result) { + return false; + } + // saveMenu 内部 saveOrUpdate 不回写表单对象主键,按全局唯一路由名称反查菜单ID + Menu menu = menuService.getOne(new LambdaQueryWrapper() + .eq(Menu::getRouteName, routeName) + .last("LIMIT 1") + ); + + // 回写 menu_id:下次发布走更新语义,防重复生成菜单 + FormDefinition updateForm = new FormDefinition(); + updateForm.setId(formId); + updateForm.setMenuId(menu.getId()); + this.updateById(updateForm); + + // 追加式角色授权(沿 tree_path 补齐祖先目录) + this.assignMenuToRoles(menu.getId(), menuForm.getRoleIds()); + return true; + } + + /** + * 确保默认挂载目录"表单中心"存在,不存在则创建 + * + * @return 默认目录实体 + */ + private Menu ensureDefaultCatalog() { + // 已有"表单中心"目录(任意层级)直接复用:兼容旧环境顶级目录等历史生成位置 + Menu catalog = menuService.getOne(new LambdaQueryWrapper() + .eq(Menu::getName, DEFAULT_CATALOG_NAME) + .eq(Menu::getType, MenuTypeEnum.CATALOG.getValue()) + .last("LIMIT 1") + ); + if (catalog != null) { + return catalog; + } + Menu adminCatalog = menuService.getOne(new LambdaQueryWrapper() + .eq(Menu::getParentId, 0L) + .eq(Menu::getName, FORM_ADMIN_CATALOG_NAME) + .eq(Menu::getType, MenuTypeEnum.CATALOG.getValue()) + .last("LIMIT 1") + ); + // 挂"动态表单"下用相对路由段(父级 /dynamic-form + center);退化顶级时用绝对路径 + // 退化路径避开 /dynamic-form 前缀:与"动态表单"目录路由并存时会重复注册顶级路由 + boolean underAdminCatalog = adminCatalog != null; + + MenuForm menuFormData = new MenuForm(); + menuFormData.setParentId(underAdminCatalog ? adminCatalog.getId() : 0L); + menuFormData.setName(DEFAULT_CATALOG_NAME); + menuFormData.setType(MenuTypeEnum.CATALOG.getValue()); + menuFormData.setRoutePath(underAdminCatalog ? "center" : "/form-center"); + menuFormData.setComponent("Layout"); + menuFormData.setVisible(1); + menuFormData.setSort(5); + // EP 图标(前端永久可渲染),避免空/失效图标名导致菜单显示异常 + menuFormData.setIcon("el-icon-EditPen"); + menuService.saveMenu(menuFormData); + + // 目录类型保存时 routeName 被置空,按名称+类型回查 + Menu createdCatalog = menuService.getOne(new LambdaQueryWrapper() + .eq(Menu::getName, DEFAULT_CATALOG_NAME) + .eq(Menu::getType, MenuTypeEnum.CATALOG.getValue()) + .last("LIMIT 1") + ); + Assert.notNull(createdCatalog, "默认目录创建失败"); + return createdCatalog; + } + + /** + * 获取表单已生成的菜单配置 + * + * @param formId 表单ID + */ + @Override + public FormMenuVO getFormMenu(Long formId) { + FormDefinition form = this.getById(formId); + if (form == null || form.getMenuId() == null) { + return null; + } + Menu menu = menuService.getById(form.getMenuId()); + if (menu == null) { + return null; + } + FormMenuVO menuVO = new FormMenuVO(); + menuVO.setMenuId(menu.getId()); + menuVO.setMenuName(menu.getName()); + menuVO.setParentId(menu.getParentId()); + List roleMenus = roleMenuService.list(new LambdaQueryWrapper() + .eq(RoleMenu::getMenuId, menu.getId()) + ); + menuVO.setRoleIds(roleMenus.stream().map(RoleMenu::getRoleId).distinct().toList()); + return menuVO; + } + + /** + * 追加式角色授权:向角色授予菜单及 tree_path 祖先目录 + * + * @param menuId 菜单ID + * @param roleIds 角色ID列表 + */ + private void assignMenuToRoles(Long menuId, List roleIds) { + if (CollectionUtil.isEmpty(roleIds)) { + return; + } + // 授权集合 = 菜单本身 + tree_path 祖先目录(如 "0,11" → 补 11,根节点 0 排除) + Menu menu = menuService.getById(menuId); + Set menuIdsToGrant = new HashSet<>(); + menuIdsToGrant.add(menuId); + if (StrUtil.isNotBlank(menu.getTreePath())) { + Arrays.stream(menu.getTreePath().split(",")) + .map(String::trim) + .filter(StrUtil::isNotBlank) + .filter(id -> !"0".equals(id)) + .forEach(id -> menuIdsToGrant.add(Long.parseLong(id))); + } + + // 查询已有关联,仅补插缺失项 + List existing = roleMenuService.list(new LambdaQueryWrapper() + .in(RoleMenu::getRoleId, roleIds) + .in(RoleMenu::getMenuId, menuIdsToGrant) + ); + Set existingKeys = existing.stream() + .map(rm -> rm.getRoleId() + ":" + rm.getMenuId()) + .collect(Collectors.toSet()); + + List toInsert = roleIds.stream() + .flatMap(roleId -> menuIdsToGrant.stream() + .filter(grantMenuId -> !existingKeys.contains(roleId + ":" + grantMenuId)) + .map(grantMenuId -> new RoleMenu(roleId, grantMenuId)) + ) + .toList(); + if (CollectionUtil.isNotEmpty(toInsert)) { + roleMenuService.saveBatch(toInsert); + // 授权变化后刷新角色权限缓存 + roleMenuService.refreshRolePermsCache(); + } + } + + /** + * 审批表单下拉选项(供工作流设计器绑定表单) + * + * @return 审批表单下拉选项列表 + */ + @Override + public List> listWorkflowFormOptions() { + return this.list(new LambdaQueryWrapper() + .eq(FormDefinition::getCategory, FormCategoryEnum.WORKFLOW.getValue()) + .eq(FormDefinition::getStatus, FormStatusEnum.PUBLISHED.getValue()) + .select(FormDefinition::getFormKey, FormDefinition::getFormName) + .orderByAsc(FormDefinition::getCreateTime) + ).stream() + .map(form -> new Option<>(form.getFormKey(), form.getFormName())) + .toList(); + } + + //--------------------------------------------------- + // AI 辅助:未开启 AI 时调用返回业务异常 + //--------------------------------------------------- + + /** + * 用 AI 把需求描述转成 form-create 规则 + * + * @param description 需求描述 + * @return 通过结构校验的 form-create rule JSON 字符串 + */ + @Override + public String aiGenerateRule(String description) { + List> rules = aiChatService.chatJsonList( + promptLoader.get(SYSTEM_PROMPT_PATH), buildAiUserPrompt(description)); + return FormRuleValidator.validateRule(JSONUtil.toJsonStr(rules)); + } + + /** + * 构造用户提示词 + * + * @param description 需求描述 + * @return 用户提示词 + */ + private String buildAiUserPrompt(String description) { + return "需求描述:\n" + description; + } + +} diff --git a/src/main/java/com/youlai/boot/module/form/util/FormRuleValidator.java b/src/main/java/com/youlai/boot/module/form/util/FormRuleValidator.java new file mode 100644 index 00000000..afb4243f --- /dev/null +++ b/src/main/java/com/youlai/boot/module/form/util/FormRuleValidator.java @@ -0,0 +1,265 @@ +package com.youlai.boot.module.form.util; + +import cn.hutool.core.util.StrUtil; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.youlai.boot.common.exception.BusinessException; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; + +/** + * 表单规则校验器(后端基础校验 + 字段白名单) + * + * @author Ray.Hao + * @since 4.9.0 + */ +public final class FormRuleValidator { + + // Jackson 线程安全,静态复用 + private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper(); + + private FormRuleValidator() { + } + + /** + * 校验并过滤表单数据 + * + * @param formJson 表单规则(form-create rule 数组 JSON 字符串) + * @param data 提交数据(field -> value 映射) + * @return 白名单过滤后的数据(保持 rule 字段顺序) + */ + public static Map validateAndFilter(String formJson, Map data) { + JsonNode rules; + try { + rules = OBJECT_MAPPER.readTree(formJson); + } catch (Exception e) { + throw new BusinessException("表单规则解析失败"); + } + if (!rules.isArray()) { + throw new BusinessException("表单规则格式非法"); + } + + Map filtered = new LinkedHashMap<>(); + List errors = new ArrayList<>(); + walk(rules, data, filtered, errors); + if (!errors.isEmpty()) { + throw new BusinessException(String.join(";", errors)); + } + return filtered; + } + + /** + * 校验表单规则结构(AI 生成或外部导入的规则先过这一层) + * + * @param formJson 表单规则(form-create rule 数组 JSON 字符串) + * @return 规则原文,便于链式使用 + */ + public static String validateRule(String formJson) { + JsonNode rules; + try { + rules = OBJECT_MAPPER.readTree(formJson); + } catch (Exception e) { + throw new BusinessException("表单规则解析失败"); + } + if (!rules.isArray() || rules.isEmpty()) { + throw new BusinessException("表单规则格式非法:应为非空数组"); + } + checkNodes(rules); + return formJson; + } + + /** + * 递归校验规则节点:每个节点必须有 type,非容器节点必须有 field + * + * @param nodes 规则节点数组 + */ + private static void checkNodes(JsonNode nodes) { + for (JsonNode node : nodes) { + if (node == null || !node.isObject()) { + throw new BusinessException("表单规则格式非法:节点必须为对象"); + } + if (!node.path("type").isTextual()) { + throw new BusinessException("表单规则格式非法:节点缺少 type"); + } + JsonNode children = node.get("children"); + if (children != null && children.isArray() && !children.isEmpty()) { + checkNodes(children); + } else if (!node.path("field").isTextual()) { + throw new BusinessException("表单规则格式非法:字段节点缺少 field"); + } + } + } + + /** + * 解析规则里 field -> title 的映射(摘要、导出等场景把字段名换成中文标题) + * + * @param formJson 表单规则 + * @return field -> title 映射,规则为空或解析失败时返回空 Map + */ + public static Map resolveTitles(String formJson) { + Map titles = new LinkedHashMap<>(); + if (StrUtil.isBlank(formJson)) { + return titles; + } + try { + collectTitles(OBJECT_MAPPER.readTree(formJson), titles); + } catch (Exception ignored) { + return titles; + } + return titles; + } + + /** + * 递归收集 field 与 title + * + * @param nodes 规则节点数组 + * @param titles 映射结果(累积写入) + */ + private static void collectTitles(JsonNode nodes, Map titles) { + for (JsonNode node : nodes) { + if (node == null || !node.isObject()) { + continue; + } + JsonNode field = node.get("field"); + JsonNode title = node.get("title"); + if (field != null && field.isTextual() && title != null && title.isTextual()) { + titles.putIfAbsent(field.asText(), title.asText()); + } + JsonNode children = node.get("children"); + if (children != null && children.isArray()) { + collectTitles(children, titles); + } + } + } + + /** + * 递归遍历规则节点:布局容器(row/col)自身无 field,其 children 递归收集 + * + * @param nodes 规则节点数组 + * @param data 提交数据 + * @param filtered 白名单过滤结果(累积写入) + * @param errors 校验错误信息(累积写入) + */ + private static void walk(JsonNode nodes, Map data, + Map filtered, List errors) { + for (JsonNode node : nodes) { + if (node == null || !node.isObject()) { + continue; + } + JsonNode fieldNode = node.get("field"); + if (fieldNode != null && fieldNode.isTextual() && !fieldNode.asText().isEmpty()) { + String field = fieldNode.asText(); + // 字段白名单:rule 未声明的 field 直接丢弃 + if (data.containsKey(field)) { + filtered.put(field, data.get(field)); + } + validateField(node, field, data.get(field), errors); + } + JsonNode children = node.get("children"); + if (children != null && children.isArray()) { + walk(children, data, filtered, errors); + } + } + } + + /** + * 单字段校验:必填与基础类型 + * + * @param ruleNode 字段规则节点 + * @param field 字段名 + * @param value 提交值(可能为 null) + * @param errors 校验错误信息(累积写入) + */ + private static void validateField(JsonNode ruleNode, String field, Object value, List errors) { + JsonNode validateArray = ruleNode.get("validate"); + if (validateArray == null || !validateArray.isArray()) { + return; + } + String title = resolveTitle(ruleNode, field); + for (JsonNode validate : validateArray) { + // 必填:null/空串/空集合均视为未填写 + if (validate.path("required").asBoolean(false) && isEmpty(value)) { + errors.add(requiredMessage(validate, title)); + } + // 类型:仅值非空时校验,避免与 required 错误重复 + if (!isEmpty(value)) { + String type = validate.path("type").asText(""); + if (!checkType(type, value)) { + errors.add("「" + title + "」数据类型非法"); + } + } + } + } + + /** + * 解析字段标题(错误提示用),缺省回退字段名 + */ + private static String resolveTitle(JsonNode ruleNode, String field) { + JsonNode title = ruleNode.get("title"); + return title != null && title.isTextual() && !title.asText().isEmpty() ? title.asText() : field; + } + + /** + * 必填错误消息:优先取 rule validate 里配置的 message,缺省用通用文案 + */ + private static String requiredMessage(JsonNode validate, String title) { + JsonNode message = validate.get("message"); + return message != null && message.isTextual() && !message.asText().isEmpty() + ? message.asText() : "「" + title + "」不能为空"; + } + + /** + * 空值判定:null、空字符串、空集合 + * + * @param value 提交值 + */ + private static boolean isEmpty(Object value) { + if (value == null) { + return true; + } + if (value instanceof String str) { + return str.trim().isEmpty(); + } + return value instanceof Collection collection && collection.isEmpty(); + } + + /** + * 基础类型校验:number(数字或数字串)/ array(集合), + * string/date 等文本类型无可靠判据,不做强校验 + * + * @param type validate 规则声明的类型 + * @param value 提交值(非空) + */ + private static boolean checkType(String type, Object value) { + return switch (type) { + case "number", "integer", "float" -> isNumeric(value); + case "array" -> value instanceof Collection; + default -> true; + }; + } + + /** + * 数字判定:Number 实例或可解析为 double 的字符串 + * + * @param value 提交值(非空) + */ + private static boolean isNumeric(Object value) { + if (value instanceof Number) { + return true; + } + if (value instanceof String str) { + try { + Double.parseDouble(str.trim()); + return true; + } catch (NumberFormatException ignored) { + return false; + } + } + return false; + } + +} diff --git a/src/main/java/com/youlai/boot/module/workflow/config/ConditionalOnWorkflowEnabled.java b/src/main/java/com/youlai/boot/module/workflow/config/ConditionalOnWorkflowEnabled.java new file mode 100644 index 00000000..a2fd4e70 --- /dev/null +++ b/src/main/java/com/youlai/boot/module/workflow/config/ConditionalOnWorkflowEnabled.java @@ -0,0 +1,22 @@ +package com.youlai.boot.module.workflow.config; + +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; + +import org.springframework.boot.autoconfigure.condition.ConditionalOnBooleanProperty; + +/** + * 工作流启用条件 + * + * @author Ray.Hao + * @since 4.9.0 + */ +@Target({ElementType.TYPE, ElementType.METHOD}) +@Retention(RetentionPolicy.RUNTIME) +@Documented +@ConditionalOnBooleanProperty(prefix = "workflow", name = "enabled") +public @interface ConditionalOnWorkflowEnabled { +} diff --git a/src/main/java/com/youlai/boot/module/workflow/config/WorkflowEngineConfig.java b/src/main/java/com/youlai/boot/module/workflow/config/WorkflowEngineConfig.java new file mode 100644 index 00000000..0ea29e1f --- /dev/null +++ b/src/main/java/com/youlai/boot/module/workflow/config/WorkflowEngineConfig.java @@ -0,0 +1,39 @@ +package com.youlai.boot.module.workflow.config; + +import com.youlai.boot.module.workflow.listener.ProcessCompletedListener; +import org.flowable.common.engine.api.delegate.event.FlowableEventListener; +import org.flowable.spring.SpringProcessEngineConfiguration; +import org.flowable.spring.boot.EngineConfigurationConfigurer; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; + +import java.util.ArrayList; +import java.util.List; + +/** + * 工作流引擎配置 + * + * @author Ray.Hao + * @since 4.9.0 + */ +@ConditionalOnWorkflowEnabled +@Configuration(proxyBeanMethods = false) +public class WorkflowEngineConfig { + + /** + * 流程完成事件监听器登记到引擎全局(任意流程结束均派发,由监听器按定义 Key 路由业务后处理) + */ + @Bean + public EngineConfigurationConfigurer processCompletedListenerRegistrar( + ProcessCompletedListener listener) { + return configuration -> { + // 追加而非覆盖:保留引擎/starter 已登记的监听器 + List listeners = new ArrayList<>(); + if (configuration.getEventListeners() != null) { + listeners.addAll(configuration.getEventListeners()); + } + listeners.add(listener); + configuration.setEventListeners(listeners); + }; + } +} diff --git a/src/main/java/com/youlai/boot/module/workflow/controller/WorkflowDefinitionController.java b/src/main/java/com/youlai/boot/module/workflow/controller/WorkflowDefinitionController.java new file mode 100644 index 00000000..e66af884 --- /dev/null +++ b/src/main/java/com/youlai/boot/module/workflow/controller/WorkflowDefinitionController.java @@ -0,0 +1,69 @@ +package com.youlai.boot.module.workflow.controller; + +import com.youlai.boot.common.result.Result; +import com.youlai.boot.module.workflow.model.form.DefinitionStateForm; +import com.youlai.boot.module.workflow.model.vo.ModelXmlVO; +import com.youlai.boot.module.workflow.model.vo.ProcessStageVO; +import com.youlai.boot.module.workflow.model.vo.StartableProcessVO; +import com.youlai.boot.module.workflow.service.WorkflowDefinitionService; +import com.youlai.boot.module.workflow.config.ConditionalOnWorkflowEnabled; +import io.swagger.v3.oas.annotations.Operation; +import io.swagger.v3.oas.annotations.Parameter; +import io.swagger.v3.oas.annotations.tags.Tag; +import jakarta.validation.Valid; +import lombok.RequiredArgsConstructor; +import org.springframework.security.access.prepost.PreAuthorize; +import org.springframework.web.bind.annotation.*; + +import java.util.List; + +/** + * 流程定义控制层(发布产物:发布后供发起、审批与流程图查看) + * + * @author Ray.Hao + * @since 4.9.0 + */ +@Tag(name = "13.工作流定义接口") +@ConditionalOnWorkflowEnabled +@RestController +@RequestMapping("/api/v1/workflow/definitions") +@RequiredArgsConstructor +public class WorkflowDefinitionController { + + private final WorkflowDefinitionService workflowDefinitionService; + + @Operation(summary = "可发起流程列表(发起页下拉数据源)") + @GetMapping("/startable") + public Result> listStartableProcesses() { + return Result.success(workflowDefinitionService.listStartableProcesses()); + } + + @Operation(summary = "流程审批阶段预览(发起页/审批弹窗展示流程走向与各环节办理人)") + @GetMapping("/{definitionId}/stages") + public Result> listProcessStages( + @Parameter(description = "流程定义ID") @PathVariable String definitionId + ) { + return Result.success(workflowDefinitionService.listProcessStages(definitionId)); + } + + @Operation(summary = "获取流程定义 BPMN XML(流程图查看)") + @GetMapping("/{definitionId}/xml") + @PreAuthorize("@ss.hasPerm('workflow:model:list')") + public Result getDefinitionXml( + @Parameter(description = "流程定义ID") @PathVariable String definitionId + ) { + return Result.success(workflowDefinitionService.getDefinitionXml(definitionId)); + } + + @Operation(summary = "启用/停用流程(停用后不可发起新流程,运行中的实例不受影响)") + @PutMapping("/{definitionId}/state") + @PreAuthorize("@ss.hasPerm('workflow:definition:update')") + public Result updateDefinitionState( + @Parameter(description = "流程定义ID") @PathVariable String definitionId, + @Valid @RequestBody DefinitionStateForm formData + ) { + workflowDefinitionService.updateDefinitionState(definitionId, formData); + return Result.success(); + } + +} diff --git a/src/main/java/com/youlai/boot/module/workflow/controller/WorkflowInstanceController.java b/src/main/java/com/youlai/boot/module/workflow/controller/WorkflowInstanceController.java new file mode 100644 index 00000000..18603437 --- /dev/null +++ b/src/main/java/com/youlai/boot/module/workflow/controller/WorkflowInstanceController.java @@ -0,0 +1,94 @@ +package com.youlai.boot.module.workflow.controller; + +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; +import com.youlai.boot.common.annotation.Log; +import com.youlai.boot.framework.web.repeatsubmit.RepeatSubmit; +import com.youlai.boot.common.enums.ActionTypeEnum; +import com.youlai.boot.common.enums.LogModuleEnum; +import com.youlai.boot.common.result.PageResult; +import com.youlai.boot.common.result.Result; +import com.youlai.boot.module.workflow.model.form.StartProcessForm; +import com.youlai.boot.module.workflow.model.query.WorkflowInstancePageQuery; +import com.youlai.boot.module.workflow.model.vo.InstanceDetailVO; +import com.youlai.boot.module.workflow.model.vo.InstancePageVO; +import com.youlai.boot.module.workflow.model.vo.ProcessDiagramVO; +import com.youlai.boot.module.workflow.service.WorkflowInstanceService; +import com.youlai.boot.module.workflow.config.ConditionalOnWorkflowEnabled; +import io.swagger.v3.oas.annotations.Operation; +import io.swagger.v3.oas.annotations.Parameter; +import io.swagger.v3.oas.annotations.tags.Tag; +import jakarta.validation.Valid; +import lombok.RequiredArgsConstructor; +import org.springframework.security.access.prepost.PreAuthorize; +import org.springframework.web.bind.annotation.*; + +/** + * 流程实例控制层(发起、我的流程、详情、流程图、撤销/终止) + * + * @author Ray.Hao + * @since 4.9.0 + */ +@Tag(name = "13.工作流实例接口") +@ConditionalOnWorkflowEnabled +@RestController +@RequestMapping("/api/v1/workflow/instances") +@RequiredArgsConstructor +public class WorkflowInstanceController { + + private final WorkflowInstanceService workflowInstanceService; + + @Operation(summary = "发起流程") + @PostMapping + @RepeatSubmit + @Log(module = LogModuleEnum.WORKFLOW, value = ActionTypeEnum.INSERT, title = "发起流程") + public Result startProcess(@Valid @RequestBody StartProcessForm formData) { + return Result.success(workflowInstanceService.startProcess(formData)); + } + + @Operation(summary = "我的流程分页列表") + @GetMapping + @Log(module = LogModuleEnum.WORKFLOW, value = ActionTypeEnum.LIST, title = "我的流程") + public PageResult getInstancePage(@Valid WorkflowInstancePageQuery queryParams) { + Page result = workflowInstanceService.getInstancePage(queryParams); + return PageResult.success(result); + } + + @Operation(summary = "获取流程图数据(节点高亮)") + @GetMapping("/{instanceId}/diagram") + public Result getProcessDiagram( + @Parameter(description = "流程实例ID") @PathVariable String instanceId + ) { + return Result.success(workflowInstanceService.getProcessDiagram(instanceId)); + } + + @Operation(summary = "获取流程实例详情") + @GetMapping("/{instanceId}") + public Result getInstanceDetail( + @Parameter(description = "流程实例ID") @PathVariable String instanceId + ) { + return Result.success(workflowInstanceService.getInstanceDetail(instanceId)); + } + + @Operation(summary = "撤销流程(仅发起人)") + @PutMapping("/{instanceId}/cancel") + @Log(module = LogModuleEnum.WORKFLOW, value = ActionTypeEnum.DELETE, title = "撤销流程") + public Result cancelProcessInstance( + @Parameter(description = "流程实例ID") @PathVariable String instanceId + ) { + workflowInstanceService.cancelProcessInstance(instanceId); + return Result.success(); + } + + @Operation(summary = "终止流程(管理员)") + @PutMapping("/{instanceId}/terminate") + @PreAuthorize("@ss.hasPerm('workflow:instance:terminate')") + @Log(module = LogModuleEnum.WORKFLOW, value = ActionTypeEnum.DELETE, title = "终止流程") + public Result terminateProcessInstance( + @Parameter(description = "流程实例ID") @PathVariable String instanceId, + @Parameter(description = "终止原因") @RequestParam(required = false) String reason + ) { + workflowInstanceService.terminateProcessInstance(instanceId, reason); + return Result.success(); + } + +} diff --git a/src/main/java/com/youlai/boot/module/workflow/controller/WorkflowModelController.java b/src/main/java/com/youlai/boot/module/workflow/controller/WorkflowModelController.java new file mode 100644 index 00000000..0d09af76 --- /dev/null +++ b/src/main/java/com/youlai/boot/module/workflow/controller/WorkflowModelController.java @@ -0,0 +1,129 @@ +package com.youlai.boot.module.workflow.controller; + +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; +import com.youlai.boot.common.annotation.Log; +import com.youlai.boot.framework.web.repeatsubmit.RepeatSubmit; +import com.youlai.boot.common.enums.ActionTypeEnum; +import com.youlai.boot.common.enums.LogModuleEnum; +import com.youlai.boot.common.result.PageResult; +import com.youlai.boot.common.result.Result; +import com.youlai.boot.module.workflow.model.form.ModelForm; +import com.youlai.boot.module.workflow.model.form.ModelXmlForm; +import com.youlai.boot.module.workflow.model.query.WorkflowModelPageQuery; +import com.youlai.boot.module.workflow.model.vo.ModelVO; +import com.youlai.boot.module.workflow.model.vo.ModelXmlVO; +import com.youlai.boot.module.workflow.service.WorkflowDemoService; +import com.youlai.boot.module.workflow.service.WorkflowModelService; +import com.youlai.boot.module.workflow.config.ConditionalOnWorkflowEnabled; +import io.swagger.v3.oas.annotations.Operation; +import io.swagger.v3.oas.annotations.Parameter; +import io.swagger.v3.oas.annotations.tags.Tag; +import jakarta.validation.Valid; +import lombok.RequiredArgsConstructor; +import org.springframework.security.access.prepost.PreAuthorize; +import org.springframework.web.bind.annotation.*; + +import java.util.Arrays; + +/** + * 流程模型控制层(设计器侧:模型 CRUD、XML、部署) + * + * @author Ray.Hao + * @since 4.9.0 + */ +@Tag(name = "13.工作流模型接口") +@ConditionalOnWorkflowEnabled +@RestController +@RequestMapping("/api/v1/workflow/models") +@RequiredArgsConstructor +public class WorkflowModelController { + + private final WorkflowModelService workflowModelService; + private final WorkflowDemoService workflowDemoService; + + @Operation(summary = "流程模型分页列表") + @GetMapping + @PreAuthorize("@ss.hasPerm('workflow:model:list')") + @Log(module = LogModuleEnum.WORKFLOW, value = ActionTypeEnum.LIST) + public PageResult getModelPage(@Valid WorkflowModelPageQuery queryParams) { + Page result = workflowModelService.getModelPage(queryParams); + return PageResult.success(result); + } + + @Operation(summary = "新增流程模型") + @PostMapping + @PreAuthorize("@ss.hasPerm('workflow:model:create')") + @RepeatSubmit + @Log(module = LogModuleEnum.WORKFLOW, value = ActionTypeEnum.INSERT) + public Result saveModel(@Valid @RequestBody ModelForm formData) { + boolean result = workflowModelService.saveModel(formData); + return Result.judge(result); + } + + @Operation(summary = "修改流程模型") + @PutMapping("/{modelId}") + @PreAuthorize("@ss.hasPerm('workflow:model:update')") + @Log(module = LogModuleEnum.WORKFLOW, value = ActionTypeEnum.UPDATE) + public Result updateModel( + @Parameter(description = "模型ID") @PathVariable String modelId, + @Valid @RequestBody ModelForm formData + ) { + boolean result = workflowModelService.updateModel(modelId, formData); + return Result.judge(result); + } + + @Operation(summary = "删除流程模型") + @DeleteMapping("/{ids}") + @PreAuthorize("@ss.hasPerm('workflow:model:delete')") + @Log(module = LogModuleEnum.WORKFLOW, value = ActionTypeEnum.DELETE) + public Result removeModels( + @Parameter(description = "模型ID,多个以英文逗号(,)拼接") @PathVariable String ids + ) { + workflowModelService.removeModels(Arrays.asList(ids.split(","))); + return Result.success(); + } + + @Operation(summary = "获取模型 BPMN XML(设计器回显)") + @GetMapping("/{modelId}/xml") + @PreAuthorize("@ss.hasPerm('workflow:model:list')") + public Result getModelXml( + @Parameter(description = "模型ID") @PathVariable String modelId + ) { + return Result.success(workflowModelService.getModelXml(modelId)); + } + + @Operation(summary = "保存模型 BPMN XML(设计器保存)") + @PutMapping("/{modelId}/xml") + @PreAuthorize("@ss.hasPerm('workflow:model:update')") + @Log(module = LogModuleEnum.WORKFLOW, value = ActionTypeEnum.UPDATE) + public Result saveModelXml( + @Parameter(description = "模型ID") @PathVariable String modelId, + @Valid @RequestBody ModelXmlForm formData + ) { + boolean result = workflowModelService.saveModelXml(modelId, formData); + return Result.judge(result); + } + + @Operation(summary = "部署流程模型") + @PostMapping("/{modelId}/deploy") + @PreAuthorize("@ss.hasPerm('workflow:model:deploy')") + @RepeatSubmit + @Log(module = LogModuleEnum.WORKFLOW, value = ActionTypeEnum.INSERT, title = "部署流程") + public Result deployModel( + @Parameter(description = "模型ID") @PathVariable String modelId + ) { + workflowModelService.deployModel(modelId); + return Result.success(); + } + + @Operation(summary = "重置工作流数据", description = "清空所有流程(含用户自建)的模型、定义、实例与历史,清理关联表单数据后重建初始演示流程") + @PostMapping("/demo/reset") + @PreAuthorize("@ss.hasPerm('workflow:model:reset')") + @RepeatSubmit + @Log(module = LogModuleEnum.WORKFLOW, value = ActionTypeEnum.DELETE, title = "重置工作流数据") + public Result resetDemoProcesses() { + workflowDemoService.reset(); + return Result.success(); + } + +} diff --git a/src/main/java/com/youlai/boot/module/workflow/controller/WorkflowTaskController.java b/src/main/java/com/youlai/boot/module/workflow/controller/WorkflowTaskController.java new file mode 100644 index 00000000..67b125c0 --- /dev/null +++ b/src/main/java/com/youlai/boot/module/workflow/controller/WorkflowTaskController.java @@ -0,0 +1,109 @@ +package com.youlai.boot.module.workflow.controller; + +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; +import com.youlai.boot.common.annotation.Log; +import com.youlai.boot.framework.web.repeatsubmit.RepeatSubmit; +import com.youlai.boot.common.enums.ActionTypeEnum; +import com.youlai.boot.common.enums.LogModuleEnum; +import com.youlai.boot.common.result.PageResult; +import com.youlai.boot.common.result.Result; +import com.youlai.boot.module.workflow.model.form.CompleteTaskForm; +import com.youlai.boot.module.workflow.model.form.RejectTaskForm; +import com.youlai.boot.module.workflow.model.query.WorkflowTaskPageQuery; +import com.youlai.boot.module.workflow.model.vo.DoneTaskVO; +import com.youlai.boot.module.workflow.model.vo.RejectTargetVO; +import com.youlai.boot.module.workflow.model.vo.TaskDetailVO; +import com.youlai.boot.module.workflow.model.vo.TodoTaskVO; +import com.youlai.boot.module.workflow.service.WorkflowTaskService; +import com.youlai.boot.module.workflow.config.ConditionalOnWorkflowEnabled; +import io.swagger.v3.oas.annotations.Operation; +import io.swagger.v3.oas.annotations.Parameter; +import io.swagger.v3.oas.annotations.tags.Tag; +import jakarta.validation.Valid; +import lombok.RequiredArgsConstructor; +import org.springframework.web.bind.annotation.*; + +import java.util.List; + +/** + * 流程任务控制层(待办/已办、审批通过/驳回) + * + * @author Ray.Hao + * @since 4.9.0 + */ +@Tag(name = "13.工作流任务接口") +@ConditionalOnWorkflowEnabled +@RestController +@RequestMapping("/api/v1/workflow/tasks") +@RequiredArgsConstructor +public class WorkflowTaskController { + + private final WorkflowTaskService workflowTaskService; + + @Operation(summary = "待办任务分页列表") + @GetMapping("/todo") + @Log(module = LogModuleEnum.WORKFLOW, value = ActionTypeEnum.LIST, title = "待办任务") + public PageResult getTodoTaskPage(@Valid WorkflowTaskPageQuery queryParams) { + Page result = workflowTaskService.getTodoTaskPage(queryParams); + return PageResult.success(result); + } + + @Operation(summary = "已办任务分页列表") + @GetMapping("/done") + @Log(module = LogModuleEnum.WORKFLOW, value = ActionTypeEnum.LIST, title = "已办任务") + public PageResult getDoneTaskPage(@Valid WorkflowTaskPageQuery queryParams) { + Page result = workflowTaskService.getDoneTaskPage(queryParams); + return PageResult.success(result); + } + + @Operation(summary = "获取待办任务详情(发起表单回显 + 审批记录)") + @GetMapping("/{taskId}") + public Result getTaskDetail( + @Parameter(description = "任务ID") @PathVariable String taskId + ) { + return Result.success(workflowTaskService.getTaskDetail(taskId)); + } + + @Operation(summary = "获取驳回目标节点列表") + @GetMapping("/{taskId}/reject-targets") + public Result> listRejectTargets( + @Parameter(description = "任务ID") @PathVariable String taskId + ) { + return Result.success(workflowTaskService.listRejectTargets(taskId)); + } + + @Operation(summary = "审批通过") + @PutMapping("/{taskId}/complete") + @RepeatSubmit + @Log(module = LogModuleEnum.WORKFLOW, value = ActionTypeEnum.UPDATE, title = "审批通过") + public Result completeTask( + @Parameter(description = "任务ID") @PathVariable String taskId, + @Valid @RequestBody CompleteTaskForm formData + ) { + workflowTaskService.completeTask(taskId, formData); + return Result.success(); + } + + @Operation(summary = "驳回") + @PutMapping("/{taskId}/reject") + @RepeatSubmit + @Log(module = LogModuleEnum.WORKFLOW, value = ActionTypeEnum.UPDATE, title = "驳回") + public Result rejectTask( + @Parameter(description = "任务ID") @PathVariable String taskId, + @Valid @RequestBody RejectTaskForm formData + ) { + workflowTaskService.rejectTask(taskId, formData); + return Result.success(); + } + + // AI 辅助:未开启 AI 时调用返回业务异常 + + @Operation(summary = "AI 生成任务审批摘要") + @PostMapping("/{taskId}/ai-summary") + public Result summarizeTask( + @Parameter(description = "任务ID") @PathVariable String taskId + ) { + return Result.success(workflowTaskService.aiSummarizeTask(taskId)); + } + +} diff --git a/src/main/java/com/youlai/boot/module/workflow/enums/InstanceStatusEnum.java b/src/main/java/com/youlai/boot/module/workflow/enums/InstanceStatusEnum.java new file mode 100644 index 00000000..4fefb7c1 --- /dev/null +++ b/src/main/java/com/youlai/boot/module/workflow/enums/InstanceStatusEnum.java @@ -0,0 +1,40 @@ +package com.youlai.boot.module.workflow.enums; + +import com.fasterxml.jackson.annotation.JsonValue; +import lombok.Getter; + +/** + * 流程实例状态枚举 + * + * @author Ray.Hao + * @since 4.9.0 + */ +@Getter +public enum InstanceStatusEnum { + + /** + * 运行中 + */ + RUNNING("running", "运行中"), + + /** + * 已完成(正常走完结束节点) + */ + FINISHED("finished", "已完成"), + + /** + * 已终止(被删除,含管理员终止与发起人撤销) + */ + TERMINATED("terminated", "已终止"); + + @JsonValue + private final String value; + + private final String label; + + InstanceStatusEnum(String value, String label) { + this.value = value; + this.label = label; + } + +} diff --git a/src/main/java/com/youlai/boot/module/workflow/handler/ProcessCompletedContext.java b/src/main/java/com/youlai/boot/module/workflow/handler/ProcessCompletedContext.java new file mode 100644 index 00000000..5ee1fd4a --- /dev/null +++ b/src/main/java/com/youlai/boot/module/workflow/handler/ProcessCompletedContext.java @@ -0,0 +1,18 @@ +package com.youlai.boot.module.workflow.handler; + +/** + * 流程完成上下文(路由业务后处理时携带的实例信息) + * + * @param processInstanceId 流程实例ID + * @param processDefinitionKey 流程定义Key(BPMN 中 process 节点的 id) + * @param businessKey 业务Key(本系统约定为发起时提交的表单数据ID) + * @param startUserId 发起人账号(发起时写入 ACT_HI_PROCINST.START_USER_ID_) + * @author Ray.Hao + * @since 4.9.0 + */ +public record ProcessCompletedContext( + String processInstanceId, + String processDefinitionKey, + String businessKey, + String startUserId) { +} diff --git a/src/main/java/com/youlai/boot/module/workflow/handler/ProcessCompletedHandler.java b/src/main/java/com/youlai/boot/module/workflow/handler/ProcessCompletedHandler.java new file mode 100644 index 00000000..a3f668e7 --- /dev/null +++ b/src/main/java/com/youlai/boot/module/workflow/handler/ProcessCompletedHandler.java @@ -0,0 +1,22 @@ +package com.youlai.boot.module.workflow.handler; + +/** + * 流程审批通过后的业务处理器(扩展点) + * + * @author Ray.Hao + * @since 4.9.0 + */ +public interface ProcessCompletedHandler { + + /** + * 适配的流程定义 Key(BPMN 中 process 节点的 id,如 expense) + */ + String getProcessDefinitionKey(); + + /** + * 审批通过后的业务处理 + * + * @param context 流程完成上下文 + */ + void handle(ProcessCompletedContext context); +} diff --git a/src/main/java/com/youlai/boot/module/workflow/handler/expense/ExpenseProcessCompletedHandler.java b/src/main/java/com/youlai/boot/module/workflow/handler/expense/ExpenseProcessCompletedHandler.java new file mode 100644 index 00000000..ddfb2562 --- /dev/null +++ b/src/main/java/com/youlai/boot/module/workflow/handler/expense/ExpenseProcessCompletedHandler.java @@ -0,0 +1,46 @@ +package com.youlai.boot.module.workflow.handler.expense; + +import cn.hutool.core.util.StrUtil; +import com.youlai.boot.module.form.model.vo.FormDataVO; +import com.youlai.boot.module.form.service.FormDataService; +import com.youlai.boot.module.workflow.handler.ProcessCompletedContext; +import com.youlai.boot.module.workflow.handler.ProcessCompletedHandler; +import com.youlai.boot.module.workflow.config.ConditionalOnWorkflowEnabled; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.stereotype.Component; + +/** + * 报销流程审批通过后的业务处理(示例:财务入账) + * + * @author Ray.Hao + * @since 4.9.0 + */ +@Slf4j +@ConditionalOnWorkflowEnabled +@Component +@RequiredArgsConstructor +public class ExpenseProcessCompletedHandler implements ProcessCompletedHandler { + + private final FormDataService formDataService; + + /** + * 适配的流程定义 Key:报销(对应 expense.bpmn20.xml 的 process id) + */ + @Override + public String getProcessDefinitionKey() { + return "expense"; + } + + @Override + public void handle(ProcessCompletedContext context) { + if (StrUtil.isBlank(context.businessKey())) { + log.info("[报销审批通过] 发起人={},实例未关联表单数据,跳过入账", context.startUserId()); + return; + } + FormDataVO formData = formDataService.getFormDataDetail(Long.valueOf(context.businessKey())); + // TODO 正式环境:调用财务系统按报销金额生成入账凭证,并将凭证号回写业务表 + log.info("[报销审批通过] 发起人={},报销内容={} → 调用财务系统入账(演示占位,未真实执行)", + context.startUserId(), formData == null ? null : formData.getDataJson()); + } +} diff --git a/src/main/java/com/youlai/boot/module/workflow/handler/purchase/PurchaseProcessCompletedHandler.java b/src/main/java/com/youlai/boot/module/workflow/handler/purchase/PurchaseProcessCompletedHandler.java new file mode 100644 index 00000000..8ed9c326 --- /dev/null +++ b/src/main/java/com/youlai/boot/module/workflow/handler/purchase/PurchaseProcessCompletedHandler.java @@ -0,0 +1,46 @@ +package com.youlai.boot.module.workflow.handler.purchase; + +import cn.hutool.core.util.StrUtil; +import com.youlai.boot.module.form.model.vo.FormDataVO; +import com.youlai.boot.module.form.service.FormDataService; +import com.youlai.boot.module.workflow.handler.ProcessCompletedContext; +import com.youlai.boot.module.workflow.handler.ProcessCompletedHandler; +import com.youlai.boot.module.workflow.config.ConditionalOnWorkflowEnabled; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.stereotype.Component; + +/** + * 采购流程审批通过后的业务处理(示例:采购入库) + * + * @author Ray.Hao + * @since 4.9.0 + */ +@Slf4j +@ConditionalOnWorkflowEnabled +@Component +@RequiredArgsConstructor +public class PurchaseProcessCompletedHandler implements ProcessCompletedHandler { + + private final FormDataService formDataService; + + /** + * 适配的流程定义 Key:采购(对应 purchase.bpmn20.xml 的 process id) + */ + @Override + public String getProcessDefinitionKey() { + return "purchase"; + } + + @Override + public void handle(ProcessCompletedContext context) { + if (StrUtil.isBlank(context.businessKey())) { + log.info("[采购审批通过] 发起人={},实例未关联表单数据,跳过入库", context.startUserId()); + return; + } + FormDataVO formData = formDataService.getFormDataDetail(Long.valueOf(context.businessKey())); + // TODO 正式环境:调用仓储系统生成入库单并变更库存 + log.info("[采购审批通过] 发起人={},采购内容={} → 调用仓储系统入库(演示占位,未真实执行)", + context.startUserId(), formData == null ? null : formData.getDataJson()); + } +} diff --git a/src/main/java/com/youlai/boot/module/workflow/listener/ProcessCompletedListener.java b/src/main/java/com/youlai/boot/module/workflow/listener/ProcessCompletedListener.java new file mode 100644 index 00000000..6d0bb3c8 --- /dev/null +++ b/src/main/java/com/youlai/boot/module/workflow/listener/ProcessCompletedListener.java @@ -0,0 +1,89 @@ +package com.youlai.boot.module.workflow.listener; + +import com.youlai.boot.module.workflow.handler.ProcessCompletedContext; +import com.youlai.boot.module.workflow.handler.ProcessCompletedHandler; +import com.youlai.boot.module.workflow.config.ConditionalOnWorkflowEnabled; +import lombok.extern.slf4j.Slf4j; +import org.flowable.common.engine.api.delegate.event.FlowableEngineEvent; +import org.flowable.common.engine.api.delegate.event.FlowableEngineEventType; +import org.flowable.common.engine.api.delegate.event.FlowableEvent; +import org.flowable.common.engine.api.delegate.event.FlowableEventListener; +import org.flowable.engine.HistoryService; +import org.flowable.engine.history.HistoricProcessInstance; +import org.springframework.context.annotation.Lazy; +import org.springframework.stereotype.Component; + +import java.util.List; +import java.util.Map; +import java.util.function.Function; +import java.util.stream.Collectors; + +/** + * 流程完成事件监听器:审批通过(实例正常结束)后按流程定义 Key 路由到业务处理器 + * + * @author Ray.Hao + * @since 4.9.0 + */ +@Slf4j +@ConditionalOnWorkflowEnabled +@Component +public class ProcessCompletedListener implements FlowableEventListener { + + private final HistoryService historyService; + private final Map handlers; + + public ProcessCompletedListener(@Lazy HistoryService historyService, List handlerList) { + this.historyService = historyService; + // 以流程定义 Key 索引处理器:新增业务后处理实现接口即自动被路由 + this.handlers = handlerList.stream() + .collect(Collectors.toMap(ProcessCompletedHandler::getProcessDefinitionKey, Function.identity())); + } + + @Override + public void onEvent(FlowableEvent event) { + if (event.getType() != FlowableEngineEventType.PROCESS_COMPLETED) { + return; + } + String processInstanceId = ((FlowableEngineEvent) event).getProcessInstanceId(); + HistoricProcessInstance instance = historyService.createHistoricProcessInstanceQuery() + .processInstanceId(processInstanceId).singleResult(); + if (instance == null) { + return; + } + ProcessCompletedHandler handler = handlers.get(instance.getProcessDefinitionKey()); + if (handler == null) { + // 未登记后处理的流程(如请假、用章)静默跳过,避免日志噪音 + log.debug("流程 [{}] 审批通过,未登记业务后处理", instance.getProcessDefinitionKey()); + return; + } + handler.handle(new ProcessCompletedContext( + instance.getId(), + instance.getProcessDefinitionKey(), + instance.getBusinessKey(), + instance.getStartUserId())); + } + + /** + * 监听器异常不回滚审批事务:后处理(入账/入库)失败不阻断流程结束 + */ + @Override + public boolean isFailOnException() { + return false; + } + + /** + * 常规事件派发(默认):不挂事务生命周期回调 + */ + @Override + public boolean isFireOnTransactionLifecycleEvent() { + return false; + } + + /** + * 事务生命周期回调时机(仅 isFireOnTransactionLifecycleEvent 为 true 时生效),此处无需 + */ + @Override + public String getOnTransaction() { + return null; + } +} diff --git a/src/main/java/com/youlai/boot/module/workflow/model/form/CompleteTaskForm.java b/src/main/java/com/youlai/boot/module/workflow/model/form/CompleteTaskForm.java new file mode 100644 index 00000000..3d6111a9 --- /dev/null +++ b/src/main/java/com/youlai/boot/module/workflow/model/form/CompleteTaskForm.java @@ -0,0 +1,26 @@ +package com.youlai.boot.module.workflow.model.form; + +import io.swagger.v3.oas.annotations.media.Schema; +import jakarta.validation.constraints.Size; +import lombok.Data; + +import java.util.Map; + +/** + * 审批任务表单对象(通过) + * + * @author Ray.Hao + * @since 4.9.0 + */ +@Schema(description = "审批任务表单对象") +@Data +public class CompleteTaskForm { + + @Schema(description = "审批意见(写入引擎评论,随任务历史归档)") + @Size(max = 500, message = "审批意见长度不能超过500个字符") + private String comment; + + @Schema(description = "流程变量(驱动后续网关条件)") + private Map variables; + +} diff --git a/src/main/java/com/youlai/boot/module/workflow/model/form/DefinitionStateForm.java b/src/main/java/com/youlai/boot/module/workflow/model/form/DefinitionStateForm.java new file mode 100644 index 00000000..8e5f4ba1 --- /dev/null +++ b/src/main/java/com/youlai/boot/module/workflow/model/form/DefinitionStateForm.java @@ -0,0 +1,21 @@ +package com.youlai.boot.module.workflow.model.form; + +import io.swagger.v3.oas.annotations.media.Schema; +import jakarta.validation.constraints.NotNull; +import lombok.Data; + +/** + * 流程定义状态表单对象(挂起/激活) + * + * @author Ray.Hao + * @since 4.9.0 + */ +@Schema(description = "流程定义状态表单对象") +@Data +public class DefinitionStateForm { + + @Schema(description = "是否挂起(true 挂起;false 激活)") + @NotNull(message = "挂起状态不能为空") + private Boolean suspend; + +} diff --git a/src/main/java/com/youlai/boot/module/workflow/model/form/ModelForm.java b/src/main/java/com/youlai/boot/module/workflow/model/form/ModelForm.java new file mode 100644 index 00000000..2fb1e88f --- /dev/null +++ b/src/main/java/com/youlai/boot/module/workflow/model/form/ModelForm.java @@ -0,0 +1,34 @@ +package com.youlai.boot.module.workflow.model.form; + +import io.swagger.v3.oas.annotations.media.Schema; +import jakarta.validation.constraints.NotBlank; +import jakarta.validation.constraints.Pattern; +import jakarta.validation.constraints.Size; +import lombok.Data; + +/** + * 流程模型表单对象 + * + * @author Ray.Hao + * @since 4.9.0 + */ +@Schema(description = "流程模型") +@Data +public class ModelForm { + + @Schema(description = "模型名称", example = "请假审批") + @NotBlank(message = "模型名称不能为空") + @Size(max = 100, message = "模型名称长度不能超过100个字符") + private String name; + + @Schema(description = "模型标识(创建后不可修改,部署时作为流程定义 key)", example = "leave") + @NotBlank(message = "模型标识不能为空") + @Size(max = 64, message = "模型标识长度不能超过64个字符") + @Pattern(regexp = "^[a-z][a-z0-9_]*$", message = "模型标识须以小写字母开头,仅含小写字母、数字、下划线") + private String key; + + @Schema(description = "模型描述") + @Size(max = 255, message = "模型描述长度不能超过255个字符") + private String description; + +} diff --git a/src/main/java/com/youlai/boot/module/workflow/model/form/ModelXmlForm.java b/src/main/java/com/youlai/boot/module/workflow/model/form/ModelXmlForm.java new file mode 100644 index 00000000..86f0a8fd --- /dev/null +++ b/src/main/java/com/youlai/boot/module/workflow/model/form/ModelXmlForm.java @@ -0,0 +1,21 @@ +package com.youlai.boot.module.workflow.model.form; + +import io.swagger.v3.oas.annotations.media.Schema; +import jakarta.validation.constraints.NotBlank; +import lombok.Data; + +/** + * 流程模型 XML 表单对象(设计器保存) + * + * @author Ray.Hao + * @since 4.9.0 + */ +@Schema(description = "流程模型XML表单对象") +@Data +public class ModelXmlForm { + + @Schema(description = "BPMN 2.0 XML(bpmn-js 产出)") + @NotBlank(message = "流程模型内容不能为空") + private String xml; + +} diff --git a/src/main/java/com/youlai/boot/module/workflow/model/form/RejectTaskForm.java b/src/main/java/com/youlai/boot/module/workflow/model/form/RejectTaskForm.java new file mode 100644 index 00000000..db6b5177 --- /dev/null +++ b/src/main/java/com/youlai/boot/module/workflow/model/form/RejectTaskForm.java @@ -0,0 +1,26 @@ +package com.youlai.boot.module.workflow.model.form; + +import io.swagger.v3.oas.annotations.media.Schema; +import jakarta.validation.constraints.NotBlank; +import jakarta.validation.constraints.Size; +import lombok.Data; + +/** + * 驳回任务表单对象 + * + * @author Ray.Hao + * @since 4.9.0 + */ +@Schema(description = "驳回任务表单对象") +@Data +public class RejectTaskForm { + + @Schema(description = "目标节点ID(驳回到的历史节点)") + @NotBlank(message = "目标节点不能为空") + private String targetActivityId; + + @Schema(description = "驳回意见(写入引擎评论,随任务历史归档)") + @Size(max = 500, message = "驳回意见长度不能超过500个字符") + private String comment; + +} diff --git a/src/main/java/com/youlai/boot/module/workflow/model/form/StartProcessForm.java b/src/main/java/com/youlai/boot/module/workflow/model/form/StartProcessForm.java new file mode 100644 index 00000000..62870767 --- /dev/null +++ b/src/main/java/com/youlai/boot/module/workflow/model/form/StartProcessForm.java @@ -0,0 +1,32 @@ +package com.youlai.boot.module.workflow.model.form; + +import io.swagger.v3.oas.annotations.media.Schema; +import jakarta.validation.constraints.NotBlank; +import lombok.Data; + +import java.util.Map; + +/** + * 发起流程表单对象 + * + * @author Ray.Hao + * @since 4.9.0 + */ +@Schema(description = "发起流程表单对象") +@Data +public class StartProcessForm { + + @Schema(description = "流程定义ID") + @NotBlank(message = "流程定义ID不能为空") + private String processDefinitionId; + + @Schema(description = "表单数据(field -> value 映射;流程绑定 formKey 时必填)") + private Map formData; + + @Schema(description = "流程变量(驱动网关条件;随实例提交)") + private Map variables; + + @Schema(description = "流程实例名称(未传时默认取流程定义名称)") + private String name; + +} diff --git a/src/main/java/com/youlai/boot/module/workflow/model/query/WorkflowInstancePageQuery.java b/src/main/java/com/youlai/boot/module/workflow/model/query/WorkflowInstancePageQuery.java new file mode 100644 index 00000000..ca3c03ec --- /dev/null +++ b/src/main/java/com/youlai/boot/module/workflow/model/query/WorkflowInstancePageQuery.java @@ -0,0 +1,22 @@ +package com.youlai.boot.module.workflow.model.query; + +import com.youlai.boot.common.base.BaseQuery; +import io.swagger.v3.oas.annotations.media.Schema; +import lombok.Data; +import lombok.EqualsAndHashCode; + +/** + * 流程实例分页查询对象 + * + * @author Ray.Hao + * @since 4.9.0 + */ +@Data +@EqualsAndHashCode(callSuper = false) +@Schema(description = "流程实例分页查询对象") +public class WorkflowInstancePageQuery extends BaseQuery { + + @Schema(description = "关键字(流程定义名称)") + private String keywords; + +} diff --git a/src/main/java/com/youlai/boot/module/workflow/model/query/WorkflowModelPageQuery.java b/src/main/java/com/youlai/boot/module/workflow/model/query/WorkflowModelPageQuery.java new file mode 100644 index 00000000..b47b0d9d --- /dev/null +++ b/src/main/java/com/youlai/boot/module/workflow/model/query/WorkflowModelPageQuery.java @@ -0,0 +1,22 @@ +package com.youlai.boot.module.workflow.model.query; + +import com.youlai.boot.common.base.BaseQuery; +import io.swagger.v3.oas.annotations.media.Schema; +import lombok.Data; +import lombok.EqualsAndHashCode; + +/** + * 流程模型分页查询对象 + * + * @author Ray.Hao + * @since 4.9.0 + */ +@Data +@EqualsAndHashCode(callSuper = false) +@Schema(description = "流程模型分页查询对象") +public class WorkflowModelPageQuery extends BaseQuery { + + @Schema(description = "关键字(模型名称)") + private String keywords; + +} diff --git a/src/main/java/com/youlai/boot/module/workflow/model/query/WorkflowTaskPageQuery.java b/src/main/java/com/youlai/boot/module/workflow/model/query/WorkflowTaskPageQuery.java new file mode 100644 index 00000000..8f7457fa --- /dev/null +++ b/src/main/java/com/youlai/boot/module/workflow/model/query/WorkflowTaskPageQuery.java @@ -0,0 +1,22 @@ +package com.youlai.boot.module.workflow.model.query; + +import com.youlai.boot.common.base.BaseQuery; +import io.swagger.v3.oas.annotations.media.Schema; +import lombok.Data; +import lombok.EqualsAndHashCode; + +/** + * 任务分页查询对象(待办/已办共用) + * + * @author Ray.Hao + * @since 4.9.0 + */ +@Data +@EqualsAndHashCode(callSuper = false) +@Schema(description = "任务分页查询对象") +public class WorkflowTaskPageQuery extends BaseQuery { + + @Schema(description = "关键字(任务名称)") + private String keywords; + +} diff --git a/src/main/java/com/youlai/boot/module/workflow/model/vo/ApprovalHistoryVO.java b/src/main/java/com/youlai/boot/module/workflow/model/vo/ApprovalHistoryVO.java new file mode 100644 index 00000000..b9a70799 --- /dev/null +++ b/src/main/java/com/youlai/boot/module/workflow/model/vo/ApprovalHistoryVO.java @@ -0,0 +1,41 @@ +package com.youlai.boot.module.workflow.model.vo; + +import com.fasterxml.jackson.annotation.JsonFormat; +import io.swagger.v3.oas.annotations.media.Schema; +import lombok.Getter; +import lombok.Setter; + +import java.util.Date; + +/** + * 审批记录VO(已办用户任务 + 审批意见) + * + * @author Ray.Hao + * @since 4.9.0 + */ +@Schema(description = "审批记录对象") +@Getter +@Setter +public class ApprovalHistoryVO { + + @Schema(description = "节点ID(与流程走向环节 nodeId 对应,供前端按环节归位记录)") + private String activityId; + + @Schema(description = "节点名称") + private String activityName; + + @Schema(description = "办理人(用户名)") + private String assignee; + + @Schema(description = "审批意见(无则为空)") + private String comment; + + @Schema(description = "任务开始时间") + @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8") + private Date startTime; + + @Schema(description = "任务办理时间") + @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8") + private Date endTime; + +} diff --git a/src/main/java/com/youlai/boot/module/workflow/model/vo/DoneTaskVO.java b/src/main/java/com/youlai/boot/module/workflow/model/vo/DoneTaskVO.java new file mode 100644 index 00000000..4421224e --- /dev/null +++ b/src/main/java/com/youlai/boot/module/workflow/model/vo/DoneTaskVO.java @@ -0,0 +1,40 @@ +package com.youlai.boot.module.workflow.model.vo; + +import com.fasterxml.jackson.annotation.JsonFormat; +import io.swagger.v3.oas.annotations.media.Schema; +import lombok.Getter; +import lombok.Setter; + +import java.util.Date; + +/** + * 已办任务VO(已办分页列表) + * + * @author Ray.Hao + * @since 4.9.0 + */ +@Schema(description = "已办任务对象") +@Getter +@Setter +public class DoneTaskVO { + + @Schema(description = "任务ID") + private String id; + + @Schema(description = "任务名称") + private String name; + + @Schema(description = "流程实例ID") + private String processInstanceId; + + @Schema(description = "流程定义名称") + private String processName; + + @Schema(description = "任务办理时间") + @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8") + private Date endTime; + + @Schema(description = "处理意见") + private String comment; + +} diff --git a/src/main/java/com/youlai/boot/module/workflow/model/vo/InstanceDetailVO.java b/src/main/java/com/youlai/boot/module/workflow/model/vo/InstanceDetailVO.java new file mode 100644 index 00000000..c57fdc1f --- /dev/null +++ b/src/main/java/com/youlai/boot/module/workflow/model/vo/InstanceDetailVO.java @@ -0,0 +1,67 @@ +package com.youlai.boot.module.workflow.model.vo; + +import com.fasterxml.jackson.annotation.JsonFormat; +import com.youlai.boot.module.workflow.enums.InstanceStatusEnum; +import io.swagger.v3.oas.annotations.media.Schema; +import lombok.Getter; +import lombok.Setter; + +import java.util.Date; +import java.util.List; + +/** + * 流程实例详情VO(详情页渲染:发起表单回显 + 审批记录) + * + * @author Ray.Hao + * @since 4.9.0 + */ +@Schema(description = "流程实例详情对象") +@Getter +@Setter +public class InstanceDetailVO { + + @Schema(description = "流程实例ID") + private String id; + + @Schema(description = "流程定义名称") + private String processName; + + @Schema(description = "发起人(用户名)") + private String startUser; + + @Schema(description = "绑定表单标识(未绑定表单为空)") + private String formKey; + + @Schema(description = "发起表单规则(按提交时快照严格回显)") + private String formJson; + + @Schema(description = "发起表单全局配置(快照)") + private String optionsJson; + + @Schema(description = "发起表单数据(field -> value 映射的 JSON 字符串)") + private String dataJson; + + @Schema(description = "实例状态") + private InstanceStatusEnum status; + + @Schema(description = "终止原因(status=terminated 时有值)") + private String deleteReason; + + @Schema(description = "发起时间") + @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8") + private Date startTime; + + @Schema(description = "结束时间(运行中为空)") + @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8") + private Date endTime; + + @Schema(description = "审批记录(按时间正序)") + private List history; + + @Schema(description = "流程走向预览(按 BPMN 编排顺序,展示各环节审批角色与办理人)") + private List stages; + + @Schema(description = "当前进行中的环节下标(正常结束为环节总数即全部完成;终止/撤销为最后办完环节的下一位置)") + private Integer activeStageIndex; + +} diff --git a/src/main/java/com/youlai/boot/module/workflow/model/vo/InstancePageVO.java b/src/main/java/com/youlai/boot/module/workflow/model/vo/InstancePageVO.java new file mode 100644 index 00000000..b8f9ab7a --- /dev/null +++ b/src/main/java/com/youlai/boot/module/workflow/model/vo/InstancePageVO.java @@ -0,0 +1,51 @@ +package com.youlai.boot.module.workflow.model.vo; + +import com.fasterxml.jackson.annotation.JsonFormat; +import com.youlai.boot.module.workflow.enums.InstanceStatusEnum; +import io.swagger.v3.oas.annotations.media.Schema; +import lombok.Getter; +import lombok.Setter; + +import java.util.Date; + +/** + * 流程实例VO(我的流程分页列表) + * + * @author Ray.Hao + * @since 4.9.0 + */ +@Schema(description = "流程实例对象") +@Getter +@Setter +public class InstancePageVO { + + @Schema(description = "流程实例ID") + private String id; + + @Schema(description = "流程定义标识") + private String processDefinitionKey; + + @Schema(description = "流程定义名称") + private String processName; + + @Schema(description = "业务主键(绑定的表单数据ID,未绑定表单为空)") + private String businessKey; + + @Schema(description = "绑定表单标识(未绑定为空)") + private String formKey; + + @Schema(description = "实例状态") + private InstanceStatusEnum status; + + @Schema(description = "终止原因(status=terminated 时有值)") + private String deleteReason; + + @Schema(description = "发起时间") + @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8") + private Date startTime; + + @Schema(description = "结束时间(运行中为空)") + @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8") + private Date endTime; + +} diff --git a/src/main/java/com/youlai/boot/module/workflow/model/vo/ModelVO.java b/src/main/java/com/youlai/boot/module/workflow/model/vo/ModelVO.java new file mode 100644 index 00000000..124249ad --- /dev/null +++ b/src/main/java/com/youlai/boot/module/workflow/model/vo/ModelVO.java @@ -0,0 +1,57 @@ +package com.youlai.boot.module.workflow.model.vo; + +import com.fasterxml.jackson.annotation.JsonFormat; +import io.swagger.v3.oas.annotations.media.Schema; +import lombok.Getter; +import lombok.Setter; + +import java.util.Date; + +/** + * 流程模型VO(分页列表) + * + * @author Ray.Hao + * @since 4.9.0 + */ +@Schema(description = "流程模型对象") +@Getter +@Setter +public class ModelVO { + + @Schema(description = "模型ID") + private String id; + + @Schema(description = "模型名称") + private String name; + + @Schema(description = "模型标识") + private String key; + + @Schema(description = "模型描述") + private String description; + + @Schema(description = "版本号") + private Integer version; + + @Schema(description = "最新发布定义ID(未发布为 null)") + private String definitionId; + + @Schema(description = "最新发布版本号(未发布为 null)") + private Integer publishedVersion; + + @Schema(description = "发布状态:true=已停用,false=已启用(未发布为 null)") + private Boolean suspended; + + @Schema(description = "发布时间(未发布为 null)") + @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8") + private Date deploymentTime; + + @Schema(description = "创建时间") + @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8") + private Date createTime; + + @Schema(description = "最后更新时间") + @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8") + private Date updateTime; + +} diff --git a/src/main/java/com/youlai/boot/module/workflow/model/vo/ModelXmlVO.java b/src/main/java/com/youlai/boot/module/workflow/model/vo/ModelXmlVO.java new file mode 100644 index 00000000..27801206 --- /dev/null +++ b/src/main/java/com/youlai/boot/module/workflow/model/vo/ModelXmlVO.java @@ -0,0 +1,25 @@ +package com.youlai.boot.module.workflow.model.vo; + +import io.swagger.v3.oas.annotations.media.Schema; +import lombok.Getter; +import lombok.Setter; + +/** + * 流程模型 XML VO(设计器回显) + * + * @author Ray.Hao + * @since 4.9.0 + */ +@Schema(description = "流程模型XML对象") +@Getter +@Setter +public class ModelXmlVO { + + @Schema(description = "BPMN 2.0 XML(bpmn-js 导入渲染;新模型为空串)") + private String xml; + + public ModelXmlVO(String xml) { + this.xml = xml; + } + +} diff --git a/src/main/java/com/youlai/boot/module/workflow/model/vo/ProcessDiagramVO.java b/src/main/java/com/youlai/boot/module/workflow/model/vo/ProcessDiagramVO.java new file mode 100644 index 00000000..c36f7776 --- /dev/null +++ b/src/main/java/com/youlai/boot/module/workflow/model/vo/ProcessDiagramVO.java @@ -0,0 +1,29 @@ +package com.youlai.boot.module.workflow.model.vo; + +import io.swagger.v3.oas.annotations.media.Schema; +import lombok.Getter; +import lombok.Setter; + +import java.util.List; + +/** + * 流程图数据VO(bpmn-js 渲染 + 节点高亮) + * + * @author Ray.Hao + * @since 4.9.0 + */ +@Schema(description = "流程图数据对象") +@Getter +@Setter +public class ProcessDiagramVO { + + @Schema(description = "BPMN 2.0 XML(bpmn-js 导入渲染)") + private String bpmnXml; + + @Schema(description = "已办节点ID列表(高亮为走过路径)") + private List executedActivityIds; + + @Schema(description = "进行中节点ID列表(高亮为当前待办)") + private List activeActivityIds; + +} diff --git a/src/main/java/com/youlai/boot/module/workflow/model/vo/ProcessStageVO.java b/src/main/java/com/youlai/boot/module/workflow/model/vo/ProcessStageVO.java new file mode 100644 index 00000000..b14fcabf --- /dev/null +++ b/src/main/java/com/youlai/boot/module/workflow/model/vo/ProcessStageVO.java @@ -0,0 +1,35 @@ +package com.youlai.boot.module.workflow.model.vo; + +import io.swagger.v3.oas.annotations.media.Schema; +import lombok.Builder; +import lombok.Getter; + +import java.util.List; + +/** + * 流程审批阶段VO(发起页与审批弹窗的流程走向预览) + * + * @author Ray.Hao + * @since 4.9.0 + */ +@Schema(description = "流程审批阶段对象") +@Getter +@Builder +public class ProcessStageVO { + + @Schema(description = "节点ID") + private final String nodeId; + + @Schema(description = "节点名称(审批环节)") + private final String nodeName; + + @Schema(description = "审批角色名称列表(角色候选组任务)") + private final List roleNames; + + @Schema(description = "角色成员账号列表(演示环境直观展示哪个用户办理该环节)") + private final List userNames; + + @Schema(description = "是否发起人本人办理(assignee=${initiator})") + private final Boolean initiator; + +} diff --git a/src/main/java/com/youlai/boot/module/workflow/model/vo/RejectTargetVO.java b/src/main/java/com/youlai/boot/module/workflow/model/vo/RejectTargetVO.java new file mode 100644 index 00000000..d12ebc8a --- /dev/null +++ b/src/main/java/com/youlai/boot/module/workflow/model/vo/RejectTargetVO.java @@ -0,0 +1,29 @@ +package com.youlai.boot.module.workflow.model.vo; + +import io.swagger.v3.oas.annotations.media.Schema; +import lombok.Getter; +import lombok.Setter; + +/** + * 驳回目标节点VO(驳回下拉选择) + * + * @author Ray.Hao + * @since 4.9.0 + */ +@Schema(description = "驳回目标节点对象") +@Getter +@Setter +public class RejectTargetVO { + + @Schema(description = "节点ID") + private String activityId; + + @Schema(description = "节点名称") + private String activityName; + + public RejectTargetVO(String activityId, String activityName) { + this.activityId = activityId; + this.activityName = activityName; + } + +} diff --git a/src/main/java/com/youlai/boot/module/workflow/model/vo/StartableProcessVO.java b/src/main/java/com/youlai/boot/module/workflow/model/vo/StartableProcessVO.java new file mode 100644 index 00000000..3c9482a1 --- /dev/null +++ b/src/main/java/com/youlai/boot/module/workflow/model/vo/StartableProcessVO.java @@ -0,0 +1,33 @@ +package com.youlai.boot.module.workflow.model.vo; + +import io.swagger.v3.oas.annotations.media.Schema; +import lombok.Getter; +import lombok.Setter; + +/** + * 可发起流程VO(发起页流程选择列表) + * + * @author Ray.Hao + * @since 4.9.0 + */ +@Schema(description = "可发起流程对象") +@Getter +@Setter +public class StartableProcessVO { + + @Schema(description = "流程定义ID") + private String id; + + @Schema(description = "流程定义标识") + private String key; + + @Schema(description = "流程定义名称") + private String name; + + @Schema(description = "版本号") + private Integer version; + + @Schema(description = "绑定表单标识(开始节点 formKey,未绑定为空;空则直接发起,无表单填写)") + private String formKey; + +} diff --git a/src/main/java/com/youlai/boot/module/workflow/model/vo/TaskDetailVO.java b/src/main/java/com/youlai/boot/module/workflow/model/vo/TaskDetailVO.java new file mode 100644 index 00000000..d67b546c --- /dev/null +++ b/src/main/java/com/youlai/boot/module/workflow/model/vo/TaskDetailVO.java @@ -0,0 +1,56 @@ +package com.youlai.boot.module.workflow.model.vo; + +import io.swagger.v3.oas.annotations.media.Schema; +import lombok.Getter; +import lombok.Setter; + +import java.util.List; + +/** + * 待办任务详情VO(审批页渲染:发起表单只读回显 + 审批记录) + * + * @author Ray.Hao + * @since 4.9.0 + */ +@Schema(description = "待办任务详情对象") +@Getter +@Setter +public class TaskDetailVO { + + @Schema(description = "任务ID") + private String taskId; + + @Schema(description = "任务名称") + private String taskName; + + @Schema(description = "当前任务节点ID(BPMN 节点,用于流程走向高亮定位)") + private String taskDefinitionKey; + + @Schema(description = "流程实例ID") + private String processInstanceId; + + @Schema(description = "流程定义名称") + private String processName; + + @Schema(description = "发起表单标识(未绑定表单为空)") + private String formKey; + + @Schema(description = "发起表单规则(按提交时快照严格回显)") + private String formJson; + + @Schema(description = "发起表单全局配置(快照)") + private String optionsJson; + + @Schema(description = "发起表单数据(field -> value 映射的 JSON 字符串)") + private String dataJson; + + @Schema(description = "当前任务绑定表单标识(任务节点 formKey,未绑定为空)") + private String taskFormKey; + + @Schema(description = "审批记录(按时间正序)") + private List history; + + @Schema(description = "流程走向预览(按 BPMN 编排顺序,展示各环节审批角色与办理人)") + private List stages; + +} diff --git a/src/main/java/com/youlai/boot/module/workflow/model/vo/TodoTaskVO.java b/src/main/java/com/youlai/boot/module/workflow/model/vo/TodoTaskVO.java new file mode 100644 index 00000000..f157cfa3 --- /dev/null +++ b/src/main/java/com/youlai/boot/module/workflow/model/vo/TodoTaskVO.java @@ -0,0 +1,43 @@ +package com.youlai.boot.module.workflow.model.vo; + +import com.fasterxml.jackson.annotation.JsonFormat; +import io.swagger.v3.oas.annotations.media.Schema; +import lombok.Getter; +import lombok.Setter; + +import java.util.Date; + +/** + * 待办任务VO(待办分页列表) + * + * @author Ray.Hao + * @since 4.9.0 + */ +@Schema(description = "待办任务对象") +@Getter +@Setter +public class TodoTaskVO { + + @Schema(description = "任务ID") + private String id; + + @Schema(description = "任务名称") + private String name; + + @Schema(description = "流程实例ID") + private String processInstanceId; + + @Schema(description = "流程定义名称") + private String processName; + + @Schema(description = "业务主键(绑定的表单数据ID,未绑定表单为空)") + private String businessKey; + + @Schema(description = "绑定表单标识(未绑定为空)") + private String formKey; + + @Schema(description = "任务创建时间") + @JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8") + private Date createTime; + +} diff --git a/src/main/java/com/youlai/boot/module/workflow/runner/WorkflowDemoInitializer.java b/src/main/java/com/youlai/boot/module/workflow/runner/WorkflowDemoInitializer.java new file mode 100644 index 00000000..b571591b --- /dev/null +++ b/src/main/java/com/youlai/boot/module/workflow/runner/WorkflowDemoInitializer.java @@ -0,0 +1,30 @@ +package com.youlai.boot.module.workflow.runner; + +import com.youlai.boot.module.workflow.service.WorkflowDemoService; +import com.youlai.boot.module.workflow.config.ConditionalOnWorkflowEnabled; +import lombok.RequiredArgsConstructor; +import org.springframework.boot.ApplicationArguments; +import org.springframework.boot.ApplicationRunner; +import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; +import org.springframework.stereotype.Component; + +/** + * 演示流程启动初始化器 + * + * @author Ray.Hao + * @since 4.9.0 + */ +@ConditionalOnWorkflowEnabled +@Component +@ConditionalOnProperty(name = "workflow.demo.enabled", havingValue = "true") +@RequiredArgsConstructor +public class WorkflowDemoInitializer implements ApplicationRunner { + + private final WorkflowDemoService workflowDemoService; + + @Override + public void run(ApplicationArguments args) { + workflowDemoService.initIfAbsent(); + } + +} diff --git a/src/main/java/com/youlai/boot/module/workflow/service/WorkflowDefinitionService.java b/src/main/java/com/youlai/boot/module/workflow/service/WorkflowDefinitionService.java new file mode 100644 index 00000000..9c60c1a7 --- /dev/null +++ b/src/main/java/com/youlai/boot/module/workflow/service/WorkflowDefinitionService.java @@ -0,0 +1,49 @@ +package com.youlai.boot.module.workflow.service; + +import com.youlai.boot.module.workflow.model.form.DefinitionStateForm; +import com.youlai.boot.module.workflow.model.vo.ModelXmlVO; +import com.youlai.boot.module.workflow.model.vo.ProcessStageVO; +import com.youlai.boot.module.workflow.model.vo.StartableProcessVO; + +import java.util.List; + +/** + * 流程定义业务接口(发布产物:可发起列表、审批阶段、流程图、启用停用) + * + * @author Ray.Hao + * @since 4.9.0 + */ +public interface WorkflowDefinitionService { + + /** + * 可发起流程列表(最新版本且激活,发起页下拉数据源) + * + * @return 流程定义集合 + */ + List listStartableProcesses(); + + /** + * 流程审批阶段预览(按 BPMN 编排顺序解析各环节的审批角色与角色成员) + * + * @param definitionId 流程定义ID + * @return 审批阶段集合 + */ + List listProcessStages(String definitionId); + + /** + * 获取流程定义 BPMN XML(流程图查看) + * + * @param definitionId 流程定义ID + * @return BPMN 2.0 XML + */ + ModelXmlVO getDefinitionXml(String definitionId); + + /** + * 启用/停用流程(停用后不可发起新实例,存量实例不受影响) + * + * @param definitionId 流程定义ID + * @param formData 状态表单数据 + */ + void updateDefinitionState(String definitionId, DefinitionStateForm formData); + +} diff --git a/src/main/java/com/youlai/boot/module/workflow/service/WorkflowDemoService.java b/src/main/java/com/youlai/boot/module/workflow/service/WorkflowDemoService.java new file mode 100644 index 00000000..c088d844 --- /dev/null +++ b/src/main/java/com/youlai/boot/module/workflow/service/WorkflowDemoService.java @@ -0,0 +1,21 @@ +package com.youlai.boot.module.workflow.service; + +/** + * 演示流程服务接口(请假、报销、采购、用章) + * + * @author Ray.Hao + * @since 4.9.0 + */ +public interface WorkflowDemoService { + + /** + * 幂等初始化演示流程(已存在则跳过):部署流程定义 + 创建模型草稿 + */ + void initIfAbsent(); + + /** + * 重置工作流数据(恢复出厂):清空所有流程定义、模型、实例与历史(含用户自建)及关联表单提交数据后重建演示流程 + */ + void reset(); + +} diff --git a/src/main/java/com/youlai/boot/module/workflow/service/WorkflowInstanceService.java b/src/main/java/com/youlai/boot/module/workflow/service/WorkflowInstanceService.java new file mode 100644 index 00000000..a0e44be5 --- /dev/null +++ b/src/main/java/com/youlai/boot/module/workflow/service/WorkflowInstanceService.java @@ -0,0 +1,65 @@ +package com.youlai.boot.module.workflow.service; + +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; +import com.youlai.boot.module.workflow.model.form.StartProcessForm; +import com.youlai.boot.module.workflow.model.query.WorkflowInstancePageQuery; +import com.youlai.boot.module.workflow.model.vo.InstanceDetailVO; +import com.youlai.boot.module.workflow.model.vo.InstancePageVO; +import com.youlai.boot.module.workflow.model.vo.ProcessDiagramVO; + +/** + * 流程实例业务接口(发起、我的流程、详情、流程图、撤销/终止) + * + * @author Ray.Hao + * @since 4.9.0 + */ +public interface WorkflowInstanceService { + + /** + * 发起流程(绑定表单时保存表单数据并以数据ID作为 businessKey,表单字段随流程变量提交) + * + * @param formData 发起流程表单数据 + * @return 流程实例ID + */ + String startProcess(StartProcessForm formData); + + /** + * 我的流程分页列表(当前用户发起,含运行中/已完成/已终止) + * + * @param queryParams 查询参数 + * @return 分页结果 + */ + Page getInstancePage(WorkflowInstancePageQuery queryParams); + + /** + * 获取流程图数据(BPMN XML + 已办/进行中节点,bpmn-js 高亮渲染) + * + * @param instanceId 流程实例ID + * @return 流程图数据 + */ + ProcessDiagramVO getProcessDiagram(String instanceId); + + /** + * 获取流程实例详情(发起表单回显 + 审批记录) + * + * @param instanceId 流程实例ID + * @return 实例详情 + */ + InstanceDetailVO getInstanceDetail(String instanceId); + + /** + * 撤销流程(仅发起人可撤销运行中实例) + * + * @param instanceId 流程实例ID + */ + void cancelProcessInstance(String instanceId); + + /** + * 终止流程(管理员终止任意运行中实例) + * + * @param instanceId 流程实例ID + * @param reason 终止原因 + */ + void terminateProcessInstance(String instanceId, String reason); + +} diff --git a/src/main/java/com/youlai/boot/module/workflow/service/WorkflowModelService.java b/src/main/java/com/youlai/boot/module/workflow/service/WorkflowModelService.java new file mode 100644 index 00000000..e0ac1b06 --- /dev/null +++ b/src/main/java/com/youlai/boot/module/workflow/service/WorkflowModelService.java @@ -0,0 +1,87 @@ +package com.youlai.boot.module.workflow.service; + +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; +import com.youlai.boot.module.workflow.model.form.ModelForm; +import com.youlai.boot.module.workflow.model.form.ModelXmlForm; +import com.youlai.boot.module.workflow.model.query.WorkflowModelPageQuery; +import com.youlai.boot.module.workflow.model.vo.ModelVO; +import com.youlai.boot.module.workflow.model.vo.ModelXmlVO; + +import java.util.Collection; +import java.util.List; +import java.util.Map; +import java.util.Set; + +/** + * 流程模型业务接口(设计器侧:模型 CRUD、XML 保存、部署、表单引用查询) + * + * @author Ray.Hao + * @since 4.9.0 + */ +public interface WorkflowModelService { + + /** + * 流程模型分页列表 + * + * @param queryParams 查询参数 + * @return 分页结果 + */ + Page getModelPage(WorkflowModelPageQuery queryParams); + + /** + * 新增流程模型(内置开始-审批-结束模板,设计器开箱即画) + * + * @param formData 模型表单数据 + * @return 是否成功 + */ + boolean saveModel(ModelForm formData); + + /** + * 修改流程模型(标识创建后不可修改) + * + * @param modelId 模型ID + * @param formData 模型表单数据 + * @return 是否成功 + */ + boolean updateModel(String modelId, ModelForm formData); + + /** + * 删除流程模型(级联删除其全部发布版本;存在运行中实例时拦截) + * + * @param modelIds 模型ID集合 + */ + void removeModels(List modelIds); + + /** + * 查询引用指定表单的流程(已部署定义与模型草稿的表单绑定) + * + * @param formKeys 表单标识集合 + * @return 表单标识 → 引用它的流程名称集合(无引用返回空 Map) + */ + Map> getFormReferences(Collection formKeys); + + /** + * 获取模型 BPMN XML(设计器回显) + * + * @param modelId 模型ID + * @return BPMN 2.0 XML + */ + ModelXmlVO getModelXml(String modelId); + + /** + * 保存模型 BPMN XML(设计器产出) + * + * @param modelId 模型ID + * @param formData XML 表单数据 + * @return 是否成功 + */ + boolean saveModelXml(String modelId, ModelXmlForm formData); + + /** + * 部署流程模型(校验 XML 并发布为流程定义新版本) + * + * @param modelId 模型ID + */ + void deployModel(String modelId); + +} diff --git a/src/main/java/com/youlai/boot/module/workflow/service/WorkflowTaskService.java b/src/main/java/com/youlai/boot/module/workflow/service/WorkflowTaskService.java new file mode 100644 index 00000000..22206e42 --- /dev/null +++ b/src/main/java/com/youlai/boot/module/workflow/service/WorkflowTaskService.java @@ -0,0 +1,78 @@ +package com.youlai.boot.module.workflow.service; + +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; +import com.youlai.boot.module.workflow.model.form.CompleteTaskForm; +import com.youlai.boot.module.workflow.model.form.RejectTaskForm; +import com.youlai.boot.module.workflow.model.query.WorkflowTaskPageQuery; +import com.youlai.boot.module.workflow.model.vo.DoneTaskVO; +import com.youlai.boot.module.workflow.model.vo.RejectTargetVO; +import com.youlai.boot.module.workflow.model.vo.TaskDetailVO; +import com.youlai.boot.module.workflow.model.vo.TodoTaskVO; + +import java.util.List; + +/** + * 流程任务业务接口(待办/已办、审批通过/驳回) + * + * @author Ray.Hao + * @since 4.9.0 + */ +public interface WorkflowTaskService { + + /** + * 待办任务分页列表(当前用户的候选/分配任务) + * + * @param queryParams 查询参数 + * @return 分页结果 + */ + Page getTodoTaskPage(WorkflowTaskPageQuery queryParams); + + /** + * 已办任务分页列表(当前用户已办理的任务) + * + * @param queryParams 查询参数 + * @return 分页结果 + */ + Page getDoneTaskPage(WorkflowTaskPageQuery queryParams); + + /** + * 获取待办任务详情(发起表单只读回显 + 审批记录) + * + * @param taskId 任务ID + * @return 任务详情 + */ + TaskDetailVO getTaskDetail(String taskId); + + /** + * 获取驳回目标节点列表(当前实例已办理过的用户任务) + * + * @param taskId 任务ID + * @return 驳回目标集合 + */ + List listRejectTargets(String taskId); + + /** + * 审批通过(意见归档为引擎评论,变量驱动后续网关) + * + * @param taskId 任务ID + * @param formData 审批表单数据 + */ + void completeTask(String taskId, CompleteTaskForm formData); + + /** + * 驳回(流转到指定历史节点,任务与意见随历史归档) + * + * @param taskId 任务ID + * @param formData 驳回表单数据 + */ + void rejectTask(String taskId, RejectTaskForm formData); + + /** + * 用 AI 汇总表单数据与审批记录,生成审批摘要 + * + * @param taskId 任务ID + * @return 摘要文本 + */ + String aiSummarizeTask(String taskId); + +} diff --git a/src/main/java/com/youlai/boot/module/workflow/service/impl/WorkflowDefinitionServiceImpl.java b/src/main/java/com/youlai/boot/module/workflow/service/impl/WorkflowDefinitionServiceImpl.java new file mode 100644 index 00000000..f27ed613 --- /dev/null +++ b/src/main/java/com/youlai/boot/module/workflow/service/impl/WorkflowDefinitionServiceImpl.java @@ -0,0 +1,189 @@ +package com.youlai.boot.module.workflow.service.impl; + +import cn.hutool.core.lang.Assert; +import cn.hutool.core.util.StrUtil; +import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; +import com.youlai.boot.module.workflow.model.form.DefinitionStateForm; +import com.youlai.boot.module.workflow.model.vo.ModelXmlVO; +import com.youlai.boot.module.workflow.model.vo.ProcessStageVO; +import com.youlai.boot.module.workflow.model.vo.StartableProcessVO; +import com.youlai.boot.module.workflow.service.WorkflowDefinitionService; +import com.youlai.boot.module.workflow.util.BpmnModelHelper; +import com.youlai.boot.system.model.entity.Role; +import com.youlai.boot.system.model.entity.SysUser; +import com.youlai.boot.system.model.entity.UserRole; +import com.youlai.boot.system.service.RoleService; +import com.youlai.boot.system.service.UserService; +import com.youlai.boot.system.service.UserRoleService; +import com.youlai.boot.module.workflow.config.ConditionalOnWorkflowEnabled; +import lombok.RequiredArgsConstructor; +import org.flowable.engine.RepositoryService; +import org.flowable.engine.repository.ProcessDefinition; +import org.springframework.stereotype.Service; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.stream.Collectors; + +/** + * 流程定义业务实现类 + * + * @author Ray.Hao + * @since 4.9.0 + */ +@ConditionalOnWorkflowEnabled +@Service +@RequiredArgsConstructor +public class WorkflowDefinitionServiceImpl implements WorkflowDefinitionService { + + private final RepositoryService repositoryService; + private final BpmnModelHelper bpmnModelHelper; + private final RoleService roleService; + private final UserService userService; + private final UserRoleService userRoleService; + + /** + * 可发起流程列表 + */ + @Override + public List listStartableProcesses() { + return repositoryService.createProcessDefinitionQuery().latestVersion().active() + .orderByProcessDefinitionKey().asc().list().stream() + .map(definition -> { + StartableProcessVO processVO = new StartableProcessVO(); + processVO.setId(definition.getId()); + processVO.setKey(definition.getKey()); + processVO.setName(definition.getName()); + processVO.setVersion(definition.getVersion()); + processVO.setFormKey(bpmnModelHelper.getStartFormKey(definition.getId())); + return processVO; + }).toList(); + } + + /** + * 流程审批阶段预览:BPMN 节点的候选组(角色编码)与办理人表达式翻译为角色名和角色成员账号, + * 让发起人在提交前即可看到"哪个环节由谁审批" + */ + @Override + public List listProcessStages(String definitionId) { + getDefinition(definitionId); + List userTasks = bpmnModelHelper.getUserTasks(definitionId); + if (userTasks.isEmpty()) { + return List.of(); + } + + // 涉及角色一次性批量解析(角色名 + 成员账号),避免逐节点回查 + Set roleCodes = userTasks.stream() + .flatMap(task -> task.candidateGroups().stream()) + .collect(Collectors.toSet()); + RoleDirectory directory = loadRoleDirectory(roleCodes); + + return userTasks.stream().map(task -> { + // 候选组任务的办理人:角色成员账号;字面量 assignee(固定用户)与未知表达式原样展示 + List userNames = new ArrayList<>(task.candidateGroups().stream() + .flatMap(code -> directory.roleUsers().getOrDefault(code, List.of()).stream()) + .distinct() + .toList()); + boolean byInitiator = StrUtil.isNotBlank(task.assignee()) + && task.assignee().contains("initiator"); + if (StrUtil.isNotBlank(task.assignee()) && !byInitiator) { + userNames.add(task.assignee()); + } + return ProcessStageVO.builder() + .nodeId(task.nodeId()) + .nodeName(task.nodeName()) + // 角色已删除或未初始化时回退展示编码,环节不因数据缺失而空白 + .roleNames(task.candidateGroups().stream() + .map(code -> directory.roleNames().getOrDefault(code, code)) + .toList()) + .userNames(userNames) + .initiator(byInitiator) + .build(); + }).toList(); + } + + /** + * 角色目录(编码 → 角色名 / 成员账号) + * + * @param roleNames 编码 → 角色名称 + * @param roleUsers 编码 → 成员账号列表 + */ + private record RoleDirectory(Map roleNames, Map> roleUsers) { + } + + /** + * 批量解析角色名称与成员账号(角色 → 用户ID → 账号 三段批查) + */ + private RoleDirectory loadRoleDirectory(Set roleCodes) { + if (roleCodes.isEmpty()) { + return new RoleDirectory(Map.of(), Map.of()); + } + List roles = roleService.list( + new LambdaQueryWrapper().in(Role::getCode, roleCodes)); + if (roles.isEmpty()) { + return new RoleDirectory(Map.of(), Map.of()); + } + List roleIds = roles.stream().map(Role::getId).toList(); + Map> userIdsByRole = userRoleService.list( + new LambdaQueryWrapper().in(UserRole::getRoleId, roleIds)) + .stream().collect(Collectors.groupingBy(UserRole::getRoleId, + Collectors.mapping(UserRole::getUserId, Collectors.toList()))); + Set userIds = userIdsByRole.values().stream() + .flatMap(List::stream).collect(Collectors.toSet()); + Map usernameById = userIds.isEmpty() ? Collections.emptyMap() + : userService.listByIds(userIds).stream() + .collect(Collectors.toMap(SysUser::getId, SysUser::getUsername)); + + Map> roleUsers = new HashMap<>(); + roles.forEach(role -> roleUsers.put(role.getCode(), + userIdsByRole.getOrDefault(role.getId(), List.of()).stream() + .map(usernameById::get) + .filter(StrUtil::isNotBlank) + .toList())); + Map roleNames = roles.stream() + .collect(Collectors.toMap(Role::getCode, Role::getName)); + return new RoleDirectory(roleNames, roleUsers); + } + + /** + * 获取流程定义 BPMN XML + * + * @param definitionId 流程定义ID + */ + @Override + public ModelXmlVO getDefinitionXml(String definitionId) { + getDefinition(definitionId); + return new ModelXmlVO(bpmnModelHelper.getBpmnXml(definitionId)); + } + + /** + * 修改流程定义状态 + * + * @param definitionId 流程定义ID + * @param formData 状态表单数据 + */ + @Override + public void updateDefinitionState(String definitionId, DefinitionStateForm formData) { + getDefinition(definitionId); + if (Boolean.TRUE.equals(formData.getSuspend())) { + repositoryService.suspendProcessDefinitionById(definitionId); + } else { + repositoryService.activateProcessDefinitionById(definitionId); + } + } + + /** + * 获取流程定义(不存在即抛业务异常) + */ + private ProcessDefinition getDefinition(String definitionId) { + ProcessDefinition definition = repositoryService.createProcessDefinitionQuery() + .processDefinitionId(definitionId).singleResult(); + Assert.notNull(definition, "流程定义不存在"); + return definition; + } + +} diff --git a/src/main/java/com/youlai/boot/module/workflow/service/impl/WorkflowDemoServiceImpl.java b/src/main/java/com/youlai/boot/module/workflow/service/impl/WorkflowDemoServiceImpl.java new file mode 100644 index 00000000..a878955c --- /dev/null +++ b/src/main/java/com/youlai/boot/module/workflow/service/impl/WorkflowDemoServiceImpl.java @@ -0,0 +1,176 @@ +package com.youlai.boot.module.workflow.service.impl; + +import cn.hutool.core.util.StrUtil; +import cn.hutool.json.JSONUtil; +import com.youlai.boot.common.exception.BusinessException; +import com.youlai.boot.module.form.service.FormDataService; +import com.youlai.boot.module.workflow.service.WorkflowDemoService; +import com.youlai.boot.module.workflow.util.BpmnModelHelper; +import com.youlai.boot.module.workflow.config.ConditionalOnWorkflowEnabled; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.flowable.engine.RepositoryService; +import org.flowable.engine.repository.Model; +import org.flowable.engine.repository.ProcessDefinition; +import org.springframework.core.io.ClassPathResource; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; +import org.springframework.util.FileCopyUtils; + +import java.io.InputStreamReader; +import java.nio.charset.StandardCharsets; +import java.util.HashSet; +import java.util.List; +import java.util.Set; + +/** + * 演示流程服务实现(请假、报销、采购、用章) + * + * @author Ray.Hao + * @since 4.9.0 + */ +@ConditionalOnWorkflowEnabled +@Service +@RequiredArgsConstructor +@Slf4j +public class WorkflowDemoServiceImpl implements WorkflowDemoService { + + private final RepositoryService repositoryService; + private final FormDataService formDataService; + private final BpmnModelHelper bpmnModelHelper; + + // 演示流程清单(key 与 resources/workflow/ 下同名 BPMN 文件的 process id 一致) + private static final List DEMO_PROCESSES = List.of( + new DemoProcess("leave", "请假审批"), + new DemoProcess("expense", "报销审批"), + new DemoProcess("purchase", "采购申请"), + new DemoProcess("seal", "用章申请") + ); + + @Override + public void initIfAbsent() { + DEMO_PROCESSES.forEach(this::initDemoProcess); + } + + @Override + @Transactional(rollbackFor = Exception.class) + public void reset() { + // 删除前收集全部流程定义的发起表单 key:引擎级联不覆盖业务库表单数据,删除后 businessKey 无从追溯 + Set formKeys = collectStartFormKeys(); + // 全量清空:定义(级联删除实例与历史,含用户自建流程)→ 模型草稿 → 流程关联的表单提交数据 + repositoryService.createDeploymentQuery().list() + .forEach(deployment -> repositoryService.deleteDeployment(deployment.getId(), true)); + repositoryService.createModelQuery().list() + .forEach(model -> repositoryService.deleteModel(model.getId())); + formKeys.forEach(this::deleteFormData); + // 重建演示流程(失败抛异常中断,整体回滚保证重置原子性) + DEMO_PROCESSES.forEach(this::redeployDemoProcess); + log.info("工作流数据已重置:清理 {} 个表单的提交数据,重建演示流程 {} 个", formKeys.size(), DEMO_PROCESSES.size()); + } + + /** + * 收集全部流程定义的发起表单 key(单个定义解析失败不影响其余收集) + */ + private Set collectStartFormKeys() { + Set formKeys = new HashSet<>(); + for (ProcessDefinition definition : repositoryService.createProcessDefinitionQuery().list()) { + try { + String formKey = bpmnModelHelper.getStartFormKey(definition.getId()); + if (StrUtil.isNotBlank(formKey)) { + formKeys.add(formKey); + } + } catch (Exception e) { + log.warn("流程定义 [{}] 表单标识解析失败,跳过其表单数据清理", definition.getKey()); + } + } + return formKeys; + } + + /** + * 重建单个演示流程(全量清空后调用) + */ + private void redeployDemoProcess(DemoProcess process) { + try { + String bpmnXml = readBpmnXml(process.key()); + repositoryService.createDeployment() + .name(process.name()) + .key(process.key()) + .addString(process.key() + ".bpmn20.xml", bpmnXml) + .deploy(); + createModelIfAbsent(process, bpmnXml); + } catch (Exception e) { + throw new BusinessException("演示流程 [" + process.name() + "] 重建失败:" + e.getMessage()); + } + } + + /** + * 初始化单个演示流程(资源文件与 key 同名,放 workflow 目录避开 processes/ 自动部署) + */ + private void initDemoProcess(DemoProcess process) { + try { + String bpmnXml = readBpmnXml(process.key()); + deployDefinitionIfAbsent(process, bpmnXml); + createModelIfAbsent(process, bpmnXml); + } catch (Exception e) { + log.error("演示流程 [{}] 初始化失败", process.name(), e); + } + } + + /** + * 幂等部署流程定义(已存在同 key 定义则跳过,删除定义后重启可重新部署) + */ + private void deployDefinitionIfAbsent(DemoProcess process, String bpmnXml) { + long count = repositoryService.createProcessDefinitionQuery() + .processDefinitionKey(process.key()).count(); + if (count > 0) { + return; + } + repositoryService.createDeployment() + .name(process.name()) + .key(process.key()) + .addString(process.key() + ".bpmn20.xml", bpmnXml) + .deploy(); + log.info("演示流程 [{}] 部署完成", process.name()); + } + + /** + * 幂等创建模型草稿(流程模型页数据源),editorSource 与部署 XML 同源 + */ + private void createModelIfAbsent(DemoProcess process, String bpmnXml) { + long count = repositoryService.createModelQuery() + .modelKey(process.key()).count(); + if (count > 0) { + return; + } + Model model = repositoryService.newModel(); + model.setKey(process.key()); + model.setName(process.name()); + model.setMetaInfo(JSONUtil.createObj().set("description", "演示流程").toString()); + repositoryService.saveModel(model); + repositoryService.addModelEditorSource(model.getId(), bpmnXml.getBytes(StandardCharsets.UTF_8)); + log.info("演示流程 [{}] 模型创建完成", process.name()); + } + + /** + * 清理演示表单提交数据(流程 businessKey 指向 form_data,随流程一并复位) + */ + private void deleteFormData(String formKey) { + formDataService.removeByFormKey(formKey); + } + + /** + * 读取演示流程 BPMN 资源 + */ + private String readBpmnXml(String key) throws Exception { + return FileCopyUtils.copyToString(new InputStreamReader( + new ClassPathResource("workflow/" + key + ".bpmn20.xml").getInputStream(), + StandardCharsets.UTF_8)); + } + + /** + * 演示流程定义(key 即 BPMN 文件名与流程标识) + */ + private record DemoProcess(String key, String name) { + } + +} diff --git a/src/main/java/com/youlai/boot/module/workflow/service/impl/WorkflowInstanceServiceImpl.java b/src/main/java/com/youlai/boot/module/workflow/service/impl/WorkflowInstanceServiceImpl.java new file mode 100644 index 00000000..dda6c3d9 --- /dev/null +++ b/src/main/java/com/youlai/boot/module/workflow/service/impl/WorkflowInstanceServiceImpl.java @@ -0,0 +1,300 @@ +package com.youlai.boot.module.workflow.service.impl; + +import cn.hutool.core.lang.Assert; +import cn.hutool.core.util.NumberUtil; +import cn.hutool.core.util.StrUtil; +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; +import com.youlai.boot.framework.security.util.SecurityUtils; +import com.youlai.boot.module.form.model.vo.FormDataVO; +import com.youlai.boot.module.form.service.FormDataService; +import com.youlai.boot.module.workflow.enums.InstanceStatusEnum; +import com.youlai.boot.module.workflow.model.form.StartProcessForm; +import com.youlai.boot.module.workflow.model.query.WorkflowInstancePageQuery; +import com.youlai.boot.module.workflow.model.vo.InstanceDetailVO; +import com.youlai.boot.module.workflow.model.vo.InstancePageVO; +import com.youlai.boot.module.workflow.model.vo.ProcessDiagramVO; +import com.youlai.boot.module.workflow.model.vo.ProcessStageVO; +import com.youlai.boot.module.workflow.service.WorkflowDefinitionService; +import com.youlai.boot.module.workflow.service.WorkflowInstanceService; +import com.youlai.boot.module.workflow.util.ApprovalHistoryHelper; +import com.youlai.boot.module.workflow.util.BpmnModelHelper; +import com.youlai.boot.module.workflow.config.ConditionalOnWorkflowEnabled; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.flowable.common.engine.impl.identity.Authentication; +import org.flowable.engine.HistoryService; +import org.flowable.engine.RepositoryService; +import org.flowable.engine.RuntimeService; +import org.flowable.engine.history.HistoricActivityInstance; +import org.flowable.engine.history.HistoricProcessInstance; +import org.flowable.engine.history.HistoricProcessInstanceQuery; +import org.flowable.engine.repository.ProcessDefinition; +import org.flowable.engine.runtime.ProcessInstance; +import org.springframework.stereotype.Service; + +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; + +/** + * 流程实例业务实现类 + * + * @author Ray.Hao + * @since 4.9.0 + */ +@Slf4j +@ConditionalOnWorkflowEnabled +@Service +@RequiredArgsConstructor +public class WorkflowInstanceServiceImpl implements WorkflowInstanceService { + + private final RuntimeService runtimeService; + private final HistoryService historyService; + private final RepositoryService repositoryService; + private final FormDataService formDataService; + private final WorkflowDefinitionService workflowDefinitionService; + private final BpmnModelHelper bpmnModelHelper; + private final ApprovalHistoryHelper approvalHistoryHelper; + + /** + * 发起流程 + * + * @param formData 发起流程表单数据 + */ + @Override + public String startProcess(StartProcessForm formData) { + ProcessDefinition definition = repositoryService.createProcessDefinitionQuery() + .processDefinitionId(formData.getProcessDefinitionId()).singleResult(); + Assert.notNull(definition, "流程定义不存在"); + Assert.isTrue(!definition.isSuspended(), "流程定义已挂起,无法发起"); + + Map variables = new HashMap<>(); + String businessKey = null; + String formKey = bpmnModelHelper.getStartFormKey(definition.getId()); + if (StrUtil.isNotBlank(formKey)) { + Map data = formData.getFormData() == null ? Map.of() : formData.getFormData(); + Long dataId = formDataService.saveFormDataReturnId(formKey, data); + Assert.notNull(dataId, "表单数据保存失败"); + businessKey = String.valueOf(dataId); + // 表单字段即流程变量,网关条件按字段名直接引用 + variables.putAll(data); + } + if (formData.getVariables() != null) { + variables.putAll(formData.getVariables()); + } + + // 发起人写入 ACT_HI_PROCINST.START_USER_ID_,供"我的流程"与发起人撤销校验使用 + Authentication.setAuthenticatedUserId(SecurityUtils.getUsername()); + try { + // 实例名:未传时回退流程定义名(实例级 NAME_,区分同流程的多次发起) + String instanceName = StrUtil.blankToDefault(formData.getName(), definition.getName()); + // RuntimeService 无 (id, businessKey, name, variables) 重载,实例名须走 builder 链式构建 + ProcessInstance instance = runtimeService.createProcessInstanceBuilder() + .processDefinitionId(definition.getId()) + .businessKey(businessKey) + .name(instanceName) + .variables(variables) + .start(); + return instance.getId(); + } finally { + Authentication.setAuthenticatedUserId(null); + } + } + + /** + * 我的流程分页列表 + * + * @param queryParams 查询参数 + */ + @Override + public Page getInstancePage(WorkflowInstancePageQuery queryParams) { + HistoricProcessInstanceQuery query = historyService.createHistoricProcessInstanceQuery() + .startedBy(SecurityUtils.getUsername()); + if (StrUtil.isNotBlank(queryParams.getKeywords())) { + query.processDefinitionNameLike("%" + queryParams.getKeywords() + "%"); + } + query.orderByProcessInstanceStartTime().desc(); + long total = query.count(); + List instances = query.listPage( + (queryParams.getPageNum() - 1) * queryParams.getPageSize(), queryParams.getPageSize()); + + // 同一定义只解析一次 formKey + Map formKeys = new HashMap<>(); + List records = instances.stream().map(instance -> { + InstancePageVO pageVO = new InstancePageVO(); + pageVO.setId(instance.getId()); + pageVO.setProcessDefinitionKey(instance.getProcessDefinitionKey()); + // 实例名优先,NAME_ 为空回退流程定义名 + pageVO.setProcessName(StrUtil.isBlank(instance.getName()) + ? instance.getProcessDefinitionName() : instance.getName()); + pageVO.setBusinessKey(instance.getBusinessKey()); + pageVO.setFormKey(formKeys.computeIfAbsent(instance.getProcessDefinitionId(), + bpmnModelHelper::getStartFormKey)); + pageVO.setStatus(resolveStatus(instance)); + pageVO.setDeleteReason(instance.getDeleteReason()); + pageVO.setStartTime(instance.getStartTime()); + pageVO.setEndTime(instance.getEndTime()); + return pageVO; + }).toList(); + + Page page = new Page<>(queryParams.getPageNum(), queryParams.getPageSize(), total); + page.setRecords(records); + return page; + } + + /** + * 获取流程图数据 + * + * @param instanceId 流程实例ID + */ + @Override + public ProcessDiagramVO getProcessDiagram(String instanceId) { + HistoricProcessInstance instance = getHistoricInstance(instanceId); + ProcessDiagramVO diagramVO = new ProcessDiagramVO(); + diagramVO.setBpmnXml(bpmnModelHelper.getBpmnXml(instance.getProcessDefinitionId())); + diagramVO.setExecutedActivityIds(historyService.createHistoricActivityInstanceQuery() + .processInstanceId(instanceId).finished().list().stream() + .map(HistoricActivityInstance::getActivityId).distinct().toList()); + // 已结束实例无进行中节点,查询会因执行流不存在而报错 + diagramVO.setActiveActivityIds(instance.getEndTime() == null + ? runtimeService.getActiveActivityIds(instanceId) : List.of()); + return diagramVO; + } + + /** + * 获取流程实例详情 + * + * @param instanceId 流程实例ID + */ + @Override + public InstanceDetailVO getInstanceDetail(String instanceId) { + HistoricProcessInstance instance = getHistoricInstance(instanceId); + InstanceDetailVO detailVO = new InstanceDetailVO(); + detailVO.setId(instance.getId()); + // 实例名优先,NAME_ 为空回退流程定义名 + detailVO.setProcessName(StrUtil.isBlank(instance.getName()) + ? instance.getProcessDefinitionName() : instance.getName()); + detailVO.setStartUser(instance.getStartUserId()); + detailVO.setStatus(resolveStatus(instance)); + detailVO.setDeleteReason(instance.getDeleteReason()); + detailVO.setStartTime(instance.getStartTime()); + detailVO.setEndTime(instance.getEndTime()); + + String formKey = bpmnModelHelper.getStartFormKey(instance.getProcessDefinitionId()); + detailVO.setFormKey(formKey); + this.fillFormData(detailVO, formKey, instance.getBusinessKey()); + detailVO.setHistory(approvalHistoryHelper.getHistory(instanceId)); + + // 流程走向预览:发起人视角直观看到流程走到哪个环节 + List stages = workflowDefinitionService.listProcessStages( + instance.getProcessDefinitionId()); + detailVO.setStages(stages); + detailVO.setActiveStageIndex(resolveActiveStageIndex(instance, stages)); + return detailVO; + } + + /** + * 计算流程走向的高亮位置:运行中取当前活动节点,正常结束为全部完成, + * 终止/撤销取最后办完环节的下一位置(已办环节仍显示完成态) + */ + private int resolveActiveStageIndex(HistoricProcessInstance instance, List stages) { + if (stages.isEmpty()) { + return 0; + } + // 正常结束:全部环节完成 + if (instance.getEndTime() != null && StrUtil.isBlank(instance.getDeleteReason())) { + return stages.size(); + } + if (instance.getEndTime() == null) { + // 运行中:第一个活动节点即为进行中的环节 + Set activeActivityIds = new HashSet<>(runtimeService.getActiveActivityIds(instance.getId())); + return stages.stream() + .filter(stage -> activeActivityIds.contains(stage.getNodeId())) + .findFirst() + .map(stages::indexOf) + .orElse(0); + } + // 终止/撤销:已办环节保持完成态,高亮停在最后办完环节之后 + return approvalHistoryHelper.getHistory(instance.getId()).stream() + .filter(record -> record.getEndTime() != null) + .reduce((first, second) -> second) + .flatMap(last -> stages.stream() + .filter(stage -> stage.getNodeName().equals(last.getActivityName())) + .findFirst()) + .map(stages::indexOf) + .map(index -> index + 1) + .orElse(0); + } + + /** + * 撤销流程 + * + * @param instanceId 流程实例ID + */ + @Override + public void cancelProcessInstance(String instanceId) { + HistoricProcessInstance instance = getHistoricInstance(instanceId); + Assert.isTrue(instance.getEndTime() == null, "流程已结束,无法撤销"); + Assert.isTrue(SecurityUtils.getUsername().equals(instance.getStartUserId()), "仅发起人可撤销流程"); + runtimeService.deleteProcessInstance(instanceId, "发起人撤销"); + } + + /** + * 终止流程 + * + * @param instanceId 流程实例ID + * @param reason 终止原因 + */ + @Override + public void terminateProcessInstance(String instanceId, String reason) { + HistoricProcessInstance instance = getHistoricInstance(instanceId); + Assert.isTrue(instance.getEndTime() == null, "流程已结束,无法终止"); + runtimeService.deleteProcessInstance(instanceId, StrUtil.blankToDefault(reason, "管理员终止")); + } + + /** + * 发起表单数据回显(按提交时快照严格回显) + */ + private void fillFormData(InstanceDetailVO detailVO, String formKey, String businessKey) { + if (StrUtil.isBlank(formKey) || StrUtil.isBlank(businessKey)) { + return; + } + // 非数字 businessKey(未经过本系统表单提交发起)无表单可回显 + if (!NumberUtil.isLong(businessKey)) { + log.warn("跳过表单回显:businessKey 非表单数据ID instanceId={} businessKey={}", detailVO.getId(), businessKey); + return; + } + FormDataVO dataVO = formDataService.getFormDataDetail(Long.valueOf(businessKey)); + if (dataVO == null) { + log.warn("发起表单数据不存在,跳过回显 instanceId={} businessKey={}", detailVO.getId(), businessKey); + return; + } + detailVO.setFormJson(dataVO.getFormJson()); + detailVO.setOptionsJson(dataVO.getOptionsJson()); + detailVO.setDataJson(dataVO.getDataJson()); + } + + /** + * 实例状态映射:未结束即运行中;有终止原因为已终止;其余为已完成 + */ + private InstanceStatusEnum resolveStatus(HistoricProcessInstance instance) { + if (instance.getEndTime() == null) { + return InstanceStatusEnum.RUNNING; + } + return StrUtil.isNotBlank(instance.getDeleteReason()) + ? InstanceStatusEnum.TERMINATED : InstanceStatusEnum.FINISHED; + } + + /** + * 获取历史流程实例(不存在即抛业务异常) + */ + private HistoricProcessInstance getHistoricInstance(String instanceId) { + HistoricProcessInstance instance = historyService.createHistoricProcessInstanceQuery() + .processInstanceId(instanceId).singleResult(); + Assert.notNull(instance, "流程实例不存在"); + return instance; + } + +} diff --git a/src/main/java/com/youlai/boot/module/workflow/service/impl/WorkflowModelServiceImpl.java b/src/main/java/com/youlai/boot/module/workflow/service/impl/WorkflowModelServiceImpl.java new file mode 100644 index 00000000..2f530786 --- /dev/null +++ b/src/main/java/com/youlai/boot/module/workflow/service/impl/WorkflowModelServiceImpl.java @@ -0,0 +1,397 @@ +package com.youlai.boot.module.workflow.service.impl; + +import cn.hutool.core.collection.CollUtil; +import cn.hutool.core.lang.Assert; +import cn.hutool.core.util.StrUtil; +import cn.hutool.json.JSONObject; +import cn.hutool.json.JSONUtil; +import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; +import com.youlai.boot.common.exception.BusinessException; +import com.youlai.boot.module.workflow.model.form.ModelForm; +import com.youlai.boot.module.workflow.model.form.ModelXmlForm; +import com.youlai.boot.module.workflow.model.query.WorkflowModelPageQuery; +import com.youlai.boot.module.workflow.model.vo.ModelVO; +import com.youlai.boot.module.workflow.model.vo.ModelXmlVO; +import com.youlai.boot.module.workflow.service.WorkflowModelService; +import com.youlai.boot.module.workflow.util.BpmnModelHelper; +import com.youlai.boot.system.model.entity.Role; +import com.youlai.boot.system.service.RoleService; +import com.youlai.boot.module.workflow.config.ConditionalOnWorkflowEnabled; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.flowable.engine.RepositoryService; +import org.flowable.engine.RuntimeService; +import org.flowable.engine.repository.Deployment; +import org.flowable.engine.repository.Model; +import org.flowable.engine.repository.ModelQuery; +import org.flowable.engine.repository.ProcessDefinition; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +import java.nio.charset.StandardCharsets; +import java.util.Collection; +import java.util.Date; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Set; +import java.util.TreeSet; +import java.util.stream.Collectors; + +/** + * 流程模型业务实现类 + * + * @author Ray.Hao + * @since 4.9.0 + */ +@ConditionalOnWorkflowEnabled +@Service +@RequiredArgsConstructor +@Slf4j +public class WorkflowModelServiceImpl implements WorkflowModelService { + + private final RepositoryService repositoryService; + private final RuntimeService runtimeService; + private final BpmnModelHelper bpmnModelHelper; + private final RoleService roleService; + + // 新模型初始模板:开始 → 审批 → 结束,设计器打开即可直接编辑 + private static final String INITIAL_XML_TEMPLATE = """ + + + + + flow1 + + + flow1 + flow2 + + + flow2 + + + + + + + + + + + + + + + + + + + + + + + + + + + """; + + /** + * 流程模型分页列表 + * + * @param queryParams 查询参数 + */ + @Override + public Page getModelPage(WorkflowModelPageQuery queryParams) { + ModelQuery query = repositoryService.createModelQuery(); + if (StrUtil.isNotBlank(queryParams.getKeywords())) { + query.modelNameLike("%" + queryParams.getKeywords() + "%"); + } + query.orderByLastUpdateTime().desc(); + long total = query.count(); + List models = query.listPage((queryParams.getPageNum() - 1) * queryParams.getPageSize(), + queryParams.getPageSize()); + + Page page = new Page<>(queryParams.getPageNum(), queryParams.getPageSize(), total); + List records = models.stream().map(this::toModelVO).toList(); + fillPublishState(records); + page.setRecords(records); + return page; + } + + /** + * 填充发布状态:模型与流程定义经 key 关联,未发布的模型无定义信息 + */ + private void fillPublishState(List records) { + if (records.isEmpty()) { + return; + } + Map latestDefinitions = repositoryService.createProcessDefinitionQuery() + .latestVersion().list().stream() + .collect(Collectors.toMap(ProcessDefinition::getKey, definition -> definition, (a, b) -> a)); + if (latestDefinitions.isEmpty()) { + return; + } + // 部署时间在 ACT_RE_DEPLOYMENT,批量取避免逐行查询 + Map deploymentTimes = latestDefinitions.values().stream() + .map(ProcessDefinition::getDeploymentId).distinct() + .map(id -> repositoryService.createDeploymentQuery().deploymentId(id).singleResult()) + .collect(Collectors.toMap(Deployment::getId, Deployment::getDeploymentTime)); + records.forEach(modelVO -> { + ProcessDefinition definition = latestDefinitions.get(modelVO.getKey()); + if (definition == null) { + return; + } + modelVO.setDefinitionId(definition.getId()); + modelVO.setPublishedVersion(definition.getVersion()); + modelVO.setSuspended(definition.isSuspended()); + modelVO.setDeploymentTime(deploymentTimes.get(definition.getDeploymentId())); + }); + } + + /** + * 新增流程模型 + * + * @param formData 模型表单数据 + */ + @Override + public boolean saveModel(ModelForm formData) { + long count = repositoryService.createModelQuery().modelKey(formData.getKey()).count(); + Assert.isTrue(count == 0, "模型标识已存在"); + + Model model = repositoryService.newModel(); + model.setKey(formData.getKey()); + model.setName(formData.getName()); + model.setMetaInfo(buildMetaInfo(formData.getDescription())); + repositoryService.saveModel(model); + repositoryService.addModelEditorSource(model.getId(), + INITIAL_XML_TEMPLATE.formatted(formData.getKey(), formData.getName()) + .getBytes(StandardCharsets.UTF_8)); + return true; + } + + /** + * 修改流程模型 + * + * @param modelId 模型ID + * @param formData 模型表单数据 + */ + @Override + public boolean updateModel(String modelId, ModelForm formData) { + Model model = getModel(modelId); + model.setName(formData.getName()); + model.setMetaInfo(buildMetaInfo(formData.getDescription())); + repositoryService.saveModel(model); + return true; + } + + /** + * 删除流程模型 + * + * @param modelIds 模型ID集合 + */ + @Override + @Transactional(rollbackFor = Exception.class) + public void removeModels(List modelIds) { + // 先全量校验再删除:批量删除中途抛错时,前面已删的模型无法回退 + List models = modelIds.stream() + .map(repositoryService::getModel) + .filter(Objects::nonNull) + .toList(); + models.forEach(this::checkNoRunningInstance); + models.forEach(this::removeModelAndDeployments); + } + + /** + * 校验流程无运行中实例 + */ + private void checkNoRunningInstance(Model model) { + long runningCount = runtimeService.createProcessInstanceQuery() + .processDefinitionKey(model.getKey()) + .count(); + if (runningCount > 0) { + throw new BusinessException("流程【" + model.getName() + "】存在 " + runningCount + + " 个运行中的实例,请先撤销或办结后再删除"); + } + } + + /** + * 删除模型的全部发布版本(级联流程定义、实例与历史)及设计草稿 + */ + private void removeModelAndDeployments(Model model) { + repositoryService.createDeploymentQuery() + .processDefinitionKey(model.getKey()).list() + .forEach(deployment -> repositoryService.deleteDeployment(deployment.getId(), true)); + repositoryService.deleteModel(model.getId()); + } + + /** + * 查询引用指定表单的流程 + * + * @param formKeys 表单标识集合 + * @return 表单标识 → 引用它的流程名称集合(无引用返回空 Map) + */ + @Override + public Map> getFormReferences(Collection formKeys) { + if (CollUtil.isEmpty(formKeys)) { + return Map.of(); + } + Set targets = new HashSet<>(formKeys); + Map> references = new HashMap<>(); + + // 已部署定义:全部版本都算引用,旧版本的实例仍在流转 + for (ProcessDefinition definition : repositoryService.createProcessDefinitionQuery().list()) { + Set referenced; + try { + referenced = bpmnModelHelper.getFormKeys(definition.getId()); + } catch (Exception e) { + log.warn("流程定义 [{}] 表单引用解析失败,跳过校验", definition.getKey()); + continue; + } + referenced.stream().filter(targets::contains) + .forEach(formKey -> recordReference(references, formKey, definition.getName())); + } + + // 模型草稿:设计器里已绑定表单,删除后该模型发布即成无表单流程 + for (Model model : repositoryService.createModelQuery().list()) { + byte[] source = repositoryService.getModelEditorSource(model.getId()); + if (source == null || source.length == 0) { + continue; + } + Set referenced; + try { + referenced = bpmnModelHelper.getFormKeysFromXml(new String(source, StandardCharsets.UTF_8)); + } catch (Exception e) { + log.warn("流程模型 [{}] 表单引用解析失败,跳过校验", model.getKey()); + continue; + } + referenced.stream().filter(targets::contains) + .forEach(formKey -> recordReference(references, formKey, model.getName())); + } + return references; + } + + /** + * 记录一条引用关系(同一表单被多个流程引用时累加,按流程名称排序保证提示稳定) + */ + private void recordReference(Map> references, String formKey, String processName) { + references.computeIfAbsent(formKey, key -> new TreeSet<>()).add(processName); + } + + /** + * 获取模型 BPMN XML + * + * @param modelId 模型ID + */ + @Override + public ModelXmlVO getModelXml(String modelId) { + getModel(modelId); + byte[] source = repositoryService.getModelEditorSource(modelId); + return new ModelXmlVO(source == null ? "" : new String(source, StandardCharsets.UTF_8)); + } + + /** + * 保存模型 BPMN XML + * + * @param modelId 模型ID + * @param formData XML 表单数据 + */ + @Override + public boolean saveModelXml(String modelId, ModelXmlForm formData) { + getModel(modelId); + repositoryService.addModelEditorSource(modelId, formData.getXml().getBytes(StandardCharsets.UTF_8)); + return true; + } + + /** + * 部署流程模型 + * + * @param modelId 模型ID + */ + @Override + public void deployModel(String modelId) { + Model model = getModel(modelId); + byte[] source = repositoryService.getModelEditorSource(modelId); + if (source == null || source.length == 0) { + throw new BusinessException("模型内容为空,请先设计流程图"); + } + String bpmnXml = new String(source, StandardCharsets.UTF_8); + // 无主任务发布前拦截:未配置办理人的节点不会进入任何人待办,流程将永久卡死 + List unassignedTasks = bpmnModelHelper.getUnassignedTaskNames(bpmnXml); + if (!unassignedTasks.isEmpty()) { + throw new BusinessException("节点【" + String.join("、", unassignedTasks) + + "】未配置办理人,发布后将无人可审批,请补充后重试"); + } + // 候选组角色存在性校验:指向不存在的角色(拼写错误/已删除)同样产生无人可办的任务 + Set groupCodes = bpmnModelHelper.getCandidateGroups(bpmnXml); + if (!groupCodes.isEmpty()) { + Set existingCodes = roleService.list( + new LambdaQueryWrapper().in(Role::getCode, groupCodes)) + .stream().map(Role::getCode).collect(Collectors.toSet()); + List invalidCodes = groupCodes.stream() + .filter(code -> !existingCodes.contains(code)).sorted().toList(); + if (!invalidCodes.isEmpty()) { + throw new BusinessException("候选组【" + String.join("、", invalidCodes) + + "】不存在,请核对角色编码后重试"); + } + } + try { + repositoryService.createDeployment() + .name(model.getName()) + .key(model.getKey()) + .addString(model.getKey() + ".bpmn20.xml", bpmnXml) + .deploy(); + } catch (BusinessException e) { + throw e; + } catch (Exception e) { + // 引擎部署时做 BPMN 解析,节点未连线、非法 XML 均在此暴露 + throw new BusinessException("流程文件校验失败,请检查节点连线与属性配置"); + } + } + + /** + * 获取模型(不存在即抛业务异常) + */ + private Model getModel(String modelId) { + Model model = repositoryService.getModel(modelId); + Assert.notNull(model, "流程模型不存在"); + return model; + } + + /** + * 构建 metaInfo(Flowable 模型约定格式,description 存放于 JSON) + */ + private String buildMetaInfo(String description) { + JSONObject metaInfo = JSONUtil.createObj().set("description", description); + return metaInfo.toString(); + } + + private ModelVO toModelVO(Model model) { + ModelVO modelVO = new ModelVO(); + modelVO.setId(model.getId()); + modelVO.setName(model.getName()); + modelVO.setKey(model.getKey()); + modelVO.setDescription(parseMetaDescription(model.getMetaInfo())); + modelVO.setVersion(model.getVersion()); + modelVO.setCreateTime(model.getCreateTime()); + modelVO.setUpdateTime(model.getLastUpdateTime()); + return modelVO; + } + + private String parseMetaDescription(String metaInfo) { + if (StrUtil.isBlank(metaInfo) || !JSONUtil.isTypeJSONObject(metaInfo)) { + return null; + } + return JSONUtil.parseObj(metaInfo).getStr("description"); + } + +} diff --git a/src/main/java/com/youlai/boot/module/workflow/service/impl/WorkflowTaskServiceImpl.java b/src/main/java/com/youlai/boot/module/workflow/service/impl/WorkflowTaskServiceImpl.java new file mode 100644 index 00000000..4b3df71e --- /dev/null +++ b/src/main/java/com/youlai/boot/module/workflow/service/impl/WorkflowTaskServiceImpl.java @@ -0,0 +1,457 @@ +package com.youlai.boot.module.workflow.service.impl; + +import cn.hutool.core.collection.CollectionUtil; +import cn.hutool.core.lang.Assert; +import cn.hutool.core.util.NumberUtil; +import cn.hutool.core.util.StrUtil; +import com.baomidou.mybatisplus.extension.plugins.pagination.Page; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.youlai.boot.common.exception.BusinessException; +import com.youlai.boot.framework.security.util.SecurityUtils; +import com.youlai.boot.module.form.model.vo.FormDataVO; +import com.youlai.boot.module.form.service.FormDataService; +import com.youlai.boot.module.form.util.FormRuleValidator; +import com.youlai.boot.module.workflow.model.form.CompleteTaskForm; +import com.youlai.boot.module.workflow.model.form.RejectTaskForm; +import com.youlai.boot.module.workflow.model.query.WorkflowTaskPageQuery; +import com.youlai.boot.module.workflow.model.vo.ApprovalHistoryVO; +import com.youlai.boot.module.workflow.model.vo.DoneTaskVO; +import com.youlai.boot.module.workflow.model.vo.RejectTargetVO; +import com.youlai.boot.module.workflow.model.vo.TaskDetailVO; +import com.youlai.boot.module.workflow.model.vo.TodoTaskVO; +import com.youlai.boot.module.workflow.service.WorkflowDefinitionService; +import com.youlai.boot.module.workflow.service.WorkflowTaskService; +import com.youlai.boot.module.workflow.util.ApprovalHistoryHelper; +import com.youlai.boot.module.workflow.util.BpmnModelHelper; +import com.youlai.boot.module.workflow.config.ConditionalOnWorkflowEnabled; +import com.youlai.boot.support.ai.AiChatService; +import com.youlai.boot.support.ai.PromptLoader; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.flowable.common.engine.impl.identity.Authentication; +import org.flowable.engine.HistoryService; +import org.flowable.engine.RepositoryService; +import org.flowable.engine.RuntimeService; +import org.flowable.engine.TaskService; +import org.flowable.engine.history.HistoricProcessInstance; +import org.flowable.engine.repository.ProcessDefinition; +import org.flowable.engine.runtime.ProcessInstance; +import org.flowable.task.api.Task; +import org.flowable.task.api.TaskQuery; +import org.flowable.task.api.history.HistoricTaskInstance; +import org.flowable.task.api.history.HistoricTaskInstanceQuery; +import org.springframework.stereotype.Service; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.Iterator; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.stream.Collectors; + +/** + * 流程任务业务实现类 + * + * @author Ray.Hao + * @since 4.9.0 + */ +@Slf4j +@ConditionalOnWorkflowEnabled +@Service +@RequiredArgsConstructor +public class WorkflowTaskServiceImpl implements WorkflowTaskService { + + // 系统提示词名称,对应 resources/prompts 下的相对路径 + private static final String SYSTEM_PROMPT_PATH = "workflow/summary.md"; + + private static final ObjectMapper OBJECT_MAPPER = new ObjectMapper(); + + private final TaskService taskService; + private final RuntimeService runtimeService; + private final HistoryService historyService; + private final RepositoryService repositoryService; + private final FormDataService formDataService; + private final WorkflowDefinitionService workflowDefinitionService; + private final BpmnModelHelper bpmnModelHelper; + private final ApprovalHistoryHelper approvalHistoryHelper; + private final AiChatService aiChatService; + private final PromptLoader promptLoader; + + /** + * 待办任务分页列表 + * + * @param queryParams 查询参数 + */ + @Override + public Page getTodoTaskPage(WorkflowTaskPageQuery queryParams) { + TaskQuery query = this.createCandidateTaskQuery(); + if (StrUtil.isNotBlank(queryParams.getKeywords())) { + query.taskNameLike("%" + queryParams.getKeywords() + "%"); + } + query.orderByTaskCreateTime().desc(); + long total = query.count(); + List tasks = query.listPage( + (queryParams.getPageNum() - 1) * queryParams.getPageSize(), queryParams.getPageSize()); + + // 流程名称、businessKey 不在任务表上,批量回查避免逐行查询 + Map processNames = getProcessNames( + tasks.stream().map(Task::getProcessDefinitionId).toList()); + Map instances = getProcessInstances( + tasks.stream().map(Task::getProcessInstanceId).collect(Collectors.toSet())); + Map formKeys = new HashMap<>(); + + List records = tasks.stream().map(task -> { + TodoTaskVO taskVO = new TodoTaskVO(); + taskVO.setId(task.getId()); + taskVO.setName(task.getName()); + taskVO.setProcessInstanceId(task.getProcessInstanceId()); + ProcessInstance instance = instances.get(task.getProcessInstanceId()); + taskVO.setProcessName(resolveProcessName( + instance == null ? null : instance.getName(), + processNames.get(task.getProcessDefinitionId()))); + taskVO.setBusinessKey(instance == null ? null : instance.getBusinessKey()); + taskVO.setFormKey(formKeys.computeIfAbsent(task.getProcessDefinitionId(), + bpmnModelHelper::getStartFormKey)); + taskVO.setCreateTime(task.getCreateTime()); + return taskVO; + }).toList(); + + Page page = new Page<>(queryParams.getPageNum(), queryParams.getPageSize(), total); + page.setRecords(records); + return page; + } + + /** + * 已办任务分页列表 + * + * @param queryParams 查询参数 + */ + @Override + public Page getDoneTaskPage(WorkflowTaskPageQuery queryParams) { + HistoricTaskInstanceQuery query = historyService.createHistoricTaskInstanceQuery() + .taskAssignee(SecurityUtils.getUsername()).finished(); + if (StrUtil.isNotBlank(queryParams.getKeywords())) { + query.taskNameLike("%" + queryParams.getKeywords() + "%"); + } + query.orderByHistoricTaskInstanceEndTime().desc(); + long total = query.count(); + List tasks = query.listPage( + (queryParams.getPageNum() - 1) * queryParams.getPageSize(), queryParams.getPageSize()); + + Map processNames = getProcessNames( + tasks.stream().map(HistoricTaskInstance::getProcessDefinitionId).toList()); + // 已办实例可能已结束,运行时表查不到,实例名须从历史表批量取(key 为流程实例ID) + Map instances = getHistoricProcessInstances( + tasks.stream().map(HistoricTaskInstance::getProcessInstanceId).collect(Collectors.toSet())); + // 意见存于 ACT_HI_COMMENT(按流程实例归档),分页内按实例去重批量回查,避免逐任务查询 + Map comments = new HashMap<>(); + tasks.stream().map(HistoricTaskInstance::getProcessInstanceId).distinct() + .forEach(processInstanceId -> taskService.getProcessInstanceComments(processInstanceId) + .forEach(comment -> { + if (StrUtil.isNotBlank(comment.getTaskId())) { + comments.put(comment.getTaskId(), comment.getFullMessage()); + } + })); + List records = tasks.stream().map(task -> { + DoneTaskVO taskVO = new DoneTaskVO(); + taskVO.setId(task.getId()); + taskVO.setName(task.getName()); + taskVO.setProcessInstanceId(task.getProcessInstanceId()); + HistoricProcessInstance instance = instances.get(task.getProcessInstanceId()); + taskVO.setProcessName(resolveProcessName( + instance == null ? null : instance.getName(), + processNames.get(task.getProcessDefinitionId()))); + taskVO.setEndTime(task.getEndTime()); + taskVO.setComment(comments.get(task.getId())); + return taskVO; + }).toList(); + + Page page = new Page<>(queryParams.getPageNum(), queryParams.getPageSize(), total); + page.setRecords(records); + return page; + } + + /** + * 获取待办任务详情 + * + * @param taskId 任务ID + */ + @Override + public TaskDetailVO getTaskDetail(String taskId) { + Task task = getCurrentUserTask(taskId); + HistoricProcessInstance instance = historyService.createHistoricProcessInstanceQuery() + .processInstanceId(task.getProcessInstanceId()).singleResult(); + Assert.notNull(instance, "流程实例不存在"); + + TaskDetailVO detailVO = new TaskDetailVO(); + detailVO.setTaskId(task.getId()); + detailVO.setTaskName(task.getName()); + detailVO.setTaskDefinitionKey(task.getTaskDefinitionKey()); + detailVO.setProcessInstanceId(task.getProcessInstanceId()); + detailVO.setProcessName(resolveProcessName(instance.getName(), instance.getProcessDefinitionName())); + detailVO.setTaskFormKey(bpmnModelHelper.getUserTaskFormKey( + task.getProcessDefinitionId(), task.getTaskDefinitionKey())); + + String formKey = bpmnModelHelper.getStartFormKey(task.getProcessDefinitionId()); + detailVO.setFormKey(formKey); + this.fillFormData(detailVO, formKey, instance.getBusinessKey()); + detailVO.setHistory(approvalHistoryHelper.getHistory(task.getProcessInstanceId())); + // 流程走向预览(审批人办理前可见完整审批链,明确前后环节办理人) + detailVO.setStages(workflowDefinitionService.listProcessStages(task.getProcessDefinitionId())); + return detailVO; + } + + /** + * 获取驳回目标节点列表 + * + * @param taskId 任务ID + */ + @Override + public List listRejectTargets(String taskId) { + Task task = getCurrentUserTask(taskId); + // 已办节点去重取首个名称;驳回当前节点自身无意义,排除 + Map targets = new LinkedHashMap<>(); + historyService.createHistoricActivityInstanceQuery() + .processInstanceId(task.getProcessInstanceId()) + .activityType("userTask") + .finished() + .orderByHistoricActivityInstanceStartTime().asc() + .list() + .forEach(activity -> { + if (!activity.getActivityId().equals(task.getTaskDefinitionKey())) { + targets.putIfAbsent(activity.getActivityId(), activity.getActivityName()); + } + }); + return targets.entrySet().stream() + .map(entry -> new RejectTargetVO(entry.getKey(), entry.getValue())) + .toList(); + } + + /** + * 审批通过 + * + * @param taskId 任务ID + * @param formData 审批表单数据 + */ + @Override + public void completeTask(String taskId, CompleteTaskForm formData) { + Task task = getCurrentUserTask(taskId); + this.addComment(task, formData.getComment()); + this.claimIfCandidate(task); + taskService.complete(taskId, formData.getVariables() == null ? Map.of() : formData.getVariables()); + } + + /** + * 驳回 + * + * @param taskId 任务ID + * @param formData 驳回表单数据 + */ + @Override + public void rejectTask(String taskId, RejectTaskForm formData) { + Task task = getCurrentUserTask(taskId); + // 目标必须是本实例已办理过的节点,防止驳回到未走过的分支 + long count = historyService.createHistoricActivityInstanceQuery() + .processInstanceId(task.getProcessInstanceId()) + .activityType("userTask") + .activityId(formData.getTargetActivityId()) + .finished() + .count(); + Assert.isTrue(count > 0, "驳回目标必须是本实例已办理过的节点"); + + this.addComment(task, formData.getComment()); + this.claimIfCandidate(task); + runtimeService.createChangeActivityStateBuilder() + .moveExecutionToActivityId(task.getExecutionId(), formData.getTargetActivityId()) + .changeState(); + } + + /** + * 获取当前用户的待办任务(不存在或非本人待办即抛业务异常) + */ + private Task getCurrentUserTask(String taskId) { + Task task = this.createCandidateTaskQuery() + .taskId(taskId) + .singleResult(); + Assert.notNull(task, "任务不存在或非你的待办"); + return task; + } + + /** + * 当前用户的候选任务查询:本人任务(办理人/候选用户)或所属角色候选组的任务 + */ + private TaskQuery createCandidateTaskQuery() { + String username = SecurityUtils.getUsername(); + List roles = new ArrayList<>(SecurityUtils.getRoles()); + if (roles.isEmpty()) { + return taskService.createTaskQuery() + .active().taskCandidateOrAssigned(username); + } + return taskService.createTaskQuery() + .active().or() + .taskCandidateOrAssigned(username) + .taskCandidateGroupIn(roles) + .endOr(); + } + + /** + * 候选组任务办理前自动认领(认领后写入办理人,已办列表与审批记录可追溯) + */ + private void claimIfCandidate(Task task) { + if (task.getAssignee() == null) { + taskService.claim(task.getId(), SecurityUtils.getUsername()); + } + } + + /** + * 审批意见写入引擎评论(发起人上下文决定评论作者) + */ + private void addComment(Task task, String comment) { + if (StrUtil.isBlank(comment)) { + return; + } + Authentication.setAuthenticatedUserId(SecurityUtils.getUsername()); + try { + taskService.addComment(task.getId(), task.getProcessInstanceId(), comment); + } finally { + Authentication.setAuthenticatedUserId(null); + } + } + + /** + * 发起表单数据回显(按提交时快照严格回显) + */ + private void fillFormData(TaskDetailVO detailVO, String formKey, String businessKey) { + if (StrUtil.isBlank(formKey) || StrUtil.isBlank(businessKey)) { + return; + } + // 非数字 businessKey(未经过本系统表单提交发起)无表单可回显 + if (!NumberUtil.isLong(businessKey)) { + log.warn("跳过表单回显:businessKey 非表单数据ID taskId={} businessKey={}", detailVO.getTaskId(), businessKey); + return; + } + FormDataVO dataVO = formDataService.getFormDataDetail(Long.valueOf(businessKey)); + if (dataVO == null) { + log.warn("发起表单数据不存在,跳过回显 taskId={} businessKey={}", detailVO.getTaskId(), businessKey); + return; + } + detailVO.setFormJson(dataVO.getFormJson()); + detailVO.setOptionsJson(dataVO.getOptionsJson()); + detailVO.setDataJson(dataVO.getDataJson()); + } + + /** + * 批量取流程定义名称(key 为流程定义ID) + */ + private Map getProcessNames(List processDefinitionIds) { + return processDefinitionIds.stream().distinct() + .collect(Collectors.toMap(id -> id, id -> { + ProcessDefinition definition = repositoryService.createProcessDefinitionQuery() + .processDefinitionId(id).singleResult(); + return definition == null ? "" : definition.getName(); + })); + } + + /** + * 解析流程名称:实例级名称优先(发起时可自定义标题区分同流程多次发起),旧实例 NAME_ 为空回退流程定义名 + */ + private String resolveProcessName(String instanceName, String definitionName) { + return StrUtil.isBlank(instanceName) ? definitionName : instanceName; + } + + /** + * 批量取历史流程实例(key 为流程实例ID;已办任务对应的实例可能已结束,须查历史表) + */ + private Map getHistoricProcessInstances(Set processInstanceIds) { + if (processInstanceIds.isEmpty()) { + return Map.of(); + } + return historyService.createHistoricProcessInstanceQuery() + .processInstanceIds(processInstanceIds).list().stream() + .collect(Collectors.toMap(HistoricProcessInstance::getId, instance -> instance)); + } + + /** + * 批量取运行中流程实例(key 为流程实例ID) + */ + private Map getProcessInstances(Set processInstanceIds) { + if (processInstanceIds.isEmpty()) { + return Map.of(); + } + return runtimeService.createProcessInstanceQuery() + .processInstanceIds(processInstanceIds).list().stream() + .collect(Collectors.toMap(ProcessInstance::getId, instance -> instance)); + } + + //--------------------------------------------------- + // AI 辅助:未开启 AI 时调用返回业务异常 + //--------------------------------------------------- + + /** + * 用 AI 汇总表单数据与审批记录,生成审批摘要 + * + * @param taskId 任务ID + * @return 摘要文本 + */ + @Override + public String aiSummarizeTask(String taskId) { + TaskDetailVO detail = getTaskDetail(taskId); + return aiChatService.chat(promptLoader.get(SYSTEM_PROMPT_PATH), buildAiUserPrompt(detail)); + } + + /** + * 构造用户提示词 + * + * @param detail 任务详情 + * @return 用户提示词 + */ + private String buildAiUserPrompt(TaskDetailVO detail) { + StringBuilder text = new StringBuilder(); + text.append("流程名称:").append(StrUtil.blankToDefault(detail.getProcessName(), "未命名流程")).append("\n"); + text.append("当前节点:").append(StrUtil.blankToDefault(detail.getTaskName(), "未命名节点")).append("\n"); + text.append("表单数据:\n").append(buildAiFormDataText(detail)); + if (CollectionUtil.isNotEmpty(detail.getHistory())) { + text.append("审批记录:\n"); + for (ApprovalHistoryVO history : detail.getHistory()) { + text.append("- ") + .append(StrUtil.blankToDefault(history.getActivityName(), "环节")) + .append("(") + .append(StrUtil.blankToDefault(history.getAssignee(), "待处理")) + .append("):") + .append(StrUtil.blankToDefault(history.getComment(), "无意见")) + .append("\n"); + } + } + return text.toString(); + } + + /** + * 把表单数据按 rule 的中文标题输出,便于模型理解字段含义 + * + * @param detail 任务详情 + * @return 逐行「标题:值」文本 + */ + private String buildAiFormDataText(TaskDetailVO detail) { + Map titles = FormRuleValidator.resolveTitles(detail.getFormJson()); + if (StrUtil.isBlank(detail.getDataJson())) { + return "(无表单数据)\n"; + } + StringBuilder text = new StringBuilder(); + try { + JsonNode data = OBJECT_MAPPER.readTree(detail.getDataJson()); + Iterator> fields = data.fields(); + while (fields.hasNext()) { + Map.Entry entry = fields.next(); + String title = titles.getOrDefault(entry.getKey(), entry.getKey()); + text.append(title).append(":").append(entry.getValue().asText()).append("\n"); + } + } catch (Exception e) { + throw new BusinessException("表单数据解析失败"); + } + return text.toString(); + } + +} diff --git a/src/main/java/com/youlai/boot/module/workflow/util/ApprovalHistoryHelper.java b/src/main/java/com/youlai/boot/module/workflow/util/ApprovalHistoryHelper.java new file mode 100644 index 00000000..ff71f71b --- /dev/null +++ b/src/main/java/com/youlai/boot/module/workflow/util/ApprovalHistoryHelper.java @@ -0,0 +1,65 @@ +package com.youlai.boot.module.workflow.util; + +import cn.hutool.core.util.StrUtil; +import com.youlai.boot.module.workflow.model.vo.ApprovalHistoryVO; +import com.youlai.boot.module.workflow.config.ConditionalOnWorkflowEnabled; +import lombok.RequiredArgsConstructor; +import org.flowable.engine.HistoryService; +import org.flowable.engine.TaskService; +import org.flowable.engine.history.HistoricActivityInstance; +import org.flowable.engine.task.Comment; +import org.springframework.stereotype.Component; + +import java.util.List; +import java.util.Map; +import java.util.stream.Collectors; + +/** + * 审批记录辅助类(用户任务含进行中节点 + 引擎评论按 taskId 归位) + * + * @author Ray.Hao + * @since 4.9.0 + */ +@ConditionalOnWorkflowEnabled +@Component +@RequiredArgsConstructor +public class ApprovalHistoryHelper { + + private final HistoryService historyService; + private final TaskService taskService; + + /** + * 获取流程实例的审批记录(按任务开始时间正序,含当前办理中节点) + * + * @param processInstanceId 流程实例ID + * @return 审批记录集合 + */ + public List getHistory(String processInstanceId) { + // 不限 finished:进行中节点 endTime 为空,时间线据此展示"进行中"态 + List activities = historyService.createHistoricActivityInstanceQuery() + .processInstanceId(processInstanceId) + .activityType("userTask") + .orderByHistoricActivityInstanceStartTime() + .asc() + .list(); + if (activities.isEmpty()) { + return List.of(); + } + // 同一节点驳回后重办会产生多条记录,评论按 taskId 精确归位、后写覆盖先写 + Map comments = taskService.getProcessInstanceComments(processInstanceId).stream() + .filter(comment -> StrUtil.isNotBlank(comment.getTaskId())) + .collect(Collectors.toMap(Comment::getTaskId, Comment::getFullMessage, (first, second) -> second)); + + return activities.stream().map(activity -> { + ApprovalHistoryVO historyVO = new ApprovalHistoryVO(); + historyVO.setActivityId(activity.getActivityId()); + historyVO.setActivityName(activity.getActivityName()); + historyVO.setAssignee(activity.getAssignee()); + historyVO.setComment(comments.get(activity.getTaskId())); + historyVO.setStartTime(activity.getStartTime()); + historyVO.setEndTime(activity.getEndTime()); + return historyVO; + }).toList(); + } + +} diff --git a/src/main/java/com/youlai/boot/module/workflow/util/BpmnModelHelper.java b/src/main/java/com/youlai/boot/module/workflow/util/BpmnModelHelper.java new file mode 100644 index 00000000..71de57ba --- /dev/null +++ b/src/main/java/com/youlai/boot/module/workflow/util/BpmnModelHelper.java @@ -0,0 +1,219 @@ +package com.youlai.boot.module.workflow.util; + +import cn.hutool.core.collection.CollUtil; +import cn.hutool.core.util.StrUtil; +import com.youlai.boot.common.exception.BusinessException; +import com.youlai.boot.module.workflow.config.ConditionalOnWorkflowEnabled; +import lombok.RequiredArgsConstructor; +import org.flowable.bpmn.converter.BpmnXMLConverter; +import org.flowable.bpmn.model.BpmnModel; +import org.flowable.bpmn.model.Process; +import org.flowable.bpmn.model.StartEvent; +import org.flowable.bpmn.model.UserTask; +import org.flowable.engine.RepositoryService; +import org.flowable.engine.repository.ProcessDefinition; +import org.springframework.stereotype.Component; + +import java.io.ByteArrayInputStream; +import java.io.InputStream; +import java.nio.charset.StandardCharsets; +import java.util.ArrayList; +import java.util.HashSet; +import java.util.List; +import java.util.Set; +import java.util.stream.Collectors; + +/** + * BPMN 模型读取辅助(formKey 与 XML 解析) + * + * @author Ray.Hao + * @since 4.9.0 + */ +@ConditionalOnWorkflowEnabled +@Component +@RequiredArgsConstructor +public class BpmnModelHelper { + + private final RepositoryService repositoryService; + + /** + * 用户任务节点的 BPMN 原始信息(办理人为未翻译的原始配置) + * + * @param nodeId 节点ID + * @param nodeName 节点名称 + * @param candidateGroups 候选组(角色编码)列表,可为空 + * @param assignee 办理人表达式(如 ${initiator}),可为空 + */ + public record UserTaskInfo(String nodeId, String nodeName, List candidateGroups, String assignee) { + } + + /** + * 获取主流程的全部用户任务节点(BPMN 文档序,即流程模型中的节点编排顺序) + * + * @param processDefinitionId 流程定义ID + */ + public List getUserTasks(String processDefinitionId) { + Process process = getMainProcess(processDefinitionId); + if (process == null) { + return List.of(); + } + return process.findFlowElementsOfType(UserTask.class).stream() + .map(task -> new UserTaskInfo(task.getId(), task.getName(), + task.getCandidateGroups(), task.getAssignee())) + .toList(); + } + + /** + * 获取开始节点绑定的表单标识 + * + * @param processDefinitionId 流程定义ID + * @return formKey,未绑定为 null + */ + public String getStartFormKey(String processDefinitionId) { + Process process = getMainProcess(processDefinitionId); + if (process == null) { + return null; + } + return process.findFlowElementsOfType(StartEvent.class).stream() + .findFirst() + .map(StartEvent::getFormKey) + .orElse(null); + } + + /** + * 获取用户任务节点绑定的表单标识 + * + * @param processDefinitionId 流程定义ID + * @param taskDefinitionKey 任务节点ID + * @return formKey,未绑定或节点非用户任务为 null + */ + public String getUserTaskFormKey(String processDefinitionId, String taskDefinitionKey) { + Process process = getMainProcess(processDefinitionId); + if (process == null) { + return null; + } + return process.findFlowElementsOfType(UserTask.class).stream() + .filter(task -> task.getId().equals(taskDefinitionKey)) + .findFirst() + .map(UserTask::getFormKey) + .orElse(null); + } + + /** + * 获取流程定义引用的全部表单标识(开始节点与用户任务节点,去重) + * + * @param processDefinitionId 流程定义ID + * @return formKey 集合,未绑定返回空集合 + */ + public Set getFormKeys(String processDefinitionId) { + Process process = getMainProcess(processDefinitionId); + if (process == null) { + return Set.of(); + } + return extractFormKeys(process); + } + + /** + * 提取 BPMN XML 引用的全部表单标识(开始节点与用户任务节点,去重) + * + * @param bpmnXml BPMN 2.0 XML 字符串 + * @return formKey 集合,无引用返回空集合 + */ + public Set getFormKeysFromXml(String bpmnXml) { + BpmnModel bpmnModel = new BpmnXMLConverter().convertToBpmnModel( + () -> new ByteArrayInputStream(bpmnXml.getBytes(StandardCharsets.UTF_8)), false, true); + Process process = bpmnModel.getMainProcess(); + if (process == null) { + throw new BusinessException("流程文件校验失败,未找到主流程"); + } + return extractFormKeys(process); + } + + /** + * 提取主流程中开始节点与用户任务节点引用的表单标识 + */ + private Set extractFormKeys(Process process) { + Set formKeys = new HashSet<>(); + process.findFlowElementsOfType(StartEvent.class).stream() + .map(StartEvent::getFormKey).filter(StrUtil::isNotBlank).forEach(formKeys::add); + process.findFlowElementsOfType(UserTask.class).stream() + .map(UserTask::getFormKey).filter(StrUtil::isNotBlank).forEach(formKeys::add); + return formKeys; + } + + /** + * 获取流程定义的 BPMN XML + * + * @param processDefinitionId 流程定义ID + * @return BPMN 2.0 XML 字符串 + */ + public String getBpmnXml(String processDefinitionId) { + try (InputStream in = repositoryService.getProcessModel(processDefinitionId)) { + if (in == null) { + throw new BusinessException("流程图不存在"); + } + return new String(in.readAllBytes(), StandardCharsets.UTF_8); + } catch (BusinessException e) { + throw e; + } catch (Exception e) { + throw new BusinessException("流程图读取失败"); + } + } + + /** + * 校验 BPMN XML 中用户任务节点的办理人配置 + * + * @param bpmnXml BPMN 2.0 XML 字符串 + * @return 未配置办理人的节点名称列表(全部已配置返回空列表) + */ + public List getUnassignedTaskNames(String bpmnXml) { + // validateSchema=false:bpmn-js 产出的命名空间前缀未必严格符合 XSD,引擎部署同样不强制 + BpmnModel bpmnModel = new BpmnXMLConverter().convertToBpmnModel( + () -> new ByteArrayInputStream(bpmnXml.getBytes(StandardCharsets.UTF_8)), false, true); + Process process = bpmnModel.getMainProcess(); + if (process == null) { + throw new BusinessException("流程文件校验失败,未找到主流程"); + } + List unassigned = new ArrayList<>(); + for (UserTask task : process.findFlowElementsOfType(UserTask.class)) { + boolean noAssignee = StrUtil.isBlank(task.getAssignee()); + boolean noGroups = CollUtil.isEmpty(task.getCandidateGroups()); + boolean noUsers = CollUtil.isEmpty(task.getCandidateUsers()); + if (noAssignee && noGroups && noUsers) { + unassigned.add(task.getName()); + } + } + return unassigned; + } + + /** + * 提取 BPMN XML 中全部用户任务引用的候选组编码(去重) + * + * @param bpmnXml BPMN 2.0 XML 字符串 + * @return 候选组角色编码集合(无候选组返回空集合) + */ + public Set getCandidateGroups(String bpmnXml) { + BpmnModel bpmnModel = new BpmnXMLConverter().convertToBpmnModel( + () -> new ByteArrayInputStream(bpmnXml.getBytes(StandardCharsets.UTF_8)), false, true); + Process process = bpmnModel.getMainProcess(); + if (process == null) { + throw new BusinessException("流程文件校验失败,未找到主流程"); + } + return process.findFlowElementsOfType(UserTask.class).stream() + .flatMap(task -> task.getCandidateGroups().stream()) + .collect(Collectors.toSet()); + } + + /** + * 获取主流程(泳道等子流程不参与 formKey 解析) + */ + private Process getMainProcess(String processDefinitionId) { + ProcessDefinition definition = repositoryService.createProcessDefinitionQuery() + .processDefinitionId(processDefinitionId).singleResult(); + if (definition == null) { + throw new BusinessException("流程定义不存在"); + } + return repositoryService.getBpmnModel(processDefinitionId).getMainProcess(); + } + +} diff --git a/src/main/java/com/youlai/boot/open/service/OpenAuthService.java b/src/main/java/com/youlai/boot/open/service/OpenAuthService.java index 78763aa6..0e976c02 100644 --- a/src/main/java/com/youlai/boot/open/service/OpenAuthService.java +++ b/src/main/java/com/youlai/boot/open/service/OpenAuthService.java @@ -1,6 +1,6 @@ package com.youlai.boot.open.service; -import com.youlai.boot.auth.model.resp.CaptchaInfo; +import com.youlai.boot.auth.password.model.vo.CaptchaVO; import com.youlai.boot.framework.security.model.AuthenticationToken; public interface OpenAuthService { @@ -8,7 +8,7 @@ public interface OpenAuthService { /** * 获取验证码 */ - CaptchaInfo getCaptcha(); + CaptchaVO getCaptcha(); /** * 发送登录/注册短信验证码(用户存在则用于登录,不存在则用于注册) diff --git a/src/main/java/com/youlai/boot/open/service/impl/OpenAuthServiceImpl.java b/src/main/java/com/youlai/boot/open/service/impl/OpenAuthServiceImpl.java index dec7f7a4..dc78a65d 100644 --- a/src/main/java/com/youlai/boot/open/service/impl/OpenAuthServiceImpl.java +++ b/src/main/java/com/youlai/boot/open/service/impl/OpenAuthServiceImpl.java @@ -14,9 +14,9 @@ import com.youlai.boot.common.constant.ClientTypeConstants; import com.youlai.boot.common.constant.RedisConstants; import com.youlai.boot.common.util.CodeGeneratorUtil; import com.youlai.boot.common.exception.BusinessException; -import com.youlai.boot.support.sms.SmsService; import com.youlai.boot.support.sms.SmsResult; import com.youlai.boot.support.sms.SmsTypeEnum; +import com.youlai.boot.support.sms.service.SmsService; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.springframework.data.redis.core.StringRedisTemplate; @@ -56,7 +56,7 @@ public class OpenAuthServiceImpl implements OpenAuthService { * 获取验证码(C 端登录无需图形验证码,预留接口返回 null) */ @Override - public com.youlai.boot.auth.model.resp.CaptchaInfo getCaptcha() { + public com.youlai.boot.auth.password.model.vo.CaptchaVO getCaptcha() { return null; } diff --git a/src/main/java/com/youlai/boot/support/ai/AiChatService.java b/src/main/java/com/youlai/boot/support/ai/AiChatService.java new file mode 100644 index 00000000..27609457 --- /dev/null +++ b/src/main/java/com/youlai/boot/support/ai/AiChatService.java @@ -0,0 +1,114 @@ +package com.youlai.boot.support.ai; + +import cn.hutool.core.util.StrUtil; +import com.youlai.boot.common.exception.BusinessException; +import lombok.RequiredArgsConstructor; +import lombok.extern.slf4j.Slf4j; +import org.springframework.ai.chat.client.ChatClient; +import org.springframework.ai.chat.model.ChatModel; +import org.springframework.beans.factory.ObjectProvider; +import org.springframework.core.ParameterizedTypeReference; +import org.springframework.stereotype.Service; + +import java.util.List; +import java.util.Map; +import java.util.function.Supplier; + +/** + * AI 对话服务 + * + * @author Ray.Hao + * @since 0.1.0 + */ +@Service +@RequiredArgsConstructor +@Slf4j +public class AiChatService { + + private final ObjectProvider chatModelProvider; + + private final ObjectProvider chatClientBuilderProvider; + + // 对话客户端,首次调用时构建 + private ChatClient chatClient; + + /** + * 发送提示词并返回模型输出 + * + * @param systemPrompt 系统提示词(角色与约束) + * @param userPrompt 用户提示词(输入数据) + * @return 模型输出文本 + */ + public String chat(String systemPrompt, String userPrompt) { + return execute("chat", () -> { + String content = client().prompt().system(systemPrompt).user(userPrompt).call().content(); + return StrUtil.blankToDefault(content, StrUtil.EMPTY).trim(); + }); + } + + /** + * 发送提示词并映射为实体 + * + * @param systemPrompt 系统提示词(角色与约束) + * @param userPrompt 用户提示词(输入数据) + * @param type 目标实体类型 + * @return 映射后的实体 + */ + public T chatEntity(String systemPrompt, String userPrompt, Class type) { + return execute("chatEntity(" + type.getSimpleName() + ")", () -> client().prompt() + .system(systemPrompt).user(userPrompt).call() + .entity(type, spec -> spec.validateSchema())); + } + + /** + * 发送提示词并映射为 JSON 数组 + * + * @param systemPrompt 系统提示词(角色与约束) + * @param userPrompt 用户提示词(输入数据) + * @return JSON 数组 + */ + public List> chatJsonList(String systemPrompt, String userPrompt) { + return execute("chatJsonList", () -> client().prompt() + .system(systemPrompt).user(userPrompt).call() + .entity(new ParameterizedTypeReference>>() { + })); + } + + /** + * 获取对话客户端,首次调用时构建 + * + * @return 对话客户端 + */ + private synchronized ChatClient client() { + if (chatClient == null) { + // 未装配 ChatModel 时 Builder 也建不出来,先判断模型是否存在,避免抛出框架的 BeanCreationException + if (chatModelProvider.getIfAvailable() == null) { + throw new BusinessException( + "AI 功能未开启,请将 spring.ai.model.chat 置为 openai 并配置 spring.ai.openai.api-key"); + } + log.info("AI 对话客户端初始化"); + chatClient = chatClientBuilderProvider.getObject().build(); + } + return chatClient; + } + + /** + * 执行模型调用并记录开始、耗时与异常 + * + * @param operation 调用标识 + * @param call 模型调用 + * @return 调用结果 + */ + private T execute(String operation, Supplier call) { + log.info("AI 调用开始, {}", operation); + long start = System.currentTimeMillis(); + try { + T result = call.get(); + log.info("AI 调用完成, {} 耗时 {} ms", operation, System.currentTimeMillis() - start); + return result; + } catch (RuntimeException e) { + log.error("AI 调用失败, {} 耗时 {} ms", operation, System.currentTimeMillis() - start, e); + throw e; + } + } +} diff --git a/src/main/java/com/youlai/boot/support/ai/PromptLoader.java b/src/main/java/com/youlai/boot/support/ai/PromptLoader.java new file mode 100644 index 00000000..2d0e3ab5 --- /dev/null +++ b/src/main/java/com/youlai/boot/support/ai/PromptLoader.java @@ -0,0 +1,113 @@ +package com.youlai.boot.support.ai; + +import cn.hutool.core.util.StrUtil; +import jakarta.annotation.PostConstruct; +import lombok.extern.slf4j.Slf4j; +import org.springframework.core.io.Resource; +import org.springframework.core.io.support.PathMatchingResourcePatternResolver; +import org.springframework.stereotype.Component; +import org.springframework.util.StreamUtils; + +import java.io.IOException; +import java.io.InputStream; +import java.nio.charset.StandardCharsets; +import java.util.Map; +import java.util.concurrent.ConcurrentHashMap; + +/** + * 提示词加载器 + * + * @author Ray.Hao + * @since 0.1.0 + */ +@Slf4j +@Component +public class PromptLoader { + + // 提示词文件位置 + private static final String LOCATION_PATTERN = "classpath*:prompts/**/*.md"; + + // 提示词目录,用于从资源地址截取提示词名称 + private static final String DIRECTORY = "prompts/"; + + // 占位符左标记 + private static final String PLACEHOLDER_LEFT = "{{"; + + // 占位符右标记 + private static final String PLACEHOLDER_RIGHT = "}}"; + + // 提示词内容,键为 prompts 下的相对路径 + private final Map prompts = new ConcurrentHashMap<>(); + + /** + * 载入全部提示词文件,读取失败则应用启动失败 + */ + @PostConstruct + public void load() { + try { + Resource[] resources = new PathMatchingResourcePatternResolver().getResources(LOCATION_PATTERN); + for (Resource resource : resources) { + try (InputStream inputStream = resource.getInputStream()) { + String content = StreamUtils.copyToString(inputStream, StandardCharsets.UTF_8).trim(); + prompts.put(resolveName(resource), content); + } + } + log.info("提示词载入完成, {} 个", prompts.size()); + } catch (IOException e) { + throw new IllegalStateException("提示词载入失败", e); + } + } + + /** + * 获取提示词原文 + * + * @param name 提示词名称,prompts 下的相对路径,如 codegen/system.md + * @return 提示词原文 + */ + public String get(String name) { + String prompt = prompts.get(name); + if (prompt == null) { + throw new IllegalStateException("提示词不存在:" + name); + } + return prompt; + } + + /** + * 获取提示词并替换占位符,替换后仍残留 {{ 的视为占位符漏传,直接抛出异常 + * + * @param name 提示词名称,prompts 下的相对路径 + * @param variables 变量值,键与文本中的 {{键}} 对应 + * @return 替换后的提示词 + */ + public String render(String name, Map variables) { + String prompt = get(name); + for (Map.Entry variable : variables.entrySet()) { + prompt = prompt.replace(PLACEHOLDER_LEFT + variable.getKey() + PLACEHOLDER_RIGHT, + StrUtil.nullToEmpty(variable.getValue())); + } + int index = prompt.indexOf(PLACEHOLDER_LEFT); + if (index >= 0) { + int end = prompt.indexOf(PLACEHOLDER_RIGHT, index); + String placeholder = end > index + ? prompt.substring(index, end + PLACEHOLDER_RIGHT.length()) + : prompt.substring(index); + throw new IllegalStateException("提示词 " + name + " 存在未替换的占位符:" + placeholder); + } + return prompt; + } + + /** + * 截取资源地址中 prompts 之后的路径作为提示词名称 + * + * @param resource 提示词资源 + * @return 提示词名称 + */ + private String resolveName(Resource resource) throws IOException { + String url = resource.getURL().toString(); + int index = url.lastIndexOf(DIRECTORY); + if (index < 0) { + throw new IllegalStateException("提示词路径异常:" + url); + } + return url.substring(index + DIRECTORY.length()); + } +} diff --git a/src/main/java/com/youlai/boot/config/property/FileStorageProperties.java b/src/main/java/com/youlai/boot/support/file/property/StorageProperties.java similarity index 60% rename from src/main/java/com/youlai/boot/config/property/FileStorageProperties.java rename to src/main/java/com/youlai/boot/support/file/property/StorageProperties.java index b732beba..0ecc9e77 100644 --- a/src/main/java/com/youlai/boot/config/property/FileStorageProperties.java +++ b/src/main/java/com/youlai/boot/support/file/property/StorageProperties.java @@ -1,4 +1,4 @@ -package com.youlai.boot.config.property; +package com.youlai.boot.support.file.property; import lombok.Data; import org.springframework.boot.context.properties.ConfigurationProperties; @@ -10,33 +10,39 @@ import java.util.Set; import java.util.stream.Collectors; /** - * 文件存储顶层配置:存储类型与上传限制。 - *

- * minio / aliyun / local 子树由各自 {@code FileService} 实现类绑定, - * 此处仅承载 {@code type} 与 {@code upload}。 + * 文件存储配置属性类 + * + * @author Ray.Hao + * @since 4.8.0 */ @Data @Component -@ConfigurationProperties(prefix = "file-storage") -public class FileStorageProperties { +@ConfigurationProperties(prefix = "storage") +public class StorageProperties { - /** 存储类型:minio | aliyun | local */ + // 存储类型,决定激活哪个 FileService 实现类 private String type; + // 上传限制 private Upload upload = new Upload(); + /** + * 上传限制配置嵌套类 + */ @Data public static class Upload { - /** 单文件大小上限,如 50MB;同时作为 spring.servlet.multipart 的上限 */ + // 单文件大小上限,如 50MB private String maxFileSize; - /** 允许的文件扩展名白名单(置空表示不限制) */ + // 允许上传的文件扩展名白名单 private List allowedExtensions; } /** - * 允许扩展名集合(小写、不含点);空集合表示不限制。 + * 获取规范化后的扩展名白名单 + * + * @return 小写、不含点的扩展名集合;空集合表示不限制 */ public Set getAllowedExtensions() { if (upload == null || upload.allowedExtensions == null) { @@ -49,4 +55,4 @@ public class FileStorageProperties { .map(String::toLowerCase) .collect(Collectors.toUnmodifiableSet()); } -} +} \ No newline at end of file diff --git a/src/main/java/com/youlai/boot/support/file/service/impl/AliyunFileServiceImpl.java b/src/main/java/com/youlai/boot/support/file/service/impl/AliyunFileServiceImpl.java index 76a13cf5..da918307 100644 --- a/src/main/java/com/youlai/boot/support/file/service/impl/AliyunFileServiceImpl.java +++ b/src/main/java/com/youlai/boot/support/file/service/impl/AliyunFileServiceImpl.java @@ -4,10 +4,12 @@ import cn.hutool.core.date.DateUtil; import cn.hutool.core.io.FileUtil; import cn.hutool.core.lang.Assert; import cn.hutool.core.util.IdUtil; +import cn.hutool.core.util.StrUtil; import com.aliyun.oss.OSS; import com.aliyun.oss.OSSClientBuilder; import com.aliyun.oss.model.ObjectMetadata; import com.aliyun.oss.model.PutObjectRequest; +import com.youlai.boot.common.exception.BusinessException; import com.youlai.boot.common.util.HashUtils; import com.youlai.boot.support.file.model.FileInfo; import com.youlai.boot.support.file.service.FileService; @@ -15,6 +17,7 @@ import jakarta.annotation.PostConstruct; import lombok.Data; import lombok.RequiredArgsConstructor; import lombok.SneakyThrows; +import lombok.extern.slf4j.Slf4j; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.stereotype.Component; @@ -25,35 +28,33 @@ import java.time.LocalDateTime; /** * 阿里云 OSS 文件存储服务。 - *

- * 当 {@code file-storage.type=aliyun} 时生效。 - * 上传文件按日期分目录存储,URL 格式:{@code https://bucket.endpoint/yyyyMMdd/uuid.suffix}。 */ @Component -@ConditionalOnProperty(value = "file-storage.type", havingValue = "aliyun") -@ConfigurationProperties(prefix = "file-storage.aliyun") +@Slf4j +@ConditionalOnProperty(value = "storage.type", havingValue = "aliyun") +@ConfigurationProperties(prefix = "storage.aliyun") @RequiredArgsConstructor @Data public class AliyunFileServiceImpl implements FileService { - /** OSS 地域节点,如 {@code oss-cn-hangzhou.aliyuncs.com} */ + // OSS 地域节点,如 {@code oss-cn-hangzhou.aliyuncs.com},兼容带 {@code http(s)://} 前缀写法 private String endpoint; - /** AccessKey ID */ + // 访问密钥 ID private String accessKeyId; - /** AccessKey Secret */ + // 访问密钥 Secret private String accessKeySecret; - /** 存储空间名称 */ + // 存储空间名称 private String bucket; private OSS aliyunOssClient; @PostConstruct public void init() { - aliyunOssClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret); + aliyunOssClient = new OSSClientBuilder().build(endpointWithProtocol(), accessKeyId, accessKeySecret); } /** - * 上传文件到阿里云 OSS,按日期分目录,返回 {@code https://bucket.endpoint/path} 格式的 URL。 + * 上传文件到阿里云 OSS,按日期分目录,返回 {@code 协议://bucket.endpoint/path} 格式的 URL。 */ @Override @SneakyThrows @@ -79,9 +80,10 @@ public class AliyunFileServiceImpl implements FileService { PutObjectRequest putObjectRequest = new PutObjectRequest(bucket, fileName, inputStream, metadata); aliyunOssClient.putObject(putObjectRequest); } catch (Exception e) { - throw new RuntimeException("文件上传失败"); + log.error("文件上传失败", e); + throw new BusinessException("文件上传失败", e); } - String fileUrl = "https://" + bucket + "." + endpoint + "/" + fileName; + String fileUrl = getFileHost() + "/" + fileName; FileInfo fileInfo = new FileInfo(); fileInfo.setName(originalFilename); fileInfo.setUrl(fileUrl); @@ -100,9 +102,31 @@ public class AliyunFileServiceImpl implements FileService { @Override public boolean deleteFile(String filePath) { Assert.notBlank(filePath, "删除文件路径不能为空"); - String fileHost = "https://" + bucket + "." + endpoint; - String fileName = filePath.substring(fileHost.length() + 1); + String fileName = filePath.substring(getFileHost().length() + 1); aliyunOssClient.deleteObject(bucket, fileName); return true; } + + /** + * 补全 endpoint 协议前缀:已带 {@code http://} 或 {@code https://} 的仅去除尾部 {@code /}, + * 纯域名写法默认补 {@code https://},避免 OSS 客户端对无协议 endpoint 默认走 http 明文传输。 + */ + private String endpointWithProtocol() { + String trimmed = StrUtil.trim(endpoint); + if (!StrUtil.startWithIgnoreCase(trimmed, "http://") && !StrUtil.startWithIgnoreCase(trimmed, "https://")) { + trimmed = "https://" + trimmed; + } + return StrUtil.removeSuffix(trimmed, "/"); + } + + /** + * 获取文件访问主机地址(含协议),如 {@code https://bucket.oss-cn-hangzhou.aliyuncs.com}。 + */ + private String getFileHost() { + String endpointWithProtocol = endpointWithProtocol(); + int schemeEnd = endpointWithProtocol.indexOf("://"); + String protocol = endpointWithProtocol.substring(0, schemeEnd); + String host = endpointWithProtocol.substring(schemeEnd + "://".length()); + return protocol + "://" + bucket + "." + host; + } } diff --git a/src/main/java/com/youlai/boot/support/file/service/impl/LocalFileServiceImpl.java b/src/main/java/com/youlai/boot/support/file/service/impl/LocalFileServiceImpl.java index 963addd3..99d0ee95 100644 --- a/src/main/java/com/youlai/boot/support/file/service/impl/LocalFileServiceImpl.java +++ b/src/main/java/com/youlai/boot/support/file/service/impl/LocalFileServiceImpl.java @@ -4,13 +4,13 @@ import cn.hutool.core.date.DatePattern; import cn.hutool.core.date.DateUtil; import cn.hutool.core.io.FileUtil; import cn.hutool.core.util.IdUtil; +import com.youlai.boot.common.exception.BusinessException; import com.youlai.boot.common.util.HashUtils; import com.youlai.boot.support.file.model.FileInfo; import com.youlai.boot.support.file.service.FileService; import lombok.Data; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; -import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.boot.context.properties.ConfigurationProperties; import org.springframework.stereotype.Component; @@ -22,21 +22,16 @@ import java.time.LocalDateTime; /** * 本地文件存储服务。 - *

- * 当 {@code file-storage.type=local} 时生效。 - * 文件写入本地磁盘 {@code file-storage.local.path} 下按日期分目录存储。 - * URL 为相对于存储根目录的路径,如 {@code /yyyyMMdd/uuid.suffix}。 */ @Data @Slf4j @Component -@ConditionalOnProperty(value = "file-storage.type", havingValue = "local") -@ConfigurationProperties(prefix = "file-storage.local") +@ConditionalOnProperty(value = "storage.type", havingValue = "local") +@ConfigurationProperties(prefix = "storage.local") @RequiredArgsConstructor public class LocalFileServiceImpl implements FileService { - /** 本地存储根目录,来自 {@code file-storage.local.path} */ - @Value("${file-storage.local.path}") + // 本地存储根目录,来自 {@code storage.local.path} private String path; /** @@ -65,7 +60,7 @@ public class LocalFileServiceImpl implements FileService { FileUtil.writeFromStream(inputStream, filePrefix + folder + File.separator + fileName); } catch (Exception e) { log.error("文件上传失败", e); - throw new RuntimeException("文件上传失败"); + throw new BusinessException("文件上传失败"); } String fileUrl = File.separator + folder + File.separator + fileName; FileInfo fileInfo = new FileInfo(); diff --git a/src/main/java/com/youlai/boot/support/file/service/impl/MinioFileServiceImpl.java b/src/main/java/com/youlai/boot/support/file/service/impl/MinioFileServiceImpl.java deleted file mode 100644 index 440cf1b8..00000000 --- a/src/main/java/com/youlai/boot/support/file/service/impl/MinioFileServiceImpl.java +++ /dev/null @@ -1,176 +0,0 @@ -package com.youlai.boot.support.file.service.impl; - -import cn.hutool.core.date.DateUtil; -import cn.hutool.core.io.FileUtil; -import cn.hutool.core.lang.Assert; -import cn.hutool.core.util.IdUtil; -import cn.hutool.core.util.StrUtil; -import com.youlai.boot.common.exception.BusinessException; -import com.youlai.boot.common.result.ResultCode; -import com.youlai.boot.common.util.HashUtils; -import com.youlai.boot.support.file.model.FileInfo; -import com.youlai.boot.support.file.service.FileService; -import io.minio.*; -import io.minio.http.Method; -import jakarta.annotation.PostConstruct; -import lombok.Data; -import lombok.RequiredArgsConstructor; -import lombok.SneakyThrows; -import lombok.extern.slf4j.Slf4j; -import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; -import org.springframework.boot.context.properties.ConfigurationProperties; -import org.springframework.stereotype.Component; -import org.springframework.web.multipart.MultipartFile; - -import java.io.InputStream; -import java.time.LocalDateTime; - -/** - * MinIO 文件存储服务。 - *

- * 当 {@code file-storage.type=minio} 时生效。 - * 上传文件按日期分目录存储,路径格式:{@code yyyyMMdd/uuid.suffix}。 - *

    - *
  • 配置了 {@code file-storage.minio.domain} 时直接用域名拼接 URL
  • - *
  • 未配置则用 MinIO 预签名 URL(去掉 query 参数后的纯路径)
  • - *
- */ -@Component -@ConditionalOnProperty(value = "file-storage.type", havingValue = "minio") -@ConfigurationProperties(prefix = "file-storage.minio") -@RequiredArgsConstructor -@Data -@Slf4j -public class MinioFileServiceImpl implements FileService { - - /** MinIO 服务端点,如 {@code http://localhost:9000} */ - private String endpoint; - /** 访问密钥 */ - private String accessKey; - /** 秘密密钥 */ - private String secretKey; - /** 存储桶名称 */ - private String bucket; - /** 自定义域名(可选),配置后不再使用预签名 URL */ - private String domain; - - private MinioClient minioClient; - - @PostConstruct - public void init() { - minioClient = MinioClient.builder() - .endpoint(endpoint) - .credentials(accessKey, secretKey) - .build(); - } - - /** - * 上传文件到 MinIO,按日期分目录,自动创建存储桶,返回文件访问 URL。 - */ - @Override - public FileInfo uploadFile(MultipartFile file) { - createBucketIfAbsent(bucket); - String originalFilename = file.getOriginalFilename(); - String suffix = FileUtil.getSuffix(originalFilename); - String dateFolder = DateUtil.format(LocalDateTime.now(), "yyyyMMdd"); - String fileName = IdUtil.simpleUUID() + "." + suffix; - - // 计算文件哈希(md5/sha1/sha256) - String md5; - String sha1; - String sha256; - try { - md5 = HashUtils.calculateMultipartFileMd5(file); - sha1 = HashUtils.calculateMultipartFileSha1(file); - sha256 = HashUtils.calculateMultipartFileSha256(file); - } catch (Exception e) { - log.error("计算文件哈希失败", e); - throw new BusinessException(ResultCode.UPLOAD_FILE_EXCEPTION, e.getMessage()); - } - - try (InputStream inputStream = file.getInputStream()) { - PutObjectArgs putObjectArgs = PutObjectArgs.builder() - .bucket(bucket) - .object(dateFolder + "/" + fileName) - .contentType(file.getContentType()) - .stream(inputStream, inputStream.available(), -1) - .build(); - minioClient.putObject(putObjectArgs); - - String fileUrl; - if (StrUtil.isBlank(domain)) { - GetPresignedObjectUrlArgs getPresignedObjectUrlArgs = GetPresignedObjectUrlArgs.builder() - .bucket(bucket) - .object(dateFolder + "/" + fileName) - .method(Method.GET) - .build(); - fileUrl = minioClient.getPresignedObjectUrl(getPresignedObjectUrlArgs); - fileUrl = fileUrl.substring(0, fileUrl.indexOf("?")); - } else { - fileUrl = domain + "/" + bucket + "/" + dateFolder + "/" + fileName; - } - - FileInfo fileInfo = new FileInfo(); - fileInfo.setName(originalFilename); - fileInfo.setUrl(fileUrl); - fileInfo.setMd5(md5); - fileInfo.setSha1(sha1); - fileInfo.setSha256(sha256); - return fileInfo; - } catch (Exception e) { - log.error("上传文件失败", e); - throw new BusinessException(ResultCode.UPLOAD_FILE_EXCEPTION, e.getMessage()); - } - } - - /** - * 删除文件。 - *

- * 从完整 URL 中提取文件名后调用 MinIO 删除。 - * - * @param filePath 文件完整 URL - * @return 删除成功返回 true - */ - @Override - public boolean deleteFile(String filePath) { - Assert.notBlank(filePath, "删除文件路径不能为空"); - try { - String fileName; - if (StrUtil.isNotBlank(domain)) { - fileName = filePath.substring(domain.length() + 1 + bucket.length() + 1); - } else { - fileName = filePath.substring(endpoint.length() + 1 + bucket.length() + 1); - } - minioClient.removeObject(RemoveObjectArgs.builder() - .bucket(bucket).object(fileName).build()); - return true; - } catch (Exception e) { - log.error("删除文件失败", e); - throw new BusinessException(ResultCode.DELETE_FILE_EXCEPTION, e.getMessage()); - } - } - - /** 生成公开读的存储桶策略 JSON */ - private static String publicBucketPolicy(String bucket) { - return "{\"Version\":\"2012-10-17\"," - + "\"Statement\":[{\"Effect\":\"Allow\"," - + "\"Principal\":{\"AWS\":[\"*\"]}," - + "\"Action\":[\"s3:ListBucketMultipartUploads\",\"s3:GetBucketLocation\",\"s3:ListBucket\"]," - + "\"Resource\":[\"arn:aws:s3:::" + bucket + "\"]}," - + "{\"Effect\":\"Allow\",\"" + "\"Principal\":{\"AWS\":[\"*\"]}," - + "\"Action\":[\"s3:ListMultipartUploadParts\",\"s3:PutObject\",\"s3:AbortMultipartUpload\",\"s3:DeleteObject\",\"s3:GetObject\"]," - + "\"Resource\":[\"arn:aws:s3:::" + bucket + "/*\"]}]}"; - } - - /** - * 存储桶不存在时自动创建,并设置为公开读策略。 - */ - @SneakyThrows - private void createBucketIfAbsent(String bucket) { - if (!minioClient.bucketExists(BucketExistsArgs.builder().bucket(bucket).build())) { - minioClient.makeBucket(MakeBucketArgs.builder().bucket(bucket).build()); - minioClient.setBucketPolicy(SetBucketPolicyArgs.builder() - .bucket(bucket).config(publicBucketPolicy(bucket)).build()); - } - } -} diff --git a/src/main/java/com/youlai/boot/support/file/service/impl/S3FileServiceImpl.java b/src/main/java/com/youlai/boot/support/file/service/impl/S3FileServiceImpl.java new file mode 100644 index 00000000..ad1cdd70 --- /dev/null +++ b/src/main/java/com/youlai/boot/support/file/service/impl/S3FileServiceImpl.java @@ -0,0 +1,202 @@ +package com.youlai.boot.support.file.service.impl; + +import cn.hutool.core.date.DateUtil; +import cn.hutool.core.io.FileUtil; +import cn.hutool.core.lang.Assert; +import cn.hutool.core.util.IdUtil; +import cn.hutool.core.util.StrUtil; +import com.youlai.boot.common.exception.BusinessException; +import com.youlai.boot.common.result.ResultCode; +import com.youlai.boot.support.file.model.FileInfo; +import com.youlai.boot.support.file.service.FileService; +import jakarta.annotation.PostConstruct; +import lombok.Data; +import lombok.RequiredArgsConstructor; +import lombok.SneakyThrows; +import lombok.extern.slf4j.Slf4j; +import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; +import org.springframework.boot.context.properties.ConfigurationProperties; +import org.springframework.stereotype.Component; +import org.springframework.web.multipart.MultipartFile; +import software.amazon.awssdk.auth.credentials.AwsBasicCredentials; +import software.amazon.awssdk.auth.credentials.StaticCredentialsProvider; +import software.amazon.awssdk.core.sync.RequestBody; +import software.amazon.awssdk.regions.Region; +import software.amazon.awssdk.services.s3.S3Client; +import software.amazon.awssdk.services.s3.S3Configuration; +import software.amazon.awssdk.services.s3.model.CreateBucketRequest; +import software.amazon.awssdk.services.s3.model.DeleteObjectRequest; +import software.amazon.awssdk.services.s3.model.GetObjectRequest; +import software.amazon.awssdk.services.s3.model.HeadBucketRequest; +import software.amazon.awssdk.services.s3.model.PutBucketPolicyRequest; +import software.amazon.awssdk.services.s3.model.PutObjectRequest; +import software.amazon.awssdk.services.s3.model.S3Exception; +import software.amazon.awssdk.services.s3.presigner.S3Presigner; +import software.amazon.awssdk.services.s3.presigner.model.GetObjectPresignRequest; + +import java.net.URI; +import java.time.Duration; +import java.time.LocalDateTime; + +/** + * S3 协议文件存储实现类(当前部署为 RustFS) + * + * @author Ray.Hao + * @since 4.8.0 + */ +@Component +@ConditionalOnProperty(value = "storage.type", havingValue = "s3") +@ConfigurationProperties(prefix = "storage.s3") +@RequiredArgsConstructor +@Data +@Slf4j +public class S3FileServiceImpl implements FileService { + + // S3 对象存储服务端点,如 {@code http://localhost:9000} + private String endpoint; + // 访问密钥 + private String accessKey; + // 秘密密钥 + private String secretKey; + // 存储桶名称 + private String bucket; + // 自定义域名(可选),配置后不再使用预签名 URL + private String domain; + + private S3Client s3Client; + private S3Presigner presigner; + + @PostConstruct + public void init() { + // IP 端点必须走 path-style:桶名作为路径而不是子域名(public.IP 无法被 DNS 解析) + S3Configuration s3Config = S3Configuration.builder() + .pathStyleAccessEnabled(true) + .build(); + s3Client = S3Client.builder() + .endpointOverride(URI.create(endpoint)) + // 非 AWS 服务必填,值仅区分区域,任意即可 + .region(Region.US_EAST_1) + .serviceConfiguration(s3Config) + .credentialsProvider(StaticCredentialsProvider.create( + AwsBasicCredentials.create(accessKey, secretKey))) + .build(); + presigner = S3Presigner.builder() + .endpointOverride(URI.create(endpoint)) + .region(Region.US_EAST_1) + .serviceConfiguration(s3Config) + .credentialsProvider(StaticCredentialsProvider.create( + AwsBasicCredentials.create(accessKey, secretKey))) + .build(); + } + + /** + * 上传文件到 S3(RustFS),按日期分目录,自动创建存储桶,返回文件访问 URL。 + */ + @Override + @SneakyThrows + public FileInfo uploadFile(MultipartFile file) { + createBucketIfAbsent(bucket); + String originalFilename = file.getOriginalFilename(); + String suffix = FileUtil.getSuffix(originalFilename); + String dateFolder = DateUtil.format(LocalDateTime.now(), "yyyyMMdd"); + String fileName = IdUtil.simpleUUID() + "." + suffix; + + try { + byte[] bytes = file.getBytes(); + PutObjectRequest putObjectRequest = PutObjectRequest.builder() + .bucket(bucket) + .key(dateFolder + "/" + fileName) + .contentType(file.getContentType()) + .build(); + // 用固定长度的字节数组上传,避免流式分块签名在某些 S3 兼容服务上报校验和不匹配 + s3Client.putObject(putObjectRequest, RequestBody.fromBytes(bytes)); + + String fileUrl; + if (StrUtil.isBlank(domain)) { + fileUrl = presignedUrl(dateFolder, fileName); + } else { + fileUrl = domain + "/" + bucket + "/" + dateFolder + "/" + fileName; + } + + FileInfo fileInfo = new FileInfo(); + fileInfo.setName(originalFilename); + fileInfo.setUrl(fileUrl); + return fileInfo; + } catch (Exception e) { + log.error("上传文件失败", e); + throw new BusinessException(ResultCode.UPLOAD_FILE_EXCEPTION, e.getMessage()); + } + } + + /** + * 生成预签名 GET URL 并去掉 query 参数,路径直达对象。 + * 依赖桶已开匿名只读(详见 createBucketIfAbsent 的策略),签名参数在 URL 中无实际作用。 + */ + private String presignedUrl(String dateFolder, String fileName) { + GetObjectRequest getObjectRequest = GetObjectRequest.builder() + .bucket(bucket) + .key(dateFolder + "/" + fileName) + .build(); + GetObjectPresignRequest presignRequest = GetObjectPresignRequest.builder() + .signatureDuration(Duration.ofMinutes(10)) + .getObjectRequest(getObjectRequest) + .build(); + String url = presigner.presignGetObject(presignRequest).url().toString(); + return url.substring(0, url.indexOf("?")); + } + + /** + * 删除文件。 + * + * @param filePath 文件完整 URL + * @return 删除成功返回 true + */ + @Override + public boolean deleteFile(String filePath) { + Assert.notBlank(filePath, "删除文件路径不能为空"); + try { + String fileName; + if (StrUtil.isNotBlank(domain)) { + fileName = filePath.substring(domain.length() + 1 + bucket.length() + 1); + } else { + fileName = filePath.substring(endpoint.length() + 1 + bucket.length() + 1); + } + s3Client.deleteObject(DeleteObjectRequest.builder() + .bucket(bucket).key(fileName).build()); + return true; + } catch (Exception e) { + log.error("删除文件失败", e); + throw new BusinessException(ResultCode.DELETE_FILE_EXCEPTION, e.getMessage()); + } + } + + /** + * 公开只读策略:匿名可列桶与读对象,禁止任何匿名写入 + */ + private static String publicBucketPolicy(String bucket) { + return "{\"Version\":\"2012-10-17\"," + + "\"Statement\":[{\"Effect\":\"Allow\"," + + "\"Principal\":{\"AWS\":[\"*\"]}," + + "\"Action\":[\"s3:GetObject\",\"s3:ListBucket\"]," + + "\"Resource\":[\"arn:aws:s3:::" + bucket + "\",\"arn:aws:s3:::" + bucket + "/*\"]}]}"; + } + + /** + * 存储桶不存在时自动创建,并设置为公开只读策略。 + */ + @SneakyThrows + private void createBucketIfAbsent(String bucket) { + try { + s3Client.headBucket(HeadBucketRequest.builder().bucket(bucket).build()); + } catch (S3Exception e) { + // 桶不存在(404)时才创建;其他错误(如权限不足)放行由调用方抛出 + if (e.statusCode() == 404) { + s3Client.createBucket(CreateBucketRequest.builder().bucket(bucket).build()); + s3Client.putBucketPolicy(PutBucketPolicyRequest.builder() + .bucket(bucket).policy(publicBucketPolicy(bucket)).build()); + } else { + throw e; + } + } + } +} \ No newline at end of file diff --git a/src/main/java/com/youlai/boot/config/MailConfig.java b/src/main/java/com/youlai/boot/support/mail/MailConfig.java similarity index 83% rename from src/main/java/com/youlai/boot/config/MailConfig.java rename to src/main/java/com/youlai/boot/support/mail/MailConfig.java index 6f980b70..4ae0d88b 100644 --- a/src/main/java/com/youlai/boot/config/MailConfig.java +++ b/src/main/java/com/youlai/boot/support/mail/MailConfig.java @@ -1,7 +1,5 @@ -package com.youlai.boot.config; +package com.youlai.boot.support.mail; -import com.youlai.boot.config.property.MailProperties; -import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.mail.javamail.JavaMailSender; @@ -12,11 +10,10 @@ import java.util.Properties; /** * 邮件发送配置 * - * @author Ray + * @author Ray.Hao * @since 2024/8/17 */ @Configuration -@EnableConfigurationProperties(MailProperties.class) public class MailConfig { private final MailProperties mailProperties; @@ -39,4 +36,4 @@ public class MailConfig { return mailSender; } -} +} \ No newline at end of file diff --git a/src/main/java/com/youlai/boot/config/property/MailProperties.java b/src/main/java/com/youlai/boot/support/mail/MailProperties.java similarity index 72% rename from src/main/java/com/youlai/boot/config/property/MailProperties.java rename to src/main/java/com/youlai/boot/support/mail/MailProperties.java index 4e7cad90..41944bce 100644 --- a/src/main/java/com/youlai/boot/config/property/MailProperties.java +++ b/src/main/java/com/youlai/boot/support/mail/MailProperties.java @@ -1,7 +1,8 @@ -package com.youlai.boot.config.property; +package com.youlai.boot.support.mail; import lombok.Data; import org.springframework.boot.context.properties.ConfigurationProperties; +import org.springframework.stereotype.Component; /** * 邮件配置属性 @@ -9,26 +10,27 @@ import org.springframework.boot.context.properties.ConfigurationProperties; * @author Ray * @since 2024/8/17 */ +@Component @ConfigurationProperties(prefix = "spring.mail") @Data public class MailProperties { - /** SMTP 服务器地址 */ + // SMTP 服务器地址 private String host; - /** SMTP 端口 */ + // SMTP 端口 private int port; - /** 发件人账号 */ + // 发件人账号 private String username; - /** 发件人密码 */ + // 发件人密码 private String password; - /** 发件人地址 */ + // 发件人地址 private String from; - /** SMTP 扩展属性 */ + // SMTP 扩展属性 private Properties properties = new Properties(); @Data @@ -37,16 +39,16 @@ public class MailProperties { @Data public static class Smtp { - /** 启用 SMTP 认证 */ + // 启用 SMTP 认证 private boolean auth; private StartTls starttls = new StartTls(); @Data public static class StartTls { - /** 启用 STARTTLS */ + // 启用 STARTTLS private boolean enable; } } } -} +} \ No newline at end of file diff --git a/src/main/java/com/youlai/boot/support/mail/EmailService.java b/src/main/java/com/youlai/boot/support/mail/service/EmailService.java similarity index 68% rename from src/main/java/com/youlai/boot/support/mail/EmailService.java rename to src/main/java/com/youlai/boot/support/mail/service/EmailService.java index 1a60dcae..401e7294 100644 --- a/src/main/java/com/youlai/boot/support/mail/EmailService.java +++ b/src/main/java/com/youlai/boot/support/mail/service/EmailService.java @@ -1,9 +1,7 @@ -package com.youlai.boot.support.mail; +package com.youlai.boot.support.mail.service; /** * 邮件发送服务接口。 - *

- * 由各邮件供应商实现(SMTP、SendGrid 等),通过 {@code mail.type} 配置项选择。 * * @author Ray.Hao * @since 3.1.0 @@ -19,6 +17,15 @@ public interface EmailService { */ void send(String to, String subject, String text); + /** + * 发送HTML格式的邮件。 + * + * @param to 收件人邮箱 + * @param subject 邮件主题 + * @param html 邮件正文(HTML 格式) + */ + void sendHtmlMail(String to, String subject, String html); + /** * 发送带附件的邮件。 * @@ -29,4 +36,4 @@ public interface EmailService { */ void sendWithAttachment(String to, String subject, String text, String filePath); -} +} \ No newline at end of file diff --git a/src/main/java/com/youlai/boot/support/mail/impl/SmtpEmailServiceImpl.java b/src/main/java/com/youlai/boot/support/mail/service/impl/SmtpEmailServiceImpl.java similarity index 59% rename from src/main/java/com/youlai/boot/support/mail/impl/SmtpEmailServiceImpl.java rename to src/main/java/com/youlai/boot/support/mail/service/impl/SmtpEmailServiceImpl.java index b76a2450..df87d87f 100644 --- a/src/main/java/com/youlai/boot/support/mail/impl/SmtpEmailServiceImpl.java +++ b/src/main/java/com/youlai/boot/support/mail/service/impl/SmtpEmailServiceImpl.java @@ -1,9 +1,11 @@ -package com.youlai.boot.support.mail.impl; +package com.youlai.boot.support.mail.service.impl; -import com.youlai.boot.config.property.MailProperties; -import com.youlai.boot.support.mail.EmailService; +import com.youlai.boot.support.mail.MailProperties; +import com.youlai.boot.support.mail.service.EmailService; import jakarta.mail.MessagingException; +import jakarta.mail.internet.MimeBodyPart; import jakarta.mail.internet.MimeMessage; +import jakarta.mail.internet.MimeMultipart; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; @@ -14,11 +16,10 @@ import org.springframework.mail.javamail.MimeMessageHelper; import org.springframework.stereotype.Service; import java.io.File; +import java.nio.charset.StandardCharsets; /** * SMTP 邮件服务。 - *

- * 当 {@code mail.type=smtp}(默认)时生效。基于 Spring {@link JavaMailSender} 发送邮件。 * * @author Ray.Hao * @since 3.1.0 @@ -30,7 +31,7 @@ import java.io.File; public class SmtpEmailServiceImpl implements EmailService { private final JavaMailSender mailSender; - /** 发件人地址等邮件配置,来自 {@code mail.*} */ + // 发件人地址等邮件配置,来自 {@code mail.*} private final MailProperties mailProperties; /** @@ -50,6 +51,36 @@ public class SmtpEmailServiceImpl implements EmailService { } } + /** + * 发送HTML格式的邮件 + * + * @param to 收件人地址 + * @param subject 邮件主题 + * @param html html格式的内容 + * @return 是否发送成功 + */ + @Override + public void sendHtmlMail(String to, String subject, String html) { + try { + MimeMessage message = mailSender.createMimeMessage(); + // 设置发件人、收件人和主题 + message.setFrom(mailProperties.getFrom()); + message.setRecipients(jakarta.mail.Message.RecipientType.TO, to); + message.setSubject(subject, StandardCharsets.UTF_8.name()); + // 创建 MimeMultipart 容器 + MimeMultipart multipart = new MimeMultipart("related"); + // 创建 HTML 内容部分 + MimeBodyPart htmlPart = new MimeBodyPart(); + htmlPart.setContent(html, "text/html; charset=UTF-8"); + multipart.addBodyPart(htmlPart); + // 设置消息内容 + message.setContent(multipart); + mailSender.send(message); + } catch (Exception e) { + log.error("发送Html邮件失败{}", e.getMessage()); + } + } + /** * 发送带附件的 HTML 邮件。 */ @@ -71,4 +102,4 @@ public class SmtpEmailServiceImpl implements EmailService { log.error("发送带附件邮件失败: {}", e.getMessage()); } } -} +} \ No newline at end of file diff --git a/src/main/java/com/youlai/boot/config/property/AliyunSmsProperties.java b/src/main/java/com/youlai/boot/support/sms/AliyunSmsProperties.java similarity index 56% rename from src/main/java/com/youlai/boot/config/property/AliyunSmsProperties.java rename to src/main/java/com/youlai/boot/support/sms/AliyunSmsProperties.java index 317e366b..36f82dd9 100644 --- a/src/main/java/com/youlai/boot/config/property/AliyunSmsProperties.java +++ b/src/main/java/com/youlai/boot/support/sms/AliyunSmsProperties.java @@ -1,8 +1,8 @@ -package com.youlai.boot.config.property; +package com.youlai.boot.support.sms; import lombok.Data; import org.springframework.boot.context.properties.ConfigurationProperties; -import org.springframework.context.annotation.Configuration; +import org.springframework.stereotype.Component; import java.util.Map; @@ -12,27 +12,27 @@ import java.util.Map; * @author Ray * @since 2024/8/17 */ -@Configuration -@ConfigurationProperties(prefix = "sms.aliyun") @Data +@Component +@ConfigurationProperties(prefix = "sms.aliyun") public class AliyunSmsProperties { - /** Access Key ID */ + // 访问密钥 ID private String accessKeyId; - /** Access Key Secret */ + // 访问密钥 Secret private String accessKeySecret; - /** API 域名,如 dysmsapi.aliyuncs.com */ + // API 域名,如 dysmsapi.aliyuncs.com private String domain; - /** 区域,如 cn-shanghai */ + // 区域,如 cn-shanghai private String regionId; - /** 短信签名 */ + // 短信签名 private String signName; - /** 短信模板集合,key 为模板用途(login/register),value 为模板CODE */ + // 短信模板集合,key 为模板用途(login/register),value 为模板CODE private Map templates; -} +} \ No newline at end of file diff --git a/src/main/java/com/youlai/boot/support/sms/SmsTypeEnum.java b/src/main/java/com/youlai/boot/support/sms/SmsTypeEnum.java index 23407809..579b757c 100644 --- a/src/main/java/com/youlai/boot/support/sms/SmsTypeEnum.java +++ b/src/main/java/com/youlai/boot/support/sms/SmsTypeEnum.java @@ -5,8 +5,6 @@ import lombok.Getter; /** * 短信类型枚举 - *

- * value 值对应 application-*.yml 中的 sms.templates.* 配置 * * @author Ray.Hao * @since 2.21.0 @@ -41,4 +39,4 @@ public enum SmsTypeEnum implements IBaseEnum { this.value = value; this.label = label; } -} +} \ No newline at end of file diff --git a/src/main/java/com/youlai/boot/support/sms/SmsService.java b/src/main/java/com/youlai/boot/support/sms/service/SmsService.java similarity index 87% rename from src/main/java/com/youlai/boot/support/sms/SmsService.java rename to src/main/java/com/youlai/boot/support/sms/service/SmsService.java index 9e8b2d52..c2bf7ba8 100644 --- a/src/main/java/com/youlai/boot/support/sms/SmsService.java +++ b/src/main/java/com/youlai/boot/support/sms/service/SmsService.java @@ -1,11 +1,12 @@ -package com.youlai.boot.support.sms; +package com.youlai.boot.support.sms.service; + +import com.youlai.boot.support.sms.SmsResult; +import com.youlai.boot.support.sms.SmsTypeEnum; import java.util.Map; /** * 短信发送服务接口。 - *

- * 由各短信供应商实现(阿里云、腾讯云等),通过 {@code sms.type} 配置项选择。 * * @author Ray.Hao * @since 2024/8/17 diff --git a/src/main/java/com/youlai/boot/support/sms/impl/AliyunSmsServiceImpl.java b/src/main/java/com/youlai/boot/support/sms/service/impl/AliyunSmsServiceImpl.java similarity index 95% rename from src/main/java/com/youlai/boot/support/sms/impl/AliyunSmsServiceImpl.java rename to src/main/java/com/youlai/boot/support/sms/service/impl/AliyunSmsServiceImpl.java index 004a27a2..5899c69c 100644 --- a/src/main/java/com/youlai/boot/support/sms/impl/AliyunSmsServiceImpl.java +++ b/src/main/java/com/youlai/boot/support/sms/service/impl/AliyunSmsServiceImpl.java @@ -1,4 +1,4 @@ -package com.youlai.boot.support.sms.impl; +package com.youlai.boot.support.sms.service.impl; import cn.hutool.json.JSONObject; import cn.hutool.json.JSONUtil; @@ -9,10 +9,10 @@ import com.aliyuncs.IAcsClient; import com.aliyuncs.exceptions.ClientException; import com.aliyuncs.http.MethodType; import com.aliyuncs.profile.DefaultProfile; +import com.youlai.boot.support.sms.AliyunSmsProperties; import com.youlai.boot.support.sms.SmsResult; import com.youlai.boot.support.sms.SmsTypeEnum; -import com.youlai.boot.config.property.AliyunSmsProperties; -import com.youlai.boot.support.sms.SmsService; +import com.youlai.boot.support.sms.service.SmsService; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.springframework.stereotype.Service; @@ -82,4 +82,4 @@ public class AliyunSmsServiceImpl implements SmsService { return SmsResult.fail(e.getMessage()); } } -} +} \ No newline at end of file diff --git a/src/main/java/com/youlai/boot/support/sse/model/OnlineUserDTO.java b/src/main/java/com/youlai/boot/support/sse/OnlineUserDTO.java similarity index 63% rename from src/main/java/com/youlai/boot/support/sse/model/OnlineUserDTO.java rename to src/main/java/com/youlai/boot/support/sse/OnlineUserDTO.java index 81cb9e51..480562e0 100644 --- a/src/main/java/com/youlai/boot/support/sse/model/OnlineUserDTO.java +++ b/src/main/java/com/youlai/boot/support/sse/OnlineUserDTO.java @@ -1,4 +1,4 @@ -package com.youlai.boot.support.sse.model; +package com.youlai.boot.support.sse; import lombok.AllArgsConstructor; import lombok.Data; @@ -9,8 +9,6 @@ import java.io.Serializable; /** * 在线用户信息 DTO。 - *

- * 用于 SSE 在线用户列表展示,包含用户名、会话数量和最早登录时间。 * * @author Ray.Hao * @since 3.0.0 @@ -23,12 +21,12 @@ public class OnlineUserDTO implements Serializable { @Serial private static final long serialVersionUID = 1L; - /** 用户名 */ + // 用户名 private String username; - /** 会话数量,多设备登录时大于 1 */ + // 会话数量,多设备登录时大于 1 private int sessionCount; - /** 最早登录时间(毫秒时间戳) */ + // 最早登录时间(毫秒时间戳) private long loginTime; } diff --git a/src/main/java/com/youlai/boot/support/sse/SseService.java b/src/main/java/com/youlai/boot/support/sse/SseService.java index e2ad037a..d9b8deee 100644 --- a/src/main/java/com/youlai/boot/support/sse/SseService.java +++ b/src/main/java/com/youlai/boot/support/sse/SseService.java @@ -4,7 +4,6 @@ import com.youlai.boot.device.model.vo.DeviceOnlineVO; import com.youlai.boot.device.service.DeviceOnlineService; import com.youlai.boot.support.sse.constant.SseEventConstants; import com.youlai.boot.support.sse.constant.SseTopics; -import com.youlai.boot.support.sse.model.OnlineUserDTO; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.springframework.stereotype.Service; @@ -16,8 +15,6 @@ import java.util.Map; /** * SSE 推送服务 - *

- * 组合 {@link SseSessionManager} 提供 SSE 建连、广播、定向推送、在线用户统计等能力。 * * @author Ray.Hao * @since 3.1.0 diff --git a/src/main/java/com/youlai/boot/support/sse/SseSessionManager.java b/src/main/java/com/youlai/boot/support/sse/SseSessionManager.java index c6a05686..f8e05688 100644 --- a/src/main/java/com/youlai/boot/support/sse/SseSessionManager.java +++ b/src/main/java/com/youlai/boot/support/sse/SseSessionManager.java @@ -19,9 +19,6 @@ import java.util.concurrent.ConcurrentHashMap; /** * SSE 会话管理器 - *

- * 维护 SSE 连接的用户会话信息,支持多设备同时登录。 - * 职责:建连 / 断开 / 心跳检测 / 定向推送 / 全员广播 * * @author Ray.Hao * @since 3.1.0 @@ -30,16 +27,16 @@ import java.util.concurrent.ConcurrentHashMap; @Component public class SseSessionManager { - /** SSE 连接超时时间:30 分钟 */ + // SSE 连接超时时间:30 分钟 public static final long TIMEOUT = 30 * 60 * 1000L; - /** 用户名 -> SseEmitter 集合(支持多设备) */ + // 用户名 -> SseEmitter 集合(支持多设备) private final Map> userEmittersMap = new ConcurrentHashMap<>(); - /** SseEmitter -> 用户名(快速定位用户) */ + // SseEmitter -> 用户名(快速定位用户) private final Map emitterUserMap = new ConcurrentHashMap<>(); - /** SseEmitter -> 连接时间 */ + // SseEmitter -> 连接时间 private final Map emitterTimeMap = new ConcurrentHashMap<>(); /** diff --git a/src/main/java/com/youlai/boot/support/sse/constant/SseEventConstants.java b/src/main/java/com/youlai/boot/support/sse/constant/SseEventConstants.java index 9e6155d4..163ca70d 100644 --- a/src/main/java/com/youlai/boot/support/sse/constant/SseEventConstants.java +++ b/src/main/java/com/youlai/boot/support/sse/constant/SseEventConstants.java @@ -11,10 +11,10 @@ public final class SseEventConstants { private SseEventConstants() { } - /** 心跳事件 */ + // 心跳事件 public static final String PING = "ping"; - /** 在线用户数事件 */ + // 在线用户数事件 public static final String ONLINE_USERS = "online-users"; /** 设备在线状态事件 */ diff --git a/src/main/java/com/youlai/boot/support/sse/constant/SseTopics.java b/src/main/java/com/youlai/boot/support/sse/constant/SseTopics.java index 3d82972b..c0695acd 100644 --- a/src/main/java/com/youlai/boot/support/sse/constant/SseTopics.java +++ b/src/main/java/com/youlai/boot/support/sse/constant/SseTopics.java @@ -11,15 +11,15 @@ public final class SseTopics { private SseTopics() { } - /** 字典变更事件 */ + // 字典变更事件 public static final String DICT = "dict"; - /** 系统消息事件 */ + // 系统消息事件 public static final String SYSTEM = "system"; - /** 通知事件 */ + // 通知事件 public static final String NOTICE = "notice"; - /** 通知撤回事件 */ + // 通知撤回事件 public static final String NOTICE_REVOKE = "notice-revoke"; } diff --git a/src/main/java/com/youlai/boot/system/adapter/log/OperationLogAdapter.java b/src/main/java/com/youlai/boot/system/adapter/log/OperationLogAdapter.java new file mode 100644 index 00000000..bb5a7957 --- /dev/null +++ b/src/main/java/com/youlai/boot/system/adapter/log/OperationLogAdapter.java @@ -0,0 +1,30 @@ +package com.youlai.boot.system.adapter.log; + +import com.youlai.boot.framework.web.log.OperationLog; +import com.youlai.boot.framework.web.log.OperationLogPort; +import com.youlai.boot.system.converter.LogConverter; +import com.youlai.boot.system.service.LogService; +import lombok.RequiredArgsConstructor; +import org.springframework.stereotype.Component; + +/** + * 操作日志适配器 + * + * @author Ray.Hao + * @since 4.7.0 + */ +@Component +@RequiredArgsConstructor +public class OperationLogAdapter implements OperationLogPort { + + private final LogService logService; + private final LogConverter logConverter; + + /** + * 记录操作日志 + */ + @Override + public void record(OperationLog operationLog) { + logService.save(logConverter.toEntity(operationLog)); + } +} diff --git a/src/main/java/com/youlai/boot/system/security/adapter/PermissionAdapter.java b/src/main/java/com/youlai/boot/system/adapter/security/PermissionAdapter.java similarity index 79% rename from src/main/java/com/youlai/boot/system/security/adapter/PermissionAdapter.java rename to src/main/java/com/youlai/boot/system/adapter/security/PermissionAdapter.java index 386fd4e3..fbd1a177 100644 --- a/src/main/java/com/youlai/boot/system/security/adapter/PermissionAdapter.java +++ b/src/main/java/com/youlai/boot/system/adapter/security/PermissionAdapter.java @@ -1,4 +1,4 @@ -package com.youlai.boot.system.security.adapter; +package com.youlai.boot.system.adapter.security; import com.youlai.boot.framework.security.port.PermissionPort; import com.youlai.boot.system.service.RoleMenuService; @@ -9,8 +9,6 @@ import java.util.Set; /** * 权限查询适配器。 - *

- * 实现 framework 层的 {@link PermissionPort},委托 {@link RoleMenuService} 查询权限集合。 * * @author Ray.Hao * @since 3.1.0 diff --git a/src/main/java/com/youlai/boot/system/security/adapter/UserAuthenticationAdapter.java b/src/main/java/com/youlai/boot/system/adapter/security/UserAuthenticationAdapter.java similarity index 88% rename from src/main/java/com/youlai/boot/system/security/adapter/UserAuthenticationAdapter.java rename to src/main/java/com/youlai/boot/system/adapter/security/UserAuthenticationAdapter.java index 6726f7d1..fbf1055b 100644 --- a/src/main/java/com/youlai/boot/system/security/adapter/UserAuthenticationAdapter.java +++ b/src/main/java/com/youlai/boot/system/adapter/security/UserAuthenticationAdapter.java @@ -1,4 +1,4 @@ -package com.youlai.boot.system.security.adapter; +package com.youlai.boot.system.adapter.security; import com.youlai.boot.common.enums.SocialPlatformEnum; import com.youlai.boot.framework.security.model.SecurityUser; @@ -10,8 +10,6 @@ import org.springframework.stereotype.Component; /** * 用户认证信息查询适配器。 - *

- * 实现 framework 层的 {@link UserAuthenticationPort},委托 system 层服务完成查询。 * * @author Ray.Hao * @since 3.1.0 diff --git a/src/main/java/com/youlai/boot/system/controller/ConfigController.java b/src/main/java/com/youlai/boot/system/controller/ConfigController.java index 73984b64..b6c2e327 100644 --- a/src/main/java/com/youlai/boot/system/controller/ConfigController.java +++ b/src/main/java/com/youlai/boot/system/controller/ConfigController.java @@ -39,7 +39,7 @@ public class ConfigController { @GetMapping @PreAuthorize("@ss.hasPerm('sys:config:list')") @Log(module = LogModuleEnum.CONFIG, value = ActionTypeEnum.LIST) - public PageResult page(@ParameterObject ConfigQuery queryParams) { + public PageResult page(@ParameterObject @Valid ConfigQuery queryParams) { IPage result = configService.page(queryParams); return PageResult.success(result); } @@ -48,7 +48,7 @@ public class ConfigController { @PostMapping @PreAuthorize("@ss.hasPerm('sys:config:create')") @Log(module = LogModuleEnum.CONFIG, value = ActionTypeEnum.INSERT) - public Result save(@RequestBody @Valid ConfigForm configForm) { + public Result save(@RequestBody @Valid ConfigForm configForm) { return Result.judge(configService.save(configForm)); } @@ -73,7 +73,7 @@ public class ConfigController { @PutMapping(value = "/{configId}") @PreAuthorize("@ss.hasPerm('sys:config:update')") @Log(module = LogModuleEnum.CONFIG, value = ActionTypeEnum.UPDATE) - public Result update(@Valid @PathVariable Long configId, @RequestBody ConfigForm configForm) { + public Result update(@PathVariable Long configId, @RequestBody @Valid ConfigForm configForm) { return Result.judge(configService.edit(configId, configForm)); } @@ -81,7 +81,7 @@ public class ConfigController { @DeleteMapping("/{configId}") @PreAuthorize("@ss.hasPerm('sys:config:delete')") @Log(module = LogModuleEnum.CONFIG, value = ActionTypeEnum.DELETE) - public Result delete(@PathVariable Long configId) { + public Result delete(@PathVariable Long configId) { return Result.judge(configService.delete(configId)); } diff --git a/src/main/java/com/youlai/boot/system/controller/DeptController.java b/src/main/java/com/youlai/boot/system/controller/DeptController.java index 7a54a8fd..f69cffca 100644 --- a/src/main/java/com/youlai/boot/system/controller/DeptController.java +++ b/src/main/java/com/youlai/boot/system/controller/DeptController.java @@ -2,7 +2,7 @@ package com.youlai.boot.system.controller; import com.youlai.boot.common.enums.ActionTypeEnum; import com.youlai.boot.common.enums.LogModuleEnum; -import com.youlai.boot.common.annotation.RepeatSubmit; +import com.youlai.boot.framework.web.repeatsubmit.RepeatSubmit; import com.youlai.boot.common.model.Option; import com.youlai.boot.common.result.Result; import com.youlai.boot.system.model.form.DeptForm; @@ -36,9 +36,10 @@ public class DeptController { @Operation(summary = "部门列表") @GetMapping + @PreAuthorize("@ss.hasPerm('sys:dept:list')") @Log(module = LogModuleEnum.DEPT, value = ActionTypeEnum.LIST) public Result> getDeptList( - DeptQuery queryParams + @Valid DeptQuery queryParams ) { List list = deptService.getDeptList(queryParams); return Result.success(list); @@ -56,7 +57,7 @@ public class DeptController { @PreAuthorize("@ss.hasPerm('sys:dept:create')") @RepeatSubmit @Log(module = LogModuleEnum.DEPT, value = ActionTypeEnum.INSERT) - public Result saveDept( + public Result saveDept( @Valid @RequestBody DeptForm formData ) { Long id = deptService.saveDept(formData); @@ -76,7 +77,7 @@ public class DeptController { @PutMapping(value = "/{deptId}") @PreAuthorize("@ss.hasPerm('sys:dept:update')") @Log(module = LogModuleEnum.DEPT, value = ActionTypeEnum.UPDATE) - public Result updateDept( + public Result updateDept( @PathVariable Long deptId, @Valid @RequestBody DeptForm formData ) { @@ -88,7 +89,7 @@ public class DeptController { @DeleteMapping("/{ids}") @PreAuthorize("@ss.hasPerm('sys:dept:delete')") @Log(module = LogModuleEnum.DEPT, value = ActionTypeEnum.DELETE) - public Result deleteDepartments( + public Result deleteDepartments( @Parameter(description ="部门ID,多个以英文逗号(,)分割") @PathVariable("ids") String ids ) { boolean result = deptService.deleteByIds(ids); diff --git a/src/main/java/com/youlai/boot/system/controller/DictController.java b/src/main/java/com/youlai/boot/system/controller/DictController.java index ef8e0487..008dd958 100644 --- a/src/main/java/com/youlai/boot/system/controller/DictController.java +++ b/src/main/java/com/youlai/boot/system/controller/DictController.java @@ -1,28 +1,28 @@ package com.youlai.boot.system.controller; import com.baomidou.mybatisplus.extension.plugins.pagination.Page; +import com.youlai.boot.common.annotation.Log; +import com.youlai.boot.common.enums.ActionTypeEnum; +import com.youlai.boot.common.enums.LogModuleEnum; import com.youlai.boot.common.model.Option; import com.youlai.boot.common.result.PageResult; import com.youlai.boot.common.result.Result; -import com.youlai.boot.common.enums.ActionTypeEnum; -import com.youlai.boot.common.enums.LogModuleEnum; +import com.youlai.boot.framework.web.repeatsubmit.RepeatSubmit; +import com.youlai.boot.support.sse.SseService; +import com.youlai.boot.support.sse.constant.SseTopics; +import com.youlai.boot.system.model.dto.DictChangeDTO; +import com.youlai.boot.system.model.form.DictForm; import com.youlai.boot.system.model.form.DictItemForm; -import com.youlai.boot.system.model.query.DictItemQuery; import com.youlai.boot.system.model.query.DictQuery; +import com.youlai.boot.system.model.query.DictItemQuery; import com.youlai.boot.system.model.vo.DictItemOptionVO; import com.youlai.boot.system.model.vo.DictItemPageVO; import com.youlai.boot.system.model.vo.DictPageVO; -import com.youlai.boot.common.annotation.RepeatSubmit; -import com.youlai.boot.system.model.form.DictForm; -import com.youlai.boot.common.annotation.Log; import com.youlai.boot.system.service.DictItemService; import com.youlai.boot.system.service.DictService; -import com.youlai.boot.support.sse.SseService; -import com.youlai.boot.support.sse.constant.SseTopics; -import com.youlai.boot.system.model.dto.DictChangeEvent; +import io.swagger.v3.oas.annotations.Operation; import io.swagger.v3.oas.annotations.Parameter; import io.swagger.v3.oas.annotations.tags.Tag; -import io.swagger.v3.oas.annotations.Operation; import jakarta.validation.Valid; import lombok.RequiredArgsConstructor; import org.springframework.security.access.prepost.PreAuthorize; @@ -34,8 +34,8 @@ import java.util.List; /** * 字典控制层 * - * @author Ray.Hao - * @since 2.9.0 + * @author Ray Hao + * @since 2022/10/12 */ @Tag(name = "06.字典接口") @RestController @@ -53,17 +53,15 @@ public class DictController { * @param dictCode 字典编码 */ private void sendDictChange(String dictCode) { - sseService.broadcast(SseTopics.DICT, new DictChangeEvent(dictCode)); + sseService.broadcast(SseTopics.DICT, new DictChangeDTO(dictCode)); } - //--------------------------------------------------- - // 字典相关接口 - //--------------------------------------------------- @Operation(summary = "字典分页列表") @GetMapping + @PreAuthorize("@ss.hasPerm('sys:dict:list')") @Log(module = LogModuleEnum.DICT, value = ActionTypeEnum.LIST) public PageResult getDictPage( - DictQuery queryParams + @Valid DictQuery queryParams ) { Page result = dictService.getDictPage(queryParams); return PageResult.success(result); @@ -91,7 +89,7 @@ public class DictController { @PreAuthorize("@ss.hasPerm('sys:dict:create')") @RepeatSubmit @Log(module = LogModuleEnum.DICT, value = ActionTypeEnum.INSERT) - public Result saveDict(@Valid @RequestBody DictForm formData) { + public Result saveDict(@Valid @RequestBody DictForm formData) { boolean result = dictService.saveDict(formData); // 发送字典更新通知 if (result) { @@ -104,14 +102,14 @@ public class DictController { @PutMapping("/{dictId}") @PreAuthorize("@ss.hasPerm('sys:dict:update')") @Log(module = LogModuleEnum.DICT, value = ActionTypeEnum.UPDATE) - public Result updateDict( + public Result updateDict( @PathVariable Long dictId, - @RequestBody DictForm dictForm + @RequestBody @Valid DictForm formData ) { - boolean status = dictService.updateDict(dictId, dictForm); + boolean status = dictService.updateDict(dictId, formData); // 发送字典更新通知 - if (status && dictForm.getDictCode() != null) { - sendDictChange(dictForm.getDictCode()); + if (status && formData.getDictCode() != null) { + sendDictChange(formData.getDictCode()); } return Result.judge(status); } @@ -120,7 +118,7 @@ public class DictController { @DeleteMapping("/{ids}") @PreAuthorize("@ss.hasPerm('sys:dict:delete')") @Log(module = LogModuleEnum.DICT, value = ActionTypeEnum.DELETE) - public Result deleteDictionaries( + public Result deleteDictionaries( @Parameter(description = "字典ID,多个以英文逗号(,)拼接") @PathVariable String ids ) { // 获取字典编码列表,用于发送删除通知 @@ -130,28 +128,25 @@ public class DictController { // 发送字典删除通知 for (String dictCode : dictCodes) { - sendDictChange(dictCode); + sendDictChange(dictCode); } return Result.success(); } - - //--------------------------------------------------- - // 字典项相关接口 - //--------------------------------------------------- - @Operation(summary = "字典项分页列表") + @Operation(summary = "获取字典项分页列表") @GetMapping("/{dictCode}/items") - public PageResult getDictItemPage( - @PathVariable String dictCode, - DictItemQuery queryParams + @PreAuthorize("@ss.hasPerm('sys:dict-item:list')") + public PageResult getDictItemsPage( + @Parameter(description = "字典编码") @PathVariable String dictCode, + @Valid DictItemQuery queryParams ) { queryParams.setDictCode(dictCode); Page result = dictItemService.getDictItemPage(queryParams); return PageResult.success(result); } - @Operation(summary = "字典项列表") + @Operation(summary = "获取字典项列表") @GetMapping("/{dictCode}/items/options") public Result> getDictItems( @Parameter(description = "字典编码") @PathVariable String dictCode @@ -160,8 +155,18 @@ public class DictController { return Result.success(list); } + @Operation(summary = "获取字典项表单数据") + @GetMapping("/{dictCode}/items/{itemId}/form") + public Result getDictItemForm( + @PathVariable String dictCode, + @Parameter(description = "字典ID") @PathVariable Long itemId + ) { + DictItemForm formData = dictItemService.getDictItemForm(itemId); + return Result.success(formData); + } + @Operation(summary = "新增字典项") - @PostMapping("/{dictCode}/items") + @PostMapping(value = "/{dictCode}/items") @PreAuthorize("@ss.hasPerm('sys:dict-item:create')") @RepeatSubmit @Log(module = LogModuleEnum.DICT, value = ActionTypeEnum.INSERT) @@ -174,31 +179,21 @@ public class DictController { // 发送字典更新通知 if (result) { - sendDictChange(dictCode); + sendDictChange(dictCode); } return Result.judge(result); } - @Operation(summary = "字典项表单数据") - @GetMapping("/{dictCode}/items/{itemId}/form") - public Result getDictItemForm( - @PathVariable String dictCode, - @Parameter(description = "字典项ID") @PathVariable Long itemId - ) { - DictItemForm formData = dictItemService.getDictItemForm(itemId); - return Result.success(formData); - } - @Operation(summary = "修改字典项") @PutMapping("/{dictCode}/items/{itemId}") @PreAuthorize("@ss.hasPerm('sys:dict-item:update')") @RepeatSubmit @Log(module = LogModuleEnum.DICT, value = ActionTypeEnum.UPDATE) - public Result updateDictItem( + public Result updateDictItem( @PathVariable String dictCode, @PathVariable Long itemId, - @RequestBody DictItemForm formData + @RequestBody @Valid DictItemForm formData ) { formData.setId(itemId); formData.setDictCode(dictCode); @@ -216,15 +211,13 @@ public class DictController { @DeleteMapping("/{dictCode}/items/{itemIds}") @PreAuthorize("@ss.hasPerm('sys:dict-item:delete')") @Log(module = LogModuleEnum.DICT, value = ActionTypeEnum.DELETE) - public Result deleteDictItems( + public Result deleteDictItemByIds( @PathVariable String dictCode, - @Parameter(description = "字典ID,多个以英文逗号(,)拼接") @PathVariable String itemIds + @Parameter(description = "字典项ID,多个以英文逗号(,)拼接") @PathVariable String itemIds ) { dictItemService.deleteDictItemByIds(itemIds); - // 发送字典更新通知 sendDictChange(dictCode); - return Result.success(); } diff --git a/src/main/java/com/youlai/boot/system/controller/FileController.java b/src/main/java/com/youlai/boot/system/controller/FileController.java index 200eb44e..fdaff799 100644 --- a/src/main/java/com/youlai/boot/system/controller/FileController.java +++ b/src/main/java/com/youlai/boot/system/controller/FileController.java @@ -5,7 +5,7 @@ import cn.hutool.core.util.StrUtil; import com.youlai.boot.common.exception.BusinessException; import com.youlai.boot.common.result.Result; import com.youlai.boot.common.result.ResultCode; -import com.youlai.boot.config.property.FileStorageProperties; +import com.youlai.boot.support.file.property.StorageProperties; import com.youlai.boot.support.file.model.FileInfo; import com.youlai.boot.support.file.service.FileService; import io.swagger.v3.oas.annotations.Parameter; @@ -33,7 +33,7 @@ import java.util.Set; public class FileController { private final FileService fileService; - private final FileStorageProperties fileStorageProperties; + private final StorageProperties storageProperties; @PostMapping @Operation(summary = "文件上传") @@ -55,7 +55,7 @@ public class FileController { @DeleteMapping @Operation(summary = "文件删除") @SneakyThrows - public Result deleteFile( + public Result deleteFile( @Parameter(description = "文件路径") @RequestParam String filePath ) { boolean result = fileService.deleteFile(filePath); @@ -66,7 +66,7 @@ public class FileController { * 文件扩展名白名单校验:{@code allowed-extensions} 为空时不限制。 */ private void validateFileExtension(MultipartFile file) { - Set allowedExtensions = fileStorageProperties.getAllowedExtensions(); + Set allowedExtensions = storageProperties.getAllowedExtensions(); if (allowedExtensions.isEmpty()) { return; } diff --git a/src/main/java/com/youlai/boot/system/controller/LogController.java b/src/main/java/com/youlai/boot/system/controller/LogController.java index c717b80e..5c9bd917 100644 --- a/src/main/java/com/youlai/boot/system/controller/LogController.java +++ b/src/main/java/com/youlai/boot/system/controller/LogController.java @@ -14,7 +14,9 @@ import com.youlai.boot.system.service.LogService; import io.swagger.v3.oas.annotations.Operation; import io.swagger.v3.oas.annotations.Parameter; import io.swagger.v3.oas.annotations.tags.Tag; +import jakarta.validation.Valid; import lombok.RequiredArgsConstructor; +import org.springframework.security.access.prepost.PreAuthorize; import org.springframework.web.bind.annotation.*; import java.time.LocalDate; @@ -35,9 +37,10 @@ public class LogController { @Operation(summary = "日志分页列表") @GetMapping + @PreAuthorize("@ss.hasPerm('sys:log:list')") @Log(module = LogModuleEnum.LOG, value = ActionTypeEnum.LIST) public PageResult getLogPage( - LogQuery queryParams + @Valid LogQuery queryParams ) { Page result = logService.getLogPage(queryParams); return PageResult.success(result); diff --git a/src/main/java/com/youlai/boot/system/controller/MenuController.java b/src/main/java/com/youlai/boot/system/controller/MenuController.java index f4a614cc..7b59e1d6 100644 --- a/src/main/java/com/youlai/boot/system/controller/MenuController.java +++ b/src/main/java/com/youlai/boot/system/controller/MenuController.java @@ -1,19 +1,22 @@ package com.youlai.boot.system.controller; import com.youlai.boot.common.annotation.Log; -import com.youlai.boot.common.annotation.RepeatSubmit; +import com.youlai.boot.framework.web.repeatsubmit.RepeatSubmit; import com.youlai.boot.common.enums.ActionTypeEnum; import com.youlai.boot.common.enums.LogModuleEnum; import com.youlai.boot.common.model.Option; import com.youlai.boot.common.result.Result; +import com.youlai.boot.system.model.form.MenuAiFillForm; import com.youlai.boot.system.model.form.MenuForm; import com.youlai.boot.system.model.query.MenuQuery; +import com.youlai.boot.system.model.vo.MenuAiVO; import com.youlai.boot.system.model.vo.MenuVO; import com.youlai.boot.system.model.vo.RouteVO; import com.youlai.boot.system.service.MenuService; import io.swagger.v3.oas.annotations.Operation; import io.swagger.v3.oas.annotations.Parameter; import io.swagger.v3.oas.annotations.tags.Tag; +import jakarta.validation.Valid; import lombok.RequiredArgsConstructor; import lombok.extern.slf4j.Slf4j; import org.springframework.security.access.prepost.PreAuthorize; @@ -38,8 +41,9 @@ public class MenuController { @Operation(summary = "菜单列表") @GetMapping + @PreAuthorize("@ss.hasPerm('sys:menu:list')") @Log(module = LogModuleEnum.MENU, value = ActionTypeEnum.LIST) - public Result> getMenus(MenuQuery queryParams) { + public Result> getMenus(@Valid MenuQuery queryParams) { List menuList = menuService.listMenus(queryParams); return Result.success(menuList); } @@ -47,11 +51,8 @@ public class MenuController { @Operation(summary = "菜单下拉列表") @GetMapping("/options") public Result>> getMenuOptions( - @Parameter(description = "是否只查询父级菜单") - @RequestParam(required = false, defaultValue = "false") boolean onlyParent - ) { - List> menus = menuService.listMenuOptions(onlyParent); - return Result.success(menus); + @Parameter(description = "菜单类型,可传多个,为空查全部") @RequestParam(required = false) List types) { + return Result.success(menuService.listMenuOptions(types)); } @Operation(summary = "当前用户菜单路由列表") @@ -76,7 +77,7 @@ public class MenuController { @PreAuthorize("@ss.hasPerm('sys:menu:create')") @RepeatSubmit @Log(module = LogModuleEnum.MENU, value = ActionTypeEnum.INSERT) - public Result addMenu(@RequestBody MenuForm menuForm) { + public Result addMenu(@RequestBody @Valid MenuForm menuForm) { boolean result = menuService.saveMenu(menuForm); return Result.judge(result); } @@ -85,9 +86,9 @@ public class MenuController { @PutMapping(value = "/{menuId}") @PreAuthorize("@ss.hasPerm('sys:menu:update')") @Log(module = LogModuleEnum.MENU, value = ActionTypeEnum.UPDATE) - public Result updateMenu( + public Result updateMenu( @Parameter(description = "菜单ID") @PathVariable Long menuId, - @RequestBody MenuForm menuForm + @RequestBody @Valid MenuForm menuForm ) { boolean result = menuService.saveMenu(menuForm); return Result.judge(result); @@ -97,7 +98,7 @@ public class MenuController { @DeleteMapping("/{menuId}") @PreAuthorize("@ss.hasPerm('sys:menu:delete')") @Log(module = LogModuleEnum.MENU, value = ActionTypeEnum.DELETE) - public Result deleteMenu( + public Result deleteMenu( @Parameter(description = "菜单ID,多个以英文(,)分割") @PathVariable Long menuId ) { boolean result = menuService.deleteMenu(menuId); @@ -108,7 +109,7 @@ public class MenuController { @PatchMapping("/{menuId}") @PreAuthorize("@ss.hasPerm('sys:menu:update')") @Log(module = LogModuleEnum.MENU, value = ActionTypeEnum.UPDATE) - public Result updateMenuVisible( + public Result updateMenuVisible( @Parameter(description = "菜单ID") @PathVariable Long menuId, @Parameter(description = "显示状态(1:显示;0:隐藏)") Integer visible @@ -117,5 +118,13 @@ public class MenuController { return Result.judge(result); } + // AI 辅助:未开启 AI 时调用返回业务异常 + + @Operation(summary = "AI 推断菜单的访问路径与权限标识") + @PostMapping("/ai-fill") + public Result aiFillMenu(@RequestBody @Valid MenuAiFillForm form) { + return Result.success(menuService.aiFillMenu(form)); + } + } diff --git a/src/main/java/com/youlai/boot/system/controller/NoticeController.java b/src/main/java/com/youlai/boot/system/controller/NoticeController.java index 639f794c..2e484a7e 100644 --- a/src/main/java/com/youlai/boot/system/controller/NoticeController.java +++ b/src/main/java/com/youlai/boot/system/controller/NoticeController.java @@ -42,7 +42,7 @@ public class NoticeController { @GetMapping @PreAuthorize("@ss.hasPerm('sys:notice:list')") @Log(module = LogModuleEnum.NOTICE, value = ActionTypeEnum.LIST) - public PageResult getNoticePage(NoticeQuery queryParams) { + public PageResult getNoticePage(@Valid NoticeQuery queryParams) { IPage result = noticeService.getNoticePage(queryParams); return PageResult.success(result); } @@ -51,7 +51,7 @@ public class NoticeController { @PostMapping @PreAuthorize("@ss.hasPerm('sys:notice:create')") @Log(module = LogModuleEnum.NOTICE, value = ActionTypeEnum.INSERT) - public Result saveNotice(@RequestBody @Valid NoticeForm formData) { + public Result saveNotice(@RequestBody @Valid NoticeForm formData) { boolean result = noticeService.saveNotice(formData); return Result.judge(result); } @@ -130,7 +130,7 @@ public class NoticeController { @Operation(summary = "获取我的通知公告分页列表") @GetMapping("/my") public PageResult getMyNoticePage( - NoticeQuery queryParams + @Valid NoticeQuery queryParams ) { IPage result = noticeService.getMyNoticePage(queryParams); return PageResult.success(result); diff --git a/src/main/java/com/youlai/boot/system/controller/RoleController.java b/src/main/java/com/youlai/boot/system/controller/RoleController.java index b665896f..d0a340c4 100644 --- a/src/main/java/com/youlai/boot/system/controller/RoleController.java +++ b/src/main/java/com/youlai/boot/system/controller/RoleController.java @@ -3,7 +3,7 @@ package com.youlai.boot.system.controller; import com.baomidou.mybatisplus.extension.plugins.pagination.Page; import com.youlai.boot.common.enums.ActionTypeEnum; import com.youlai.boot.common.enums.LogModuleEnum; -import com.youlai.boot.common.annotation.RepeatSubmit; +import com.youlai.boot.framework.web.repeatsubmit.RepeatSubmit; import com.youlai.boot.common.model.Option; import com.youlai.boot.common.result.PageResult; import com.youlai.boot.common.result.Result; @@ -39,9 +39,10 @@ public class RoleController { @Operation(summary = "角色分页列表") @GetMapping + @PreAuthorize("@ss.hasPerm('sys:role:list')") @Log(module = LogModuleEnum.ROLE, value = ActionTypeEnum.LIST) public PageResult getRolePage( - RoleQuery queryParams + @Valid RoleQuery queryParams ) { Page result = roleService.getRolePage(queryParams); return PageResult.success(result); @@ -54,12 +55,18 @@ public class RoleController { return Result.success(list); } + @Operation(summary = "角色编码下拉列表") + @GetMapping("/code-options") + public Result>> listRoleCodeOptions() { + return Result.success(roleService.listRoleCodeOptions()); + } + @Operation(summary = "新增角色") @PostMapping @PreAuthorize("@ss.hasPerm('sys:role:create')") @RepeatSubmit @Log(module = LogModuleEnum.ROLE, value = ActionTypeEnum.INSERT) - public Result addRole(@Valid @RequestBody RoleForm roleForm) { + public Result addRole(@Valid @RequestBody RoleForm roleForm) { boolean result = roleService.saveRole(roleForm); return Result.judge(result); } @@ -78,7 +85,7 @@ public class RoleController { @PutMapping(value = "/{roleId}") @PreAuthorize("@ss.hasPerm('sys:role:update')") @Log(module = LogModuleEnum.ROLE, value = ActionTypeEnum.UPDATE) - public Result updateRole( + public Result updateRole( @Parameter(description = "角色ID") @PathVariable Long roleId, @Valid @RequestBody RoleForm roleForm) { boolean result = roleService.saveRole(roleForm); @@ -100,7 +107,7 @@ public class RoleController { @PutMapping(value = "/{roleId}/status") @PreAuthorize("@ss.hasPerm('sys:role:update')") @Log(module = LogModuleEnum.ROLE, value = ActionTypeEnum.UPDATE) - public Result updateRoleStatus( + public Result updateRoleStatus( @Parameter(description = "角色ID") @PathVariable Long roleId, @Parameter(description = "状态(1:启用;0:禁用)") @RequestParam Integer status ) { diff --git a/src/main/java/com/youlai/boot/system/controller/UserController.java b/src/main/java/com/youlai/boot/system/controller/UserController.java index b3abe52e..2f30d4d1 100644 --- a/src/main/java/com/youlai/boot/system/controller/UserController.java +++ b/src/main/java/com/youlai/boot/system/controller/UserController.java @@ -3,10 +3,11 @@ package com.youlai.boot.system.controller; import cn.idev.excel.EasyExcel; import cn.idev.excel.ExcelWriter; import com.youlai.boot.common.annotation.Log; -import com.youlai.boot.common.annotation.RepeatSubmit; +import com.youlai.boot.framework.web.repeatsubmit.RepeatSubmit; import com.youlai.boot.common.enums.ActionTypeEnum; import com.youlai.boot.common.enums.LogModuleEnum; import com.youlai.boot.common.enums.StatusEnum; +import com.youlai.boot.common.exception.BusinessException; import com.youlai.boot.framework.security.util.SecurityUtils; import com.youlai.boot.common.model.Option; import com.youlai.boot.common.result.ExcelResult; @@ -17,6 +18,7 @@ import com.youlai.boot.system.service.UserImportReader; import com.youlai.boot.system.model.form.EmailUpdateForm; import com.youlai.boot.system.model.form.MobileUpdateForm; import com.youlai.boot.system.model.form.PasswordUpdateForm; +import com.youlai.boot.system.model.form.PasswordResetForm; import com.youlai.boot.system.model.form.PasswordVerifyForm; import com.youlai.boot.system.model.form.UserForm; import com.youlai.boot.system.model.form.UserImportForm; @@ -57,7 +59,7 @@ import java.nio.charset.StandardCharsets; import java.util.List; /** - * 用户控制层 + * 用户管理控制器. * * @author Ray.Hao * @since 4.3.1 @@ -74,6 +76,7 @@ public class UserController { @Operation(summary = "用户列表") @GetMapping + @PreAuthorize("@ss.hasPerm('sys:user:list')") @Log(module = LogModuleEnum.USER, value = ActionTypeEnum.LIST) public PageResult getUserList( @Valid UserQuery queryParams @@ -86,7 +89,7 @@ public class UserController { @PreAuthorize("@ss.hasPerm('sys:user:create')") @RepeatSubmit @Log(module = LogModuleEnum.USER, value = ActionTypeEnum.INSERT) - public Result saveUser( + public Result saveUser( @RequestBody @Valid UserForm userForm ) { boolean result = userService.saveUser(userForm); @@ -146,11 +149,11 @@ public class UserController { @PutMapping(value = "/{userId}/password/reset") @PreAuthorize("@ss.hasPerm('sys:user:reset-password')") @Log(module = LogModuleEnum.USER, value = ActionTypeEnum.RESET_PASSWORD) - public Result resetUserPassword( + public Result resetUserPassword( @Parameter(description = "用户ID") @PathVariable Long userId, - @RequestParam String password + @Parameter(description = "重置密码表单") @RequestBody @Valid PasswordResetForm formData ) { - boolean result = userService.resetUserPassword(userId, password); + boolean result = userService.resetUserPassword(userId, formData.getPassword()); return Result.judge(result); } @@ -168,14 +171,15 @@ public class UserController { response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"); response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(fileName, StandardCharsets.UTF_8)); - String fileClassPath = "templates" + File.separator + "excel" + File.separator + fileName; + // ClassLoader 只认 / 分隔,用 File.separator 打 jar 后(Linux)会取不到资源 + String fileClassPath = "excel/" + fileName; InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream(fileClassPath); try (ServletOutputStream outputStream = response.getOutputStream(); ExcelWriter excelWriter = EasyExcel.write(outputStream).withTemplate(inputStream).build()) { excelWriter.finish(); } catch (IOException e) { - throw new RuntimeException("用户导入模板下载失败", e); + throw new BusinessException("用户导入模板下载失败", e); } } @@ -193,7 +197,7 @@ public class UserController { @GetMapping("/export") @PreAuthorize("@ss.hasPerm('sys:user:export')") @Log(module = LogModuleEnum.USER, value = ActionTypeEnum.EXPORT) - public void exportUsers(UserQuery queryParams, HttpServletResponse response) throws IOException { + public void exportUsers(@Valid UserQuery queryParams, HttpServletResponse response) throws IOException { String fileName = "用户列表.xlsx"; response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"); response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(fileName, StandardCharsets.UTF_8)); @@ -221,7 +225,7 @@ public class UserController { @Operation(summary = "个人中心修改用户信息") @PutMapping("/profile") @Log(module = LogModuleEnum.USER, value = ActionTypeEnum.UPDATE) - public Result updateUserProfile(@RequestBody UserProfileForm formData) { + public Result updateUserProfile(@RequestBody @Valid UserProfileForm formData) { boolean result = userService.updateUserProfile(formData); return Result.judge(result); } @@ -230,8 +234,8 @@ public class UserController { @Operation(summary = "当前用户修改密码") @PutMapping(value = "/password") @Log(module = LogModuleEnum.USER, value = ActionTypeEnum.CHANGE_PASSWORD) - public Result changeCurrentUserPassword( - @RequestBody PasswordUpdateForm data + public Result changeCurrentUserPassword( + @RequestBody @Valid PasswordUpdateForm data ) { Long currUserId = SecurityUtils.getUserId(); boolean result = userService.changeUserPassword(currUserId, data); @@ -240,7 +244,7 @@ public class UserController { @Operation(summary = "发送短信验证码(绑定或更换手机号)") @PostMapping(value = "/mobile/code") - public Result sendMobileCode( + public Result sendMobileCode( @Parameter(description = "手机号码", required = true) @RequestParam String mobile ) { boolean result = userService.sendMobileCode(mobile); @@ -249,7 +253,7 @@ public class UserController { @Operation(summary = "绑定或更换手机号") @PutMapping(value = "/mobile") - public Result bindOrChangeMobile( + public Result bindOrChangeMobile( @RequestBody @Validated MobileUpdateForm data ) { boolean result = userService.bindOrChangeMobile(data); @@ -258,7 +262,7 @@ public class UserController { @Operation(summary = "解绑手机号") @DeleteMapping(value = "/mobile") - public Result unbindMobile( + public Result unbindMobile( @RequestBody @Validated PasswordVerifyForm data ) { boolean result = userService.unbindMobile(data); @@ -276,7 +280,7 @@ public class UserController { @Operation(summary = "绑定或更换邮箱") @PutMapping(value = "/email") - public Result bindOrChangeEmail( + public Result bindOrChangeEmail( @RequestBody @Validated EmailUpdateForm data ) { boolean result = userService.bindOrChangeEmail(data); @@ -285,7 +289,7 @@ public class UserController { @Operation(summary = "解绑邮箱") @DeleteMapping(value = "/email") - public Result unbindEmail( + public Result unbindEmail( @RequestBody @Validated PasswordVerifyForm data ) { boolean result = userService.unbindEmail(data); diff --git a/src/main/java/com/youlai/boot/system/converter/DictItemConverter.java b/src/main/java/com/youlai/boot/system/converter/DictItemConverter.java index 99a354b0..81e22731 100644 --- a/src/main/java/com/youlai/boot/system/converter/DictItemConverter.java +++ b/src/main/java/com/youlai/boot/system/converter/DictItemConverter.java @@ -3,12 +3,9 @@ package com.youlai.boot.system.converter; import com.baomidou.mybatisplus.extension.plugins.pagination.Page; import com.youlai.boot.system.model.entity.DictItem; import com.youlai.boot.system.model.form.DictItemForm; -import com.youlai.boot.system.model.vo.DictPageVO; -import com.youlai.boot.common.model.Option; +import com.youlai.boot.system.model.vo.DictItemPageVO; import org.mapstruct.Mapper; -import java.util.List; - /** * 字典项对象转换器 * @@ -18,12 +15,9 @@ import java.util.List; @Mapper(componentModel = "spring") public interface DictItemConverter { - Page toPageVo(Page page); + Page toPageVo(Page page); DictItemForm toForm(DictItem entity); - DictItem toEntity(DictItemForm formFata); - - Option toOption(DictItem dictItem); - List> toOption(List dictData); + DictItem toEntity(DictItemForm formData); } diff --git a/src/main/java/com/youlai/boot/system/converter/LogConverter.java b/src/main/java/com/youlai/boot/system/converter/LogConverter.java new file mode 100644 index 00000000..199f6bc6 --- /dev/null +++ b/src/main/java/com/youlai/boot/system/converter/LogConverter.java @@ -0,0 +1,23 @@ +package com.youlai.boot.system.converter; + +import com.youlai.boot.framework.web.log.OperationLog; +import com.youlai.boot.system.model.entity.SysLog; +import org.mapstruct.Mapper; + +/** + * 操作日志转换器 + * + * @author Ray.Hao + * @since 4.7.0 + */ +@Mapper(componentModel = "spring") +public interface LogConverter { + + /** + * 操作日志载荷转为日志实体 + * + * @param operationLog 操作日志载荷 + * @return 日志实体 + */ + SysLog toEntity(OperationLog operationLog); +} diff --git a/src/main/java/com/youlai/boot/system/enums/MenuTypeEnum.java b/src/main/java/com/youlai/boot/system/enums/MenuTypeEnum.java index 107b7abb..0cac4fe9 100644 --- a/src/main/java/com/youlai/boot/system/enums/MenuTypeEnum.java +++ b/src/main/java/com/youlai/boot/system/enums/MenuTypeEnum.java @@ -20,15 +20,11 @@ public enum MenuTypeEnum implements IBaseEnum { EXTERNAL("E", "外链"), BUTTON("B", "按钮"); - /** - * 数据库存储值 - */ + // 数据库存储值 @EnumValue private final String value; - /** - * 友好名称 - */ + // 友好名称 private final String label; MenuTypeEnum(String value, String label) { diff --git a/src/main/java/com/youlai/boot/system/mapper/DictItemMapper.java b/src/main/java/com/youlai/boot/system/mapper/DictItemMapper.java index 64bb7af5..69b877ca 100644 --- a/src/main/java/com/youlai/boot/system/mapper/DictItemMapper.java +++ b/src/main/java/com/youlai/boot/system/mapper/DictItemMapper.java @@ -18,10 +18,10 @@ public interface DictItemMapper extends BaseMapper { /** * 字典项分页列表 + * + * @param page 分页参数 + * @param queryParams 查询参数 + * @return 字典项分页列表 */ Page getDictItemPage(Page page, DictItemQuery queryParams); } - - - - diff --git a/src/main/java/com/youlai/boot/system/mapper/DictMapper.java b/src/main/java/com/youlai/boot/system/mapper/DictMapper.java index c18b5d06..2c9a1c18 100644 --- a/src/main/java/com/youlai/boot/system/mapper/DictMapper.java +++ b/src/main/java/com/youlai/boot/system/mapper/DictMapper.java @@ -26,7 +26,3 @@ public interface DictMapper extends BaseMapper { Page getDictPage(Page page, DictQuery queryParams); } - - - - diff --git a/src/main/java/com/youlai/boot/system/mapper/RoleMapper.java b/src/main/java/com/youlai/boot/system/mapper/RoleMapper.java index fead0397..147ebb4d 100644 --- a/src/main/java/com/youlai/boot/system/mapper/RoleMapper.java +++ b/src/main/java/com/youlai/boot/system/mapper/RoleMapper.java @@ -28,8 +28,6 @@ public interface RoleMapper extends BaseMapper { /** * 获取角色的数据权限信息列表 - *

- * 返回角色编码和数据权限范围的映射列表 * * @param roleCodes 角色编码集合 * @return 角色数据权限信息列表 [{code: 'ADMIN', data_scope: 1}, ...] diff --git a/src/main/java/com/youlai/boot/system/model/dto/DictChangeEvent.java b/src/main/java/com/youlai/boot/system/model/dto/DictChangeDTO.java similarity index 62% rename from src/main/java/com/youlai/boot/system/model/dto/DictChangeEvent.java rename to src/main/java/com/youlai/boot/system/model/dto/DictChangeDTO.java index d6d0f5e3..fc9ced3e 100644 --- a/src/main/java/com/youlai/boot/system/model/dto/DictChangeEvent.java +++ b/src/main/java/com/youlai/boot/system/model/dto/DictChangeDTO.java @@ -8,9 +8,7 @@ import java.io.Serial; import java.io.Serializable; /** - * 字典变更事件 - *

- * 当字典数据发生变更时,通过 SSE 广播此事件通知前端清除缓存。 + * 字典变更通知数据 * * @author Ray.Hao * @since 3.0.0 @@ -18,24 +16,24 @@ import java.io.Serializable; @Data @NoArgsConstructor @AllArgsConstructor -public class DictChangeEvent implements Serializable { +public class DictChangeDTO implements Serializable { @Serial private static final long serialVersionUID = 1L; - /** 字典编码 */ + // 字典编码 private String dictCode; - /** 事件时间戳 */ + // 变更时间戳 private long timestamp; /** - * 创建字典变更事件(自动设置当前时间戳) + * 创建字典变更通知数据(自动设置当前时间戳) * * @param dictCode 字典编码 */ - public DictChangeEvent(String dictCode) { + public DictChangeDTO(String dictCode) { this.dictCode = dictCode; this.timestamp = System.currentTimeMillis(); } -} +} \ No newline at end of file diff --git a/src/main/java/com/youlai/boot/system/model/dto/MenuCreateDTO.java b/src/main/java/com/youlai/boot/system/model/dto/MenuCreateDTO.java new file mode 100644 index 00000000..911de1e9 --- /dev/null +++ b/src/main/java/com/youlai/boot/system/model/dto/MenuCreateDTO.java @@ -0,0 +1,23 @@ +package com.youlai.boot.system.model.dto; + +/** + * 创建菜单DTO + * + * @author Ray.Hao + * @since 4.8.0 + */ +public record MenuCreateDTO( + + /** 菜单名称 */ + String name, + + /** 路由名称,同时作为前端组件目录名 */ + String routeName, + + /** 前端组件所属模块名,如 system */ + String moduleName, + + /** 按钮权限前缀使用的表名,如 sys_user */ + String tableName +) { +} \ No newline at end of file diff --git a/src/main/java/com/youlai/boot/system/model/dto/RolePermsDTO.java b/src/main/java/com/youlai/boot/system/model/dto/RolePermsDTO.java index 68698ded..32b6f879 100644 --- a/src/main/java/com/youlai/boot/system/model/dto/RolePermsDTO.java +++ b/src/main/java/com/youlai/boot/system/model/dto/RolePermsDTO.java @@ -12,13 +12,9 @@ import java.util.Set; @Data public class RolePermsDTO { - /** - * 角色编码 - */ + // 角色编码 private String roleCode; - /** - * 权限集合 - */ + // 权限集合 private Set perms; } \ No newline at end of file diff --git a/src/main/java/com/youlai/boot/system/model/entity/Config.java b/src/main/java/com/youlai/boot/system/model/entity/Config.java index 40a8075f..1fa7c495 100644 --- a/src/main/java/com/youlai/boot/system/model/entity/Config.java +++ b/src/main/java/com/youlai/boot/system/model/entity/Config.java @@ -18,42 +18,28 @@ import lombok.EqualsAndHashCode; @TableName("sys_config") public class Config extends BaseEntity { - /** - * 配置名称 - */ + // 配置名称 private String configName; - /** - * 配置键 - */ + // 配置键 private String configKey; - /** - * 配置值 - */ + // 配置值 private String configValue; - /** - * 描述、备注 - */ + // 描述、备注 @TableField(updateStrategy = FieldStrategy.ALWAYS) private String remark; - /** - * 创建人ID - */ + // 创建人ID @TableField(fill = FieldFill.INSERT) private Long createBy; - /** - * 更新人ID - */ + // 更新人ID @TableField(fill = FieldFill.INSERT_UPDATE) private Long updateBy; - /** - * 逻辑删除标识(0-未删除 1-已删除) - */ + // 逻辑删除标识(0-未删除 1-已删除) private Integer isDeleted; } diff --git a/src/main/java/com/youlai/boot/system/model/entity/Dept.java b/src/main/java/com/youlai/boot/system/model/entity/Dept.java index cb31f54d..2c5914fd 100644 --- a/src/main/java/com/youlai/boot/system/model/entity/Dept.java +++ b/src/main/java/com/youlai/boot/system/model/entity/Dept.java @@ -18,51 +18,33 @@ import lombok.EqualsAndHashCode; @EqualsAndHashCode(callSuper = true) public class Dept extends BaseEntity { - /** - * 部门名称 - */ + // 部门名称 private String name; - /** - * 部门编码 - */ + // 部门编码 private String code; - /** - * 父节点id - */ + // 父节点id private Long parentId; - /** - * 父节点id路径 - */ + // 父节点id路径 private String treePath; - /** - * 显示顺序 - */ + // 显示顺序 private Integer sort; - /** - * 状态(1-正常 0-禁用) - */ + // 状态(1-正常 0-禁用) private Integer status; - /** - * 创建人 ID - */ + // 创建人 ID @TableField(fill = FieldFill.INSERT) private Long createBy; - /** - * 更新人 ID - */ + // 更新人 ID @TableField(fill = FieldFill.INSERT_UPDATE) private Long updateBy; - /** - * 是否删除(0-否 1-是) - */ + // 是否删除(0-否 1-是) private Integer isDeleted; } \ No newline at end of file diff --git a/src/main/java/com/youlai/boot/system/model/entity/Dict.java b/src/main/java/com/youlai/boot/system/model/entity/Dict.java index 1085e4f2..536f838e 100644 --- a/src/main/java/com/youlai/boot/system/model/entity/Dict.java +++ b/src/main/java/com/youlai/boot/system/model/entity/Dict.java @@ -6,7 +6,7 @@ import lombok.Data; import lombok.EqualsAndHashCode; /** - * 字典实体 + * 字典实体对象 * * @author Ray.Hao * @since 2022/12/17 @@ -16,31 +16,21 @@ import lombok.EqualsAndHashCode; @Data public class Dict extends BaseEntity { - /** - * 字典编码 - */ + // 字典编码 private String dictCode; - /** - * 字典名称 - */ + // 字典名称 private String name; - /** - * 状态(1:启用, 0:停用) - */ + // 状态(1:启用, 0:停用) private Integer status; - /** - * 备注 - */ + // 备注 @TableField(updateStrategy = FieldStrategy.ALWAYS) private String remark; - /** - * 逻辑删除标识(0-未删除 1-已删除) - */ + // 逻辑删除(1-已删除 0-未删除) private Integer isDeleted; -} \ No newline at end of file +} diff --git a/src/main/java/com/youlai/boot/system/model/entity/DictItem.java b/src/main/java/com/youlai/boot/system/model/entity/DictItem.java index 0fc80ee2..9da940e6 100644 --- a/src/main/java/com/youlai/boot/system/model/entity/DictItem.java +++ b/src/main/java/com/youlai/boot/system/model/entity/DictItem.java @@ -16,52 +16,38 @@ import lombok.EqualsAndHashCode; @Data public class DictItem extends BaseEntity { - /** - * 字典编码 - */ + // 字典编码 private String dictCode; - /** - * 字典项名称 - */ + // 字典项名称 private String label; - /** - * 字典项值 - */ + // 字典项值 private String value; - /** - * 排序 - */ + // 排序 private Integer sort; - /** - * 状态(1-正常,0-禁用) - */ + // 状态(1-启用,0-停用) private Integer status; - /** - * 备注 - */ + // 备注 @TableField(updateStrategy = FieldStrategy.ALWAYS) private String remark; - /** - * 标签类型 - */ + // 标签类型 @TableField(updateStrategy = FieldStrategy.ALWAYS) private String tagType; - /** - * 创建人 ID - */ + // 创建人 ID @TableField(fill = FieldFill.INSERT) private Long createBy; - /** - * 更新人 ID - */ + // 更新人 ID @TableField(fill = FieldFill.INSERT_UPDATE) private Long updateBy; -} \ No newline at end of file + + // 逻辑删除(1-已删除 0-未删除) + private Integer isDeleted; + +} diff --git a/src/main/java/com/youlai/boot/system/model/entity/Menu.java b/src/main/java/com/youlai/boot/system/model/entity/Menu.java index 2eb8d833..9bed7331 100644 --- a/src/main/java/com/youlai/boot/system/model/entity/Menu.java +++ b/src/main/java/com/youlai/boot/system/model/entity/Menu.java @@ -18,90 +18,55 @@ import java.util.Map; @Data @EqualsAndHashCode(callSuper = true) public class Menu extends BaseEntity { - /** - * 父菜单ID - */ + // 父菜单ID private Long parentId; - /** - * 菜单名称 - */ + // 菜单名称 private String name; - /** - * 菜单类型(C-目录 M-菜单 E-外链 B-按钮) - */ + // 菜单类型(C-目录 M-菜单 E-外链 B-按钮) private String type; - /** - * 路由名称(Vue Router 中定义的路由名称) - */ + // 路由名称(Vue Router 中定义的路由名称) @TableField(updateStrategy = FieldStrategy.ALWAYS) private String routeName; - /** - * 路由路径(Vue Router 中定义的 URL 路径) - */ + // 路由路径(Vue Router 中定义的 URL 路径) private String routePath; - /** - * 组件路径(vue页面完整路径,省略.vue后缀) - */ + // 组件路径(vue页面完整路径,省略.vue后缀) @TableField(updateStrategy = FieldStrategy.ALWAYS) private String component; - /** - * 外链地址 - */ + // 外链地址 @TableField(updateStrategy = FieldStrategy.ALWAYS) private String externalUrl; - /** - * 权限标识 - */ + // 权限标识 @TableField(updateStrategy = FieldStrategy.ALWAYS) private String perm; - /** - * 显示状态(1:显示;0:隐藏) - */ + // 显示状态(1:显示;0:隐藏) private Integer visible; - /** - * 排序 - */ + // 排序 private Integer sort; - /** - * 菜单图标 - */ + // 菜单图标 @TableField(updateStrategy = FieldStrategy.ALWAYS) private String icon; - /** - * 跳转路径 - */ + // 跳转路径 @TableField(updateStrategy = FieldStrategy.ALWAYS) private String redirect; - /** - * 父节点路径,以英文逗号(,)分割 - */ + // 父节点路径,以英文逗号(,)分割 private String treePath; - /** - * 【菜单】是否开启页面缓存(1:开启;0:关闭) - */ + // 【菜单】是否开启页面缓存(1:开启;0:关闭) private Integer keepAlive; - /** - * 【目录】只有一个子路由是否始终显示(1:是 0:否) - */ - private Integer alwaysShow; - - /** - * 路由参数 - */ + // 路由参数 @TableField(updateStrategy = FieldStrategy.ALWAYS, typeHandler = JacksonTypeHandler.class) private Map params; diff --git a/src/main/java/com/youlai/boot/system/model/entity/Notice.java b/src/main/java/com/youlai/boot/system/model/entity/Notice.java index e2a4317b..fa7d9f09 100644 --- a/src/main/java/com/youlai/boot/system/model/entity/Notice.java +++ b/src/main/java/com/youlai/boot/system/model/entity/Notice.java @@ -22,69 +22,43 @@ public class Notice extends BaseEntity { @Serial private static final long serialVersionUID = 1L; - /** - * 通知标题 - */ + // 通知标题 private String title; - /** - * 通知内容 - */ + // 通知内容 private String content; - /** - * 通知类型 - */ + // 通知类型 private Integer type; - /** - * 发布人 - */ + // 发布人 private Long publisherId; - /** - * 通知等级(L: 低, M: 中, H: 高) - */ + // 通知等级(L: 低, M: 中, H: 高) private String level; - /** - * 目标类型(1: 全体, 2: 指定) - */ + // 目标类型(1: 全体, 2: 指定) private Integer targetType; - /** - * 目标用户ID集合 - */ + // 目标用户ID集合 @TableField(updateStrategy = FieldStrategy.ALWAYS) private String targetUserIds; - /** - * 发布状态(0: 未发布, 1: 已发布, -1: 已撤回) - */ + // 发布状态(0: 未发布, 1: 已发布, -1: 已撤回) private Integer publishStatus; - /** - * 发布时间 - */ + // 发布时间 private LocalDateTime publishTime; - /** - * 撤回时间 - */ + // 撤回时间 private LocalDateTime revokeTime; - /** - * 创建人ID - */ + // 创建人ID @TableField(fill = FieldFill.INSERT) private Long createBy; - /** - * 更新人ID - */ + // 更新人ID @TableField(fill = FieldFill.INSERT_UPDATE) private Long updateBy; - /** - * 逻辑删除标识(0-未删除 1-已删除) - */ + // 逻辑删除标识(0-未删除 1-已删除) private Integer isDeleted; } diff --git a/src/main/java/com/youlai/boot/system/model/entity/Role.java b/src/main/java/com/youlai/boot/system/model/entity/Role.java index d81a3823..1e91ffdb 100644 --- a/src/main/java/com/youlai/boot/system/model/entity/Role.java +++ b/src/main/java/com/youlai/boot/system/model/entity/Role.java @@ -18,45 +18,29 @@ import lombok.EqualsAndHashCode; @EqualsAndHashCode(callSuper = true) public class Role extends BaseEntity { - /** - * 角色名称 - */ + // 角色名称 private String name; - /** - * 角色编码 - */ + // 角色编码 private String code; - /** - * 显示顺序 - */ + // 显示顺序 private Integer sort; - /** - * 角色状态(1-正常 0-停用) - */ + // 角色状态(1-正常 0-停用) private Integer status; - /** - * 数据权限 - */ + // 数据权限 private Integer dataScope; - /** - * 创建人 ID - */ + // 创建人 ID @TableField(fill = FieldFill.INSERT) private Long createBy; - /** - * 更新人 ID - */ + // 更新人 ID @TableField(fill = FieldFill.INSERT_UPDATE) private Long updateBy; - /** - * 是否删除(0-否 1-是) - */ + // 是否删除(0-否 1-是) private Integer isDeleted; } \ No newline at end of file diff --git a/src/main/java/com/youlai/boot/system/model/entity/RoleDept.java b/src/main/java/com/youlai/boot/system/model/entity/RoleDept.java index 93ef111b..dc4cd420 100644 --- a/src/main/java/com/youlai/boot/system/model/entity/RoleDept.java +++ b/src/main/java/com/youlai/boot/system/model/entity/RoleDept.java @@ -7,8 +7,6 @@ import lombok.NoArgsConstructor; /** * 角色部门关联实体 - *

- * 用于存储角色自定义数据权限时,可访问的部门ID列表 * * @author Ray.Hao * @since 3.0.0 @@ -19,14 +17,10 @@ import lombok.NoArgsConstructor; @AllArgsConstructor public class RoleDept { - /** - * 角色ID - */ + // 角色ID private Long roleId; - /** - * 部门ID - */ + // 部门ID private Long deptId; } diff --git a/src/main/java/com/youlai/boot/system/model/entity/RoleMenu.java b/src/main/java/com/youlai/boot/system/model/entity/RoleMenu.java index e16825d6..8ac94e8d 100644 --- a/src/main/java/com/youlai/boot/system/model/entity/RoleMenu.java +++ b/src/main/java/com/youlai/boot/system/model/entity/RoleMenu.java @@ -14,14 +14,10 @@ import lombok.NoArgsConstructor; @AllArgsConstructor @NoArgsConstructor public class RoleMenu { - /** - * 角色ID - */ + // 角色ID private Long roleId; - /** - * 菜单ID - */ + // 菜单ID private Long menuId; } \ No newline at end of file diff --git a/src/main/java/com/youlai/boot/system/model/entity/SysLog.java b/src/main/java/com/youlai/boot/system/model/entity/SysLog.java index b7712d7f..789ac82d 100644 --- a/src/main/java/com/youlai/boot/system/model/entity/SysLog.java +++ b/src/main/java/com/youlai/boot/system/model/entity/SysLog.java @@ -18,103 +18,65 @@ import java.time.LocalDateTime; @TableName("sys_log") public class SysLog implements Serializable { - /** - * 主键 - */ + // 主键 @TableId(type = IdType.AUTO) private Long id; - /** - * 模块 - */ + // 模块 private LogModuleEnum module; - /** - * 操作类型 - */ + // 操作类型 @TableField(value = "action_type") private ActionTypeEnum actionType; - /** - * 操作标题 - */ + // 操作标题 private String title; - /** - * 自定义日志内容,最长 500 字符 - */ + // 自定义日志内容,最长 500 字符 private String content; - /** - * 操作人ID - */ + // 操作人ID private Long operatorId; - /** - * 操作人名称 - */ + // 操作人名称 private String operatorName; - /** - * 请求路径 - */ + // 请求路径 private String requestUri; - /** - * 请求方式 - */ + // 请求方式 @TableField(value = "request_method") private String requestMethod; - /** - * IP 地址 - */ + // IP 地址 private String ip; - /** - * 省份 - */ + // 省份 private String province; - /** - * 城市 - */ + // 城市 private String city; - /** - * 设备 - */ + // 设备 private String device; - /** - * 操作系统 - */ + // 操作系统 private String os; - /** - * 浏览器 - */ + // 浏览器 private String browser; - /** - * 状态:0失败 1成功 - */ + // 状态:0失败 1成功 private Integer status; - /** - * 错误信息,切面内截断至 1000 字符 - */ + // 错误信息,切面内截断至 1000 字符 @TableField(value = "error_msg") private String errorMsg; - /** - * 执行时间(毫秒) - */ + // 执行时间(毫秒) private Integer executionTime; - /** - * 操作时间 - */ + // 操作时间 private LocalDateTime createTime; } diff --git a/src/main/java/com/youlai/boot/system/model/entity/SysUser.java b/src/main/java/com/youlai/boot/system/model/entity/SysUser.java index 728edbbc..355053c6 100644 --- a/src/main/java/com/youlai/boot/system/model/entity/SysUser.java +++ b/src/main/java/com/youlai/boot/system/model/entity/SysUser.java @@ -13,68 +13,44 @@ import lombok.EqualsAndHashCode; @EqualsAndHashCode(callSuper = true) public class SysUser extends BaseEntity { - /** - * 用户名 - */ + // 用户名 private String username; - /** - * 昵称 - */ + // 昵称 private String nickname; - /** - * 性别(1-男 2-女 0-保密) - */ + // 性别(1-男 2-女 0-保密) private Integer gender; - /** - * 密码 - */ + // 密码 private String password; - /** - * 部门ID - */ + // 部门ID private Long deptId; - /** - * 用户头像 - */ + // 用户头像 @TableField(updateStrategy = FieldStrategy.ALWAYS) private String avatar; - /** - * 联系方式 - */ + // 联系方式 @TableField(updateStrategy = FieldStrategy.ALWAYS) private String mobile; - /** - * 状态(1-正常 0-禁用) - */ + // 状态(1-正常 0-禁用) private Integer status; - /** - * 用户邮箱 - */ + // 用户邮箱 @TableField(updateStrategy = FieldStrategy.ALWAYS) private String email; - /** - * 创建人 ID - */ + // 创建人 ID @TableField(fill = FieldFill.INSERT) private Long createBy; - /** - * 更新人 ID - */ + // 更新人 ID @TableField(fill = FieldFill.INSERT_UPDATE) private Long updateBy; - /** - * 是否删除(0-否 1-是) - */ + // 是否删除(0-否 1-是) private Integer isDeleted; } \ No newline at end of file diff --git a/src/main/java/com/youlai/boot/system/model/entity/UserNotice.java b/src/main/java/com/youlai/boot/system/model/entity/UserNotice.java index ea91e5f7..cde22216 100644 --- a/src/main/java/com/youlai/boot/system/model/entity/UserNotice.java +++ b/src/main/java/com/youlai/boot/system/model/entity/UserNotice.java @@ -20,15 +20,15 @@ import java.time.LocalDateTime; @TableName("sys_user_notice") public class UserNotice extends BaseEntity { - /** 公共通知id */ + // 公共通知id private Long noticeId; - /** 用户id */ + // 用户id private Long userId; - /** 读取状态,0未读,1已读 */ + // 读取状态,0未读,1已读 private Integer isRead; - /** 用户阅读时间 */ + // 用户阅读时间 private LocalDateTime readTime; - /** 逻辑删除标识(0-未删除 1-已删除) */ + // 逻辑删除标识(0-未删除 1-已删除) @TableLogic(value = "0", delval = "1") private Integer isDeleted; } diff --git a/src/main/java/com/youlai/boot/system/model/entity/UserRole.java b/src/main/java/com/youlai/boot/system/model/entity/UserRole.java index 9ab2e05d..d52a09b5 100644 --- a/src/main/java/com/youlai/boot/system/model/entity/UserRole.java +++ b/src/main/java/com/youlai/boot/system/model/entity/UserRole.java @@ -17,13 +17,9 @@ import lombok.NoArgsConstructor; @AllArgsConstructor @NoArgsConstructor public class UserRole { - /** - * 用户ID - */ + // 用户ID private Long userId; - /** - * 角色ID - */ + // 角色ID private Long roleId; } \ No newline at end of file diff --git a/src/main/java/com/youlai/boot/system/model/entity/UserSocial.java b/src/main/java/com/youlai/boot/system/model/entity/UserSocial.java index c5bbd7fc..ee640d67 100644 --- a/src/main/java/com/youlai/boot/system/model/entity/UserSocial.java +++ b/src/main/java/com/youlai/boot/system/model/entity/UserSocial.java @@ -16,59 +16,37 @@ import java.time.LocalDateTime; @Setter public class UserSocial { - /** - * 主键ID - */ + // 主键ID private Long id; - /** - * 用户ID - */ + // 用户ID private Long userId; - /** - * 平台类型 - */ + // 平台类型 private SocialPlatformEnum platform; - /** - * 平台openid - */ + // 平台openid private String openid; - /** - * 微信unionid - */ + // 微信unionid private String unionid; - /** - * 第三方昵称 - */ + // 第三方昵称 private String nickname; - /** - * 第三方头像URL - */ + // 第三方头像URL private String avatar; - /** - * 微信session_key - */ + // 微信session_key private String sessionKey; - /** - * 是否已验证(1-已验证 0-未验证) - */ + // 是否已验证(1-已验证 0-未验证) private Integer verified; - /** - * 绑定时间 - */ + // 绑定时间 private LocalDateTime createTime; - /** - * 更新时间 - */ + // 更新时间 private LocalDateTime updateTime; } diff --git a/src/main/java/com/youlai/boot/system/model/form/DictForm.java b/src/main/java/com/youlai/boot/system/model/form/DictForm.java index b17d320a..039866da 100644 --- a/src/main/java/com/youlai/boot/system/model/form/DictForm.java +++ b/src/main/java/com/youlai/boot/system/model/form/DictForm.java @@ -4,12 +4,8 @@ package com.youlai.boot.system.model.form; import io.swagger.v3.oas.annotations.media.Schema; import jakarta.validation.constraints.NotBlank; import lombok.Data; -import lombok.Getter; -import lombok.Setter; import org.hibernate.validator.constraints.Range; -import java.util.List; - /** * 字典表单对象 * diff --git a/src/main/java/com/youlai/boot/system/model/form/DictItemForm.java b/src/main/java/com/youlai/boot/system/model/form/DictItemForm.java index 373a5216..3c48101b 100644 --- a/src/main/java/com/youlai/boot/system/model/form/DictItemForm.java +++ b/src/main/java/com/youlai/boot/system/model/form/DictItemForm.java @@ -2,7 +2,11 @@ package com.youlai.boot.system.model.form; import io.swagger.v3.oas.annotations.media.Schema; +import jakarta.validation.constraints.NotBlank; +import jakarta.validation.constraints.Size; import lombok.Data; +import org.hibernate.validator.constraints.Length; +import org.hibernate.validator.constraints.Range; /** * 字典项表单对象 @@ -14,25 +18,32 @@ import lombok.Data; @Data public class DictItemForm { - @Schema(description = "字典项ID") + @Schema(description = "字典项ID(由请求路径传入并覆盖,仅用于表单回显)") private Long id; - @Schema(description = "字典编码") + @Schema(description = "字典编码(由请求路径传入并覆盖,仅用于表单回显)") private String dictCode; @Schema(description = "字典项值") + @NotBlank(message = "字典项值不能为空") + @Length(max = 100, message = "字典项值长度不能超过 100 个字符") private String value; @Schema(description = "字典项标签") + @NotBlank(message = "字典项标签不能为空") + @Length(max = 100, message = "字典项标签长度不能超过 100 个字符") private String label; @Schema(description = "排序") + @Range(min = 0, max = 9999, message = "排序值需在 0-9999 之间") private Integer sort; - @Schema(description = "状态(0:禁用,1:启用)") + @Schema(description = "状态(1-启用,0-禁用)") + @Range(min = 0, max = 1, message = "状态取值不正确") private Integer status; - @Schema(description = "字典类型(用于显示样式)") + @Schema(description = "标签样式(primary-主要 success-成功 warning-警告 danger-危险 info-信息)") + @Size(max = 30, message = "标签样式长度不能超过 30 个字符") private String tagType; } diff --git a/src/main/java/com/youlai/boot/system/model/form/MenuAiFillForm.java b/src/main/java/com/youlai/boot/system/model/form/MenuAiFillForm.java new file mode 100644 index 00000000..497f9c6f --- /dev/null +++ b/src/main/java/com/youlai/boot/system/model/form/MenuAiFillForm.java @@ -0,0 +1,26 @@ +package com.youlai.boot.system.model.form; + +import io.swagger.v3.oas.annotations.media.Schema; +import jakarta.validation.constraints.NotBlank; +import lombok.Data; + +/** + * AI 推断菜单配置入参 + * + * @author Ray.Hao + * @since 0.1.0 + */ +@Schema(description = "AI 推断菜单配置入参") +@Data +public class MenuAiFillForm { + + @Schema(description = "菜单名称", example = "公告管理") + @NotBlank(message = "菜单名称不能为空") + private String name; + + @Schema(description = "菜单类型(C-目录 M-菜单 E-外链 B-按钮)", example = "M") + private String type; + + @Schema(description = "上级菜单ID,用于参考同级菜单的命名风格", example = "1") + private Long parentId; +} diff --git a/src/main/java/com/youlai/boot/system/model/form/MenuForm.java b/src/main/java/com/youlai/boot/system/model/form/MenuForm.java index 459ab708..921ee496 100644 --- a/src/main/java/com/youlai/boot/system/model/form/MenuForm.java +++ b/src/main/java/com/youlai/boot/system/model/form/MenuForm.java @@ -60,10 +60,13 @@ public class MenuForm { @Schema(description = "【菜单】是否开启页面缓存", example = "1") private Integer keepAlive; - @Schema(description = "【目录】只有一个子路由是否始终显示", example = "1") - private Integer alwaysShow; - @Schema(description = "路由参数") private List params; + @Schema(description = "新增页面菜单时是否生成增删改查按钮") + private Boolean generateCrudButtons; + + @Schema(description = "按钮权限标识前缀,如 sys:user") + private String buttonPermPrefix; + } diff --git a/src/main/java/com/youlai/boot/system/model/form/PasswordResetForm.java b/src/main/java/com/youlai/boot/system/model/form/PasswordResetForm.java new file mode 100644 index 00000000..8396dfb9 --- /dev/null +++ b/src/main/java/com/youlai/boot/system/model/form/PasswordResetForm.java @@ -0,0 +1,21 @@ +package com.youlai.boot.system.model.form; + +import io.swagger.v3.oas.annotations.media.Schema; +import jakarta.validation.constraints.NotBlank; +import jakarta.validation.constraints.Size; +import lombok.Data; + +/** + * 重置密码表单 + * + * @author youlai.tech + */ +@Schema(description = "重置密码表单") +@Data +public class PasswordResetForm { + + @Schema(description = "新密码") + @NotBlank(message = "新密码不能为空") + @Size(min = 6, max = 20, message = "密码长度需在 6-20 个字符之间") + private String password; +} \ No newline at end of file diff --git a/src/main/java/com/youlai/boot/system/model/form/PasswordUpdateForm.java b/src/main/java/com/youlai/boot/system/model/form/PasswordUpdateForm.java index aaab86d7..f2c33344 100644 --- a/src/main/java/com/youlai/boot/system/model/form/PasswordUpdateForm.java +++ b/src/main/java/com/youlai/boot/system/model/form/PasswordUpdateForm.java @@ -1,6 +1,8 @@ package com.youlai.boot.system.model.form; import io.swagger.v3.oas.annotations.media.Schema; +import jakarta.validation.constraints.NotBlank; +import jakarta.validation.constraints.Size; import lombok.Data; /** @@ -14,11 +16,15 @@ import lombok.Data; public class PasswordUpdateForm { @Schema(description = "原密码") + @NotBlank(message = "原密码不能为空") private String oldPassword; @Schema(description = "新密码") + @NotBlank(message = "新密码不能为空") + @Size(min = 6, max = 20, message = "密码长度需在 6-20 个字符之间") private String newPassword; @Schema(description = "确认密码") + @NotBlank(message = "确认密码不能为空") private String confirmPassword; } diff --git a/src/main/java/com/youlai/boot/system/model/form/RoleForm.java b/src/main/java/com/youlai/boot/system/model/form/RoleForm.java index 3f0e09d2..410b5757 100644 --- a/src/main/java/com/youlai/boot/system/model/form/RoleForm.java +++ b/src/main/java/com/youlai/boot/system/model/form/RoleForm.java @@ -2,8 +2,6 @@ package com.youlai.boot.system.model.form; import io.swagger.v3.oas.annotations.media.Schema; import lombok.Data; - -// import jakarta.validation.constraints.NotBlank; import jakarta.validation.constraints.NotBlank; import org.hibernate.validator.constraints.Range; diff --git a/src/main/java/com/youlai/boot/system/model/form/UserProfileForm.java b/src/main/java/com/youlai/boot/system/model/form/UserProfileForm.java index 25953345..5f0bf3ff 100644 --- a/src/main/java/com/youlai/boot/system/model/form/UserProfileForm.java +++ b/src/main/java/com/youlai/boot/system/model/form/UserProfileForm.java @@ -1,7 +1,10 @@ package com.youlai.boot.system.model.form; import io.swagger.v3.oas.annotations.media.Schema; +import jakarta.validation.constraints.NotBlank; +import jakarta.validation.constraints.Size; import lombok.Data; +import org.hibernate.validator.constraints.Range; /** * 个人中心用户信息 @@ -12,13 +15,18 @@ import lombok.Data; @Schema(description = "个人中心用户信息") @Data public class UserProfileForm { + @Schema(description = "用户昵称") + @NotBlank(message = "用户昵称不能为空") + @Size(max = 50, message = "用户昵称长度不能超过 50 个字符") private String nickname; @Schema(description = "头像URL") + @Size(max = 255, message = "头像地址长度不能超过 255 个字符") private String avatar; @Schema(description = "性别") + @Range(min = 0, max = 2, message = "性别取值不正确") private Integer gender; } diff --git a/src/main/java/com/youlai/boot/system/model/query/UserQuery.java b/src/main/java/com/youlai/boot/system/model/query/UserQuery.java index 43bdeed0..2cde9070 100644 --- a/src/main/java/com/youlai/boot/system/model/query/UserQuery.java +++ b/src/main/java/com/youlai/boot/system/model/query/UserQuery.java @@ -1,6 +1,5 @@ package com.youlai.boot.system.model.query; -import com.fasterxml.jackson.annotation.JsonIgnore; import com.youlai.boot.common.base.BaseQuery; import io.swagger.v3.oas.annotations.media.Schema; import lombok.Data; @@ -10,7 +9,7 @@ import java.util.List; @Data @EqualsAndHashCode(callSuper = false) -@Schema(description = "用户查询对象") +@Schema(description = "用户分页查询对象") public class UserQuery extends BaseQuery { @Schema(description = "关键字(用户名/昵称/手机号)") @@ -25,10 +24,7 @@ public class UserQuery extends BaseQuery { @Schema(description = "角色ID") private List roleIds; - @Schema(description = "创建时间范围") + // 创建时间范围,下标 0 为开始时间、下标 1 为结束时间,只传日期时自动补全为当天 00:00:00 / 23:59:59 + @Schema(description = "创建时间范围,格式为 [开始时间, 结束时间]") private List createTime; - - @JsonIgnore - @Schema(hidden = true) - private Boolean isRoot; } diff --git a/src/main/java/com/youlai/boot/system/model/vo/DictItemOptionVO.java b/src/main/java/com/youlai/boot/system/model/vo/DictItemOptionVO.java index 3fc2742c..246b2755 100644 --- a/src/main/java/com/youlai/boot/system/model/vo/DictItemOptionVO.java +++ b/src/main/java/com/youlai/boot/system/model/vo/DictItemOptionVO.java @@ -21,9 +21,7 @@ public class DictItemOptionVO { @Schema(description = "字典项标签") private String label; - @Schema(description = "标签类型") + @Schema(description = "标签样式") private String tagType; } - - \ No newline at end of file diff --git a/src/main/java/com/youlai/boot/system/model/vo/DictItemPageVO.java b/src/main/java/com/youlai/boot/system/model/vo/DictItemPageVO.java index 53a1b8df..177c4ac0 100644 --- a/src/main/java/com/youlai/boot/system/model/vo/DictItemPageVO.java +++ b/src/main/java/com/youlai/boot/system/model/vo/DictItemPageVO.java @@ -28,12 +28,13 @@ public class DictItemPageVO { @Schema(description = "字典值") private String value; + @Schema(description = "标签样式") + private String tagType; + @Schema(description = "排序") private Integer sort; - @Schema(description = "状态(1:启用,0:禁用)") + @Schema(description = "状态(1-启用,0-停用)") private Integer status; } - - \ No newline at end of file diff --git a/src/main/java/com/youlai/boot/system/model/vo/DictPageVO.java b/src/main/java/com/youlai/boot/system/model/vo/DictPageVO.java index 5185146b..a2d5454e 100644 --- a/src/main/java/com/youlai/boot/system/model/vo/DictPageVO.java +++ b/src/main/java/com/youlai/boot/system/model/vo/DictPageVO.java @@ -24,8 +24,6 @@ public class DictPageVO { @Schema(description = "字典编码") private String dictCode; - @Schema(description = "字典状态(1-启用,0-禁用)") + @Schema(description = "字典状态(1-启用,0-停用)") private Integer status; } - - \ No newline at end of file diff --git a/src/main/java/com/youlai/boot/system/model/vo/MenuAiVO.java b/src/main/java/com/youlai/boot/system/model/vo/MenuAiVO.java new file mode 100644 index 00000000..70bae7bb --- /dev/null +++ b/src/main/java/com/youlai/boot/system/model/vo/MenuAiVO.java @@ -0,0 +1,26 @@ +package com.youlai.boot.system.model.vo; + +import io.swagger.v3.oas.annotations.media.Schema; +import lombok.Data; + +import java.util.List; + +/** + * AI 推断的菜单配置 + * + * @author Ray.Hao + * @since 0.1.0 + */ +@Schema(description = "AI 推断的菜单配置") +@Data +public class MenuAiVO { + + @Schema(description = "访问路径") + private String routePath; + + @Schema(description = "权限标识") + private String perm; + + @Schema(description = "建议的图标关键词,按贴切程度排列") + private List iconKeywords; +} diff --git a/src/main/java/com/youlai/boot/system/model/vo/RouteVO.java b/src/main/java/com/youlai/boot/system/model/vo/RouteVO.java index 121ca5df..8c32f42e 100644 --- a/src/main/java/com/youlai/boot/system/model/vo/RouteVO.java +++ b/src/main/java/com/youlai/boot/system/model/vo/RouteVO.java @@ -50,10 +50,6 @@ public class RouteVO { @JsonInclude(JsonInclude.Include.NON_NULL) private Boolean keepAlive; - @Schema(description = "【目录】只有一个子路由是否始终显示", example = "true") - @JsonInclude(JsonInclude.Include.NON_NULL) - private Boolean alwaysShow; - @Schema(description = "外链地址(内嵌模式用)", example = "https://www.youlai.tech") @JsonInclude(JsonInclude.Include.NON_NULL) private String externalUrl; diff --git a/src/main/java/com/youlai/boot/system/schedule/OnlineUserCountTask.java b/src/main/java/com/youlai/boot/system/schedule/OnlineUserCountTask.java index 9eb60767..e66ecb34 100644 --- a/src/main/java/com/youlai/boot/system/schedule/OnlineUserCountTask.java +++ b/src/main/java/com/youlai/boot/system/schedule/OnlineUserCountTask.java @@ -8,7 +8,6 @@ import org.springframework.stereotype.Component; /** * 在线用户统计定时任务 - *

每 3 分钟统计并广播当前在线用户数量

* * @author Ray.Hao * @since 3.1.0 diff --git a/src/main/java/com/youlai/boot/system/schedule/XxlJobSample.java b/src/main/java/com/youlai/boot/system/schedule/XxlJobSample.java index bfaa3481..52eb68fe 100644 --- a/src/main/java/com/youlai/boot/system/schedule/XxlJobSample.java +++ b/src/main/java/com/youlai/boot/system/schedule/XxlJobSample.java @@ -6,8 +6,6 @@ import org.springframework.stereotype.Component; /** * XXL-JOB 示例任务。 - *

- * 需在调度中心配置同名任务后方可执行。 * * @author Ray.Hao * @since 3.1.0 diff --git a/src/main/java/com/youlai/boot/system/service/DictService.java b/src/main/java/com/youlai/boot/system/service/DictService.java index a064deda..942098b1 100644 --- a/src/main/java/com/youlai/boot/system/service/DictService.java +++ b/src/main/java/com/youlai/boot/system/service/DictService.java @@ -6,7 +6,6 @@ import com.youlai.boot.common.model.Option; import com.youlai.boot.system.model.entity.Dict; import com.youlai.boot.system.model.form.DictForm; import com.youlai.boot.system.model.query.DictQuery; -import com.youlai.boot.system.model.vo.DictItemOptionVO; import com.youlai.boot.system.model.vo.DictPageVO; import java.util.List; diff --git a/src/main/java/com/youlai/boot/system/service/MenuService.java b/src/main/java/com/youlai/boot/system/service/MenuService.java index 1429226c..2370b0e2 100644 --- a/src/main/java/com/youlai/boot/system/service/MenuService.java +++ b/src/main/java/com/youlai/boot/system/service/MenuService.java @@ -1,11 +1,13 @@ package com.youlai.boot.system.service; import com.baomidou.mybatisplus.extension.service.IService; -import com.youlai.boot.codegen.model.entity.GenTable; +import com.youlai.boot.system.model.dto.MenuCreateDTO; +import com.youlai.boot.system.model.form.MenuAiFillForm; import com.youlai.boot.system.model.form.MenuForm; import com.youlai.boot.common.model.Option; import com.youlai.boot.system.model.entity.Menu; import com.youlai.boot.system.model.query.MenuQuery; +import com.youlai.boot.system.model.vo.MenuAiVO; import com.youlai.boot.system.model.vo.MenuVO; import com.youlai.boot.system.model.vo.RouteVO; @@ -27,9 +29,9 @@ public interface MenuService extends IService

{ /** * 获取菜单下拉列表 * - * @param onlyParent 是否只查询父级菜单 + * @param types 菜单类型,为空查全部 */ - List> listMenuOptions(boolean onlyParent); + List> listMenuOptions(List types); /** * 新增菜单 @@ -73,10 +75,18 @@ public interface MenuService extends IService { boolean deleteMenu(Long id); /** - * 代码生成时添加菜单 + * 为代码生成创建菜单 * * @param parentMenuId 父菜单ID - * @param genConfig 实体名 + * @param dto 创建菜单数据载体 */ - void addMenuForCodegen(Long parentMenuId, GenTable genTable); + void addMenuForCodegen(Long parentMenuId, MenuCreateDTO dto); + + /** + * 用 AI 推断菜单的访问路径、权限标识与配套按钮,命名风格参照同级菜单 + * + * @param form 菜单信息 + * @return 推断结果 + */ + MenuAiVO aiFillMenu(MenuAiFillForm form); } diff --git a/src/main/java/com/youlai/boot/system/service/RoleMenuService.java b/src/main/java/com/youlai/boot/system/service/RoleMenuService.java index 1a2d948b..29337fbb 100644 --- a/src/main/java/com/youlai/boot/system/service/RoleMenuService.java +++ b/src/main/java/com/youlai/boot/system/service/RoleMenuService.java @@ -46,8 +46,6 @@ public interface RoleMenuService extends IService { /** * 获取角色权限集合(带缓存) - *

- * 采用 Read-Through 缓存策略,缓存未命中时自动回源数据库 * * @param roleCodes 角色编码集合 * @return 权限集合 diff --git a/src/main/java/com/youlai/boot/system/service/RoleService.java b/src/main/java/com/youlai/boot/system/service/RoleService.java index 8ade9edc..e211e2da 100644 --- a/src/main/java/com/youlai/boot/system/service/RoleService.java +++ b/src/main/java/com/youlai/boot/system/service/RoleService.java @@ -37,6 +37,13 @@ public interface RoleService extends IService { */ List> listRoleOptions(); + /** + * 角色编码下拉列表(value 为角色编码) + * + * @return 角色编码选项列表 + */ + List> listRoleCodeOptions(); + /** * * @param roleForm @@ -102,8 +109,6 @@ public interface RoleService extends IService { /** * 获取用户所有角色的数据权限列表 - *

- * 用于实现多角色数据权限合并(并集策略) * * @param roleCodes 角色编码集合 * @return 角色数据权限列表 diff --git a/src/main/java/com/youlai/boot/system/service/UserImportReader.java b/src/main/java/com/youlai/boot/system/service/UserImportReader.java index 3cd3f909..c5ece4ec 100644 --- a/src/main/java/com/youlai/boot/system/service/UserImportReader.java +++ b/src/main/java/com/youlai/boot/system/service/UserImportReader.java @@ -28,8 +28,6 @@ import java.util.stream.Collectors; /** * 用户导入读取器。 - *

- * 基于 EasyExcel 的 {@link AnalysisEventListener},逐行读取 Excel 并完成校验、持久化。 * * @author Ray * @since 2022/4/10 @@ -37,9 +35,7 @@ import java.util.stream.Collectors; @Slf4j public class UserImportReader extends AnalysisEventListener { - /** - * Excel 导入结果 - */ + // Excel 导入结果 @Getter private final ExcelResult excelResult; @@ -52,14 +48,11 @@ public class UserImportReader extends AnalysisEventListener { private final List deptList; private final List genderList; - /** - * 当前行 - */ + // 当前行 private Integer currentRow = 1; /** * 构造方法 - *

在构造方法中给需要查询的内容查询好,尽量避免每条数据查询一次

*/ public UserImportReader() { this.userService = SpringUtil.getBean(UserService.class); @@ -78,9 +71,6 @@ public class UserImportReader extends AnalysisEventListener { /** * 每一条数据解析都会来调用 - *

- * 1. 数据校验;全字段校验 - * 2. 数据持久化; * * @param userImportDto 一行数据,类似于 {@link AnalysisContext#readRowHolder()} */ diff --git a/src/main/java/com/youlai/boot/system/service/impl/DictItemServiceImpl.java b/src/main/java/com/youlai/boot/system/service/impl/DictItemServiceImpl.java index 48c65a29..4e85259f 100644 --- a/src/main/java/com/youlai/boot/system/service/impl/DictItemServiceImpl.java +++ b/src/main/java/com/youlai/boot/system/service/impl/DictItemServiceImpl.java @@ -1,5 +1,6 @@ package com.youlai.boot.system.service.impl; +import cn.hutool.core.lang.Assert; import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; import com.baomidou.mybatisplus.extension.plugins.pagination.Page; import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; @@ -44,7 +45,6 @@ public class DictItemServiceImpl extends ServiceImpl i return this.baseMapper.getDictItemPage(page, queryParams); } - /** * 获取字典项列表 * @@ -57,6 +57,7 @@ public class DictItemServiceImpl extends ServiceImpl i .eq(DictItem::getDictCode, dictCode) .eq(DictItem::getStatus, 1) .orderByAsc(DictItem::getSort) + .orderByAsc(DictItem::getId) ).stream() .map(item -> { DictItemOptionVO dictItemOptionVo = new DictItemOptionVO(); @@ -67,8 +68,6 @@ public class DictItemServiceImpl extends ServiceImpl i }).toList(); } - - /** * 获取字典项表单 * @@ -76,7 +75,7 @@ public class DictItemServiceImpl extends ServiceImpl i * @return 字典项表单 */ @Override - public DictItemForm getDictItemForm( Long itemId) { + public DictItemForm getDictItemForm(Long itemId) { DictItem entity = this.getById(itemId); return dictItemConverter.toForm(entity); } @@ -89,6 +88,7 @@ public class DictItemServiceImpl extends ServiceImpl i */ @Override public boolean saveDictItem(DictItemForm formData) { + validateValueUnique(formData.getDictCode(), formData.getValue(), null); DictItem entity = dictItemConverter.toEntity(formData); return this.save(entity); } @@ -101,6 +101,7 @@ public class DictItemServiceImpl extends ServiceImpl i */ @Override public boolean updateDictItem(DictItemForm formData) { + validateValueUnique(formData.getDictCode(), formData.getValue(), formData.getId()); DictItem entity = dictItemConverter.toEntity(formData); return this.updateById(entity); } @@ -118,8 +119,20 @@ public class DictItemServiceImpl extends ServiceImpl i this.removeByIds(idList); } + /** + * 校验同一字典下字典项值唯一 + * + * @param dictCode 字典编码 + * @param value 字典项值 + * @param excludeId 更新时传当前字典项ID以排除自身,新增传 null 不排除任何记录 + */ + private void validateValueUnique(String dictCode, String value, Long excludeId) { + long count = this.count(new LambdaQueryWrapper() + .eq(DictItem::getDictCode, dictCode) + .eq(DictItem::getValue, value) + .ne(excludeId != null, DictItem::getId, excludeId) + ); + Assert.isTrue(count == 0, "该字典下字典项值已存在"); + } + } - - - - diff --git a/src/main/java/com/youlai/boot/system/service/impl/DictServiceImpl.java b/src/main/java/com/youlai/boot/system/service/impl/DictServiceImpl.java index ffc8e06d..c128890f 100644 --- a/src/main/java/com/youlai/boot/system/service/impl/DictServiceImpl.java +++ b/src/main/java/com/youlai/boot/system/service/impl/DictServiceImpl.java @@ -134,7 +134,7 @@ public class DictServiceImpl extends ServiceImpl implements Di .eq(DictItem::getDictCode, entity.getDictCode()) .select(DictItem::getId) ); - if (!dictItemList.isEmpty()){ + if (!dictItemList.isEmpty()) { List dictItemIds = dictItemList.stream().map(DictItem::getId).toList(); DictItem dictItem = new DictItem(); dictItem.setDictCode(dict.getDictCode()); @@ -155,13 +155,14 @@ public class DictServiceImpl extends ServiceImpl implements Di @Transactional @Override public void deleteDictByIds(List ids) { + // 先取字典编码:删除后再查会被逻辑删除条件过滤,导致字典项无法级联删除 + List dictCodes = this.listByIds(ids).stream().map(Dict::getDictCode).toList(); + // 删除字典 this.removeByIds(ids); // 删除字典项 - List list = this.listByIds(ids); - if (!list.isEmpty()) { - List dictCodes = list.stream().map(Dict::getDictCode).toList(); + if (!dictCodes.isEmpty()) { dictItemService.remove(new LambdaQueryWrapper() .in(DictItem::getDictCode, dictCodes) ); @@ -181,7 +182,3 @@ public class DictServiceImpl extends ServiceImpl implements Di } } - - - - diff --git a/src/main/java/com/youlai/boot/system/service/impl/MenuServiceImpl.java b/src/main/java/com/youlai/boot/system/service/impl/MenuServiceImpl.java index 28c581dd..86f5aa34 100644 --- a/src/main/java/com/youlai/boot/system/service/impl/MenuServiceImpl.java +++ b/src/main/java/com/youlai/boot/system/service/impl/MenuServiceImpl.java @@ -7,13 +7,19 @@ import cn.hutool.core.util.StrUtil; import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper; import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper; import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; -import com.youlai.boot.codegen.model.entity.GenTable; +import com.youlai.boot.common.base.IBaseEnum; +import com.youlai.boot.common.exception.BusinessException; import com.youlai.boot.framework.security.util.SecurityUtils; +import com.youlai.boot.support.ai.AiChatService; +import com.youlai.boot.support.ai.PromptLoader; import com.youlai.boot.system.converter.MenuConverter; import com.youlai.boot.system.mapper.MenuMapper; +import com.youlai.boot.system.model.dto.MenuCreateDTO; import com.youlai.boot.system.model.entity.Menu; +import com.youlai.boot.system.model.form.MenuAiFillForm; import com.youlai.boot.system.model.form.MenuForm; import com.youlai.boot.system.model.query.MenuQuery; +import com.youlai.boot.system.model.vo.MenuAiVO; import com.youlai.boot.system.model.vo.MenuVO; import com.youlai.boot.system.model.vo.RouteVO; import com.youlai.boot.common.constant.SystemConstants; @@ -45,6 +51,12 @@ public class MenuServiceImpl extends ServiceImpl implements Me private final RoleMenuService roleMenuService; + // 系统提示词名称,对应 resources/prompts 下的相对路径 + private static final String SYSTEM_PROMPT_PATH = "menu/system.md"; + + private final AiChatService aiChatService; + private final PromptLoader promptLoader; + /** * 菜单列表 @@ -100,12 +112,12 @@ public class MenuServiceImpl extends ServiceImpl implements Me /** * 菜单下拉数据 * - * @param onlyParent 是否只查询父级菜单 如果为true,排除按钮 + * @param types 菜单类型,为空查全部 */ @Override - public List> listMenuOptions(boolean onlyParent) { + public List> listMenuOptions(List types) { List

menuList = this.list(new LambdaQueryWrapper() - .in(onlyParent, Menu::getType, MenuTypeEnum.CATALOG.getValue(), MenuTypeEnum.MENU.getValue()) + .in(CollectionUtil.isNotEmpty(types), Menu::getType, types) .orderByAsc(Menu::getSort) ); return buildMenuOptions(SystemConstants.ROOT_NODE_ID, menuList); @@ -265,9 +277,8 @@ public class MenuServiceImpl extends ServiceImpl implements Me && ObjectUtil.equals(menu.getKeepAlive(), 1)) { meta.setKeepAlive(true); } - meta.setAlwaysShow(ObjectUtil.equals(menu.getAlwaysShow(), 1)); - - if (isEmbedded && StrUtil.isNotBlank(externalUrl)) { + // 外链地址透传前端:新标签页按站内外链打开,内嵌模式供 iframe 页取址 + if (isExternal && StrUtil.isNotBlank(externalUrl)) { meta.setExternalUrl(externalUrl); } @@ -303,12 +314,18 @@ public class MenuServiceImpl extends ServiceImpl implements Me menuForm.setComponent(null); } if (Objects.equals(menuForm.getParentId(), menuForm.getId())) { - throw new RuntimeException("父级菜单不能为当前菜单"); + throw new BusinessException("父级菜单不能为当前菜单"); } + validateMenuParent(menuForm); Menu entity = menuConverter.toEntity(menuForm); String treePath = generateMenuTreePath(menuForm.getParentId()); entity.setTreePath(treePath); + // 新增菜单未指定排序时排到同级末尾 + if (menuForm.getId() == null && entity.getSort() == null) { + entity.setSort(resolveNextSort(menuForm.getParentId())); + } + List params = menuForm.getParams(); if (CollectionUtil.isNotEmpty(params)) { entity.setParams(params.stream() @@ -330,9 +347,13 @@ public class MenuServiceImpl extends ServiceImpl implements Me boolean result = this.saveOrUpdate(entity); if (result) { - // 编辑刷新角色权限缓存 if (menuForm.getId() != null) { + // 编辑刷新角色权限缓存 roleMenuService.refreshRolePermsCache(); + } else if (Boolean.TRUE.equals(menuForm.getGenerateCrudButtons()) + && StrUtil.isNotBlank(menuForm.getButtonPermPrefix())) { + // 新增页面菜单时按需生成增删改查按钮 + saveCrudButtons(entity.getId(), menuForm.getButtonPermPrefix().trim(), treePath); } } // 修改菜单如果有子菜单,则更新子菜单的树路径 @@ -377,6 +398,77 @@ public class MenuServiceImpl extends ServiceImpl implements Me } } + /** + * 同级菜单的最大排序 + 1 + * + * @param parentId 父菜单ID + * @return 下一个排序值 + */ + private int resolveNextSort(Long parentId) { + Menu maxSortMenu = this.getOne(new LambdaQueryWrapper() + .eq(Menu::getParentId, parentId) + .orderByDesc(Menu::getSort) + .last("LIMIT 1") + ); + return maxSortMenu == null || maxSortMenu.getSort() == null ? 1 : maxSortMenu.getSort() + 1; + } + + /** + * 校验上级菜单层级:按钮只能挂在菜单下,其他类型只能挂在顶级或目录下 + * + * @param menuForm 菜单表单 + */ + private void validateMenuParent(MenuForm menuForm) { + // 父级没变时跳过校验,让历史遗留的非法层级仍可编辑其他字段 + if (menuForm.getId() != null) { + Menu current = this.getById(menuForm.getId()); + if (current != null && Objects.equals(current.getParentId(), menuForm.getParentId())) { + return; + } + } + + boolean isButton = MenuTypeEnum.BUTTON.getValue().equals(menuForm.getType()); + Long parentId = menuForm.getParentId(); + if (parentId == null || SystemConstants.ROOT_NODE_ID.equals(parentId)) { + Assert.isFalse(isButton, "按钮权限只能挂在菜单下"); + return; + } + + Menu parent = this.getById(parentId); + Assert.notNull(parent, "上级菜单不存在"); + if (isButton) { + Assert.isTrue(MenuTypeEnum.MENU.getValue().equals(parent.getType()), "按钮权限只能挂在菜单下"); + } else { + Assert.isFalse(MenuTypeEnum.MENU.getValue().equals(parent.getType()), "菜单下只能挂按钮权限"); + } + } + + /** + * 生成增删改查按钮权限 + * + * @param menuId 所属菜单ID + * @param permPrefix 权限标识前缀,不含末尾冒号,如 sys:user + * @param menuTreePath 所属菜单的树路径 + */ + private void saveCrudButtons(Long menuId, String permPrefix, String menuTreePath) { + String[] names = {"查询", "新增", "修改", "删除"}; + String[] actions = {"list", "create", "update", "delete"}; + // 树路径记录祖先链,等于所属菜单的树路径加上所属菜单ID,删除菜单时据此级联 + String buttonTreePath = menuTreePath + "," + menuId; + + for (int i = 0; i < names.length; i++) { + Menu button = new Menu(); + button.setParentId(menuId); + button.setType(MenuTypeEnum.BUTTON.getValue()); + button.setName(names[i]); + button.setPerm(permPrefix + ":" + actions[i]); + button.setSort(i + 1); + button.setVisible(1); + button.setTreePath(buttonTreePath); + this.save(button); + } + } + /** * 修改菜单显示状态 @@ -440,40 +532,30 @@ public class MenuServiceImpl extends ServiceImpl implements Me } /** - * 代码生成时添加菜单 + * 为代码生成创建菜单 * * @param parentMenuId 父菜单ID - * @param genTable 实体名称 + * @param dto 创建菜单数据载体 */ @Override - public void addMenuForCodegen(Long parentMenuId, GenTable genTable) { + public void addMenuForCodegen(Long parentMenuId, MenuCreateDTO dto) { Menu parentMenu = this.getById(parentMenuId); Assert.notNull(parentMenu, "上级菜单不存在"); - String entityName = genTable.getEntityName(); - - long count = this.count(new LambdaQueryWrapper().eq(Menu::getRouteName, entityName)); + long count = this.count(new LambdaQueryWrapper().eq(Menu::getRouteName, dto.routeName())); if (count > 0) { return; } - // 获取父级菜单子菜单最带的排序 - Menu maxSortMenu = this.getOne(new LambdaQueryWrapper().eq(Menu::getParentId, parentMenuId) - .orderByDesc(Menu::getSort) - .last("limit 1") - ); - int sort = 1; - if (maxSortMenu != null) { - sort = maxSortMenu.getSort() + 1; - } + int sort = resolveNextSort(parentMenuId); Menu menu = new Menu(); menu.setParentId(parentMenuId); - menu.setName(genTable.getBusinessName()); + menu.setName(dto.name()); - menu.setRouteName(entityName); - menu.setRoutePath(StrUtil.toSymbolCase(entityName, '-')); - menu.setComponent(genTable.getModuleName() + "/" + StrUtil.toSymbolCase(entityName, '-') + "/index"); + menu.setRouteName(dto.routeName()); + menu.setRoutePath(StrUtil.toSymbolCase(dto.routeName(), '-')); + menu.setComponent(dto.moduleName() + "/" + StrUtil.toSymbolCase(dto.routeName(), '-') + "/index"); menu.setType(MenuTypeEnum.MENU.getValue()); menu.setSort(sort); menu.setVisible(1); @@ -485,25 +567,74 @@ public class MenuServiceImpl extends ServiceImpl implements Me menu.setTreePath(treePath); this.updateById(menu); - // 生成CURD按钮权限 - String permPrefix = genTable.getModuleName() + ":" + genTable.getTableName().replace("_", "-") + ":"; - String[] actions = {"查询", "新增", "修改", "删除"}; - String[] perms = {"list", "create", "update", "delete"}; - - for (int i = 0; i < actions.length; i++) { - Menu button = new Menu(); - button.setParentId(menu.getId()); - button.setType(MenuTypeEnum.BUTTON.getValue()); - button.setName(actions[i]); - button.setPerm(permPrefix + perms[i]); - button.setSort(i + 1); - this.save(button); - - // 生成treePath - button.setTreePath(treePath + "," + button.getId()); - this.updateById(button); - } + // 生成 CRUD 按钮权限 + saveCrudButtons(menu.getId(), dto.moduleName() + ":" + dto.tableName().replace("_", "-"), treePath); } } + //--------------------------------------------------- + // AI 辅助:未开启 AI 时调用返回业务异常 + //--------------------------------------------------- + + /** + * 用 AI 推断菜单的访问路径、权限标识与配套按钮 + * + * @param form 菜单信息 + * @return 推断结果 + */ + @Override + public MenuAiVO aiFillMenu(MenuAiFillForm form) { + return aiChatService.chatEntity( + promptLoader.get(SYSTEM_PROMPT_PATH), buildAiUserPrompt(form), MenuAiVO.class); + } + + /** + * 构造用户提示词,附带同级菜单样本供模型沿用既有命名风格 + * + * @param form 菜单信息 + * @return 用户提示词 + */ + private String buildAiUserPrompt(MenuAiFillForm form) { + StringBuilder text = new StringBuilder(); + text.append("菜单名称:").append(form.getName()).append("\n"); + text.append("菜单类型:").append(menuTypeLabel(form.getType())).append("\n"); + + Long parentId = form.getParentId() == null ? SystemConstants.ROOT_NODE_ID : form.getParentId(); + Menu parent = this.getById(parentId); + text.append("上级菜单:").append(parent == null ? "顶级" : parent.getName()).append("\n"); + + List siblings = this.list(new LambdaQueryWrapper() + .eq(Menu::getParentId, parentId) + .orderByAsc(Menu::getSort) + .last("LIMIT 10") + ); + text.append("同级菜单示例:\n"); + if (CollectionUtil.isEmpty(siblings)) { + text.append("(无)\n"); + } else { + // 示例路径只展示当前这一级的路径片段 + siblings.forEach(menu -> text.append("- ") + .append(menu.getName()) + .append("(类型 ").append(menuTypeLabel(menu.getType())) + .append(",路径片段 ").append(StrUtil.blankToDefault(StrUtil.removePrefix(menu.getRoutePath(), "/"), "无")) + .append(",权限 ").append(StrUtil.blankToDefault(menu.getPerm(), "无")) + .append(")\n")); + } + return text.toString(); + } + + /** + * 菜单类型取中文名称,枚举无匹配时沿用原值 + * + * @param type 菜单类型 + * @return 中文名称 + */ + private String menuTypeLabel(String type) { + if (StrUtil.isBlank(type)) { + return "未指定"; + } + MenuTypeEnum menuType = IBaseEnum.getEnumByValue(type, MenuTypeEnum.class); + return menuType == null ? type : menuType.getLabel(); + } + } diff --git a/src/main/java/com/youlai/boot/system/service/impl/NoticeServiceImpl.java b/src/main/java/com/youlai/boot/system/service/impl/NoticeServiceImpl.java index 28bcc7cf..b001e69f 100644 --- a/src/main/java/com/youlai/boot/system/service/impl/NoticeServiceImpl.java +++ b/src/main/java/com/youlai/boot/system/service/impl/NoticeServiceImpl.java @@ -9,7 +9,7 @@ import com.baomidou.mybatisplus.extension.plugins.pagination.Page; import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl; import com.youlai.boot.common.exception.BusinessException; import com.youlai.boot.framework.security.util.SecurityUtils; -import com.youlai.boot.support.sse.model.OnlineUserDTO; +import com.youlai.boot.support.sse.OnlineUserDTO; import com.youlai.boot.system.converter.NoticeConverter; import com.youlai.boot.system.enums.NoticePublishStatusEnum; import com.youlai.boot.system.enums.NoticeTargetEnum; @@ -57,7 +57,7 @@ public class NoticeServiceImpl extends ServiceImpl impleme * 获取通知公告分页列表 * * @param queryParams 查询参数 - * @return {@link IPage< NoticePageVO >} 通知公告分页列表 + * @return {@link IPage} 通知公告分页列表 */ @Override public IPage getNoticePage(NoticeQuery queryParams) { diff --git a/src/main/java/com/youlai/boot/system/service/impl/RoleMenuServiceImpl.java b/src/main/java/com/youlai/boot/system/service/impl/RoleMenuServiceImpl.java index 33c58220..9914f3fc 100644 --- a/src/main/java/com/youlai/boot/system/service/impl/RoleMenuServiceImpl.java +++ b/src/main/java/com/youlai/boot/system/service/impl/RoleMenuServiceImpl.java @@ -12,6 +12,7 @@ import lombok.extern.slf4j.Slf4j; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.stereotype.Service; +import java.time.Duration; import java.util.*; import java.util.stream.Collectors; @@ -26,6 +27,9 @@ import java.util.stream.Collectors; @Slf4j public class RoleMenuServiceImpl extends ServiceImpl implements RoleMenuService { + // 权限缓存 TTL(秒)。 + private static final Duration ROLE_PERMS_TTL = Duration.ofSeconds(600); + private final RedisTemplate redisTemplate; /** @@ -48,6 +52,7 @@ public class RoleMenuServiceImpl extends ServiceImpl i redisTemplate.opsForHash().put(cacheKey, roleCode, perms); } }); + refreshCacheTtl(cacheKey); } log.info("权限缓存刷新完成"); @@ -71,6 +76,7 @@ public class RoleMenuServiceImpl extends ServiceImpl i Set perms = rolePerms.getPerms(); if (CollectionUtil.isNotEmpty(perms)) { redisTemplate.opsForHash().put(cacheKey, roleCode, perms); + refreshCacheTtl(cacheKey); } } } @@ -97,6 +103,7 @@ public class RoleMenuServiceImpl extends ServiceImpl i Set perms = rolePerms.getPerms(); if (CollectionUtil.isNotEmpty(perms)) { redisTemplate.opsForHash().put(cacheKey, newRoleCode, perms); + refreshCacheTtl(cacheKey); } } } @@ -106,12 +113,6 @@ public class RoleMenuServiceImpl extends ServiceImpl i /** * 获取角色权限集合(带缓存) - *

- * 采用 Read-Through 缓存策略: - *

    - *
  1. 优先从 Redis Hash 缓存读取
  2. - *
  3. 缓存未命中时回源 DB 并写入缓存
  4. - *
* * @param roleCodes 角色编码集合 * @return 权限集合 @@ -163,11 +164,21 @@ public class RoleMenuServiceImpl extends ServiceImpl i redisTemplate.opsForHash().put(cacheKey, roleCode, dbPerms); perms.addAll(dbPerms); } + refreshCacheTtl(cacheKey); } return perms; } + /** + * 刷新权限缓存TTL(写后滑动续期:有写入的周期内缓存常驻,静置超过 TTL 整 Key 过期触发回源重建) + * + * @param cacheKey 缓存Key + */ + private void refreshCacheTtl(String cacheKey) { + redisTemplate.expire(cacheKey, ROLE_PERMS_TTL); + } + /** * 获取角色拥有的菜单ID集合 * diff --git a/src/main/java/com/youlai/boot/system/service/impl/RoleServiceImpl.java b/src/main/java/com/youlai/boot/system/service/impl/RoleServiceImpl.java index 0c55e54f..846ad734 100644 --- a/src/main/java/com/youlai/boot/system/service/impl/RoleServiceImpl.java +++ b/src/main/java/com/youlai/boot/system/service/impl/RoleServiceImpl.java @@ -55,7 +55,7 @@ public class RoleServiceImpl extends ServiceImpl implements Ro * 角色分页列表 * * @param queryParams 角色查询参数 - * @return {@link Page< RolePageVO >} – 角色分页列表 + * @return {@link Page} – 角色分页列表 */ @Override public Page getRolePage(RoleQuery queryParams) { @@ -99,6 +99,19 @@ public class RoleServiceImpl extends ServiceImpl implements Ro return roleConverter.toOptions(roleList); } + @Override + public List> listRoleCodeOptions() { + // value 为角色编码(引擎候选组按编码匹配),与按 ID 取值的 listRoleOptions 区分 + List roleList = this.list(new LambdaQueryWrapper() + .ne(!SecurityUtils.isRoot(), Role::getCode, SystemConstants.ROOT_ROLE_CODE) + .select(Role::getCode, Role::getName) + .orderByAsc(Role::getSort) + ); + return roleList.stream() + .map(role -> new Option<>(role.getCode(), role.getName())) + .toList(); + } + /** * 保存角色 * @@ -216,7 +229,7 @@ public class RoleServiceImpl extends ServiceImpl implements Ro // 刷新角色的权限缓存 roleMenuService.refreshRolePermsCache(role.getCode()); - // When role is disabled, invalidate sessions of all users with this role + // 角色禁用时使该角色下所有用户的会话失效 if (status == 0) { List userIds = userRoleService.listUserIdsByRoleId(roleId); for (Long userId : userIds) { @@ -278,7 +291,7 @@ public class RoleServiceImpl extends ServiceImpl implements Ro public void assignMenusToRole(Long roleId, List menuIds) { Role role = this.getById(roleId); if (role == null) { - throw new RuntimeException("角色不存在"); + throw new BusinessException("角色不存在"); } // 删除角色菜单 roleMenuService.remove( @@ -323,8 +336,6 @@ public class RoleServiceImpl extends ServiceImpl implements Ro /** * 获取用户所有角色的数据权限列表 - *

- * 用于实现多角色数据权限合并(并集策略) * * @param roleCodes 角色编码集合 * @return 角色数据权限列表 diff --git a/src/main/java/com/youlai/boot/system/service/impl/UserServiceImpl.java b/src/main/java/com/youlai/boot/system/service/impl/UserServiceImpl.java index 8444c0c2..a799774e 100644 --- a/src/main/java/com/youlai/boot/system/service/impl/UserServiceImpl.java +++ b/src/main/java/com/youlai/boot/system/service/impl/UserServiceImpl.java @@ -12,17 +12,22 @@ import com.youlai.boot.common.constant.RedisConstants; import com.youlai.boot.common.constant.SystemConstants; import com.youlai.boot.common.exception.BusinessException; import com.youlai.boot.common.model.Option; -import com.youlai.boot.support.sms.SmsTypeEnum; -import com.youlai.boot.support.mail.EmailService; -import com.youlai.boot.support.sms.SmsService; import com.youlai.boot.framework.security.model.RoleDataScope; import com.youlai.boot.framework.security.model.SecurityUser; import com.youlai.boot.framework.security.token.TokenManager; import com.youlai.boot.framework.security.util.SecurityUtils; +import com.youlai.boot.support.mail.service.EmailService; +import com.youlai.boot.support.sms.SmsTypeEnum; +import com.youlai.boot.support.sms.service.SmsService; import com.youlai.boot.system.converter.UserConverter; import com.youlai.boot.system.enums.DictCodeEnum; import com.youlai.boot.system.mapper.UserMapper; -import com.youlai.boot.system.model.form.*; +import com.youlai.boot.system.model.form.EmailUpdateForm; +import com.youlai.boot.system.model.form.MobileUpdateForm; +import com.youlai.boot.system.model.form.PasswordUpdateForm; +import com.youlai.boot.system.model.form.PasswordVerifyForm; +import com.youlai.boot.system.model.form.UserForm; +import com.youlai.boot.system.model.form.UserProfileForm; import com.youlai.boot.system.model.vo.CurrentUserVO; import com.youlai.boot.system.model.vo.UserExportVO; import com.youlai.boot.system.model.entity.Dept; @@ -40,15 +45,21 @@ import org.springframework.security.crypto.password.PasswordEncoder; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; -import java.util.*; +import java.util.Arrays; +import java.util.HashMap; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Set; import java.util.concurrent.TimeUnit; import java.util.stream.Collectors; /** - * 用户业务实现类 + * 用户业务实现类. * * @author Ray.Hao - * @since 2022/1/14 + * @since 0.0.1 */ @Service @RequiredArgsConstructor @@ -78,10 +89,10 @@ public class UserServiceImpl extends ServiceImpl implements /** - * 获取用户分页列表 + * 获取用户分页列表. * - * @param queryParams 查询参数 - * @return {@link IPage} 用户分页列表 + * @param queryParams 分页查询条件(含关键字、状态、部门过滤) + * @return 用户分页数据(含角色、部门名称) */ @Override public IPage getUserPage(UserQuery queryParams) { @@ -91,18 +102,15 @@ public class UserServiceImpl extends ServiceImpl implements int pageSize = queryParams.getPageSize(); Page page = new Page<>(pageNum, pageSize); - boolean isRoot = SecurityUtils.isRoot(); - queryParams.setIsRoot(isRoot); - // 查询数据 return this.baseMapper.getUserPage(page, queryParams); } /** - * 获取用户表单数据 + * 获取用户表单回显数据. * - * @param userId 用户ID - * @return {@link UserForm} 用户表单数据 + * @param userId 用户 ID + * @return 用户表单(含已分配角色 ID 列表),用于编辑页回显 */ @Override public UserForm getUserFormData(Long userId) { @@ -110,10 +118,11 @@ public class UserServiceImpl extends ServiceImpl implements } /** - * 新增用户 + * 新增用户. * - * @param userForm 用户表单对象 - * @return true|false + * @param userForm 用户表单(username 必填且唯一,roleIds 为角色 ID 列表) + * @return 新增成功返回 true + * @throws BusinessException 如果用户名已存在 */ @Override @Transactional(rollbackFor = Exception.class) @@ -144,11 +153,12 @@ public class UserServiceImpl extends ServiceImpl implements } /** - * 更新用户 + * 更新用户. * - * @param userId 用户ID - * @param userForm 用户表单对象 - * @return true|false + * @param userId 用户 ID + * @param userForm 用户表单(username 必填且唯一,roleIds 为角色 ID 列表) + * @return 更新成功返回 true + * @throws BusinessException 如果用户不存在或用户名已被占用 */ @Override @Transactional(rollbackFor = Exception.class) @@ -181,10 +191,11 @@ public class UserServiceImpl extends ServiceImpl implements } /** - * 删除用户 + * 批量删除用户. * - * @param idsStr 用户ID,多个以英文逗号(,)分割 - * @return true|false + * @param idsStr 用户 ID,多个以英文逗号分割 + * @return 删除成功返回 true + * @throws BusinessException 如果 idsStr 为空 */ @Override @Transactional(rollbackFor = Exception.class) @@ -200,10 +211,10 @@ public class UserServiceImpl extends ServiceImpl implements } /** - * 根据用户名获取认证凭证信息 + * 根据用户名获取认证凭证信息. * - * @param username 用户名 - * @return 用户认证凭证信息 {@link SecurityUser} + * @param username 用户名(唯一) + * @return 认证凭证,用户不存在时返回 null */ @Override public SecurityUser getAuthInfoByUsername(String username) { @@ -217,7 +228,10 @@ public class UserServiceImpl extends ServiceImpl implements } /** - * 根据手机号获取用户认证信息 + * 根据手机号获取认证凭证信息. + * + * @param mobile 手机号 + * @return 认证凭证,手机号为空或用户不存在时返回 null */ @Override public SecurityUser getAuthInfoByMobile(String mobile) { @@ -234,17 +248,14 @@ public class UserServiceImpl extends ServiceImpl implements } /** - * 获取导出用户列表 + * 获取导出用户列表. * - * @param queryParams 查询参数 - * @return {@link List} 导出用户列表 + * @param queryParams 查询条件(含关键字、状态、部门过滤) + * @return 导出用户列表(gender 字段已翻译为中文) */ @Override public List listExportUsers(UserQuery queryParams) { - boolean isRoot = SecurityUtils.isRoot(); - queryParams.setIsRoot(isRoot); - List exportUsers = this.baseMapper.listExportUsers(queryParams); if (CollectionUtil.isNotEmpty(exportUsers)) { //获取性别的字典项 @@ -273,9 +284,9 @@ public class UserServiceImpl extends ServiceImpl implements } /** - * 获取登录用户信息 + * 获取当前登录用户信息. * - * @return {@link CurrentUserVO} 用户信息 + * @return 当前用户信息(含角色、权限) */ @Override public CurrentUserVO getCurrentUserInfo() { @@ -338,10 +349,10 @@ public class UserServiceImpl extends ServiceImpl implements } /** - * 获取个人中心用户信息 + * 获取个人中心用户信息. * - * @param userId 用户ID - * @return {@link UserProfileVO} 个人中心用户信息 + * @param userId 用户 ID + * @return 个人中心信息(含角色、部门名称) */ @Override public UserProfileVO getUserProfile(Long userId) { @@ -349,10 +360,11 @@ public class UserServiceImpl extends ServiceImpl implements } /** - * 修改个人中心用户信息 + * 修改个人中心用户信息. * - * @param formData 表单数据 - * @return true|false + * @param formData 个人中心表单(nickname/avatar/gender 至少一个非空) + * @return 修改成功返回 true + * @throws BusinessException 如果所有字段均为空 */ @Override public boolean updateUserProfile(UserProfileForm formData) { @@ -371,11 +383,12 @@ public class UserServiceImpl extends ServiceImpl implements } /** - * 修改指定用户密码 + * 修改当前用户密码. * - * @param userId 用户ID - * @param data 密码修改表单数据 - * @return true|false + * @param userId 用户 ID + * @param data 密码表单(含原密码、新密码、确认密码) + * @return 修改成功返回 true + * @throws BusinessException 如果用户不存在、原密码错误、新旧密码相同或确认密码不一致 */ @Override public boolean changeUserPassword(Long userId, PasswordUpdateForm data) { @@ -415,11 +428,11 @@ public class UserServiceImpl extends ServiceImpl implements } /** - * 重置指定用户密码 + * 重置用户密码. * - * @param userId 用户ID - * @param password 密码重置表单数据 - * @return true|false + * @param userId 用户 ID + * @param password 新密码(明文,内部加密存储) + * @return 重置成功返回 true */ @Override public boolean resetUserPassword(Long userId, String password) { @@ -435,10 +448,11 @@ public class UserServiceImpl extends ServiceImpl implements } /** - * 发送短信验证码(绑定或更换手机号) + * 发送短信验证码(绑定或更换手机号). * * @param mobile 手机号 - * @return true|false + * @return 发送成功返回 true,失败返回 false 并记录日志 + * @throws BusinessException 如果手机号已被其他账号绑定 */ @Override public boolean sendMobileCode(String mobile) { @@ -452,8 +466,7 @@ public class UserServiceImpl extends ServiceImpl implements throw new BusinessException("手机号已被其他账号绑定"); } - // String code = String.valueOf((int) ((Math.random() * 9 + 1) * 1000)); - // TODO 为了方便测试,验证码固定为 123456,实际开发中在配置了厂商短信服务后,可以使用上面的随机验证码 + // TODO 固定验证码 123456 便于测试,接入短信厂商后改为随机生成 String code = "123456"; Map templateParams = new HashMap<>(); @@ -474,10 +487,11 @@ public class UserServiceImpl extends ServiceImpl implements } /** - * 绑定或更换手机号 + * 绑定或更换手机号. * - * @param form 表单数据 - * @return true|false + * @param form 手机号绑定表单(含密码、手机号、验证码) + * @return 绑定成功返回 true + * @throws BusinessException 如果用户不存在、密码错误、验证码过期/错误或手机号已被绑定 */ @Override public boolean bindOrChangeMobile(MobileUpdateForm form) { @@ -527,9 +541,10 @@ public class UserServiceImpl extends ServiceImpl implements } /** - * 发送邮箱验证码(绑定或更换邮箱) + * 发送邮箱验证码(绑定或更换邮箱). * - * @param email 邮箱 + * @param email 邮箱地址 + * @throws BusinessException 如果邮箱已被其他账号绑定 */ @Override public void sendEmailCode(String email) { @@ -543,8 +558,7 @@ public class UserServiceImpl extends ServiceImpl implements throw new BusinessException("邮箱已被其他账号绑定"); } - // String code = String.valueOf((int) ((Math.random() * 9 + 1) * 1000)); - // TODO 为了方便测试,验证码固定为 123456,实际开发中在配置了邮箱服务后,可以使用上面的随机验证码 + // TODO 固定验证码 123456 便于测试,接入邮箱服务后改为随机生成 String code = "123456"; emailService.send(email, "邮箱验证码", "您的验证码为:" + code + ",请在5分钟内使用"); @@ -554,10 +568,11 @@ public class UserServiceImpl extends ServiceImpl implements } /** - * 修改当前用户邮箱 + * 绑定或更换邮箱. * - * @param form 表单数据 - * @return true|false + * @param form 邮箱绑定表单(含密码、邮箱、验证码) + * @return 绑定成功返回 true + * @throws BusinessException 如果用户不存在、密码错误、验证码过期/错误或邮箱已被绑定 */ @Override public boolean bindOrChangeEmail(EmailUpdateForm form) { @@ -608,10 +623,11 @@ public class UserServiceImpl extends ServiceImpl implements } /** - * 解绑手机号 + * 解绑手机号. * - * @param form 表单数据 - * @return true|false + * @param form 密码验证表单(含密码) + * @return 解绑成功返回 true + * @throws BusinessException 如果用户不存在、未绑定手机号或密码错误 */ @Override public boolean unbindMobile(PasswordVerifyForm form) { @@ -638,10 +654,11 @@ public class UserServiceImpl extends ServiceImpl implements } /** - * 解绑邮箱 + * 解绑邮箱. * - * @param form 表单数据 - * @return true|false + * @param form 密码验证表单(含密码) + * @return 解绑成功返回 true + * @throws BusinessException 如果用户不存在、未绑定邮箱或密码错误 */ @Override public boolean unbindEmail(PasswordVerifyForm form) { @@ -667,6 +684,13 @@ public class UserServiceImpl extends ServiceImpl implements ); } + /** + * 修改用户状态. + * + * @param userId 用户 ID + * @param status 状态(1:启用 0:禁用) + * @return 修改成功返回 true + */ @Override public boolean updateUserStatus(Long userId, Integer status) { return this.update(new LambdaUpdateWrapper() @@ -676,9 +700,9 @@ public class UserServiceImpl extends ServiceImpl implements } /** - * 获取用户选项列表 + * 获取用户下拉选项列表. * - * @return {@link List>} 用户选项列表 + * @return 启用状态的用户选项(value 为用户 ID,label 为昵称) */ @Override public List> listUserOptions() { diff --git a/src/main/resources/META-INF/additional-spring-configuration-metadata.json b/src/main/resources/META-INF/additional-spring-configuration-metadata.json index 3e7ba880..5b09a787 100644 --- a/src/main/resources/META-INF/additional-spring-configuration-metadata.json +++ b/src/main/resources/META-INF/additional-spring-configuration-metadata.json @@ -1,67 +1,67 @@ { "properties": [ { - "name": "file-storage.type", + "name": "storage.type", "type": "java.lang.String", - "description": "文件存储类型:minio | aliyun | local" + "description": "文件存储类型:s3 | aliyun | local" }, { - "name": "file-storage.upload.max-file-size", + "name": "storage.upload.max-file-size", "type": "java.lang.String", "description": "单文件大小上限(如 50MB),同时作为 spring.servlet.multipart 的上限" }, { - "name": "file-storage.upload.allowed-extensions", + "name": "storage.upload.allowed-extensions", "type": "java.util.List", "description": "允许的文件扩展名白名单(置空表示不限制)" }, { - "name": "file-storage.minio.endpoint", + "name": "storage.s3.endpoint", "type": "java.lang.String", - "description": "MinIO 服务 Endpoint" + "description": "S3 服务 Endpoint(S3 协议兼容存储,默认部署 RustFS)" }, { - "name": "file-storage.minio.access-key", + "name": "storage.s3.access-key", "type": "java.lang.String", - "description": "MinIO 访问凭据" + "description": "S3 访问凭据" }, { - "name": "file-storage.minio.secret-key", + "name": "storage.s3.secret-key", "type": "java.lang.String", - "description": "MinIO 凭据密钥" + "description": "S3 凭据密钥" }, { - "name": "file-storage.minio.bucket", + "name": "storage.s3.bucket", "type": "java.lang.String", - "description": "MinIO 存储桶名称" + "description": "S3 存储桶名称" }, { - "name": "file-storage.minio.domain", + "name": "storage.s3.domain", "type": "java.lang.String", - "description": "MinIO 自定义域名(文件 URL 域名)" + "description": "S3 自定义域名(文件 URL 域名)" }, { - "name": "file-storage.aliyun.endpoint", + "name": "storage.aliyun.endpoint", "type": "java.lang.String", "description": "阿里云 OSS 服务 Endpoint" }, { - "name": "file-storage.aliyun.access-key-id", + "name": "storage.aliyun.access-key-id", "type": "java.lang.String", "description": "阿里云 OSS 访问凭据 ID" }, { - "name": "file-storage.aliyun.access-key-secret", + "name": "storage.aliyun.access-key-secret", "type": "java.lang.String", "description": "阿里云 OSS 凭据密钥" }, { - "name": "file-storage.aliyun.bucket", + "name": "storage.aliyun.bucket", "type": "java.lang.String", "description": "阿里云 OSS 存储桶名称" }, { - "name": "file-storage.local.path", + "name": "storage.local.path", "type": "java.lang.String", "description": "本地存储根目录(相对路径基于工作目录)" }, diff --git a/src/main/resources/application-dev.yml b/src/main/resources/application-dev.yml index 4c0d22b7..bc36d07e 100644 --- a/src/main/resources/application-dev.yml +++ b/src/main/resources/application-dev.yml @@ -88,7 +88,37 @@ spring: username: fht password: fanhuitong authentication-database: admin - + # AI 对话(本环境无默认密钥,默认关闭;演示环境配置见 application-youlai.yml) + ai: + # 装配开关:none 关闭,openai 启用 + model: + chat: none + embedding: none + image: none + moderation: none + audio: + speech: none + transcription: none + # 启用后在此填写模型凭据与名称 + openai: + # 厂商接口地址(OpenAI 兼容根地址) + base-url: https://dashscope.aliyuncs.com/compatible-mode/v1 + # 厂商 API 密钥(本文件入版本库,用环境变量 AI_API_KEY 提供) + api-key: ${AI_API_KEY:} + chat: + options: + # 对话模型标识 + model: qwen3.7-flash + # 采样温度,取值 0~1,越小输出越稳定 + temperature: 0.3 + # 百炼私有参数:推理模型的思考内容耗时可占整次调用的大头,false 关闭 + extra-body: + enable_thinking: false + servlet: + multipart: + # 单文件大小上限,单一来源绑定 storage.upload.max-file-size + max-file-size: ${storage.upload.max-file-size:50MB} + max-request-size: ${storage.upload.max-file-size:50MB} mybatis-plus: mapper-locations: classpath*:/mapper/**/*.xml global-config: @@ -118,8 +148,8 @@ rate-limit: # 安全配置 security: - session: - type: jwt # 会话方式 [jwt|redis-token] + token: + type: jwt # 令牌策略 [jwt|redis-token] access-token-time-to-live: 7200 # 访问令牌 有效期(单位:秒),默认 2 小时,-1 表示永不过期 refresh-token-time-to-live: 604800 # 刷新令牌有效期(单位:秒),默认 7 天,-1 表示永不过期 # 家属客户端(client)独立令牌有效期,与管理后台区分;未配置时回退到上方全局值 @@ -129,21 +159,20 @@ security: secret-key: SecretKey012345678901234567890123456789012345678901234567890123456789 # JWT密钥(HS256算法至少32字符) redis-token: allow-multi-login: true # 是否允许多设备登录 - # 安全白名单路径,仅跳过 AuthorizationFilter 过滤器,还是会走 Spring Security 的其他过滤器(CSRF、CORS等) - ignore-urls: - - /api/v1/auth/login/** # 登录接口(账号密码登录) + # 匿名放行路径,仅跳过认证与授权判断,仍走过滤器链(保留安全响应头) + permit-all-urls: + - /api/v1/auth/login # 登录接口(账号密码登录) - /api/v1/auth/captcha # 验证码获取接口 - /api/v1/auth/sms/** # 短信验证码接口(发送验证码、短信登录) - /api/v1/auth/refresh-token # 刷新令牌接口 - /api/v1/auth/wxma/** # 微信小程序认证接口(静默登录/手机号快捷登录/绑定手机号) - - /api/v1/logs/** # 日志接口(访问日志列表) - /api/v1/auth/qr-code/** # 扫码登录接口(生成票据/查询状态/换取令牌) - /api/v1/sn/** # 移动设备专用接口(通过设备签名验证) - /api/v1/open/** # C端客户端(open)接口(注册/登录/短信/刷新令牌等,落地 app_user) - /static/** # 静态资源(应用图标等,img 标签无法携带 token;文件名为内容MD5,不可枚举) - # 非安全端点路径,完全绕过 Spring Security 的过滤器 - unsecured-urls: - - ${springdoc.swagger-ui.path} + - /api/v1/forms/public/** # 公开表单接口(匿名渲染/提交,Service 校验 is_public 总闸 + IP 限流) + - /api/v1/health # 健康检查接口(供探针与限流测试) + - ${springdoc.swagger-ui.path} # Swagger UI 路径 - /doc.html - /swagger-ui/** - /v3/api-docs/** @@ -152,9 +181,9 @@ security: - /error # 文件存储 -file-storage: - # 存储类型:minio | aliyun | local - type: minio +storage: + # 存储类型:s3 | aliyun | local + type: s3 # 上传限制 upload: # 单文件大小上限(同时作为 spring.servlet.multipart 的上限,单一来源) @@ -165,8 +194,8 @@ file-storage: - jpeg - png - gif - # MinIO 对象存储 - minio: + # S3 对象存储(S3 协议兼容服务,默认部署 RustFS) + s3: endpoint: http://111.229.83.153:9000 access-key: bybaddp7zyARpgNbEGKf secret-key: p9rBdQZPBIJcMH23iyFkZkXmmawbmwPlk3JLlaaj @@ -227,11 +256,15 @@ springdoc: - group: "系统管理" # 分组名称 paths-to-match: "/**" # 匹配的请求路径 packages-to-scan: # 扫描的 Controller 包,限制只生成指定包的接口文档 - - com.youlai.boot.auth.controller + - com.youlai.boot.auth.password.controller + - com.youlai.boot.auth.sms.controller + - com.youlai.boot.auth.qrcode.controller + - com.youlai.boot.auth.wxma.controller + - com.youlai.boot.auth.session.controller - com.youlai.boot.system.controller - - com.youlai.boot.file.controller - com.youlai.boot.codegen.controller - - com.youlai.boot.message.controller + - com.youlai.boot.module.form.controller + - com.youlai.boot.module.workflow.controller default-flat-param-object: true # knife4j 配置 @@ -242,23 +275,6 @@ knife4j: setting: language: zh_cn -# xxl-job 定时任务配置 -xxl: - job: - # 定时任务开关 - enabled: false - admin: - # 多个地址使用,分割 - addresses: http://127.0.0.1:8686/xxl-job-admin - accessToken: default_token - executor: - appname: xxl-job-executor-${spring.application.name} - address: - ip: - port: 9999 - logpath: /data/applogs/xxl-job/jobhandler - logretentiondays: 30 - # 验证码配置 captcha: # 验证码类型 circle-圆圈干扰验证码|gif-Gif验证码|line-干扰线验证码|shear-扭曲干扰验证码 @@ -288,6 +304,23 @@ captcha: # 验证码有效期(秒) expire-seconds: 120 +# xxl-job 定时任务配置 +xxl: + job: + # 定时任务开关 + enabled: false + admin: + # 调度中心地址,多个地址用逗号分割;3.4.1 起调度中心 context-path 为 /,地址不带 /xxl-job-admin 后缀 + addresses: http://127.0.0.1:8080 + accessToken: default_token + executor: + appname: xxl-job-executor-${spring.application.name} + address: + ip: + port: 9999 + logpath: /data/applogs/xxl-job/jobhandler + logretentiondays: 30 + # 微信小程序配置 wx: miniapp: @@ -316,3 +349,23 @@ mqtt: status-topic: ttstd/device/status # 设备在线判定超时时间(秒),设备每上报一次心跳刷新该 TTL,超时未上报即判定离线 online-timeout: 90 + +# 工作流(可选扩展,开启只需将 enabled 改为 true,引擎开关自动跟随) +workflow: + enabled: false + demo: + # 演示流程自动部署开关 + enabled: true + +# 工作流引擎 +flowable: + # 流程引擎跟随业务开关 workflow.enabled + process: + enabled: ${workflow.enabled:false} + # 用户与角色走系统自有体系(sys_user/sys_role),不启用 Flowable IDM 与事件注册表 + idm: + enabled: false + eventregistry: + enabled: false + # 引擎表初始化策略,true 启动时检查并自动建/更新 ACT_* 表;可选 true/false/create/create-drop + database-schema-update: true diff --git a/src/main/resources/application-prod.yml b/src/main/resources/application-prod.yml index 728a5e51..96cdbbbe 100644 --- a/src/main/resources/application-prod.yml +++ b/src/main/resources/application-prod.yml @@ -83,6 +83,37 @@ spring: username: fht password: fanhuitong authentication-database: admin + # AI 对话(本环境无默认密钥,默认关闭;演示环境配置见 application-youlai.yml) + ai: + # 装配开关:none 关闭,openai 启用 + model: + chat: none + embedding: none + image: none + moderation: none + audio: + speech: none + transcription: none + # 启用后在此填写模型凭据与名称 + openai: + # 厂商接口地址(OpenAI 兼容根地址) + base-url: https://dashscope.aliyuncs.com/compatible-mode/v1 + # 厂商 API 密钥(本文件入版本库,用环境变量 AI_API_KEY 提供) + api-key: ${AI_API_KEY:} + chat: + options: + # 对话模型标识 + model: qwen3.7-flash + # 采样温度,取值 0~1,越小输出越稳定 + temperature: 0.3 + # 百炼私有参数:推理模型的思考内容耗时可占整次调用的大头,false 关闭 + extra-body: + enable_thinking: false + servlet: + multipart: + # 单文件大小上限,单一来源绑定 storage.upload.max-file-size + max-file-size: ${storage.upload.max-file-size:50MB} + max-request-size: ${storage.upload.max-file-size:50MB} mybatis-plus: mapper-locations: classpath*:/mapper/**/*.xml global-config: @@ -112,8 +143,8 @@ rate-limit: # 安全配置 security: - session: - type: jwt # 会话方式 [jwt|redis-token] + token: + type: jwt # 令牌策略 [jwt|redis-token] access-token-time-to-live: 7200 # 访问令牌 有效期(单位:秒),默认 2 小时,-1 表示永不过期 refresh-token-time-to-live: 604800 # 刷新令牌有效期(单位:秒),默认 7 天,-1 表示永不过期 # 家属客户端(client)独立令牌有效期,与管理后台区分;未配置时回退到上方全局值 @@ -123,21 +154,20 @@ security: secret-key: SecretKey012345678901234567890123456789012345678901234567890123456789 # JWT密钥(HS256算法至少32字符) redis-token: allow-multi-login: true # 是否允许多设备登录 - # 安全白名单路径,仅跳过 AuthorizationFilter 过滤器,还是会走 Spring Security 的其他过滤器(CSRF、CORS等) - ignore-urls: - - /api/v1/auth/login/** # 登录接口(账号密码登录) + # 匿名放行路径,仅跳过认证与授权判断,仍走过滤器链(保留安全响应头) + permit-all-urls: + - /api/v1/auth/login # 登录接口(账号密码登录) - /api/v1/auth/captcha # 验证码获取接口 - /api/v1/auth/sms/** # 短信验证码接口(发送验证码、短信登录) - /api/v1/auth/refresh-token # 刷新令牌接口 - /api/v1/auth/wxma/** # 微信小程序认证接口(静默登录/手机号快捷登录/绑定手机号) - - /api/v1/logs/** # 日志接口(访问日志列表) - /api/v1/auth/qr-code/** # 扫码登录接口(生成票据/查询状态/换取令牌) - /api/v1/sn/** # 移动设备专用接口(通过设备签名验证) - /api/v1/open/** # C端客户端(open)接口(注册/登录/短信/刷新令牌等,落地 app_user) - /static/** # 静态资源(应用图标等,img 标签无法携带 token;文件名为内容MD5,不可枚举) - # 非安全端点路径,完全绕过 Spring Security 的过滤器 - unsecured-urls: - - ${springdoc.swagger-ui.path} + - /api/v1/forms/public/** # 公开表单接口(匿名渲染/提交,Service 校验 is_public 总闸 + IP 限流) + - /api/v1/health # 健康检查接口(供探针与限流测试) + - ${springdoc.swagger-ui.path} # Swagger UI 路径 - /doc.html - /swagger-ui/** - /v3/api-docs/** @@ -146,9 +176,9 @@ security: - /error # 文件存储 -file-storage: - # 存储类型:minio | aliyun | local - type: minio +storage: + # 存储类型:s3 | aliyun | local + type: s3 # 上传限制 upload: # 单文件大小上限(同时作为 spring.servlet.multipart 的上限,单一来源) @@ -159,11 +189,11 @@ file-storage: - jpeg - png - gif - # MinIO 对象存储 - minio: + # S3 对象存储(S3 协议兼容服务,默认部署 RustFS) + s3: endpoint: http://localhost:9000 - access-key: minioadmin - secret-key: minioadmin + access-key: rustfs-admin + secret-key: rustfs-admin bucket: public # 自定义域名:配置后文件 URL 走域名,留空则用 endpoint(IP)格式 domain: @@ -177,6 +207,7 @@ file-storage: local: # 存储根目录(相对路径基于工作目录;生产建议挂载独立卷) path: ./uploads/ + # 短信配置 sms: # 阿里云短信 @@ -208,11 +239,15 @@ springdoc: - group: "系统管理" # 分组名称 paths-to-match: "/**" # 匹配的请求路径 packages-to-scan: # 扫描的 Controller 包,限制只生成指定包的接口文档 - - com.youlai.boot.auth.controller + - com.youlai.boot.auth.password.controller + - com.youlai.boot.auth.sms.controller + - com.youlai.boot.auth.qrcode.controller + - com.youlai.boot.auth.wxma.controller + - com.youlai.boot.auth.session.controller - com.youlai.boot.system.controller - - com.youlai.boot.file.controller - com.youlai.boot.codegen.controller - - com.youlai.boot.message.controller + - com.youlai.boot.module.form.controller + - com.youlai.boot.module.workflow.controller default-flat-param-object: true # 将对象参数扁平化显示在文档中 # knife4j 配置 @@ -222,23 +257,6 @@ knife4j: setting: language: zh_cn -# xxl-job 定时任务配置 -xxl: - job: - # 定时任务开关 - enabled: false - admin: - # 多个地址使用,分割 - addresses: http://127.0.0.1:8686/xxl-job-admin - accessToken: default_token - executor: - appname: xxl-job-executor-${spring.application.name} - address: - ip: - port: 9999 - logpath: /data/applogs/xxl-job/jobhandler - logretentiondays: 30 - # 验证码配置 captcha: # 验证码类型 circle-圆圈干扰验证码|gif-Gif验证码|line-干扰线验证码|shear-扭曲干扰验证码 @@ -268,7 +286,24 @@ captcha: # 验证码有效期(秒) expire-seconds: 120 -# 微信小程配置 +# xxl-job 定时任务配置 +xxl: + job: + # 定时任务开关 + enabled: false + admin: + # 调度中心地址,多个地址用逗号分割;3.4.1 起调度中心 context-path 为 /,地址不带 /xxl-job-admin 后缀 + addresses: http://127.0.0.1:8080 + accessToken: default_token + executor: + appname: xxl-job-executor-${spring.application.name} + address: + ip: + port: 9999 + logpath: /data/applogs/xxl-job/jobhandler + logretentiondays: 30 + +# 微信小程序配置 wx: miniapp: app-id: Your_AppId @@ -296,3 +331,23 @@ mqtt: status-topic: ttstd/device/status # 设备在线判定超时时间(秒),设备每上报一次心跳刷新该 TTL,超时未上报即判定离线 online-timeout: 90 + +# 工作流(可选扩展,开启只需将 enabled 改为 true,引擎开关自动跟随) +workflow: + enabled: false + demo: + # 演示流程自动部署开关 + enabled: false + +# 工作流引擎 +flowable: + # 流程引擎跟随业务开关 workflow.enabled + process: + enabled: ${workflow.enabled:false} + # 用户与角色走系统自有体系(sys_user/sys_role),不启用 Flowable IDM 与事件注册表 + idm: + enabled: false + eventregistry: + enabled: false + # 引擎表初始化策略,true 启动时检查并自动建/更新 ACT_* 表;可选 true/false/create/create-drop + database-schema-update: false diff --git a/src/main/resources/application.yml b/src/main/resources/application.yml index 675fee96..61cf8909 100644 --- a/src/main/resources/application.yml +++ b/src/main/resources/application.yml @@ -6,8 +6,3 @@ spring: config: # 引入代码生成模块的配置(数据源、表前缀等),由 codegen.yml 提供 import: classpath:codegen.yml - servlet: - multipart: - # 单文件大小上限,取自 file-storage.upload.max-file-size(单一来源) - max-file-size: ${file-storage.upload.max-file-size:50MB} - max-request-size: ${file-storage.upload.max-file-size:50MB} diff --git a/src/main/resources/banner.txt b/src/main/resources/banner.txt deleted file mode 100644 index f4ce6a15..00000000 --- a/src/main/resources/banner.txt +++ /dev/null @@ -1,13 +0,0 @@ -${AnsiColor.BRIGHT_BLUE} - __ __ _ _ - \ \ / / | | (_) - \ \_/ /__ _ _ | | __ _ _ - \ / _ \| | | | | | / _` | | - | | (_) | |_| | | |___| (_| | | - |_|\___/ \__,_| |______\__,_|_| - -${AnsiColor.BRIGHT_GREEN} -Spring Boot Version: ${spring-boot.version}${spring-boot.formatted-version} -有来官网: https://www.youlai.tech/ -版权所属: 有来开源组织 -${AnsiColor.BRIGHT_BLUE} \ No newline at end of file diff --git a/src/main/resources/codegen.yml b/src/main/resources/codegen.yml index 9ce6490e..ff07ff42 100644 --- a/src/main/resources/codegen.yml +++ b/src/main/resources/codegen.yml @@ -17,45 +17,45 @@ codegen: ## 模板配置 templateConfigs: API: - templatePath: codegen/frontend/ts/api.ts.vm + templatePath: frontend/ts/api.ts.vm subpackageName: api extension: .ts API_TYPES: - templatePath: codegen/frontend/ts/api-types.ts.vm + templatePath: frontend/ts/api-types.ts.vm subpackageName: types extension: .ts VIEW: - templatePath: codegen/frontend/ts/index.vue.vm + templatePath: frontend/ts/index.vue.vm subpackageName: views extension: .vue Controller: - templatePath: codegen/backend/controller.java.vm + templatePath: backend/controller.java.vm subpackageName: controller Service: - templatePath: codegen/backend/service.java.vm + templatePath: backend/service.java.vm subpackageName: service ServiceImpl: - templatePath: codegen/backend/serviceImpl.java.vm + templatePath: backend/serviceImpl.java.vm subpackageName: service.impl Mapper: - templatePath: codegen/backend/mapper.java.vm + templatePath: backend/mapper.java.vm subpackageName: mapper MapperXml: - templatePath: codegen/backend/mapper.xml.vm + templatePath: backend/mapper.xml.vm subpackageName: mapper extension: .xml Converter: - templatePath: codegen/backend/converter.java.vm + templatePath: backend/converter.java.vm subpackageName: converter Query: - templatePath: codegen/backend/query.java.vm + templatePath: backend/query.java.vm subpackageName: model.query Form: - templatePath: codegen/backend/form.java.vm + templatePath: backend/form.java.vm subpackageName: model.form VO: - templatePath: codegen/backend/vo.java.vm + templatePath: backend/vo.java.vm subpackageName: model.vo Entity: - templatePath: codegen/backend/entity.java.vm + templatePath: backend/entity.java.vm subpackageName: model.entity diff --git a/src/main/resources/templates/codegen/backend/controller.java.vm b/src/main/resources/codegen/backend/controller.java.vm similarity index 100% rename from src/main/resources/templates/codegen/backend/controller.java.vm rename to src/main/resources/codegen/backend/controller.java.vm diff --git a/src/main/resources/templates/codegen/backend/converter.java.vm b/src/main/resources/codegen/backend/converter.java.vm similarity index 100% rename from src/main/resources/templates/codegen/backend/converter.java.vm rename to src/main/resources/codegen/backend/converter.java.vm diff --git a/src/main/resources/templates/codegen/backend/entity.java.vm b/src/main/resources/codegen/backend/entity.java.vm similarity index 100% rename from src/main/resources/templates/codegen/backend/entity.java.vm rename to src/main/resources/codegen/backend/entity.java.vm diff --git a/src/main/resources/templates/codegen/backend/form.java.vm b/src/main/resources/codegen/backend/form.java.vm similarity index 100% rename from src/main/resources/templates/codegen/backend/form.java.vm rename to src/main/resources/codegen/backend/form.java.vm diff --git a/src/main/resources/templates/codegen/backend/mapper.java.vm b/src/main/resources/codegen/backend/mapper.java.vm similarity index 100% rename from src/main/resources/templates/codegen/backend/mapper.java.vm rename to src/main/resources/codegen/backend/mapper.java.vm diff --git a/src/main/resources/templates/codegen/backend/mapper.xml.vm b/src/main/resources/codegen/backend/mapper.xml.vm similarity index 100% rename from src/main/resources/templates/codegen/backend/mapper.xml.vm rename to src/main/resources/codegen/backend/mapper.xml.vm diff --git a/src/main/resources/templates/codegen/backend/query.java.vm b/src/main/resources/codegen/backend/query.java.vm similarity index 100% rename from src/main/resources/templates/codegen/backend/query.java.vm rename to src/main/resources/codegen/backend/query.java.vm diff --git a/src/main/resources/templates/codegen/backend/service.java.vm b/src/main/resources/codegen/backend/service.java.vm similarity index 100% rename from src/main/resources/templates/codegen/backend/service.java.vm rename to src/main/resources/codegen/backend/service.java.vm diff --git a/src/main/resources/templates/codegen/backend/serviceImpl.java.vm b/src/main/resources/codegen/backend/serviceImpl.java.vm similarity index 100% rename from src/main/resources/templates/codegen/backend/serviceImpl.java.vm rename to src/main/resources/codegen/backend/serviceImpl.java.vm diff --git a/src/main/resources/templates/codegen/backend/vo.java.vm b/src/main/resources/codegen/backend/vo.java.vm similarity index 100% rename from src/main/resources/templates/codegen/backend/vo.java.vm rename to src/main/resources/codegen/backend/vo.java.vm diff --git a/src/main/resources/templates/codegen/frontend/js/api.js.vm b/src/main/resources/codegen/frontend/js/api.js.vm similarity index 100% rename from src/main/resources/templates/codegen/frontend/js/api.js.vm rename to src/main/resources/codegen/frontend/js/api.js.vm diff --git a/src/main/resources/templates/codegen/frontend/js/index.curd.js.vue.vm b/src/main/resources/codegen/frontend/js/index.crud.js.vue.vm similarity index 90% rename from src/main/resources/templates/codegen/frontend/js/index.curd.js.vue.vm rename to src/main/resources/codegen/frontend/js/index.crud.js.vue.vm index ee1fec35..6a5f6d94 100644 --- a/src/main/resources/templates/codegen/frontend/js/index.curd.js.vue.vm +++ b/src/main/resources/codegen/frontend/js/index.crud.js.vue.vm @@ -1,7 +1,7 @@ @@ -67,7 +67,7 @@ defineOptions({ }); import ${entityName}API from "@/api/${moduleName}/${entityKebab}"; -import usePage from "@/components/CURD/usePage"; +import useCrudPage from "@/components/Crud/useCrudPage"; // 组合式 CRUD const { @@ -83,7 +83,7 @@ const { handleExportClick, handleSearchClick, handleFilterChange, -} = usePage(); +} = useCrudPage(); // 搜索配置 const searchConfig = reactive({ @@ -105,11 +105,11 @@ const searchConfig = reactive({ }, #else { -#if($fieldConfig.javaType == "String") +#if($fieldConfig.fieldType == "String") type: "input", -#elseif($fieldConfig.javaType == "Integer" || $fieldConfig.javaType == "Long") +#elseif($fieldConfig.fieldType == "Integer" || $fieldConfig.fieldType == "Long") type: "input-number", -#elseif($fieldConfig.javaType == "Date" || $fieldConfig.javaType == "LocalDateTime") +#elseif($fieldConfig.fieldType == "LocalDate" || $fieldConfig.fieldType == "LocalDateTime") type: "date-picker", #else type: "input", @@ -118,7 +118,7 @@ const searchConfig = reactive({ prop: "$fieldConfig.fieldName", attrs: { placeholder: "$fieldConfig.fieldComment", -#if($fieldConfig.javaType == "Date" || $fieldConfig.javaType == "LocalDateTime") +#if($fieldConfig.fieldType == "LocalDate" || $fieldConfig.fieldType == "LocalDateTime") type: "daterange", "range-separator": "~", "start-placeholder": "开始时间", @@ -228,7 +228,7 @@ const addModalConfig = reactive({ }, #else { -#if($fieldConfig.javaType == "String") +#if($fieldConfig.fieldType == "String") #if($fieldConfig.fieldName.contains("password") || $fieldConfig.fieldName.contains("pwd")) type: "input", attrs: { @@ -272,7 +272,7 @@ const addModalConfig = reactive({ rules: [{ required: true, message: "$fieldConfig.fieldComment不能为空", trigger: "blur" }], #end #end -#elseif($fieldConfig.javaType == "Integer" || $fieldConfig.javaType == "Long") +#elseif($fieldConfig.fieldType == "Integer" || $fieldConfig.fieldType == "Long") type: "input-number", attrs: { placeholder: "$fieldConfig.fieldComment", @@ -281,7 +281,7 @@ const addModalConfig = reactive({ #if($fieldConfig.isRequired == 1) rules: [{ required: true, message: "$fieldConfig.fieldComment不能为空", trigger: "blur" }], #end -#elseif($fieldConfig.javaType == "BigDecimal" || $fieldConfig.javaType == "Double") +#elseif($fieldConfig.fieldType == "BigDecimal" || $fieldConfig.fieldType == "Double") type: "input-number", attrs: { placeholder: "$fieldConfig.fieldComment", @@ -291,7 +291,7 @@ const addModalConfig = reactive({ #if($fieldConfig.isRequired == 1) rules: [{ required: true, message: "$fieldConfig.fieldComment不能为空", trigger: "blur" }], #end -#elseif($fieldConfig.javaType == "Date" || $fieldConfig.javaType == "LocalDateTime") +#elseif($fieldConfig.fieldType == "LocalDate" || $fieldConfig.fieldType == "LocalDateTime") type: "date-picker", attrs: { type: "datetime", @@ -303,7 +303,7 @@ const addModalConfig = reactive({ #if($fieldConfig.isRequired == 1) rules: [{ required: true, message: "$fieldConfig.fieldComment不能为空", trigger: "change" }], #end -#elseif($fieldConfig.javaType == "Boolean" || $fieldConfig.fieldName.contains("status")) +#elseif($fieldConfig.fieldType == "Boolean" || $fieldConfig.fieldName.contains("status")) type: "switch", attrs: { activeText: "启用", diff --git a/src/main/resources/templates/codegen/frontend/js/index.js.vue.vm b/src/main/resources/codegen/frontend/js/index.js.vue.vm similarity index 100% rename from src/main/resources/templates/codegen/frontend/js/index.js.vue.vm rename to src/main/resources/codegen/frontend/js/index.js.vue.vm diff --git a/src/main/resources/templates/codegen/frontend/ts/api-types.ts.vm b/src/main/resources/codegen/frontend/ts/api-types.ts.vm similarity index 100% rename from src/main/resources/templates/codegen/frontend/ts/api-types.ts.vm rename to src/main/resources/codegen/frontend/ts/api-types.ts.vm diff --git a/src/main/resources/templates/codegen/frontend/ts/api.ts.vm b/src/main/resources/codegen/frontend/ts/api.ts.vm similarity index 100% rename from src/main/resources/templates/codegen/frontend/ts/api.ts.vm rename to src/main/resources/codegen/frontend/ts/api.ts.vm diff --git a/src/main/resources/templates/codegen/frontend/ts/index.curd.vue.vm b/src/main/resources/codegen/frontend/ts/index.crud.vue.vm similarity index 89% rename from src/main/resources/templates/codegen/frontend/ts/index.curd.vue.vm rename to src/main/resources/codegen/frontend/ts/index.crud.vue.vm index fff17201..5db65ff9 100644 --- a/src/main/resources/templates/codegen/frontend/ts/index.curd.vue.vm +++ b/src/main/resources/codegen/frontend/ts/index.crud.vue.vm @@ -1,7 +1,7 @@ @@ -68,8 +68,8 @@ defineOptions({ import ${entityName}API from "@/api/${moduleName}/${entityKebab}"; import type { ${entityName}Form, ${entityName}QueryParams } from "@/api/${moduleName}/${entityKebab}"; -import type { IObject, IOperateData, IModalConfig, IContentConfig, ISearchConfig } from "@/components/CURD/types"; -import usePage from "@/components/CURD/usePage"; +import type { IObject, IOperateData, IModalConfig, ICrudTableConfig, ISearchConfig } from "@/components/Crud/types"; +import useCrudPage from "@/components/Crud/useCrudPage"; // 组合式 CRUD const { @@ -85,7 +85,7 @@ const { handleExportClick, handleSearchClick, handleFilterChange, -} = usePage(); +} = useCrudPage(); // 搜索配置 const searchConfig: ISearchConfig = reactive({ @@ -107,11 +107,11 @@ const searchConfig: ISearchConfig = reactive({ }, #else { -#if($fieldConfig.javaType == "String") +#if($fieldConfig.fieldType == "String") type: "input", -#elseif($fieldConfig.javaType == "Integer" || $fieldConfig.javaType == "Long") +#elseif($fieldConfig.fieldType == "Integer" || $fieldConfig.fieldType == "Long") type: "input-number", -#elseif($fieldConfig.javaType == "Date" || $fieldConfig.javaType == "LocalDateTime") +#elseif($fieldConfig.fieldType == "LocalDate" || $fieldConfig.fieldType == "LocalDateTime") type: "date-picker", #else type: "input", @@ -120,7 +120,7 @@ const searchConfig: ISearchConfig = reactive({ prop: "$fieldConfig.fieldName", attrs: { placeholder: "$fieldConfig.fieldComment", -#if($fieldConfig.javaType == "Date" || $fieldConfig.javaType == "LocalDateTime") +#if($fieldConfig.fieldType == "LocalDate" || $fieldConfig.fieldType == "LocalDateTime") type: "daterange", "range-separator": "~", "start-placeholder": "开始时间", @@ -138,7 +138,7 @@ const searchConfig: ISearchConfig = reactive({ }); // 列表配置 -const contentConfig: IContentConfig<${entityName}QueryParams> = reactive({ +const contentConfig: ICrudTableConfig<${entityName}QueryParams> = reactive({ // 权限前缀 permPrefix: "${moduleName}:${entityKebab}", table: { @@ -230,7 +230,7 @@ const addModalConfig: IModalConfig<${entityName}Form> = reactive({ }, #else { -#if($fieldConfig.javaType == "String") +#if($fieldConfig.fieldType == "String") #if($fieldConfig.fieldName.contains("password") || $fieldConfig.fieldName.contains("pwd")) type: "input", attrs: { @@ -274,7 +274,7 @@ const addModalConfig: IModalConfig<${entityName}Form> = reactive({ rules: [{ required: true, message: "$fieldConfig.fieldComment不能为空", trigger: "blur" }], #end #end -#elseif($fieldConfig.javaType == "Integer" || $fieldConfig.javaType == "Long") +#elseif($fieldConfig.fieldType == "Integer" || $fieldConfig.fieldType == "Long") type: "input-number", attrs: { placeholder: "$fieldConfig.fieldComment", @@ -283,7 +283,7 @@ const addModalConfig: IModalConfig<${entityName}Form> = reactive({ #if($fieldConfig.isRequired == 1) rules: [{ required: true, message: "$fieldConfig.fieldComment不能为空", trigger: "blur" }], #end -#elseif($fieldConfig.javaType == "BigDecimal" || $fieldConfig.javaType == "Double") +#elseif($fieldConfig.fieldType == "BigDecimal" || $fieldConfig.fieldType == "Double") type: "input-number", attrs: { placeholder: "$fieldConfig.fieldComment", @@ -293,7 +293,7 @@ const addModalConfig: IModalConfig<${entityName}Form> = reactive({ #if($fieldConfig.isRequired == 1) rules: [{ required: true, message: "$fieldConfig.fieldComment不能为空", trigger: "blur" }], #end -#elseif($fieldConfig.javaType == "Date" || $fieldConfig.javaType == "LocalDateTime") +#elseif($fieldConfig.fieldType == "LocalDate" || $fieldConfig.fieldType == "LocalDateTime") type: "date-picker", attrs: { type: "datetime", @@ -305,7 +305,7 @@ const addModalConfig: IModalConfig<${entityName}Form> = reactive({ #if($fieldConfig.isRequired == 1) rules: [{ required: true, message: "$fieldConfig.fieldComment不能为空", trigger: "change" }], #end -#elseif($fieldConfig.javaType == "Boolean" || $fieldConfig.fieldName.contains("status")) +#elseif($fieldConfig.fieldType == "Boolean" || $fieldConfig.fieldName.contains("status")) type: "switch", attrs: { activeText: "启用", diff --git a/src/main/resources/templates/codegen/frontend/ts/index.vue.vm b/src/main/resources/codegen/frontend/ts/index.vue.vm similarity index 100% rename from src/main/resources/templates/codegen/frontend/ts/index.vue.vm rename to src/main/resources/codegen/frontend/ts/index.vue.vm diff --git a/src/main/resources/templates/excel/用户导入模板.xlsx b/src/main/resources/excel/用户导入模板.xlsx similarity index 100% rename from src/main/resources/templates/excel/用户导入模板.xlsx rename to src/main/resources/excel/用户导入模板.xlsx diff --git a/src/main/resources/data/ip2region.xdb b/src/main/resources/ip2region/ip2region.xdb similarity index 100% rename from src/main/resources/data/ip2region.xdb rename to src/main/resources/ip2region/ip2region.xdb diff --git a/src/main/resources/logback-spring.xml b/src/main/resources/logback-spring.xml index 9391b1a8..1c9ba4f2 100644 --- a/src/main/resources/logback-spring.xml +++ b/src/main/resources/logback-spring.xml @@ -47,17 +47,14 @@ - - - - - - + + + + - + - diff --git a/src/main/resources/mapper/form/FormDataMapper.xml b/src/main/resources/mapper/form/FormDataMapper.xml new file mode 100644 index 00000000..3f172114 --- /dev/null +++ b/src/main/resources/mapper/form/FormDataMapper.xml @@ -0,0 +1,24 @@ + + + + + + diff --git a/src/main/resources/mapper/form/FormDefinitionMapper.xml b/src/main/resources/mapper/form/FormDefinitionMapper.xml new file mode 100644 index 00000000..bde8b1ad --- /dev/null +++ b/src/main/resources/mapper/form/FormDefinitionMapper.xml @@ -0,0 +1,39 @@ + + + + + + diff --git a/src/main/resources/mapper/system/DictItemMapper.xml b/src/main/resources/mapper/system/DictItemMapper.xml index ab6cfec2..2b4ad820 100644 --- a/src/main/resources/mapper/system/DictItemMapper.xml +++ b/src/main/resources/mapper/system/DictItemMapper.xml @@ -11,11 +11,13 @@ dict_code, label, value, + tag_type, sort, status FROM sys_dict_item + is_deleted = 0 AND ( value LIKE CONCAT('%', #{queryParams.keywords} ,'%') @@ -27,5 +29,6 @@ AND dict_code = #{queryParams.dictCode} + ORDER BY sort ASC, id ASC diff --git a/src/main/resources/mapper/system/DictMapper.xml b/src/main/resources/mapper/system/DictMapper.xml index 670694b4..2628f549 100644 --- a/src/main/resources/mapper/system/DictMapper.xml +++ b/src/main/resources/mapper/system/DictMapper.xml @@ -3,7 +3,8 @@ PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"> - + + diff --git a/src/main/resources/mapper/system/MenuMapper.xml b/src/main/resources/mapper/system/MenuMapper.xml index 2f5afaae..63eb81ee 100644 --- a/src/main/resources/mapper/system/MenuMapper.xml +++ b/src/main/resources/mapper/system/MenuMapper.xml @@ -24,7 +24,6 @@ t1.visible, t1.redirect, t1.type, - t1.always_show, t1.keep_alive, t1.params FROM diff --git a/src/main/resources/mapper/system/UserMapper.xml b/src/main/resources/mapper/system/UserMapper.xml index c6ddbe80..46d4caf6 100644 --- a/src/main/resources/mapper/system/UserMapper.xml +++ b/src/main/resources/mapper/system/UserMapper.xml @@ -71,7 +71,11 @@ - ORDER BY u.${queryParams.sortBy} ${queryParams.order} + ORDER BY u.${queryParams.sortBy} + + DESC + ASC + diff --git a/src/main/resources/prompts/codegen/system.md b/src/main/resources/prompts/codegen/system.md new file mode 100644 index 00000000..df815200 --- /dev/null +++ b/src/main/resources/prompts/codegen/system.md @@ -0,0 +1,15 @@ +你是代码生成器的配置助手,根据数据库表结构推断代码生成配置。 +取值约束: +- businessName:中文简明业务名(如:用户、角色、通告) +- fieldComment:中文简明字段描述(如:用户名、创建时间) +- formType:{{formTypes}} +- queryType:{{queryTypes}} +- isRequired、isShowInList、isShowInForm、isShowInQuery:1 是,0 否 +- dictType:字典类型编码,无法确定时留空 +推断规则: +- 时间字段用 DATE_TIME 且查询用 BETWEEN,纯日期用 DATE +- 名称、标题等文本字段查询用 LIKE +- 状态、类型等枚举字段用 SELECT 或 RADIO,查询用 EQ +- 布尔或启用状态用 SWITCH +- id、create_time、update_time、is_deleted 等系统字段不出现在表单和查询中 +- columnName 必须与输入完全一致,只允许输出输入中出现的列 diff --git a/src/main/resources/prompts/form/system.md b/src/main/resources/prompts/form/system.md new file mode 100644 index 00000000..ff2c9dcc --- /dev/null +++ b/src/main/resources/prompts/form/system.md @@ -0,0 +1,16 @@ +你是表单设计助手,根据需求描述生成 form-create(Vue3 + Element Plus)表单规则数组。 +规则项结构: +{"type":"input","field":"username","title":"用户名","props":{"placeholder":"请输入用户名"},"validate":[{"required":true,"message":"请输入用户名","trigger":["blur","change"]}]} +可用组件 type: +- 基础:input、textarea、inputNumber、select、radio、checkbox、switch、datePicker、timePicker、slider、rate、upload +- 布局:row(children 为 col 数组)、col(children 为规则项数组) +- 业务组件:DictSelect(字典选择,props:{"code":"字典编码","type":"select|radio|checkbox","placeholder":"请选择"})、FileUpload(附件上传,props:{"limit":5,"maxFileSize":10,"accept":"*","uploadBtnText":"上传文件"}) +约定: +- field 用小写英文下划线命名,全局唯一 +- title 用中文 +- 必填字段加 validate 里的 required +- 日期用 datePicker,日期时间加 props:{"type":"datetime"},日期范围加 props:{"type":"daterange"} +- select/radio/checkbox 的选项写在 props.options,格式 [{"label":"是","value":1}] +- 状态、类型等枚举字段优先用 DictSelect +- 附件、图片类字段用 FileUpload +- 不要输出 children 为空的容器节点 diff --git a/src/main/resources/prompts/menu/system.md b/src/main/resources/prompts/menu/system.md new file mode 100644 index 00000000..080ca4c5 --- /dev/null +++ b/src/main/resources/prompts/menu/system.md @@ -0,0 +1,14 @@ +你是后台管理系统的菜单配置助手,根据菜单名称推断访问路径、权限标识和图标。 + +取值约束: +- routePath:当前这一级的路径片段,只含一段,不含上级路径,不带前导斜杠;小写英文,多个单词用连字符分隔(如 user、data-report),不用汉语拼音 +- perm:模块:资源:操作 三段式(如 sys:user:create),全部小写英文 +- iconKeywords:2 到 3 个小写英文关键词,描述该菜单最贴切的图标含义(如 user、setting、notice),按贴切程度排列,不要带 el-icon- 前缀 + +推断规则: +- 目录、页面推断 routePath 与 iconKeywords;按钮推断 perm;外链不推断任何字段 +- routePath 不是完整访问地址:不管挂在哪一级,都只输出自己这一段的路径,上位路径由系统拼接 +- 命名风格必须与「同级菜单示例」保持一致,模块前缀优先沿用示例中已出现的写法 +- iconKeywords 用通用的名词语义(如 user、order、chart),不要用形容词 +- 不要自创新的模块前缀,示例中无法参照时按系统现有命名习惯推断 +- 无法确定时留空:routePath、perm 输出空字符串,iconKeywords 输出空数组,不要编造 diff --git a/src/main/resources/prompts/workflow/summary.md b/src/main/resources/prompts/workflow/summary.md new file mode 100644 index 00000000..cac46d8f --- /dev/null +++ b/src/main/resources/prompts/workflow/summary.md @@ -0,0 +1,8 @@ +你是审批助手,根据流程表单数据与审批记录生成审批摘要,帮助审批人快速决策。 +直接输出中文摘要,不要标题、不要 Markdown 标记、不要分点罗列。 +要求: +- 控制在 200 字以内 +- 先说明这是一份什么申请(申请人、事由、关键金额或时间) +- 再说明已完成的审批环节与意见 +- 最后提示需重点关注的异常(金额超阈值、时间冲突、材料缺失等),无异常则不写 +- 不要编造表单与审批记录之外的信息 diff --git a/src/main/resources/workflow/expense.bpmn20.xml b/src/main/resources/workflow/expense.bpmn20.xml new file mode 100644 index 00000000..ba1b7b53 --- /dev/null +++ b/src/main/resources/workflow/expense.bpmn20.xml @@ -0,0 +1,92 @@ + + + + + flow1 + + + flow1 + flow2 + + + flow2 + flow3 + flow4 + + + flow3 + flow5 + + + flow4 + flow5 + flow6 + + + flow6 + + + + + ${amount > 5000} + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/main/resources/workflow/leave.bpmn20.xml b/src/main/resources/workflow/leave.bpmn20.xml new file mode 100644 index 00000000..39f46a01 --- /dev/null +++ b/src/main/resources/workflow/leave.bpmn20.xml @@ -0,0 +1,79 @@ + + + + + flow1 + + + flow1 + flow2 + + + flow2 + flow3 + flow4 + + + flow3 + flow5 + + + flow4 + flow5 + + + + + ${days > 3} + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/main/resources/workflow/purchase.bpmn20.xml b/src/main/resources/workflow/purchase.bpmn20.xml new file mode 100644 index 00000000..5de37dcd --- /dev/null +++ b/src/main/resources/workflow/purchase.bpmn20.xml @@ -0,0 +1,93 @@ + + + + + + flow1 + + + flow1 + flow2 + + + flow2 + flow3 + flow4 + + + flow3 + flow5 + + + flow4 + flow5 + flow6 + + + flow6 + + + + + ${amount > 10000} + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/main/resources/workflow/seal.bpmn20.xml b/src/main/resources/workflow/seal.bpmn20.xml new file mode 100644 index 00000000..443c91ce --- /dev/null +++ b/src/main/resources/workflow/seal.bpmn20.xml @@ -0,0 +1,55 @@ + + + + + flow1 + + + flow1 + flow2 + + + flow2 + flow3 + + + flow3 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/test/java/com/youlai/boot/ArchitectureTest.java b/src/test/java/com/youlai/boot/ArchitectureTest.java new file mode 100644 index 00000000..3761b750 --- /dev/null +++ b/src/test/java/com/youlai/boot/ArchitectureTest.java @@ -0,0 +1,59 @@ +package com.youlai.boot; + +import com.tngtech.archunit.junit.AnalyzeClasses; +import com.tngtech.archunit.junit.ArchTest; +import com.tngtech.archunit.lang.ArchRule; + +import static com.tngtech.archunit.lang.syntax.ArchRuleDefinition.noClasses; +import static com.tngtech.archunit.library.dependencies.SlicesRuleDefinition.slices; + +/** + * 分层依赖约束 + * + * @author Ray.Hao + * @since 4.8.0 + */ +@AnalyzeClasses(packages = "com.youlai.boot") +class ArchitectureTest { + + @ArchTest + static final ArchRule commonShouldNotDependOnUpperLayers = + noClasses().that().resideInAPackage("com.youlai.boot.common..") + .should().dependOnClassesThat().resideInAnyPackage( + "com.youlai.boot.config..", + "com.youlai.boot.framework..", + "com.youlai.boot.system..", + "com.youlai.boot.module..", + "com.youlai.boot.auth..", + "com.youlai.boot.codegen..", + "com.youlai.boot.support..") + .because("common 是纯共享层,只提供基础类型,不感知装配层、框架层和业务模块"); + + @ArchTest + static final ArchRule frameworkShouldNotDependOnBusinessModules = + noClasses().that().resideInAPackage("com.youlai.boot.framework..") + .should().dependOnClassesThat().resideInAnyPackage( + "com.youlai.boot.system..", + "com.youlai.boot.module..", + "com.youlai.boot.auth..", + "com.youlai.boot.codegen..") + .because("framework 提供通用技术能力,不依赖具体业务模块"); + + @ArchTest + static final ArchRule systemShouldNotDependOnCodegen = + noClasses().that().resideInAPackage("com.youlai.boot.system..") + .should().dependOnClassesThat().resideInAPackage("com.youlai.boot.codegen..") + .because("依赖方向为 codegen -> system,system 不得反向依赖代码生成"); + + @ArchTest + static final ArchRule controllersShouldNotDependOnMappers = + noClasses().that().haveSimpleNameEndingWith("Controller") + .should().dependOnClassesThat().haveSimpleNameEndingWith("Mapper") + .because("Controller 只能通过 Service 访问数据层"); + + @ArchTest + static final ArchRule businessPackagesShouldBeFreeOfCycles = + slices().matching("com.youlai.boot.(*)..") + .should().beFreeOfCycles() + .because("顶层包之间应单向依赖,出现环说明模块边界被绕过"); +} diff --git a/src/test/java/com/youlai/boot/validation/ValidationTest.java b/src/test/java/com/youlai/boot/validation/ValidationTest.java new file mode 100644 index 00000000..7b8cb677 --- /dev/null +++ b/src/test/java/com/youlai/boot/validation/ValidationTest.java @@ -0,0 +1,121 @@ +package com.youlai.boot.validation; + +import jakarta.validation.Validation; +import jakarta.validation.Validator; +import jakarta.validation.constraints.NotNull; +import org.junit.jupiter.api.BeforeAll; +import org.junit.jupiter.api.Test; +import org.springframework.core.type.classreading.MetadataReader; +import org.springframework.core.type.filter.AnnotationTypeFilter; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RestController; + +import jakarta.validation.Valid; +import org.springframework.validation.annotation.Validated; + +import java.lang.reflect.Method; +import java.lang.reflect.Parameter; +import java.util.ArrayList; +import java.util.List; +import java.util.Set; + +import static org.assertj.core.api.Assertions.assertThat; + +/** + * 参数校验约束测试 + * + * @author Ray.Hao + * @since 4.8.0 + */ +class ValidationTest { + + private static Validator validator; + + @BeforeAll + static void setUp() { + validator = Validation.buildDefaultValidatorFactory().getValidator(); + } + + @Test + void passwordResetFormShouldRejectBlankAndShortPassword() { + var blank = new com.youlai.boot.system.model.form.PasswordResetForm(); + assertThat(validator.validate(blank)).isNotEmpty(); + + var form = new com.youlai.boot.system.model.form.PasswordResetForm(); + form.setPassword("12345"); + assertThat(validator.validate(form)).isNotEmpty(); + + form.setPassword("123456"); + assertThat(validator.validate(form)).isEmpty(); + } + + @Test + void passwordUpdateFormShouldRequireAllThreeFields() { + var form = new com.youlai.boot.system.model.form.PasswordUpdateForm(); + assertThat(validator.validate(form)).hasSize(3); + + form.setOldPassword("123456"); + form.setNewPassword("123456"); + form.setConfirmPassword("123456"); + assertThat(validator.validate(form)).isEmpty(); + } + + @Test + void baseQueryShouldRejectOutOfRangePaging() { + var query = new com.youlai.boot.system.model.query.UserQuery(); + assertThat(validator.validate(query)).isEmpty(); + + query.setPageNum(0); + assertThat(validator.validate(query)).isNotEmpty(); + + query.setPageNum(1); + query.setPageSize(201); + assertThat(validator.validate(query)).isNotEmpty(); + + query.setPageSize(200); + query.setOrder("DROP TABLE"); + assertThat(validator.validate(query)).isNotEmpty(); + + query.setOrder("DESC"); + assertThat(validator.validate(query)).isEmpty(); + } + + @Test + void genConfigFormShouldRequireCoreFields() { + var form = new com.youlai.boot.codegen.model.form.GenConfigForm(); + assertThat(validator.validate(form)).isNotEmpty(); + + form.setTableName("sys_user"); + form.setBusinessName("用户"); + form.setModuleName("system"); + form.setPackageName("com.youlai"); + form.setEntityName("User"); + assertThat(validator.validate(form)).isEmpty(); + } + + @Test + void everyRequestBodyParameterShouldTriggerValidation() throws Exception { + var scanner = new org.springframework.context.annotation.ClassPathScanningCandidateComponentProvider(false); + scanner.addIncludeFilter(new AnnotationTypeFilter(RestController.class)); + + List violations = new ArrayList<>(); + for (var definition : scanner.findCandidateComponents("com.youlai.boot")) { + Class controller = Class.forName(definition.getBeanClassName()); + for (Method method : controller.getDeclaredMethods()) { + for (Parameter parameter : method.getParameters()) { + // Bean Validation 只作用于 Bean 类型,Map/List 等动态数据由 Service 层业务校验 + boolean isBeanType = parameter.getType().getName().startsWith("com.youlai.boot"); + boolean missingValidation = isBeanType + && parameter.isAnnotationPresent(RequestBody.class) + && !parameter.isAnnotationPresent(Valid.class) + && !parameter.isAnnotationPresent(Validated.class); + if (missingValidation) { + violations.add(controller.getSimpleName() + "#" + method.getName() + + " 的参数 " + parameter.getName() + " 缺少 @Valid"); + } + } + } + } + assertThat(violations).as(String.join(";", violations)).isEmpty(); + } +}