Compare commits

..
109 Commits
Author SHA1 Message Date
Timi 23204f3a48 v1.0.81
CI / build-deploy (pull_request) Successful in 1m2s
CI / notify-on-failure (pull_request) Skipped
2026-11-25 20:06:56 +08:00
Timi 02193b2ad1 feat(file): restrict preview to images and videos
- generate size-aware thumbnails (32-512px) with single-flight and atomic writes
- add optional v parameter for immutable browser caching
- serve PNG for PNG/GIF sources and JPEG otherwise
- drop PDF, text and WebP from preview support
2026-11-25 20:05:28 +08:00
Timi 62a2bbfe44 feat(api): add batch detail endpoints 2026-11-25 16:00:08 +08:00
Timi dd82259221 docs(openapi): add AI index and annotate setting endpoints
- add openapi-index.py to generate a compact Markdown index from OpenAPI JSON/YAML
- generate docs/openapi.index.md from the export scripts by default
- annotate SettingController with tags, operations, parameters and public security
- document the AI index workflow in api-integration.md
2026-11-25 13:18:08 +08:00
Timi 3f4a85a3d3 feat: remove preview file request rate limit 2026-11-25 12:50:09 +08:00
Timi d4fc4274fd v1.0.80
CI / build-deploy (pull_request) Successful in 10m21s
CI / notify-on-failure (pull_request) Skipped
2026-11-25 01:25:46 +08:00
Timi aefc0ad205 feat(openapi): integrate springdoc and API integration guide
- add springdoc-openapi and expose /v3/api-docs, /v3/api-docs.yaml and Swagger UI
- keep API docs responses unwrapped by replacing the global return handler
- add Chinese @Tag/@Operation/@Parameter docs for file and async task controllers
- add docs/api-integration.md and local export scripts for AI agent consumption
- ignore local OpenAPI snapshots and force LF for shell scripts
2026-11-25 01:23:30 +08:00
Timi dc5f62fd93 chore: remove serena project config 2026-11-25 01:23:26 +08:00
Timi 3b62f795de feat(file): refactor file management module
- add virtual path storage, granular permissions, trash and share features

- secure upload, archive and transfer tasks; add folder size calculation

- split controllers and add async task SSE progress events

- add Flyway migrations and file module tests
2026-11-24 15:36:17 +08:00
Timi 7e7a9cf60c feat(gao-ai): add confirmed write operations
- add prepare/commit/cancel MCP tools and pending operation state
- enforce execution identity, permissions, exact confirmation and audit
- support attachments and operation confirmation cards
- rewrite Dify DSL for write routing and destructive confirmations
2026-11-24 11:41:59 +08:00
Timi 58310b1e33 feat(gao): add customer profile and event month PDF exports 2026-11-23 15:27:25 +08:00
Timi badda20f32 v1.0.79
CI / build-deploy (pull_request) Successful in 35s
CI / notify-on-failure (pull_request) Skipped
2026-11-20 13:11:39 +08:00
Timi 386e26e77e feat(gao): add customer point ledger detail api 2026-11-19 17:56:07 +08:00
Timi 597101723c feat(gao): update customer recycle api 2026-11-19 16:11:18 +08:00
Timi 30e5888240 style(gao): perf GaoRecycle* code 2026-11-19 11:21:11 +08:00
Timi 743f491efc style(gao): long sql to XML 2026-11-19 01:38:42 +08:00
Timi c40ba5383e feat(gao): add GaoRecycleLedger entity 2026-11-19 01:33:36 +08:00
Timi ca87a273bc feat(gao): point redemption in product stock list and detail 2026-11-18 16:41:03 +08:00
Timi 0166a5585b chore(app): change max app update note to 8 2026-11-18 16:28:44 +08:00
Timi 78cfe0708c feat(gao): sync point redemption photo to product stock out 2026-11-18 16:27:58 +08:00
Timi bdcf32ba26 v1.0.78
CI / build-deploy (pull_request) Successful in 33s
CI / notify-on-failure (pull_request) Skipped
2026-11-18 00:10:14 +08:00
Timi 6feaad4b33 fix(app): db transactional 2026-11-18 00:10:01 +08:00
Timi 8954902994 v1.0.77
CI / build-deploy (pull_request) Successful in 34s
CI / notify-on-failure (pull_request) Skipped
2026-11-17 23:37:38 +08:00
Timi 09a8547ded feat(app): dual pointer for app channel 2026-11-17 23:37:31 +08:00
Timi 82110e36b7 v1.0.76
CI / build-deploy (pull_request) Successful in 33s
CI / notify-on-failure (pull_request) Skipped
2026-11-17 16:37:51 +08:00
Timi 5604edc00b fix(app): lost update log for point to native package 2026-11-17 16:37:33 +08:00
Timi 7294e9050d v1.0.75
CI / build-deploy (pull_request) Successful in 33s
CI / notify-on-failure (pull_request) Skipped
2026-11-17 15:55:08 +08:00
Timi 7d87ca7a86 fix(app): host update 2026-11-17 15:55:08 +08:00
Timi 6b2841274d v1.0.74
CI / build-deploy (pull_request) Successful in 33s
CI / notify-on-failure (pull_request) Skipped
2026-11-17 14:55:12 +08:00
Timi d5ccfbb231 fix(system): delete app release fail 2026-11-17 14:54:58 +08:00
Timi 96750730d3 v1.0.73
CI / build-deploy (pull_request) Successful in 34s
CI / notify-on-failure (pull_request) Skipped
2026-11-17 14:26:22 +08:00
Timi 725503152e fix(attach): lost file name for download 2026-11-17 14:26:09 +08:00
Timi 5233ac7eef v1.0.72
CI / build-deploy (pull_request) Successful in 35s
CI / notify-on-failure (pull_request) Skipped
2026-11-17 11:51:44 +08:00
Timi 343406efc7 feat(app): response apk package 2026-11-17 11:51:44 +08:00
Timi ee33284a2c feat(gao): support customer birthdate followup reminder 2026-11-16 16:23:00 +08:00
Timi 32bfdaa116 fix(gao): allow CI update log 2026-11-15 17:15:34 +08:00
Timi 7bbd217bdd feat(gao): no modification product base unit 2026-11-14 16:31:43 +08:00
Timi 1349b3c069 fix(gao): order remind url 2026-11-14 15:49:55 +08:00
Timi 8c0845d610 fix(system): fix apk recent update log 2026-11-14 15:05:56 +08:00
Timi 4ae8b1dda8 v1.0.71
CI / build-deploy (pull_request) Successful in 34s
CI / notify-on-failure (pull_request) Skipped
2026-11-14 01:05:20 +08:00
Timi f0c586ace8 feat(gao recycle): customer recycle list 2026-11-14 01:05:02 +08:00
Timi 43e7a509c2 feat(gao recycle): support quick fulfillment for recycle order 2026-11-13 19:05:52 +08:00
Timi a14a9a5581 feat(system): app update log api 2026-11-13 15:04:29 +08:00
Timi 8f4a839b2f v1.0.70
CI / build-deploy (pull_request) Successful in 32s
CI / notify-on-failure (pull_request) Skipped
2026-11-12 17:44:23 +08:00
Timi bd3f10fe60 fix: db timezone 2026-11-12 17:44:03 +08:00
Timi 169fd257a9 feat: recycle system 2026-11-12 17:37:05 +08:00
Timi bc901e2f0b v1.0.69
CI / build-deploy (pull_request) Successful in 33s
CI / notify-on-failure (pull_request) Skipped
2026-11-08 20:04:59 +08:00
Timi 74dd150469 add recycle 2026-11-08 18:50:53 +08:00
Timi 03a4d4a8ff v1.0.68
CI / build-deploy (pull_request) Successful in 34s
CI / notify-on-failure (pull_request) Skipped
2026-11-08 02:02:47 +08:00
Timi 7d8172e063 feat: can fulfillment sku order filter 2026-11-08 01:39:42 +08:00
Timi e5a065fbaf fix: gray permille for appVersion 2026-11-08 00:46:46 +08:00
Timi a8c04cf342 v1.0.67
CI / build-deploy (pull_request) Successful in 32s
CI / notify-on-failure (pull_request) Skipped
2026-11-07 00:05:23 +08:00
Timi 669118c0f8 fix attach create response fail 2026-11-07 00:05:11 +08:00
Timi b2cbe15d8b v1.0.66
CI / build-deploy (pull_request) Successful in 32s
CI / notify-on-failure (pull_request) Skipped
2026-11-06 23:58:41 +08:00
Timi a5426ce894 add APP_RELEASE attach 2026-11-06 23:58:29 +08:00
Timi aef3864a31 v1.0.65
CI / build-deploy (pull_request) Successful in 34s
CI / notify-on-failure (pull_request) Skipped
2026-11-06 23:36:48 +08:00
Timi 9a6bdfc3f0 add: app version and user api key 2026-11-06 23:36:32 +08:00
Timi d029ba58c3 v1.0.64
CI / build-deploy (pull_request) Successful in 32s
CI / notify-on-failure (pull_request) Skipped
2026-10-30 01:23:04 +08:00
Timi b0b623fa10 support customer list 2026-10-30 01:22:45 +08:00
Timi 4f1a5cbd9d v1.0.63
CI / build-deploy (pull_request) Successful in 33s
CI / notify-on-failure (pull_request) Skipped
2026-10-29 20:01:44 +08:00
Timi 9aac55a180 add skuFulfillmentList 2026-10-29 14:23:29 +08:00
Timi 6fd765661d fix cancel fulfillment permission 2026-10-28 11:56:11 +08:00
Timi 7222d19d02 v1.0.62
CI / build-deploy (pull_request) Successful in 33s
CI / notify-on-failure (pull_request) Skipped
2026-10-28 00:57:47 +08:00
Timi 5d55aee586 cancel sale order with fulfillment and fund record 2026-10-28 00:35:12 +08:00
Timi 14a81d1080 download from attachment api for data export 2026-10-26 11:46:02 +08:00
Timi 3d53a6a34b v1.0.61
CI / build-deploy (pull_request) Successful in 32s
CI / notify-on-failure (pull_request) Skipped
2026-10-26 00:33:58 +08:00
Timi fe8e9b7a8c fix data export 2026-10-26 00:33:40 +08:00
Timi 389bee2e45 v1.0.60
CI / build-deploy (pull_request) Successful in 26s
CI / notify-on-failure (pull_request) Skipped
2026-10-25 01:17:43 +08:00
Timi f3eddc69af add data export 2026-10-25 01:17:24 +08:00
Timi c20f0b6f45 fix AOP log 2026-10-23 14:33:37 +08:00
Timi 282832b950 split AuditOperation 2026-10-22 11:56:31 +08:00
Timi 72111f0a1b v1.0.59
CI / build-deploy (pull_request) Successful in 27s
CI / notify-on-failure (pull_request) Skipped
2026-10-21 01:35:59 +08:00
Timi 4ba6e3a76f fix multilingual serialize 2026-10-21 01:35:43 +08:00
Timi 98b48cc9ae unlimit GaoOrderFulfillmentPage endAt 2026-10-21 01:01:46 +08:00
Timi b3db103494 add Tag useCount 2026-10-21 01:01:34 +08:00
Timi 618d91c6aa add quick fulfillment 2026-10-20 21:46:04 +08:00
Timi 7d272d3cd3 v1.0.58
CI / build-deploy (pull_request) Successful in 30s
CI / notify-on-failure (pull_request) Skipped
2026-10-16 01:33:32 +08:00
Timi adaadcbe51 fix GaoProductStockRecordPageResult 2026-10-16 01:33:17 +08:00
Timi a4abdc0632 add GaoPointRedeemSkuPageResult 2026-10-16 00:22:37 +08:00
Timi dbf7cb8b0f product stock total for page 2026-10-15 10:43:34 +08:00
Timi ce2a0d2995 revoke fulfillment and payment for cancel sale order 2026-10-14 15:53:46 +08:00
Timi f0b001dba9 add /manual-in/batch for gao product 2026-10-14 14:44:31 +08:00
Timi 0dab1ad039 v1.0.57
CI / build-deploy (pull_request) Successful in 27s
CI / notify-on-failure (pull_request) Skipped
2026-10-05 16:10:07 +08:00
Timi 12fb82de34 update gao product edit 2026-10-05 16:09:35 +08:00
Timi 8fe00fbb7c update sms max customer 2026-09-26 09:58:49 +08:00
Timi b6f20c976d v1.0.56
CI / build-deploy (pull_request) Successful in 26s
CI / notify-on-failure (pull_request) Skipped
2026-09-25 23:43:25 +08:00
Timi 369da9f997 add main agent DSL 2026-09-25 22:07:42 +08:00
Timi cd8e552d21 support sku filter 2026-09-25 22:07:31 +08:00
Timi b30434777d v1.0.55
CI / build-deploy (pull_request) Successful in 27s
CI / notify-on-failure (pull_request) Skipped
2026-09-23 23:15:19 +08:00
Timi 4aafb17214 add point chart 2026-09-23 21:54:39 +08:00
Timi 134218b56a v1.0.54
CI / build-deploy (pull_request) Successful in 26s
CI / notify-on-failure (pull_request) Skipped
2026-09-23 01:07:17 +08:00
Timi 5a07bfb7e3 add sku filter 2026-09-23 00:14:18 +08:00
Timi 1203ccfa4a with skuId for only once sku 2026-09-22 17:53:45 +08:00
Timi 7adea85e1f update order remind content 2026-09-22 16:52:18 +08:00
Timi 48eaf2356f v1.0.53
CI / build-deploy (pull_request) Successful in 26s
CI / notify-on-failure (pull_request) Skipped
2026-09-22 01:31:15 +08:00
Timi 970952d9fa clone fulfillment attach to stock out 2026-09-21 23:59:13 +08:00
Timi e5bfb59a1c v1.0.52
CI / build-deploy (pull_request) Successful in 27s
CI / notify-on-failure (pull_request) Skipped
2026-09-21 01:18:35 +08:00
Timi 51c1d20d3c more filter for sales order 2026-09-20 15:40:03 +08:00
Timi 9256e08cfc v1.0.51
CI / build-deploy (pull_request) Successful in 26s
CI / notify-on-failure (pull_request) Skipped
2026-09-19 01:26:29 +08:00
Timi d0dcd0283e add customer order summary 2026-09-19 01:26:03 +08:00
Timi 76c5495c32 add package filter for SalesOrderPage 2026-09-18 18:28:15 +08:00
Timi cee7dd2442 v1.0.50
CI / build-deploy (pull_request) Successful in 28s
CI / notify-on-failure (pull_request) Skipped
2026-09-18 01:51:00 +08:00
Timi 8f2545f271 add customer followup 2026-09-18 01:47:54 +08:00
Timi b5a7c0d46c v1.0.49
CI / build-deploy (pull_request) Successful in 25s
CI / notify-on-failure (pull_request) Skipped
2026-09-17 01:31:21 +08:00
Timi 088afbe5c1 update customer in list 2026-09-17 01:31:02 +08:00
Timi 0d155ec5b2 update AIAgent 2026-09-16 15:15:36 +08:00
Timi 7d53d31c3f add GaoProductStockBatchRequest 2026-09-16 15:15:19 +08:00
Timi cd8bcae5be auto verify for order fulfillment and payment 2026-09-16 13:06:39 +08:00
Timi a2b6253d1d add customerCount for list event record 2026-09-16 12:54:39 +08:00
605 changed files with 34243 additions and 3202 deletions
+2
View File
@@ -0,0 +1,2 @@
# Shell 脚本使用 LF,避免 Windows 下 CRLF 导致执行失败
*.sh text eol=lf
+9
View File
@@ -4,6 +4,11 @@
/target
/temp
/AGENTS.md
/.workbuddy
# OpenAPI 本地导出(scripts/export-openapi.*)
/docs/openapi.local.yaml
/docs/openapi.local.json
multilingualField/
!.mvn/wrapper/maven-wrapper.jar
@@ -41,5 +46,9 @@ build/
### VS Code ###
.vscode/
### Python ###
__pycache__/
*.py[cod]
### Mac OS ###
.DS_Store
-9
View File
@@ -1,9 +0,0 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="SqlDialectMappings">
<file url="file://$PROJECT_DIR$/src/main/resources/db/migration/timiserver/V1__init_schema.sql" dialect="MariaDB" />
<file url="file://$PROJECT_DIR$/src/main/resources/db/migration/timiserver/V2__init_system_data.sql" dialect="GenericSQL" />
<file url="file://$PROJECT_DIR$/src/main/resources/mapper/timi-server/gao/GaoEventRecordMapper.xml" dialect="MariaDB" />
<file url="PROJECT" dialect="MariaDB" />
</component>
</project>
-2
View File
@@ -1,2 +0,0 @@
/cache
/project.local.yml
-1
View File
@@ -1 +0,0 @@
TimiServerAPI 是一个基于 Spring Boot 的高耦合业务后端服务,代码位于 src/main/java/com/imyeyu/api,下分多个业务模块,如 blog、common、gitea、forevermc、journal、minecraft、music、system 等。项目使用多数据源 MySQL(timiserver、gitea、forevermc)、MongoDB、Redis、MyBatis,并引入 Flyway 做数据库迁移。运行环境为 Windows,JDK 21。
-1
View File
@@ -1 +0,0 @@
项目约定:全部沟通、注释、文档使用中文;Java 使用 tab 缩进;注释要求符合 javadoc;优先使用官方 API,不随意引入外部依赖;字符串优先用 formatted(),长动态字符串用 StringBuilder;优先用代码级工具做精确修改;避免盲目通读大文件,先缩小目录和符号范围。
-1
View File
@@ -1 +0,0 @@
Windows / PowerShell 常用命令:`Get-ChildItem -Force` 查看目录,`rg --files` 列文件,`rg -n "PATTERN" PATH` 搜索文本,`mvn -q -DskipTests compile` 做基础编译验证,`git diff -- PATH` 查看改动。配置文件主要在 `src/main/resources`,Java 源码在 `src/main/java`。
-1
View File
@@ -1 +0,0 @@
完成任务后,优先做最小范围验证。Java 侧先尝试 `mvn -q -DskipTests compile`;如果失败,区分是本次改动导致还是项目已有编译问题。不要回滚用户已有改动,不要做破坏性 git 操作。多数据源场景要特别检查 `@Primary`、`@Qualifier` 和自动装配框架(如 Flyway)的绑定关系。
-154
View File
@@ -1,154 +0,0 @@
# the name by which the project can be referenced within Serena
project_name: "TimiServerAPI"
# list of languages for which language servers are started; choose from:
# al bash clojure cpp csharp
# csharp_omnisharp dart elixir elm erlang
# fortran fsharp go groovy haskell
# haxe java julia kotlin lua
# markdown
# matlab nix pascal perl php
# php_phpactor powershell python python_jedi r
# rego ruby ruby_solargraph rust scala
# swift terraform toml typescript typescript_vts
# vue yaml zig
# (This list may be outdated. For the current list, see values of Language enum here:
# https://github.com/oraios/serena/blob/main/src/solidlsp/ls_config.py
# For some languages, there are alternative language servers, e.g. csharp_omnisharp, ruby_solargraph.)
# Note:
# - For C, use cpp
# - For JavaScript, use typescript
# - For Free Pascal/Lazarus, use pascal
# Special requirements:
# Some languages require additional setup/installations.
# See here for details: https://oraios.github.io/serena/01-about/020_programming-languages.html#language-servers
# When using multiple languages, the first language server that supports a given file will be used for that file.
# The first language is the default language and the respective language server will be used as a fallback.
# Note that when using the JetBrains backend, language servers are not used and this list is correspondingly ignored.
languages:
- java
# the encoding used by text files in the project
# For a list of possible encodings, see https://docs.python.org/3.11/library/codecs.html#standard-encodings
encoding: "utf-8"
# line ending convention to use when writing source files.
# Possible values: unset (use global setting), "lf", "crlf", or "native" (platform default)
# This does not affect Serena's own files (e.g. memories and configuration files), which always use native line endings.
line_ending:
# The language backend to use for this project.
# If not set, the global setting from serena_config.yml is used.
# Valid values: LSP, JetBrains
# Note: the backend is fixed at startup. If a project with a different backend
# is activated post-init, an error will be returned.
language_backend:
# whether to use project's .gitignore files to ignore files
ignore_all_files_in_gitignore: true
# advanced configuration option allowing to configure language server-specific options.
# Maps the language key to the options.
# Have a look at the docstring of the constructors of the LS implementations within solidlsp (e.g., for C# or PHP) to see which options are available.
# No documentation on options means no options are available.
ls_specific_settings: {}
# list of additional paths to ignore in this project.
# Same syntax as gitignore, so you can use * and **.
# Note: global ignored_paths from serena_config.yml are also applied additively.
ignored_paths: []
# whether the project is in read-only mode
# If set to true, all editing tools will be disabled and attempts to use them will result in an error
# Added on 2025-04-18
read_only: false
# list of tool names to exclude.
# This extends the existing exclusions (e.g. from the global configuration)
#
# Below is the complete list of tools for convenience.
# To make sure you have the latest list of tools, and to view their descriptions,
# execute `uv run scripts/print_tool_overview.py`.
#
# * `activate_project`: Activates a project based on the project name or path.
# * `check_onboarding_performed`: Checks whether project onboarding was already performed.
# * `create_text_file`: Creates/overwrites a file in the project directory.
# * `delete_memory`: Delete a memory file. Should only happen if a user asks for it explicitly,
# for example by saying that the information retrieved from a memory file is no longer correct
# or no longer relevant for the project.
# * `edit_memory`: Replaces content matching a regular expression in a memory.
# * `execute_shell_command`: Executes a shell command.
# * `find_file`: Finds files in the given relative paths
# * `find_referencing_symbols`: Finds symbols that reference the given symbol using the language server backend
# * `find_symbol`: Performs a global (or local) search using the language server backend.
# * `get_current_config`: Prints the current configuration of the agent, including the active and available projects, tools, contexts, and modes.
# * `get_symbols_overview`: Gets an overview of the top-level symbols defined in a given file.
# * `initial_instructions`: Provides instructions Serena usage (i.e. the 'Serena Instructions Manual')
# for clients that do not read the initial instructions when the MCP server is connected.
# * `insert_after_symbol`: Inserts content after the end of the definition of a given symbol.
# * `insert_before_symbol`: Inserts content before the beginning of the definition of a given symbol.
# * `list_dir`: Lists files and directories in the given directory (optionally with recursion).
# * `list_memories`: List available memories. Any memory can be read using the `read_memory` tool.
# * `onboarding`: Performs onboarding (identifying the project structure and essential tasks, e.g. for testing or building).
# * `read_file`: Reads a file within the project directory.
# * `read_memory`: Read the content of a memory file. This tool should only be used if the information
# is relevant to the current task. You can infer whether the information
# is relevant from the memory file name.
# You should not read the same memory file multiple times in the same conversation.
# * `rename_memory`: Renames or moves a memory. Moving between project and global scope is supported
# (e.g., renaming "global/foo" to "bar" moves it from global to project scope).
# * `rename_symbol`: Renames a symbol throughout the codebase using language server refactoring capabilities.
# For JB, we use a separate tool.
# * `replace_content`: Replaces content in a file (optionally using regular expressions).
# * `replace_symbol_body`: Replaces the full definition of a symbol using the language server backend.
# * `safe_delete_symbol`:
# * `search_for_pattern`: Performs a search for a pattern in the project.
# * `write_memory`: Write some information (utf-8-encoded) about this project that can be useful for future tasks to a memory in md format.
# The memory name should be meaningful.
excluded_tools: []
# list of tools to include that would otherwise be disabled (particularly optional tools that are disabled by default).
# This extends the existing inclusions (e.g. from the global configuration).
included_optional_tools: []
# fixed set of tools to use as the base tool set (if non-empty), replacing Serena's default set of tools.
# This cannot be combined with non-empty excluded_tools or included_optional_tools.
fixed_tools: []
# list of mode names to that are always to be included in the set of active modes
# The full set of modes to be activated is base_modes + default_modes.
# If the setting is undefined, the base_modes from the global configuration (serena_config.yml) apply.
# Otherwise, this setting overrides the global configuration.
# Set this to [] to disable base modes for this project.
# Set this to a list of mode names to always include the respective modes for this project.
base_modes:
# list of mode names that are to be activated by default.
# The full set of modes to be activated is base_modes + default_modes.
# If the setting is undefined, the default_modes from the global configuration (serena_config.yml) apply.
# Otherwise, this overrides the setting from the global configuration (serena_config.yml).
# This setting can, in turn, be overridden by CLI parameters (--mode).
default_modes:
# initial prompt for the project. It will always be given to the LLM upon activating the project
# (contrary to the memories, which are loaded on demand).
initial_prompt: ""
# time budget (seconds) per tool call for the retrieval of additional symbol information
# such as docstrings or parameter information.
# This overrides the corresponding setting in the global configuration; see the documentation there.
# If null or missing, use the setting from the global configuration.
symbol_info_budget:
# list of regex patterns which, when matched, mark a memory entry as read‑only.
# Extends the list from the global configuration, merging the two lists.
read_only_memory_patterns: []
# list of regex patterns for memories to completely ignore.
# Matching memories will not appear in list_memories or activate_project output
# and cannot be accessed via read_memory or write_memory.
# To access ignored memory files, use the read_file tool on the raw file path.
# Extends the list from the global configuration, merging the two lists.
# Example: ["_archive/.*", "_episodes/.*"]
ignored_memory_patterns: []
+9 -1
View File
@@ -4,4 +4,12 @@
技术栈:SpringBoot MariaDB MyBatis Redis
[timijava](https://github.com/imyeyu/timijava)
[timijava](https://github.com/imyeyu/timijava)
### GAO 客户画像 PDF
`POST /gao/customer/profile/pdf?id={客户ID}` 返回 `application/pdf`,响应按浏览器内预览处理。调用者需要独立的 `CUSTOMER_PROFILE:READ` 权限,且客户必须在其门店数据范围内;画像读取不再要求分别持有订单、积分或回收物权限。默认不将该权限授予店长或门店管理角色,需要在角色管理中显式授权。
统计限定客户所属门店。事件包含已核销及无需核销的记录,排除待核销记录,并沿用既有事件查询对历史消费事件的排除规则;上月和本月按服务端时区的自然月计算。订单排除取消单,金额由分换算为元,净收款为已付款减退款。积分月份按流水发生时间统计获得和消费;回收物按品种和单位分别展示,账户流水中的获得、使用及人工调整与回收支付的当前核销状态分别统计。数量、积分和金额均按每四位分组。
PDF 使用 `templates/GaoCustomerProfile.ftl`,单页展示最多 6 种事件、6 项产品、4 种回收物和 3 条跟进提醒;多出的数据不影响总体汇总。长文本会截断,页面空间不足时会缩小字号;若仍无法排入一页,接口返回错误,不生成多页文件。使用首张 `PHOTO` 附件并按比例转为灰度;无图片或图片格式无法解码时使用占位。字体使用服务器上合法安装的宋体 SimSun,默认路径为 `C:/Windows/Fonts/simsun.ttc`。非 Windows 环境或使用其他路径时,设置 `gao.customer-profile.font-path` 指向包含 SimSun 的 TTC 文件;服务不会自动替换字体,字体缺失时接口返回错误。项目不分发该字体文件。
View File
+283
View File
@@ -0,0 +1,283 @@
# TimiServerAPI 接口对接说明
> 接口的路径、方法、参数、请求体、响应体以 `docs/openapi.local.yaml` 为准。本文只补充 OpenAPI 无法完整表达的横切约定:统一响应包装、鉴权、错误码、分页、二进制响应与 SSE。
>
> 本文不重复 OpenAPI 中的接口清单和字段说明。
- 服务版本:`1.0.79`
- OpenAPI 版本:`3.1.0`
- 默认本地地址:`http://localhost:18092`(无 context-path)
- OpenAPI JSON:`/v3/api-docs`
- OpenAPI YAML:`/v3/api-docs.yaml`
- Swagger UI:`/swagger-ui.html`
---
## 1. 文档快照与覆盖范围
### 1.1 导出本地快照
仓库提供两个导出脚本,默认输出 `docs/openapi.local.yaml`:
```powershell
# PowerShell
.\scripts\export-openapi.ps1
# 指定地址与文件名(.json 后缀会导出 JSON)
.\scripts\export-openapi.ps1 -BaseUrl http://192.168.1.10:18092 -OutFile docs\openapi.local.json
```
```bash
# Bash
bash scripts/export-openapi.sh
bash scripts/export-openapi.sh http://192.168.1.10:18092 docs/openapi.local.json
```
`docs/openapi.local.*` 是本地快照,已在 `.gitignore` 中忽略,不应提交。需要给远程 AI Agent 使用时,优先发送该文件,而不是 `localhost` 地址。
导出脚本会同时生成面向 AI Agent 的接口索引 `docs/openapi.index.md`:按业务模块列出接口的方法、路径、摘要、参数、请求体与响应 schema。索引体积远小于完整 OpenAPI,适合先用于定位,再读取 OpenAPI 中的对应片段。PowerShell 使用 `-NoIndex`、Bash 使用 `SKIP_INDEX=1` 可跳过索引生成。
### 1.2 覆盖范围说明
SpringDoc 会扫描项目中的全部 Controller,因此 OpenAPI 文件里会包含用户、标签、系统设置等模块的接口。目前已对文件、异步任务与系统设置模块的 8 个 Controller 补充了完整的中文 `@Tag` / `@Operation` / `@Parameter` 描述;这些接口的路径、参数、请求体和响应结构均已包含在 OpenAPI 中。其他模块的接口属于 SpringDoc 自动生成的基础描述,业务语义可能不完整,复杂接口请结合源码或联调确认。
OpenAPI 中还声明了全局 `Token` 安全要求,但登录、注册等公开接口实际可能不需要登录。**是否需要鉴权以接口实际行为为准**;公开接口已在 OpenAPI 中按操作单独标记 `security`。
---
## 2. 基础约定
### 2.1 请求格式
- 普通接口:`Content-Type: application/json`
- 上传类接口:`multipart/form-data`
- 字符编码:UTF-8
- 时间字段:除特别说明外,均为 **epoch 毫秒**(`long`)
- 大小字段:字节(`long`)
### 2.2 鉴权
请求头优先使用:
```http
Token: <登录令牌或 API Key>
```
服务端也兼容以下写法:
```http
token: <登录令牌或 API Key>
```
以及 URL 参数:
```text
?token=<登录令牌或 API Key>
```
> 生产环境建议只使用 `Token` 请求头。URL 参数容易进入访问日志、浏览器历史和 Referer。
>
> 浏览器原生 `EventSource` 不能设置自定义请求头,SSE 场景才使用 `?token=`。
支持两种凭证:
1. **登录令牌**:通过登录接口获取,具体接口见 OpenAPI。
2. **API Key**:以 `tk_` 开头,格式为 `tk_<8位十六进制>_<32位十六进制>`。API Key 创建后只返回一次明文,不能用于管理 API Key 本身。
### 2.3 统一响应包装(TimiResponse)
除二进制、SSE 等特殊接口外,所有 JSON 接口都会被统一包装为:
```json
{
"code": 20000,
"message": "可选,面向用户的提示",
"messageCode": "可选,国际化消息键",
"data": {}
}
```
字段说明:
| 字段 | 类型 | 说明 |
| --- | --- | --- |
| `code` | number | 业务代码,**不是 HTTP 状态码** |
| `message` | string | 提示信息,可能根据语言返回不同文案 |
| `messageCode` | string | 国际化消息键,可能不存在 |
| `data` | any | 业务数据;为 `null` 时通常被省略 |
判断成功请使用:
```ts
const success = response.code <= 30000; // 20000 成功,20001 表示成功但忽略请求
```
不要只根据 HTTP 状态码判断业务结果。普通 JSON 接口即使业务失败,HTTP 状态通常仍是 `200`。
### 2.4 错误码
| code | 含义 |
| --- | --- |
| `20000` | 成功 |
| `20001` | 成功,忽略请求 |
| `40000` | 缺少参数 / 未登录 |
| `40001` | 参数不合法 |
| `40002` | 参数已过期 |
| `40100` | 无权限 |
| `40101` | 权限错误 |
| `40102` | 非法请求 / 请求过于频繁 |
| `40301` | 数据已存在 |
| `40400` | 数据不存在 |
| `40401` | 返回数据异常 |
| `40402` | 数据被禁用 |
| `40403` | 上游服务超时 |
| `50000` | 服务异常 |
| `50001` | 不支持的操作 |
| `50002` | 服务内部变量缺失 |
| `50003` | 服务已关闭 |
| `50300` | 服务繁忙 |
### 2.5 多语言
可通过以下任一方式指定语言:
```http
Accept-Language: zh-CN
```
```text
?lang=zh_CN
```
默认 `zh_CN`。
### 2.6 分页
分页接口的请求体通常是 `Page<T>`:
```json
{
"index": 0,
"size": 16,
"equalsExample": {},
"likesExample": {},
"equalsLogic": "AND",
"likesLogic": "OR",
"orderMap": {
"created_at": "DESC"
}
}
```
- `index`:页码,**从 0 开始**,默认 `0`
- `size`:每页数量,默认 `16`;部分接口会限制最大值(例如 100)
- `equalsExample`:精确匹配示例
- `likesExample`:模糊匹配示例
- `equalsLogic`:精确条件连接方式,`AND` / `OR`
- `likesLogic`:模糊条件连接方式,`AND` / `OR`
- `orderMap`:排序字段与方向,字段通常使用数据库下划线命名
分页响应通常是 `PageResult<T>`:
```json
{
"total": 128,
"pages": 8,
"list": [],
"empty": false,
"notEmpty": true
}
```
---
## 3. 特殊响应类型
### 3.1 二进制响应
部分接口直接返回二进制数据或字节流,不经过 `TimiResponse`:
- 成功时直接返回字节流
- 失败时使用标准 HTTP 状态码,例如 `400`、`403`、`404`、`500`
- 响应头可能包含 `Content-Type`、`Content-Length`、`Content-Disposition`、`ETag`、`Last-Modified`、`Accept-Ranges`、`Content-Range`
- 前端应使用 `blob` / `arrayBuffer`,不能按 JSON 解析
具体哪些接口属于二进制响应,以 OpenAPI 中定义的响应 `Content-Type` 为准。
#### 缩略图预览
`GET /system/file/preview/{path}` 仅支持图片和视频,其他类型返回 `400`。图片和视频统一返回缩略图:
- `size`:缩略图最大边长(像素),范围 `32-512`,默认 `256`
- `v`:缓存版本号,建议传文件列表返回的 `etag`;传入后响应使用一年强缓存,不传时缓存一天
- 响应 `Content-Type` 为 `image/jpeg` 或 `image/png`;PNG/GIF 源图使用 PNG,其余使用 JPEG
- 支持 `If-None-Match` 条件请求,`ETag` 已包含缩略图尺寸和算法版本
### 3.2 SSE
部分长任务接口使用 `text/event-stream`,不经过 `TimiResponse`。事件类型如下:
| event | 说明 |
| --- | --- |
| `snapshot` | 连接建立后的当前任务快照 |
| `progress` | 状态或进度发生变化 |
| `heartbeat` | 心跳,约 15 秒一次 |
| `done` | 任务成功,随后服务端关闭连接 |
| `error` | 任务失败、被中断、死亡,或订阅异常,随后关闭连接 |
说明:
- 事件 `data` 是 JSON,字段和状态枚举以 OpenAPI 中对应的任务模型为准。
- 任务结束后服务端主动关闭连接;断线后可回退到 OpenAPI 中的任务详情接口轮询。
- 浏览器原生 `EventSource` 不能设置 `Token` 请求头,使用查询参数传递令牌。
```ts
const source = new EventSource(`${sseUrl}?token=${encodeURIComponent(token)}`);
source.addEventListener("progress", (event) => {
const task = JSON.parse(event.data);
console.log(task.progress, task.status);
});
source.addEventListener("done", (event) => {
const task = JSON.parse(event.data);
source.close();
});
```
其中 `sseUrl` 从 OpenAPI 中对应的 SSE 接口获取。
---
## 4. AI Agent 对接建议
1. **优先使用导出的 OpenAPI 文件**,不要只给 `localhost` URL。远程 Agent 无法访问本机地址。可先读 `docs/openapi.index.md` 定位模块和接口,再读取 OpenAPI 中的对应片段,避免整份文档占用上下文。
2. 用 OpenAPI 生成 TypeScript 类型和请求客户端,再在客户端层统一补充 `TimiResponse` 包装。
3. 不要假设 OpenAPI 的返回类型就是最终响应体;普通 JSON 接口需要取 `data`。
4. 二进制接口单独处理:使用 `blob` / `arrayBuffer`,按 HTTP 状态判断成败。
5. SSE 单独处理:使用 `EventSource` 或 fetch 流式读取,`Token` 放查询参数。
6. 分页接口使用 `Page<T>` / `PageResult<T>`,`index` 从 0 开始。
7. 业务错误优先看 `code`,不要只看 HTTP 状态。
8. 接口路径、参数和字段结构以 OpenAPI 为准,不要根据本文猜测。
推荐给 AI Agent 的简要约束:
```text
这是一个 Spring Boot 接口项目。接口路径、参数和响应结构以 OpenAPI 为准。
普通 JSON 接口返回 TimiResponse 包装:{ code, message?, messageCode?, data? },
code <= 30000 表示成功。鉴权使用 Token 请求头。
二进制接口不包装,按 HTTP 状态判断;SSE 接口不包装,Token 放查询参数。
分页请求使用 Page<T>,index 从 0 开始。
```
---
## 5. 已知限制
- OpenAPI 的响应 Schema 不包含 `TimiResponse` 包装。
- 只有文件、异步任务与系统设置模块的 8 个 Controller 有较完整的中文接口描述,其他模块为基础自动生成信息。
- 二进制接口的响应体无法在 OpenAPI 中完整表达,需结合本文和实际响应头处理。
- OpenAPI 全局声明了 `Token`,公开接口的实际鉴权行为以接口为准。
- 当前没有提交固定的 `docs/openapi.yaml` 版本化文件;需要时使用导出脚本生成本地快照,或后续接入 CI 导出。
- `docs/openapi.index.md` 从本地 OpenAPI 快照生成,接口变更后需重新执行导出脚本更新;索引只提供定位信息,字段定义以 OpenAPI 原文为准。
+814
View File
@@ -0,0 +1,814 @@
# TimiServerAPI 接口索引
> 本文件由 `scripts/openapi-index.py` 从 OpenAPI 快照生成,请勿手工编辑。
> 数据来源:`docs/openapi.local.yaml`。完整字段定义以 OpenAPI 原文为准。
- 服务版本:`1.0.79`
- OpenAPI 版本:`3.1.0`
- 路径数:464
- 接口数:466(同一路径的同一处理器会合并多个 HTTP 方法)
- 模块数:36
## 使用说明
- 先按模块定位接口,再读取 `docs/openapi.local.yaml` 中对应的 `path` 或 `components/schemas`,不要整文件加载。
- 参数列中 `*` 表示必填;`header:`、`cookie:` 为参数位置前缀,其余为 path/query 参数。
- 摘要前的 `[公开]` 表示 OpenAPI 中显式标记为无需登录;未标记的接口默认使用 `Token` 鉴权。
- 方法列出现多个 HTTP 方法,表示 Controller 使用了未限定 method 的 `@RequestMapping`。
- 请求体和响应列展示顶层 schema 名称;`binary` 表示二进制响应,`SSE` 表示 `text/event-stream`。
- 普通 JSON 接口的响应仍由 `TimiResponse` 包装,鉴权、错误码、分页等约定见 `docs/api-integration.md`。
## 模块导航
| 模块 | 接口数 | 路径前缀 |
| --- | ---: | --- |
| [`gao-ai`](#module-gao-ai) | 8 | `/gao/ai/` |
| [`gao-customer`](#module-gao-customer) | 41 | `/gao/customer/` |
| [`gao-data-export`](#module-gao-data-export) | 3 | `/gao/data-export/` |
| [`gao-event`](#module-gao-event) | 20 | `/gao/event/` |
| [`gao-fund`](#module-gao-fund) | 5 | `/gao/fund/` |
| [`gao-notify`](#module-gao-notify) | 2 | `/gao/notify/` |
| [`gao-order`](#module-gao-order) | 13 | `/gao/order/` |
| [`gao-package`](#module-gao-package) | 6 | `/gao/package/` |
| [`gao-point`](#module-gao-point) | 11 | `/gao/point/` |
| [`gao-product`](#module-gao-product) | 51 | `/gao/product/` |
| [`gao-recycle`](#module-gao-recycle) | 32 | `/gao/recycle/` |
| [`gao-report`](#module-gao-report) | 1 | `/gao/report/` |
| [`gao-role`](#module-gao-role) | 2 | `/gao/role/` |
| [`gao-sales`](#module-gao-sales) | 27 | `/gao/sales/` |
| [`gao-store`](#module-gao-store) | 28 | `/gao/store/` |
| [`gao-tag`](#module-gao-tag) | 7 | `/gao/tag/` |
| [`gao-user`](#module-gao-user) | 10 | `/gao/user/` |
| [`system`](#module-system) | 48 | `/system/` |
| [`user`](#module-user) | 44 | `/user/` |
| [`app`](#module-app) | 13 | `/app/` |
| [`.well-known`](#module-.well-known) | 6 | `/.well-known/` |
| [`article`](#module-article) | 5 | `/article/` |
| [`attach`](#module-attach) | 14 | `/attach/` |
| [`captcha`](#module-captcha) | 2 | `/captcha/` |
| [`comment`](#module-comment) | 13 | `/comment/` |
| [`feedback`](#module-feedback) | 5 | `/feedback/` |
| [`fmc`](#module-fmc) | 1 | `/fmc/` |
| [`icon`](#module-icon) | 4 | `/icon/` |
| [`journal`](#module-journal) | 7 | `/journal/` |
| [`log`](#module-log) | 1 | `/log/` |
| [`mcp`](#module-mcp) | 5 | `/mcp/` |
| [`mirror`](#module-mirror) | 2 | `/mirror/` |
| [`notify`](#module-notify) | 15 | `/notify/` |
| [`root`](#module-root) | 1 | `/` |
| [`setting`](#module-setting) | 6 | `/setting/` |
| [`tag`](#module-tag) | 7 | `/tag/` |
<a id="module-gao-ai"></a>
## gao-ai
共 8 个接口,路径前缀 `/gao/ai/`。
| 方法 | 路径 | 摘要 | 参数 | 请求体 | 响应 | Tag |
| --- | --- | --- | --- | --- | --- | --- |
| POST | `/gao/ai/attachment/upload` | upload | storeId | object{file} (multipart/form-data) | Array<GaoAiAttachmentView> | gao-ai-operation-controller |
| POST | `/gao/ai/chat` | chat | - | GaoAiChatRequest | SSE | gao-ai-chat-controller |
| POST | `/gao/ai/conversation/delete` | deleteConversation | conversationId* | - | - | gao-ai-chat-controller |
| POST | `/gao/ai/conversation/list` | listConversation | - | GaoAiConversationListRequest | JsonNode | gao-ai-chat-controller |
| POST | `/gao/ai/conversation/read` | readConversation | - | GaoAiConversationReadRequest | JsonNode | gao-ai-chat-controller |
| POST | `/gao/ai/operation/cancel` | cancel | - | GaoAiOperationCommitRequest | GaoAiToolResult | gao-ai-operation-controller |
| POST | `/gao/ai/operation/commit` | commit | - | GaoAiOperationCommitRequest | GaoAiToolResult | gao-ai-operation-controller |
| GET | `/gao/ai/operation/pending` | pending | conversationId, storeId | - | GaoAiToolResult | gao-ai-operation-controller |
<a id="module-gao-customer"></a>
## gao-customer
共 41 个接口,路径前缀 `/gao/customer/`。
| 方法 | 路径 | 摘要 | 参数 | 请求体 | 响应 | Tag |
| --- | --- | --- | --- | --- | --- | --- |
| POST | `/gao/customer/chart/customer/disease/word` | customerDiseaseWord | - | GaoCustomerDiseaseWordReq | Array<GaoCustomerDiseaseWordView> | gao-customer-chart-controller |
| POST | `/gao/customer/chart/event/record/calendar` | eventRecordCalendar | - | GaoCustomerChartReq | Array<GaoEventRecordCalendarView> | gao-customer-chart-controller |
| POST | `/gao/customer/chart/event/record/daily` | eventRecordDaily | - | GaoCustomerChartReq | Array<GaoEventRecordDailyStatView> | gao-customer-chart-controller |
| POST | `/gao/customer/consumption-record/list` | list | - | GaoCustomerConsumptionRecordPage | GaoCustomerConsumptionRecordPageResult | gao-customer-consumption-record-controller |
| POST | `/gao/customer/create` | create | - | GaoCustomer_Public | string | gao-customer-controller |
| POST | `/gao/customer/delete` | delete | id* | - | - | gao-customer-controller |
| POST | `/gao/customer/detail` | detail | id* | - | GaoCustomer_Public | gao-customer-controller |
| POST | `/gao/customer/find/code` | findByCode | storeId*, code* | - | GaoCustomer_Public | gao-customer-controller |
| POST | `/gao/customer/find/id` | findById | id* | - | GaoCustomer_Public | gao-customer-controller |
| POST | `/gao/customer/find/name` | findByName | storeId*, name* | - | GaoCustomer_Public | gao-customer-controller |
| POST | `/gao/customer/follow-up-reminder/complete` | complete | id* | - | - | gao-customer-follow-up-reminder-controller |
| POST | `/gao/customer/follow-up-reminder/create` | create | - | GaoCustomerFollowUpReminder | string | gao-customer-follow-up-reminder-controller |
| POST | `/gao/customer/follow-up-reminder/delete` | delete | id* | - | - | gao-customer-follow-up-reminder-controller |
| POST | `/gao/customer/follow-up-reminder/detail` | detail | id* | - | GaoCustomerFollowUpReminder_Public | gao-customer-follow-up-reminder-controller |
| POST | `/gao/customer/follow-up-reminder/list` | list | - | GaoCustomerFollowUpReminderPage_Public | GaoCustomerFollowUpReminderPageResult_Public | gao-customer-follow-up-reminder-controller |
| POST | `/gao/customer/follow-up-reminder/update` | update | - | GaoCustomerFollowUpReminder | - | gao-customer-follow-up-reminder-controller |
| POST | `/gao/customer/invite/delete` | deleteInvite | customerId* | - | - | gao-customer-controller |
| POST | `/gao/customer/invite/save` | saveInvite | introducerCustomerId*, customerId* | - | - | gao-customer-controller |
| POST | `/gao/customer/invited/list` | listInvited | introducerCustomerId* | - | Array<GaoCustomer_Public> | gao-customer-controller |
| POST | `/gao/customer/list` | list | - | GaoCustomerPage_Public | PageResultGaoCustomer_Public | gao-customer-controller |
| POST | `/gao/customer/package/cancel` | cancel | - | GaoCustomerPackageCancelRequest | GaoCustomerPackage | gao-customer-package-controller |
| POST | `/gao/customer/package/detail` | detail | id* | - | GaoCustomerPackage | gao-customer-package-controller |
| POST | `/gao/customer/package/list` | list | - | GaoCustomerPackagePage | PageResultGaoCustomerPackage | gao-customer-package-controller |
| POST | `/gao/customer/package/purchase` | purchase | - | GaoCustomerPackagePurchaseRequest | GaoCustomerPackage | gao-customer-package-controller |
| POST | `/gao/customer/point/account/detail` | detailById | id*, storeId | - | GaoPointAccount | gao-point-account-controller |
| POST | `/gao/customer/point/account/detail/customer` | detail | customerId*, storeId | - | GaoPointAccount | gao-point-account-controller |
| POST | `/gao/customer/point/account/list` | list | - | GaoPointAccountPage | PageResultGaoPointAccount | gao-point-account-controller |
| POST | `/gao/customer/point/adjust` | adjust | - | GaoPointAdjustRequest | - | gao-point-ledger-controller |
| POST | `/gao/customer/point/ledger/detail` | detail | id*, storeId | - | GaoPointLedger | gao-point-ledger-controller |
| POST | `/gao/customer/point/ledger/list` | list | - | GaoPointLedgerPage | PageResultGaoPointLedger | gao-point-ledger-controller |
| POST | `/gao/customer/point/rule/create` | create | - | GaoPointRule | string | gao-point-rule-controller |
| POST | `/gao/customer/point/rule/delete` | delete | id* | - | - | gao-point-rule-controller |
| POST | `/gao/customer/point/rule/detail` | detail | id* | - | GaoPointRule | gao-point-rule-controller |
| POST | `/gao/customer/point/rule/list` | list | - | PageGaoPointRule | PageResultGaoPointRule | gao-point-rule-controller |
| POST | `/gao/customer/point/rule/script/list` | scriptList | - | - | Array<GroovyScript> | gao-point-rule-controller |
| POST | `/gao/customer/point/rule/sort` | sort | - | Array<string> | - | gao-point-rule-controller |
| POST | `/gao/customer/point/rule/update` | update | - | GaoPointRule | - | gao-point-rule-controller |
| POST | `/gao/customer/profile/pdf` | pdf | id* | - | - | gao-customer-profile-controller |
| POST | `/gao/customer/state/daily` | dailyStat | - | GaoCustomerTrendStateReq | Array<GaoCustomerDailyStateView> | gao-customer-controller |
| POST | `/gao/customer/state/gender` | genderStat | storeId* | - | Array<GaoCustomerGenderStatView> | gao-customer-controller |
| POST | `/gao/customer/update` | update | - | GaoCustomer | - | gao-customer-controller |
<a id="module-gao-data-export"></a>
## gao-data-export
共 3 个接口,路径前缀 `/gao/data-export/`。
| 方法 | 路径 | 摘要 | 参数 | 请求体 | 响应 | Tag |
| --- | --- | --- | --- | --- | --- | --- |
| POST | `/gao/data-export/stat` | stat | - | GaoDataExportStatRequest | GaoDataExportStatView | gao-data-export-controller |
| POST | `/gao/data-export/task` | create | - | GaoDataExportCreateRequest | GaoDataExportTaskView | gao-data-export-controller |
| GET | `/gao/data-export/task/{taskId}` | detail | taskId* | - | GaoDataExportTaskView | gao-data-export-controller |
<a id="module-gao-event"></a>
## gao-event
共 20 个接口,路径前缀 `/gao/event/`。
| 方法 | 路径 | 摘要 | 参数 | 请求体 | 响应 | Tag |
| --- | --- | --- | --- | --- | --- | --- |
| POST | `/gao/event/create` | create | - | GaoEvent | - | gao-event-controller |
| POST | `/gao/event/delete` | delete | id* | - | - | gao-event-controller |
| POST | `/gao/event/detail` | detail | id* | - | GaoEvent | gao-event-controller |
| POST | `/gao/event/list` | list | - | PageGaoEvent | PageResultGaoEvent | gao-event-controller |
| POST | `/gao/event/list/history` | listHistory | - | PageGaoEvent | PageResultGaoEvent | gao-event-controller |
| POST | `/gao/event/list/valid` | listValid | storeId* | - | Array<GaoEvent> | gao-event-controller |
| POST | `/gao/event/options/update` | updateOptions | id* | Array<GaoEventOptionGroup> | - | gao-event-controller |
| POST | `/gao/event/record/create` | create | - | GaoEventRecord | - | gao-event-record-controller |
| POST | `/gao/event/record/create/batch` | createBatch | - | Array<GaoEventRecord> | - | gao-event-record-controller |
| POST | `/gao/event/record/create/customer` | createWithCustomer | - | GaoCustomer | - | gao-event-record-controller |
| POST | `/gao/event/record/delete` | delete | id* | - | - | gao-event-record-controller |
| POST | `/gao/event/record/detail` | detail | id* | - | GaoEventRecord_Public | gao-event-record-controller |
| POST | `/gao/event/record/list` | list | - | GaoEventRecordPage_Public | GaoEventRecordPageResult_Public | gao-event-record-controller |
| POST | `/gao/event/record/month/pdf` | export | eventId*, month* | - | - | gao-event-month-export-controller |
| POST | `/gao/event/record/option/stat` | optionStat | - | GaoEventRecordPage | Array<GaoEventOptionStatView> | gao-event-record-controller |
| POST | `/gao/event/record/rank` | eventRank | - | GaoEventRecordRankPage | PageResultGaoCustomerEventRankView | gao-event-record-controller |
| POST | `/gao/event/record/update` | update | - | GaoEventRecord | - | gao-event-record-controller |
| POST | `/gao/event/record/verify` | verify | id* | - | - | gao-event-record-controller |
| POST | `/gao/event/sort` | sort | - | Array<string> | - | gao-event-controller |
| POST | `/gao/event/update` | update | - | GaoEvent | - | gao-event-controller |
<a id="module-gao-fund"></a>
## gao-fund
共 5 个接口,路径前缀 `/gao/fund/`。
| 方法 | 路径 | 摘要 | 参数 | 请求体 | 响应 | Tag |
| --- | --- | --- | --- | --- | --- | --- |
| POST | `/gao/fund/record/detail` | detail | id* | - | GaoFundRecord | gao-fund-record-controller |
| POST | `/gao/fund/record/list` | list | - | GaoFundRecordPage | PageResultGaoFundRecord | gao-fund-record-controller |
| POST | `/gao/fund/record/my-receive/detail` | detailMyReceive | id* | - | GaoFundRecord | gao-fund-record-controller |
| POST | `/gao/fund/record/my-receive/list` | listMyReceive | - | GaoFundRecordPage | PageResultGaoFundRecord | gao-fund-record-controller |
| POST | `/gao/fund/record/revoke` | revoke | - | GaoFundRevokeRequest | GaoFundRecord | gao-fund-record-controller |
<a id="module-gao-notify"></a>
## gao-notify
共 2 个接口,路径前缀 `/gao/notify/`。
| 方法 | 路径 | 摘要 | 参数 | 请求体 | 响应 | Tag |
| --- | --- | --- | --- | --- | --- | --- |
| POST | `/gao/notify/create` | create | - | Notify | Notify | gao-notify-controller |
| POST | `/gao/notify/recipient/list` | recipientList | - | PageGaoUser_Public | PageResultGaoUser_Public | gao-notify-controller |
<a id="module-gao-order"></a>
## gao-order
共 13 个接口,路径前缀 `/gao/order/`。
| 方法 | 路径 | 摘要 | 参数 | 请求体 | 响应 | Tag |
| --- | --- | --- | --- | --- | --- | --- |
| POST | `/gao/order/fulfillment/cancel` | cancel | - | GaoOrderFulfillmentActionRequest | GaoOrderFulfillment | gao-order-fulfillment-controller |
| POST | `/gao/order/fulfillment/create` | create | - | GaoOrderFulfillmentCreateRequest | GaoOrderFulfillment | gao-order-fulfillment-controller |
| POST | `/gao/order/fulfillment/create-and-verify` | createAndVerify | - | GaoOrderFulfillmentCreateRequest | GaoOrderFulfillment | gao-order-fulfillment-controller |
| POST | `/gao/order/fulfillment/detail` | detail | id* | - | GaoOrderFulfillment | gao-order-fulfillment-controller |
| POST | `/gao/order/fulfillment/list` | list | - | GaoOrderFulfillmentPage | PageResultGaoOrderFulfillment | gao-order-fulfillment-controller |
| POST | `/gao/order/fulfillment/prepare-stock` | prepareStock | - | GaoOrderFulfillmentPrepareStockRequest | GaoOrderFulfillment | gao-order-fulfillment-controller |
| POST | `/gao/order/fulfillment/quick/create` | createQuickFulfillment | - | GaoQuickFulfillmentCreateRequest | Array<GaoOrderFulfillment> | gao-order-fulfillment-controller |
| POST | `/gao/order/fulfillment/quick/sku-list` | listQuickFulfillmentSku | - | GaoQuickFulfillmentCustomerRequest | Array<GaoQuickFulfillmentSkuView> | gao-order-fulfillment-controller |
| POST | `/gao/order/fulfillment/quick/source-order-list` | listQuickFulfillmentSourceOrder | - | GaoQuickFulfillmentSourceOrderListRequest | Array<GaoQuickFulfillmentSourceOrderView> | gao-order-fulfillment-controller |
| POST | `/gao/order/fulfillment/reject` | reject | - | GaoOrderFulfillmentActionRequest | GaoOrderFulfillment | gao-order-fulfillment-controller |
| POST | `/gao/order/fulfillment/return` | returnGoods | - | GaoOrderFulfillmentReturnRequest | GaoOrderFulfillment | gao-order-fulfillment-controller |
| POST | `/gao/order/fulfillment/revoke` | revoke | - | GaoOrderFulfillmentRevokeRequest | GaoOrderFulfillment | gao-order-fulfillment-controller |
| POST | `/gao/order/fulfillment/verify` | verify | - | GaoOrderFulfillmentActionRequest | GaoOrderFulfillment | gao-order-fulfillment-controller |
<a id="module-gao-package"></a>
## gao-package
共 6 个接口,路径前缀 `/gao/package/`。
| 方法 | 路径 | 摘要 | 参数 | 请求体 | 响应 | Tag |
| --- | --- | --- | --- | --- | --- | --- |
| POST | `/gao/package/config/create` | create | - | GaoPackageConfig | string | gao-package-config-controller |
| POST | `/gao/package/config/delete` | delete | id* | - | - | gao-package-config-controller |
| POST | `/gao/package/config/detail` | detail | id* | - | GaoPackageConfig | gao-package-config-controller |
| POST | `/gao/package/config/list` | list | - | GaoPackageConfigPage | PageResultGaoPackageConfig | gao-package-config-controller |
| POST | `/gao/package/config/list/valid` | listValid | storeId* | - | Array<GaoPackageConfig> | gao-package-config-controller |
| POST | `/gao/package/config/update` | update | - | GaoPackageConfig | - | gao-package-config-controller |
<a id="module-gao-point"></a>
## gao-point
共 11 个接口,路径前缀 `/gao/point/`。
| 方法 | 路径 | 摘要 | 参数 | 请求体 | 响应 | Tag |
| --- | --- | --- | --- | --- | --- | --- |
| POST | `/gao/point/redeem-sku/create` | create | - | GaoPointRedeemSkuRequest | GaoPointRedeemSku | gao-point-redeem-sku-controller |
| POST | `/gao/point/redeem-sku/delete` | delete | id*, storeId | - | - | gao-point-redeem-sku-controller |
| POST | `/gao/point/redeem-sku/detail` | detail | id*, storeId | - | GaoPointRedeemSku | gao-point-redeem-sku-controller |
| POST | `/gao/point/redeem-sku/disable` | disable | id*, storeId | - | - | gao-point-redeem-sku-controller |
| POST | `/gao/point/redeem-sku/list` | list | - | GaoPointRedeemSkuPage | GaoPointRedeemSkuPageResult | gao-point-redeem-sku-controller |
| POST | `/gao/point/redeem-sku/update` | update | - | GaoPointRedeemSkuRequest | GaoPointRedeemSku | gao-point-redeem-sku-controller |
| POST | `/gao/point/redemption/create` | create | - | GaoPointRedemptionCreateRequest | GaoPointRedemption | gao-point-redemption-controller |
| POST | `/gao/point/redemption/detail` | detail | id*, storeId | - | GaoPointRedemption | gao-point-redemption-controller |
| POST | `/gao/point/redemption/list` | list | - | GaoPointRedemptionPage | PageResultGaoPointRedemption | gao-point-redemption-controller |
| POST | `/gao/point/redemption/return` | returnRedemption | - | GaoPointRedemptionReturnRequest | GaoPointRedemption | gao-point-redemption-controller |
| POST | `/gao/point/redemption/return/list` | returnList | redemptionId*, storeId | - | Array<GaoPointRedemptionReturn> | gao-point-redemption-controller |
<a id="module-gao-product"></a>
## gao-product
共 51 个接口,路径前缀 `/gao/product/`。
| 方法 | 路径 | 摘要 | 参数 | 请求体 | 响应 | Tag |
| --- | --- | --- | --- | --- | --- | --- |
| POST | `/gao/product/category/create` | categoryCreate | - | GaoProductCategory | string | gao-product-controller |
| POST | `/gao/product/category/disable` | categoryDisable | id* | - | - | gao-product-controller |
| POST | `/gao/product/category/list` | categoryList | - | GaoProductCategoryPage | PageResultGaoProductCategory | gao-product-controller |
| POST | `/gao/product/category/sort` | categorySort | - | Array<string> | - | gao-product-controller |
| POST | `/gao/product/category/update` | categoryUpdate | - | GaoProductCategory | - | gao-product-controller |
| POST | `/gao/product/chart/fulfillment/daily` | fulfillmentDaily | - | GaoProductChartReq | Array<GaoProductFulfillmentDailyStatView> | gao-product-chart-controller |
| POST | `/gao/product/chart/fulfillment/rank` | fulfillmentRank | - | GaoProductChartReq | Array<GaoProductFulfillmentRankView> | gao-product-chart-controller |
| POST | `/gao/product/chart/sales/daily` | salesDaily | - | GaoProductChartReq | Array<GaoProductSalesDailyStatView> | gao-product-chart-controller |
| POST | `/gao/product/chart/sales/rank` | salesRank | - | GaoProductChartReq | Array<GaoProductSalesRankView> | gao-product-chart-controller |
| POST | `/gao/product/chart/sales/unit/rank` | unitSalesRank | - | GaoProductChartReq | Array<GaoProductUnitSalesRankView> | gao-product-chart-controller |
| POST | `/gao/product/chart/stock/health` | stockHealth | - | GaoProductChartReq | Array<GaoProductStockHealthView> | gao-product-chart-controller |
| POST | `/gao/product/chart/stock/movement/daily` | stockMovementDaily | - | GaoProductChartReq | Array<GaoProductStockMovementDailyStatView> | gao-product-chart-controller |
| POST | `/gao/product/chart/structure/category` | category | - | GaoProductChartReq | Array<GaoProductCategoryStatView> | gao-product-chart-controller |
| POST | `/gao/product/chart/structure/type` | type | - | GaoProductChartReq | Array<GaoProductTypeStatView> | gao-product-chart-controller |
| POST | `/gao/product/create` | create | - | GaoProduct | string | gao-product-controller |
| POST | `/gao/product/delete` | delete | id* | - | - | gao-product-controller |
| POST | `/gao/product/detail` | detail | id* | - | GaoProduct | gao-product-controller |
| POST | `/gao/product/disable` | disable | id* | - | - | gao-product-controller |
| POST | `/gao/product/list` | list | - | GaoProductPage | PageResultGaoProduct | gao-product-controller |
| POST | `/gao/product/sellable/list` | sellableList | - | GaoProductPage | Array<GaoProduct> | gao-product-controller |
| POST | `/gao/product/sku/chart/fulfillment/daily` | fulfillmentDaily | - | GaoProductChartReq | Array<GaoProductSkuFulfillmentDailyStatView> | gao-product-sku-chart-controller |
| POST | `/gao/product/sku/chart/fulfillment/rank` | fulfillmentRank | - | GaoProductChartReq | Array<GaoProductSkuFulfillmentRankView> | gao-product-sku-chart-controller |
| POST | `/gao/product/sku/chart/sales/daily` | salesDaily | - | GaoProductChartReq | Array<GaoProductSkuSalesDailyStatView> | gao-product-sku-chart-controller |
| POST | `/gao/product/sku/chart/sales/rank` | salesRank | - | GaoProductChartReq | Array<GaoProductSkuSalesRankView> | gao-product-sku-chart-controller |
| POST | `/gao/product/sku/chart/sales/unit/rank` | unitSalesRank | - | GaoProductChartReq | Array<GaoProductSkuUnitSalesRankView> | gao-product-sku-chart-controller |
| POST | `/gao/product/sku/chart/stock/health` | stockHealth | - | GaoProductChartReq | Array<GaoProductSkuStockHealthView> | gao-product-sku-chart-controller |
| POST | `/gao/product/sku/chart/stock/movement/daily` | stockMovementDaily | - | GaoProductChartReq | Array<GaoProductSkuStockMovementDailyStatView> | gao-product-sku-chart-controller |
| POST | `/gao/product/sku/create` | skuCreate | - | GaoProductSku | string | gao-product-controller |
| POST | `/gao/product/sku/detail` | skuDetail | id* | - | GaoProductSku | gao-product-controller |
| POST | `/gao/product/sku/disable` | skuDisable | id* | - | - | gao-product-controller |
| POST | `/gao/product/sku/fulfillment-list` | skuFulfillmentList | - | Array<string> | Array<GaoProductSkuFulfillmentView> | gao-product-controller |
| POST | `/gao/product/sku/update` | skuUpdate | - | GaoProductSku | - | gao-product-controller |
| POST | `/gao/product/spec/create` | specCreate | - | GaoProductSpec | string | gao-product-controller |
| POST | `/gao/product/spec/list` | specList | productId* | - | Array<GaoProductSpec> | gao-product-controller |
| POST | `/gao/product/spec/update` | specUpdate | - | GaoProductSpec | - | gao-product-controller |
| POST | `/gao/product/spec/value/create` | specValueCreate | - | GaoProductSpecValue | string | gao-product-controller |
| POST | `/gao/product/spec/value/update` | specValueUpdate | - | GaoProductSpecValue | - | gao-product-controller |
| POST | `/gao/product/stock/batch-detail` | batchDetail | - | GaoProductStockBatchRequest | Array<GaoProductStock> | gao-product-stock-controller |
| POST | `/gao/product/stock/detail` | detail | storeId, skuId* | - | GaoProductStock | gao-product-stock-controller |
| POST | `/gao/product/stock/initial-in` | initialIn | - | GaoProductStockChangeRequest | GaoProductStock | gao-product-stock-controller |
| POST | `/gao/product/stock/list` | list | - | GaoProductStockPage | PageResultGaoProductStock | gao-product-stock-controller |
| POST | `/gao/product/stock/manual-in` | manualIn | - | GaoProductStockChangeRequest | GaoProductStock | gao-product-stock-controller |
| POST | `/gao/product/stock/manual-in/batch` | manualInBatch | - | GaoProductStockManualInBatchRequest | Array<GaoProductStock> | gao-product-stock-controller |
| POST | `/gao/product/stock/manual-out` | manualOut | - | GaoProductStockChangeRequest | GaoProductStock | gao-product-stock-controller |
| POST | `/gao/product/stock/manual-revoke` | manualRevoke | - | GaoProductStockManualRevokeRequest | GaoProductStock | gao-product-stock-controller |
| POST | `/gao/product/stock/product-list` | productList | - | GaoProductStockPage | PageResultGaoProductStockProductView | gao-product-stock-controller |
| POST | `/gao/product/stock/record/detail` | recordDetail | id* | - | GaoProductStockRecord | gao-product-stock-controller |
| POST | `/gao/product/stock/record/list` | recordList | - | GaoProductStockRecordPage | GaoProductStockRecordPageResult | gao-product-stock-controller |
| POST | `/gao/product/stock/stocktake-gain` | stocktakeGain | - | GaoProductStockChangeRequest | GaoProductStock | gao-product-stock-controller |
| POST | `/gao/product/stock/stocktake-loss` | stocktakeLoss | - | GaoProductStockChangeRequest | GaoProductStock | gao-product-stock-controller |
| POST | `/gao/product/update` | update | - | GaoProduct | - | gao-product-controller |
<a id="module-gao-recycle"></a>
## gao-recycle
共 32 个接口,路径前缀 `/gao/recycle/`。
| 方法 | 路径 | 摘要 | 参数 | 请求体 | 响应 | Tag |
| --- | --- | --- | --- | --- | --- | --- |
| POST | `/gao/recycle/account/customers` | customers | - | GaoRecycleAccountCustomerPage | GaoRecycleAccountCustomerPageResult | gao-recycle-account-controller |
| POST | `/gao/recycle/account/items` | accountItems | storeId* | - | Array<GaoRecycleItem> | gao-recycle-account-controller |
| POST | `/gao/recycle/account/list` | list | storeId*, customerId* | - | Array<GaoRecycleAccount> | gao-recycle-account-controller |
| POST | `/gao/recycle/account/yield/delete` | deleteYield | storeId*, skuId*, recycleItemId* | - | - | gao-recycle-account-controller |
| POST | `/gao/recycle/account/yield/list` | yields | storeId*, skuId* | - | Array<GaoRecycleProductYield> | gao-recycle-account-controller |
| POST | `/gao/recycle/account/yield/product/list` | yieldsByProduct | storeId*, productId* | - | Array<GaoRecycleProductYield> | gao-recycle-account-controller |
| POST | `/gao/recycle/account/yield/save` | saveYield | storeId*, skuId*, recycleItemId*, quantityPerBase* | - | - | gao-recycle-account-controller |
| POST | `/gao/recycle/config/item/detail` | itemDetail | storeId, id* | - | GaoRecycleItem | gao-recycle-config-controller |
| POST | `/gao/recycle/config/item/save` | saveItem | - | GaoRecycleItemRequest | GaoRecycleItem | gao-recycle-config-controller |
| POST | `/gao/recycle/config/items` | items | storeId, status, keyword, offset, limit | - | PageResultGaoRecycleItem | gao-recycle-config-controller |
| POST | `/gao/recycle/config/rule/delete` | deleteRule | storeId, id* | - | - | gao-recycle-config-controller |
| POST | `/gao/recycle/config/rule/detail` | ruleDetail | storeId, id* | - | GaoRecycleExchangeRule | gao-recycle-config-controller |
| POST | `/gao/recycle/config/rule/save` | saveRule | - | GaoRecycleExchangeRuleRequest | GaoRecycleExchangeRule | gao-recycle-config-controller |
| POST | `/gao/recycle/config/rules` | rules | storeId, status, recycleItemId, skuId, keyword, offset, limit | - | PageResultGaoRecycleExchangeRule | gao-recycle-config-controller |
| POST | `/gao/recycle/config/rules/active` | activeRules | storeId, recycleItemId, skuId, keyword, offset, limit | - | PageResultGaoRecycleExchangeRule | gao-recycle-config-controller |
| POST | `/gao/recycle/exchange/create` | create | - | GaoRecycleExchangeCreateRequest | GaoRecycleExchange | gao-recycle-exchange-write-controller |
| POST | `/gao/recycle/exchange/detail` | detail | id* | - | GaoRecycleExchangeDetail | gao-recycle-exchange-query-controller |
| POST | `/gao/recycle/ledger/adjust` | adjust | - | GaoRecycleAccountAdjustRequest | - | gao-recycle-ledger-controller |
| POST | `/gao/recycle/ledger/detail` | detail | id* | - | GaoRecycleLedger | gao-recycle-ledger-controller |
| POST | `/gao/recycle/ledger/list` | list | - | GaoRecycleLedgerPage | PageResultGaoRecycleLedger | gao-recycle-ledger-controller |
| POST | `/gao/recycle/payment/cancel` | cancel | - | GaoRecyclePaymentRequest | GaoRecyclePayment | gao-recycle-payment-controller |
| POST | `/gao/recycle/payment/create` | create | - | GaoRecyclePaymentRequest | GaoRecyclePayment | gao-recycle-payment-controller |
| POST | `/gao/recycle/payment/create-and-verify` | createAndVerify | - | GaoRecyclePaymentRequest | GaoRecyclePayment | gao-recycle-payment-controller |
| POST | `/gao/recycle/payment/detail` | detail | id* | - | GaoRecyclePayment | gao-recycle-payment-controller |
| POST | `/gao/recycle/payment/list` | list | orderId* | - | Array<GaoRecyclePayment> | gao-recycle-payment-controller |
| POST | `/gao/recycle/payment/reject` | reject | - | GaoRecyclePaymentRequest | GaoRecyclePayment | gao-recycle-payment-controller |
| POST | `/gao/recycle/payment/revoke` | revoke | - | GaoRecyclePaymentRequest | GaoRecyclePayment | gao-recycle-payment-controller |
| POST | `/gao/recycle/payment/search` | search | storeId, customerId, orderId, status, beginAt, endAt, offset, limit | - | Array<GaoRecyclePayment> | gao-recycle-payment-controller |
| POST | `/gao/recycle/payment/transactions` | transactions | orderId* | - | Array<GaoOrderTransactionView> | gao-recycle-payment-controller |
| POST | `/gao/recycle/payment/verify` | verify | - | GaoRecyclePaymentRequest | GaoRecyclePayment | gao-recycle-payment-controller |
| POST | `/gao/recycle/stat/exchange` | exchange | storeId, startAt*, endAt* | - | Array<GaoRecycleExchangeStatView> | gao-recycle-stat-controller |
| POST | `/gao/recycle/stat/recycle` | recycle | storeId, startAt*, endAt* | - | Array<GaoRecycleStatView> | gao-recycle-stat-controller |
<a id="module-gao-report"></a>
## gao-report
共 1 个接口,路径前缀 `/gao/report/`。
| 方法 | 路径 | 摘要 | 参数 | 请求体 | 响应 | Tag |
| --- | --- | --- | --- | --- | --- | --- |
| POST | `/gao/report/options/customers` | customers | storeId, keyword, offset | - | Array<GaoReportOption> | gao-report-option-controller |
<a id="module-gao-role"></a>
## gao-role
共 2 个接口,路径前缀 `/gao/role/`。
| 方法 | 路径 | 摘要 | 参数 | 请求体 | 响应 | Tag |
| --- | --- | --- | --- | --- | --- | --- |
| POST | `/gao/role/available/list` | availableList | - | - | Array<Role> | gao-role-controller |
| POST | `/gao/role/management/list` | managementList | - | - | Array<Role> | gao-role-controller |
<a id="module-gao-sales"></a>
## gao-sales
共 27 个接口,路径前缀 `/gao/sales/`。
| 方法 | 路径 | 摘要 | 参数 | 请求体 | 响应 | Tag |
| --- | --- | --- | --- | --- | --- | --- |
| POST | `/gao/sales/order/cancel` | cancel | - | GaoSalesOrderCancelRequest | GaoSalesOrder | gao-sales-order-controller |
| POST | `/gao/sales/order/chart/customer/calendar` | calendar | - | GaoSalesOrderChartReq | Array<GaoSalesOrderCalendarStatView> | gao-sales-order-chart-controller |
| POST | `/gao/sales/order/chart/customer/consumption/daily` | consumptionDaily | - | GaoSalesOrderChartReq | Array<GaoSalesOrderConsumptionDailyStatView> | gao-sales-order-chart-controller |
| POST | `/gao/sales/order/chart/customer/product/rank` | customerProductRank | - | GaoSalesOrderChartReq | Array<GaoCustomerOrderProductRankView> | gao-sales-order-chart-controller |
| POST | `/gao/sales/order/chart/customer/rank` | customerRank | - | GaoSalesOrderChartReq | Array<GaoCustomerOrderRankView> | gao-sales-order-chart-controller |
| POST | `/gao/sales/order/chart/customer/repeat/daily` | repeatDaily | - | GaoSalesOrderChartReq | Array<GaoCustomerRepeatDailyStatView> | gao-sales-order-chart-controller |
| POST | `/gao/sales/order/chart/customer/repeat/interval` | repeatInterval | - | GaoSalesOrderChartReq | Array<GaoCustomerRepeatIntervalStatView> | gao-sales-order-chart-controller |
| POST | `/gao/sales/order/chart/customer/sku/rank` | customerSkuRank | - | GaoSalesOrderChartReq | Array<GaoCustomerOrderSkuRankView> | gao-sales-order-chart-controller |
| POST | `/gao/sales/order/chart/daily` | daily | - | GaoSalesOrderChartReq | Array<GaoSalesOrderDailyStatView> | gao-sales-order-chart-controller |
| POST | `/gao/sales/order/chart/payment` | payment | - | GaoSalesOrderChartReq | Array<GaoSalesOrderPaymentStatView> | gao-sales-order-chart-controller |
| POST | `/gao/sales/order/chart/receivable` | receivable | - | GaoSalesOrderChartReq | GaoSalesOrderReceivableStatView | gao-sales-order-chart-controller |
| POST | `/gao/sales/order/chart/status` | status | - | GaoSalesOrderChartReq | Array<GaoSalesOrderStatusStatView> | gao-sales-order-chart-controller |
| POST | `/gao/sales/order/chart/type` | type | - | GaoSalesOrderChartReq | Array<GaoSalesOrderTypeStatView> | gao-sales-order-chart-controller |
| POST | `/gao/sales/order/customer-product/list` | customerProductList | - | GaoCustomerProductPage | PageResultGaoCustomerProductCustomerView | gao-sales-order-controller |
| POST | `/gao/sales/order/detail` | detail | id* | - | GaoSalesOrder | gao-sales-order-controller |
| POST | `/gao/sales/order/direct-product/create` | createDirectProduct | - | GaoDirectProductOrderCreateRequest | GaoSalesOrder | gao-sales-order-controller |
| POST | `/gao/sales/order/fund/revoke` | revoke | - | GaoOrderPaymentRevokeRequest | GaoFundRecord | gao-sales-order-controller |
| POST | `/gao/sales/order/list` | list | - | GaoSalesOrderPage | PageResultGaoSalesOrder | gao-sales-order-controller |
| POST | `/gao/sales/order/payment/cancel` | cancelPayment | - | GaoOrderPaymentActionRequest | GaoFundRecord | gao-sales-order-controller |
| POST | `/gao/sales/order/payment/receive` | receive | - | GaoOrderPaymentReceiveRequest | GaoFundRecord | gao-sales-order-controller |
| POST | `/gao/sales/order/payment/receive-and-verify` | receiveAndVerify | - | GaoOrderPaymentReceiveRequest | GaoFundRecord | gao-sales-order-controller |
| POST | `/gao/sales/order/payment/reject` | reject | - | GaoOrderPaymentActionRequest | GaoFundRecord | gao-sales-order-controller |
| POST | `/gao/sales/order/payment/verify` | verify | id* | - | GaoFundRecord | gao-sales-order-controller |
| POST | `/gao/sales/order/refund` | refund | - | GaoOrderPaymentRefundRequest | GaoFundRecord | gao-sales-order-controller |
| POST | `/gao/sales/order/refund/confirm-none` | confirmNoRefund | - | GaoOrderPaymentNoRefundRequest | GaoFundRecord | gao-sales-order-controller |
| POST | `/gao/sales/order/summary` | summary | - | GaoSalesOrderPage | GaoSalesOrderReceivableStatView | gao-sales-order-controller |
| POST | `/gao/sales/order/update` | update | - | GaoSalesOrderUpdateRequest | GaoSalesOrder | gao-sales-order-controller |
<a id="module-gao-store"></a>
## gao-store
共 28 个接口,路径前缀 `/gao/store/`。
| 方法 | 路径 | 摘要 | 参数 | 请求体 | 响应 | Tag |
| --- | --- | --- | --- | --- | --- | --- |
| POST | `/gao/store/business/day/calendar` | calendar | storeId*, beginDateValue*, endDateValue* | - | Array<GaoStoreBusinessDay> | gao-store-business-day-controller |
| POST | `/gao/store/business/day/create` | create | - | GaoStoreBusinessDay | string | gao-store-business-day-controller |
| POST | `/gao/store/business/day/delete` | delete | id* | - | - | gao-store-business-day-controller |
| POST | `/gao/store/business/day/detail` | detail | id* | - | GaoStoreBusinessDay | gao-store-business-day-controller |
| POST | `/gao/store/business/day/list` | list | - | PageGaoStoreBusinessDay | PageResultGaoStoreBusinessDay | gao-store-business-day-controller |
| POST | `/gao/store/business/day/update` | update | - | GaoStoreBusinessDay | - | gao-store-business-day-controller |
| POST | `/gao/store/chart/customer/age` | customerAge | storeId* | - | Array<GaoCustomerAgeStatView> | gao-store-chart-controller |
| POST | `/gao/store/chart/customer/daily` | customerDaily | - | GaoStoreChartReq | Array<GaoCustomerDailyStateView> | gao-store-chart-controller |
| POST | `/gao/store/chart/customer/gender` | customerGender | storeId* | - | Array<GaoCustomerGenderStatView> | gao-store-chart-controller |
| POST | `/gao/store/chart/event/record/calendar` | eventRecordCalendar | - | GaoStoreChartReq | Array<GaoEventRecordCalendarView> | gao-store-chart-controller |
| POST | `/gao/store/chart/event/record/daily` | eventRecordDaily | - | GaoStoreChartReq | Array<GaoEventRecordDailyStatView> | gao-store-chart-controller |
| POST | `/gao/store/chart/event/record/number-value/daily` | eventRecordNumberValueDaily | - | GaoStoreChartReq | Array<GaoEventRecordNumberValueDailyStatView> | gao-store-chart-controller |
| POST | `/gao/store/chart/point/ledger/daily` | pointDaily | - | GaoStoreChartReq | Array<GaoPointDailyStatView> | gao-store-chart-controller |
| POST | `/gao/store/chart/point/redemption/product/rank` | pointRedemptionProductRank | - | GaoStoreChartReq | Array<GaoPointRedemptionProductRankView> | gao-store-chart-controller |
| POST | `/gao/store/create` | create | - | GaoStore | string | gao-store-controller |
| POST | `/gao/store/delete` | delete | id* | - | - | gao-store-controller |
| POST | `/gao/store/detail` | detail | id* | - | GaoStore | gao-store-controller |
| POST | `/gao/store/diary/create` | create | - | Article | string | gao-store-diary-controller |
| POST | `/gao/store/diary/delete` | delete | id* | - | - | gao-store-diary-controller |
| POST | `/gao/store/diary/detail` | detail | id* | - | Article_Public | gao-store-diary-controller |
| POST | `/gao/store/diary/list` | list | - | GaoStoreDiaryPage_Public | PageResultArticle_Public | gao-store-diary-controller |
| POST | `/gao/store/diary/update` | update | - | Article | - | gao-store-diary-controller |
| POST | `/gao/store/list` | list | - | PageGaoStore | PageResultGaoStore | gao-store-controller |
| POST | `/gao/store/setting/map` | map | - | Array<string> | Map<String, Setting> | gao-store-setting-controller |
| POST | `/gao/store/setting/update` | update | - | Array<Setting> | - | gao-store-setting-controller |
| POST | `/gao/store/sort` | sort | - | Array<string> | - | gao-store-controller |
| POST | `/gao/store/update` | update | - | GaoStore | - | gao-store-controller |
| POST | `/gao/store/user` | getLoginStore | - | - | GaoStore | gao-store-controller |
<a id="module-gao-tag"></a>
## gao-tag
共 7 个接口,路径前缀 `/gao/tag/`。
| 方法 | 路径 | 摘要 | 参数 | 请求体 | 响应 | Tag |
| --- | --- | --- | --- | --- | --- | --- |
| POST | `/gao/tag/apply` | apply | - | TagApply | - | gao-tag-controller |
| POST | `/gao/tag/create` | create | - | Tag_Public | Tag_Public | gao-tag-controller |
| POST | `/gao/tag/delete` | delete | id* | - | - | gao-tag-controller |
| POST | `/gao/tag/detail` | detail | id* | - | Tag_Public | gao-tag-controller |
| POST | `/gao/tag/list` | list | - | PageTag_Public | PageResultTag_Public | gao-tag-controller |
| GET | `/gao/tag/list/biz/id` | listByBizType | bizType*, bizId* | - | Array<Tag_Public> | gao-tag-controller |
| POST | `/gao/tag/update` | update | - | Tag | - | gao-tag-controller |
<a id="module-gao-user"></a>
## gao-user
共 10 个接口,路径前缀 `/gao/user/`。
| 方法 | 路径 | 摘要 | 参数 | 请求体 | 响应 | Tag |
| --- | --- | --- | --- | --- | --- | --- |
| POST | `/gao/user/create` | create | - | GaoUser_Public | GaoUser_Public | gao-user-controller |
| POST | `/gao/user/delete` | delete | id* | - | - | gao-user-controller |
| POST | `/gao/user/detail` | detail | id* | - | GaoUser_Public | gao-user-controller |
| POST | `/gao/user/invite` | invite | - | GaoUserInviteCreateRequest | GaoUserInviteCreateResponse | gao-user-controller |
| POST | `/gao/user/invite/register` | registerByInvite | - | GaoUserInviteRegisterRequest_Public | LoginResponse_Public | gao-user-controller |
| POST | `/gao/user/invite/validate` | validateInvite | - | GaoUserInviteValidateRequest | GaoUserInviteValidateResponse | gao-user-controller |
| POST | `/gao/user/list` | list | - | PageGaoUser_Public | PageResultGaoUser_Public | gao-user-controller |
| POST | `/gao/user/role/list` | roleList | - | - | Array<Role> | gao-user-controller |
| POST | `/gao/user/transfer/store` | transferStore | - | GaoUser_Public | GaoUser_Public | gao-user-controller |
| POST | `/gao/user/update` | update | - | GaoUser_Public | GaoUser_Public | gao-user-controller |
<a id="module-system"></a>
## system
共 48 个接口,路径前缀 `/system/`。
| 方法 | 路径 | 摘要 | 参数 | 请求体 | 响应 | Tag |
| --- | --- | --- | --- | --- | --- | --- |
| GET | `/system/docker/container` | listContainers | - | - | Array<DockerContainerSummaryView> | docker-controller |
| GET | `/system/docker/container/{containerId}/history` | getContainerHistory | containerId*, window | - | DockerContainerHistoryView | docker-controller |
| GET | `/system/docker/container/{containerId}/status` | getContainerStatus | containerId* | - | DockerContainerStatusView | docker-controller |
| POST | `/system/file/copy` | 创建复制任务 | - | ArchiveRequest | string | 系统-文件归档 |
| POST | `/system/file/cut` | 创建移动任务 | - | ArchiveRequest | string | 系统-文件归档 |
| POST | `/system/file/delete` | 删除到回收站 | - | FileListRequest | Array<FileTrash> | 系统-文件回收站 |
| GET/HEAD | `/system/file/download/{path}` | 下载文件 | path* | - | - | 系统-文件内容 |
| GET | `/system/file/exist` | 判断路径是否存在 | path* | - | boolean | 系统-文件 |
| GET | `/system/file/hash` | 计算文件 SHA-256 | path* | - | FileHash | 系统-文件 |
| GET | `/system/file/list` | 获取目录列表 | path | - | Array<ServerFile> | 系统-文件 |
| POST | `/system/file/mkdir` | 创建目录 | - | MkdirRequest | ServerFile | 系统-文件 |
| GET | `/system/file/object/{path}` | 获取文件属性 | path* | - | ServerFile | 系统-文件 |
| GET | `/system/file/preview/{path}` | 预览文件 | path* | - | - | 系统-文件内容 |
| GET | `/system/file/read/{path}` | 读取文件 | path* | - | - | 系统-文件内容 |
| POST | `/system/file/rename` | 重命名或移动 | - | RenameRequest | ServerFile | 系统-文件 |
| POST | `/system/file/search` | 搜索文件 | - | SearchRequest | SearchResult | 系统-文件 |
| GET | `/system/file/share` | 获取分享列表 | - | - | Array<FileShare> | 系统-文件分享 |
| POST | `/system/file/share` | 创建文件分享 | - | ShareCreateRequest | FileShare | 系统-文件分享 |
| DELETE | `/system/file/share/{id}` | 取消文件分享 | id* | - | FileShare | 系统-文件分享 |
| GET/HEAD | `/system/file/share/{token}/download` | [公开] 下载分享文件 | token*, password | - | - | 系统-文件分享 |
| POST | `/system/file/size` | 统计目录大小 | - | PathRequest | string | 系统-文件 |
| POST | `/system/file/tar` | 创建 TAR 压缩任务 | - | ArchiveRequest | string | 系统-文件归档 |
| GET | `/system/file/trash` | 获取回收站列表 | - | - | Array<FileTrash> | 系统-文件回收站 |
| DELETE | `/system/file/trash` | 清空回收站 | - | - | integer | 系统-文件回收站 |
| POST | `/system/file/trash/restore` | 恢复回收站文件 | - | IdRequest | ServerFile | 系统-文件回收站 |
| DELETE | `/system/file/trash/{id}` | 彻底删除回收站记录 | id* | - | - | 系统-文件回收站 |
| POST | `/system/file/untar` | 创建 TAR 解压任务 | - | UnarchiveRequest | string | 系统-文件归档 |
| POST | `/system/file/unzip` | 创建 ZIP 解压任务 | - | UnarchiveRequest | string | 系统-文件归档 |
| POST | `/system/file/upload` | 上传文件 | path*, name*, overwrite | object{file} | ServerFile | 系统-文件上传 |
| POST | `/system/file/upload/chunk` | 上传分片 | uploadId*, index* | object{file} | - | 系统-文件上传 |
| POST | `/system/file/upload/complete` | 完成分片上传 | - | UploadCompleteRequest | ServerFile | 系统-文件上传 |
| POST | `/system/file/upload/init` | 初始化分片上传 | - | UploadInitRequest | UploadInit | 系统-文件上传 |
| POST | `/system/file/zip` | 创建 ZIP 压缩任务 | - | ArchiveRequest | string | 系统-文件归档 |
| POST | `/system/multilingual/create` | create | - | Multilingual_Admin | Multilingual_Admin | multilingual-controller |
| POST | `/system/multilingual/delete` | delete | id* | - | - | multilingual-controller |
| POST | `/system/multilingual/detail` | detail | id* | - | Multilingual_Admin | multilingual-controller |
| POST | `/system/multilingual/update` | update | - | Multilingual | - | multilingual-controller |
| GET | `/system/server/status` | getStatus | metrics | - | SystemStatusSnapshotView | system-controller |
| GET | `/system/server/status/history` | getStatusHistory | window, metrics | - | SystemStatusHistoryView | system-controller |
| POST | `/system/task/debug` | 创建调试任务 | second | - | string | 系统-异步任务 |
| GET | `/system/task/detail` | 获取任务详情 | uuid* | - | AbstractAsyncTask | 系统-异步任务 |
| GET | `/system/task/events` | 订阅任务事件 | uuid* | - | SSE | 系统-异步任务 |
| POST | `/system/task/interrupt` | 中断任务 | uuid* | - | - | 系统-异步任务 |
| POST | `/system/task/list` | 获取任务列表 | - | - | Array<AsyncTaskView> | 系统-异步任务 |
| POST | `/system/task/pause` | 暂停任务 | uuid* | - | - | 系统-异步任务 |
| POST | `/system/task/start` | 启动任务 | uuid* | - | - | 系统-异步任务 |
| GET | `/system/ups/history` | getHistory | window | - | UpsHistoryView | ups-controller |
| GET | `/system/ups/status` | getStatus | - | - | UpsStatusView | ups-controller |
<a id="module-user"></a>
## user
共 44 个接口,路径前缀 `/user/`。
| 方法 | 路径 | 摘要 | 参数 | 请求体 | 响应 | Tag |
| --- | --- | --- | --- | --- | --- | --- |
| POST | `/user/api-key/create` | create | - | CreateRequest | CreateResult | user-api-key-controller |
| POST | `/user/api-key/delete` | delete | id* | - | - | user-api-key-controller |
| POST | `/user/api-key/list` | list | - | - | Array<KeyInfo> | user-api-key-controller |
| POST | `/user/api-key/revoke` | revoke | id* | - | - | user-api-key-controller |
| POST | `/user/cancel` | cancel | - | CancelRequest | - | user-controller |
| POST | `/user/create` | create | - | User | - | user-controller |
| POST | `/user/current/update` | updateCurrent | - | User | LoginResponse | user-controller |
| GET/HEAD/POST/PUT/PATCH/DELETE/OPTIONS | `/user/delete` | delete | id* | - | - | user-controller |
| GET/HEAD/POST/PUT/PATCH/DELETE/OPTIONS | `/user/detail` | detail | id* | - | User | user-controller |
| POST | `/user/list` | list | - | PageUser | PageResultUser | user-controller |
| POST | `/user/login` | login | - | CaptchaDataLoginRequest_Public | LoginResponse_Public | user-controller |
| POST | `/user/login/sms` | loginBySms | - | SmsCaptchaVerifyRequest_Public | LoginResponse_Public | user-controller |
| GET/HEAD/POST/PUT/PATCH/DELETE/OPTIONS | `/user/login/token` | token | - | - | LoginResponse_Public | user-controller |
| POST | `/user/logout` | logout | - | - | - | user-controller |
| POST | `/user/permission/create` | create | - | Permission | - | permission-controller |
| POST | `/user/permission/create/batch` | createBatch | - | BatchCreateReq | - | permission-controller |
| POST | `/user/permission/delete` | delete | id* | - | - | permission-controller |
| POST | `/user/permission/grantable/list` | listGrantable | moduleCode* | - | Array<Permission> | permission-controller |
| POST | `/user/permission/list` | list | - | PagePermission | PageResultPermission | permission-controller |
| POST | `/user/permission/update` | update | - | Permission | - | permission-controller |
| POST | `/user/phone/verify` | verifyPhone | - | PhoneVerifyRequest | - | user-controller |
| POST | `/user/phone/verify/send` | sendPhoneCode | - | PhoneVerifyCodeSendRequest | - | user-controller |
| POST | `/user/register` | register | - | CaptchaDataUser_Public | LoginResponse_Public | user-controller |
| POST | `/user/role/authorized/create` | authorizeUserRole | - | UserRoleAuthorizeRequest | - | role-controller |
| POST | `/user/role/authorized/list` | listUserRole | moduleCode, userId* | - | Array<Role> | role-controller |
| POST | `/user/role/authorized/permission` | listAuthorizedPermission | userId* | - | Array<Permission> | role-controller |
| POST | `/user/role/create` | create | - | Role | - | role-controller |
| POST | `/user/role/current/detail/list` | listCurrentRoleDetail | moduleCode | - | Array<Role> | role-controller |
| POST | `/user/role/delegation/grantable/list` | listGrantableDelegationPermission | roleId* | - | Array<Permission> | role-controller |
| POST | `/user/role/delegation/list` | listDelegationPermission | roleId* | - | Array<Permission> | role-controller |
| POST | `/user/role/delegation/update` | updateRoleDelegation | - | Role | - | role-controller |
| POST | `/user/role/delete` | delete | id* | - | - | role-controller |
| POST | `/user/role/detail` | detail | id* | - | Role | role-controller |
| POST | `/user/role/grantable/list` | listGrantableRole | moduleCode* | - | Array<Role> | role-controller |
| POST | `/user/role/list` | list | - | PageRole | PageResultRole | role-controller |
| POST | `/user/role/manageable/list` | listManageableRole | moduleCode* | - | Array<Role> | role-controller |
| POST | `/user/role/parent/create/grantable/list` | listCreateGrantableParentRole | moduleCode* | - | Array<Role> | role-controller |
| POST | `/user/role/parent/grantable/list` | listGrantableParentRole | roleId* | - | Array<Role> | role-controller |
| POST | `/user/role/parent/update` | updateRoleParent | - | Role | - | role-controller |
| POST | `/user/role/permission/grantable/list` | listGrantableRolePermission | roleId* | - | Array<Permission> | role-controller |
| POST | `/user/role/update` | update | - | Role | - | role-controller |
| POST | `/user/update` | update | - | User | - | user-controller |
| POST | `/user/update/email` | updateEmail | - | - | - | user-controller |
| POST | `/user/update/password` | updatePassword | - | UpdatePasswordRequest | - | user-controller |
<a id="module-app"></a>
## app
共 13 个接口,路径前缀 `/app/`。
| 方法 | 路径 | 摘要 | 参数 | 请求体 | 响应 | Tag |
| --- | --- | --- | --- | --- | --- | --- |
| POST | `/app/channel/delete` | channelDelete | channelId* | - | - | app-release-controller |
| GET | `/app/channel/list` | channelList | productId* | - | Array<AppChannel> | app-release-controller |
| POST | `/app/product/delete` | productDelete | productId* | - | - | app-release-controller |
| POST | `/app/product/list` | productList | - | - | Array<AppProduct> | app-release-controller |
| POST | `/app/product/save` | productSave | - | AppProduct | AppProduct | app-release-controller |
| POST | `/app/release/create` | releaseCreate | - | AppRelease | AppRelease | app-release-controller |
| POST | `/app/release/delete` | releaseDelete | releaseId* | - | - | app-release-controller |
| GET | `/app/release/list` | releaseList | productId* | - | Array<AppRelease> | app-release-controller |
| POST | `/app/release/publish` | publish | releaseId*, channelCode, grayPermille, note | - | - | app-release-controller |
| POST | `/app/release/revoke` | revoke | releaseId* | - | - | app-release-controller |
| POST | `/app/release/rollback` | rollback | productId*, channelCode, targetReleaseId* | - | - | app-release-controller |
| POST | `/app/update/check` | check | - | AppUpdateCheckRequest | AppUpdateCheckResponse | app-update-controller |
| POST | `/app/update/notes` | notes | - | AppUpdateCheckRequest | AppUpdateNotesResponse | app-update-controller |
<a id="module-.well-known"></a>
## .well-known
共 6 个接口,路径前缀 `/.well-known/`。
| 方法 | 路径 | 摘要 | 参数 | 请求体 | 响应 | Tag |
| --- | --- | --- | --- | --- | --- | --- |
| GET | `/.well-known/oauth-authorization-server` | notSupported | - | - | - | gao-ai-mcp-o-auth-discovery-controller |
| GET | `/.well-known/oauth-authorization-server/mcp/gao-ai` | notSupported | - | - | - | gao-ai-mcp-o-auth-discovery-controller |
| GET | `/.well-known/oauth-protected-resource` | notSupported | - | - | - | gao-ai-mcp-o-auth-discovery-controller |
| GET | `/.well-known/oauth-protected-resource/mcp/gao-ai` | notSupported | - | - | - | gao-ai-mcp-o-auth-discovery-controller |
| GET | `/.well-known/openid-configuration` | notSupported | - | - | - | gao-ai-mcp-o-auth-discovery-controller |
| GET | `/.well-known/openid-configuration/mcp/gao-ai` | notSupported | - | - | - | gao-ai-mcp-o-auth-discovery-controller |
<a id="module-article"></a>
## article
共 5 个接口,路径前缀 `/article/`。
| 方法 | 路径 | 摘要 | 参数 | 请求体 | 响应 | Tag |
| --- | --- | --- | --- | --- | --- | --- |
| POST | `/article/create` | create | - | Article_Public | Article_Public | article-controller |
| POST | `/article/delete` | delete | id* | - | - | article-controller |
| GET/HEAD/POST/PUT/PATCH/DELETE/OPTIONS | `/article/detail` | detail | id* | - | Article_Public | article-controller |
| POST | `/article/list` | list | - | PageArticle_Public | PageResultArticle_Public | article-controller |
| POST | `/article/update` | update | - | Article | - | article-controller |
<a id="module-attach"></a>
## attach
共 14 个接口,路径前缀 `/attach/`。
| 方法 | 路径 | 摘要 | 参数 | 请求体 | 响应 | Tag |
| --- | --- | --- | --- | --- | --- | --- |
| GET | `/attach/count/biz` | countByBiz | bizType*, bizId*, attachTypeList | - | integer | attachment-controller |
| POST | `/attach/create` | create | - | Attachment (multipart/form-data) | Attachment | attachment-controller |
| POST | `/attach/delete` | delete | id* | - | - | attachment-controller |
| POST | `/attach/detail` | detail | id* | - | Attachment | attachment-controller |
| GET | `/attach/detail/byAttachType` | detailByAttachType | bizType*, bizId*, attachType* | - | Attachment | attachment-controller |
| GET | `/attach/detail/byBiz` | detailByBiz | bizType*, bizId* | - | Attachment | attachment-controller |
| GET | `/attach/download/{id}` | readById | id*, thumbWidth, thumbHeight, fitMode | - | - | attachment-controller |
| GET | `/attach/list/biz` | listByBiz | bizType*, bizId*, attachTypeList | - | Array<Attachment> | attachment-controller |
| POST | `/attach/page/biz` | pageByBiz | bizType*, bizId*, attachTypeList | PageAttachment | PageResultAttachment | attachment-controller |
| GET | `/attach/read/{id}` | readById | id*, thumbWidth, thumbHeight, fitMode | - | - | attachment-controller |
| GET | `/attach/temp/download` | read | id* | - | - | attachment-controller |
| GET | `/attach/temp/read` | read | id* | - | - | attachment-controller |
| POST | `/attach/temp/upload` | upload | file*, ttl | - | Array<TempFileResp> | attachment-controller |
| POST | `/attach/update` | update | - | Attachment (multipart/form-data) | - | attachment-controller |
<a id="module-captcha"></a>
## captcha
共 2 个接口,路径前缀 `/captcha/`。
| 方法 | 路径 | 摘要 | 参数 | 请求体 | 响应 | Tag |
| --- | --- | --- | --- | --- | --- | --- |
| GET | `/captcha` | captcha | width*, height* | - | Result | common-controller |
| GET | `/captcha/img` | captchaImg | width*, height* | - | - | common-controller |
<a id="module-comment"></a>
## comment
共 13 个接口,路径前缀 `/comment/`。
| 方法 | 路径 | 摘要 | 参数 | 请求体 | 响应 | Tag |
| --- | --- | --- | --- | --- | --- | --- |
| POST | `/comment/create` | create | - | CommentCreateReq_Public | Comment_Public | comment-controller |
| POST | `/comment/delete` | delete | id*, userId* | - | - | comment-controller |
| GET | `/comment/detail/tree` | detailTree | id*, currentUserId | - | Comment_Public | comment-controller |
| GET | `/comment/flat/list` | listFlatRoot | bizType*, bizId*, offset, currentUserId | - | FlatCommentListResp_Public | comment-controller |
| GET | `/comment/flat/thread` | getFlatThread | commentId*, offset, currentUserId | - | CommentThreadResp_Public | comment-controller |
| POST | `/comment/layer/list` | listLayer | currentUserId | CommentLayerQueryReq_Public | CommentLayerResp_Public | comment-controller |
| POST | `/comment/like` | like | commentId*, userId* | - | - | comment-controller |
| POST | `/comment/like/list` | listLikedRecord | userId* | PageUserBehaviorRecord_Public | PageResultUserBehaviorRecord_Public | comment-controller |
| GET | `/comment/nested/children` | getNestedChildren | commentId*, offset, currentUserId | - | CommentLayerResp_Public | comment-controller |
| GET | `/comment/nested/detail` | getNestedDetail | commentId*, currentUserId | - | CommentNodeResp_Public | comment-controller |
| GET | `/comment/nested/list` | listNestedRoot | bizType*, bizId*, offset, currentUserId | - | NestedCommentListResp_Public | comment-controller |
| POST | `/comment/reply` | reply | - | CommentReplyReq_Public | Comment_Public | comment-controller |
| POST | `/comment/unlike` | unlike | commentId*, userId* | - | - | comment-controller |
<a id="module-feedback"></a>
## feedback
共 5 个接口,路径前缀 `/feedback/`。
| 方法 | 路径 | 摘要 | 参数 | 请求体 | 响应 | Tag |
| --- | --- | --- | --- | --- | --- | --- |
| POST | `/feedback/create` | create | - | CaptchaDataFeedback_Public | - | feedback-controller |
| POST | `/feedback/delete` | delete | id* | - | - | feedback-controller |
| POST | `/feedback/detail` | detail | id* | - | Feedback_Admin | feedback-controller |
| POST | `/feedback/list` | list | - | PageFeedback_Admin | PageResultFeedback_Admin | feedback-controller |
| POST | `/feedback/update` | update | - | Feedback | - | feedback-controller |
<a id="module-fmc"></a>
## fmc
共 1 个接口,路径前缀 `/fmc/`。
| 方法 | 路径 | 摘要 | 参数 | 请求体 | 响应 | Tag |
| --- | --- | --- | --- | --- | --- | --- |
| POST | `/fmc/server/report` | report | - | - | - | server-controller |
<a id="module-icon"></a>
## icon
共 4 个接口,路径前缀 `/icon/`。
| 方法 | 路径 | 摘要 | 参数 | 请求体 | 响应 | Tag |
| --- | --- | --- | --- | --- | --- | --- |
| GET | `/icon/export/ttf` | exportTtf | - | - | - | icon-controller |
| GET | `/icon/name/list` | listName | - | - | Array<string> | icon-controller |
| GET | `/icon/svg/map` | mapSvg | - | - | Map<String, string> | icon-controller |
| GET | `/icon/unicode/map` | mapUnicode | - | - | Map<String, string> | icon-controller |
<a id="module-journal"></a>
## journal
共 7 个接口,路径前缀 `/journal/`。
| 方法 | 路径 | 摘要 | 参数 | 请求体 | 响应 | Tag |
| --- | --- | --- | --- | --- | --- | --- |
| GET | `/journal/tool/memo` | getMemo | - | - | string | tool-controller |
| POST | `/journal/tool/memo/update` | updateMemo | data* | - | - | tool-controller |
| POST | `/journal/travel/create` | create | - | Travel | - | travel-controller |
| POST | `/journal/travel/delete` | delete | - | string | - | travel-controller |
| POST | `/journal/travel/list` | list | - | PageTravel | PageResultTravel | travel-controller |
| POST | `/journal/travel/update` | update | - | Travel | - | travel-controller |
| GET | `/journal/travel/{id}` | detail | id* | - | Travel | travel-controller |
<a id="module-log"></a>
## log
共 1 个接口,路径前缀 `/log/`。
| 方法 | 路径 | 摘要 | 参数 | 请求体 | 响应 | Tag |
| --- | --- | --- | --- | --- | --- | --- |
| POST | `/log/create` | create | - | ClientLogRequest | - | logger-controller |
<a id="module-mcp"></a>
## mcp
共 5 个接口,路径前缀 `/mcp/`。
| 方法 | 路径 | 摘要 | 参数 | 请求体 | 响应 | Tag |
| --- | --- | --- | --- | --- | --- | --- |
| POST | `/mcp/gao-ai` | handle | header:Authorization, header:X-Timi-AI-Session | JsonNode | object | gao-ai-mcp-controller |
| POST | `/mcp/gao-ai-commit` | handle | header:Authorization, header:X-Timi-AI-Session | JsonNode | object | gao-ai-mcp-commit-controller |
| GET | `/mcp/gao-ai/.well-known/oauth-authorization-server` | notSupported | - | - | - | gao-ai-mcp-o-auth-discovery-controller |
| GET | `/mcp/gao-ai/.well-known/oauth-protected-resource` | notSupported | - | - | - | gao-ai-mcp-o-auth-discovery-controller |
| GET | `/mcp/gao-ai/.well-known/openid-configuration` | notSupported | - | - | - | gao-ai-mcp-o-auth-discovery-controller |
<a id="module-mirror"></a>
## mirror
共 2 个接口,路径前缀 `/mirror/`。
| 方法 | 路径 | 摘要 | 参数 | 请求体 | 响应 | Tag |
| --- | --- | --- | --- | --- | --- | --- |
| GET | `/mirror/list` | list | - | - | Array<MirrorView> | mirror-controller |
| GET | `/mirror/{mirrorName}` | get | mirrorName* | - | JsonNode | mirror-controller |
<a id="module-notify"></a>
## notify
共 15 个接口,路径前缀 `/notify/`。
| 方法 | 路径 | 摘要 | 参数 | 请求体 | 响应 | Tag |
| --- | --- | --- | --- | --- | --- | --- |
| POST | `/notify/cancel` | cancel | id* | - | - | notify-controller |
| POST | `/notify/create` | create | - | Notify | Notify | notify-controller |
| POST | `/notify/delete` | delete | id* | - | - | notify-controller |
| GET/HEAD/POST/PUT/PATCH/DELETE/OPTIONS | `/notify/detail` | detail | id* | - | Notify_Public | notify-controller |
| POST | `/notify/internal/delete` | deleteInternal | id* | - | - | notify-controller |
| POST | `/notify/internal/detail` | internalDetail | id* | - | NotifyDetail_Public | notify-controller |
| POST | `/notify/internal/internal` | listInternal | unreadOnly | PageNotifyDetail | PageResultNotifyDetail | notify-controller |
| POST | `/notify/internal/read` | markSiteRead | id* | - | - | notify-controller |
| POST | `/notify/internal/read/all` | markAllSiteRead | - | - | - | notify-controller |
| POST | `/notify/internal/unread/count` | countUnreadSite | - | - | integer | notify-controller |
| POST | `/notify/management/cancel` | managementCancel | id* | - | - | notify-controller |
| POST | `/notify/management/delete` | managementDelete | id* | - | - | notify-controller |
| POST | `/notify/management/detail` | managementDetail | id* | - | Notify_Admin | notify-controller |
| POST | `/notify/management/list` | managementList | - | PageNotify_Admin | PageResultNotifyManagementItem_Admin | notify-controller |
| POST | `/notify/sms/captcha/create` | smsCaptchaCreate | - | CaptchaDataNotify | string | notify-controller |
<a id="module-root"></a>
## root
共 1 个接口,路径前缀 `/`。
| 方法 | 路径 | 摘要 | 参数 | 请求体 | 响应 | Tag |
| --- | --- | --- | --- | --- | --- | --- |
| GET/HEAD/POST/PUT/PATCH/DELETE/OPTIONS | `/` | root | - | - | string | common-controller |
<a id="module-setting"></a>
## setting
共 6 个接口,路径前缀 `/setting/`。
| 方法 | 路径 | 摘要 | 参数 | 请求体 | 响应 | Tag |
| --- | --- | --- | --- | --- | --- | --- |
| POST | `/setting/create` | 创建配置 | - | Setting_Admin | Setting_Admin | 系统-配置 |
| POST | `/setting/delete` | 删除配置 | - | string | - | 系统-配置 |
| POST | `/setting/detail` | 查询配置详情 | - | string | Setting_Admin | 系统-配置 |
| POST | `/setting/list` | 查询配置列表 | - | PageSetting_Admin | PageResultSetting_Admin | 系统-配置 |
| GET/HEAD/POST/PUT/PATCH/DELETE/OPTIONS | `/setting/map` | [公开] 查询公开配置映射 | bizType*, bizId, code | - | Map<String, Setting_Public> | 系统-配置 |
| POST | `/setting/update` | 更新配置 | - | Setting | - | 系统-配置 |
<a id="module-tag"></a>
## tag
共 7 个接口,路径前缀 `/tag/`。
| 方法 | 路径 | 摘要 | 参数 | 请求体 | 响应 | Tag |
| --- | --- | --- | --- | --- | --- | --- |
| POST | `/tag/apply` | apply | - | TagApply | - | tag-controller |
| POST | `/tag/create` | create | - | Tag_Public | Tag_Public | tag-controller |
| POST | `/tag/delete` | delete | id* | - | - | tag-controller |
| POST | `/tag/detail` | detail | id* | - | Tag_Public | tag-controller |
| POST | `/tag/list` | list | - | PageTag_Public | PageResultTag_Public | tag-controller |
| GET | `/tag/list/biz/id` | listByBizType | bizType*, bizId* | - | Array<Tag_Public> | tag-controller |
| POST | `/tag/update` | update | - | Tag | - | tag-controller |
+27 -2
View File
@@ -11,7 +11,7 @@
<groupId>com.imyeyu.timiserverapi</groupId>
<artifactId>TimiServerAPI</artifactId>
<version>1.0.48</version>
<version>1.0.81</version>
<packaging>jar</packaging>
<name>TimiServerAPI</name>
<description>imyeyu.com API</description>
@@ -180,6 +180,11 @@
</repositories>
<dependencies>
<dependency>
<groupId>com.openhtmltopdf</groupId>
<artifactId>openhtmltopdf-pdfbox</artifactId>
<version>1.0.10</version>
</dependency>
<dependency>
<groupId>org.apache.groovy</groupId>
<artifactId>groovy</artifactId>
@@ -188,7 +193,16 @@
<dependency>
<groupId>com.imyeyu.spring</groupId>
<artifactId>timi-spring</artifactId>
<version>0.0.19</version>
<version>0.0.20</version>
</dependency>
<dependency>
<groupId>org.springdoc</groupId>
<artifactId>springdoc-openapi-starter-webmvc-ui</artifactId>
<version>2.10.1</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-freemarker</artifactId>
</dependency>
<dependency>
<groupId>com.imyeyu.network</groupId>
@@ -215,6 +229,11 @@
<artifactId>tinypinyin</artifactId>
<version>2.0.3</version>
</dependency>
<dependency>
<groupId>cn.6tail</groupId>
<artifactId>lunar</artifactId>
<version>1.7.8</version>
</dependency>
<dependency>
<groupId>com.hankcs</groupId>
<artifactId>hanlp</artifactId>
@@ -237,6 +256,12 @@
</exclusion>
</exclusions>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<version>2.3.232</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.mariadb.jdbc</groupId>
<artifactId>mariadb-java-client</artifactId>
+124
View File
@@ -0,0 +1,124 @@
<#
.SYNOPSIS
导出本地 OpenAPI 文档。
.DESCRIPTION
从本地已启动的服务获取 /v3/api-docs.yaml(或 JSON),写入 docs 目录。
默认同时生成面向 AI Agent 的接口索引 docs/openapi.index.md。
生成的 OpenAPI 快照已被 .gitignore 忽略;索引文件可按需提交或单独发送。
.PARAMETER BaseUrl
服务地址,默认 http://localhost:18092。
.PARAMETER OutFile
输出文件路径,默认 docs/openapi.local.yaml。
扩展名为 .json 时导出 JSON,否则导出 YAML。
.PARAMETER IndexFile
接口索引输出路径,默认 docs/openapi.index.md。
.PARAMETER NoIndex
跳过接口索引生成。
.EXAMPLE
.\scripts\export-openapi.ps1
.EXAMPLE
.\scripts\export-openapi.ps1 -BaseUrl http://192.168.1.10:18092 -OutFile docs/openapi.local.json
.EXAMPLE
.\scripts\export-openapi.ps1 -NoIndex
#>
param(
[string]$BaseUrl = "http://localhost:18092",
[string]$OutFile,
[string]$IndexFile,
[switch]$NoIndex
)
$ErrorActionPreference = "Stop"
$RootDir = Split-Path -Parent $PSScriptRoot
if ([string]::IsNullOrWhiteSpace($OutFile)) {
$OutFile = Join-Path $RootDir "docs\openapi.local.yaml"
}
if ([string]::IsNullOrWhiteSpace($IndexFile)) {
$IndexFile = Join-Path $RootDir "docs\openapi.index.md"
}
$BaseUrl = $BaseUrl.TrimEnd("/")
$OutFile = [System.IO.Path]::GetFullPath($OutFile)
$IndexFile = [System.IO.Path]::GetFullPath($IndexFile)
$OutDir = Split-Path -Parent $OutFile
if (-not (Test-Path -LiteralPath $OutDir)) {
New-Item -ItemType Directory -Path $OutDir -Force | Out-Null
}
if ([System.IO.Path]::GetExtension($OutFile) -ieq ".json") {
$ApiPath = "/v3/api-docs"
} else {
$ApiPath = "/v3/api-docs.yaml"
}
$Url = "$BaseUrl$ApiPath"
Write-Host "Fetching $Url"
Invoke-WebRequest -Uri $Url -OutFile $OutFile -UseBasicParsing
Write-Host "OpenAPI exported to $OutFile"
if ($NoIndex) {
exit 0
}
if ($IndexFile -eq $OutFile) {
Write-Warning "接口索引不能与 OpenAPI 输出文件相同,跳过接口索引生成。"
exit 0
}
$IndexScript = Join-Path $PSScriptRoot "openapi-index.py"
if (-not (Test-Path -LiteralPath $IndexScript)) {
Write-Warning "未找到 $IndexScript,跳过接口索引生成。"
exit 0
}
$Python = $null
foreach ($Candidate in @("python", "python3")) {
$Command = Get-Command $Candidate -ErrorAction SilentlyContinue
if ($Command) {
$Python = $Command.Source
break
}
}
if (-not $Python) {
Write-Warning "未找到 Python,跳过接口索引生成。安装 Python 或使用 -NoIndex 关闭该提示。"
exit 0
}
$IndexDir = Split-Path -Parent $IndexFile
if (-not (Test-Path -LiteralPath $IndexDir)) {
New-Item -ItemType Directory -Path $IndexDir -Force | Out-Null
}
$IndexInput = $OutFile
$TempIndexInput = $null
if ([System.IO.Path]::GetExtension($OutFile) -ine ".json") {
$TempIndexInput = [System.IO.Path]::GetTempFileName()
try {
Invoke-WebRequest -Uri "$BaseUrl/v3/api-docs" -OutFile $TempIndexInput -UseBasicParsing
$IndexInput = $TempIndexInput
} catch {
Write-Warning "获取 OpenAPI JSON 失败,跳过接口索引生成:$($_.Exception.Message)"
$IndexInput = $null
}
}
if ($IndexInput) {
& $Python $IndexScript $IndexInput $IndexFile
if ($LASTEXITCODE -ne 0) {
Write-Warning "接口索引生成失败(退出码 $LASTEXITCODE)。"
}
}
if ($TempIndexInput -and (Test-Path -LiteralPath $TempIndexInput)) {
Remove-Item -LiteralPath $TempIndexInput -Force
}
+79
View File
@@ -0,0 +1,79 @@
#!/usr/bin/env bash
# 导出本地 OpenAPI 文档,并默认生成面向 AI Agent 的接口索引。
#
# 用法:
# scripts/export-openapi.sh [baseUrl] [outFile] [indexFile]
#
# 输出文件扩展名为 .json 时导出 JSON,否则导出 YAML。
# 索引默认输出到 docs/openapi.index.md;设置 SKIP_INDEX=1 可跳过。
# 生成的 OpenAPI 快照已被 .gitignore 忽略;索引文件可按需提交或单独发送。
set -euo pipefail
ROOT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
BASE_URL="${1:-http://localhost:18092}"
OUT_FILE="${2:-$ROOT_DIR/docs/openapi.local.yaml}"
INDEX_FILE="${3:-$ROOT_DIR/docs/openapi.index.md}"
BASE_URL="${BASE_URL%/}"
mkdir -p "$(dirname "$OUT_FILE")"
case "$OUT_FILE" in
*.json)
API_PATH="/v3/api-docs"
;;
*)
API_PATH="/v3/api-docs.yaml"
;;
esac
echo "Fetching ${BASE_URL}${API_PATH}"
curl -fsS "${BASE_URL}${API_PATH}" -o "$OUT_FILE"
echo "OpenAPI exported to $OUT_FILE"
if [[ "${SKIP_INDEX:-0}" == "1" ]]; then
exit 0
fi
if [[ "$INDEX_FILE" == "$OUT_FILE" ]]; then
echo "warning: 接口索引不能与 OpenAPI 输出文件相同,跳过接口索引生成。" >&2
exit 0
fi
INDEX_SCRIPT="$ROOT_DIR/scripts/openapi-index.py"
if [[ ! -f "$INDEX_SCRIPT" ]]; then
echo "warning: 未找到 $INDEX_SCRIPT,跳过接口索引生成。" >&2
exit 0
fi
PYTHON="$(command -v python3 2>/dev/null || command -v python 2>/dev/null || true)"
if [[ -z "$PYTHON" ]]; then
echo "warning: 未找到 Python,跳过接口索引生成。安装 Python 或设置 SKIP_INDEX=1 关闭该提示。" >&2
exit 0
fi
INDEX_INPUT="$OUT_FILE"
TEMP_JSON=""
cleanup() {
if [[ -n "$TEMP_JSON" ]]; then
rm -f "$TEMP_JSON"
fi
}
trap cleanup EXIT
if [[ "$OUT_FILE" != *.json ]]; then
TEMP_JSON="$(mktemp)"
if curl -fsS "${BASE_URL}/v3/api-docs" -o "$TEMP_JSON"; then
INDEX_INPUT="$TEMP_JSON"
else
echo "warning: 获取 OpenAPI JSON 失败,跳过接口索引生成。" >&2
INDEX_INPUT=""
fi
fi
if [[ -n "$INDEX_INPUT" ]]; then
mkdir -p "$(dirname "$INDEX_FILE")"
if ! "$PYTHON" "$INDEX_SCRIPT" "$INDEX_INPUT" "$INDEX_FILE"; then
echo "warning: 接口索引生成失败。" >&2
fi
fi
+356
View File
@@ -0,0 +1,356 @@
#!/usr/bin/env python3
"""从 OpenAPI 文档生成供 AI Agent 使用的接口索引。
默认优先读取 JSON(标准库即可解析);读取 YAML 时需要安装 PyYAML。
导出脚本会优先传入 /v3/api-docs 的 JSON,避免额外依赖。
"""
from __future__ import annotations
import argparse
import json
import re
import sys
from pathlib import Path
from typing import Any
HTTP_METHODS = ("get", "head", "post", "put", "patch", "delete", "options", "trace")
REQUEST_MEDIA = ("application/json", "multipart/form-data", "application/x-www-form-urlencoded", "*/*")
RESPONSE_MEDIA = ("application/json", "*/*", "text/event-stream", "application/octet-stream")
def load_spec(path: Path) -> dict[str, Any]:
text = path.read_text(encoding="utf-8")
try:
data = json.loads(text)
except json.JSONDecodeError:
try:
import yaml
except ImportError as exc:
raise SystemExit(
"无法解析 YAML:请安装 PyYAML(pip install pyyaml),"
"或改用 /v3/api-docs 的 JSON 输出。"
) from exc
data = yaml.safe_load(text)
if not isinstance(data, dict):
raise SystemExit("OpenAPI 文档格式不正确:根节点必须是对象")
return data
def resolve(spec: dict[str, Any], value: Any) -> Any:
"""解析本地 $ref,最多跟随 32 层,避免循环引用。"""
for _ in range(32):
if not isinstance(value, dict) or "$ref" not in value:
return value
ref = value["$ref"]
if not isinstance(ref, str) or not ref.startswith("#/"):
return value
current: Any = spec
for part in ref[2:].split("/"):
part = part.replace("~1", "/").replace("~0", "~")
if not isinstance(current, dict) or part not in current:
return value
current = current[part]
value = current
return value
def ref_name(ref: str) -> str:
return ref.rsplit("/", 1)[-1].replace("~1", "/").replace("~0", "~")
def schema_label(spec: dict[str, Any], schema: Any, depth: int = 0) -> str:
if not isinstance(schema, dict) or depth > 4:
return "-"
if "$ref" in schema:
return ref_name(str(schema["$ref"]))
schema_type = schema.get("type")
if isinstance(schema_type, list):
schema_type = "/".join(str(item) for item in schema_type)
if schema_type == "array":
return f"Array<{schema_label(spec, schema.get('items'), depth + 1)}>"
if schema_type == "object" or "properties" in schema:
additional = schema.get("additionalProperties")
if isinstance(additional, dict):
return f"Map<String, {schema_label(spec, additional, depth + 1)}>"
if additional is True:
return "Map<String, any>"
properties = schema.get("properties")
if isinstance(properties, dict) and properties:
names = list(properties)
if len(names) > 8:
names = names[:8] + ["..."]
return "object{" + ", ".join(names) + "}"
return "object"
for keyword in ("oneOf", "anyOf", "allOf"):
items = schema.get(keyword)
if isinstance(items, list) and items:
joiner = " | " if keyword == "oneOf" else " & "
return "(" + joiner.join(schema_label(spec, item, depth + 1) for item in items) + ")"
if schema_type == "string" and schema.get("format") in ("binary", "byte"):
return "binary"
if schema_type:
return str(schema_type)
return "-"
def pick_media(content: Any, preferred: tuple[str, ...]) -> tuple[str | None, Any]:
if not isinstance(content, dict) or not content:
return None, None
for media in preferred:
if media in content:
return media, content[media]
media = next(iter(content))
return media, content[media]
def request_label(spec: dict[str, Any], operation: dict[str, Any]) -> str:
body = resolve(spec, operation.get("requestBody"))
if not isinstance(body, dict):
return "-"
media, entry = pick_media(body.get("content"), REQUEST_MEDIA)
if media is None:
return "-"
schema = entry.get("schema") if isinstance(entry, dict) else None
label = schema_label(spec, schema)
if label == "-":
return media
if media in ("application/json", "*/*"):
return label
return f"{label} ({media})"
def response_label(spec: dict[str, Any], operation: dict[str, Any]) -> str:
responses = operation.get("responses")
if not isinstance(responses, dict) or not responses:
return "-"
response = None
for code in ("200", "201", "202", "204"):
if code in responses:
response = responses[code]
break
if response is None:
for code, candidate in responses.items():
if str(code).startswith("2"):
response = candidate
break
if response is None and "default" in responses:
response = responses["default"]
response = resolve(spec, response)
if not isinstance(response, dict):
return "-"
media, entry = pick_media(response.get("content"), RESPONSE_MEDIA)
if media is None:
return "-"
if media == "text/event-stream":
return "SSE"
schema = entry.get("schema") if isinstance(entry, dict) else None
label = schema_label(spec, schema)
if label == "-":
return media
if media in ("application/json", "*/*"):
return label
return f"{label} ({media})"
def parameter_label(spec: dict[str, Any], path_item: dict[str, Any], operation: dict[str, Any]) -> str:
merged: dict[tuple[str, str], dict[str, Any]] = {}
for source in (path_item.get("parameters"), operation.get("parameters")):
if not isinstance(source, list):
continue
for raw in source:
parameter = resolve(spec, raw)
if not isinstance(parameter, dict):
continue
name = parameter.get("name")
location = parameter.get("in")
if name and location:
merged[(str(name), str(location))] = parameter
if not merged:
return "-"
parts = []
for (name, location), parameter in merged.items():
prefix = ""
if location in ("header", "cookie"):
prefix = f"{location}:"
suffix = "*" if parameter.get("required") else ""
parts.append(f"{prefix}{name}{suffix}")
return ", ".join(parts)
def cell(value: Any) -> str:
text = "" if value is None else str(value)
text = re.sub(r"\s+", " ", text).strip()
text = text.replace("|", "\\|")
return text or "-"
def module_key(path: str) -> str:
segments = [segment for segment in path.split("/") if segment]
if not segments:
return "root"
if segments[0] == "gao" and len(segments) > 1:
return f"gao-{segments[1]}"
return segments[0]
def module_prefix(key: str) -> str:
if key == "root":
return "/"
if key.startswith("gao-"):
return f"/gao/{key[4:]}/"
return f"/{key}/"
def module_sort(key: str) -> tuple[int, str]:
if key.startswith("gao-"):
return 0, key
order = {"system": 1, "user": 2, "app": 3}
return order.get(key, 4), key
def collect_operations(spec: dict[str, Any]) -> list[dict[str, Any]]:
paths = spec.get("paths")
if not isinstance(paths, dict):
return []
operations = []
for path, path_item in paths.items():
if not isinstance(path_item, dict):
continue
path_item = resolve(spec, path_item)
if not isinstance(path_item, dict):
continue
for method in HTTP_METHODS:
operation = path_item.get(method)
if not isinstance(operation, dict):
continue
operation = resolve(spec, operation)
if not isinstance(operation, dict):
continue
summary = operation.get("summary") or operation.get("operationId") or ""
if operation.get("summary") is None and isinstance(summary, str):
summary = re.sub(r"_\d+$", "", summary)
if operation.get("deprecated"):
summary = f"[已废弃] {summary}"
public = operation["security"] == [] if "security" in operation else not spec.get("security")
if public:
summary = f"[公开] {summary}"
operations.append({
"methods": [method.upper()],
"path": path,
"summary": summary,
"parameters": parameter_label(spec, path_item, operation),
"request": request_label(spec, operation),
"response": response_label(spec, operation),
"tag": ", ".join(operation.get("tags") or []),
"module": module_key(path),
"order": (path, HTTP_METHODS.index(method)),
})
# 同一个处理器的多个 HTTP 方法(如 @RequestMapping 未限定 method)合并为一行。
merged: dict[tuple[Any, ...], dict[str, Any]] = {}
for operation in operations:
key = (
operation["path"],
operation["summary"],
operation["parameters"],
operation["request"],
operation["response"],
operation["tag"],
operation["module"],
)
if key in merged:
merged[key]["methods"].append(operation["methods"][0])
else:
merged[key] = operation
return list(merged.values())
def render(spec: dict[str, Any], source: str) -> str:
info = spec.get("info") if isinstance(spec.get("info"), dict) else {}
title = info.get("title") or "OpenAPI"
version = info.get("version") or "-"
openapi_version = spec.get("openapi") or "-"
paths = spec.get("paths") if isinstance(spec.get("paths"), dict) else {}
operations = collect_operations(spec)
groups: dict[str, list[dict[str, Any]]] = {}
for operation in operations:
groups.setdefault(operation["module"], []).append(operation)
for items in groups.values():
items.sort(key=lambda item: item["order"])
lines = [
f"# {title} 接口索引",
"",
"> 本文件由 `scripts/openapi-index.py` 从 OpenAPI 快照生成,请勿手工编辑。",
f"> 数据来源:`{source}`。完整字段定义以 OpenAPI 原文为准。",
"",
f"- 服务版本:`{version}`",
f"- OpenAPI 版本:`{openapi_version}`",
f"- 路径数:{len(paths)}",
f"- 接口数:{len(operations)}(同一路径的同一处理器会合并多个 HTTP 方法)",
f"- 模块数:{len(groups)}",
"",
"## 使用说明",
"",
"- 先按模块定位接口,再读取 `docs/openapi.local.yaml` 中对应的 `path` 或 `components/schemas`,不要整文件加载。",
"- 参数列中 `*` 表示必填;`header:`、`cookie:` 为参数位置前缀,其余为 path/query 参数。",
"- 摘要前的 `[公开]` 表示 OpenAPI 中显式标记为无需登录;未标记的接口默认使用 `Token` 鉴权。",
"- 方法列出现多个 HTTP 方法,表示 Controller 使用了未限定 method 的 `@RequestMapping`。",
"- 请求体和响应列展示顶层 schema 名称;`binary` 表示二进制响应,`SSE` 表示 `text/event-stream`。",
"- 普通 JSON 接口的响应仍由 `TimiResponse` 包装,鉴权、错误码、分页等约定见 `docs/api-integration.md`。",
"",
"## 模块导航",
"",
"| 模块 | 接口数 | 路径前缀 |",
"| --- | ---: | --- |",
]
for key in sorted(groups, key=module_sort):
lines.append(f"| [`{cell(key)}`](#module-{key}) | {len(groups[key])} | `{module_prefix(key)}` |")
for key in sorted(groups, key=module_sort):
lines.extend([
"",
f'<a id="module-{key}"></a>',
f"## {key}",
"",
f"共 {len(groups[key])} 个接口,路径前缀 `{module_prefix(key)}`。",
"",
"| 方法 | 路径 | 摘要 | 参数 | 请求体 | 响应 | Tag |",
"| --- | --- | --- | --- | --- | --- | --- |",
])
for operation in groups[key]:
lines.append(
"| {method} | `{path}` | {summary} | {parameters} | {request} | {response} | {tag} |".format(
method="/".join(operation["methods"]),
path=cell(operation["path"]),
summary=cell(operation["summary"]),
parameters=cell(operation["parameters"]),
request=cell(operation["request"]),
response=cell(operation["response"]),
tag=cell(operation["tag"]),
)
)
lines.append("")
return "\n".join(lines)
def main() -> int:
parser = argparse.ArgumentParser(description="从 OpenAPI 文档生成 AI Agent 接口索引")
parser.add_argument("input", type=Path, help="OpenAPI JSON/YAML 文件")
parser.add_argument("output", type=Path, help="输出的 Markdown 文件")
parser.add_argument(
"--source-label",
default="docs/openapi.local.yaml",
help="索引中显示的数据来源(默认 docs/openapi.local.yaml)",
)
args = parser.parse_args()
spec = load_spec(args.input)
args.output.parent.mkdir(parents=True, exist_ok=True)
args.output.write_text(render(spec, args.source_label), encoding="utf-8", newline="\n")
print(f"OpenAPI index written to {args.output}")
return 0
if __name__ == "__main__":
sys.exit(main())
+82
View File
@@ -0,0 +1,82 @@
# GAO 门店智能助手 Dify DSL 配置说明
`main_agent.yml` 是 Advanced Chat 应用,支持:
- 知识库规则回答
- 实时业务查询 Agent
- 规则 + 实时数据混合分析
- 带预览和人工确认的写操作
## 1. MCP Provider
导入 DSL 后需要配置两个 MCP Provider。
| DSL 中的 Provider | 后端地址 | 服务密钥 |
|---|---|---|
| `gao-mcp-server-dev` | `http(s)://<backend>/mcp/gao-ai` | 系统设置 `DIFY_MCP_SERVICE_KEY` |
| `gao-mcp-commit-dev` | `http(s)://<backend>/mcp/gao-ai-commit` | 系统设置 `DIFY_MCP_COMMIT_SERVICE_KEY` |
要求:
1. `gao-mcp-server-dev` 只暴露查询工具和 `operation_prepare`。
2. `gao-mcp-commit-dev` 只暴露 `operation_commit`、`operation_cancel`。
3. **提交 Provider 不得绑定到任何 Agent 节点**,只允许 `main_agent.yml` 中的确定性工具节点调用。
4. 如果 Dify 中的 Provider ID 与 DSL 不一致,请同时修改 DSL 中 `commit_tool`、`cancel_tool`、`prepare_tool` 的 `provider_id` 和 `provider_name`。
## 2. 写能力开关
后端默认关闭写能力:
```yaml
gao:
ai:
write:
enabled: true
confirmation-ttl-seconds: 600
result-ttl-seconds: 1800
max-prepares-per-10-minutes: 10
max-commits-per-10-minutes: 10
order-max-sale-amount: 1000000
order-max-discount-rate: 0.30
point-adjust-max-abs: 10000
stock-change-max-quantity: 1000
attachment-max-count: 10
attachment-max-size-mb: 10
attachment-ttl-seconds: 86400
```
## 3. 附件
Dify 内置文件上传保持关闭。前端流程:
1. 调用 `POST /gao/ai/attachment/upload` 上传凭证,获得 `token`。
2. 聊天请求携带 `attachmentTokenList`。
3. 后端把附件 token 注入 Dify start 输入 `attachmentTokensJson`。
4. `operation_prepare` 解析并校验附件,token 不进入模型提示词。
## 4. 确认流程
### 文本确认
1. 用户发起写操作。
2. `operation_prepare` 返回 `PENDING_CONFIRMATION`、`previewText`、`requiredPhrase`。
3. 下一轮聊天后端注入 `pendingOperationToken` 等 start 输入。
4. `pending_gate` 判断是否存在待确认操作。
5. `pending_action` 规则判断确认/取消。
6. 确认时调用 `operation_commit`;取消时调用 `operation_cancel`。
### 卡片确认
1. 后端在 SSE 结束前推送 `operation_preview`。
2. 卡片调用 `GET /gao/ai/operation/pending` 恢复状态。
3. 确认调用 `POST /gao/ai/operation/commit`。
4. 取消调用 `POST /gao/ai/operation/cancel`。
卡片使用公开 `operationId`,确认 token 不进入浏览器。
## 5. 安全边界
- 模型不可传 `storeId`、`operatorUserId`、`requestNo`、`confirmationToken`。
- 提交工具只接受确认 token,不接受业务参数。
- 破坏性和敏感操作必须精确短语,并重新校验权限、门店、价格、库存和状态。
- 物理删除不在操作注册表中。
File diff suppressed because it is too large Load Diff
@@ -5,6 +5,8 @@ import com.imyeyu.api.bean.CorePermissionCode;
import com.imyeyu.api.bean.ModuleCode;
import com.imyeyu.api.modules.user.service.PermissionChecker;
import com.imyeyu.java.TimiJava;
import com.imyeyu.java.bean.timi.TimiException;
import com.imyeyu.spring.annotation.IgnoreGlobalReturn;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.lang.NonNull;
@@ -12,6 +14,8 @@ import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import java.io.IOException;
///
/// CORE 权限注解处理器
///
@@ -32,14 +36,28 @@ public class RequireCorePermissionInterceptor implements HandlerInterceptor {
return true;
}
RequireCorePermission annotation = handlerMethod.getMethodAnnotation(RequireCorePermission.class);
if (annotation == null) {
annotation = handlerMethod.getBeanType().getAnnotation(RequireCorePermission.class);
}
if (annotation == null || TimiJava.isEmpty(annotation.value())) {
return true;
}
String[] permissionCodeList = java.util.Arrays.stream(annotation.value()).map(CorePermissionCode::getValue).toArray(String[]::new);
if (annotation.mode() == PermissionMatchMode.ANY) {
permissionChecker.checkAny(ModuleCode.CORE, permissionCodeList);
} else {
permissionChecker.checkAll(ModuleCode.CORE, permissionCodeList);
try {
if (annotation.mode() == PermissionMatchMode.ANY) {
permissionChecker.checkAny(ModuleCode.CORE, permissionCodeList);
} else {
permissionChecker.checkAll(ModuleCode.CORE, permissionCodeList);
}
} catch (TimiException e) {
if (handlerMethod.hasMethodAnnotation(IgnoreGlobalReturn.class) && !resp.isCommitted()) {
try {
resp.sendError(HttpServletResponse.SC_FORBIDDEN, e.getMessage());
} catch (IOException ignored) {
}
return false;
}
throw e;
}
return true;
}
@@ -55,6 +55,10 @@ public enum CorePermissionCode implements BuiltinPermissionCode {
USER_UPDATE("USER:UPDATE", "用户修改", false, true),
USER_DELETE("USER:DELETE", "用户删除", false, true),
API_KEY_CREATE("API_KEY:CREATE", "API 密钥创建", false, true),
API_KEY_READ("API_KEY:READ", "API 密钥读取", false, true),
API_KEY_DELETE("API_KEY:DELETE", "API 密钥删除", false, true),
FEEDBACK_CREATE("FEEDBACK:CREATE", "反馈创建", false, true),
FEEDBACK_READ("FEEDBACK:READ", "反馈读取", false, true),
FEEDBACK_UPDATE("FEEDBACK:UPDATE", "反馈修改", false, true),
@@ -65,6 +69,11 @@ public enum CorePermissionCode implements BuiltinPermissionCode {
NOTIFY_DELETE("NOTIFY:DELETE", "通知删除", false, true),
NOTIFY_CANCEL("NOTIFY:CANCEL", "通知取消", false, true),
FILE_READ("FILE:READ", "文件读取", false, true),
FILE_WRITE("FILE:WRITE", "文件写入", false, true),
FILE_DELETE("FILE:DELETE", "文件删除", false, true),
FILE_SHARE("FILE:SHARE", "文件分享", false, true),
USER_ROLE_CREATE("USER_ROLE:CREATE", "用户角色创建", true, true),
USER_ROLE_READ("USER_ROLE:READ", "用户角色读取", true, true),
USER_ROLE_DELETE("USER_ROLE:DELETE", "用户角色删除", true, true);
@@ -10,4 +10,6 @@ public enum ModuleCode {
CORE,
GAO,
APP,
}
@@ -24,4 +24,13 @@ public interface SettingEnum {
String getDefaultValue();
Setting.ValueType getValueType();
/// 配置作用域
///
/// 业务级配置由业务对象自己维护,启动时不初始化记录
///
/// @return 配置作用域
default Setting.Scope getScope() {
return Setting.Scope.SYSTEM;
}
}
@@ -0,0 +1,96 @@
package com.imyeyu.api.config;
import io.swagger.v3.oas.models.Components;
import io.swagger.v3.oas.models.OpenAPI;
import io.swagger.v3.oas.models.info.Info;
import io.swagger.v3.oas.models.security.SecurityRequirement;
import io.swagger.v3.oas.models.security.SecurityScheme;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.beans.factory.config.ConfigurableListableBeanFactory;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.beans.factory.support.BeanDefinitionRegistryPostProcessor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.ByteArrayHttpMessageConverter;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import java.util.List;
/**
* OpenAPI 接口文档配置
*
* @author 夜雨
* @since 2026-11-24
*/
@Configuration
public class OpenApiConfig {
/**
* 移除 timi-spring 默认的全局返回处理器,由 {@link OpenApiGlobalReturnHandler} 替代。
*
* <p>默认处理器会把所有响应包装为 TimiResponse,导致 SpringDoc 的接口描述无法被 Swagger UI 解析。</p>
*
* @return Bean 定义注册后处理器
*/
@Bean
public static BeanDefinitionRegistryPostProcessor openApiGlobalReturnHandlerReplacer() {
return new BeanDefinitionRegistryPostProcessor() {
@Override
public void postProcessBeanDefinitionRegistry(BeanDefinitionRegistry registry) {
for (String beanName : registry.getBeanDefinitionNames()) {
BeanDefinition definition = registry.getBeanDefinition(beanName);
if ("globalReturnHandler".equals(beanName)
|| "com.imyeyu.spring.util.GlobalReturnHandler".equals(definition.getBeanClassName())) {
registry.removeBeanDefinition(beanName);
}
}
}
@Override
public void postProcessBeanFactory(ConfigurableListableBeanFactory beanFactory) {
}
};
}
/**
* 接口文档信息与认证方式
*
* @return OpenAPI 配置
*/
@Bean
public OpenAPI timiServerOpenAPI() {
return new OpenAPI()
.info(new Info()
.title("TimiServerAPI")
.description("夜雨综合数据中心接口")
.version("1.0.79"))
.components(new Components()
.addSecuritySchemes("Token", new SecurityScheme()
.name("Token")
.type(SecurityScheme.Type.APIKEY)
.in(SecurityScheme.In.HEADER)
.description("登录令牌或 API Key,也可通过 URL 参数 token 传递")))
.addSecurityItem(new SecurityRequirement().addList("Token"));
}
/**
* 注册字节数组消息转换器,确保接口文档以原始 JSON 输出。
*
* <p>项目的消息转换器配置仅注册了 Jackson 转换器,{@code byte[]} 会被序列化为 Base64 字符串,
* 导致 Swagger UI 无法解析接口文档。</p>
*
* @return Web MVC 配置
*/
@Bean
public WebMvcConfigurer openApiByteArrayMessageConverter() {
return new WebMvcConfigurer() {
@Override
public void extendMessageConverters(List<HttpMessageConverter<?>> converters) {
converters.add(0, new ByteArrayHttpMessageConverter());
}
};
}
}
@@ -0,0 +1,28 @@
package com.imyeyu.api.config;
import com.imyeyu.spring.util.GlobalReturnHandler;
import org.springframework.core.MethodParameter;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.lang.NonNull;
import org.springframework.web.bind.annotation.RestControllerAdvice;
/**
* 全局返回处理器,跳过 SpringDoc 接口。
*
* <p>接口文档响应需要保持原始 JSON 结构,不能包装为 TimiResponse。</p>
*
* @author 夜雨
* @since 2026-11-24
*/
@RestControllerAdvice
public class OpenApiGlobalReturnHandler extends GlobalReturnHandler {
@Override
public boolean supports(@NonNull MethodParameter returnType, @NonNull Class<? extends HttpMessageConverter<?>> converterType) {
Class<?> containingClass = returnType.getContainingClass();
if (containingClass != null && containingClass.getName().startsWith("org.springdoc.")) {
return false;
}
return super.supports(returnType, converterType);
}
}
@@ -3,6 +3,8 @@ package com.imyeyu.api.config;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.imyeyu.api.modules.common.entity.Multilingual;
import com.imyeyu.api.modules.gao.ai.entity.GaoAiSession;
import com.imyeyu.api.modules.gao.ai.operation.GaoAiAttachmentToken;
import com.imyeyu.api.modules.gao.ai.operation.GaoAiPendingOperation;
import com.imyeyu.api.modules.gao.bean.GaoUserInviteCache;
import com.imyeyu.spring.bean.RedisConfigParams;
import com.imyeyu.spring.config.AbstractRedisConfig;
@@ -19,11 +21,6 @@ import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.cache.interceptor.KeyGenerator;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.serializer.support.DeserializingConverter;
import org.springframework.core.serializer.support.SerializingConverter;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.SerializationException;
import org.springframework.lang.Nullable;
import java.time.Duration;
@@ -107,31 +104,7 @@ public class RedisConfig extends AbstractRedisConfig {
/** @return 多语言环境,ID: {@link Multilingual} */
@Bean("redisLanguage")
public Redis<String, Multilingual> getLanguageRedisTemplate() {
return getRedis(database, RedisSerializers.STRING, new RedisSerializer<>() {
public Multilingual deserialize(@Nullable byte[] bytes) {
if (bytes == null || bytes.length == 0) {
return null;
}
try {
return (Multilingual) new DeserializingConverter().convert(bytes);
} catch (Exception var3) {
throw new SerializationException("Cannot deserialize", var3);
}
}
public byte[] serialize(@Nullable Multilingual multilingual) {
if (multilingual == null) {
return new byte[0];
} else {
try {
return new SerializingConverter().convert(multilingual);
} catch (Exception var3) {
throw new SerializationException("Cannot serialize", var3);
}
}
}
});
return getRedis(database, RedisSerializers.STRING, RedisSerializers.jacksonSerializer(jackson, Multilingual.class));
}
@Bean("redisCaptcha")
@@ -216,4 +189,22 @@ public class RedisConfig extends AbstractRedisConfig {
public Redis<String, GaoAiSession> getGaoAiSessionRedisTemplate() {
return getRedis(database, RedisSerializers.STRING, RedisSerializers.jacksonSerializer(jackson, GaoAiSession.class));
}
/// @return AI 待确认操作,token 摘要/公开 ID: 待确认操作
@Bean("redisGaoAiOperation")
public Redis<String, GaoAiPendingOperation> getGaoAiOperationRedisTemplate() {
return getRedis(database, RedisSerializers.STRING, RedisSerializers.jacksonSerializer(jackson, GaoAiPendingOperation.class));
}
/// @return AI 待确认操作索引,用户+门店/来源会话: 公开操作 ID
@Bean("redisGaoAiOperationIndex")
public Redis<String, String> getGaoAiOperationIndexRedisTemplate() {
return getRedis(database, RedisSerializers.STRING, RedisSerializers.STRING);
}
/// @return AI 附件凭证,token 摘要: 附件凭证
@Bean("redisGaoAiAttachment")
public Redis<String, GaoAiAttachmentToken> getGaoAiAttachmentRedisTemplate() {
return getRedis(database, RedisSerializers.STRING, RedisSerializers.jacksonSerializer(jackson, GaoAiAttachmentToken.class));
}
}
@@ -8,9 +8,9 @@ import com.fasterxml.jackson.databind.json.JsonMapper;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import com.imyeyu.api.annotation.RequestRateLimitInterceptor;
import com.imyeyu.api.annotation.RequireCorePermissionInterceptor;
import com.imyeyu.api.modules.app.annotation.RequireAppPermissionInterceptor;
import com.imyeyu.api.modules.gao.annotation.RequireGaoPermissionInterceptor;
import com.imyeyu.api.modules.journal.util.JournalAPIInterceptor;
import com.imyeyu.api.modules.system.util.SystemAPIInterceptor;
import com.imyeyu.spring.annotation.RequestBodyValueArgumentResolver;
import com.imyeyu.utils.Time;
import lombok.RequiredArgsConstructor;
@@ -37,11 +37,11 @@ import java.util.List;
public class WebConfig implements WebMvcConfigurer {
private final ObjectMapper jackson;
private final SystemAPIInterceptor systemAPIInterceptor;
private final JournalAPIInterceptor journalAPIInterceptor;
private final RequestRateLimitInterceptor requestRateLimitInterceptor;
private final RequireGaoPermissionInterceptor requireGaoPermissionInterceptor;
private final RequireCorePermissionInterceptor requireCorePermissionInterceptor;
private final RequireAppPermissionInterceptor requireAppPermissionInterceptor;
/**
* 过滤器
@@ -50,10 +50,10 @@ public class WebConfig implements WebMvcConfigurer {
*/
@Override
public void addInterceptors(InterceptorRegistry registry) {
registry.addInterceptor(systemAPIInterceptor).addPathPatterns(SystemAPIInterceptor.PATH);
registry.addInterceptor(journalAPIInterceptor).addPathPatterns(JournalAPIInterceptor.PATH);
registry.addInterceptor(requireCorePermissionInterceptor).addPathPatterns("/**");
registry.addInterceptor(requireGaoPermissionInterceptor).addPathPatterns("/**");
registry.addInterceptor(requireAppPermissionInterceptor).addPathPatterns("/**");
registry.addInterceptor(requestRateLimitInterceptor).addPathPatterns("/**");
}
@@ -21,6 +21,7 @@ import org.springframework.transaction.PlatformTransactionManager;
import javax.sql.DataSource;
import java.sql.SQLException;
import java.time.OffsetDateTime;
import java.util.ArrayList;
import java.util.List;
@@ -32,17 +33,14 @@ import java.util.List;
*/
@Configuration
@MapperScan(basePackages = {
"com.imyeyu.api.modules.git.mapper",
"com.imyeyu.api.modules.gao.mapper",
"com.imyeyu.api.modules.bill.mapper",
"com.imyeyu.api.modules.user.mapper",
"com.imyeyu.api.modules.blog.mapper",
"com.imyeyu.api.modules.lyric.mapper",
"com.imyeyu.api.modules.mirror.mapper",
"com.imyeyu.api.modules.system.mapper",
"com.imyeyu.api.modules.common.mapper",
"com.imyeyu.api.modules.app.mapper",
"com.imyeyu.api.modules.journal.mapper",
"com.imyeyu.api.modules.minecraft.mapper"
}, sqlSessionFactoryRef = "timiServerSqlSessionFactory")
public class TimiServerDBConfig {
@@ -58,6 +56,9 @@ public class TimiServerDBConfig {
dataSource.setMinimumIdle(10);
dataSource.setMaximumPoolSize(100);
dataSource.setConnectionTestQuery("SELECT 1");
// 日统计按后端时区划分日期
String offset = OffsetDateTime.now().getOffset().getId();
dataSource.setConnectionInitSql("SET time_zone = '%s'".formatted("Z".equals(offset) ? "+00:00" : offset));
dataSource.setMaxLifetime(Time.S * 180);
dataSource.setIdleTimeout(Time.S * 120);
@@ -0,0 +1,29 @@
package com.imyeyu.api.modules.app.annotation;
import com.imyeyu.api.bean.PermissionMatchMode;
import com.imyeyu.api.modules.app.bean.AppPermissionCode;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
///
/// 要求 APP 模块权限
///
/// @author Codex
/// @since 2026-11-06
@Target({ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
public @interface RequireAppPermission {
/// 所需权限
///
/// @return 权限列表
AppPermissionCode[] value();
/// 匹配模式
///
/// @return 匹配模式
PermissionMatchMode mode() default PermissionMatchMode.ALL;
}
@@ -0,0 +1,48 @@
package com.imyeyu.api.modules.app.annotation;
import com.imyeyu.api.bean.ModuleCode;
import com.imyeyu.api.bean.PermissionMatchMode;
import com.imyeyu.api.modules.app.bean.AppPermissionCode;
import com.imyeyu.api.modules.user.service.PermissionChecker;
import com.imyeyu.java.TimiJava;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.lang.NonNull;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import java.util.Arrays;
///
/// APP 权限注解处理器
///
/// @author Codex
/// @since 2026-11-06
@Component
public class RequireAppPermissionInterceptor implements HandlerInterceptor {
private final PermissionChecker permissionChecker;
public RequireAppPermissionInterceptor(PermissionChecker permissionChecker) {
this.permissionChecker = permissionChecker;
}
@Override
public boolean preHandle(@NonNull HttpServletRequest req, @NonNull HttpServletResponse resp, @NonNull Object handler) {
if (!(handler instanceof HandlerMethod handlerMethod)) {
return true;
}
RequireAppPermission annotation = handlerMethod.getMethodAnnotation(RequireAppPermission.class);
if (annotation == null || TimiJava.isEmpty(annotation.value())) {
return true;
}
String[] permissionCodeList = Arrays.stream(annotation.value()).map(AppPermissionCode::getValue).toArray(String[]::new);
if (annotation.mode() == PermissionMatchMode.ANY) {
permissionChecker.checkAny(ModuleCode.APP, permissionCodeList);
} else {
permissionChecker.checkAll(ModuleCode.APP, permissionCodeList);
}
return true;
}
}
@@ -0,0 +1,47 @@
package com.imyeyu.api.modules.app.bean;
import com.imyeyu.api.bean.ModuleCode;
import com.imyeyu.api.modules.user.bean.BuiltinPermissionCode;
import lombok.AllArgsConstructor;
import lombok.Getter;
///
/// APP 模块权限枚举
///
/// @author Codex
/// @since 2026-11-06
@Getter
@AllArgsConstructor
public enum AppPermissionCode implements BuiltinPermissionCode {
APP_PRODUCT_CREATE("APP_PRODUCT:CREATE", "应用产品创建", false, true),
APP_PRODUCT_READ("APP_PRODUCT:READ", "应用产品读取", false, true),
APP_PRODUCT_UPDATE("APP_PRODUCT:UPDATE", "应用产品修改", false, true),
APP_PRODUCT_DELETE("APP_PRODUCT:DELETE", "应用产品删除", false, true),
APP_CHANNEL_CREATE("APP_CHANNEL:CREATE", "应用通道创建", false, true),
APP_CHANNEL_DELETE("APP_CHANNEL:DELETE", "应用通道删除", false, true),
APP_RELEASE_CREATE("APP_RELEASE:CREATE", "应用发布创建", false, true),
APP_RELEASE_READ("APP_RELEASE:READ", "应用发布读取", false, true),
APP_RELEASE_PUBLISH("APP_RELEASE:PUBLISH", "应用发布上线", false, true),
APP_RELEASE_ROLLBACK("APP_RELEASE:ROLLBACK", "应用发布回滚", false, true),
APP_RELEASE_REVOKE("APP_RELEASE:REVOKE", "应用发布撤回", false, true),
APP_RELEASE_DELETE("APP_RELEASE:DELETE", "应用发布删除", false, true);
private final String value;
private final String defaultName;
private final boolean grantToSystem;
private final boolean grantToAdmin;
/// 权限模块
///
/// @return 模块代码
@Override
public ModuleCode getModuleCode() {
return ModuleCode.APP;
}
}
@@ -0,0 +1,184 @@
package com.imyeyu.api.modules.app.controller;
import com.imyeyu.api.modules.app.annotation.RequireAppPermission;
import com.imyeyu.api.modules.app.bean.AppPermissionCode;
import com.imyeyu.api.modules.app.entity.AppChannel;
import com.imyeyu.api.modules.app.entity.AppProduct;
import com.imyeyu.api.modules.app.entity.AppRelease;
import com.imyeyu.api.modules.app.service.AppVersionService;
import com.imyeyu.api.modules.user.service.UserLoginService;
import com.imyeyu.spring.annotation.AOPLog;
import com.imyeyu.spring.annotation.RequestRateLimit;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
///
/// 应用发布管理接口
///
/// 操作人一律取当前登录身份,不接受请求参数指定
/// 用 API Key 调用时为密钥归属用户,用登录令牌调用时为登录用户
///
/// @author Codex
/// @since 2026-11-06
@Slf4j
@RestController
@RequiredArgsConstructor
@RequestMapping("/app")
public class AppReleaseController {
private final AppVersionService service;
private final UserLoginService userLoginService;
/// 查询产品列表
///
/// @return 产品列表
@RequireAppPermission(AppPermissionCode.APP_PRODUCT_READ)
@RequestRateLimit
@PostMapping("/product/list")
public List<AppProduct> productList() {
return service.listProducts();
}
/// 保存产品
///
/// @param product 产品
/// @return 保存后的产品
@AOPLog
@RequireAppPermission({AppPermissionCode.APP_PRODUCT_CREATE, AppPermissionCode.APP_PRODUCT_UPDATE})
@RequestRateLimit
@PostMapping("/product/save")
public AppProduct productSave(@RequestBody AppProduct product) {
return service.saveProduct(product);
}
/// 查询发布列表
///
/// @param productId 产品 ID
/// @return 发布列表
@RequireAppPermission(AppPermissionCode.APP_RELEASE_READ)
@RequestRateLimit
@GetMapping("/release/list")
public List<AppRelease> releaseList(@RequestParam String productId) {
return service.listReleases(productId);
}
/// 创建发布记录
///
/// @param release 发布记录
/// @return 创建后的记录
@AOPLog
@RequireAppPermission(AppPermissionCode.APP_RELEASE_CREATE)
@RequestRateLimit
@PostMapping("/release/create")
public AppRelease releaseCreate(@RequestBody AppRelease release) {
return service.create(release, operator());
}
/// 发布版本
///
/// @param releaseId 发布 ID
/// @param channelCode 通道代码
/// @param grayPermille 灰度比例,万分比
/// @param note 变更说明
@AOPLog
@RequireAppPermission(AppPermissionCode.APP_RELEASE_PUBLISH)
@RequestRateLimit
@PostMapping("/release/publish")
public void publish(
@RequestParam String releaseId,
@RequestParam(defaultValue = AppVersionService.DEFAULT_CHANNEL) String channelCode,
@RequestParam(required = false) Integer grayPermille,
@RequestParam(required = false) String note
) {
service.publish(releaseId, channelCode, grayPermille, operator(), note);
}
/// 回滚通道到指定版本
///
/// @param productId 产品 ID
/// @param channelCode 通道代码
/// @param targetReleaseId 目标发布 ID
@AOPLog
@RequireAppPermission(AppPermissionCode.APP_RELEASE_ROLLBACK)
@RequestRateLimit
@PostMapping("/release/rollback")
public void rollback(
@RequestParam String productId,
@RequestParam(defaultValue = AppVersionService.DEFAULT_CHANNEL) String channelCode,
@RequestParam String targetReleaseId
) {
service.rollback(productId, channelCode, targetReleaseId, operator());
}
/// 撤回发布
///
/// @param releaseId 发布 ID
@AOPLog
@RequireAppPermission(AppPermissionCode.APP_RELEASE_REVOKE)
@RequestRateLimit
@PostMapping("/release/revoke")
public void revoke(@RequestParam String releaseId) {
service.revoke(releaseId, operator());
}
/// 查询通道列表
///
/// @param productId 产品 ID
/// @return 通道列表
@RequireAppPermission(AppPermissionCode.APP_RELEASE_READ)
@RequestRateLimit
@GetMapping("/channel/list")
public List<AppChannel> channelList(@RequestParam String productId) {
return service.listChannels(productId);
}
/// 删除草稿发布
///
/// @param releaseId 发布 ID
@AOPLog
@RequireAppPermission(AppPermissionCode.APP_RELEASE_DELETE)
@RequestRateLimit
@PostMapping("/release/delete")
public void releaseDelete(@RequestParam String releaseId) {
service.deleteRelease(releaseId, operator());
}
/// 删除通道
///
/// @param channelId 通道 ID
@AOPLog
@RequireAppPermission(AppPermissionCode.APP_CHANNEL_DELETE)
@RequestRateLimit
@PostMapping("/channel/delete")
public void channelDelete(@RequestParam String channelId) {
service.deleteChannel(channelId, operator());
}
/// 删除产品
///
/// @param productId 产品 ID
@AOPLog
@RequireAppPermission(AppPermissionCode.APP_PRODUCT_DELETE)
@RequestRateLimit
@PostMapping("/product/delete")
public void productDelete(@RequestParam String productId) {
service.deleteProduct(productId, operator());
}
/// 取当前操作人
///
/// 接口都带权限注解,执行到这里一定已登录,取不到会直接抛错
///
/// @return 当前登录用户 ID
private String operator() {
return userLoginService.getRequireLoginUserId();
}
}
@@ -0,0 +1,56 @@
package com.imyeyu.api.modules.app.controller;
import com.imyeyu.api.modules.app.service.AppVersionService;
import com.imyeyu.api.modules.app.vo.AppUpdateCheckRequest;
import com.imyeyu.api.modules.app.vo.AppUpdateCheckResponse;
import com.imyeyu.api.modules.app.vo.AppUpdateNotesResponse;
import com.imyeyu.spring.annotation.IgnoreGlobalReturn;
import com.imyeyu.spring.annotation.RequestRateLimit;
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.RestController;
///
/// 应用更新接口
///
/// 供 Capacitor 插件直接调用,不要求登录态,因此不加权限注解
///
/// @author Codex
/// @since 2026-11-06
@Slf4j
@RestController
@RequiredArgsConstructor
@RequestMapping("/app/update")
public class AppUpdateController {
private final AppVersionService service;
/// 检查更新
///
/// 直接返回插件要求的原始 JSON,不能套通用响应包装
///
/// @param req 插件上报信息
/// @return 插件协议响应
@IgnoreGlobalReturn
@RequestRateLimit
@PostMapping("/check")
public AppUpdateCheckResponse check(@RequestBody AppUpdateCheckRequest req) {
return service.check(req);
}
/// 查询更新日志
///
/// 返回当前运行版本到目标版本之间的变更说明,供版本历史页使用
/// 目标版本与 check 用同一套规则解析,包含灰度与兼容区间,保证「有日志」和「能更新」一致
///
/// @param req 插件上报信息,version_name 为当前运行版本
/// @return 更新日志
@RequestRateLimit
@PostMapping("/notes")
public AppUpdateNotesResponse notes(@RequestBody AppUpdateCheckRequest req) {
return service.notes(req);
}
}
@@ -0,0 +1,38 @@
package com.imyeyu.api.modules.app.entity;
import com.imyeyu.spring.entity.UUIDEntity;
import lombok.Data;
import lombok.EqualsAndHashCode;
///
/// 应用发布通道
///
/// 通道分别持有热更包和原生包指针
///
/// @author Codex
/// @since 2026-11-06
@Data
@EqualsAndHashCode(callSuper = true)
public class AppChannel extends UUIDEntity {
/// 产品 ID
protected String productId;
/// 通道代码,如 stable、beta
protected String code;
/// 通道名称
protected String name;
/// 当前热更包发布 ID
protected String bundleReleaseId;
/// 当前原生包发布 ID
protected String nativeReleaseId;
/// 过渡期旧指针
protected String releaseId;
/// 最后操作人用户 ID
protected String updatedBy;
}
@@ -0,0 +1,43 @@
package com.imyeyu.api.modules.app.entity;
import com.imyeyu.spring.entity.UUIDEntity;
import lombok.Data;
import lombok.EqualsAndHashCode;
///
/// 应用产品
///
/// @author Codex
/// @since 2026-11-06
@Data
@EqualsAndHashCode(callSuper = true)
public class AppProduct extends UUIDEntity {
/// 平台
public enum Platform {
/// Android
ANDROID,
/// iOS
IOS
}
/// 产品标识,取 Capacitor appId
protected String appKey;
/// 产品名称
protected String name;
/// 平台
protected Platform platform;
/// 包名
protected String packageName;
/// 检查接口密钥,为空时不校验
protected String updateKey;
/// true 为允许检查更新
protected Boolean enabled;
}
@@ -0,0 +1,85 @@
package com.imyeyu.api.modules.app.entity;
import com.imyeyu.spring.entity.UUIDEntity;
import lombok.Data;
import lombok.EqualsAndHashCode;
///
/// 应用发布记录
///
/// 创建后不可变,回滚只改通道指针,不修改本记录
///
/// @author Codex
/// @since 2026-11-06
@Data
@EqualsAndHashCode(callSuper = true)
public class AppRelease extends UUIDEntity {
/// 产物类型
public enum Kind {
/// 原生安装包
NATIVE,
/// Web 热更包
BUNDLE
}
/// 发布状态
public enum Status {
/// 待发布
DRAFT,
/// 已发布
PUBLISHED,
/// 已撤回
REVOKED
}
/// 产品 ID
protected String productId;
/// 产物类型
protected Kind kind;
/// 版本号,热更包为 semver
protected String versionName;
/// 原生 versionCode,kind 为 NATIVE 时必填
protected Integer versionCode;
/// 兼容的最低原生 versionCode,kind 为 BUNDLE 时必填
protected Integer minVersionCode;
/// 兼容的最高原生 versionCode,为空表示不限
protected Integer maxVersionCode;
/// 产物附件 ID
protected String attachmentId;
/// 产物字节数
protected Long artifactSize;
/// 产物 SHA-256
protected String sha256;
/// 灰度比例,万分比,10000 为全量
protected Integer grayPermille;
/// true 为强制更新,仅 kind 为 NATIVE 时有效
protected Boolean mandatory;
/// 发布状态
protected Status status;
/// 变更说明
protected String note;
/// 发布人用户 ID
protected String createdBy;
/// 首次发布时间
protected Long publishedAt;
}
@@ -0,0 +1,54 @@
package com.imyeyu.api.modules.app.mapper;
import com.imyeyu.api.modules.app.entity.AppChannel;
import com.imyeyu.spring.mapper.BaseMapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;
import java.util.List;
///
/// 应用发布通道
///
/// @author Codex
/// @since 2026-11-06
public interface AppChannelMapper extends BaseMapper<AppChannel, String> {
/// 按产品与通道代码查询
///
/// @param productId 产品 ID
/// @param code 通道代码
/// @return 通道
@Select("SELECT * FROM app_channel WHERE product_id = #{productId} AND code = #{code} AND deleted_at IS NULL LIMIT 1")
AppChannel selectByProductAndCode(@Param("productId") String productId, @Param("code") String code);
/// 按产品查询通道列表
///
/// @param productId 产品 ID
/// @return 通道列表
@Select("SELECT * FROM app_channel WHERE product_id = #{productId} AND deleted_at IS NULL ORDER BY code")
List<AppChannel> selectByProduct(@Param("productId") String productId);
/// 切换通道指针
///
/// @param id 通道 ID
/// @param releaseId 目标发布 ID,为空表示指向空
/// @param updatedBy 操作人用户 ID
/// @param updatedAt 更新时间
/// @return 影响行数
@Update("UPDATE app_channel SET release_id = #{releaseId}, updated_by = #{updatedBy}, updated_at = #{updatedAt} WHERE id = #{id}")
int updateReleaseId(
@Param("id") String id,
@Param("releaseId") String releaseId,
@Param("updatedBy") String updatedBy,
@Param("updatedAt") Long updatedAt
);
/// 按类型切换指针并同步旧指针
@Update("UPDATE app_channel SET bundle_release_id = CASE WHEN #{nativeRelease} = false THEN #{releaseId} ELSE bundle_release_id END, native_release_id = CASE WHEN #{nativeRelease} = true THEN #{releaseId} ELSE native_release_id END, release_id = #{releaseId}, updated_by = #{updatedBy}, updated_at = #{updatedAt} WHERE id = #{id}")
int updatePointers(@Param("id") String id, @Param("releaseId") String releaseId, @Param("nativeRelease") boolean nativeRelease, @Param("updatedBy") String updatedBy, @Param("updatedAt") Long updatedAt);
/// 清除所有通道中指向撤回记录的指针
@Update("UPDATE app_channel SET bundle_release_id = CASE WHEN bundle_release_id = #{releaseId} THEN NULL ELSE bundle_release_id END, native_release_id = CASE WHEN native_release_id = #{releaseId} THEN NULL ELSE native_release_id END, release_id = CASE WHEN release_id = #{releaseId} THEN NULL ELSE release_id END, updated_by = #{updatedBy}, updated_at = #{updatedAt} WHERE product_id = #{productId} AND deleted_at IS NULL AND (bundle_release_id = #{releaseId} OR native_release_id = #{releaseId} OR release_id = #{releaseId})")
int clearRelease(@Param("productId") String productId, @Param("releaseId") String releaseId, @Param("updatedBy") String updatedBy, @Param("updatedAt") Long updatedAt);
}
@@ -0,0 +1,22 @@
package com.imyeyu.api.modules.app.mapper;
import com.imyeyu.api.modules.app.entity.AppProduct;
import com.imyeyu.spring.mapper.BaseMapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
///
/// 应用产品
///
/// @author Codex
/// @since 2026-11-06
public interface AppProductMapper extends BaseMapper<AppProduct, String> {
/// 按产品标识查询
///
/// @param appKey 产品标识
/// @param platform 平台
/// @return 产品
@Select("SELECT * FROM app_product WHERE app_key = #{appKey} AND platform = #{platform} AND deleted_at IS NULL LIMIT 1")
AppProduct selectByAppKey(@Param("appKey") String appKey, @Param("platform") AppProduct.Platform platform);
}
@@ -0,0 +1,44 @@
package com.imyeyu.api.modules.app.mapper;
import com.imyeyu.api.modules.app.entity.AppRelease;
import com.imyeyu.spring.mapper.BaseMapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import java.util.List;
///
/// 应用发布记录
///
/// @author Codex
/// @since 2026-11-06
public interface AppReleaseMapper extends BaseMapper<AppRelease, String> {
/// 查询产品下已发布的同类型产物
///
/// @param productId 产品 ID
/// @param kind 产物类型
/// @return 发布列表,按发布时间倒序
@Select("SELECT * FROM app_release WHERE product_id = #{productId} AND kind = #{kind} AND status = 'PUBLISHED' AND deleted_at IS NULL ORDER BY published_at DESC")
List<AppRelease> selectPublished(@Param("productId") String productId, @Param("kind") AppRelease.Kind kind);
/// 按版本号查询
///
/// @param productId 产品 ID
/// @param kind 产物类型
/// @param versionName 版本号
/// @return 发布记录
@Select("SELECT * FROM app_release WHERE product_id = #{productId} AND kind = #{kind} AND version_name = #{versionName} AND deleted_at IS NULL LIMIT 1")
AppRelease selectByVersion(
@Param("productId") String productId,
@Param("kind") AppRelease.Kind kind,
@Param("versionName") String versionName
);
/// 查询产品下全部发布记录
///
/// @param productId 产品 ID
/// @return 发布列表,按创建时间倒序
@Select("SELECT * FROM app_release WHERE product_id = #{productId} AND deleted_at IS NULL ORDER BY created_at DESC")
List<AppRelease> selectByProduct(@Param("productId") String productId);
}
@@ -0,0 +1,573 @@
package com.imyeyu.api.modules.app.service;
import com.imyeyu.api.modules.app.entity.AppChannel;
import com.imyeyu.api.modules.app.entity.AppProduct;
import com.imyeyu.api.modules.app.entity.AppRelease;
import com.imyeyu.api.config.dbsource.TimiServerDBConfig;
import com.imyeyu.api.modules.app.mapper.AppChannelMapper;
import com.imyeyu.api.modules.app.mapper.AppProductMapper;
import com.imyeyu.api.modules.app.mapper.AppReleaseMapper;
import com.imyeyu.api.modules.app.vo.AppUpdateCheckRequest;
import com.imyeyu.api.modules.app.vo.AppUpdateCheckResponse;
import com.imyeyu.api.modules.app.vo.AppUpdateNote;
import com.imyeyu.api.modules.app.vo.AppUpdateNotesResponse;
import com.imyeyu.api.modules.system.entity.Logger;
import com.imyeyu.api.modules.system.service.LoggerService;
import com.imyeyu.java.TimiJava;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.servlet.support.ServletUriComponentsBuilder;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.zip.CRC32;
///
/// 应用版本服务
///
/// 核心只有一个判断:给定设备当前状态和通道,它此刻应该运行哪一份产物
///
/// @author Codex
/// @since 2026-11-06
@Slf4j
@Service
@RequiredArgsConstructor
public class AppVersionService {
/// 默认通道
public static final String DEFAULT_CHANNEL = "stable";
/// 内置包版本标识
public static final String BUILTIN_VERSION = "builtin";
/// 首个能处理外壳安装包的 Web 包版本
///
/// 更早的包不认识 shell 标记,只会把 url 当热更 zip 交给插件解压,拿到 APK 必然失败。
/// 通道指向原生包时,低于这个版本的设备改为下发热更包,先把它升到能自升级为止
public static final String SHELL_AWARE_VERSION = "1.3.2";
/// 首个按独立字段接收外壳更新的 Web 包版本
///
/// 从这版起响应把安装包放到 shellUrl,主字段 url 永远给热更包;
/// 更早的包只认「主字段 + shell 标记」,所以两套语义要并存到 1.5.0 铺开为止
public static final String SHELL_JSON_AWARE_VERSION = "1.5.0";
/// 更新日志最多返回的版本条数
public static final int MAX_NOTES = 8;
/// 已是最新时展示的版本条数
public static final int TAIL_NOTES = 8;
/// 灰度基数
private static final long GRAY_BASE = 10000L;
private final AppProductMapper productMapper;
private final AppChannelMapper channelMapper;
private final AppReleaseMapper releaseMapper;
private final LoggerService loggerService;
/// 检查更新
///
/// @param req 插件上报信息
/// @return 插件协议响应,无更新时回显当前版本
public AppUpdateCheckResponse check(AppUpdateCheckRequest req) {
String currentVersion = currentVersion(req);
AppProduct product = resolveProduct(req);
if (product == null) {
return AppUpdateCheckResponse.none(currentVersion);
}
int currentCode = parseInt(req.getVersionCode(), 0);
AppRelease bundlePointer = resolvePointer(product, req, AppRelease.Kind.BUNDLE);
AppRelease nativePointer = resolvePointer(product, req, AppRelease.Kind.NATIVE);
AppRelease bundle = bundlePointer == null ? null : resolveBundle(bundlePointer, product, currentCode, currentVersion, req.getDeviceId());
AppRelease nativeTarget = nativePointer == null ? null : resolveNative(nativePointer, currentCode);
boolean shellAware = 0 <= compareVersion(currentVersion, SHELL_AWARE_VERSION);
boolean jsonAware = 0 <= compareVersion(currentVersion, SHELL_JSON_AWARE_VERSION);
// 认识 shell 标记但还不认识独立字段的包,主字段继续给安装包
if (nativeTarget != null && shellAware && !jsonAware) {
return buildResponse(nativeTarget, Boolean.TRUE.equals(nativeTarget.getMandatory()), true);
}
AppUpdateCheckResponse response = bundle == null ? AppUpdateCheckResponse.none(currentVersion) : buildResponse(bundle, false, false);
if (nativeTarget != null && jsonAware) {
AppUpdateCheckResponse shell = buildResponse(nativeTarget, false, true);
response.setShellUrl(shell.getUrl());
response.setShellVersion(shell.getVersion());
response.setShellChecksum(shell.getChecksum());
response.setShellMandatory(Boolean.TRUE.equals(nativeTarget.getMandatory()));
}
return response;
}
/// 查询更新日志
///
/// 区间上界取通道当前版本,不走灰度与兼容区间判断。
/// 原因:客户端拿不到原生 versionCode,也无法保证命中灰度分桶,套用检查更新的判定会让日志
/// 大面积为空。日志是「这个产品最近发了什么」,不是「你这台设备能装什么」,分发决策仍由 check 负责
///
/// 有更新时返回 (当前版本, 通道版本] 区间;已是最新时区间为空,改为返回最近 TAIL_NOTES 个版本,
/// 否则更新完就看不到任何说明
///
/// @param req 插件上报信息
/// @return 变更说明,按版本号从新到旧
public AppUpdateNotesResponse notes(AppUpdateCheckRequest req) {
String currentVersion = currentVersion(req);
AppProduct product = resolveProduct(req);
if (product == null) {
return new AppUpdateNotesResponse(null, Collections.emptyList());
}
AppRelease target = resolvePointer(product, req, AppRelease.Kind.BUNDLE);
// 指针为空(刚建通道还没发过热更)时退回最近一次发布,日志不该跟着空
if (target == null) {
target = latestPublishedBundle(product);
}
if (target == null) {
return new AppUpdateNotesResponse(null, Collections.emptyList());
}
// 当前版本不低于通道版本:已是最新,或回滚后反而超前
boolean upToDate = 0 <= compareVersion(currentVersion, target.getVersionName());
List<AppUpdateNote> notes = new ArrayList<>();
for (AppRelease item : releaseMapper.selectPublished(product.getId(), AppRelease.Kind.BUNDLE)) {
// 上界恒定:不展示比通道版本更新的记录
if (0 < compareVersion(item.getVersionName(), target.getVersionName())) {
continue;
}
// 有更新时才设下界,已是最新则不限
if (!upToDate && 0 >= compareVersion(item.getVersionName(), currentVersion)) {
continue;
}
notes.add(new AppUpdateNote(item.getVersionName(), item.getNote(), item.getPublishedAt()));
}
// 按版本号倒序,最新的在最前
notes.sort((a, b) -> compareVersion(b.getVersion(), a.getVersion()));
int limit = upToDate ? TAIL_NOTES : MAX_NOTES;
List<AppUpdateNote> limited = limit < notes.size() ? notes.subList(0, limit) : notes;
return new AppUpdateNotesResponse(target.getVersionName(), limited);
}
/// 取当前运行的 Web 包版本
///
/// @param req 插件上报信息
/// @return 版本号,未上报时为内置包标识
private String currentVersion(AppUpdateCheckRequest req) {
return TimiJava.isEmpty(req.getVersionName()) ? BUILTIN_VERSION : req.getVersionName();
}
/// 解析并校验产品
///
/// @param req 插件上报信息
/// @return 产品,不存在、已停用或密钥不匹配时为 null
private AppProduct resolveProduct(AppUpdateCheckRequest req) {
AppProduct product = productMapper.selectByAppKey(req.getAppId(), parsePlatform(req.getPlatform()));
if (product == null || !Boolean.TRUE.equals(product.getEnabled())) {
log.warn("应用不存在或已停用,appId={}", req.getAppId());
return null;
}
if (!TimiJava.isEmpty(product.getUpdateKey()) && !product.getUpdateKey().equals(req.getKey())) {
log.warn("更新密钥不匹配,appId={}", req.getAppId());
return null;
}
return product;
}
/// 取通道当前指向的发布记录
///
/// @param product 产品
/// @param req 插件上报信息
/// @return 发布记录,通道为空或指向的记录不可用时为 null
private AppRelease resolvePointer(AppProduct product, AppUpdateCheckRequest req, AppRelease.Kind kind) {
String channelCode = TimiJava.isEmpty(req.getChannel()) ? DEFAULT_CHANNEL : req.getChannel();
AppChannel channel = channelMapper.selectByProductAndCode(product.getId(), channelCode);
if (channel == null) {
return null;
}
String id = kind == AppRelease.Kind.BUNDLE ? channel.getBundleReleaseId() : channel.getNativeReleaseId();
// 兼容旧代码在回滚期间仅更新旧指针的情况
if (TimiJava.isEmpty(id)) {
id = channel.getReleaseId();
}
if (TimiJava.isEmpty(id)) {
return null;
}
AppRelease release = releaseMapper.select(id);
return release != null && release.getKind() == kind && release.getStatus() == AppRelease.Status.PUBLISHED ? release : null;
}
/// 原生包是否需要更新
///
/// @param release 通道当前发布记录
/// @param currentCode 当前原生 versionCode
/// @return 需要更新时返回发布记录,否则返回 null
private AppRelease resolveNative(AppRelease release, int currentCode) {
if (release.getVersionCode() == null || release.getVersionCode() <= currentCode) {
return null;
}
return release;
}
/// 热更包是否需要更新
///
/// @param release 通道当前发布记录
/// @param product 产品
/// @param currentCode 当前原生 versionCode
/// @param currentVersion 当前 Web 包版本
/// @param deviceId 设备标识
/// @return 需要更新时返回发布记录,否则返回 null
private AppRelease resolveBundle(
AppRelease release,
AppProduct product,
int currentCode,
String currentVersion,
String deviceId
) {
// 原生版本不在兼容区间内,装了会崩
if (release.getMinVersionCode() != null && currentCode < release.getMinVersionCode()) {
return null;
}
if (release.getMaxVersionCode() != null && release.getMaxVersionCode() < currentCode) {
return null;
}
// 已是最新,或低于当前版本时不做降级
if (release.getVersionName().equals(currentVersion)) {
return null;
}
if (0 < compareVersion(currentVersion, release.getVersionName())) {
return null;
}
// 灰度分桶不能含 releaseId,否则每次发版都会重排用户
if (!hitGray(release.getGrayPermille(), deviceId, product.getAppKey())) {
return null;
}
return release;
}
/// 取最近一次发布的热更包
///
/// 通道指向原生包时,更新日志没有「通道版本」可用,改用这里兜底。
/// 日志是「这个产品最近发了什么」,与设备能不能装无关,所以不套灰度与兼容区间
///
/// @param product 产品
/// @return 版本最高的已发布热更包,没有则返回 null
private AppRelease latestPublishedBundle(AppProduct product) {
AppRelease latest = null;
for (AppRelease item : releaseMapper.selectPublished(product.getId(), AppRelease.Kind.BUNDLE)) {
if (latest == null || 0 < compareVersion(item.getVersionName(), latest.getVersionName())) {
latest = item;
}
}
return latest;
}
/// 判断设备是否命中灰度
///
/// @param grayPermille 灰度比例,万分比
/// @param deviceId 设备标识
/// @param appKey 产品标识
/// @return true 为命中
private boolean hitGray(Integer grayPermille, String deviceId, String appKey) {
if (grayPermille == null || GRAY_BASE <= grayPermille) {
return true;
}
if (TimiJava.isEmpty(deviceId)) {
return false;
}
CRC32 crc = new CRC32();
crc.update((deviceId + ":" + appKey).getBytes(StandardCharsets.UTF_8));
return crc.getValue() % GRAY_BASE < grayPermille;
}
/// 构造更新响应
///
/// note 为历史构建号时不下发,避免客户端把它当成更新说明展示
///
/// @param release 发布记录
/// @param mandatory true 为强制更新
/// @param shell true 为外壳安装包,客户端需要下载后覆盖安装
/// @return 更新响应
private AppUpdateCheckResponse buildResponse(AppRelease release, boolean mandatory, boolean shell) {
String url = ServletUriComponentsBuilder.fromCurrentContextPath()
.path("/attach/download/")
.path(release.getAttachmentId())
.toUriString();
return new AppUpdateCheckResponse(release.getVersionName(), url, release.getSha256(), mandatory, shell, release.getNote(), null, null, null, null);
}
/// 比较版本号
///
/// 只处理数字段,预发布标识按 0 处理
///
/// @param a 版本 A
/// @param b 版本 B
/// @return 负数表示 A 小于 B
private int compareVersion(String a, String b) {
if (BUILTIN_VERSION.equals(a)) {
return -1;
}
if (BUILTIN_VERSION.equals(b)) {
return 1;
}
String[] left = a.split("\\.");
String[] right = b.split("\\.");
int length = Math.max(left.length, right.length);
for (int i = 0; i < length; i++) {
int x = i < left.length ? parseInt(left[i], 0) : 0;
int y = i < right.length ? parseInt(right[i], 0) : 0;
if (x != y) {
return 0 < Integer.compare(x, y) ? 1 : -1;
}
}
return 0;
}
/// 安全解析整数
///
/// @param value 原始值
/// @param defaultValue 默认值
/// @return 解析结果
private int parseInt(String value, int defaultValue) {
if (TimiJava.isEmpty(value)) {
return defaultValue;
}
try {
return Integer.parseInt(value.trim());
} catch (NumberFormatException e) {
return defaultValue;
}
}
/// 解析平台
///
/// @param platform 平台字符串
/// @return 平台枚举
private AppProduct.Platform parsePlatform(String platform) {
if (TimiJava.isEmpty(platform)) {
return AppProduct.Platform.ANDROID;
}
try {
return AppProduct.Platform.valueOf(platform.trim().toUpperCase());
} catch (IllegalArgumentException e) {
return AppProduct.Platform.ANDROID;
}
}
/// 发布版本
///
/// @param releaseId 发布 ID
/// @param channelCode 通道代码
/// @param grayPermille 灰度比例,为空时保持原值
/// @param operatorId 操作人用户 ID
/// @param note 变更说明
@Transactional(TimiServerDBConfig.ROLLBACKER)
public void publish(String releaseId, String channelCode, Integer grayPermille, String operatorId, String note) {
AppRelease release = releaseMapper.select(releaseId);
if (release == null) {
throw new IllegalArgumentException("发布记录不存在");
}
AppChannel channel = channelMapper.selectByProductAndCode(release.getProductId(), channelCode);
if (channel == null) {
throw new IllegalArgumentException("通道不存在");
}
checkCompatibility(release);
Long now = System.currentTimeMillis();
// 发布不指定灰度按全量处理:草稿默认是 0,直接沿用会让所有设备都拿不到包
release.setGrayPermille(grayPermille == null ? (int) GRAY_BASE : grayPermille);
release.setStatus(AppRelease.Status.PUBLISHED);
if (release.getPublishedAt() == null) {
release.setPublishedAt(now);
}
release.setNote(TimiJava.isEmpty(note) ? release.getNote() : note);
release.setUpdatedAt(now);
releaseMapper.updateSelective(release);
channelMapper.updatePointers(channel.getId(), releaseId, release.getKind() == AppRelease.Kind.NATIVE, operatorId, now);
log("APP_RELEASE_PUBLISH", releaseId);
}
/// 回滚通道到指定发布
///
/// 回滚只改指针,同时把目标版本灰度拉满,否则只有部分设备能回退
///
/// @param productId 产品 ID
/// @param channelCode 通道代码
/// @param targetReleaseId 目标发布 ID
/// @param operatorId 操作人用户 ID
@Transactional(TimiServerDBConfig.ROLLBACKER)
public void rollback(String productId, String channelCode, String targetReleaseId, String operatorId) {
AppChannel channel = channelMapper.selectByProductAndCode(productId, channelCode);
if (channel == null) {
throw new IllegalArgumentException("通道不存在");
}
AppRelease target = releaseMapper.select(targetReleaseId);
if (target == null || !target.getProductId().equals(productId)) {
throw new IllegalArgumentException("目标发布不存在");
}
Long now = System.currentTimeMillis();
target.setGrayPermille((int) GRAY_BASE);
target.setStatus(AppRelease.Status.PUBLISHED);
target.setUpdatedAt(now);
releaseMapper.updateSelective(target);
channelMapper.updatePointers(channel.getId(), targetReleaseId, target.getKind() == AppRelease.Kind.NATIVE, operatorId, now);
log("APP_RELEASE_ROLLBACK", targetReleaseId);
}
/// 撤回发布
///
/// @param releaseId 发布 ID
/// @param operatorId 操作人用户 ID
@Transactional(TimiServerDBConfig.ROLLBACKER)
public void revoke(String releaseId, String operatorId) {
AppRelease release = releaseMapper.select(releaseId);
if (release == null) {
throw new IllegalArgumentException("发布记录不存在");
}
Long now = System.currentTimeMillis();
release.setStatus(AppRelease.Status.REVOKED);
release.setUpdatedAt(now);
releaseMapper.updateSelective(release);
channelMapper.clearRelease(release.getProductId(), releaseId, operatorId, now);
log("APP_RELEASE_REVOKE", releaseId);
}
/// 创建发布记录
///
/// @param release 发布记录
/// @param operatorId 操作人用户 ID
/// @return 创建后的记录
public AppRelease create(AppRelease release, String operatorId) {
AppRelease exists = releaseMapper.selectByVersion(release.getProductId(), release.getKind(), release.getVersionName());
if (exists != null) {
throw new IllegalArgumentException("版本已存在,不可重复使用版本号");
}
checkCompatibility(release);
Long now = System.currentTimeMillis();
release.setStatus(AppRelease.Status.DRAFT);
release.setGrayPermille(release.getGrayPermille() == null ? 0 : release.getGrayPermille());
release.setMandatory(Boolean.TRUE.equals(release.getMandatory()));
release.setCreatedBy(operatorId);
release.setCreatedAt(now);
releaseMapper.insert(release);
return release;
}
/// 查询产品列表
///
/// @return 产品列表
public List<AppProduct> listProducts() {
return productMapper.selectAll();
}
/// 保存产品
///
/// @param product 产品
/// @return 保存后的产品
public AppProduct saveProduct(AppProduct product) {
Long now = System.currentTimeMillis();
if (TimiJava.isEmpty(product.getId())) {
product.setEnabled(product.getEnabled() == null || product.getEnabled());
product.setCreatedAt(now);
productMapper.insert(product);
return product;
}
product.setUpdatedAt(now);
productMapper.updateSelective(product);
return productMapper.select(product.getId());
}
/// 查询产品发布列表
///
/// @param productId 产品 ID
/// @return 发布列表
public List<AppRelease> listReleases(String productId) {
return releaseMapper.selectByProduct(productId);
}
/// 查询产品通道列表
///
/// @param productId 产品 ID
/// @return 通道列表
public List<AppChannel> listChannels(String productId) {
return channelMapper.selectByProduct(productId);
}
/// 删除草稿发布
///
/// 已发布的版本不允许删除,必须走撤回
///
/// @param releaseId 发布 ID
/// @param operatorId 操作人用户 ID
public void deleteRelease(String releaseId, String operatorId) {
AppRelease release = releaseMapper.select(releaseId);
if (release == null) {
throw new IllegalArgumentException("发布记录不存在");
}
if (release.getStatus() == AppRelease.Status.PUBLISHED) {
throw new IllegalArgumentException("已发布的版本不能删除,请先撤回");
}
releaseMapper.delete(releaseId);
log("APP_RELEASE_DELETE", releaseId);
}
/// 删除通道
///
/// @param channelId 通道 ID
/// @param operatorId 操作人用户 ID
public void deleteChannel(String channelId, String operatorId) {
AppChannel channel = channelMapper.select(channelId);
if (channel == null) {
throw new IllegalArgumentException("通道不存在");
}
if (DEFAULT_CHANNEL.equals(channel.getCode())) {
throw new IllegalArgumentException("默认通道不能删除");
}
channelMapper.destroy(channelId);
log("APP_CHANNEL_DELETE", channelId);
}
/// 删除产品
///
/// 产品下仍有未删除的发布记录时拒绝删除,避免留下孤儿数据
///
/// @param productId 产品 ID
/// @param operatorId 操作人用户 ID
public void deleteProduct(String productId, String operatorId) {
AppProduct product = productMapper.select(productId);
if (product == null) {
throw new IllegalArgumentException("产品不存在");
}
if (!releaseMapper.selectByProduct(productId).isEmpty()) {
throw new IllegalArgumentException("产品下仍有发布记录,不能删除");
}
productMapper.destroy(productId);
log("APP_PRODUCT_DELETE", productId);
}
/// 校验兼容区间
///
/// @param release 发布记录
private void checkCompatibility(AppRelease release) {
if (release.getKind() != AppRelease.Kind.BUNDLE) {
if (release.getVersionCode() == null) {
throw new IllegalArgumentException("原生包必须指定 versionCode");
}
return;
}
if (release.getMinVersionCode() == null) {
throw new IllegalArgumentException("热更包必须指定兼容的最低原生 versionCode");
}
if (release.getMaxVersionCode() != null && release.getMaxVersionCode() < release.getMinVersionCode()) {
throw new IllegalArgumentException("兼容区间上限不能小于下限");
}
}
/// 写操作日志
///
/// @param action 操作标识
/// @param result 操作对象
private void log(String action, String result) {
Logger logger = new Logger(Logger.Module.APP, Logger.Level.INFO, action);
logger.setResult(result);
loggerService.create(logger);
}
}
@@ -0,0 +1,61 @@
package com.imyeyu.api.modules.app.vo;
import com.fasterxml.jackson.annotation.JsonProperty;
import lombok.Data;
///
/// 应用更新检查请求
///
/// 字段名遵循 Capgo 插件的上报协议,不可随意改名
///
/// @author Codex
/// @since 2026-11-06
@Data
public class AppUpdateCheckRequest {
/// 平台
@JsonProperty("platform")
protected String platform;
/// 设备标识,用于灰度分桶
@JsonProperty("device_id")
protected String deviceId;
/// 产品标识,取 Capacitor appId
@JsonProperty("app_id")
protected String appId;
/// 当前运行的 Web 包版本,内置包为 builtin
@JsonProperty("version_name")
protected String versionName;
/// 当前原生 versionCode
@JsonProperty("version_code")
protected String versionCode;
/// 当前原生版本名
@JsonProperty("version_build")
protected String versionBuild;
/// 插件版本
@JsonProperty("plugin_version")
protected String pluginVersion;
/// 系统版本
@JsonProperty("version_os")
protected String versionOs;
/// true 为模拟器
@JsonProperty("is_emulator")
protected Boolean emulator;
/// true 为生产包
@JsonProperty("is_prod")
protected Boolean prod;
/// 通道代码,为空时取 stable
protected String channel;
/// 检查接口密钥
protected String key;
}
@@ -0,0 +1,61 @@
package com.imyeyu.api.modules.app.vo;
import com.fasterxml.jackson.annotation.JsonInclude;
import lombok.AllArgsConstructor;
import lombok.Data;
///
/// 应用更新检查响应
///
/// Capgo 插件要求 url 必须存在,无更新时回显当前版本号让插件跳过下载
///
/// @author Codex
/// @since 2026-11-06
@Data
@AllArgsConstructor
@JsonInclude(JsonInclude.Include.NON_NULL)
public class AppUpdateCheckResponse {
/// 版本号
protected String version;
/// 产物下载地址
protected String url;
/// 产物 SHA-256
protected String checksum;
/// 是否为强制更新
protected Boolean mandatory;
/// 是否为外壳安装包
///
/// 客户端据此判断走热更还是下载安装包。字段名不能叫 kind:
/// Capgo 插件把 kind 视为错误响应的标记,收到后会直接判为检查失败
protected Boolean shell;
/// 变更说明,供 App 展示更新日志
///
/// 字段名不能叫 message:Capgo 插件把 message 当作错误信息,收到会直接判为检查失败
protected String note;
/// 外壳下载地址
protected String shellUrl;
/// 外壳版本
protected String shellVersion;
/// 外壳 SHA-256
protected String shellChecksum;
/// true 为强制更新
protected Boolean shellMandatory;
/// 构建无更新响应,version 与当前一致时插件不会下载
///
/// @param currentVersion 当前运行的 Web 包版本
/// @return 无更新响应
public static AppUpdateCheckResponse none(String currentVersion) {
return new AppUpdateCheckResponse(currentVersion, "", null, false, null, null, null, null, null, null);
}
}
@@ -0,0 +1,23 @@
package com.imyeyu.api.modules.app.vo;
import lombok.AllArgsConstructor;
import lombok.Data;
///
/// 单条版本变更说明
///
/// @author Codex
/// @since 2026-11-13
@Data
@AllArgsConstructor
public class AppUpdateNote {
/// 版本号
protected String version;
/// 变更说明,来自发布记录的 note
protected String note;
/// 首次发布时间
protected Long publishedAt;
}
@@ -0,0 +1,24 @@
package com.imyeyu.api.modules.app.vo;
import lombok.AllArgsConstructor;
import lombok.Data;
import java.util.List;
///
/// 应用更新日志响应
///
/// 供 App 的版本历史页使用,返回当前运行版本到目标版本之间的全部变更说明
///
/// @author Codex
/// @since 2026-11-13
@Data
@AllArgsConstructor
public class AppUpdateNotesResponse {
/// 目标版本号,为空表示当前没有可更新到的版本
protected String version;
/// 变更说明,按版本号从新到旧
protected List<AppUpdateNote> notes;
}
@@ -1,7 +1,7 @@
package com.imyeyu.api.modules.common.controller;
import com.imyeyu.api.modules.common.entity.Attachment;
import com.imyeyu.api.modules.common.bean.attachment.ThumbnailFitMode;
import com.imyeyu.api.modules.common.entity.Attachment;
import com.imyeyu.api.modules.common.service.AttachmentService;
import com.imyeyu.api.modules.common.service.AttachmentVariantService;
import com.imyeyu.api.modules.common.service.TempFileService;
@@ -68,6 +68,8 @@ public class AttachmentController {
@PostMapping(value = "/create", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
public Attachment create(Attachment attachment) {
service.create(attachment);
attachment.setFile(null);
attachment.setInputStream(null);
return attachment;
}
@@ -258,7 +260,9 @@ public class AttachmentController {
}
private void setDownloadHeader(Attachment attachment) throws UnsupportedEncodingException {
if (attachment != null && TimiSpring.getRequest().getRequestURI().endsWith("/download") && attachment.getName() != null) {
// 路径带 /download 就强制下载:/download/{id} 的结尾是 id,用 endsWith 匹配不到
boolean download = TimiSpring.getRequest().getRequestURI().contains("/download");
if (attachment != null && download && attachment.getName() != null) {
TimiSpring.getResponse().setHeader("Content-Disposition", Network.getFileDownloadHeader(attachment.getName()));
}
}
@@ -10,6 +10,10 @@ import com.imyeyu.spring.annotation.RequestRateLimit;
import com.imyeyu.spring.bean.Page;
import com.imyeyu.spring.bean.PageResult;
import com.imyeyu.spring.util.ResponseView;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.security.SecurityRequirements;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
@@ -21,12 +25,11 @@ import org.springframework.web.bind.annotation.RestController;
import java.util.List;
import java.util.Map;
/**
*
*
* @author 夜雨
* @since 2026-04-23 16:31
*/
/// 系统配置接口
///
/// @author 夜雨
/// @since 2026-04-23 16:31
@Tag(name = "系统-配置", description = "系统配置公开查询与管理接口")
@Slf4j
@RestController
@RequiredArgsConstructor
@@ -43,12 +46,17 @@ public class SettingController {
* @param code 配置代码列表,可为空
* @return 公开配置映射
*/
@Operation(summary = "查询公开配置映射", description = "按业务类型查询公开配置,返回以配置代码为键的映射;无需登录。")
@SecurityRequirements
@JsonView(ResponseView.Public.class)
@RequestRateLimit
@RequestMapping("/map")
public Map<String, Setting> map(
@Parameter(description = "业务类型", required = true)
@RequestParam String bizType,
@Parameter(description = "业务 ID,系统级配置省略")
@RequestParam(required = false) String bizId,
@Parameter(description = "配置代码列表,省略时返回全部公开配置")
@RequestParam(required = false) List<String> code
) {
return service.mapPublic(bizType, bizId, code);
@@ -60,6 +68,7 @@ public class SettingController {
* @param page 分页查询
* @return 配置列表
*/
@Operation(summary = "查询配置列表", description = "分页查询配置,需要 SETTING:READ 权限。")
@JsonView(ResponseView.Admin.class)
@RequestRateLimit
@RequireCorePermission(CorePermissionCode.SETTING_READ)
@@ -74,11 +83,14 @@ public class SettingController {
* @param id 配置 ID
* @return 配置详情
*/
@Operation(summary = "查询配置详情", description = "按配置 ID 查询配置,需要 SETTING:READ 权限。")
@JsonView(ResponseView.Admin.class)
@RequestRateLimit
@RequireCorePermission(CorePermissionCode.SETTING_READ)
@PostMapping("/detail")
public Setting detail(@RequestBody String id) {
public Setting detail(
@io.swagger.v3.oas.annotations.parameters.RequestBody(description = "配置 ID", required = true)
@RequestBody String id) {
return service.get(id);
}
@@ -88,6 +100,7 @@ public class SettingController {
* @param setting 配置
* @return 配置
*/
@Operation(summary = "创建配置", description = "创建配置,需要 SETTING:CREATE 权限。")
@AOPLog
@JsonView(ResponseView.Admin.class)
@RequireCorePermission(CorePermissionCode.SETTING_CREATE)
@@ -103,6 +116,7 @@ public class SettingController {
*
* @param setting 配置
*/
@Operation(summary = "更新配置", description = "更新配置,需要 SETTING:UPDATE 权限。")
@AOPLog
@RequestRateLimit
@RequireCorePermission(CorePermissionCode.SETTING_UPDATE)
@@ -116,11 +130,14 @@ public class SettingController {
*
* @param id 配置 ID
*/
@Operation(summary = "删除配置", description = "按配置 ID 删除配置,需要 SETTING:DELETE 权限。")
@AOPLog
@RequestRateLimit
@RequireCorePermission(CorePermissionCode.SETTING_DELETE)
@PostMapping("/delete")
public void delete(@RequestBody String id) {
public void delete(
@io.swagger.v3.oas.annotations.parameters.RequestBody(description = "配置 ID", required = true)
@RequestBody String id) {
service.delete(id);
}
}
@@ -56,9 +56,23 @@ public class Attachment extends UUIDEntity {
GAO_POINT_REDEMPTION_RETURN,
GAO_RECYCLE_ITEM,
GAO_RECYCLE_EXCHANGE,
GAO_RECYCLE_EXCHANGE_REVOKE,
GAO_RECYCLE_PAYMENT,
GAO_CUSTOMER_FOLLOW_UP_REMINDER,
GAO_DATA_EXPORT,
TEMP_FILE,
MIRROR
MIRROR,
APP_RELEASE
}
protected BizType bizType;
@@ -77,6 +77,19 @@ public class Setting extends UUIDEntity {
JSON_OBJECT
}
/// 配置作用域
///
/// @author Codex
/// @since 2026-11-16
public enum Scope {
/// 系统级,bizId 固定为全零 UUID,启动时自动初始化
SYSTEM,
/// 业务级,bizId 为业务对象 ID,启动时不初始化
BUSINESS
}
@JsonView(ResponseView.Public.class)
private String bizType;
@@ -1,5 +1,6 @@
package com.imyeyu.api.modules.common.entity;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.imyeyu.api.annotation.MultilingualField;
import com.imyeyu.spring.annotation.table.Transient;
import com.imyeyu.spring.entity.UUIDEntity;
@@ -40,4 +41,9 @@ public class Tag extends UUIDEntity {
/// 中文名称
@Transient
protected String zhCN;
/// 当前查询业务下的使用量
@Transient
@JsonInclude(JsonInclude.Include.NON_NULL)
protected Long useCount;
}
@@ -18,6 +18,16 @@ public interface NotifyMapper extends BaseMapper<Notify, String> {
/// 原子创建业务提醒
int insertIfAbsent(Notify notify);
/// 按业务查重键查询未删除通知
///
/// @param bizType 业务类型
/// @param bizRemindedType 业务提醒类型
/// @param bizRemindedKey 业务提醒查重键
/// @return 通知
Notify selectByBusinessKey(@Param("bizType") String bizType,
@Param("bizRemindedType") String bizRemindedType,
@Param("bizRemindedKey") String bizRemindedKey);
/// 分页查询管理端通知
///
/// @param userId 管理员用户 ID
@@ -1,6 +1,8 @@
package com.imyeyu.api.modules.common.mapper;
import com.imyeyu.api.modules.common.entity.Tag;
import com.imyeyu.api.modules.common.entity.TagApply;
import com.imyeyu.spring.bean.Page;
import com.imyeyu.spring.mapper.BaseMapper;
import org.apache.ibatis.annotations.Param;
@@ -33,5 +35,23 @@ public interface TagMapper extends BaseMapper<Tag, String> {
/// @return 标签列表
List<Tag> selectByOwnerAndKeyword(@Param("ownerType") Tag.OwnerType ownerType, @Param("ownerId") String ownerId, @Param("keyword") String keyword, @Param("offset") long offset, @Param("limit") long limit);
/// 按归属和名称关键词分页查询标签,并统计指定业务的使用量
///
/// @param ownerType 归属类型
/// @param ownerId 归属 ID
/// @param keyword 名称关键词
/// @param bizType 业务类型
/// @param offset 分页偏移量
/// @param limit 分页数量
/// @return 标签列表
List<Tag> selectByOwnerAndKeywordWithUseCount(@Param("page") Page<Tag> page, @Param("ownerType") Tag.OwnerType ownerType, @Param("ownerId") String ownerId, @Param("keyword") String keyword, @Param("bizType") TagApply.BizType bizType, @Param("offset") long offset, @Param("limit") long limit);
/// 查询指定标签在指定业务下的使用量
///
/// @param tagId 标签 ID
/// @param bizType 业务类型
/// @return 使用量
long countUseByTagIdAndBizType(@Param("tagId") String tagId, @Param("bizType") TagApply.BizType bizType);
Tag selectByOwnerAndZhCN(@Param("ownerType") Tag.OwnerType ownerType, @Param("ownerId") String ownerId, @Param("zhCN") String zhCN);
}
@@ -18,6 +18,11 @@ import java.util.Map;
*/
public interface AttachmentService extends BaseService<Attachment, String> {
/// 在无 HTTP 请求上下文时创建系统生成的附件
///
/// @param attachment 待创建附件
void createBySystem(Attachment attachment);
///
/// 克隆附件,复制业务属性和文件内容并生成新的附件记录
///
@@ -26,6 +26,12 @@ public interface NotifyDetailService extends BaseService<NotifyDetail, String> {
/// @param detailId 通知详情 ID
void requeue(String detailId);
/// 取消尚未生效的通知详情
///
/// @param detailId 通知详情 ID
/// @param reason 取消原因
void cancelPending(String detailId, String reason);
/// 分页查询用户的站内通知
///
/// @param page 分页参数
@@ -19,6 +19,14 @@ public interface NotifyService extends BaseService<Notify, String> {
/// @param notify 通知
void createIfAbsent(Notify notify);
/// 按业务查重键查询未删除通知
///
/// @param bizType 业务类型
/// @param bizRemindedType 业务提醒类型
/// @param bizRemindedKey 业务提醒查重键
/// @return 通知
Notify getByBusinessKey(String bizType, String bizRemindedType, String bizRemindedKey);
/// 分页查询当前用户创建的通知
///
/// @param page 分页参数
@@ -26,6 +26,23 @@ public interface TagService extends BaseService<Tag, String> {
/// @return 标签分页
PageResult<Tag> pageByOwnerAndKeyword(Page<Tag> page, Tag.OwnerType ownerType, String ownerId, String keyword);
/// 按归属和名称关键词分页查询标签,并按指定业务的使用量排序
///
/// @param page 分页参数
/// @param ownerType 归属类型
/// @param ownerId 归属 ID
/// @param keyword 名称关键词
/// @param bizType 业务类型
/// @return 标签分页
PageResult<Tag> pageByOwnerAndKeywordWithUseCount(Page<Tag> page, Tag.OwnerType ownerType, String ownerId, String keyword, TagApply.BizType bizType);
/// 查询指定标签在指定业务下的使用量
///
/// @param tagId 标签 ID
/// @param bizType 业务类型
/// @return 使用量
long countUseByTagIdAndBizType(String tagId, TagApply.BizType bizType);
/// 按业务查询标签列表
///
/// @param bizType 业务类型
@@ -66,6 +66,20 @@ public class AttachmentServiceImplement extends AbstractEntityService<Attachment
@Transactional(TimiServerDBConfig.ROLLBACKER)
@Override
public void create(Attachment attachment) {
createInternal(attachment, TimiSpring.getRequestIP());
}
@Transactional(TimiServerDBConfig.ROLLBACKER)
@Override
public void createBySystem(Attachment attachment) {
createInternal(attachment, "SYSTEM");
}
/// 创建附件并记录上传来源
///
/// @param attachment 待创建附件
/// @param uploaderIp 上传来源 IP
private void createInternal(Attachment attachment, String uploaderIp) {
TimiException.required(attachment.getBizType(), "not found String");
TimiException.required(attachment.getName(), "not found attachment.name");
String mongoId = null;
@@ -82,7 +96,7 @@ public class AttachmentServiceImplement extends AbstractEntityService<Attachment
attachment.setSize(gridFSFile.getLength());
attachment.setMd5(IO.md5(gridFSBucket.openDownloadStream(gridFSFile.getObjectId())));
attachment.setMimeType(new Tika().detect(gridFSBucket.openDownloadStream(gridFSFile.getObjectId())));
attachment.setUploaderIp(TimiSpring.getRequestIP());
attachment.setUploaderIp(uploaderIp);
attachment.setIsDestroyed(false);
if (attachment.getMimeType().startsWith("image")) {
BufferedImage image = ImageIO.read(gridFSBucket.openDownloadStream(gridFSFile.getObjectId()));
@@ -184,6 +198,7 @@ public class AttachmentServiceImplement extends AbstractEntityService<Attachment
try (InputStream inputStream = getInputStreamByMongoId(source.getMongoId())) {
target.setInputStream(inputStream);
create(target);
target.setInputStream(null);
return target;
} catch (IOException e) {
if (target.getMongoId() != null) {
@@ -229,6 +244,9 @@ public class AttachmentServiceImplement extends AbstractEntityService<Attachment
@Override
public InputStream getInputStreamByMongoId(String mongoId) {
GridFSFile gridFSFile = gridFsTemplate.findOne(new Query(Criteria.where("_id").is(mongoId)));
if (gridFSFile == null) {
throw new java.util.NoSuchElementException("GridFS file not found: " + mongoId);
}
return gridFSBucket.openDownloadStream(gridFSFile.getObjectId());
}
@@ -301,6 +319,10 @@ public class AttachmentServiceImplement extends AbstractEntityService<Attachment
throw new TimiException(TimiCode.ERROR, "exception.attachment.file.required");
}
Attachment tempFile = mapper.selectRaw(tempFileId);
if (tempFile == null) {
// 临时文件不存在或已过期,按业务错误拒绝,避免空指针变成 500
throw new TimiException(TimiCode.ERROR, "exception.attachment.file.notfound");
}
tempFile.setBizType(bizType);
tempFile.setBizId(bizId);
tempFile.setAttachType(item.getAttachType());
@@ -319,6 +341,10 @@ public class AttachmentServiceImplement extends AbstractEntityService<Attachment
// 将临时文件的 GridFS 存储转移至当前永久记录,废弃临时记录
Attachment current = mapper.selectRaw(item.getId());
Attachment tempFile = mapper.selectRaw(tempFileId);
if (current == null || tempFile == null) {
// 附件或临时文件已被清理,按业务错误拒绝
throw new TimiException(TimiCode.ERROR, "exception.attachment.file.notfound");
}
// 源文件版本已变化,旧缩略图全部失效
variantService.deleteBySourceId(current.getId());
// 删除旧 GridFS 文件
@@ -57,7 +57,7 @@ public class AttachmentVariantServiceImplement implements AttachmentVariantServi
private static final int THUMB_MAX_HEIGHT = 4096;
private static final long THUMB_MAX_PIXELS = 16_000_000L;
private static final long THUMB_CACHE_TTL = Time.D * 7;
private static final long THUMB_LOCK_TTL = Time.M * 10;
private static final long THUMB_LOCK_TTL = Time.M;
private static final double THUMB_TARGET_SECONDS = 2;
private static final int VARIANT_NAME_MAX_LENGTH = 255;
private static final String THUMB_OUTPUT_FORMAT = "png";
@@ -24,7 +24,7 @@ import java.util.List;
@RequiredArgsConstructor
public class MultilingualServiceImplement extends AbstractEntityService<Multilingual, String> implements MultilingualService {
private static final String KEY_PREFIX = "MULTILINGUAL:";
private static final String KEY_PREFIX = "MULTILINGUAL:V2:";
private final MultilingualMapper mapper;
@@ -108,6 +108,36 @@ public class NotifyDetailServiceImplement extends AbstractEntityService<NotifyDe
super.delete(detailId);
}
/// 取消尚未生效的通知详情
///
/// @param detailId 通知详情 ID
/// @param reason 取消原因
@Override
@Transactional(TimiServerDBConfig.ROLLBACKER)
public void cancelPending(String detailId, String reason) {
TimiException.required(detailId, "未找到通知详情 ID");
NotifyDetail detail = get(detailId);
TimiException.required(detail, "未找到通知详情");
if (detail.getStatus() == NotifyDetail.Status.CANCEL) {
return;
}
long now = Time.now();
boolean canCancel = detail.getMsgType() == NotifyDetail.MsgType.INTERNAL
? detail.getSendAt() != null && now < detail.getSendAt()
: detail.getMsgType() != null && detail.getMsgType().isQueue()
&& detail.getStatus() == NotifyDetail.Status.WAITING;
if (!canCancel) {
return;
}
if (detail.getMsgType().isQueue()) {
detail.getMsgType().getService().destroyQueue(detail);
}
detail.setStatus(NotifyDetail.Status.CANCEL);
detail.setResultDesc(TimiJava.defaultIfEmpty(reason, "通知已取消"));
update(detail);
}
/// 重新将通知详情放入消息队列
///
/// @param detailId 通知详情 ID
@@ -69,6 +69,20 @@ public class NotifyServiceImplement extends AbstractEntityService<Notify, String
createDetails(notify);
}
/// 按业务查重键查询未删除通知
///
/// @param bizType 业务类型
/// @param bizRemindedType 业务提醒类型
/// @param bizRemindedKey 业务提醒查重键
/// @return 通知
@Override
public Notify getByBusinessKey(String bizType, String bizRemindedType, String bizRemindedKey) {
TimiException.required(bizType, "未找到通知业务类型");
TimiException.required(bizRemindedType, "未找到通知提醒类型");
TimiException.required(bizRemindedKey, "未找到通知查重键");
return mapper.selectByBusinessKey(bizType, bizRemindedType, bizRemindedKey);
}
/// 校验并补全通知创建字段
///
/// @param notify 通知
@@ -7,6 +7,7 @@ import com.imyeyu.api.modules.common.mapper.TagApplyMapper;
import com.imyeyu.api.modules.common.mapper.TagMapper;
import com.imyeyu.api.modules.common.service.MultilingualService;
import com.imyeyu.api.modules.common.service.TagService;
import com.imyeyu.java.TimiJava;
import com.imyeyu.java.bean.timi.TimiException;
import com.imyeyu.spring.bean.Page;
import com.imyeyu.spring.bean.PageResult;
@@ -82,6 +83,21 @@ public class TagServiceImplement extends AbstractEntityService<Tag, String> impl
return result;
}
@Override
public PageResult<Tag> pageByOwnerAndKeywordWithUseCount(Page<Tag> page, Tag.OwnerType ownerType, String ownerId, String keyword, TagApply.BizType bizType) {
PageResult<Tag> result = new PageResult<>();
result.setTotal(TimiJava.isNotEmpty(keyword)
? mapper.countByOwnerAndKeyword(ownerType, ownerId, keyword)
: mapper.countByPage(page));
result.setList(mapper.selectByOwnerAndKeywordWithUseCount(page, ownerType, ownerId, keyword, bizType, page.getOffset(), page.getLimit()));
return result;
}
@Override
public long countUseByTagIdAndBizType(String tagId, TagApply.BizType bizType) {
return mapper.countUseByTagIdAndBizType(tagId, bizType);
}
@Override
public List<Tag> listByBizType(TagApply.BizType bizType, String bizId) {
return listByIdList(listApply(bizType, bizId).stream().map(TagApply::getTagId).toList());
@@ -14,10 +14,6 @@ import org.springframework.stereotype.Component;
@Component
public class GaoAiProperties {
/// MCP 服务间密钥
@Value("${gao.ai.mcp-service-key:}")
private String mcpServiceKey;
/// AI 会话有效期,单位秒
@Value("${gao.ai.session-ttl-seconds:300}")
private long sessionTtlSeconds;
@@ -34,15 +30,55 @@ public class GaoAiProperties {
@Value("${gao.ai.read-timeout-seconds:600}")
private long readTimeoutSeconds;
/// true 为允许缺少 AI 会话时使用固定测试会话,仅用于本地调试
@Value("${gao.ai.allow-missing-session:false}")
private boolean allowMissingSession;
/// 是否启用智能体写能力
@Value("${gao.ai.write.enabled:false}")
private boolean writeEnabled;
/// 缺少 AI 会话时使用的测试用户 ID
@Value("${gao.ai.debug-user-id:dify-agent-debug}")
private String debugUserId;
/// 待确认操作有效期,单位秒
@Value("${gao.ai.write.confirmation-ttl-seconds:600}")
private long confirmationTtlSeconds;
/// 缺少 AI 会话时使用的测试门店 ID
@Value("${gao.ai.debug-store-id:00000000-0000-0000-0000-000000000001}")
private String debugStoreId;
/// 提交结果保留时间,单位秒
@Value("${gao.ai.write.result-ttl-seconds:1800}")
private long resultTtlSeconds;
/// 10 分钟内最大准备次数
@Value("${gao.ai.write.max-prepares-per-10-minutes:10}")
private int maxPreparesPer10Minutes;
/// 10 分钟内最大提交次数
@Value("${gao.ai.write.max-commits-per-10-minutes:10}")
private int maxCommitsPer10Minutes;
/// 单次 AI 会话最大工具调用次数
@Value("${gao.ai.write.max-tool-calls-per-session:30}")
private int maxToolCallsPerSession;
/// 单个订单最大成交金额,单位分
@Value("${gao.ai.write.order-max-sale-amount:1000000}")
private long orderMaxSaleAmount;
/// 订单/套餐最大折扣率,0.30 表示最多优惠 30%
@Value("${gao.ai.write.max-discount-rate:0.30}")
private double maxDiscountRate;
/// 单次积分调整最大绝对值
@Value("${gao.ai.write.point-adjust-max-abs:10000}")
private long pointAdjustMaxAbs;
/// 单次库存变更最大数量
@Value("${gao.ai.write.stock-change-max-quantity:1000}")
private long stockChangeMaxQuantity;
/// 单次操作最大附件数
@Value("${gao.ai.write.attachment-max-count:10}")
private int attachmentMaxCount;
/// 单个附件最大大小,单位 MB
@Value("${gao.ai.write.attachment-max-size-mb:10}")
private long attachmentMaxSizeMb;
/// 附件凭证有效期,单位秒
@Value("${gao.ai.write.attachment-ttl-seconds:86400}")
private long attachmentTtlSeconds;
}
@@ -1,8 +1,11 @@
package com.imyeyu.api.modules.gao.ai.controller;
import com.fasterxml.jackson.databind.JsonNode;
import com.imyeyu.api.modules.gao.ai.service.GaoAiAccessException;
import com.imyeyu.api.modules.gao.ai.service.GaoAiChatService;
import com.imyeyu.api.modules.gao.ai.vo.GaoAiChatRequest;
import com.imyeyu.api.modules.gao.ai.vo.GaoAiConversationListRequest;
import com.imyeyu.api.modules.gao.ai.vo.GaoAiConversationReadRequest;
import com.imyeyu.spring.annotation.IgnoreGlobalReturn;
import com.imyeyu.spring.annotation.RequestRateLimit;
import lombok.RequiredArgsConstructor;
@@ -10,6 +13,7 @@ import org.springframework.http.HttpStatus;
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 org.springframework.web.server.ResponseStatusException;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;
@@ -38,7 +42,57 @@ public class GaoAiChatController {
try {
return chatService.chat(request);
} catch (GaoAiAccessException e) {
throw new ResponseStatusException(HttpStatus.valueOf(e.getStatus()), e.getMessage(), e);
throw accessException(e);
}
}
/// 列出当前登录用户的历史会话
///
/// @param request 历史会话分页请求
/// @return 历史会话分页结果
@RequestRateLimit
@PostMapping("/conversation/list")
public JsonNode listConversation(@RequestBody(required = false) GaoAiConversationListRequest request) {
try {
return chatService.listConversation(request);
} catch (GaoAiAccessException e) {
throw accessException(e);
}
}
/// 读取指定历史会话的消息
///
/// @param request 历史会话读取请求
/// @return 会话消息分页结果
@RequestRateLimit
@PostMapping("/conversation/read")
public JsonNode readConversation(@RequestBody GaoAiConversationReadRequest request) {
try {
return chatService.readConversation(request);
} catch (GaoAiAccessException e) {
throw accessException(e);
}
}
/// 删除当前登录用户的历史会话
///
/// @param conversationId Dify 会话 ID
/// @return 无
@RequestRateLimit
@PostMapping("/conversation/delete")
public void deleteConversation(@RequestParam String conversationId) {
try {
chatService.deleteConversation(conversationId);
} catch (GaoAiAccessException e) {
throw accessException(e);
}
}
/// 转换智能体访问异常
///
/// @param exception 智能体访问异常
/// @return HTTP 响应状态异常
private ResponseStatusException accessException(GaoAiAccessException exception) {
return new ResponseStatusException(HttpStatus.valueOf(exception.getStatus()), exception.getMessage(), exception);
}
}
@@ -0,0 +1,171 @@
package com.imyeyu.api.modules.gao.ai.controller;
import com.imyeyu.api.bean.ModuleCode;
import com.imyeyu.api.modules.gao.ai.operation.GaoAiAttachmentService;
import com.imyeyu.api.modules.gao.ai.operation.GaoAiOperationException;
import com.imyeyu.api.modules.gao.ai.operation.GaoAiOperationService;
import com.imyeyu.api.modules.gao.ai.operation.GaoAiPendingOperation;
import com.imyeyu.api.modules.gao.ai.operation.GaoAiPendingOperationService;
import com.imyeyu.api.modules.gao.ai.vo.GaoAiAttachmentView;
import com.imyeyu.api.modules.gao.ai.vo.GaoAiOperationCommitRequest;
import com.imyeyu.api.modules.gao.ai.vo.GaoAiToolResult;
import com.imyeyu.api.modules.gao.bean.GaoRoleCode;
import com.imyeyu.api.modules.gao.service.GaoStoreScopeService;
import com.imyeyu.api.modules.user.entity.User;
import com.imyeyu.api.modules.user.service.RoleChecker;
import com.imyeyu.api.modules.user.service.UserLoginService;
import com.imyeyu.java.bean.timi.TimiException;
import com.imyeyu.spring.annotation.RequestRateLimit;
import lombok.RequiredArgsConstructor;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.server.ResponseStatusException;
import java.util.List;
/// GAO 智能体写操作卡片和附件接口
///
/// 浏览器只使用登录令牌,不接触确认 token。
///
/// @author Codex
/// @since 2026-11-23
@RestController
@RequiredArgsConstructor
@RequestMapping("/gao/ai")
public class GaoAiOperationController {
private final GaoAiOperationService operationService;
private final GaoAiPendingOperationService pendingService;
private final GaoAiAttachmentService attachmentService;
private final UserLoginService userLoginService;
private final RoleChecker roleChecker;
private final GaoStoreScopeService storeScopeService;
/// 上传 AI 操作附件
///
/// @param files 文件列表
/// @param storeId 门店 ID,全局管理员必填
/// @return 附件凭证
@RequestRateLimit
@PostMapping(value = "/attachment/upload", consumes = "multipart/form-data")
public List<GaoAiAttachmentView> upload(@RequestParam("file") List<MultipartFile> files,
@RequestParam(required = false) String storeId) {
User user = requireAiUser();
String resolvedStoreId = resolveStoreId(storeId);
try {
return attachmentService.upload(user.getId(), resolvedStoreId, files).stream()
.map(item -> new GaoAiAttachmentView(item.token(), item.name(), item.mimeType(), item.size(), item.expiresAt()))
.toList();
} catch (GaoAiOperationException e) {
throw new ResponseStatusException(HttpStatus.BAD_REQUEST, e.getMessage(), e);
}
}
/// 查询当前待确认操作
///
/// @param conversationId Dify 会话 ID
/// @param storeId 门店 ID,全局管理员必填
/// @return 待确认操作视图
@RequestRateLimit
@GetMapping("/operation/pending")
public GaoAiToolResult pending(@RequestParam(required = false) String conversationId,
@RequestParam(required = false) String storeId) {
User user = requireAiUser();
return operationService.pending(user.getId(), resolveStoreId(storeId), conversationId);
}
/// 卡片确认提交
///
/// @param request 提交请求
/// @return 提交结果
@RequestRateLimit
@PostMapping("/operation/commit")
public GaoAiToolResult commit(@RequestBody GaoAiOperationCommitRequest request) {
User user = requireAiUser();
if (request == null || request.getOperationId() == null || request.getOperationId().isBlank()) {
throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "缺少操作 ID");
}
try {
GaoAiPendingOperation pending = pendingService.requireByOperationId(request.getOperationId());
if (!user.getId().equals(pending.getUserId())) {
throw new ResponseStatusException(HttpStatus.FORBIDDEN, "无权操作该待确认操作");
}
storeScopeService.checkStoreId(pending.getStoreId());
return operationService.commit(user.getId(), pending.getStoreId(), request.getConversationId(),
request.getOperationId(), request.getConfirmationPhrase(), request.getReason());
} catch (GaoAiOperationException e) {
return failure(e);
} catch (TimiException e) {
return failure("STORE_SCOPE_DENIED", e.getMessage());
}
}
/// 卡片取消
///
/// @param request 取消请求
/// @return 取消结果
@RequestRateLimit
@PostMapping("/operation/cancel")
public GaoAiToolResult cancel(@RequestBody GaoAiOperationCommitRequest request) {
User user = requireAiUser();
if (request == null || request.getOperationId() == null || request.getOperationId().isBlank()) {
throw new ResponseStatusException(HttpStatus.BAD_REQUEST, "缺少操作 ID");
}
try {
GaoAiPendingOperation pending = pendingService.requireByOperationId(request.getOperationId());
if (!user.getId().equals(pending.getUserId())) {
throw new ResponseStatusException(HttpStatus.FORBIDDEN, "无权操作该待确认操作");
}
storeScopeService.checkStoreId(pending.getStoreId());
return operationService.cancel(user.getId(), pending.getStoreId(), request.getOperationId());
} catch (GaoAiOperationException e) {
return failure(e);
} catch (TimiException e) {
return failure("STORE_SCOPE_DENIED", e.getMessage());
}
}
private GaoAiToolResult failure(GaoAiOperationException exception) {
return failure(exception.getErrorCode(), exception.getMessage());
}
private GaoAiToolResult failure(String errorCode, String errorMessage) {
GaoAiToolResult result = new GaoAiToolResult();
result.setStatus("FAILED");
result.setErrorCode(errorCode);
result.setErrorMessage(errorMessage);
result.setRetryable(false);
return result;
}
private User requireAiUser() {
User user = userLoginService.getLoginUser();
if (user == null) {
throw new ResponseStatusException(HttpStatus.UNAUTHORIZED, "登录已过期,请重新登录");
}
if (!roleChecker.hasAny(ModuleCode.GAO, GaoRoleCode.STORE_MANAGER.name())) {
throw new ResponseStatusException(HttpStatus.FORBIDDEN, "当前账号无权使用门店智能助手");
}
return user;
}
private String resolveStoreId(String requestedStoreId) {
try {
String storeId = storeScopeService.resolveStoreId(requestedStoreId);
if (storeId == null || storeId.isBlank()) {
throw new ResponseStatusException(HttpStatus.FORBIDDEN, "当前账号没有可用的所属门店");
}
return storeId;
} catch (ResponseStatusException e) {
throw e;
} catch (RuntimeException e) {
throw new ResponseStatusException(HttpStatus.FORBIDDEN, "当前账号没有可用的所属门店", e);
}
}
}
@@ -37,4 +37,37 @@ public class GaoAiAuditLog {
/// 记录时间,单位毫秒
private long createdAt;
/// 审计动作
private String action;
/// 写操作代码
private String operation;
/// 公开操作 ID
private String operationId;
/// 幂等请求号
private String requestNo;
/// 确认 token 摘要
private String confirmationTokenDigest;
/// 风险级别
private String riskLevel;
/// 结果实体类型
private String entityType;
/// 结果实体 ID
private String entityId;
/// 错误码
private String errorCode;
/// true 为幂等重放
private boolean idempotentReplay;
/// 原因摘要
private String reasonDigest;
}
@@ -28,7 +28,7 @@ public class GaoAiSession {
/// Dify 会话 ID,可为空
private String difyConversationId;
/// 允许调用的只读工具
/// 允许调用的工具
private Set<String> allowedTools = new LinkedHashSet<>();
/// 过期时间,单位毫秒
@@ -1,9 +1,10 @@
package com.imyeyu.api.modules.gao.ai.mcp;
import com.imyeyu.api.modules.gao.ai.config.GaoAiProperties;
import com.imyeyu.api.modules.common.service.SettingService;
import com.imyeyu.api.modules.gao.ai.entity.GaoAiSession;
import com.imyeyu.api.modules.gao.ai.service.GaoAiSessionService;
import com.imyeyu.api.modules.gao.ai.service.implement.GaoAiSessionServiceImplement.GaoAiSessionException;
import com.imyeyu.api.modules.gao.bean.GaoSystemSetting;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
@@ -20,23 +21,34 @@ import java.security.MessageDigest;
@RequiredArgsConstructor
public class GaoAiMcpAuthentication {
private final GaoAiProperties properties;
private final SettingService settingService;
private final GaoAiSessionService sessionService;
/// 校验 Dify 服务密钥和 AI 会话
///
/// @param authorization Authorization 请求头
/// @param sessionId X-Timi-AI-Session 请求头
/// @param headerSessionId X-Timi-AI-Session 请求头
/// @param argumentSessionId MCP 工具参数中的 AI 会话 ID
/// @param toolName 工具名称,可为空
/// @return 已认证会话
public GaoAiSession authenticate(String authorization, String sessionId, String toolName) {
authenticateService(authorization);
if (isBlank(sessionId) && properties.isAllowMissingSession()) {
GaoAiSession session = debugSession();
if (toolName != null && !session.getAllowedTools().contains(toolName)) {
throw new GaoAiSessionException("AI 会话无权调用该工具", 403);
}
return session;
public GaoAiSession authenticate(String authorization, String headerSessionId, String argumentSessionId, String toolName) {
return authenticate(authorization, headerSessionId, argumentSessionId, toolName, false);
}
/// 校验 Dify 服务密钥和 AI 会话
///
/// @param authorization Authorization 请求头
/// @param headerSessionId X-Timi-AI-Session 请求头
/// @param argumentSessionId MCP 工具参数中的 AI 会话 ID
/// @param toolName 工具名称,可为空
/// @param commit true 为提交 Provider
/// @return 已认证会话
public GaoAiSession authenticate(String authorization, String headerSessionId, String argumentSessionId,
String toolName, boolean commit) {
authenticateService(authorization, commit);
String sessionId = headerSessionId;
if (isBlank(sessionId) && !isBlank(argumentSessionId)) {
sessionId = argumentSessionId;
}
GaoAiSession session = sessionService.require(sessionId);
if (toolName != null && (session.getAllowedTools() == null || !session.getAllowedTools().contains(toolName))) {
@@ -51,9 +63,22 @@ public class GaoAiMcpAuthentication {
///
/// @param authorization Authorization 请求头
public void authenticateService(String authorization) {
String expectedKey = trim(properties.getMcpServiceKey());
authenticateService(authorization, false);
}
/// 只校验 Dify 服务间密钥
///
/// @param authorization Authorization 请求头
/// @param commit true 为提交 Provider
public void authenticateService(String authorization, boolean commit) {
String key = commit
? settingService.getSystem(GaoSystemSetting.DIFY_MCP_COMMIT_SERVICE_KEY).asString()
: settingService.getSystem(GaoSystemSetting.DIFY_MCP_SERVICE_KEY).asString();
if (commit && (key == null || key.isEmpty())) {
throw new GaoAiSessionException("MCP 提交服务密钥未配置", 503);
}
String actualKey = bearerValue(authorization);
if (expectedKey.isEmpty() || actualKey.isEmpty() || !constantTimeEquals(expectedKey, actualKey)) {
if (key == null || key.isEmpty() || actualKey.isEmpty() || !constantTimeEquals(key, actualKey)) {
throw new GaoAiSessionException("MCP 服务认证失败", 401);
}
}
@@ -77,24 +102,6 @@ public class GaoAiMcpAuthentication {
return value == null ? "" : value.trim();
}
/// 创建固定的开发测试会话
///
/// @return 开发测试会话
private GaoAiSession debugSession() {
String userId = trim(properties.getDebugUserId());
String storeId = trim(properties.getDebugStoreId());
if (userId.isEmpty() || storeId.isEmpty()) {
throw new GaoAiSessionException("开发测试会话缺少用户或门店配置", 401);
}
GaoAiSession session = new GaoAiSession();
session.setSessionId("dify-agent-debug-bypass");
session.setUserId(userId);
session.setStoreId(storeId);
session.setAllowedTools(GaoAiToolNames.orderedReadOnlyTools());
session.setExpiresAt(Long.MAX_VALUE);
return session;
}
/// 判断字符串是否为空
///
/// @param value 待判断字符串
@@ -0,0 +1,252 @@
package com.imyeyu.api.modules.gao.ai.mcp;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.imyeyu.api.modules.gao.ai.entity.GaoAiSession;
import com.imyeyu.api.modules.gao.ai.mcp.tool.GaoAiWriteTool;
import com.imyeyu.api.modules.gao.ai.operation.GaoAiOperationException;
import com.imyeyu.api.modules.gao.ai.service.GaoAiSessionService;
import com.imyeyu.api.modules.gao.ai.service.GaoAiToolException;
import com.imyeyu.api.modules.gao.ai.service.implement.GaoAiSessionServiceImplement.GaoAiSessionException;
import com.imyeyu.api.modules.gao.ai.vo.GaoAiToolResult;
import com.imyeyu.api.modules.user.context.ExecutionIdentityContext;
import com.imyeyu.spring.annotation.IgnoreGlobalReturn;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;
/// GAO 智能体提交 MCP 接口
///
/// 使用独立服务密钥,只暴露提交和取消工具,不允许绑定到 Agent 节点。
///
/// @author Codex
/// @since 2026-11-23
@Slf4j
@RestController
@RequestMapping("/mcp/gao-ai-commit")
public class GaoAiMcpCommitController {
private final ObjectMapper jackson;
private final GaoAiMcpAuthentication authentication;
private final GaoAiSessionService sessionService;
private final Map<String, GaoAiWriteTool> toolMap;
public GaoAiMcpCommitController(ObjectMapper jackson, GaoAiMcpAuthentication authentication,
GaoAiSessionService sessionService, List<GaoAiWriteTool> toolList) {
this.jackson = jackson;
this.authentication = authentication;
this.sessionService = sessionService;
this.toolMap = toolList.stream()
.filter(tool -> tool.provider() == GaoAiWriteTool.Provider.COMMIT)
.collect(Collectors.toUnmodifiableMap(GaoAiWriteTool::name, Function.identity()));
}
/// 处理提交 MCP JSON-RPC 请求
///
/// @param authorization 提交服务密钥
/// @param aiSessionId AI 会话头
/// @param request JSON-RPC 请求
/// @return JSON-RPC 响应
@IgnoreGlobalReturn
@PostMapping
public ResponseEntity<Object> handle(
@RequestHeader(value = HttpHeaders.AUTHORIZATION, required = false) String authorization,
@RequestHeader(value = "X-Timi-AI-Session", required = false) String aiSessionId,
@RequestBody JsonNode request) {
JsonNode id = request == null ? null : request.get("id");
String method = text(request, "method");
String toolName = text(request == null ? null : request.path("params"), "name");
try {
if (request == null || !request.isObject()) {
return response(400, error(id, -32600, "MCP 请求格式无效"));
}
if (method == null) {
return response(400, error(id, -32600, "MCP 请求缺少 method"));
}
return switch (method) {
case "initialize" -> {
authentication.authenticateService(authorization, true);
yield response(200, success(id, initializeResult()));
}
case "notifications/initialized", "ping" -> {
authentication.authenticateService(authorization, true);
yield response(200, success(id, Map.of()));
}
case "tools/list" -> {
authentication.authenticateService(authorization, true);
yield response(200, success(id, toolsResult()));
}
case "tools/call" -> {
JsonNode params = request.path("params");
String argumentSessionId = text(params.path("arguments"), "aiSessionId");
GaoAiSession session = authentication.authenticate(authorization, aiSessionId,
argumentSessionId, text(params, "name"), true);
yield response(200, success(id, executeTool(session, params, aiSessionId)));
}
default -> response(400, error(id, -32601, "MCP 方法不支持"));
};
} catch (GaoAiSessionException e) {
log.warn("GAO MCP 提交认证失败:method={}, toolName={}, status={}, reason={}",
method, toolName, e.getStatus(), e.getMessage());
return response(e.getStatus(), error(id, -32001, e.getMessage()));
} catch (GaoAiToolException e) {
log.warn("GAO MCP 提交工具失败:method={}, toolName={}, status={}, reason={}",
method, toolName, e.getStatus(), e.getMessage());
return response(e.getStatus(), error(id, -32602, e.getMessage()));
} catch (RuntimeException e) {
log.warn("GAO 智能体提交 MCP 请求失败", e);
return response(500, error(id, -32603, "智能体操作提交失败,请稍后重试"));
}
}
private Object executeTool(GaoAiSession session, JsonNode params, String aiSessionId) {
if (params == null || !params.isObject()) {
throw new GaoAiToolException("工具参数格式无效", 400);
}
String toolName = text(params, "name");
GaoAiWriteTool tool = toolMap.get(toolName);
if (tool == null) {
throw new GaoAiToolException("工具不存在或未启用", 403);
}
JsonNode arguments = params.has("arguments") ? params.get("arguments") : jackson.createObjectNode();
if (arguments == null || !arguments.isObject()) {
throw new GaoAiToolException("工具参数格式无效", 400);
}
ObjectNode businessArguments = ((ObjectNode) arguments).deepCopy();
businessArguments.remove("aiSessionId");
if (containsField(businessArguments, "storeId")) {
throw new GaoAiToolException("工具请求不允许携带 storeId", 403);
}
try {
GaoAiToolResult result = ExecutionIdentityContext.runAs(session.getUserId(), "GAO_AI_MCP_COMMIT",
session.getSessionId(), () -> tool.execute(session, businessArguments));
if (hasText(aiSessionId)) {
sessionService.increaseUsedCount(aiSessionId);
}
return mapResult(result);
} catch (GaoAiOperationException e) {
return mapFailure(e);
}
}
private Map<String, Object> mapResult(GaoAiToolResult result) {
if (result == null) {
result = new GaoAiToolResult();
result.setStatus("FAILED");
result.setErrorCode("INTERNAL_ERROR");
result.setErrorMessage("工具未返回结果");
}
Map<String, Object> content = new LinkedHashMap<>();
content.put("type", "text");
content.put("text", writeJson(result));
return Map.of("content", List.of(content), "structuredContent", result);
}
private Map<String, Object> mapFailure(GaoAiOperationException exception) {
GaoAiToolResult result = new GaoAiToolResult();
result.setStatus("FAILED");
result.setErrorCode(exception.getErrorCode());
result.setErrorMessage(exception.getMessage());
result.setRetryable(exception.isRetryable());
result.setCandidates(exception.getCandidates());
result.setMissingFields(exception.getMissingFields());
return mapResult(result);
}
private Map<String, Object> initializeResult() {
Map<String, Object> result = new LinkedHashMap<>();
result.put("protocolVersion", "2025-03-26");
result.put("capabilities", Map.of("tools", Map.of("listChanged", false)));
result.put("serverInfo", Map.of("name", "TimiServerAPI-GAO-AI-COMMIT", "version", "1.0"));
return result;
}
private Map<String, Object> toolsResult() {
List<Map<String, Object>> tools = new ArrayList<>();
for (GaoAiWriteTool tool : toolMap.values()) {
Map<String, Object> item = new LinkedHashMap<>();
item.put("name", tool.name());
item.put("description", tool.description());
item.put("inputSchema", tool.inputSchema());
tools.add(item);
}
return Map.of("tools", tools);
}
private ResponseEntity<Object> response(int status, Object body) {
return ResponseEntity.status(status).body(body);
}
private Map<String, Object> success(JsonNode id, Object result) {
Map<String, Object> response = new LinkedHashMap<>();
response.put("jsonrpc", "2.0");
response.put("id", id);
response.put("result", result);
return response;
}
private Map<String, Object> error(JsonNode id, int code, String message) {
Map<String, Object> response = new LinkedHashMap<>();
response.put("jsonrpc", "2.0");
response.put("id", id);
response.put("error", Map.of("code", code, "message", message));
return response;
}
private String text(JsonNode node, String field) {
if (node == null || !node.hasNonNull(field)) {
return null;
}
String value = node.get(field).asText();
return value == null || value.trim().isEmpty() ? null : value.trim();
}
private boolean hasText(String value) {
return value != null && !value.trim().isEmpty();
}
private boolean containsField(JsonNode node, String field) {
if (node == null) {
return false;
}
if (node.isObject()) {
if (node.has(field)) {
return true;
}
for (JsonNode child : node) {
if (containsField(child, field)) {
return true;
}
}
}
if (node.isArray()) {
for (JsonNode child : node) {
if (containsField(child, field)) {
return true;
}
}
}
return false;
}
private String writeJson(Object value) {
try {
return jackson.writeValueAsString(value);
} catch (Exception e) {
throw new GaoAiToolException("工具结果序列化失败", 500);
}
}
}
@@ -2,15 +2,19 @@ package com.imyeyu.api.modules.gao.ai.mcp;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.imyeyu.api.modules.gao.ai.entity.GaoAiAuditLog;
import com.imyeyu.api.modules.gao.ai.entity.GaoAiSession;
import com.imyeyu.api.modules.gao.ai.mcp.tool.GaoAiTool;
import com.imyeyu.api.modules.gao.ai.mcp.tool.GaoAiWriteTool;
import com.imyeyu.api.modules.gao.ai.operation.GaoAiOperationException;
import com.imyeyu.api.modules.gao.ai.service.GaoAiAuditService;
import com.imyeyu.api.modules.gao.ai.service.GaoAiSessionService;
import com.imyeyu.api.modules.gao.ai.service.GaoAiToolException;
import com.imyeyu.api.modules.gao.ai.service.implement.GaoAiSessionServiceImplement.GaoAiSessionException;
import com.imyeyu.api.modules.gao.ai.vo.GaoAiToolRequest;
import com.imyeyu.api.modules.gao.ai.vo.GaoAiToolResult;
import com.imyeyu.api.modules.user.context.ExecutionIdentityContext;
import com.imyeyu.spring.annotation.IgnoreGlobalReturn;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpHeaders;
@@ -29,7 +33,7 @@ import java.util.stream.Collectors;
/// GAO 智能体 MCP Streamable HTTP 接口
///
/// Dify 通过 Docker 内网访问本接口,业务查询只允许调用已注册的只读工具
/// 主 Provider 暴露只读工具和写操作准备工具;提交工具使用独立 Provider。
///
/// @author Codex
/// @since 2026-09-15
@@ -43,14 +47,19 @@ public class GaoAiMcpController {
private final GaoAiSessionService sessionService;
private final GaoAiAuditService auditService;
private final Map<String, GaoAiTool> toolMap;
private final Map<String, GaoAiWriteTool> writeToolMap;
public GaoAiMcpController(ObjectMapper jackson, GaoAiMcpAuthentication authentication,
GaoAiSessionService sessionService, GaoAiAuditService auditService, List<GaoAiTool> toolList) {
GaoAiSessionService sessionService, GaoAiAuditService auditService, List<GaoAiTool> toolList,
List<GaoAiWriteTool> writeToolList) {
this.jackson = jackson;
this.authentication = authentication;
this.sessionService = sessionService;
this.auditService = auditService;
this.toolMap = toolList.stream().collect(Collectors.toUnmodifiableMap(GaoAiTool::name, Function.identity()));
this.writeToolMap = writeToolList.stream()
.filter(tool -> tool.provider() == GaoAiWriteTool.Provider.MAIN)
.collect(Collectors.toUnmodifiableMap(GaoAiWriteTool::name, Function.identity()));
}
/// 处理 MCP JSON-RPC 请求
@@ -90,12 +99,13 @@ public class GaoAiMcpController {
yield response(200, success(id, toolsResult()));
}
case "tools/call" -> {
GaoAiSession session = authentication.authenticate(authorization, aiSessionId, text(request.path("params"), "name"));
if (!hasText(aiSessionId)) {
log.warn("GAO MCP 使用开发测试会话:toolName={}, userId={}, storeId={}",
toolName, session.getUserId(), session.getStoreId());
JsonNode params = request.path("params");
String argumentSessionId = text(params.path("arguments"), "aiSessionId");
GaoAiSession session = authentication.authenticate(authorization, aiSessionId, argumentSessionId, text(params, "name"));
if (hasText(argumentSessionId) && !hasText(aiSessionId)) {
log.info("GAO MCP 使用工具参数中的 AI 会话:toolName={}, aiSessionLength={}", toolName, length(argumentSessionId));
}
yield response(200, success(id, executeTool(session, request.path("params"), aiSessionId)));
yield response(200, success(id, executeTool(session, params, hasText(aiSessionId) ? aiSessionId : argumentSessionId)));
}
default -> response(400, error(id, -32601, "MCP 方法不支持"));
};
@@ -118,24 +128,54 @@ public class GaoAiMcpController {
throw new GaoAiToolException("工具参数格式无效", 400);
}
String toolName = text(params, "name");
JsonNode arguments = params.has("arguments") ? params.get("arguments") : jackson.createObjectNode();
if (arguments == null || !arguments.isObject()) {
throw new GaoAiToolException("工具参数格式无效", 400);
}
ObjectNode businessArguments = ((ObjectNode) arguments).deepCopy();
businessArguments.remove("aiSessionId");
if (containsField(businessArguments, "storeId")) {
throw new GaoAiToolException("工具请求不允许携带 storeId", 403);
}
long startedAt = System.currentTimeMillis();
GaoAiWriteTool writeTool = writeToolMap.get(toolName);
if (writeTool != null) {
try {
GaoAiToolResult result = ExecutionIdentityContext.runAs(session.getUserId(), "GAO_AI_MCP",
session.getSessionId(), () -> writeTool.execute(session, businessArguments));
if (result == null) {
result = new GaoAiToolResult();
result.setStatus("FAILED");
result.setErrorCode("INTERNAL_ERROR");
result.setErrorMessage("工具未返回结果");
}
long duration = System.currentTimeMillis() - startedAt;
if (hasText(aiSessionId)) {
sessionService.increaseUsedCount(aiSessionId);
}
recordAudit(session, null, toolName, duration, "SUCCESS", 0L);
Map<String, Object> content = new LinkedHashMap<>();
content.put("type", "text");
content.put("text", writeJson(result));
return Map.of("content", List.of(content), "structuredContent", result);
} catch (GaoAiOperationException e) {
recordAudit(session, null, toolName, System.currentTimeMillis() - startedAt, "ERROR", 0L);
return structuredFailure(e);
} catch (RuntimeException e) {
recordAudit(session, null, toolName, System.currentTimeMillis() - startedAt, "ERROR", 0L);
throw e;
}
}
GaoAiTool tool = toolMap.get(toolName);
if (tool == null) {
throw new GaoAiToolException("工具不存在或未启用", 403);
}
JsonNode arguments = params == null || !params.has("arguments") ? jackson.createObjectNode() : params.get("arguments");
if (arguments == null || !arguments.isObject()) {
throw new GaoAiToolException("工具参数格式无效", 400);
}
if (containsField(arguments, "storeId")) {
throw new GaoAiToolException("工具请求不允许携带 storeId", 403);
}
GaoAiToolRequest request;
try {
request = jackson.treeToValue(arguments, GaoAiToolRequest.class);
request = jackson.treeToValue(businessArguments, GaoAiToolRequest.class);
} catch (Exception e) {
throw new GaoAiToolException("工具参数格式无效", 400);
}
long startedAt = System.currentTimeMillis();
try {
GaoAiToolResult result = tool.execute(session, request);
long duration = System.currentTimeMillis() - startedAt;
@@ -156,6 +196,20 @@ public class GaoAiMcpController {
}
}
private Map<String, Object> structuredFailure(GaoAiOperationException exception) {
GaoAiToolResult result = new GaoAiToolResult();
result.setStatus("FAILED");
result.setErrorCode(exception.getErrorCode());
result.setErrorMessage(exception.getMessage());
result.setRetryable(exception.isRetryable());
result.setCandidates(exception.getCandidates());
result.setMissingFields(exception.getMissingFields());
Map<String, Object> content = new LinkedHashMap<>();
content.put("type", "text");
content.put("text", writeJson(result));
return Map.of("content", List.of(content), "structuredContent", result);
}
private Map<String, Object> initializeResult() {
Map<String, Object> result = new LinkedHashMap<>();
result.put("protocolVersion", "2025-03-26");
@@ -165,17 +219,24 @@ public class GaoAiMcpController {
}
private Map<String, Object> toolsResult() {
List<Map<String, Object>> tools = toolMap.values().stream()
.map(tool -> {
Map<String, Object> item = new LinkedHashMap<>();
item.put("name", tool.name());
item.put("description", tool.description());
item.put("inputSchema", tool.inputSchema());
return item;
}).toList();
List<Map<String, Object>> tools = new java.util.ArrayList<>();
for (GaoAiTool tool : toolMap.values()) {
tools.add(toolDescriptor(tool.name(), tool.description(), tool.inputSchema()));
}
for (GaoAiWriteTool tool : writeToolMap.values()) {
tools.add(toolDescriptor(tool.name(), tool.description(), tool.inputSchema()));
}
return Map.of("tools", tools);
}
private Map<String, Object> toolDescriptor(String name, String description, Map<String, Object> inputSchema) {
Map<String, Object> item = new LinkedHashMap<>();
item.put("name", name);
item.put("description", description);
item.put("inputSchema", inputSchema);
return item;
}
private void recordAudit(GaoAiSession session, GaoAiToolRequest request, String toolName, long duration,
String status, long resultCount) {
GaoAiAuditLog audit = new GaoAiAuditLog();
@@ -4,7 +4,7 @@ import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
/// GAO 智能体只读工具名称
/// GAO 智能体 MCP 工具名称
///
/// @author Codex
/// @since 2026-09-15
@@ -20,6 +20,12 @@ public final class GaoAiToolNames {
public static final String BUSINESS_REPORT = "business_report";
public static final String STORE_DIARY_QUERY = "store_diary_query";
public static final String METRIC_DEFINITION = "metric_definition";
public static final String FULFILLMENT_QUERY = "fulfillment_query";
public static final String FOLLOW_UP_QUERY = "follow_up_query";
public static final String OPERATION_PREPARE = "operation_prepare";
public static final String OPERATION_COMMIT = "operation_commit";
public static final String OPERATION_CANCEL = "operation_cancel";
public static final Set<String> READ_ONLY_TOOLS = java.util.Collections.unmodifiableSet(new LinkedHashSet<>(List.of(
STORE_OVERVIEW,
@@ -31,16 +37,38 @@ public final class GaoAiToolNames {
POINT_QUERY,
BUSINESS_REPORT,
STORE_DIARY_QUERY,
METRIC_DEFINITION
METRIC_DEFINITION,
FULFILLMENT_QUERY,
FOLLOW_UP_QUERY
)));
public static final Set<String> PREPARE_TOOLS = java.util.Collections.unmodifiableSet(
new LinkedHashSet<>(List.of(OPERATION_PREPARE)));
public static final Set<String> COMMIT_TOOLS = java.util.Collections.unmodifiableSet(
new LinkedHashSet<>(List.of(OPERATION_COMMIT, OPERATION_CANCEL)));
private GaoAiToolNames() {
}
/// 生成稳定的工具顺序
/// 生成模型可见的查询和准备工具
///
/// @return 工具名称集合
public static Set<String> orderedReadOnlyTools() {
return new LinkedHashSet<>(READ_ONLY_TOOLS);
public static Set<String> orderedModelTools() {
Set<String> result = new LinkedHashSet<>(READ_ONLY_TOOLS);
result.addAll(PREPARE_TOOLS);
return result;
}
/// 生成会话允许的全部工具
///
/// 主 MCP 只暴露查询和准备工具,提交 Provider 单独使用提交工具。
///
/// @return 工具名称集合
public static Set<String> orderedSessionTools() {
Set<String> result = new LinkedHashSet<>(READ_ONLY_TOOLS);
result.addAll(PREPARE_TOOLS);
result.addAll(COMMIT_TOOLS);
return result;
}
}
@@ -0,0 +1,96 @@
package com.imyeyu.api.modules.gao.ai.mcp.tool;
import com.imyeyu.api.modules.gao.ai.entity.GaoAiSession;
import com.imyeyu.api.modules.gao.ai.mcp.GaoAiToolNames;
import com.imyeyu.api.modules.gao.ai.vo.GaoAiToolRequest;
import com.imyeyu.api.modules.gao.ai.vo.GaoAiToolResult;
import com.imyeyu.api.modules.gao.entity.GaoCustomer;
import com.imyeyu.api.modules.gao.entity.GaoCustomerFollowUpReminder;
import com.imyeyu.api.modules.gao.service.GaoCustomerFollowUpReminderService;
import com.imyeyu.api.modules.gao.service.GaoCustomerService;
import com.imyeyu.api.modules.gao.vo.customer.GaoCustomerFollowUpReminderPage;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
/// 客户跟进提醒查询工具
///
/// @author Codex
/// @since 2026-11-23
@Component
@RequiredArgsConstructor
public class FollowUpQueryTool implements GaoAiTool {
private static final ZoneId ZONE = ZoneId.systemDefault();
private static final DateTimeFormatter DATE_TIME = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm");
private final GaoCustomerFollowUpReminderService followUpService;
private final GaoCustomerService customerService;
@Override
public String name() {
return GaoAiToolNames.FOLLOW_UP_QUERY;
}
@Override
public String description() {
return "查询当前门店客户跟进提醒,返回提醒 ID、客户、内容、提醒时间和状态";
}
@Override
public GaoAiToolResult execute(GaoAiSession session, GaoAiToolRequest request) {
GaoCustomerFollowUpReminderPage page = new GaoCustomerFollowUpReminderPage();
page.setStoreId(session.getStoreId());
page.setCustomerId(filter(request, "customerId"));
String status = filter(request, "status");
if (status != null) {
try {
page.setStatus(GaoCustomerFollowUpReminder.Status.valueOf(status.trim().toUpperCase()));
} catch (RuntimeException e) {
throw new com.imyeyu.api.modules.gao.ai.service.GaoAiToolException("跟进状态无效", 400);
}
}
page.setSize(Math.max(1, Math.min(20, request.getPageSize() == null ? 10 : request.getPageSize())));
var result = followUpService.pageByQuery(page);
List<GaoCustomerFollowUpReminder> list = result == null || result.getList() == null ? List.of() : result.getList();
Map<String, GaoCustomer> customerMap = customerService.mapByIdList(list.stream()
.map(GaoCustomerFollowUpReminder::getCustomerId).distinct().toList());
List<Object> details = list.stream().map(item -> {
GaoCustomer customer = customerMap.get(item.getCustomerId());
Map<String, Object> detail = new LinkedHashMap<>();
detail.put("reminderId", item.getId());
detail.put("customerId", item.getCustomerId());
detail.put("customerName", customer == null ? null : customer.getName());
detail.put("content", item.getContent());
detail.put("remindAt", dateTime(item.getRemindAt()));
detail.put("status", item.getStatus());
return (Object) detail;
}).toList();
GaoAiToolResult toolResult = new GaoAiToolResult();
toolResult.getSummary().put("total", result == null ? 0L : result.getTotal());
toolResult.getSummary().put("returnedCount", details.size());
toolResult.setDetails(details);
toolResult.getSource().put("metric", "客户跟进提醒");
toolResult.getSource().put("generatedAt", Instant.now().atZone(ZONE).toOffsetDateTime().toString());
return toolResult;
}
private String filter(GaoAiToolRequest request, String key) {
if (request == null || request.getFilters() == null) {
return null;
}
Object value = request.getFilters().get(key);
return value == null || value.toString().isBlank() ? null : value.toString().trim();
}
private String dateTime(Long millis) {
return millis == null ? null : LocalDateTime.ofInstant(Instant.ofEpochMilli(millis), ZONE).format(DATE_TIME);
}
}
@@ -0,0 +1,120 @@
package com.imyeyu.api.modules.gao.ai.mcp.tool;
import com.imyeyu.api.modules.gao.ai.entity.GaoAiSession;
import com.imyeyu.api.modules.gao.ai.mcp.GaoAiToolNames;
import com.imyeyu.api.modules.gao.ai.vo.GaoAiToolRequest;
import com.imyeyu.api.modules.gao.ai.vo.GaoAiToolResult;
import com.imyeyu.api.modules.gao.entity.GaoOrderFulfillment;
import com.imyeyu.api.modules.gao.entity.GaoSalesOrder;
import com.imyeyu.api.modules.gao.service.GaoOrderFulfillmentService;
import com.imyeyu.api.modules.gao.service.GaoSalesOrderService;
import com.imyeyu.api.modules.gao.vo.order.GaoOrderFulfillmentPage;
import com.imyeyu.api.modules.gao.vo.salesorder.GaoSalesOrderPage;
import com.imyeyu.spring.bean.PageResult;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
/// 履约查询工具
///
/// 返回订单号和履约请求号,供写操作按业务号定位履约单。
///
/// @author Codex
/// @since 2026-11-23
@Component
@RequiredArgsConstructor
public class FulfillmentQueryTool implements GaoAiTool {
private static final ZoneId ZONE = ZoneId.systemDefault();
private static final DateTimeFormatter DATE_TIME = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm");
private final GaoOrderFulfillmentService fulfillmentService;
private final GaoSalesOrderService salesOrderService;
@Override
public String name() {
return GaoAiToolNames.FULFILLMENT_QUERY;
}
@Override
public String description() {
return "查询当前门店履约单,返回订单号、履约请求号、状态和履约时间";
}
@Override
public GaoAiToolResult execute(GaoAiSession session, GaoAiToolRequest request) {
GaoOrderFulfillmentPage page = new GaoOrderFulfillmentPage();
page.setStoreId(session.getStoreId());
page.setOrderAllowed(true);
page.setSalesOrderId(filter(request, "salesOrderId"));
page.setCustomerId(filter(request, "customerId"));
String orderNo = filter(request, "orderNo", "keyword");
if (orderNo != null && page.getSalesOrderId() == null) {
GaoSalesOrderPage orderPage = new GaoSalesOrderPage();
orderPage.setStoreId(session.getStoreId());
orderPage.setKeyword(orderNo);
orderPage.setOrderAllowed(true);
orderPage.setSize(2);
PageResult<GaoSalesOrder> orderResult = salesOrderService.pageByQuery(orderPage);
if (orderResult != null && orderResult.getList() != null && !orderResult.getList().isEmpty()) {
page.setSalesOrderId(orderResult.getList().getFirst().getId());
}
}
String status = filter(request, "status");
if (status != null) {
try {
page.setStatus(GaoOrderFulfillment.Status.valueOf(status.trim().toUpperCase()));
} catch (RuntimeException e) {
throw new com.imyeyu.api.modules.gao.ai.service.GaoAiToolException("履约状态无效", 400);
}
}
page.setSize(Math.max(1, Math.min(20, request.getPageSize() == null ? 10 : request.getPageSize())));
PageResult<GaoOrderFulfillment> result = fulfillmentService.pageByQuery(page);
List<GaoOrderFulfillment> list = result == null || result.getList() == null ? List.of() : result.getList();
Map<String, GaoSalesOrder> orderMap = salesOrderService.mapByIdList(list.stream()
.map(GaoOrderFulfillment::getSalesOrderId).distinct().toList());
List<Object> details = list.stream().map(item -> {
GaoSalesOrder order = orderMap.get(item.getSalesOrderId());
Map<String, Object> detail = new LinkedHashMap<>();
detail.put("fulfillmentId", item.getId());
detail.put("orderNo", order == null ? null : order.getOrderNo());
detail.put("salesOrderId", item.getSalesOrderId());
detail.put("requestNo", item.getRequestNo());
detail.put("status", item.getStatus());
detail.put("deliveredAt", dateTime(item.getDeliveredAt()));
detail.put("remark", item.getRemark());
return (Object) detail;
}).toList();
GaoAiToolResult toolResult = new GaoAiToolResult();
toolResult.getSummary().put("total", result == null ? 0L : result.getTotal());
toolResult.getSummary().put("returnedCount", details.size());
toolResult.setDetails(details);
toolResult.getSource().put("metric", "履约单、订单号和履约请求号");
toolResult.getSource().put("generatedAt", Instant.now().atZone(ZONE).toOffsetDateTime().toString());
return toolResult;
}
private String filter(GaoAiToolRequest request, String... keys) {
if (request == null || request.getFilters() == null) {
return null;
}
for (String key : keys) {
Object value = request.getFilters().get(key);
if (value != null && !value.toString().isBlank()) {
return value.toString().trim();
}
}
return null;
}
private String dateTime(Long millis) {
return millis == null ? null : LocalDateTime.ofInstant(Instant.ofEpochMilli(millis), ZONE).format(DATE_TIME);
}
}
@@ -4,6 +4,7 @@ import com.imyeyu.api.modules.gao.ai.entity.GaoAiSession;
import com.imyeyu.api.modules.gao.ai.vo.GaoAiToolRequest;
import com.imyeyu.api.modules.gao.ai.vo.GaoAiToolResult;
import java.util.LinkedHashMap;
import java.util.Map;
/// GAO 智能体只读工具
@@ -36,15 +37,19 @@ public interface GaoAiTool {
),
"additionalProperties", false
);
Map<String, Object> properties = new LinkedHashMap<>();
properties.put("query", Map.of("type", "string", "description", "自然语言关键词"));
properties.put("timeRange", timeRange);
properties.put("filters", Map.of("type", "object"));
properties.put("pageSize", Map.of("type", "integer", "minimum", 1, "maximum", 20));
properties.put("cursor", Map.of("type", "string"));
properties.put("aiSessionId", Map.of(
"type", "string",
"description", "由工作流变量注入的 AI 会话 ID,不允许由模型生成"
));
return Map.of(
"type", "object",
"properties", Map.of(
"query", Map.of("type", "string", "description", "自然语言关键词"),
"timeRange", timeRange,
"filters", Map.of("type", "object"),
"pageSize", Map.of("type", "integer", "minimum", 1, "maximum", 20),
"cursor", Map.of("type", "string")
),
"properties", properties,
"additionalProperties", false
);
}
@@ -0,0 +1,43 @@
package com.imyeyu.api.modules.gao.ai.mcp.tool;
import com.fasterxml.jackson.databind.JsonNode;
import com.imyeyu.api.modules.gao.ai.entity.GaoAiSession;
import com.imyeyu.api.modules.gao.ai.vo.GaoAiToolResult;
import java.util.Map;
/// GAO 智能体写工具
///
/// @author Codex
/// @since 2026-11-23
public interface GaoAiWriteTool {
/// 工具提供方
enum Provider {
/// 主 MCP,模型可见
MAIN,
/// 提交 MCP,只允许确定性工具节点调用
COMMIT
}
/// @return 工具名称
String name();
/// @return 工具描述
String description();
/// @return 工具提供方
Provider provider();
/// @return MCP 输入参数结构
Map<String, Object> inputSchema();
/// 执行工具
///
/// @param session 已认证会话
/// @param arguments 已移除 aiSessionId 的业务参数
/// @return 工具结果
GaoAiToolResult execute(GaoAiSession session, JsonNode arguments);
}
@@ -0,0 +1,59 @@
package com.imyeyu.api.modules.gao.ai.mcp.tool;
import com.fasterxml.jackson.databind.JsonNode;
import com.imyeyu.api.modules.gao.ai.entity.GaoAiSession;
import com.imyeyu.api.modules.gao.ai.mcp.GaoAiToolNames;
import com.imyeyu.api.modules.gao.ai.operation.GaoAiOperationService;
import com.imyeyu.api.modules.gao.ai.vo.GaoAiToolResult;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;
import java.util.LinkedHashMap;
import java.util.Map;
/// GAO 智能体待确认操作取消工具
///
/// @author Codex
/// @since 2026-11-23
@Component
@RequiredArgsConstructor
public class OperationCancelTool implements GaoAiWriteTool {
private final GaoAiOperationService operationService;
@Override
public String name() {
return GaoAiToolNames.OPERATION_CANCEL;
}
@Override
public String description() {
return "取消一个待确认写操作。只接受 confirmationToken,不产生业务副作用。";
}
@Override
public Provider provider() {
return Provider.COMMIT;
}
@Override
public Map<String, Object> inputSchema() {
Map<String, Object> properties = new LinkedHashMap<>();
properties.put("confirmationToken", Map.of("type", "string", "description", "服务端签发的确认 token"));
properties.put("aiSessionId", Map.of("type", "string", "description", "AI 会话 ID"));
return Map.of("type", "object", "properties", properties, "additionalProperties", false);
}
@Override
public GaoAiToolResult execute(GaoAiSession session, JsonNode arguments) {
return operationService.cancel(session, text(arguments, "confirmationToken"));
}
private String text(JsonNode node, String field) {
if (node == null || !node.hasNonNull(field)) {
return null;
}
String value = node.get(field).asText();
return value == null || value.isBlank() ? null : value.trim();
}
}
@@ -0,0 +1,65 @@
package com.imyeyu.api.modules.gao.ai.mcp.tool;
import com.fasterxml.jackson.databind.JsonNode;
import com.imyeyu.api.modules.gao.ai.entity.GaoAiSession;
import com.imyeyu.api.modules.gao.ai.mcp.GaoAiToolNames;
import com.imyeyu.api.modules.gao.ai.operation.GaoAiOperationService;
import com.imyeyu.api.modules.gao.ai.vo.GaoAiToolResult;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;
import java.util.LinkedHashMap;
import java.util.Map;
/// GAO 智能体待确认操作提交工具
///
/// 只能由 Dify 确定性工具节点调用,不接受任何业务参数。
///
/// @author Codex
/// @since 2026-11-23
@Component
@RequiredArgsConstructor
public class OperationCommitTool implements GaoAiWriteTool {
private final GaoAiOperationService operationService;
@Override
public String name() {
return GaoAiToolNames.OPERATION_COMMIT;
}
@Override
public String description() {
return "提交一个已准备的写操作。只接受服务端签发的 confirmationToken,不接受业务参数。";
}
@Override
public Provider provider() {
return Provider.COMMIT;
}
@Override
public Map<String, Object> inputSchema() {
Map<String, Object> properties = new LinkedHashMap<>();
properties.put("confirmationToken", Map.of("type", "string", "description", "服务端签发的确认 token"));
properties.put("confirmationPhrase", Map.of("type", "string",
"description", "破坏性或敏感操作要求的精确确认短语"));
properties.put("reason", Map.of("type", "string", "description", "破坏性或敏感操作的原因"));
properties.put("aiSessionId", Map.of("type", "string", "description", "AI 会话 ID"));
return Map.of("type", "object", "properties", properties, "additionalProperties", false);
}
@Override
public GaoAiToolResult execute(GaoAiSession session, JsonNode arguments) {
return operationService.commit(session, text(arguments, "confirmationToken"),
text(arguments, "confirmationPhrase"), text(arguments, "reason"));
}
private String text(JsonNode node, String field) {
if (node == null || !node.hasNonNull(field)) {
return null;
}
String value = node.get(field).asText();
return value == null || value.isBlank() ? null : value.trim();
}
}
@@ -0,0 +1,85 @@
package com.imyeyu.api.modules.gao.ai.mcp.tool;
import com.fasterxml.jackson.databind.JsonNode;
import com.imyeyu.api.modules.gao.ai.entity.GaoAiSession;
import com.imyeyu.api.modules.gao.ai.mcp.GaoAiToolNames;
import com.imyeyu.api.modules.gao.ai.operation.GaoAiOperationRegistry;
import com.imyeyu.api.modules.gao.ai.operation.GaoAiOperationService;
import com.imyeyu.api.modules.gao.ai.vo.GaoAiToolResult;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;
import java.util.LinkedHashMap;
import java.util.Map;
/// GAO 智能体写操作准备工具
///
/// 模型只负责填写业务参数,门店、操作人、请求号和确认 token 全部由后端生成。
///
/// @author Codex
/// @since 2026-11-23
@Component
@RequiredArgsConstructor
public class OperationPrepareTool implements GaoAiWriteTool {
private final GaoAiOperationRegistry registry;
private final GaoAiOperationService operationService;
@Override
public String name() {
return GaoAiToolNames.OPERATION_PREPARE;
}
@Override
public String description() {
return """
准备一个门店业务写操作,只生成预览和确认凭证,不写业务数据。
必须严格按操作目录传入 operation,并在 argumentsJson 中传入操作所需字段。
禁止传 storeId、operatorUserId、requestNo、confirmationToken、operationId。
操作目录:
""" + registry.catalog();
}
@Override
public Provider provider() {
return Provider.MAIN;
}
@Override
public Map<String, Object> inputSchema() {
Map<String, Object> properties = new LinkedHashMap<>();
properties.put("operation", Map.of("type", "string", "enum", registry.codes(),
"description", "写操作代码"));
properties.put("argumentsJson", Map.of("type", "string",
"description", "严格 JSON 对象字符串,字段由 operation 决定"));
properties.put("attachmentTokensJson", Map.of("type", "string",
"description", "附件凭证 JSON 数组,由工作流变量注入,模型不得生成"));
properties.put("aiSessionId", Map.of("type", "string",
"description", "由工作流变量注入的 AI 会话 ID,不允许由模型生成"));
return Map.of("type", "object", "properties", properties, "additionalProperties", false);
}
@Override
public GaoAiToolResult execute(GaoAiSession session, JsonNode arguments) {
String operation = text(arguments, "operation");
String argumentsJson = jsonText(arguments, "argumentsJson");
String attachmentTokensJson = jsonText(arguments, "attachmentTokensJson");
return operationService.prepare(session, operation, argumentsJson, attachmentTokensJson);
}
private String text(JsonNode node, String field) {
if (node == null || !node.hasNonNull(field)) {
return null;
}
String value = node.get(field).asText();
return value == null || value.isBlank() ? null : value.trim();
}
private String jsonText(JsonNode node, String field) {
if (node == null || !node.hasNonNull(field)) {
return null;
}
JsonNode value = node.get(field);
return value.isTextual() ? value.asText() : value.toString();
}
}
@@ -0,0 +1,49 @@
package com.imyeyu.api.modules.gao.ai.operation;
import com.imyeyu.api.modules.common.entity.Attachment;
import org.springframework.web.multipart.MultipartFile;
import java.util.List;
/// GAO 智能体附件凭证服务
///
/// @author Codex
/// @since 2026-11-23
public interface GaoAiAttachmentService {
/// 上传并登记附件凭证
///
/// @param userId 用户 ID
/// @param storeId 门店 ID
/// @param files 文件列表
/// @return 凭证和展示信息
List<UploadedAttachment> upload(String userId, String storeId, List<MultipartFile> files);
/// 解析并校验凭证
///
/// @param userId 用户 ID
/// @param storeId 门店 ID
/// @param tokens 凭证列表
/// @return 附件凭证
List<GaoAiAttachmentToken> resolve(String userId, String storeId, List<String> tokens);
/// 克隆为可提交给业务 Service 的临时附件
///
/// 每次 commit 都克隆,避免重试时临时文件已被业务消费。
///
/// @param userId 用户 ID
/// @param storeId 门店 ID
/// @param tokens 凭证列表
/// @return 附件列表
List<Attachment> cloneForCommit(String userId, String storeId, List<String> tokens);
/// 上传结果
///
/// @param token 凭证
/// @param name 文件名
/// @param mimeType MIME 类型
/// @param size 文件大小
/// @param expiresAt 过期时间
record UploadedAttachment(String token, String name, String mimeType, Long size, long expiresAt) {
}
}
@@ -0,0 +1,180 @@
package com.imyeyu.api.modules.gao.ai.operation;
import com.imyeyu.api.modules.common.entity.Attachment;
import com.imyeyu.api.modules.common.service.AttachmentService;
import com.imyeyu.api.modules.common.service.TempFileService;
import com.imyeyu.api.modules.common.vo.attach.TempFileResp;
import com.imyeyu.api.modules.gao.ai.config.GaoAiProperties;
import com.imyeyu.spring.util.Redis;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.util.ArrayList;
import java.util.Base64;
import java.util.List;
/// GAO 智能体附件凭证服务实现
///
/// @author Codex
/// @since 2026-11-23
@Service
@RequiredArgsConstructor
public class GaoAiAttachmentServiceImplement implements GaoAiAttachmentService {
private static final String KEY_PREFIX = "GAO:AI:ATTACH:";
private final GaoAiProperties properties;
private final TempFileService tempFileService;
private final AttachmentService attachmentService;
@Qualifier("redisGaoAiAttachment")
private final Redis<String, GaoAiAttachmentToken> redis;
private final SecureRandom secureRandom = new SecureRandom();
@Override
public List<UploadedAttachment> upload(String userId, String storeId, List<MultipartFile> files) {
if (userId == null || userId.isBlank() || storeId == null || storeId.isBlank()) {
throw new GaoAiOperationException("STORE_SCOPE_DENIED", "缺少用户或门店");
}
if (files == null || files.isEmpty()) {
throw new GaoAiOperationException("ATTACHMENT_REQUIRED", "请先上传凭证照片");
}
int maxCount = Math.max(1, properties.getAttachmentMaxCount());
if (files.size() > maxCount) {
throw new GaoAiOperationException("VALIDATION_FAILED", "一次最多上传 %d 个附件".formatted(maxCount));
}
long maxSize = Math.max(1L, properties.getAttachmentMaxSizeMb()) * 1024L * 1024L;
for (MultipartFile file : files) {
if (file == null || file.isEmpty()) {
throw new GaoAiOperationException("VALIDATION_FAILED", "附件不能为空");
}
if (file.getSize() > maxSize) {
throw new GaoAiOperationException("VALIDATION_FAILED", "单个附件不能超过 %d MB".formatted(properties.getAttachmentMaxSizeMb()));
}
String contentType = file.getContentType();
if (!allowedContentType(contentType)) {
throw new GaoAiOperationException("VALIDATION_FAILED", "仅支持图片或 PDF 凭证");
}
}
long ttlMs = Math.max(60_000L, properties.getAttachmentTtlSeconds() * 1000L);
List<TempFileResp> tempFiles;
try {
tempFiles = tempFileService.create(files, ttlMs);
} catch (RuntimeException e) {
throw new GaoAiOperationException("ATTACHMENT_UPLOAD_FAILED", "附件上传失败,请检查文件大小和类型");
}
List<UploadedAttachment> result = new ArrayList<>();
for (int index = 0; index < tempFiles.size(); index++) {
TempFileResp tempFile = tempFiles.get(index);
Attachment attachment = attachmentService.get(tempFile.getId());
if (attachment == null) {
throw new GaoAiOperationException("ATTACHMENT_INVALID", "附件上传失败");
}
String mimeType = attachment.getMimeType();
if (!allowedContentType(mimeType)) {
attachmentService.destroy(attachment.getId());
throw new GaoAiOperationException("VALIDATION_FAILED", "附件内容类型不受支持");
}
String token = newToken();
GaoAiAttachmentToken tokenEntity = new GaoAiAttachmentToken();
tokenEntity.setTokenHash(hash(token));
tokenEntity.setTempFileId(tempFile.getId());
tokenEntity.setUserId(userId);
tokenEntity.setStoreId(storeId);
tokenEntity.setName(attachment.getName());
tokenEntity.setMimeType(mimeType);
tokenEntity.setSize(attachment.getSize());
tokenEntity.setAttachType(mimeType != null && mimeType.startsWith("image") ? "PHOTO" : "OTHER");
tokenEntity.setExpiresAt(System.currentTimeMillis() + ttlMs);
redis.set(key(tokenEntity.getTokenHash()), tokenEntity, ttlMs);
result.add(new UploadedAttachment(token, tokenEntity.getName(), tokenEntity.getMimeType(),
tokenEntity.getSize(), tokenEntity.getExpiresAt()));
}
return result;
}
@Override
public List<GaoAiAttachmentToken> resolve(String userId, String storeId, List<String> tokens) {
if (tokens == null || tokens.isEmpty()) {
return List.of();
}
List<GaoAiAttachmentToken> result = new ArrayList<>();
long now = System.currentTimeMillis();
for (String token : tokens) {
if (token == null || token.isBlank()) {
continue;
}
GaoAiAttachmentToken entity = redis.get(key(hash(token.trim())));
if (entity == null) {
throw new GaoAiOperationException("ATTACHMENT_INVALID", "附件凭证不存在或已过期,请重新上传");
}
if (entity.getExpiresAt() <= now) {
redis.destroy(key(entity.getTokenHash()));
throw new GaoAiOperationException("ATTACHMENT_EXPIRED", "附件凭证已过期,请重新上传");
}
if (!userId.equals(entity.getUserId()) || !storeId.equals(entity.getStoreId())) {
throw new GaoAiOperationException("ATTACHMENT_INVALID", "附件凭证不属于当前用户或门店");
}
result.add(entity);
}
return result;
}
@Override
public List<Attachment> cloneForCommit(String userId, String storeId, List<String> tokens) {
List<GaoAiAttachmentToken> tokenList = resolve(userId, storeId, tokens);
List<Attachment> result = new ArrayList<>();
for (GaoAiAttachmentToken token : tokenList) {
try {
Attachment clone = attachmentService.clone(token.getTempFileId());
Attachment attachment = new Attachment();
attachment.setTempFileId(clone.getId());
attachment.setName(token.getName());
attachment.setAttachType(token.getAttachType());
attachment.setMetadata(clone.getMetadata());
result.add(attachment);
} catch (RuntimeException e) {
throw new GaoAiOperationException("ATTACHMENT_INVALID", "附件已失效,请重新上传");
}
}
return result;
}
private String newToken() {
byte[] bytes = new byte[32];
secureRandom.nextBytes(bytes);
return "att_" + Base64.getUrlEncoder().withoutPadding().encodeToString(bytes);
}
private String key(String tokenHash) {
return KEY_PREFIX + tokenHash;
}
private String hash(String value) {
try {
byte[] bytes = MessageDigest.getInstance("SHA-256").digest(value.getBytes(StandardCharsets.UTF_8));
StringBuilder result = new StringBuilder(bytes.length * 2);
for (byte item : bytes) {
result.append("%02x".formatted(item & 0xff));
}
return result.toString();
} catch (NoSuchAlgorithmException e) {
throw new IllegalStateException("当前 JDK 不支持 SHA-256", e);
}
}
private boolean allowedContentType(String contentType) {
if (contentType == null) {
return false;
}
String value = contentType.toLowerCase();
return value.startsWith("image/") || "application/pdf".equals(value);
}
}
@@ -0,0 +1,40 @@
package com.imyeyu.api.modules.gao.ai.operation;
import lombok.Data;
/// GAO 智能体附件凭证
///
/// 原始凭证只在浏览器和聊天请求中出现,Redis 只保存摘要。
///
/// @author Codex
/// @since 2026-11-23
@Data
public class GaoAiAttachmentToken {
/// 凭证摘要
private String tokenHash;
/// 临时文件 ID
private String tempFileId;
/// 用户 ID
private String userId;
/// 门店 ID
private String storeId;
/// 文件名
private String name;
/// MIME 类型
private String mimeType;
/// 文件大小
private Long size;
/// 业务附件类型
private String attachType = "PHOTO";
/// 过期时间
private long expiresAt;
}
@@ -0,0 +1,65 @@
package com.imyeyu.api.modules.gao.ai.operation;
import lombok.Data;
/// GAO 智能体写操作提交结果
///
/// @author Codex
/// @since 2026-11-23
@Data
public class GaoAiCommitResult {
/// 结果状态,成功固定为 SUCCEEDED
private String status;
/// 操作代码
private String operation;
/// 结果实体类型
private String entityType;
/// 结果实体 ID
private String entityId;
/// 结果实体业务单号
private String entityNo;
/// 给用户的结果文本
private String resultText;
/// true 为幂等重放
private boolean idempotentReplay;
/// 错误码
private String errorCode;
/// 错误消息
private String errorMessage;
/// 是否可重试
private boolean retryable;
/// 成功结果
public static GaoAiCommitResult success(String operation, String entityType, String entityId, String entityNo,
String resultText) {
GaoAiCommitResult result = new GaoAiCommitResult();
result.setStatus("SUCCEEDED");
result.setOperation(operation);
result.setEntityType(entityType);
result.setEntityId(entityId);
result.setEntityNo(entityNo);
result.setResultText(resultText);
return result;
}
/// 失败结果
public static GaoAiCommitResult failure(String operation, String errorCode, String errorMessage, boolean retryable) {
GaoAiCommitResult result = new GaoAiCommitResult();
result.setStatus("FAILED");
result.setOperation(operation);
result.setErrorCode(errorCode);
result.setErrorMessage(errorMessage);
result.setRetryable(retryable);
return result;
}
}
@@ -0,0 +1,66 @@
package com.imyeyu.api.modules.gao.ai.operation;
import lombok.Getter;
/// GAO 智能体写操作
///
/// 物理删除不在枚举中,静态检查可直接证明 AI 写能力不存在删除入口。
///
/// @author Codex
/// @since 2026-11-23
@Getter
public enum GaoAiOperation {
CUSTOMER_CREATE("客户创建", "CUSTOMER"),
CUSTOMER_UPDATE("客户资料修改", "CUSTOMER"),
FOLLOW_UP_CREATE("客户跟进提醒创建", "CUSTOMER_FOLLOW_UP"),
FOLLOW_UP_UPDATE("客户跟进提醒修改", "CUSTOMER_FOLLOW_UP"),
FOLLOW_UP_COMPLETE("客户跟进提醒完成", "CUSTOMER_FOLLOW_UP"),
STORE_DIARY_CREATE("门店日记创建", "STORE_DIARY"),
STORE_DIARY_UPDATE("门店日记修改", "STORE_DIARY"),
EVENT_RECORD_CREATE("登记事件记录创建", "EVENT_RECORD"),
EVENT_RECORD_UPDATE("登记事件记录修改", "EVENT_RECORD"),
EVENT_RECORD_VERIFY("登记事件记录核销", "EVENT_RECORD"),
STOCK_MANUAL_IN("库存手工入库", "PRODUCT_STOCK"),
STOCK_MANUAL_OUT("库存手工出库", "PRODUCT_STOCK"),
STOCK_STOCKTAKE_GAIN("库存盘盈", "PRODUCT_STOCK"),
STOCK_STOCKTAKE_LOSS("库存盘亏", "PRODUCT_STOCK"),
SALES_ORDER_CREATE("销售订单创建", "SALES_ORDER"),
SALES_ORDER_UPDATE("销售订单备注和附件修改", "SALES_ORDER"),
SALES_ORDER_CANCEL("销售订单取消", "SALES_ORDER"),
PAYMENT_RECEIVE("销售订单收款登记", "FUND_RECORD"),
PAYMENT_RECEIVE_AND_VERIFY("销售订单收款登记并核销", "FUND_RECORD"),
PAYMENT_VERIFY("销售订单收款核销", "FUND_RECORD"),
PAYMENT_REJECT("销售订单收款拒绝", "FUND_RECORD"),
PAYMENT_CANCEL("销售订单待核销收款撤销", "FUND_RECORD"),
PAYMENT_REFUND("销售订单退款", "FUND_RECORD"),
FUND_REVOKE("资金流水冲正", "FUND_RECORD"),
FULFILLMENT_CREATE("履约创建", "ORDER_FULFILLMENT"),
FULFILLMENT_CREATE_AND_VERIFY("履约创建并核销", "ORDER_FULFILLMENT"),
FULFILLMENT_VERIFY("履约核销", "ORDER_FULFILLMENT"),
FULFILLMENT_REJECT("履约拒绝", "ORDER_FULFILLMENT"),
FULFILLMENT_CANCEL("待核销履约撤销", "ORDER_FULFILLMENT"),
POINT_ADJUST("客户积分人工调整", "POINT_LEDGER"),
POINT_REDEMPTION_CREATE("积分兑换创建", "POINT_REDEMPTION"),
CUSTOMER_PACKAGE_PURCHASE("客户套餐购买", "CUSTOMER_PACKAGE");
/// 操作标题
private final String title;
/// 结果实体类型
private final String entityType;
GaoAiOperation(String title, String entityType) {
this.title = title;
this.entityType = entityType;
}
}
@@ -0,0 +1,51 @@
package com.imyeyu.api.modules.gao.ai.operation;
import com.imyeyu.api.modules.gao.ai.entity.GaoAiSession;
import lombok.Getter;
/// GAO 智能体写操作执行上下文
///
/// @author Codex
/// @since 2026-11-23
@Getter
public final class GaoAiOperationContext {
private final GaoAiSession session;
private final String userId;
private final String storeId;
private final String conversationId;
private final String requestId;
private GaoAiOperationContext(GaoAiSession session, String userId, String storeId, String conversationId, String requestId) {
this.session = session;
this.userId = userId;
this.storeId = storeId;
this.conversationId = conversationId;
this.requestId = requestId;
}
/// 从 AI 会话创建执行上下文
///
/// @param session AI 会话
/// @param requestId 请求追踪 ID
/// @return 执行上下文
public static GaoAiOperationContext of(GaoAiSession session, String requestId) {
return new GaoAiOperationContext(session, session.getUserId(), session.getStoreId(),
session.getDifyConversationId(), requestId);
}
/// 从已认证用户创建执行上下文,用于 REST commit/cancel
///
/// @param userId 用户 ID
/// @param storeId 门店 ID
/// @param conversationId Dify 会话 ID,可为空
/// @param requestId 请求追踪 ID
/// @return 执行上下文
public static GaoAiOperationContext of(String userId, String storeId, String conversationId, String requestId) {
return new GaoAiOperationContext(null, userId, storeId, conversationId, requestId);
}
}
@@ -0,0 +1,89 @@
package com.imyeyu.api.modules.gao.ai.operation;
import com.imyeyu.api.modules.gao.bean.GaoPermissionCode;
import lombok.Getter;
import java.util.List;
/// GAO 智能体写操作定义
///
/// @author Codex
/// @since 2026-11-23
@Getter
public class GaoAiOperationDefinition {
/// 风险级别
public enum RiskLevel {
/// 普通创建/修改
NORMAL,
/// 影响金额、价格或不可逆状态
SENSITIVE,
/// 取消、拒绝、冲正、退款等逆向操作
DESTRUCTIVE
}
/// 附件策略
public enum AttachmentPolicy {
/// 不接收附件
NONE,
/// 可选附件
OPTIONAL,
/// 必须至少一张照片
REQUIRED
}
private final GaoAiOperation operation;
private final RiskLevel riskLevel;
private final AttachmentPolicy attachmentPolicy;
private final List<GaoPermissionCode> permissions;
private final boolean reasonRequired;
GaoAiOperationDefinition(GaoAiOperation operation, RiskLevel riskLevel, AttachmentPolicy attachmentPolicy,
List<GaoPermissionCode> permissions, boolean reasonRequired) {
this.operation = operation;
this.riskLevel = riskLevel;
this.attachmentPolicy = attachmentPolicy;
this.permissions = List.copyOf(permissions);
this.reasonRequired = reasonRequired;
}
/// @return 操作代码
public String code() {
return operation.name();
}
/// @return 操作标题
public String title() {
return operation.getTitle();
}
/// @return 结果实体类型
public String entityType() {
return operation.getEntityType();
}
/// @return 是否破坏性操作
public boolean destructive() {
return riskLevel == RiskLevel.DESTRUCTIVE;
}
/// @return 是否敏感操作
public boolean sensitive() {
return riskLevel == RiskLevel.SENSITIVE || destructive();
}
/// @return 是否必须精确确认短语
public boolean exactPhraseRequired() {
return destructive();
}
}
@@ -0,0 +1,62 @@
package com.imyeyu.api.modules.gao.ai.operation;
import lombok.Getter;
import java.util.List;
/// GAO 智能体写操作异常
///
/// 业务错误通过错误码返回给 MCP/前端,不直接暴露内部异常。
///
/// @author Codex
/// @since 2026-11-23
@Getter
public class GaoAiOperationException extends RuntimeException {
private final String errorCode;
private final boolean retryable;
private final List<Object> candidates;
private final List<String> missingFields;
public GaoAiOperationException(String errorCode, String message) {
this(errorCode, message, false, List.of(), List.of());
}
public GaoAiOperationException(String errorCode, String message, boolean retryable) {
this(errorCode, message, retryable, List.of(), List.of());
}
public GaoAiOperationException(String errorCode, String message, List<?> candidates) {
this(errorCode, message, false, candidates, List.of());
}
public GaoAiOperationException(String errorCode, String message, boolean retryable, List<?> candidates,
List<String> missingFields) {
super(message);
this.errorCode = errorCode;
this.retryable = retryable;
this.candidates = candidates == null ? List.of() : candidates.stream().map(item -> (Object) item).toList();
this.missingFields = missingFields == null ? List.of() : List.copyOf(missingFields);
}
/// 缺少字段
///
/// @param message 提示
/// @param missingFields 缺失字段
/// @return 异常
public static GaoAiOperationException clarification(String message, List<String> missingFields) {
return new GaoAiOperationException("NEEDS_CLARIFICATION", message, false, List.of(), missingFields);
}
/// 存在歧义
///
/// @param message 提示
/// @param candidates 候选
/// @return 异常
public static GaoAiOperationException candidates(String message, List<?> candidates) {
return new GaoAiOperationException("CANDIDATES", message, false, candidates, List.of());
}
}
@@ -0,0 +1,37 @@
package com.imyeyu.api.modules.gao.ai.operation;
import com.fasterxml.jackson.databind.JsonNode;
import com.imyeyu.api.modules.common.entity.Attachment;
import java.util.List;
import java.util.Set;
/// GAO 智能体写操作处理器
///
/// @author Codex
/// @since 2026-11-23
public interface GaoAiOperationHandler {
/// @return 支持的操作
Set<GaoAiOperation> supports();
/// 准备操作,只做解析、校验和预览,不写业务数据
///
/// @param context 执行上下文
/// @param definition 操作定义
/// @param arguments 参数
/// @param attachments 已校验附件
/// @return 准备结果
GaoAiPreparedOperation prepare(GaoAiOperationContext context, GaoAiOperationDefinition definition,
JsonNode arguments, List<GaoAiAttachmentToken> attachments);
/// 提交操作,业务参数只从待确认记录读取
///
/// @param context 执行上下文
/// @param pending 待确认操作
/// @param arguments 标准化参数
/// @param attachments 已克隆的附件
/// @return 提交结果
GaoAiCommitResult commit(GaoAiOperationContext context, GaoAiPendingOperation pending,
JsonNode arguments, List<Attachment> attachments);
}
@@ -0,0 +1,181 @@
package com.imyeyu.api.modules.gao.ai.operation;
import com.imyeyu.api.modules.gao.ai.operation.GaoAiOperationDefinition.AttachmentPolicy;
import com.imyeyu.api.modules.gao.ai.operation.GaoAiOperationDefinition.RiskLevel;
import com.imyeyu.api.modules.gao.bean.GaoPermissionCode;
import org.springframework.stereotype.Component;
import java.util.Arrays;
import java.util.Collections;
import java.util.EnumMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
/// GAO 智能体写操作注册表
///
/// 所有写操作必须显式登记,未登记操作一律拒绝。
/// 注册表中不存在任何物理删除操作。
///
/// @author Codex
/// @since 2026-11-23
@Component
public class GaoAiOperationRegistry {
private final Map<GaoAiOperation, GaoAiOperationDefinition> definitions;
public GaoAiOperationRegistry() {
Map<GaoAiOperation, GaoAiOperationDefinition> map = new EnumMap<>(GaoAiOperation.class);
register(map, GaoAiOperation.CUSTOMER_CREATE, RiskLevel.NORMAL, AttachmentPolicy.OPTIONAL,
List.of(GaoPermissionCode.CUSTOMER_CREATE), false);
register(map, GaoAiOperation.CUSTOMER_UPDATE, RiskLevel.NORMAL, AttachmentPolicy.OPTIONAL,
List.of(GaoPermissionCode.CUSTOMER_UPDATE), false);
register(map, GaoAiOperation.FOLLOW_UP_CREATE, RiskLevel.NORMAL, AttachmentPolicy.OPTIONAL,
List.of(GaoPermissionCode.CUSTOMER_FOLLOW_UP_REMINDER_CREATE), false);
register(map, GaoAiOperation.FOLLOW_UP_UPDATE, RiskLevel.NORMAL, AttachmentPolicy.OPTIONAL,
List.of(GaoPermissionCode.CUSTOMER_FOLLOW_UP_REMINDER_UPDATE), false);
register(map, GaoAiOperation.FOLLOW_UP_COMPLETE, RiskLevel.NORMAL, AttachmentPolicy.NONE,
List.of(GaoPermissionCode.CUSTOMER_FOLLOW_UP_REMINDER_COMPLETE), false);
register(map, GaoAiOperation.STORE_DIARY_CREATE, RiskLevel.NORMAL, AttachmentPolicy.OPTIONAL,
List.of(GaoPermissionCode.STORE_DIARY_CREATE), false);
register(map, GaoAiOperation.STORE_DIARY_UPDATE, RiskLevel.NORMAL, AttachmentPolicy.OPTIONAL,
List.of(GaoPermissionCode.STORE_DIARY_UPDATE), false);
register(map, GaoAiOperation.EVENT_RECORD_CREATE, RiskLevel.NORMAL, AttachmentPolicy.OPTIONAL,
List.of(GaoPermissionCode.EVENT_RECORD_CREATE), false);
register(map, GaoAiOperation.EVENT_RECORD_UPDATE, RiskLevel.NORMAL, AttachmentPolicy.OPTIONAL,
List.of(GaoPermissionCode.EVENT_RECORD_UPDATE), false);
register(map, GaoAiOperation.EVENT_RECORD_VERIFY, RiskLevel.SENSITIVE, AttachmentPolicy.NONE,
List.of(GaoPermissionCode.EVENT_RECORD_VERIFY), false);
register(map, GaoAiOperation.STOCK_MANUAL_IN, RiskLevel.NORMAL, AttachmentPolicy.OPTIONAL,
List.of(GaoPermissionCode.PRODUCT_STOCK_CREATE), false);
register(map, GaoAiOperation.STOCK_MANUAL_OUT, RiskLevel.NORMAL, AttachmentPolicy.OPTIONAL,
List.of(GaoPermissionCode.PRODUCT_STOCK_CREATE), false);
register(map, GaoAiOperation.STOCK_STOCKTAKE_GAIN, RiskLevel.SENSITIVE, AttachmentPolicy.OPTIONAL,
List.of(GaoPermissionCode.PRODUCT_STOCK_CREATE), false);
register(map, GaoAiOperation.STOCK_STOCKTAKE_LOSS, RiskLevel.SENSITIVE, AttachmentPolicy.OPTIONAL,
List.of(GaoPermissionCode.PRODUCT_STOCK_CREATE), false);
register(map, GaoAiOperation.SALES_ORDER_CREATE, RiskLevel.NORMAL, AttachmentPolicy.OPTIONAL,
List.of(GaoPermissionCode.SALES_ORDER_CREATE), false);
register(map, GaoAiOperation.SALES_ORDER_UPDATE, RiskLevel.NORMAL, AttachmentPolicy.OPTIONAL,
List.of(GaoPermissionCode.SALES_ORDER_UPDATE), false);
register(map, GaoAiOperation.SALES_ORDER_CANCEL, RiskLevel.DESTRUCTIVE, AttachmentPolicy.OPTIONAL,
List.of(GaoPermissionCode.SALES_ORDER_CANCEL), true);
register(map, GaoAiOperation.PAYMENT_RECEIVE, RiskLevel.NORMAL, AttachmentPolicy.REQUIRED,
List.of(GaoPermissionCode.FUND_RECEIVE_CREATE), false);
register(map, GaoAiOperation.PAYMENT_RECEIVE_AND_VERIFY, RiskLevel.SENSITIVE, AttachmentPolicy.REQUIRED,
List.of(GaoPermissionCode.FUND_RECEIVE_CREATE, GaoPermissionCode.FUND_RECEIVE_VERIFY), false);
register(map, GaoAiOperation.PAYMENT_VERIFY, RiskLevel.SENSITIVE, AttachmentPolicy.NONE,
List.of(GaoPermissionCode.FUND_RECEIVE_VERIFY), false);
register(map, GaoAiOperation.PAYMENT_REJECT, RiskLevel.DESTRUCTIVE, AttachmentPolicy.NONE,
List.of(GaoPermissionCode.FUND_RECEIVE_VERIFY), true);
register(map, GaoAiOperation.PAYMENT_CANCEL, RiskLevel.DESTRUCTIVE, AttachmentPolicy.NONE,
List.of(GaoPermissionCode.FUND_RECEIVE_CREATE), true);
register(map, GaoAiOperation.PAYMENT_REFUND, RiskLevel.DESTRUCTIVE, AttachmentPolicy.REQUIRED,
List.of(GaoPermissionCode.FUND_REFUND), true);
register(map, GaoAiOperation.FUND_REVOKE, RiskLevel.DESTRUCTIVE, AttachmentPolicy.REQUIRED,
List.of(GaoPermissionCode.FUND_REVOKE), true);
register(map, GaoAiOperation.FULFILLMENT_CREATE, RiskLevel.NORMAL, AttachmentPolicy.REQUIRED,
List.of(GaoPermissionCode.ORDER_FULFILLMENT_CREATE), false);
register(map, GaoAiOperation.FULFILLMENT_CREATE_AND_VERIFY, RiskLevel.SENSITIVE, AttachmentPolicy.REQUIRED,
List.of(GaoPermissionCode.ORDER_FULFILLMENT_CREATE, GaoPermissionCode.ORDER_FULFILLMENT_VERIFY), false);
register(map, GaoAiOperation.FULFILLMENT_VERIFY, RiskLevel.SENSITIVE, AttachmentPolicy.NONE,
List.of(GaoPermissionCode.ORDER_FULFILLMENT_VERIFY), false);
register(map, GaoAiOperation.FULFILLMENT_REJECT, RiskLevel.DESTRUCTIVE, AttachmentPolicy.NONE,
List.of(GaoPermissionCode.ORDER_FULFILLMENT_VERIFY), true);
register(map, GaoAiOperation.FULFILLMENT_CANCEL, RiskLevel.DESTRUCTIVE, AttachmentPolicy.NONE,
List.of(GaoPermissionCode.ORDER_FULFILLMENT_CREATE), true);
register(map, GaoAiOperation.POINT_ADJUST, RiskLevel.SENSITIVE, AttachmentPolicy.NONE,
List.of(GaoPermissionCode.POINT_ADJUST), false);
register(map, GaoAiOperation.POINT_REDEMPTION_CREATE, RiskLevel.NORMAL, AttachmentPolicy.REQUIRED,
List.of(GaoPermissionCode.POINT_REDEMPTION_CREATE), false);
register(map, GaoAiOperation.CUSTOMER_PACKAGE_PURCHASE, RiskLevel.NORMAL, AttachmentPolicy.OPTIONAL,
List.of(GaoPermissionCode.CUSTOMER_PACKAGE_CREATE), false);
this.definitions = Collections.unmodifiableMap(map);
}
private void register(Map<GaoAiOperation, GaoAiOperationDefinition> map, GaoAiOperation operation,
RiskLevel riskLevel, AttachmentPolicy attachmentPolicy, List<GaoPermissionCode> permissions,
boolean reasonRequired) {
map.put(operation, new GaoAiOperationDefinition(operation, riskLevel, attachmentPolicy, permissions, reasonRequired));
}
/// 获取操作定义
///
/// @param operation 操作
/// @return 操作定义
public GaoAiOperationDefinition require(GaoAiOperation operation) {
GaoAiOperationDefinition definition = operation == null ? null : definitions.get(operation);
if (definition == null) {
throw new GaoAiOperationException("FEATURE_DISABLED", "该操作未对智能助手开放");
}
return definition;
}
/// 按代码解析操作
///
/// @param code 操作代码
/// @return 操作定义
public GaoAiOperationDefinition require(String code) {
if (code == null || code.isBlank()) {
throw new GaoAiOperationException("VALIDATION_FAILED", "缺少操作类型");
}
try {
return require(GaoAiOperation.valueOf(code.trim().toUpperCase()));
} catch (IllegalArgumentException e) {
throw new GaoAiOperationException("FEATURE_DISABLED", "不支持的操作类型");
}
}
/// @return 全部操作定义
public List<GaoAiOperationDefinition> list() {
return List.copyOf(definitions.values());
}
/// @return 操作代码列表
public List<String> codes() {
return definitions.keySet().stream().map(Enum::name).toList();
}
/// 生成给模型和前端阅读的操作目录
///
/// @return 操作目录文本
public String catalog() {
return definitions.values().stream()
.map(definition -> "- %s:%s;权限:%s;风险:%s".formatted(
definition.code(),
definition.title(),
definition.getPermissions().stream().map(GaoPermissionCode::getValue).collect(Collectors.joining(",")),
definition.getRiskLevel().name()))
.collect(Collectors.joining("\n"));
}
/// 判断操作代码是否存在
///
/// @param code 操作代码
/// @return true 为存在
public boolean contains(String code) {
try {
return definitions.containsKey(GaoAiOperation.valueOf(code));
} catch (RuntimeException e) {
return false;
}
}
/// @return 静态检查用:确认没有任何删除操作代码
public List<String> destructiveOperationCodes() {
return Arrays.stream(GaoAiOperation.values())
.filter(operation -> definitions.get(operation).destructive())
.map(Enum::name)
.toList();
}
}
@@ -0,0 +1,70 @@
package com.imyeyu.api.modules.gao.ai.operation;
import com.imyeyu.api.modules.gao.ai.entity.GaoAiSession;
import com.imyeyu.api.modules.gao.ai.vo.GaoAiToolResult;
/// GAO 智能体写操作服务
///
/// @author Codex
/// @since 2026-11-23
public interface GaoAiOperationService {
/// 准备写操作
///
/// @param session AI 会话
/// @param operation 操作代码
/// @param argumentsJson 业务参数 JSON
/// @param attachmentTokensJson 附件凭证 JSON 数组
/// @return 准备结果
GaoAiToolResult prepare(GaoAiSession session, String operation, String argumentsJson, String attachmentTokensJson);
/// 按确认 token 提交
///
/// @param session AI 会话
/// @param token 确认 token
/// @param confirmationPhrase 确认短语
/// @param reason 操作原因
/// @return 提交结果
GaoAiToolResult commit(GaoAiSession session, String token, String confirmationPhrase, String reason);
/// 按公开操作 ID 提交,用于前端卡片 REST 接口
///
/// @param userId 用户 ID
/// @param storeId 门店 ID
/// @param conversationId Dify 会话 ID
/// @param operationId 公开操作 ID
/// @param confirmationPhrase 确认短语
/// @param reason 操作原因
/// @return 提交结果
GaoAiToolResult commit(String userId, String storeId, String conversationId, String operationId,
String confirmationPhrase, String reason);
/// 按确认 token 取消
///
/// @param session AI 会话
/// @param token 确认 token
/// @return 取消结果
GaoAiToolResult cancel(GaoAiSession session, String token);
/// 按公开操作 ID 取消
///
/// @param userId 用户 ID
/// @param storeId 门店 ID
/// @param operationId 公开操作 ID
/// @return 取消结果
GaoAiToolResult cancel(String userId, String storeId, String operationId);
/// 查询当前活跃待确认操作
///
/// @param userId 用户 ID
/// @param storeId 门店 ID
/// @param conversationId Dify 会话 ID
/// @return 待确认操作视图
GaoAiToolResult pending(String userId, String storeId, String conversationId);
/// 绑定 Dify 会话
///
/// @param sourceSessionId 来源 AI 会话 ID
/// @param conversationId Dify 会话 ID
void bindConversation(String sourceSessionId, String conversationId);
}
@@ -0,0 +1,600 @@
package com.imyeyu.api.modules.gao.ai.operation;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.imyeyu.api.modules.gao.ai.config.GaoAiProperties;
import com.imyeyu.api.modules.gao.ai.entity.GaoAiAuditLog;
import com.imyeyu.api.modules.gao.ai.entity.GaoAiSession;
import com.imyeyu.api.modules.gao.ai.operation.GaoAiOperationDefinition.RiskLevel;
import com.imyeyu.api.modules.gao.ai.service.GaoAiAuditService;
import com.imyeyu.api.modules.gao.ai.vo.GaoAiToolResult;
import com.imyeyu.api.modules.gao.service.GaoStoreScopeService;
import com.imyeyu.api.modules.user.context.ExecutionIdentityContext;
import com.imyeyu.java.bean.timi.TimiException;
import com.imyeyu.spring.util.Redis;
import jakarta.annotation.PostConstruct;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.EnumMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
/// GAO 智能体写操作服务实现
///
/// @author Codex
/// @since 2026-11-23
@Slf4j
@Service
@RequiredArgsConstructor
public class GaoAiOperationServiceImplement implements GaoAiOperationService {
private static final String COMMIT_LOCK_PREFIX = "GAO:AI:OP:COMMIT:";
private final GaoAiProperties properties;
private final GaoAiOperationRegistry registry;
private final GaoAiToolAuthorizer authorizer;
private final GaoAiPendingOperationService pendingService;
private final GaoAiAttachmentService attachmentService;
private final GaoAiAuditService auditService;
private final GaoAiOperationSupport support;
private final GaoStoreScopeService storeScopeService;
private final ObjectMapper jackson;
private final List<GaoAiOperationHandler> handlerList;
// @Qualifier("redisLocker")
private Redis<String, Integer> locker;
// @Qualifier("redisRateLimit")
private Redis<String, Integer> rateLimitRedis;
private Map<GaoAiOperation, GaoAiOperationHandler> handlerMap;
@PostConstruct
private void postConstruct() {
Map<GaoAiOperation, GaoAiOperationHandler> map = new EnumMap<>(GaoAiOperation.class);
for (GaoAiOperationHandler handler : handlerList) {
for (GaoAiOperation operation : handler.supports()) {
GaoAiOperationHandler previous = map.put(operation, handler);
if (previous != null) {
throw new IllegalStateException("重复注册 GAO AI 写操作处理器:" + operation);
}
}
}
for (GaoAiOperation operation : GaoAiOperation.values()) {
if (!map.containsKey(operation)) {
throw new IllegalStateException("GAO AI 写操作缺少处理器:" + operation);
}
}
this.handlerMap = Map.copyOf(map);
}
@Override
public GaoAiToolResult prepare(GaoAiSession session, String operation, String argumentsJson, String attachmentTokensJson) {
long startedAt = System.currentTimeMillis();
GaoAiOperationDefinition definition = null;
List<String> tokens = List.of();
try {
if (!properties.isWriteEnabled()) {
return failure("FEATURE_DISABLED", "FEATURE_DISABLED", "智能助手写能力暂未开放", false, startedAt,
List.of(), List.of());
}
checkRate("PREPARE", session.getUserId(), properties.getMaxPreparesPer10Minutes());
definition = registry.require(operation);
authorizer.check(session.getUserId(), definition);
try {
storeScopeService.checkStoreId(session.getStoreId());
} catch (TimiException e) {
throw new GaoAiOperationException("STORE_SCOPE_DENIED", e.getMessage());
}
if (argumentsJson != null && argumentsJson.length() > 20_000) {
throw new GaoAiOperationException("VALIDATION_FAILED", "操作参数过长");
}
JsonNode arguments = support.object(argumentsJson);
rejectForbiddenFields(arguments, "$");
tokens = parseTokens(attachmentTokensJson);
if (definition.getAttachmentPolicy() == GaoAiOperationDefinition.AttachmentPolicy.NONE) {
tokens = List.of();
}
if (definition.getAttachmentPolicy() == GaoAiOperationDefinition.AttachmentPolicy.REQUIRED && tokens.isEmpty()) {
throw new GaoAiOperationException("ATTACHMENT_REQUIRED", "该操作必须上传凭证照片");
}
List<GaoAiAttachmentToken> attachments = attachmentService.resolve(session.getUserId(), session.getStoreId(), tokens);
if (definition.getAttachmentPolicy() == GaoAiOperationDefinition.AttachmentPolicy.REQUIRED
&& attachments.stream().noneMatch(item -> item.getMimeType() != null && item.getMimeType().startsWith("image/"))) {
throw new GaoAiOperationException("ATTACHMENT_REQUIRED", "该操作必须上传照片凭证");
}
GaoAiOperationHandler handler = handler(definition.getOperation());
GaoAiOperationContext context = GaoAiOperationContext.of(session, UUID.randomUUID().toString());
GaoAiPreparedOperation prepared = handler.prepare(context, definition, arguments, attachments);
if (prepared == null || prepared.getPreviewText() == null) {
throw new GaoAiOperationException("INTERNAL_ERROR", "操作准备失败");
}
if (prepared.getArgumentsJson() == null || prepared.getArgumentsJson().isBlank()) {
prepared.setArgumentsJson(arguments.toString());
}
RiskLevel riskLevel = prepared.getRiskLevel();
if (riskLevel == null || riskLevel.ordinal() < definition.getRiskLevel().ordinal()) {
riskLevel = definition.getRiskLevel();
}
prepared.setRiskLevel(riskLevel);
if (prepared.getTitle() == null) {
prepared.setTitle(definition.title());
}
if (prepared.getRequiredPhrase() == null && definition.exactPhraseRequired()) {
prepared.setRequiredPhrase("确认" + definition.title());
}
if (prepared.getRiskLevel() == RiskLevel.DESTRUCTIVE) {
prepared.setReasonRequired(true);
}
String requestNo = support.requestNo(definition.getOperation());
GaoAiPendingOperationService.Created created = pendingService.create(context, definition, requestNo,
prepared.getArgumentsJson(), tokens, prepared);
GaoAiPendingOperation pending = created.pending();
recordAudit("GAO_AI_WRITE_PREPARE", "SUCCESS", session.getUserId(), session.getStoreId(),
session.getDifyConversationId(), pending.getOperation(), pending.getOperationId(), pending.getRequestNo(),
created.token(), pending.getRiskLevel(), null, null, false, null, startedAt);
// token 只由服务端下一轮注入,不返回给 Dify 工具输出,避免进入工作流日志和模型上下文
return success(pending, null, false);
} catch (GaoAiOperationException e) {
recordAudit("GAO_AI_WRITE_PREPARE", "FAILED", session.getUserId(), session.getStoreId(),
session.getDifyConversationId(), definition == null ? operation : definition.code(), null, null,
null, definition == null ? null : definition.getRiskLevel().name(), e.getErrorCode(), null, false,
null, startedAt);
return failure(e.getErrorCode(), e.getErrorCode(), e.getMessage(), e.isRetryable(), startedAt,
e.getCandidates(), e.getMissingFields());
} catch (TimiException e) {
recordAudit("GAO_AI_WRITE_PREPARE", "FAILED", session.getUserId(), session.getStoreId(),
session.getDifyConversationId(), definition == null ? operation : definition.code(), null, null,
null, definition == null ? null : definition.getRiskLevel().name(), "VALIDATION_FAILED", null,
false, null, startedAt);
return failure("VALIDATION_FAILED", "VALIDATION_FAILED", e.getMessage(), false, startedAt, List.of(), List.of());
} catch (RuntimeException e) {
log.warn("GAO AI 写操作准备失败:operation={}, userId={}, storeId={}", operation, session.getUserId(),
session.getStoreId(), e);
recordAudit("GAO_AI_WRITE_PREPARE", "ERROR", session.getUserId(), session.getStoreId(),
session.getDifyConversationId(), definition == null ? operation : definition.code(), null, null,
null, definition == null ? null : definition.getRiskLevel().name(), "INTERNAL_ERROR", null,
false, null, startedAt);
return failure("INTERNAL_ERROR", "INTERNAL_ERROR", "操作准备失败,请稍后重试", false, startedAt,
List.of(), List.of());
}
}
@Override
public GaoAiToolResult commit(GaoAiSession session, String token, String confirmationPhrase, String reason) {
long startedAt = System.currentTimeMillis();
GaoAiPendingOperation pending = null;
try {
pending = pendingService.requireByToken(token);
if (!pending.belongsTo(session.getUserId(), session.getStoreId())) {
throw new GaoAiOperationException("CONFIRMATION_REQUIRED", "确认凭证无效");
}
return commitInternal(pending, confirmationPhrase, reason, token, startedAt);
} catch (GaoAiOperationException e) {
recordAudit("GAO_AI_WRITE_COMMIT", "FAILED", session.getUserId(), session.getStoreId(),
session.getDifyConversationId(), pending == null ? null : pending.getOperation(),
pending == null ? null : pending.getOperationId(), pending == null ? null : pending.getRequestNo(),
token, pending == null ? null : pending.getRiskLevel(), e.getErrorCode(), null, false, reason, startedAt);
return failure("FAILED", e.getErrorCode(), e.getMessage(), e.isRetryable(), startedAt, List.of(), List.of());
} catch (RuntimeException e) {
log.warn("GAO AI 写操作提交失败:token={}", token == null ? 0 : token.length(), e);
recordAudit("GAO_AI_WRITE_COMMIT", "ERROR", session.getUserId(), session.getStoreId(),
session.getDifyConversationId(), pending == null ? null : pending.getOperation(),
pending == null ? null : pending.getOperationId(), pending == null ? null : pending.getRequestNo(),
token, pending == null ? null : pending.getRiskLevel(), "INTERNAL_ERROR", null, false, reason, startedAt);
return failure("FAILED", "INTERNAL_ERROR", "操作提交失败,请稍后重试", false, startedAt, List.of(), List.of());
}
}
@Override
public GaoAiToolResult commit(String userId, String storeId, String conversationId, String operationId,
String confirmationPhrase, String reason) {
long startedAt = System.currentTimeMillis();
GaoAiPendingOperation pending = null;
try {
pending = pendingService.requireByOperationId(operationId);
if (!pending.belongsTo(userId, storeId)) {
throw new GaoAiOperationException("CONFIRMATION_REQUIRED", "操作不存在或已过期");
}
return commitInternal(pending, confirmationPhrase, reason, null, startedAt);
} catch (GaoAiOperationException e) {
recordAudit("GAO_AI_WRITE_COMMIT", "FAILED", userId, storeId, conversationId,
pending == null ? null : pending.getOperation(), pending == null ? operationId : pending.getOperationId(),
pending == null ? null : pending.getRequestNo(), null, pending == null ? null : pending.getRiskLevel(),
e.getErrorCode(), null, false, reason, startedAt);
return failure("FAILED", e.getErrorCode(), e.getMessage(), e.isRetryable(), startedAt, List.of(), List.of());
} catch (RuntimeException e) {
log.warn("GAO AI 卡片提交失败:operationId={}", operationId, e);
recordAudit("GAO_AI_WRITE_COMMIT", "ERROR", userId, storeId, conversationId,
pending == null ? null : pending.getOperation(), pending == null ? operationId : pending.getOperationId(),
pending == null ? null : pending.getRequestNo(), null, pending == null ? null : pending.getRiskLevel(),
"INTERNAL_ERROR", null, false, reason, startedAt);
return failure("FAILED", "INTERNAL_ERROR", "操作提交失败,请稍后重试", false, startedAt, List.of(), List.of());
}
}
private GaoAiToolResult commitInternal(GaoAiPendingOperation pending, String confirmationPhrase, String reason,
String token, long startedAt) {
if (pending.getStatus() == GaoAiPendingOperation.Status.SUCCEEDED) {
return replay(pending);
}
if (pending.getStatus() == GaoAiPendingOperation.Status.CANCELLED) {
throw new GaoAiOperationException("CONFIRMATION_CANCELLED", "该操作已取消");
}
if (pending.getStatus() == GaoAiPendingOperation.Status.EXPIRED) {
throw new GaoAiOperationException("CONFIRMATION_EXPIRED", "该操作已过期");
}
if (pending.getStatus() == GaoAiPendingOperation.Status.SUPERSEDED) {
throw new GaoAiOperationException("CONFIRMATION_SUPERSEDED", "该操作已被新的操作替代");
}
if (pending.getStatus() == GaoAiPendingOperation.Status.COMMITTING) {
if (System.currentTimeMillis() - pending.getUpdatedAt() > 60_000L) {
pending.setStatus(GaoAiPendingOperation.Status.PENDING);
pendingService.save(pending);
} else {
throw new GaoAiOperationException("CONFIRMATION_IN_PROGRESS", "操作正在提交,请稍后查询结果", true);
}
}
if (pending.getStatus() == GaoAiPendingOperation.Status.FAILED) {
return failure("FAILED", pending.getLastErrorCode() == null ? "VALIDATION_FAILED" : pending.getLastErrorCode(),
pending.getLastErrorMessage() == null ? "操作提交失败" : pending.getLastErrorMessage(), false,
startedAt, List.of(), List.of());
}
long now = System.currentTimeMillis();
if (pending.getExpiresAt() <= now) {
pending.setStatus(GaoAiPendingOperation.Status.EXPIRED);
pendingService.save(pending);
throw new GaoAiOperationException("CONFIRMATION_EXPIRED", "确认已过期,请重新发起操作");
}
checkRate("COMMIT", pending.getUserId(), properties.getMaxCommitsPer10Minutes());
GaoAiOperationDefinition definition = registry.require(pending.getOperation());
authorizer.check(pending.getUserId(), definition);
if (pending.getRequiredPhrase() != null && !pending.getRequiredPhrase().isBlank()
&& !support.normalizePhrase(pending.getRequiredPhrase()).equals(support.normalizePhrase(confirmationPhrase))) {
throw new GaoAiOperationException("CONFIRMATION_PHRASE_MISMATCH",
"请按提示回复完整确认短语");
}
if (pending.isReasonRequired() && (reason == null || reason.isBlank())) {
throw new GaoAiOperationException("REASON_REQUIRED", "该操作必须填写原因");
}
String lockKey = COMMIT_LOCK_PREFIX + pending.getOperationId();
if (!locker.lock(lockKey, 1, 30_000L)) {
throw new GaoAiOperationException("CONFIRMATION_IN_PROGRESS", "操作正在提交,请稍后查询结果", true);
}
try {
GaoAiPendingOperation current = pendingService.requireByOperationId(pending.getOperationId());
if (current.getStatus() == GaoAiPendingOperation.Status.SUCCEEDED) {
return replay(current);
}
if (current.getStatus() == GaoAiPendingOperation.Status.COMMITTING) {
throw new GaoAiOperationException("CONFIRMATION_IN_PROGRESS", "操作正在提交,请稍后查询结果", true);
}
if (current.getStatus() == GaoAiPendingOperation.Status.FAILED) {
return failure("FAILED", current.getLastErrorCode() == null ? "VALIDATION_FAILED"
: current.getLastErrorCode(), current.getLastErrorMessage() == null ? "操作提交失败"
: current.getLastErrorMessage(), false, startedAt, List.of(), List.of());
}
if (current.getStatus() == GaoAiPendingOperation.Status.CANCELLED) {
throw new GaoAiOperationException("CONFIRMATION_CANCELLED", "该操作已取消");
}
if (current.getStatus() == GaoAiPendingOperation.Status.SUPERSEDED) {
throw new GaoAiOperationException("CONFIRMATION_SUPERSEDED", "该操作已被新的操作替代");
}
if (!current.confirmable(System.currentTimeMillis())) {
throw new GaoAiOperationException("CONFIRMATION_EXPIRED", "确认已过期,请重新发起操作");
}
current.setStatus(GaoAiPendingOperation.Status.COMMITTING);
current.setAttemptCount(current.getAttemptCount() + 1);
current.setCommitReason(reason);
pendingService.save(current);
GaoAiOperationContext context = GaoAiOperationContext.of(current.getUserId(), current.getStoreId(),
current.getConversationId(), current.getOperationId());
JsonNode arguments = support.object(current.getArgumentsJson());
List<com.imyeyu.api.modules.common.entity.Attachment> attachments = attachmentService.cloneForCommit(
current.getUserId(), current.getStoreId(), current.getAttachmentTokens());
GaoAiOperationHandler handler = handler(definition.getOperation());
GaoAiCommitResult result = ExecutionIdentityContext.runAs(current.getUserId(), "GAO_AI_OPERATION_COMMIT",
current.getOperationId(), () -> {
try {
storeScopeService.checkStoreId(current.getStoreId());
} catch (TimiException e) {
throw new GaoAiOperationException("STORE_SCOPE_DENIED", e.getMessage());
}
GaoAiCommitResult commitResult = handler.commit(context, current, arguments, attachments);
if (commitResult == null) {
throw new GaoAiOperationException("INTERNAL_ERROR", "业务操作未返回结果");
}
return commitResult;
});
current.setStatus(GaoAiPendingOperation.Status.SUCCEEDED);
current.setResultEntityId(result.getEntityId());
current.setResultEntityNo(result.getEntityNo());
current.setResultText(result.getResultText());
current.setCommittedAt(System.currentTimeMillis());
current.setLastErrorCode(null);
current.setLastErrorMessage(null);
pendingService.save(current);
recordAudit("GAO_AI_WRITE_COMMIT", "SUCCESS", current.getUserId(), current.getStoreId(),
current.getConversationId(), current.getOperation(), current.getOperationId(), current.getRequestNo(),
token, current.getRiskLevel(), null, result.getEntityType(), false, reason, startedAt);
GaoAiToolResult toolResult = success(current, null, false);
toolResult.setIdempotentReplay(false);
return toolResult;
} catch (GaoAiOperationException e) {
GaoAiPendingOperation current = safePending(pending);
if (current != null && !(current.getStatus() == GaoAiPendingOperation.Status.COMMITTING
&& "CONFIRMATION_IN_PROGRESS".equals(e.getErrorCode()))) {
current.setLastErrorCode(e.getErrorCode());
current.setLastErrorMessage(e.getMessage());
boolean keepPending = e.isRetryable()
|| "CONFIRMATION_PHRASE_MISMATCH".equals(e.getErrorCode())
|| "REASON_REQUIRED".equals(e.getErrorCode());
current.setStatus(keepPending ? GaoAiPendingOperation.Status.PENDING
: GaoAiPendingOperation.Status.FAILED);
pendingService.save(current);
}
recordAudit("GAO_AI_WRITE_COMMIT", "FAILED", pending.getUserId(), pending.getStoreId(),
pending.getConversationId(), pending.getOperation(), pending.getOperationId(), pending.getRequestNo(),
token, pending.getRiskLevel(), e.getErrorCode(), null, false, reason, startedAt);
throw e;
} catch (TimiException e) {
GaoAiPendingOperation current = safePending(pending);
if (current != null) {
current.setStatus(GaoAiPendingOperation.Status.FAILED);
current.setLastErrorCode("VALIDATION_FAILED");
current.setLastErrorMessage(e.getMessage());
pendingService.save(current);
}
recordAudit("GAO_AI_WRITE_COMMIT", "FAILED", pending.getUserId(), pending.getStoreId(),
pending.getConversationId(), pending.getOperation(), pending.getOperationId(), pending.getRequestNo(),
token, pending.getRiskLevel(), "VALIDATION_FAILED", null, false, reason, startedAt);
return failure("FAILED", "VALIDATION_FAILED", e.getMessage(), false, startedAt, List.of(), List.of());
} catch (RuntimeException e) {
log.warn("GAO AI 写操作提交异常:operationId={}", pending.getOperationId(), e);
GaoAiPendingOperation current = safePending(pending);
if (current != null) {
current.setStatus(GaoAiPendingOperation.Status.FAILED);
current.setLastErrorCode("INTERNAL_ERROR");
current.setLastErrorMessage("操作提交失败,请稍后重试");
pendingService.save(current);
}
recordAudit("GAO_AI_WRITE_COMMIT", "ERROR", pending.getUserId(), pending.getStoreId(),
pending.getConversationId(), pending.getOperation(), pending.getOperationId(), pending.getRequestNo(),
token, pending.getRiskLevel(), "INTERNAL_ERROR", null, false, reason, startedAt);
return failure("FAILED", "INTERNAL_ERROR", "操作提交失败,请稍后重试", false, startedAt, List.of(), List.of());
} finally {
locker.releaseLock(lockKey);
}
}
@Override
public GaoAiToolResult cancel(GaoAiSession session, String token) {
GaoAiPendingOperation pending = pendingService.requireByToken(token);
if (!pending.belongsTo(session.getUserId(), session.getStoreId())) {
throw new GaoAiOperationException("CONFIRMATION_REQUIRED", "确认凭证无效");
}
return cancelInternal(pending);
}
@Override
public GaoAiToolResult cancel(String userId, String storeId, String operationId) {
GaoAiPendingOperation pending = pendingService.requireByOperationId(operationId);
if (!pending.belongsTo(userId, storeId)) {
throw new GaoAiOperationException("CONFIRMATION_REQUIRED", "操作不存在或已过期");
}
return cancelInternal(pending);
}
private GaoAiToolResult cancelInternal(GaoAiPendingOperation pending) {
if (pending.getStatus() == GaoAiPendingOperation.Status.CANCELLED) {
return cancelled(pending);
}
if (pending.getStatus() == GaoAiPendingOperation.Status.SUCCEEDED) {
throw new GaoAiOperationException("CONFIRMATION_REQUIRED", "操作已经成功,不能取消");
}
if (pending.getStatus() == GaoAiPendingOperation.Status.COMMITTING) {
throw new GaoAiOperationException("CONFIRMATION_IN_PROGRESS", "操作正在提交,不能取消", true);
}
pending.setStatus(GaoAiPendingOperation.Status.CANCELLED);
pending.setCancelledAt(System.currentTimeMillis());
pendingService.save(pending);
recordAudit("GAO_AI_WRITE_CANCEL", "SUCCESS", pending.getUserId(), pending.getStoreId(),
pending.getConversationId(), pending.getOperation(), pending.getOperationId(), pending.getRequestNo(),
null, pending.getRiskLevel(), null, null, false, null, System.currentTimeMillis());
return cancelled(pending);
}
@Override
public GaoAiToolResult pending(String userId, String storeId, String conversationId) {
GaoAiPendingOperation pending = pendingService.findActive(userId, storeId, conversationId);
if (pending == null) {
GaoAiToolResult result = new GaoAiToolResult();
result.setStatus("NONE");
return result;
}
return success(pending, null, false);
}
@Override
public void bindConversation(String sourceSessionId, String conversationId) {
GaoAiPendingOperation pending = pendingService.findActiveBySourceSession(sourceSessionId);
if (pending != null) {
pendingService.bindConversation(pending, conversationId);
}
}
private GaoAiOperationHandler handler(GaoAiOperation operation) {
GaoAiOperationHandler handler = handlerMap.get(operation);
if (handler == null) {
throw new GaoAiOperationException("FEATURE_DISABLED", "该操作处理器未启用");
}
return handler;
}
private GaoAiToolResult success(GaoAiPendingOperation pending, String token, boolean replay) {
GaoAiToolResult result = new GaoAiToolResult();
result.setStatus(replay ? "SUCCEEDED" : "PENDING_CONFIRMATION");
result.setOperation(pending.getOperation());
result.setTitle(pending.getTitle());
result.setOperationId(pending.getOperationId());
result.setConfirmationToken(token);
result.setRiskLevel(pending.getRiskLevel());
result.setRequiredPhrase(pending.getRequiredPhrase());
result.setExpiresAt(pending.getExpiresAt());
result.setDestructive(RiskLevel.DESTRUCTIVE.name().equals(pending.getRiskLevel()));
result.setReasonRequired(pending.isReasonRequired());
result.setAttachmentCount(pending.getAttachmentTokens() == null ? 0 : pending.getAttachmentTokens().size());
result.setPreview(pending.getPreview());
result.setPreviewText(pending.getPreviewText());
result.setImpactText(pending.getImpactText());
result.setEntityType(pending.getEntityType());
result.setEntityId(pending.getResultEntityId());
result.setEntityNo(pending.getResultEntityNo());
result.setResultText(pending.getResultText());
result.setIdempotentReplay(replay);
return result;
}
private GaoAiToolResult replay(GaoAiPendingOperation pending) {
GaoAiToolResult result = success(pending, null, true);
result.setStatus("SUCCEEDED");
result.setIdempotentReplay(true);
return result;
}
private GaoAiToolResult cancelled(GaoAiPendingOperation pending) {
GaoAiToolResult result = new GaoAiToolResult();
result.setStatus("CANCELLED");
result.setOperation(pending.getOperation());
result.setOperationId(pending.getOperationId());
result.setResultText("已取消待确认操作。");
return result;
}
private GaoAiToolResult failure(String status, String errorCode, String errorMessage, boolean retryable,
long startedAt, List<Object> candidates) {
return failure(status, errorCode, errorMessage, retryable, startedAt, candidates, List.of());
}
private GaoAiToolResult failure(String status, String errorCode, String errorMessage, boolean retryable,
long startedAt, List<Object> candidates, List<String> missingFields) {
GaoAiToolResult result = new GaoAiToolResult();
result.setStatus(status);
result.setErrorCode(errorCode);
result.setErrorMessage(errorMessage);
result.setRetryable(retryable);
result.setCandidates(candidates == null ? List.of() : new ArrayList<>(candidates));
result.setMissingFields(missingFields == null ? List.of() : new ArrayList<>(missingFields));
result.getSource().put("duration", Math.max(0L, System.currentTimeMillis() - startedAt));
return result;
}
private List<String> parseTokens(String attachmentTokensJson) {
if (attachmentTokensJson == null || attachmentTokensJson.isBlank()) {
return List.of();
}
try {
JsonNode node = jackson.readTree(attachmentTokensJson);
if (node == null || node.isNull()) {
return List.of();
}
if (node.isArray()) {
List<String> result = new ArrayList<>();
for (JsonNode item : node) {
if (item != null && item.isTextual() && !item.asText().isBlank()) {
result.add(item.asText().trim());
}
}
return result;
}
if (node.isTextual() && !node.asText().isBlank()) {
return List.of(node.asText().trim());
}
} catch (Exception e) {
throw new GaoAiOperationException("VALIDATION_FAILED", "附件凭证格式无效");
}
throw new GaoAiOperationException("VALIDATION_FAILED", "附件凭证格式无效");
}
private void rejectForbiddenFields(JsonNode node, String path) {
if (node == null) {
return;
}
if (node.isObject()) {
var fields = node.fields();
while (fields.hasNext()) {
var entry = fields.next();
String name = entry.getKey();
if ("storeId".equals(name) || "operatorUserId".equals(name) || "userId".equals(name)
|| "requestNo".equals(name) || "confirmationToken".equals(name) || "operationId".equals(name)
|| "sourceSessionId".equals(name) || "requestId".equals(name)) {
throw new GaoAiOperationException("VALIDATION_FAILED", "参数不允许包含 " + name);
}
rejectForbiddenFields(entry.getValue(), path + "." + name);
}
} else if (node.isArray()) {
for (JsonNode item : node) {
rejectForbiddenFields(item, path + "[]");
}
}
}
private GaoAiPendingOperation safePending(GaoAiPendingOperation pending) {
try {
return pendingService.requireByOperationId(pending.getOperationId());
} catch (RuntimeException e) {
return null;
}
}
private void checkRate(String action, String userId, int limit) {
if (limit <= 0 || userId == null || userId.isBlank()) {
return;
}
long window = System.currentTimeMillis() / 600_000L;
String key = "GAO:AI:RATE:%s:%s:%d".formatted(action, userId, window);
String lockKey = key + ":LOCK";
if (!locker.lock(lockKey, 1, 3_000L)) {
throw new GaoAiOperationException("RATE_LIMITED", "操作过于频繁,请稍后重试", true);
}
try {
Integer current = rateLimitRedis.get(key);
int next = current == null ? 1 : current + 1;
if (next > limit) {
throw new GaoAiOperationException("RATE_LIMITED", "操作过于频繁,请稍后重试", true);
}
rateLimitRedis.set(key, next, 600_000L);
} finally {
locker.releaseLock(lockKey);
}
}
private void recordAudit(String action, String status, String userId, String storeId, String conversationId,
String operation, String operationId, String requestNo, String token, String riskLevel, String errorCode,
String entityType, boolean idempotentReplay, String reason, long startedAt) {
GaoAiAuditLog audit = new GaoAiAuditLog();
audit.setAction(action);
audit.setUserId(userId);
audit.setStoreId(storeId);
audit.setConversationId(conversationId);
audit.setOperation(operation);
audit.setOperationId(operationId);
audit.setRequestNo(requestNo);
audit.setConfirmationTokenDigest(token == null ? null : auditService.digest(token));
audit.setRiskLevel(riskLevel);
audit.setErrorCode(errorCode);
audit.setEntityType(entityType);
audit.setIdempotentReplay(idempotentReplay);
audit.setReasonDigest(reason == null ? null : auditService.digest(reason));
audit.setToolName("operation");
audit.setStatus(status);
audit.setDuration(Math.max(0L, System.currentTimeMillis() - startedAt));
audit.setCreatedAt(System.currentTimeMillis());
auditService.record(audit);
}
}
@@ -0,0 +1,834 @@
package com.imyeyu.api.modules.gao.ai.operation;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.imyeyu.api.modules.gao.entity.GaoCustomer;
import com.imyeyu.api.modules.gao.entity.GaoCustomerFollowUpReminder;
import com.imyeyu.api.modules.gao.entity.GaoEvent;
import com.imyeyu.api.modules.gao.entity.GaoEventRecord;
import com.imyeyu.api.modules.gao.entity.GaoFundRecord;
import com.imyeyu.api.modules.gao.entity.GaoOrderFulfillment;
import com.imyeyu.api.modules.gao.entity.GaoPackageConfig;
import com.imyeyu.api.modules.gao.entity.GaoPointRedeemSku;
import com.imyeyu.api.modules.gao.entity.GaoProduct;
import com.imyeyu.api.modules.gao.entity.GaoProductSku;
import com.imyeyu.api.modules.gao.entity.GaoProductSkuUnit;
import com.imyeyu.api.modules.gao.entity.GaoSalesOrder;
import com.imyeyu.api.modules.gao.service.GaoCustomerFollowUpReminderService;
import com.imyeyu.api.modules.gao.service.GaoCustomerService;
import com.imyeyu.api.modules.gao.service.GaoEventRecordService;
import com.imyeyu.api.modules.gao.service.GaoEventService;
import com.imyeyu.api.modules.gao.service.GaoFundRecordService;
import com.imyeyu.api.modules.gao.service.GaoOrderFulfillmentService;
import com.imyeyu.api.modules.gao.service.GaoPackageConfigService;
import com.imyeyu.api.modules.gao.service.GaoPointRedeemSkuService;
import com.imyeyu.api.modules.gao.service.GaoProductService;
import com.imyeyu.api.modules.gao.service.GaoProductSkuService;
import com.imyeyu.api.modules.gao.service.GaoSalesOrderService;
import com.imyeyu.api.modules.gao.vo.customer.GaoCustomerFollowUpReminderPage;
import com.imyeyu.api.modules.gao.vo.customer.GaoCustomerPage;
import com.imyeyu.api.modules.gao.vo.event.GaoEventRecordPage;
import com.imyeyu.api.modules.gao.vo.point.GaoPointRedeemSkuPage;
import com.imyeyu.api.modules.gao.vo.product.GaoProductPage;
import com.imyeyu.api.modules.gao.vo.product.GaoProductSkuUnitSelection;
import com.imyeyu.api.modules.gao.vo.salesorder.GaoSalesOrderPage;
import com.imyeyu.spring.bean.PageResult;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.concurrent.ThreadLocalRandom;
/// GAO 智能体写操作公共支持
///
/// @author Codex
/// @since 2026-11-23
@Service
@RequiredArgsConstructor
public class GaoAiOperationSupport {
private static final ZoneId ZONE = ZoneId.systemDefault();
private static final DateTimeFormatter DATE_TIME = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm");
private static final DateTimeFormatter REQUEST_TIME = DateTimeFormatter.ofPattern("yyyyMMddHHmmss");
private final ObjectMapper jackson;
private final GaoCustomerService customerService;
private final GaoCustomerFollowUpReminderService followUpService;
private final GaoSalesOrderService salesOrderService;
private final GaoProductService productService;
private final GaoProductSkuService skuService;
private final GaoEventService eventService;
private final GaoEventRecordService eventRecordService;
private final GaoPackageConfigService packageConfigService;
private final GaoPointRedeemSkuService redeemSkuService;
private final GaoOrderFulfillmentService fulfillmentService;
private final GaoFundRecordService fundRecordService;
/// 解析 JSON 对象
///
/// @param json JSON 文本
/// @return JSON 对象
public JsonNode object(String json) {
if (json == null || json.isBlank()) {
return jackson.createObjectNode();
}
try {
JsonNode node = jackson.readTree(json);
if (node == null || !node.isObject()) {
throw new GaoAiOperationException("VALIDATION_FAILED", "操作参数必须是 JSON 对象");
}
return node;
} catch (GaoAiOperationException e) {
throw e;
} catch (Exception e) {
throw new GaoAiOperationException("VALIDATION_FAILED", "操作参数 JSON 格式无效");
}
}
/// 复制为可修改对象
///
/// @param node 原参数
/// @return 可修改对象
public com.fasterxml.jackson.databind.node.ObjectNode normalizable(JsonNode node) {
if (node != null && node.isObject()) {
return ((com.fasterxml.jackson.databind.node.ObjectNode) node).deepCopy();
}
return jackson.createObjectNode();
}
/// 第一个非空文本字段
///
/// @param node JSON 对象
/// @param fields 字段名
/// @return 文本,未找到返回 null
public String text(JsonNode node, String... fields) {
if (node == null) {
return null;
}
for (String field : fields) {
if (node.hasNonNull(field)) {
String value = node.get(field).asText();
if (value != null && !value.isBlank()) {
return value.trim();
}
}
}
return null;
}
/// 必填文本
///
/// @param node JSON 对象
/// @param label 展示名称
/// @param fields 字段名
/// @return 文本
public String requiredText(JsonNode node, String label, String... fields) {
String value = text(node, fields);
if (value == null) {
throw GaoAiOperationException.clarification("请补充" + label, List.of(fields[0]));
}
return value;
}
/// 可选长整型
///
/// @param node JSON 对象
/// @param fields 字段名
/// @return 长整型,未找到返回 null
public Long optionalLong(JsonNode node, String... fields) {
if (node == null) {
return null;
}
for (String field : fields) {
if (node.hasNonNull(field)) {
try {
return node.get(field).asLong();
} catch (RuntimeException e) {
throw new GaoAiOperationException("VALIDATION_FAILED", field + " 必须是整数");
}
}
}
return null;
}
/// 必填长整型
///
/// @param node JSON 对象
/// @param label 展示名称
/// @param fields 字段名
/// @return 长整型
public long requiredLong(JsonNode node, String label, String... fields) {
Long value = optionalLong(node, fields);
if (value == null) {
throw GaoAiOperationException.clarification("请补充" + label, List.of(fields[0]));
}
return value;
}
/// 可选小数
///
/// @param node JSON 对象
/// @param fields 字段名
/// @return 小数,未找到返回 null
public BigDecimal optionalDecimal(JsonNode node, String... fields) {
if (node == null) {
return null;
}
for (String field : fields) {
if (node.hasNonNull(field)) {
try {
return node.get(field).decimalValue();
} catch (RuntimeException e) {
throw new GaoAiOperationException("VALIDATION_FAILED", field + " 必须是数字");
}
}
}
return null;
}
/// 必填小数
///
/// @param node JSON 对象
/// @param label 展示名称
/// @param fields 字段名
/// @return 小数
public BigDecimal requiredDecimal(JsonNode node, String label, String... fields) {
BigDecimal value = optionalDecimal(node, fields);
if (value == null) {
throw GaoAiOperationException.clarification("请补充" + label, List.of(fields[0]));
}
return value;
}
/// 可选布尔
///
/// @param node JSON 对象
/// @param fields 字段名
/// @return 布尔,未找到返回 null
public Boolean optionalBoolean(JsonNode node, String... fields) {
if (node == null) {
return null;
}
for (String field : fields) {
if (node.hasNonNull(field)) {
return node.get(field).asBoolean();
}
}
return null;
}
/// 解析数组字段,支持数组或 JSON 字符串
///
/// @param node JSON 对象
/// @param field 字段名
/// @return 数组元素
public List<JsonNode> array(JsonNode node, String field) {
if (node == null || !node.hasNonNull(field)) {
return List.of();
}
JsonNode value = node.get(field);
if (value.isArray()) {
List<JsonNode> result = new ArrayList<>();
value.forEach(result::add);
return result;
}
if (value.isTextual()) {
try {
JsonNode parsed = jackson.readTree(value.asText());
if (parsed != null && parsed.isArray()) {
List<JsonNode> result = new ArrayList<>();
parsed.forEach(result::add);
return result;
}
} catch (Exception ignored) {
// 交由调用方返回字段错误
}
}
throw new GaoAiOperationException("VALIDATION_FAILED", field + " 必须是数组");
}
/// 生成后端幂等请求号
///
/// @param operation 操作
/// @return 请求号
public String requestNo(GaoAiOperation operation) {
int random = ThreadLocalRandom.current().nextInt(0x1000000);
return "AI-%s-%s-%06x".formatted(operation.name(), LocalDateTime.now(ZONE).format(REQUEST_TIME), random);
}
/// 金额格式化
///
/// @param cents 分
/// @return 元文本
public String money(Long cents) {
if (cents == null) {
return "0.00 元";
}
return BigDecimal.valueOf(cents).movePointLeft(2).setScale(2, RoundingMode.HALF_UP).toPlainString() + " 元";
}
/// 时间格式化
///
/// @param millis 毫秒时间戳
/// @return 时间文本
public String dateTime(Long millis) {
if (millis == null) {
return "-";
}
return LocalDateTime.ofInstant(Instant.ofEpochMilli(millis), ZONE).format(DATE_TIME);
}
/// 规范化确认短语
///
/// @param value 用户输入
/// @return 规范化文本
public String normalizePhrase(String value) {
if (value == null) {
return "";
}
return value.replaceAll("[\\s,。!?、;:,.!?;:'\"“”‘’]", "").toLowerCase(Locale.ROOT);
}
/// 手机号脱敏
///
/// @param phone 手机号
/// @return 脱敏手机号
public String maskPhone(String phone) {
if (phone == null || phone.length() < 7) {
return phone;
}
return phone.substring(0, 3) + "****" + phone.substring(phone.length() - 4);
}
/// 客户摘要
///
/// @param customer 客户
/// @return 摘要
public Map<String, Object> customerBrief(GaoCustomer customer) {
Map<String, Object> result = new LinkedHashMap<>();
result.put("id", customer.getId());
result.put("name", customer.getName());
result.put("code", customer.getCode());
result.put("telephone", maskPhone(customer.getTelephone()));
return result;
}
/// 订单摘要
///
/// @param order 订单
/// @return 摘要
public Map<String, Object> orderBrief(GaoSalesOrder order) {
Map<String, Object> result = new LinkedHashMap<>();
result.put("id", order.getId());
result.put("orderNo", order.getOrderNo());
result.put("customerId", order.getCustomerId());
result.put("saleAmount", money(order.getSaleAmount()));
result.put("paidAmount", money(order.getPaidAmount()));
result.put("pendingPaidAmount", money(order.getPendingPaidAmount()));
result.put("unpaidAmount", money(order.getUnpaidAmount()));
result.put("status", order.getStatus());
result.put("paymentStatus", order.getPaymentStatus());
result.put("refundStatus", order.getRefundStatus());
return result;
}
/// 解析客户
///
/// @param storeId 门店 ID
/// @param node 参数
/// @return 客户
public GaoCustomer customer(String storeId, JsonNode node) {
String value = text(node, "customerId", "customerKeyword", "customerName", "customerCode");
if (value == null) {
throw GaoAiOperationException.clarification("请补充客户姓名或编码", List.of("customerKeyword"));
}
GaoCustomer customer = customerService.get(value);
if (customer != null) {
requireStore(storeId, customer.getStoreId(), "客户不属于当前门店");
return customer;
}
customer = customerService.getByCode(storeId, value);
if (customer == null) {
customer = customerService.getByName(storeId, value);
}
if (customer != null) {
return customer;
}
GaoCustomerPage page = new GaoCustomerPage();
page.setStoreId(storeId);
page.setKeyword(value);
page.setSize(5);
PageResult<GaoCustomer> result = customerService.pageByQuery(page);
if (result != null && result.getList() != null && result.getList().size() == 1) {
return result.getList().getFirst();
}
if (result != null && result.getList() != null && result.getList().size() > 1) {
throw GaoAiOperationException.candidates("匹配到多个客户,请选择客户编码",
result.getList().stream().map(this::customerBrief).toList());
}
throw GaoAiOperationException.candidates("未找到客户,请确认姓名或编码", List.of());
}
/// 解析销售订单
///
/// @param storeId 门店 ID
/// @param node 参数
/// @return 订单详情
public GaoSalesOrder order(String storeId, JsonNode node) {
String value = text(node, "salesOrderId", "orderId", "orderNo", "orderKeyword");
if (value == null) {
throw GaoAiOperationException.clarification("请补充订单号", List.of("orderNo"));
}
GaoSalesOrder order = salesOrderService.get(value);
if (order != null) {
requireStore(storeId, order.getStoreId(), "订单不属于当前门店");
return salesOrderService.detail(order.getId());
}
GaoSalesOrderPage page = new GaoSalesOrderPage();
page.setStoreId(storeId);
page.setKeyword(value);
page.setOrderAllowed(true);
page.setSize(5);
PageResult<GaoSalesOrder> result = salesOrderService.pageByQuery(page);
if (result != null && result.getList() != null && result.getList().size() == 1) {
return salesOrderService.detail(result.getList().getFirst().getId());
}
if (result != null && result.getList() != null && result.getList().size() > 1) {
throw GaoAiOperationException.candidates("匹配到多个订单,请选择订单号",
result.getList().stream().map(this::orderBrief).toList());
}
throw GaoAiOperationException.candidates("未找到订单,请确认订单号", List.of());
}
/// 解析 SKU 单位
///
/// @param storeId 门店 ID
/// @param node 参数
/// @param purchase true 为采购/入库,false 为销售
/// @return SKU 单位选项
public GaoProductSkuUnitSelection skuUnit(String storeId, JsonNode node, boolean purchase) {
String skuId = text(node, "skuId");
String unitId = text(node, "skuUnitId", "unitId");
String unitKeyword = text(node, "unitKeyword", "unitName");
if (skuId != null) {
GaoProductSku sku = skuService.get(skuId);
if (sku == null) {
throw new GaoAiOperationException("VALIDATION_FAILED", "SKU 不存在");
}
requireStore(storeId, sku.getStoreId(), "SKU 不属于当前门店");
GaoProduct product = productService.get(sku.getProductId());
if (product == null || product.getStatus() != GaoProduct.Status.ACTIVE || sku.getStatus() != GaoProductSku.Status.ACTIVE) {
throw new GaoAiOperationException("VALIDATION_FAILED", "SKU 已停用");
}
List<GaoProductSkuUnit> units = skuService.listUnitBySkuId(skuId);
GaoProductSkuUnit unit = selectUnit(units, unitId, unitKeyword, purchase);
return new GaoProductSkuUnitSelection(product, sku, unit);
}
String keyword = requiredText(node, "skuKeyword", "productKeyword", "productName", "keyword");
String unitText = unitKeyword;
GaoProductPage page = new GaoProductPage();
page.setStoreId(storeId);
page.setKeyword(keyword);
page.setStatus(GaoProduct.Status.ACTIVE);
page.setSize(20);
List<GaoProduct> products = purchase
? safeProductList(productService.pageByQuery(page))
: productService.listSellable(page);
List<GaoProductSkuUnitSelection> candidates = new ArrayList<>();
for (GaoProduct product : products) {
if (product == null || product.getStatus() != GaoProduct.Status.ACTIVE) {
continue;
}
for (GaoProductSku sku : product.getSkuList() == null ? List.<GaoProductSku>of() : product.getSkuList()) {
if (sku == null || sku.getStatus() != GaoProductSku.Status.ACTIVE) {
continue;
}
for (GaoProductSkuUnit unit : sku.getUnitList() == null ? List.<GaoProductSkuUnit>of() : sku.getUnitList()) {
if (!availableUnit(unit, purchase)) {
continue;
}
if ((contains(product.getName(), keyword) || matchesSku(sku, keyword))
&& matchesUnit(unit, unitText)) {
candidates.add(new GaoProductSkuUnitSelection(product, sku, unit));
}
}
}
}
if (candidates.size() == 1) {
return candidates.getFirst();
}
if (candidates.size() > 1) {
throw GaoAiOperationException.candidates("匹配到多个产品单位,请选择具体规格",
candidates.stream().map(this::skuBrief).toList());
}
throw GaoAiOperationException.candidates("未找到可销售的产品单位,请确认产品名称", List.of());
}
/// 解析登记事件
///
/// @param storeId 门店 ID
/// @param node 参数
/// @return 事件
public GaoEvent event(String storeId, JsonNode node) {
String value = text(node, "eventId", "eventKeyword", "eventName");
if (value == null) {
throw GaoAiOperationException.clarification("请补充登记事件名称", List.of("eventKeyword"));
}
List<GaoEvent> events = eventService.listValid(storeId);
List<GaoEvent> matches = events.stream()
.filter(event -> value.equals(event.getId()) || contains(event.getName(), value))
.toList();
if (matches.size() == 1) {
return matches.getFirst();
}
if (matches.size() > 1) {
throw GaoAiOperationException.candidates("匹配到多个登记事件,请选择名称",
matches.stream().map(event -> brief("id", event.getId(), "name", event.getName())).toList());
}
throw GaoAiOperationException.candidates("未找到登记事件,请确认名称", List.of());
}
/// 解析登记记录
///
/// @param storeId 门店 ID
/// @param node 参数
/// @return 记录
public GaoEventRecord eventRecord(String storeId, JsonNode node) {
String value = text(node, "eventRecordId", "recordId", "recordKeyword");
if (value == null) {
throw GaoAiOperationException.clarification("请补充登记记录 ID", List.of("eventRecordId"));
}
GaoEventRecord record = eventRecordService.get(value);
if (record != null) {
requireStore(storeId, record.getStoreId(), "登记记录不属于当前门店");
return record;
}
GaoEventRecordPage page = new GaoEventRecordPage();
page.setStoreId(storeId);
page.setKeyword(value);
page.setSize(5);
PageResult<GaoEventRecord> result = eventRecordService.pageByRange(page);
if (result != null && result.getList() != null && result.getList().size() == 1) {
return result.getList().getFirst();
}
if (result != null && result.getList() != null && result.getList().size() > 1) {
throw GaoAiOperationException.candidates("匹配到多条登记记录,请选择具体记录",
result.getList().stream().map(item -> brief("id", item.getId(), "customerId", item.getCustomerId(),
"registeredAt", dateTime(item.getRegisteredAt()))).toList());
}
throw GaoAiOperationException.candidates("未找到登记记录", List.of());
}
/// 解析套餐配置
///
/// @param storeId 门店 ID
/// @param node 参数
/// @return 套餐配置
public GaoPackageConfig packageConfig(String storeId, JsonNode node) {
String value = text(node, "packageConfigId", "packageKeyword", "packageName");
if (value == null) {
throw GaoAiOperationException.clarification("请补充套餐名称", List.of("packageKeyword"));
}
List<GaoPackageConfig> configs = packageConfigService.listValid(storeId);
List<GaoPackageConfig> matches = configs.stream()
.filter(config -> value.equals(config.getId()) || contains(config.getName(), value))
.toList();
if (matches.size() == 1) {
return matches.getFirst();
}
if (matches.size() > 1) {
throw GaoAiOperationException.candidates("匹配到多个套餐,请选择套餐名称",
matches.stream().map(config -> brief("id", config.getId(), "name", config.getName(),
"standardAmount", money(config.getStandardAmount()))).toList());
}
throw GaoAiOperationException.candidates("未找到可购买套餐", List.of());
}
/// 解析积分兑换 SKU
///
/// @param storeId 门店 ID
/// @param node 参数
/// @return 兑换配置
public GaoPointRedeemSku redeemSku(String storeId, JsonNode node) {
String value = text(node, "redeemSkuId", "redeemKeyword", "productKeyword");
if (value == null) {
throw GaoAiOperationException.clarification("请补充兑换产品名称", List.of("redeemKeyword"));
}
if (isIdLike(value)) {
try {
GaoPointRedeemSku detail = redeemSkuService.detail(storeId, value);
if (detail != null) {
return detail;
}
} catch (RuntimeException ignored) {
// 关键词不是 ID,继续按名称搜索
}
}
GaoPointRedeemSkuPage page = new GaoPointRedeemSkuPage();
page.setStoreId(storeId);
page.setKeyword(value);
page.setStatus(GaoPointRedeemSku.Status.ACTIVE);
page.setSize(5);
var result = redeemSkuService.pageByQuery(page);
if (result != null && result.getList() != null && result.getList().size() == 1) {
return result.getList().getFirst();
}
if (result != null && result.getList() != null && result.getList().size() > 1) {
throw GaoAiOperationException.candidates("匹配到多个兑换产品,请选择具体产品",
result.getList().stream().map(item -> brief("id", item.getId(), "defaultPointCost", item.getDefaultPointCost())).toList());
}
throw GaoAiOperationException.candidates("未找到可兑换产品", List.of());
}
/// 解析跟进提醒
///
/// @param storeId 门店 ID
/// @param node 参数
/// @return 跟进提醒
public GaoCustomerFollowUpReminder followUp(String storeId, JsonNode node) {
String value = text(node, "reminderId", "followUpId");
if (value != null) {
GaoCustomerFollowUpReminder reminder = followUpService.get(value);
if (reminder == null) {
throw new GaoAiOperationException("VALIDATION_FAILED", "未找到跟进提醒");
}
requireStore(storeId, reminder.getStoreId(), "跟进提醒不属于当前门店");
return reminder;
}
GaoCustomer customer = customer(storeId, node);
GaoCustomerFollowUpReminderPage page = new GaoCustomerFollowUpReminderPage();
page.setStoreId(storeId);
page.setCustomerId(customer.getId());
page.setStatus(GaoCustomerFollowUpReminder.Status.PENDING);
page.setSize(5);
var result = followUpService.pageByQuery(page);
List<GaoCustomerFollowUpReminder> list = result == null || result.getList() == null ? List.of() : result.getList();
if (list.size() == 1) {
return list.getFirst();
}
if (list.size() > 1) {
throw GaoAiOperationException.candidates("该客户有多条待完成跟进,请选择提醒 ID",
list.stream().map(item -> brief("reminderId", item.getId(), "content", item.getContent(),
"remindAt", dateTime(item.getRemindAt()))).toList());
}
throw new GaoAiOperationException("VALIDATION_FAILED", "该客户没有待完成的跟进提醒");
}
/// 解析履约单
///
/// @param storeId 门店 ID
/// @param node 参数
/// @return 履约单
public GaoOrderFulfillment fulfillment(String storeId, JsonNode node) {
String id = text(node, "fulfillmentId", "fulfillmentNo");
if (id != null) {
GaoOrderFulfillment fulfillment = fulfillmentService.detail(id);
if (fulfillment == null) {
throw new GaoAiOperationException("VALIDATION_FAILED", "未找到履约单");
}
requireStore(storeId, fulfillment.getStoreId(), "履约单不属于当前门店");
return fulfillment;
}
String requestNo = text(node, "fulfillmentRequestNo", "fulfillmentNo");
String orderValue = text(node, "orderNo", "salesOrderId", "orderId");
if (orderValue == null) {
throw GaoAiOperationException.clarification("请补充履约单 ID,或订单号加履约请求号",
List.of("fulfillmentId"));
}
GaoSalesOrder order = order(storeId, node);
List<GaoOrderFulfillment> list = fulfillmentService.listBySalesOrderId(order.getId());
String status = text(node, "status");
List<GaoOrderFulfillment> matches = list.stream()
.filter(item -> requestNo == null || requestNo.equals(item.getRequestNo()))
.filter(item -> status == null || status.equalsIgnoreCase(String.valueOf(item.getStatus())))
.toList();
if (matches.size() == 1) {
return matches.getFirst();
}
if (matches.size() > 1) {
throw GaoAiOperationException.candidates("匹配到多张履约单,请选择请求号",
matches.stream().map(item -> brief("requestNo", item.getRequestNo(),
"status", item.getStatus().name(), "deliveredAt", dateTime(item.getDeliveredAt()))).toList());
}
throw GaoAiOperationException.candidates("未找到履约单", list.stream()
.limit(10)
.map(item -> brief("requestNo", item.getRequestNo(), "status", item.getStatus().name(),
"deliveredAt", dateTime(item.getDeliveredAt())))
.toList());
}
/// 解析资金流水
///
/// 支持内部 ID、业务请求号,或订单号加金额/操作类型定位,避免把内部 ID 暴露给模型。
///
/// @param storeId 门店 ID
/// @param node 参数
/// @return 资金流水
public GaoFundRecord fundRecord(String storeId, JsonNode node) {
String id = text(node, "fundRecordId", "fundId");
if (id != null) {
GaoFundRecord record = fundRecordService.get(id);
if (record == null) {
throw new GaoAiOperationException("VALIDATION_FAILED", "未找到资金流水");
}
requireStore(storeId, record.getStoreId(), "资金流水不属于当前门店");
return record;
}
String requestNo = text(node, "fundRequestNo", "fundNo");
if (requestNo != null) {
GaoFundRecord record = fundRecordService.getByRequestNo(storeId, requestNo);
if (record == null) {
throw new GaoAiOperationException("VALIDATION_FAILED", "未找到资金流水");
}
return record;
}
String orderValue = text(node, "orderNo", "salesOrderId", "orderId");
if (orderValue == null) {
throw GaoAiOperationException.clarification("请补充资金流水请求号或订单号",
List.of("fundRequestNo"));
}
GaoSalesOrder order = order(storeId, node);
Long amount = optionalLong(node, "amount");
String operationType = text(node, "operationType", "fundOperationType");
String status = text(node, "fundStatus", "status");
List<GaoFundRecord> records = order.getFundRecordList() == null ? List.of() : order.getFundRecordList();
List<GaoFundRecord> matches = records.stream()
.filter(item -> amount == null || amount.equals(item.getAmount()))
.filter(item -> operationType == null || operationType.equalsIgnoreCase(String.valueOf(item.getOperationType())))
.filter(item -> status == null || status.equalsIgnoreCase(String.valueOf(item.getStatus())))
.toList();
if (matches.size() == 1) {
return matches.getFirst();
}
if (matches.size() > 1) {
throw GaoAiOperationException.candidates("匹配到多笔资金流水,请选择请求号",
matches.stream().map(this::fundBrief).toList());
}
throw GaoAiOperationException.candidates("未找到资金流水", records.stream().map(this::fundBrief).toList());
}
/// 校验门店一致
///
/// @param expected 期望门店
/// @param actual 实际门店
/// @param message 错误消息
public void requireStore(String expected, String actual, String message) {
if (expected == null || !expected.equals(actual)) {
throw new GaoAiOperationException("STORE_SCOPE_DENIED", message);
}
}
/// 计算行金额
///
/// @param unitPrice 单价,分
/// @param quantity 数量
/// @return 行金额,分
public long lineAmount(long unitPrice, BigDecimal quantity) {
try {
return BigDecimal.valueOf(unitPrice).multiply(quantity).setScale(0, RoundingMode.UNNECESSARY).longValueExact();
} catch (ArithmeticException e) {
throw new GaoAiOperationException("VALIDATION_FAILED", "数量与单价无法得到整数分金额");
}
}
/// 判断文本包含关系
///
/// @param source 源文本
/// @param keyword 关键词
/// @return true 为匹配
public boolean contains(String source, String keyword) {
if (source == null || keyword == null) {
return false;
}
return source.toLowerCase(Locale.ROOT).contains(keyword.toLowerCase(Locale.ROOT));
}
private GaoProductSkuUnit selectUnit(List<GaoProductSkuUnit> units, String unitId, String unitKeyword, boolean purchase) {
List<GaoProductSkuUnit> available = units.stream().filter(unit -> availableUnit(unit, purchase)).toList();
if (unitId != null) {
return available.stream().filter(unit -> unitId.equals(unit.getId())).findFirst()
.orElseThrow(() -> new GaoAiOperationException("VALIDATION_FAILED", "SKU 单位不存在或不可用"));
}
if (unitKeyword != null) {
List<GaoProductSkuUnit> matches = available.stream().filter(unit -> contains(unit.getName(), unitKeyword)).toList();
if (matches.size() == 1) {
return matches.getFirst();
}
if (matches.size() > 1) {
throw GaoAiOperationException.candidates("匹配到多个单位,请选择单位",
matches.stream().map(unit -> brief("id", unit.getId(), "name", unit.getName())).toList());
}
throw new GaoAiOperationException("VALIDATION_FAILED", "SKU 单位不存在或不可用");
}
if (available.size() == 1) {
return available.getFirst();
}
throw GaoAiOperationException.candidates("请选择 SKU 单位",
available.stream().map(unit -> brief("id", unit.getId(), "name", unit.getName(),
"salePrice", money(unit.getSalePrice()))).toList());
}
private boolean availableUnit(GaoProductSkuUnit unit, boolean purchase) {
return unit != null && (purchase ? Boolean.TRUE.equals(unit.getAllowPurchase()) : Boolean.TRUE.equals(unit.getAllowSale()));
}
private boolean matchesSku(GaoProductSku sku, String keyword) {
return contains(sku.getName(), keyword) || contains(sku.getCode(), keyword) || contains(sku.getBarcode(), keyword);
}
private boolean matchesUnit(GaoProductSkuUnit unit, String keyword) {
return keyword == null || contains(unit.getName(), keyword) || keyword.equals(unit.getId());
}
private boolean isIdLike(String value) {
return value != null && (value.matches("[0-9a-fA-F]{32}") || value.matches("[0-9a-fA-F-]{36}"));
}
private List<GaoProduct> safeProductList(PageResult<GaoProduct> result) {
return result == null || result.getList() == null ? List.of() : result.getList();
}
private Map<String, Object> fundBrief(GaoFundRecord record) {
Map<String, Object> result = new LinkedHashMap<>();
result.put("requestNo", record.getRequestNo());
result.put("amount", money(record.getAmount()));
result.put("operationType", record.getOperationType());
result.put("status", record.getStatus());
result.put("occurredAt", dateTime(record.getOccurredAt()));
return result;
}
private Map<String, Object> skuBrief(GaoProductSkuUnitSelection selection) {
Map<String, Object> result = new LinkedHashMap<>();
result.put("productName", selection.getProduct().getName());
result.put("skuId", selection.getSku().getId());
result.put("skuName", selection.getSku().getName());
result.put("skuCode", selection.getSku().getCode());
result.put("unitId", selection.getUnit().getId());
result.put("unitName", selection.getUnit().getName());
result.put("salePrice", money(selection.getUnit().getSalePrice()));
return result;
}
/// 构造允许 null 值的候选摘要
///
/// @param keyValues 键值对
/// @return 有序 Map
public Map<String, Object> brief(Object... keyValues) {
Map<String, Object> result = new LinkedHashMap<>();
for (int index = 0; index + 1 < keyValues.length; index += 2) {
result.put(String.valueOf(keyValues[index]), keyValues[index + 1]);
}
return result;
}
}
@@ -0,0 +1,154 @@
package com.imyeyu.api.modules.gao.ai.operation;
import lombok.Data;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
/// GAO 智能体待确认操作
///
/// 该对象只保存在服务端 Redis,`confirmationToken` 本身不落库,
/// 只保存其 SHA-256 摘要。
///
/// @author Codex
/// @since 2026-11-23
@Data
public class GaoAiPendingOperation {
/// 待确认操作状态
public enum Status {
/// 待确认
PENDING,
/// 提交中
COMMITTING,
/// 已成功
SUCCEEDED,
/// 最终失败
FAILED,
/// 已取消
CANCELLED,
/// 已过期
EXPIRED,
/// 已被新的待确认操作替代
SUPERSEDED
}
/// 公开操作 ID,前端卡片使用
private String operationId;
/// 确认 token 的 SHA-256 摘要
private String tokenHash;
/// 操作代码
private String operation;
/// 操作标题
private String title;
/// 风险级别
private String riskLevel;
/// 结果实体类型
private String entityType;
/// 用户 ID
private String userId;
/// 门店 ID
private String storeId;
/// Dify 会话 ID
private String conversationId;
/// 产生该操作的 AI 会话 ID
private String sourceSessionId;
/// 后端生成的幂等请求号
private String requestNo;
/// 标准化后的业务参数 JSON
private String argumentsJson;
/// 附件 token 列表
private List<String> attachmentTokens = new ArrayList<>();
/// 预览结构
private Map<String, Object> preview = new LinkedHashMap<>();
/// 预览文本
private String previewText;
/// 风险影响说明
private String impactText;
/// 精确确认短语
private String requiredPhrase;
/// 是否必须填写原因
private boolean reasonRequired;
/// 当前状态
private Status status = Status.PENDING;
/// 创建时间
private long createdAt;
/// 更新时间
private long updatedAt;
/// 过期时间
private long expiresAt;
/// 提交次数
private int attemptCount;
/// 提交原因
private String commitReason;
/// 最近一次错误码
private String lastErrorCode;
/// 最近一次错误消息
private String lastErrorMessage;
/// 成功结果实体 ID
private String resultEntityId;
/// 成功结果实体单号
private String resultEntityNo;
/// 成功结果文本
private String resultText;
/// 成功时间
private long committedAt;
/// 取消时间
private long cancelledAt;
/// 判断是否仍可确认
///
/// @param now 当前时间
/// @return true 为可确认
public boolean confirmable(long now) {
return status == Status.PENDING && now < expiresAt;
}
/// 判断是否属于指定用户和门店
///
/// @param userId 用户 ID
/// @param storeId 门店 ID
/// @return true 为匹配
public boolean belongsTo(String userId, String storeId) {
return userId != null && userId.equals(this.userId) && storeId != null && storeId.equals(this.storeId);
}
}
@@ -0,0 +1,79 @@
package com.imyeyu.api.modules.gao.ai.operation;
import java.util.List;
/// GAO 智能体待确认操作服务
///
/// @author Codex
/// @since 2026-11-23
public interface GaoAiPendingOperationService {
/// 创建待确认操作
///
/// @param context 执行上下文
/// @param definition 操作定义
/// @param requestNo 后端生成的幂等请求号
/// @param argumentsJson 标准化业务参数
/// @param attachmentTokens 附件凭证
/// @param prepared 准备结果
/// @return 待确认操作,包含原始 token 的创建结果
Created create(GaoAiOperationContext context, GaoAiOperationDefinition definition, String requestNo,
String argumentsJson, List<String> attachmentTokens, GaoAiPreparedOperation prepared);
/// 查询用户和门店当前活跃的待确认操作
///
/// @param userId 用户 ID
/// @param storeId 门店 ID
/// @param conversationId Dify 会话 ID,可为空
/// @return 待确认操作,无则为 null
GaoAiPendingOperation findActive(String userId, String storeId, String conversationId);
/// 按来源 AI 会话查询待确认操作
///
/// @param sourceSessionId 来源 AI 会话 ID
/// @return 待确认操作,无则为 null
GaoAiPendingOperation findActiveBySourceSession(String sourceSessionId);
/// 按确认 token 获取待确认操作
///
/// @param token 确认 token
/// @return 待确认操作
GaoAiPendingOperation requireByToken(String token);
/// 按公开操作 ID 获取待确认操作
///
/// @param operationId 公开操作 ID
/// @return 待确认操作
GaoAiPendingOperation requireByOperationId(String operationId);
/// 绑定 Dify 会话 ID
///
/// @param pending 待确认操作
/// @param conversationId Dify 会话 ID
void bindConversation(GaoAiPendingOperation pending, String conversationId);
/// 为下一轮文本确认签发新的 token
///
/// 只更新服务端摘要,旧 token 立即失效。
///
/// @param pending 待确认操作
/// @return 新的原始 token
String issueToken(GaoAiPendingOperation pending);
/// 保存待确认操作
///
/// @param pending 待确认操作
void save(GaoAiPendingOperation pending);
/// 清理当前活跃索引
///
/// @param pending 待确认操作
void clearActive(GaoAiPendingOperation pending);
/// 创建结果
///
/// @param pending 待确认操作
/// @param token 原始确认 token,只在创建时返回一次
record Created(GaoAiPendingOperation pending, String token) {
}
}
@@ -0,0 +1,310 @@
package com.imyeyu.api.modules.gao.ai.operation;
import com.imyeyu.api.modules.gao.ai.config.GaoAiProperties;
import com.imyeyu.api.modules.gao.ai.operation.GaoAiOperationDefinition.RiskLevel;
import com.imyeyu.spring.util.Redis;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.util.Base64;
import java.util.List;
/// GAO 智能体待确认操作服务实现
///
/// @author Codex
/// @since 2026-11-23
@Service
@RequiredArgsConstructor
public class GaoAiPendingOperationServiceImplement implements GaoAiPendingOperationService {
private static final String TOKEN_PREFIX = "GAO:AI:OP:TOKEN:";
private static final String ID_PREFIX = "GAO:AI:OP:ID:";
private static final String ACTIVE_PREFIX = "GAO:AI:OP:ACTIVE:";
private static final String SESSION_PREFIX = "GAO:AI:OP:SESSION:";
private static final String LOCK_PREFIX = "GAO:AI:OP:LOCK:";
private final GaoAiProperties properties;
// @Qualifier("redisGaoAiOperation")
private Redis<String, GaoAiPendingOperation> redis;
// @Qualifier("redisGaoAiOperationIndex")
private Redis<String, String> indexRedis;
// @Qualifier("redisLocker")
private Redis<String, Integer> locker;
private final SecureRandom secureRandom = new SecureRandom();
@Override
public Created create(GaoAiOperationContext context, GaoAiOperationDefinition definition, String requestNo,
String argumentsJson, List<String> attachmentTokens, GaoAiPreparedOperation prepared) {
String lockKey = LOCK_PREFIX + context.getUserId() + ":" + context.getStoreId();
if (!locker.lock(lockKey, 1, 5_000L)) {
throw new GaoAiOperationException("CONFIRMATION_IN_PROGRESS", "操作正在处理,请稍后重试", true);
}
try {
supersedeActive(context.getUserId(), context.getStoreId());
long now = System.currentTimeMillis();
long ttlMs = Math.max(60_000L, properties.getConfirmationTtlSeconds() * 1000L);
String token = newToken();
GaoAiPendingOperation pending = new GaoAiPendingOperation();
pending.setOperationId(newOperationId());
pending.setTokenHash(hash(token));
pending.setOperation(definition.code());
pending.setTitle(definition.title());
RiskLevel riskLevel = prepared.getRiskLevel() == null ? definition.getRiskLevel() : prepared.getRiskLevel();
pending.setRiskLevel(riskLevel.name());
pending.setEntityType(definition.entityType());
pending.setUserId(context.getUserId());
pending.setStoreId(context.getStoreId());
pending.setConversationId(blankToNull(context.getConversationId()));
pending.setSourceSessionId(context.getSession() == null ? null : context.getSession().getSessionId());
pending.setRequestNo(requestNo);
pending.setArgumentsJson(argumentsJson);
pending.setAttachmentTokens(attachmentTokens == null ? List.of() : List.copyOf(attachmentTokens));
pending.setPreview(prepared.getPreview());
pending.setPreviewText(prepared.getPreviewText());
pending.setImpactText(prepared.getImpactText());
pending.setRequiredPhrase(prepared.getRequiredPhrase());
pending.setReasonRequired(prepared.isReasonRequired() || definition.isReasonRequired());
pending.setStatus(GaoAiPendingOperation.Status.PENDING);
pending.setCreatedAt(now);
pending.setUpdatedAt(now);
pending.setExpiresAt(now + ttlMs);
save(pending);
return new Created(pending, token);
} finally {
locker.releaseLock(lockKey);
}
}
@Override
public GaoAiPendingOperation findActive(String userId, String storeId, String conversationId) {
if (isBlank(userId) || isBlank(storeId)) {
return null;
}
String operationId = indexRedis.get(activeKey(userId, storeId));
if (isBlank(operationId)) {
return null;
}
GaoAiPendingOperation pending = redis.get(idKey(operationId));
if (pending == null) {
indexRedis.destroy(activeKey(userId, storeId));
return null;
}
if (!pending.belongsTo(userId, storeId)) {
indexRedis.destroy(activeKey(userId, storeId));
return null;
}
if (pending.getStatus() == GaoAiPendingOperation.Status.PENDING && pending.getExpiresAt() <= System.currentTimeMillis()) {
pending.setStatus(GaoAiPendingOperation.Status.EXPIRED);
save(pending);
return null;
}
if (pending.getStatus() != GaoAiPendingOperation.Status.PENDING) {
clearActive(pending);
return null;
}
if (!isBlank(conversationId) && !isBlank(pending.getConversationId())
&& !conversationId.equals(pending.getConversationId())) {
return null;
}
return pending;
}
@Override
public GaoAiPendingOperation findActiveBySourceSession(String sourceSessionId) {
if (isBlank(sourceSessionId)) {
return null;
}
String operationId = indexRedis.get(sessionKey(sourceSessionId));
if (isBlank(operationId)) {
return null;
}
GaoAiPendingOperation pending = redis.get(idKey(operationId));
if (pending == null || pending.getStatus() != GaoAiPendingOperation.Status.PENDING
|| pending.getExpiresAt() <= System.currentTimeMillis()) {
indexRedis.destroy(sessionKey(sourceSessionId));
return null;
}
return pending;
}
@Override
public GaoAiPendingOperation requireByToken(String token) {
if (isBlank(token)) {
throw new GaoAiOperationException("CONFIRMATION_REQUIRED", "缺少确认凭证");
}
String tokenHash = hash(token.trim());
GaoAiPendingOperation pending = redis.get(tokenKey(tokenHash));
if (pending == null || !tokenHash.equals(pending.getTokenHash())) {
throw new GaoAiOperationException("CONFIRMATION_REQUIRED", "确认凭证无效或已过期");
}
return pending;
}
@Override
public GaoAiPendingOperation requireByOperationId(String operationId) {
if (isBlank(operationId)) {
throw new GaoAiOperationException("CONFIRMATION_REQUIRED", "缺少操作 ID");
}
GaoAiPendingOperation pending = redis.get(idKey(operationId.trim()));
if (pending == null) {
throw new GaoAiOperationException("CONFIRMATION_REQUIRED", "操作不存在或已过期");
}
return pending;
}
@Override
public void bindConversation(GaoAiPendingOperation pending, String conversationId) {
if (pending == null || isBlank(conversationId)) {
return;
}
if (isBlank(pending.getConversationId())) {
pending.setConversationId(conversationId.trim());
pending.setUpdatedAt(System.currentTimeMillis());
save(pending);
}
}
@Override
public String issueToken(GaoAiPendingOperation pending) {
if (pending == null) {
throw new GaoAiOperationException("CONFIRMATION_REQUIRED", "没有可确认的操作");
}
String lockKey = LOCK_PREFIX + "TOKEN:" + pending.getOperationId();
if (!locker.lock(lockKey, 1, 5_000L)) {
throw new GaoAiOperationException("CONFIRMATION_IN_PROGRESS", "操作正在处理,请稍后重试", true);
}
try {
GaoAiPendingOperation current = redis.get(idKey(pending.getOperationId()));
if (current == null || current.getStatus() != GaoAiPendingOperation.Status.PENDING) {
throw new GaoAiOperationException("CONFIRMATION_REQUIRED", "没有可确认的操作");
}
if (current.getExpiresAt() <= System.currentTimeMillis()) {
throw new GaoAiOperationException("CONFIRMATION_EXPIRED", "确认已过期,请重新发起操作");
}
String token = newToken();
current.setTokenHash(hash(token));
current.setUpdatedAt(System.currentTimeMillis());
save(current);
pending.setTokenHash(current.getTokenHash());
pending.setUpdatedAt(current.getUpdatedAt());
return token;
} finally {
locker.releaseLock(lockKey);
}
}
@Override
public void save(GaoAiPendingOperation pending) {
if (pending == null || isBlank(pending.getOperationId())) {
return;
}
long now = System.currentTimeMillis();
pending.setUpdatedAt(now);
long remain = Math.max(1_000L, pending.getExpiresAt() - now);
long ttlMs = remain + Math.max(0L, properties.getResultTtlSeconds() * 1000L);
redis.set(idKey(pending.getOperationId()), pending, ttlMs);
if (!isBlank(pending.getTokenHash())) {
redis.set(tokenKey(pending.getTokenHash()), pending, ttlMs);
}
if (pending.getStatus() == GaoAiPendingOperation.Status.PENDING) {
indexRedis.set(activeKey(pending.getUserId(), pending.getStoreId()), pending.getOperationId(), ttlMs);
if (!isBlank(pending.getSourceSessionId())) {
indexRedis.set(sessionKey(pending.getSourceSessionId()), pending.getOperationId(), ttlMs);
}
} else {
clearActive(pending);
}
}
@Override
public void clearActive(GaoAiPendingOperation pending) {
if (pending == null) {
return;
}
if (!isBlank(pending.getUserId()) && !isBlank(pending.getStoreId())) {
indexRedis.destroy(activeKey(pending.getUserId(), pending.getStoreId()));
}
if (!isBlank(pending.getSourceSessionId())) {
indexRedis.destroy(sessionKey(pending.getSourceSessionId()));
}
}
private void supersedeActive(String userId, String storeId) {
String operationId = indexRedis.get(activeKey(userId, storeId));
if (isBlank(operationId)) {
return;
}
GaoAiPendingOperation old = redis.get(idKey(operationId));
if (old == null) {
indexRedis.destroy(activeKey(userId, storeId));
return;
}
if (old.getStatus() == GaoAiPendingOperation.Status.COMMITTING) {
throw new GaoAiOperationException("CONFIRMATION_IN_PROGRESS", "上一个操作正在提交,请稍后重试", true);
}
if (old.getStatus() == GaoAiPendingOperation.Status.PENDING) {
old.setStatus(GaoAiPendingOperation.Status.SUPERSEDED);
save(old);
} else {
clearActive(old);
}
}
private String newToken() {
byte[] bytes = new byte[32];
secureRandom.nextBytes(bytes);
return "op_" + Base64.getUrlEncoder().withoutPadding().encodeToString(bytes);
}
private String newOperationId() {
byte[] bytes = new byte[18];
secureRandom.nextBytes(bytes);
return "pub_" + Base64.getUrlEncoder().withoutPadding().encodeToString(bytes);
}
private String hash(String value) {
try {
byte[] bytes = MessageDigest.getInstance("SHA-256").digest(value.getBytes(StandardCharsets.UTF_8));
StringBuilder result = new StringBuilder(bytes.length * 2);
for (byte item : bytes) {
result.append("%02x".formatted(item & 0xff));
}
return result.toString();
} catch (NoSuchAlgorithmException e) {
throw new IllegalStateException("当前 JDK 不支持 SHA-256", e);
}
}
private String tokenKey(String hash) {
return TOKEN_PREFIX + hash;
}
private String idKey(String operationId) {
return ID_PREFIX + operationId;
}
private String activeKey(String userId, String storeId) {
return ACTIVE_PREFIX + userId + ":" + storeId;
}
private String sessionKey(String sessionId) {
return SESSION_PREFIX + sessionId;
}
private String blankToNull(String value) {
return isBlank(value) ? null : value.trim();
}
private boolean isBlank(String value) {
return value == null || value.isBlank();
}
}
@@ -0,0 +1,50 @@
package com.imyeyu.api.modules.gao.ai.operation;
import com.imyeyu.api.modules.gao.ai.operation.GaoAiOperationDefinition.RiskLevel;
import lombok.Data;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
/// GAO 智能体写操作准备结果
///
/// @author Codex
/// @since 2026-11-23
@Data
public class GaoAiPreparedOperation {
/// 标准 JSON 参数,commit 时直接读取,不再接受模型输入
private String argumentsJson;
/// 预览结构
private Map<String, Object> preview = new LinkedHashMap<>();
/// 预览文本
private String previewText;
/// 风险影响说明
private String impactText;
/// 风险级别,默认取操作定义
private RiskLevel riskLevel;
/// 精确确认短语,破坏性/敏感操作为必填
private String requiredPhrase;
/// 是否必须填写原因
private boolean reasonRequired;
/// 警告
private List<String> warnings = new ArrayList<>();
/// 缺失字段
private List<String> missingFields = new ArrayList<>();
/// 候选列表,存在歧义时返回
private List<Object> candidates = new ArrayList<>();
/// 实体标题,用于卡片
private String title;
}
@@ -0,0 +1,62 @@
package com.imyeyu.api.modules.gao.ai.operation;
import com.imyeyu.api.modules.gao.bean.GaoPermissionCode;
import com.imyeyu.api.modules.user.service.PermissionChecker;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import java.util.Set;
/// GAO 智能体写工具授权器
///
/// 权限实时按会话用户查询,prepare 和 commit 都会校验。
///
/// @author Codex
/// @since 2026-11-23
@Service
@RequiredArgsConstructor
public class GaoAiToolAuthorizer {
private final PermissionChecker permissionChecker;
/// 校验操作定义要求的全部权限
///
/// @param userId 用户 ID
/// @param definition 操作定义
public void check(String userId, GaoAiOperationDefinition definition) {
if (definition == null) {
throw new GaoAiOperationException("FEATURE_DISABLED", "该操作未开放");
}
for (GaoPermissionCode code : definition.getPermissions()) {
checkCode(userId, code);
}
}
/// 校验单个权限
///
/// @param userId 用户 ID
/// @param code 权限码
public void checkCode(String userId, GaoPermissionCode code) {
if (!hasCode(userId, code)) {
throw new GaoAiOperationException("PERMISSION_DENIED",
"当前账号缺少权限:%s".formatted(code.getDefaultName()));
}
}
/// 判断是否拥有权限
///
/// @param userId 用户 ID
/// @param code 权限码
/// @return true 为拥有
public boolean hasCode(String userId, GaoPermissionCode code) {
if (userId == null || userId.isBlank() || code == null) {
return false;
}
Set<String> permissionCodes = permissionChecker.codeSet(userId);
return permissionCodes != null && permissionCodes.contains(buildKey(code));
}
private String buildKey(GaoPermissionCode code) {
return code.getModuleCode().name() + ":" + code.getValue();
}
}
@@ -0,0 +1,419 @@
package com.imyeyu.api.modules.gao.ai.operation.handler;
import com.fasterxml.jackson.databind.JsonNode;
import com.imyeyu.api.modules.common.entity.Attachment;
import com.imyeyu.api.modules.gao.ai.operation.GaoAiAttachmentToken;
import com.imyeyu.api.modules.gao.ai.operation.GaoAiCommitResult;
import com.imyeyu.api.modules.gao.ai.operation.GaoAiOperation;
import com.imyeyu.api.modules.gao.ai.operation.GaoAiOperationContext;
import com.imyeyu.api.modules.gao.ai.operation.GaoAiOperationDefinition;
import com.imyeyu.api.modules.gao.ai.operation.GaoAiOperationException;
import com.imyeyu.api.modules.gao.ai.operation.GaoAiOperationHandler;
import com.imyeyu.api.modules.gao.ai.operation.GaoAiOperationSupport;
import com.imyeyu.api.modules.gao.ai.operation.GaoAiPendingOperation;
import com.imyeyu.api.modules.gao.ai.operation.GaoAiPreparedOperation;
import com.imyeyu.api.modules.gao.entity.GaoCustomer;
import com.imyeyu.api.modules.gao.entity.GaoCustomerFollowUpReminder;
import com.imyeyu.api.modules.gao.service.GaoCustomerFollowUpReminderService;
import com.imyeyu.api.modules.gao.service.GaoCustomerService;
import com.imyeyu.api.modules.user.bean.Gender;
import com.imyeyu.api.modules.user.entity.User;
import com.imyeyu.api.modules.user.service.UserService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
/// 客户与客户跟进写操作处理器
///
/// @author Codex
/// @since 2026-11-23
@Component
@RequiredArgsConstructor
public class CustomerOperationHandler implements GaoAiOperationHandler {
private static final ZoneId ZONE = ZoneId.systemDefault();
private static final DateTimeFormatter DATE_TIME = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm");
private final GaoAiOperationSupport support;
private final GaoCustomerService customerService;
private final GaoCustomerFollowUpReminderService followUpService;
private final UserService userService;
@Override
public Set<GaoAiOperation> supports() {
return Set.of(GaoAiOperation.CUSTOMER_CREATE, GaoAiOperation.CUSTOMER_UPDATE,
GaoAiOperation.FOLLOW_UP_CREATE, GaoAiOperation.FOLLOW_UP_UPDATE, GaoAiOperation.FOLLOW_UP_COMPLETE);
}
@Override
public GaoAiPreparedOperation prepare(GaoAiOperationContext context, GaoAiOperationDefinition definition,
JsonNode arguments, List<GaoAiAttachmentToken> attachments) {
return switch (definition.getOperation()) {
case CUSTOMER_CREATE -> prepareCustomerCreate(arguments, attachments);
case CUSTOMER_UPDATE -> prepareCustomerUpdate(context, arguments, attachments);
case FOLLOW_UP_CREATE -> prepareFollowUpCreate(context, arguments, attachments);
case FOLLOW_UP_UPDATE -> prepareFollowUpUpdate(context, arguments, attachments);
case FOLLOW_UP_COMPLETE -> prepareFollowUpComplete(context, arguments);
default -> throw new GaoAiOperationException("FEATURE_DISABLED", "不支持的操作");
};
}
@Override
public GaoAiCommitResult commit(GaoAiOperationContext context, GaoAiPendingOperation pending,
JsonNode arguments, List<Attachment> attachments) {
return switch (GaoAiOperation.valueOf(pending.getOperation())) {
case CUSTOMER_CREATE -> commitCustomerCreate(context, arguments, attachments);
case CUSTOMER_UPDATE -> commitCustomerUpdate(arguments, attachments);
case FOLLOW_UP_CREATE -> commitFollowUpCreate(arguments, attachments);
case FOLLOW_UP_UPDATE -> commitFollowUpUpdate(arguments, attachments);
case FOLLOW_UP_COMPLETE -> commitFollowUpComplete(arguments);
default -> throw new GaoAiOperationException("FEATURE_DISABLED", "不支持的操作");
};
}
private GaoAiPreparedOperation prepareCustomerCreate(JsonNode arguments, List<GaoAiAttachmentToken> attachments) {
String name = support.requiredText(arguments, "客户姓名", "name", "customerName");
com.fasterxml.jackson.databind.node.ObjectNode normalized = support.normalizable(arguments);
normalized.put("name", name);
Map<String, Object> preview = new LinkedHashMap<>();
preview.put("name", name);
preview.put("gender", support.text(arguments, "gender"));
preview.put("birthdate", support.text(arguments, "birthdate"));
preview.put("telephone", support.maskPhone(support.text(arguments, "telephone")));
preview.put("address", support.text(arguments, "address"));
preview.put("remark", support.text(arguments, "remark"));
preview.put("attachmentCount", attachments.size());
GaoAiPreparedOperation result = new GaoAiPreparedOperation();
result.setArgumentsJson(normalized.toString());
result.setPreview(preview);
result.setTitle("新建客户");
result.setPreviewText("""
### 待确认:新建客户
姓名:%s
性别:%s
出生日期:%s
电话:%s
地址:%s
备注:%s
凭证:%d 张
请回复“确认”执行,回复“取消”放弃。
""".formatted(name, blank(support.text(arguments, "gender")), blank(support.text(arguments, "birthdate")),
blank(support.maskPhone(support.text(arguments, "telephone"))), blank(support.text(arguments, "address")),
blank(support.text(arguments, "remark")), attachments.size()));
return result;
}
private GaoAiPreparedOperation prepareCustomerUpdate(GaoAiOperationContext context, JsonNode arguments,
List<GaoAiAttachmentToken> attachments) {
GaoCustomer customer = support.customer(context.getStoreId(), arguments);
com.fasterxml.jackson.databind.node.ObjectNode normalized = support.normalizable(arguments);
normalized.put("customerId", customer.getId());
Map<String, Object> preview = new LinkedHashMap<>();
preview.put("customer", support.customerBrief(customer));
preview.put("changes", changeSummary(arguments, "name", "gender", "birthdate", "telephone", "address", "remark", "disease"));
preview.put("attachmentCount", attachments.size());
GaoAiPreparedOperation result = new GaoAiPreparedOperation();
result.setArgumentsJson(normalized.toString());
result.setPreview(preview);
result.setTitle("修改客户资料");
result.setPreviewText("""
### 待确认:修改客户资料
客户:%s(%s)
修改项:%s
凭证:%d 张
请回复“确认”执行,回复“取消”放弃。
""".formatted(customer.getName(), blank(customer.getCode()), preview.get("changes"), attachments.size()));
return result;
}
private GaoAiPreparedOperation prepareFollowUpCreate(GaoAiOperationContext context, JsonNode arguments,
List<GaoAiAttachmentToken> attachments) {
GaoCustomer customer = support.customer(context.getStoreId(), arguments);
User responsible = responsibleUser(context, arguments);
String content = support.requiredText(arguments, "跟进内容", "content", "remark");
long remindAt = requiredRemindAt(arguments);
com.fasterxml.jackson.databind.node.ObjectNode normalized = support.normalizable(arguments);
normalized.put("customerId", customer.getId());
normalized.put("responsibleUserId", responsible.getId());
normalized.put("content", content);
normalized.put("remindAt", remindAt);
Map<String, Object> preview = new LinkedHashMap<>();
preview.put("customer", support.customerBrief(customer));
preview.put("responsibleUser", responsible.getName());
preview.put("content", content);
preview.put("remindAt", support.dateTime(remindAt));
preview.put("internalNotifyEnabled", support.optionalBoolean(arguments, "internalNotifyEnabled"));
preview.put("smsNotifyEnabled", support.optionalBoolean(arguments, "smsNotifyEnabled"));
GaoAiPreparedOperation result = new GaoAiPreparedOperation();
result.setArgumentsJson(normalized.toString());
result.setPreview(preview);
result.setTitle("新建客户跟进提醒");
result.setPreviewText("""
### 待确认:新建客户跟进提醒
客户:%s(%s)
负责人:%s
内容:%s
提醒时间:%s
请回复“确认”执行,回复“取消”放弃。
""".formatted(customer.getName(), blank(customer.getCode()), responsible.getName(), content,
support.dateTime(remindAt)));
return result;
}
private GaoAiPreparedOperation prepareFollowUpUpdate(GaoAiOperationContext context, JsonNode arguments,
List<GaoAiAttachmentToken> attachments) {
GaoCustomerFollowUpReminder reminder = support.followUp(context.getStoreId(), arguments);
com.fasterxml.jackson.databind.node.ObjectNode normalized = support.normalizable(arguments);
normalized.put("reminderId", reminder.getId());
Long remindAt = support.optionalLong(arguments, "remindAt");
if (remindAt == null && support.text(arguments, "remindAtText", "remindTime") != null) {
remindAt = requiredRemindAt(arguments);
normalized.put("remindAt", remindAt);
}
Map<String, Object> preview = new LinkedHashMap<>();
preview.put("reminderId", reminder.getId());
preview.put("customerId", reminder.getCustomerId());
preview.put("content", support.text(arguments, "content", "remark") == null ? reminder.getContent()
: support.text(arguments, "content", "remark"));
preview.put("remindAt", support.dateTime(remindAt == null ? reminder.getRemindAt() : remindAt));
preview.put("attachmentCount", attachments.size());
GaoAiPreparedOperation result = new GaoAiPreparedOperation();
result.setArgumentsJson(normalized.toString());
result.setPreview(preview);
result.setTitle("修改客户跟进提醒");
result.setPreviewText("""
### 待确认:修改客户跟进提醒
提醒 ID:%s
客户 ID:%s
内容:%s
提醒时间:%s
请回复“确认”执行,回复“取消”放弃。
""".formatted(reminder.getId(), reminder.getCustomerId(), preview.get("content"), preview.get("remindAt")));
return result;
}
private GaoAiPreparedOperation prepareFollowUpComplete(GaoAiOperationContext context, JsonNode arguments) {
GaoCustomerFollowUpReminder reminder = support.followUp(context.getStoreId(), arguments);
com.fasterxml.jackson.databind.node.ObjectNode normalized = support.normalizable(arguments);
normalized.put("reminderId", reminder.getId());
Map<String, Object> preview = new LinkedHashMap<>();
preview.put("reminderId", reminder.getId());
preview.put("customerId", reminder.getCustomerId());
preview.put("content", reminder.getContent());
GaoAiPreparedOperation result = new GaoAiPreparedOperation();
result.setArgumentsJson(normalized.toString());
result.setPreview(preview);
result.setTitle("完成客户跟进提醒");
result.setPreviewText("""
### 待确认:完成客户跟进提醒
提醒 ID:%s
客户 ID:%s
内容:%s
请回复“确认”执行,回复“取消”放弃。
""".formatted(reminder.getId(), reminder.getCustomerId(), reminder.getContent()));
return result;
}
private GaoAiCommitResult commitCustomerCreate(GaoAiOperationContext context, JsonNode arguments,
List<Attachment> attachments) {
GaoCustomer customer = new GaoCustomer();
customer.setName(support.requiredText(arguments, "name", "customerName"));
customer.setCode(support.text(arguments, "code"));
customer.setGender(gender(support.text(arguments, "gender")));
customer.setBirthdate(birthdate(support.text(arguments, "birthdate")));
customer.setTelephone(support.text(arguments, "telephone"));
customer.setAddress(support.text(arguments, "address"));
customer.setRemark(support.text(arguments, "remark"));
customer.setDisease(support.text(arguments, "disease"));
customer.setAttachmentList(attachments);
// storeId 只来自已认证会话,模型参数不包含门店
customer.setStoreId(context.getStoreId());
customerService.create(customer);
return GaoAiCommitResult.success(GaoAiOperation.CUSTOMER_CREATE.name(), "CUSTOMER", customer.getId(),
customer.getCode(), "已创建客户 %s。".formatted(customer.getName()));
}
private GaoAiCommitResult commitCustomerUpdate(JsonNode arguments, List<Attachment> attachments) {
GaoCustomer existing = customerService.get(support.requiredText(arguments, "customerId", "id"));
if (existing == null) {
throw new GaoAiOperationException("STALE_PREVIEW", "客户已不存在,请重新发起");
}
GaoCustomer customer = new GaoCustomer();
customer.setId(existing.getId());
customer.setStoreId(existing.getStoreId());
customer.setName(defaultText(support.text(arguments, "name", "customerName"), existing.getName()));
customer.setCode(defaultText(support.text(arguments, "code"), existing.getCode()));
customer.setGender(support.text(arguments, "gender") == null ? existing.getGender() : gender(support.text(arguments, "gender")));
customer.setBirthdate(support.text(arguments, "birthdate") == null ? existing.getBirthdate() : birthdate(support.text(arguments, "birthdate")));
customer.setBirthdateCalendar(existing.getBirthdateCalendar());
customer.setTelephone(defaultText(support.text(arguments, "telephone"), existing.getTelephone()));
customer.setAddress(defaultText(support.text(arguments, "address"), existing.getAddress()));
customer.setRemark(support.text(arguments, "remark"));
customer.setDisease(defaultText(support.text(arguments, "disease"), existing.getDisease()));
customer.setConditioningPart(existing.getConditioningPart());
customer.setIntroducerCustomerId(existing.getIntroducerCustomerId());
if (attachments.isEmpty()) {
customerService.update(customer);
} else {
customer.setAttachmentList(attachments);
customerService.updateWithAttachment(customer);
}
return GaoAiCommitResult.success(GaoAiOperation.CUSTOMER_UPDATE.name(), "CUSTOMER", customer.getId(),
customer.getCode(), "已更新客户 %s 的资料。".formatted(customer.getName()));
}
private GaoAiCommitResult commitFollowUpCreate(JsonNode arguments, List<Attachment> attachments) {
GaoCustomer customer = customerService.get(support.requiredText(arguments, "customerId", "id"));
if (customer == null) {
throw new GaoAiOperationException("STALE_PREVIEW", "客户已不存在,请重新发起");
}
GaoCustomerFollowUpReminder reminder = new GaoCustomerFollowUpReminder();
reminder.setStoreId(customer.getStoreId());
reminder.setCustomerId(customer.getId());
reminder.setResponsibleUserId(support.requiredText(arguments, "responsibleUserId"));
reminder.setContent(support.requiredText(arguments, "content", "remark"));
reminder.setRemindAt(requiredRemindAt(arguments));
reminder.setInternalNotifyEnabled(support.optionalBoolean(arguments, "internalNotifyEnabled"));
reminder.setSmsNotifyEnabled(support.optionalBoolean(arguments, "smsNotifyEnabled"));
reminder.setAttachmentList(attachments);
followUpService.create(reminder);
return GaoAiCommitResult.success(GaoAiOperation.FOLLOW_UP_CREATE.name(), "CUSTOMER_FOLLOW_UP", reminder.getId(),
null, "已创建客户跟进提醒,提醒时间 %s。".formatted(support.dateTime(reminder.getRemindAt())));
}
private GaoAiCommitResult commitFollowUpUpdate(JsonNode arguments, List<Attachment> attachments) {
GaoCustomerFollowUpReminder existing = followUpService.get(support.requiredText(arguments, "reminderId", "id"));
if (existing == null) {
throw new GaoAiOperationException("STALE_PREVIEW", "跟进提醒已不存在,请重新发起");
}
GaoCustomerFollowUpReminder reminder = new GaoCustomerFollowUpReminder();
reminder.setId(existing.getId());
reminder.setStoreId(existing.getStoreId());
reminder.setCustomerId(existing.getCustomerId());
reminder.setResponsibleUserId(defaultText(support.text(arguments, "responsibleUserId"), existing.getResponsibleUserId()));
reminder.setContent(defaultText(support.text(arguments, "content", "remark"), existing.getContent()));
reminder.setRemindAt(support.optionalLong(arguments, "remindAt") == null ? existing.getRemindAt()
: support.optionalLong(arguments, "remindAt"));
reminder.setInternalNotifyEnabled(support.optionalBoolean(arguments, "internalNotifyEnabled") == null
? existing.getInternalNotifyEnabled() : support.optionalBoolean(arguments, "internalNotifyEnabled"));
reminder.setSmsNotifyEnabled(support.optionalBoolean(arguments, "smsNotifyEnabled") == null
? existing.getSmsNotifyEnabled() : support.optionalBoolean(arguments, "smsNotifyEnabled"));
reminder.setAttachmentList(attachments);
followUpService.update(reminder);
return GaoAiCommitResult.success(GaoAiOperation.FOLLOW_UP_UPDATE.name(), "CUSTOMER_FOLLOW_UP", reminder.getId(),
null, "已修改客户跟进提醒。");
}
private GaoAiCommitResult commitFollowUpComplete(JsonNode arguments) {
String reminderId = support.requiredText(arguments, "reminderId", "id");
followUpService.complete(reminderId);
return GaoAiCommitResult.success(GaoAiOperation.FOLLOW_UP_COMPLETE.name(), "CUSTOMER_FOLLOW_UP", reminderId,
null, "已完成客户跟进提醒。");
}
private User responsibleUser(GaoAiOperationContext context, JsonNode arguments) {
String userId = support.text(arguments, "responsibleUserId");
if (userId != null) {
User user = userService.get(userId);
if (user == null) {
throw new GaoAiOperationException("VALIDATION_FAILED", "负责人不存在");
}
return user;
}
String name = support.text(arguments, "responsibleUserName", "responsibleUserKeyword");
if (name != null) {
User user = userService.getByName(name);
if (user == null) {
throw GaoAiOperationException.candidates("未找到负责人,请确认姓名", List.of());
}
return user;
}
User user = userService.get(context.getUserId());
if (user == null) {
throw new GaoAiOperationException("VALIDATION_FAILED", "当前用户不存在");
}
return user;
}
private long requiredRemindAt(JsonNode arguments) {
Long value = support.optionalLong(arguments, "remindAt");
if (value != null) {
return value;
}
String text = support.text(arguments, "remindAtText", "remindTime");
if (text == null) {
throw GaoAiOperationException.clarification("请补充提醒时间", List.of("remindAt"));
}
try {
return LocalDateTime.parse(text, DATE_TIME).atZone(ZONE).toInstant().toEpochMilli();
} catch (RuntimeException e) {
throw new GaoAiOperationException("VALIDATION_FAILED", "提醒时间格式应为 yyyy-MM-dd HH:mm");
}
}
private String changeSummary(JsonNode arguments, String... fields) {
Map<String, Object> changes = new LinkedHashMap<>();
for (String field : fields) {
String value = support.text(arguments, field);
if (value != null) {
changes.put(field, "telephone".equals(field) ? support.maskPhone(value) : value);
}
}
return changes.isEmpty() ? "无" : changes.toString();
}
private Gender gender(String value) {
if (value == null) {
return null;
}
if ("男".equals(value) || "MALE".equalsIgnoreCase(value)) {
return Gender.MALE;
}
if ("女".equals(value) || "FEMALE".equalsIgnoreCase(value)) {
return Gender.FEMALE;
}
throw new GaoAiOperationException("VALIDATION_FAILED", "性别只能是男或女");
}
private LocalDate birthdate(String value) {
if (value == null) {
return null;
}
try {
return LocalDate.parse(value);
} catch (RuntimeException e) {
throw new GaoAiOperationException("VALIDATION_FAILED", "出生日期格式应为 yyyy-MM-dd");
}
}
private String defaultText(String value, String fallback) {
return value == null ? fallback : value;
}
private String blank(String value) {
return value == null ? "-" : value;
}
}
@@ -0,0 +1,911 @@
package com.imyeyu.api.modules.gao.ai.operation.handler;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.imyeyu.api.modules.common.entity.Attachment;
import com.imyeyu.api.modules.common.service.AttachmentService;
import com.imyeyu.api.modules.gao.ai.config.GaoAiProperties;
import com.imyeyu.api.modules.gao.ai.operation.GaoAiAttachmentToken;
import com.imyeyu.api.modules.gao.ai.operation.GaoAiCommitResult;
import com.imyeyu.api.modules.gao.ai.operation.GaoAiOperation;
import com.imyeyu.api.modules.gao.ai.operation.GaoAiOperationContext;
import com.imyeyu.api.modules.gao.ai.operation.GaoAiOperationDefinition;
import com.imyeyu.api.modules.gao.ai.operation.GaoAiOperationDefinition.RiskLevel;
import com.imyeyu.api.modules.gao.ai.operation.GaoAiOperationException;
import com.imyeyu.api.modules.gao.ai.operation.GaoAiOperationHandler;
import com.imyeyu.api.modules.gao.ai.operation.GaoAiOperationSupport;
import com.imyeyu.api.modules.gao.ai.operation.GaoAiPendingOperation;
import com.imyeyu.api.modules.gao.ai.operation.GaoAiPreparedOperation;
import com.imyeyu.api.modules.gao.ai.operation.GaoAiToolAuthorizer;
import com.imyeyu.api.modules.gao.bean.GaoPermissionCode;
import com.imyeyu.api.modules.gao.entity.GaoCustomer;
import com.imyeyu.api.modules.gao.entity.GaoFundRecord;
import com.imyeyu.api.modules.gao.entity.GaoOrderFulfillment;
import com.imyeyu.api.modules.gao.entity.GaoSalesOrder;
import com.imyeyu.api.modules.gao.entity.GaoSalesOrderItem;
import com.imyeyu.api.modules.gao.service.GaoOrderFulfillmentService;
import com.imyeyu.api.modules.gao.service.GaoOrderPaymentService;
import com.imyeyu.api.modules.gao.service.GaoSalesOrderService;
import com.imyeyu.api.modules.gao.vo.order.GaoDirectProductOrderCreateRequest;
import com.imyeyu.api.modules.gao.vo.order.GaoOrderFulfillmentActionRequest;
import com.imyeyu.api.modules.gao.vo.order.GaoOrderFulfillmentCreateRequest;
import com.imyeyu.api.modules.gao.vo.order.GaoOrderFulfillmentItemRequest;
import com.imyeyu.api.modules.gao.vo.order.GaoOrderFulfillmentReturnRequest;
import com.imyeyu.api.modules.gao.vo.order.GaoOrderFulfillmentRevokeRequest;
import com.imyeyu.api.modules.gao.vo.order.GaoOrderPaymentActionRequest;
import com.imyeyu.api.modules.gao.vo.order.GaoOrderPaymentReceiveRequest;
import com.imyeyu.api.modules.gao.vo.order.GaoOrderPaymentRefundRequest;
import com.imyeyu.api.modules.gao.vo.order.GaoOrderPaymentRevokeRequest;
import com.imyeyu.api.modules.gao.vo.salesorder.GaoSalesOrderCancelRequest;
import com.imyeyu.api.modules.gao.vo.salesorder.GaoSalesOrderItemRequest;
import com.imyeyu.api.modules.gao.vo.salesorder.GaoSalesOrderUpdateRequest;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
/// 订单、收款与履约写操作处理器
///
/// @author Codex
/// @since 2026-11-23
@Component
@RequiredArgsConstructor
public class OrderOperationHandler implements GaoAiOperationHandler {
private final GaoAiOperationSupport support;
private final GaoAiProperties properties;
private final GaoAiToolAuthorizer authorizer;
private final GaoSalesOrderService salesOrderService;
private final GaoOrderPaymentService paymentService;
private final GaoOrderFulfillmentService fulfillmentService;
private final AttachmentService attachmentService;
@Override
public Set<GaoAiOperation> supports() {
return Set.of(GaoAiOperation.SALES_ORDER_CREATE, GaoAiOperation.SALES_ORDER_UPDATE,
GaoAiOperation.SALES_ORDER_CANCEL, GaoAiOperation.PAYMENT_RECEIVE,
GaoAiOperation.PAYMENT_RECEIVE_AND_VERIFY, GaoAiOperation.PAYMENT_VERIFY,
GaoAiOperation.PAYMENT_REJECT, GaoAiOperation.PAYMENT_CANCEL, GaoAiOperation.PAYMENT_REFUND,
GaoAiOperation.FUND_REVOKE, GaoAiOperation.FULFILLMENT_CREATE,
GaoAiOperation.FULFILLMENT_CREATE_AND_VERIFY, GaoAiOperation.FULFILLMENT_VERIFY,
GaoAiOperation.FULFILLMENT_REJECT, GaoAiOperation.FULFILLMENT_CANCEL);
}
@Override
public GaoAiPreparedOperation prepare(GaoAiOperationContext context, GaoAiOperationDefinition definition,
JsonNode arguments, List<GaoAiAttachmentToken> attachments) {
return switch (definition.getOperation()) {
case SALES_ORDER_CREATE -> prepareOrderCreate(context, definition, arguments, attachments);
case SALES_ORDER_UPDATE -> prepareOrderUpdate(context, arguments, attachments);
case SALES_ORDER_CANCEL -> prepareOrderCancel(context, definition, arguments, attachments);
case PAYMENT_RECEIVE, PAYMENT_RECEIVE_AND_VERIFY -> preparePaymentReceive(context, definition, arguments, attachments);
case PAYMENT_VERIFY -> preparePaymentVerify(context, arguments);
case PAYMENT_REJECT, PAYMENT_CANCEL -> preparePaymentAction(context, definition, arguments);
case PAYMENT_REFUND -> prepareRefund(context, definition, arguments, attachments);
case FUND_REVOKE -> prepareFundRevoke(context, definition, arguments, attachments);
case FULFILLMENT_CREATE, FULFILLMENT_CREATE_AND_VERIFY -> prepareFulfillmentCreate(context, definition, arguments, attachments);
case FULFILLMENT_VERIFY -> prepareFulfillmentAction(context, definition, arguments);
case FULFILLMENT_REJECT, FULFILLMENT_CANCEL -> prepareFulfillmentAction(context, definition, arguments);
default -> throw new GaoAiOperationException("FEATURE_DISABLED", "不支持的操作");
};
}
@Override
public GaoAiCommitResult commit(GaoAiOperationContext context, GaoAiPendingOperation pending,
JsonNode arguments, List<Attachment> attachments) {
return switch (GaoAiOperation.valueOf(pending.getOperation())) {
case SALES_ORDER_CREATE -> commitOrderCreate(context, pending, arguments, attachments);
case SALES_ORDER_UPDATE -> commitOrderUpdate(arguments, attachments);
case SALES_ORDER_CANCEL -> commitOrderCancel(context, pending, arguments, attachments);
case PAYMENT_RECEIVE -> commitPaymentReceive(context, pending, arguments, attachments, false);
case PAYMENT_RECEIVE_AND_VERIFY -> commitPaymentReceive(context, pending, arguments, attachments, true);
case PAYMENT_VERIFY -> commitPaymentVerify(arguments);
case PAYMENT_REJECT -> commitPaymentAction(arguments, false);
case PAYMENT_CANCEL -> commitPaymentAction(arguments, true);
case PAYMENT_REFUND -> commitRefund(context, pending, arguments, attachments);
case FUND_REVOKE -> commitFundRevoke(context, pending, arguments, attachments);
case FULFILLMENT_CREATE -> commitFulfillmentCreate(context, pending, arguments, attachments, false);
case FULFILLMENT_CREATE_AND_VERIFY -> commitFulfillmentCreate(context, pending, arguments, attachments, true);
case FULFILLMENT_VERIFY -> commitFulfillmentVerify(arguments);
case FULFILLMENT_REJECT -> commitFulfillmentAction(arguments, false);
case FULFILLMENT_CANCEL -> commitFulfillmentAction(arguments, true);
default -> throw new GaoAiOperationException("FEATURE_DISABLED", "不支持的操作");
};
}
private GaoAiPreparedOperation prepareOrderCreate(GaoAiOperationContext context, GaoAiOperationDefinition definition,
JsonNode arguments, List<GaoAiAttachmentToken> attachments) {
GaoCustomer customer = support.customer(context.getStoreId(), arguments);
List<JsonNode> items = support.array(arguments, "itemList");
if (items.isEmpty()) {
throw GaoAiOperationException.clarification("请补充订单产品明细", List.of("itemList"));
}
if (items.size() > 20) {
throw new GaoAiOperationException("VALIDATION_FAILED", "单笔订单最多 20 个明细");
}
ObjectNode normalized = support.normalizable(arguments);
normalized.put("customerId", customer.getId());
ArrayNode normalizedItems = normalized.putArray("itemList");
List<Map<String, Object>> previewItems = new ArrayList<>();
long standardTotal = 0;
long saleTotal = 0;
boolean override = false;
String overrideReason = support.text(arguments, "overrideReason", "priceReason", "reason");
for (int index = 0; index < items.size(); index++) {
JsonNode item = items.get(index);
var selection = support.skuUnit(context.getStoreId(), item, false);
BigDecimal quantity = support.requiredDecimal(item, "购买数量", "quantity");
if (quantity.signum() <= 0) {
throw new GaoAiOperationException("VALIDATION_FAILED", "购买数量必须大于 0");
}
Long standardPrice = selection.getUnit().getSalePrice();
if (standardPrice == null) {
throw new GaoAiOperationException("VALIDATION_FAILED", "产品单位缺少建议售价");
}
Long requestedPrice = support.optionalLong(item, "unitPrice");
boolean lineOverride = requestedPrice != null && !requestedPrice.equals(standardPrice);
if (lineOverride && requestedPrice < 0) {
throw new GaoAiOperationException("VALIDATION_FAILED", "单价不能为负数");
}
long lineStandard = support.lineAmount(standardPrice, quantity);
long lineSale = support.lineAmount(lineOverride ? requestedPrice : standardPrice, quantity);
if (lineOverride) {
override = true;
authorizer.checkCode(context.getUserId(), GaoPermissionCode.SALES_ORDER_PRICE_OVERRIDE);
validateDiscount(lineStandard, lineSale);
}
standardTotal = Math.addExact(standardTotal, lineStandard);
saleTotal = Math.addExact(saleTotal, lineSale);
ObjectNode normalizedItem = normalizedItems.addObject();
normalizedItem.put("skuId", selection.getSku().getId());
normalizedItem.put("skuUnitId", selection.getUnit().getId());
normalizedItem.put("quantity", quantity.toPlainString());
normalizedItem.put("sort", index);
if (lineOverride) {
normalizedItem.put("unitPrice", requestedPrice);
}
if (support.text(item, "remark") != null) {
normalizedItem.put("remark", support.text(item, "remark"));
}
Map<String, Object> preview = new LinkedHashMap<>();
preview.put("productName", selection.getProduct().getName());
preview.put("skuName", selection.getSku().getName());
preview.put("skuCode", selection.getSku().getCode());
preview.put("unitName", selection.getUnit().getName());
preview.put("quantity", quantity.toPlainString());
preview.put("standardUnitPrice", support.money(standardPrice));
preview.put("unitPrice", support.money(lineOverride ? requestedPrice : standardPrice));
preview.put("lineAmount", support.money(lineSale));
previewItems.add(preview);
}
if (saleTotal > properties.getOrderMaxSaleAmount()) {
throw new GaoAiOperationException("VALIDATION_FAILED", "订单金额超过单笔上限");
}
if (override) {
validateDiscount(standardTotal, saleTotal);
}
if (override && (overrideReason == null || overrideReason.isBlank())) {
throw GaoAiOperationException.clarification("改价必须填写原因", List.of("overrideReason"));
}
if (overrideReason != null) {
normalized.put("overrideReason", overrideReason);
}
if (support.text(arguments, "remark") != null) {
normalized.put("remark", support.text(arguments, "remark"));
}
Map<String, Object> preview = new LinkedHashMap<>();
preview.put("customer", support.customerBrief(customer));
preview.put("items", previewItems);
preview.put("standardAmount", support.money(standardTotal));
preview.put("saleAmount", support.money(saleTotal));
preview.put("discount", discountText(standardTotal, saleTotal));
preview.put("attachmentCount", attachments.size());
GaoAiPreparedOperation result = new GaoAiPreparedOperation();
result.setArgumentsJson(normalized.toString());
result.setPreview(preview);
result.setTitle("新建销售订单");
if (override) {
result.setRiskLevel(RiskLevel.SENSITIVE);
result.setReasonRequired(true);
result.setRequiredPhrase("确认以 %s 创建订单".formatted(support.money(saleTotal)));
}
StringBuilder lines = new StringBuilder();
for (Map<String, Object> item : previewItems) {
lines.append("- %s / %s × %s %s,单价 %s,小计 %s%n".formatted(item.get("productName"),
item.get("skuName"), item.get("quantity"), item.get("unitName"), item.get("unitPrice"), item.get("lineAmount")));
}
result.setPreviewText("""
### 待确认:新建销售订单
客户:%s(%s)
明细:
%s
合计:%s
下单时间:%s
请回复“确认”执行,回复“取消”放弃。
""".formatted(customer.getName(), blank(customer.getCode()), lines, support.money(saleTotal),
support.dateTime(support.optionalLong(arguments, "purchasedAt"))));
return result;
}
private GaoAiPreparedOperation prepareOrderUpdate(GaoAiOperationContext context, JsonNode arguments,
List<GaoAiAttachmentToken> attachments) {
GaoSalesOrder order = support.order(context.getStoreId(), arguments);
ObjectNode normalized = support.normalizable(arguments);
normalized.put("salesOrderId", order.getId());
Map<String, Object> preview = new LinkedHashMap<>();
preview.put("order", support.orderBrief(order));
preview.put("remark", support.text(arguments, "remark"));
preview.put("attachmentCount", attachments.size());
GaoAiPreparedOperation result = new GaoAiPreparedOperation();
result.setArgumentsJson(normalized.toString());
result.setPreview(preview);
result.setTitle("修改销售订单备注和附件");
result.setPreviewText("""
### 待确认:修改销售订单
订单:%s
当前金额:%s
新备注:%s
新增附件:%d 个
请回复“确认”执行,回复“取消”放弃。
""".formatted(order.getOrderNo(), support.money(order.getSaleAmount()),
blank(support.text(arguments, "remark")), attachments.size()));
return result;
}
private GaoAiPreparedOperation prepareOrderCancel(GaoAiOperationContext context, GaoAiOperationDefinition definition,
JsonNode arguments, List<GaoAiAttachmentToken> attachments) {
GaoSalesOrder order = support.order(context.getStoreId(), arguments);
String reason = support.requiredText(arguments, "取消原因", "reason");
ObjectNode normalized = support.normalizable(arguments);
normalized.put("salesOrderId", order.getId());
normalized.put("reason", reason);
List<JsonNode> fulfillmentRevokeList = support.array(arguments, "fulfillmentRevokeList");
List<JsonNode> fulfillmentReturnList = support.array(arguments, "fulfillmentReturnList");
List<JsonNode> fundRevokeList = support.array(arguments, "fundRevokeList");
List<JsonNode> fundRefundList = support.array(arguments, "fundRefundList");
boolean hasReversal = !fulfillmentRevokeList.isEmpty() || !fulfillmentReturnList.isEmpty()
|| !fundRevokeList.isEmpty() || !fundRefundList.isEmpty();
for (JsonNode item : fulfillmentRevokeList) {
support.requiredText(item, "履约单 ID", "fulfillmentId");
}
for (JsonNode item : fulfillmentReturnList) {
support.requiredText(item, "履约单 ID", "fulfillmentId");
}
for (JsonNode item : fundRevokeList) {
support.requiredText(item, "资金流水 ID", "fundRecordId");
}
for (JsonNode item : fundRefundList) {
support.requiredText(item, "退款金额", "amount");
}
if (!fulfillmentRevokeList.isEmpty()) {
authorizer.checkCode(context.getUserId(), GaoPermissionCode.ORDER_FULFILLMENT_REVOKE);
}
if (!fulfillmentReturnList.isEmpty()) {
authorizer.checkCode(context.getUserId(), GaoPermissionCode.ORDER_FULFILLMENT_RETURN);
}
if (!fundRevokeList.isEmpty()) {
authorizer.checkCode(context.getUserId(), GaoPermissionCode.FUND_REVOKE);
}
if (!fundRefundList.isEmpty()) {
authorizer.checkCode(context.getUserId(), GaoPermissionCode.FUND_REFUND);
}
if (hasReversal && !hasImage(attachments)) {
throw new GaoAiOperationException("ATTACHMENT_REQUIRED", "订单取消包含冲正、退货或退款时必须上传照片凭证");
}
Map<String, Object> preview = new LinkedHashMap<>();
preview.put("order", support.orderBrief(order));
preview.put("reason", reason);
preview.put("fulfillmentRevokeCount", support.array(arguments, "fulfillmentRevokeList").size());
preview.put("fulfillmentReturnCount", support.array(arguments, "fulfillmentReturnList").size());
preview.put("fundRevokeCount", support.array(arguments, "fundRevokeList").size());
preview.put("fundRefundCount", support.array(arguments, "fundRefundList").size());
preview.put("attachmentCount", attachments.size());
GaoAiPreparedOperation result = new GaoAiPreparedOperation();
result.setArgumentsJson(normalized.toString());
result.setPreview(preview);
result.setTitle("取消销售订单");
result.setRiskLevel(RiskLevel.DESTRUCTIVE);
result.setReasonRequired(true);
result.setRequiredPhrase("确认取消订单 %s".formatted(order.getOrderNo()));
result.setImpactText("订单将取消,关联的待核销收款、履约以及指定的冲正、退货、退款将同步处理。");
result.setPreviewText("""
### 待确认:取消销售订单
订单:%s
客户:%s
金额:%s
取消原因:%s
履约冲正:%d 单
履约退货:%d 单
资金冲正:%d 笔
退款:%d 笔
%s
请回复“确认取消订单 %s”执行,回复“取消”放弃。
""".formatted(order.getOrderNo(), order.getCustomerId(), support.money(order.getSaleAmount()), reason,
preview.get("fulfillmentRevokeCount"), preview.get("fulfillmentReturnCount"),
preview.get("fundRevokeCount"), preview.get("fundRefundCount"), result.getImpactText(), order.getOrderNo()));
return result;
}
private GaoAiPreparedOperation preparePaymentReceive(GaoAiOperationContext context, GaoAiOperationDefinition definition,
JsonNode arguments, List<GaoAiAttachmentToken> attachments) {
GaoSalesOrder order = support.order(context.getStoreId(), arguments);
long amount = support.requiredLong(arguments, "收款金额", "amount");
if (amount <= 0) {
throw new GaoAiOperationException("VALIDATION_FAILED", "收款金额必须大于 0");
}
ObjectNode normalized = support.normalizable(arguments);
normalized.put("salesOrderId", order.getId());
normalized.put("amount", amount);
Map<String, Object> preview = new LinkedHashMap<>();
preview.put("order", support.orderBrief(order));
preview.put("amount", support.money(amount));
preview.put("unpaidAmount", support.money(order.getUnpaidAmount()));
preview.put("attachmentCount", attachments.size());
GaoAiPreparedOperation result = new GaoAiPreparedOperation();
result.setArgumentsJson(normalized.toString());
result.setPreview(preview);
result.setTitle(definition.title());
result.setPreviewText("""
### 待确认:%s
订单:%s
客户:%s
收款金额:%s
当前未收:%s
凭证:%d 张
请回复“确认”执行,回复“取消”放弃。
""".formatted(definition.title(), order.getOrderNo(), order.getCustomerId(), support.money(amount),
support.money(order.getUnpaidAmount()), attachments.size()));
return result;
}
private GaoAiPreparedOperation preparePaymentVerify(GaoAiOperationContext context, JsonNode arguments) {
GaoFundRecord record = support.fundRecord(context.getStoreId(), arguments);
ObjectNode normalized = support.normalizable(arguments);
normalized.put("fundRecordId", record.getId());
Map<String, Object> preview = new LinkedHashMap<>();
preview.put("fundRecordId", record.getId());
preview.put("amount", support.money(record.getAmount()));
preview.put("customerId", record.getCustomerId());
preview.put("bizId", record.getBizId());
GaoAiPreparedOperation result = new GaoAiPreparedOperation();
result.setArgumentsJson(normalized.toString());
result.setPreview(preview);
result.setTitle("核销收款");
result.setRiskLevel(RiskLevel.SENSITIVE);
result.setPreviewText("""
### 待确认:核销收款
资金流水:%s
金额:%s
订单 ID:%s
请回复“确认”执行,回复“取消”放弃。
""".formatted(record.getId(), support.money(record.getAmount()), record.getBizId()));
return result;
}
private GaoAiPreparedOperation preparePaymentAction(GaoAiOperationContext context, GaoAiOperationDefinition definition,
JsonNode arguments) {
GaoFundRecord record = support.fundRecord(context.getStoreId(), arguments);
String reason = support.requiredText(arguments, "操作原因", "reason");
ObjectNode normalized = support.normalizable(arguments);
normalized.put("fundRecordId", record.getId());
normalized.put("reason", reason);
Map<String, Object> preview = new LinkedHashMap<>();
preview.put("fundRecordId", record.getId());
preview.put("amount", support.money(record.getAmount()));
preview.put("reason", reason);
GaoAiPreparedOperation result = new GaoAiPreparedOperation();
result.setArgumentsJson(normalized.toString());
result.setPreview(preview);
result.setTitle(definition.title());
result.setRiskLevel(RiskLevel.DESTRUCTIVE);
result.setReasonRequired(true);
result.setRequiredPhrase("确认%s %s".formatted(definition.title(), support.money(record.getAmount())));
result.setPreviewText("""
### 待确认:%s
资金流水:%s
金额:%s
原因:%s
请回复“确认%s %s”执行,回复“取消”放弃。
""".formatted(definition.title(), record.getId(), support.money(record.getAmount()), reason,
definition.title(), support.money(record.getAmount())));
return result;
}
private GaoAiPreparedOperation prepareRefund(GaoAiOperationContext context, GaoAiOperationDefinition definition,
JsonNode arguments, List<GaoAiAttachmentToken> attachments) {
GaoSalesOrder order = support.order(context.getStoreId(), arguments);
long amount = support.requiredLong(arguments, "退款金额", "amount");
if (amount <= 0) {
throw new GaoAiOperationException("VALIDATION_FAILED", "退款金额必须大于 0");
}
String reason = support.requiredText(arguments, "退款原因", "reason");
ObjectNode normalized = support.normalizable(arguments);
normalized.put("salesOrderId", order.getId());
normalized.put("amount", amount);
normalized.put("reason", reason);
Map<String, Object> preview = new LinkedHashMap<>();
preview.put("order", support.orderBrief(order));
preview.put("amount", support.money(amount));
preview.put("reason", reason);
preview.put("attachmentCount", attachments.size());
GaoAiPreparedOperation result = new GaoAiPreparedOperation();
result.setArgumentsJson(normalized.toString());
result.setPreview(preview);
result.setTitle("销售订单退款");
result.setRiskLevel(RiskLevel.DESTRUCTIVE);
result.setReasonRequired(true);
result.setRequiredPhrase("确认退款 %s".formatted(support.money(amount)));
result.setImpactText("退款将形成资金流水,订单退款状态可能发生变化。");
result.setPreviewText("""
### 待确认:销售订单退款
订单:%s
退款金额:%s
原因:%s
凭证:%d 张
请回复“确认退款 %s”执行,回复“取消”放弃。
""".formatted(order.getOrderNo(), support.money(amount), reason, attachments.size(), support.money(amount)));
return result;
}
private GaoAiPreparedOperation prepareFundRevoke(GaoAiOperationContext context, GaoAiOperationDefinition definition,
JsonNode arguments, List<GaoAiAttachmentToken> attachments) {
GaoFundRecord record = support.fundRecord(context.getStoreId(), arguments);
String reason = support.requiredText(arguments, "冲正原因", "reason");
ObjectNode normalized = support.normalizable(arguments);
normalized.put("fundRecordId", record.getId());
normalized.put("reason", reason);
Map<String, Object> preview = new LinkedHashMap<>();
preview.put("fundRecordId", record.getId());
preview.put("amount", support.money(record.getAmount()));
preview.put("reason", reason);
preview.put("attachmentCount", attachments.size());
GaoAiPreparedOperation result = new GaoAiPreparedOperation();
result.setArgumentsJson(normalized.toString());
result.setPreview(preview);
result.setTitle("资金流水冲正");
result.setRiskLevel(RiskLevel.DESTRUCTIVE);
result.setReasonRequired(true);
result.setRequiredPhrase("确认冲正资金流水 %s".formatted(support.money(record.getAmount())));
result.setImpactText("原资金流水将失效,并生成反向冲正流水。");
result.setPreviewText("""
### 待确认:资金流水冲正
资金流水:%s
金额:%s
原因:%s
凭证:%d 张
请回复“确认冲正资金流水 %s”执行,回复“取消”放弃。
""".formatted(record.getId(), support.money(record.getAmount()), reason, attachments.size(),
support.money(record.getAmount())));
return result;
}
private GaoAiPreparedOperation prepareFulfillmentCreate(GaoAiOperationContext context,
GaoAiOperationDefinition definition, JsonNode arguments, List<GaoAiAttachmentToken> attachments) {
GaoSalesOrder order = support.order(context.getStoreId(), arguments);
List<JsonNode> items = fulfillmentItems(order, arguments);
if (items.isEmpty()) {
throw GaoAiOperationException.clarification("请补充履约明细", List.of("itemList"));
}
ObjectNode normalized = support.normalizable(arguments);
normalized.put("salesOrderId", order.getId());
ArrayNode normalizedItems = normalized.putArray("itemList");
List<Map<String, Object>> previewItems = new ArrayList<>();
Map<String, GaoSalesOrderItem> itemMap = new LinkedHashMap<>();
if (order.getItemList() != null) {
for (GaoSalesOrderItem item : order.getItemList()) {
itemMap.put(item.getId(), item);
}
}
for (JsonNode item : items) {
String sourceId = support.requiredText(item, "sourceOrderItemId", "orderItemId");
String unitId = support.requiredText(item, "skuUnitId");
BigDecimal quantity = support.requiredDecimal(item, "quantity");
GaoSalesOrderItem source = itemMap.get(sourceId);
if (source == null) {
throw new GaoAiOperationException("VALIDATION_FAILED", "履约明细不属于当前订单");
}
ObjectNode normalizedItem = normalizedItems.addObject();
normalizedItem.put("sourceOrderItemId", sourceId);
normalizedItem.put("skuUnitId", unitId);
normalizedItem.put("quantity", quantity.toPlainString());
Map<String, Object> previewItem = new LinkedHashMap<>();
previewItem.put("productName", source.getProductNameSnapshot());
previewItem.put("skuName", source.getSkuNameSnapshot());
previewItem.put("quantity", quantity.toPlainString());
previewItem.put("unitName", source.getUnitSnapshot());
previewItems.add(previewItem);
}
Map<String, Object> preview = new LinkedHashMap<>();
preview.put("order", support.orderBrief(order));
preview.put("items", previewItems);
preview.put("attachmentCount", attachments.size());
GaoAiPreparedOperation result = new GaoAiPreparedOperation();
result.setArgumentsJson(normalized.toString());
result.setPreview(preview);
result.setTitle(definition.title());
result.setPreviewText("""
### 待确认:%s
订单:%s
履约明细:%d 项
凭证:%d 张
请回复“确认”执行,回复“取消”放弃。
""".formatted(definition.title(), order.getOrderNo(), previewItems.size(), attachments.size()));
return result;
}
private GaoAiPreparedOperation prepareFulfillmentAction(GaoAiOperationContext context,
GaoAiOperationDefinition definition, JsonNode arguments) {
GaoOrderFulfillment fulfillment = support.fulfillment(context.getStoreId(), arguments);
String reason = support.text(arguments, "reason");
if (definition.getOperation() != GaoAiOperation.FULFILLMENT_VERIFY && (reason == null || reason.isBlank())) {
throw GaoAiOperationException.clarification("请补充操作原因", List.of("reason"));
}
ObjectNode normalized = support.normalizable(arguments);
normalized.put("fulfillmentId", fulfillment.getId());
if (reason != null) {
normalized.put("reason", reason);
}
Map<String, Object> preview = new LinkedHashMap<>();
preview.put("fulfillmentId", fulfillment.getId());
preview.put("orderId", fulfillment.getSalesOrderId());
preview.put("status", fulfillment.getStatus());
preview.put("reason", reason);
GaoAiPreparedOperation result = new GaoAiPreparedOperation();
result.setArgumentsJson(normalized.toString());
result.setPreview(preview);
result.setTitle(definition.title());
if (definition.destructive()) {
result.setRiskLevel(RiskLevel.DESTRUCTIVE);
result.setReasonRequired(true);
result.setRequiredPhrase("确认%s %s".formatted(definition.title(), fulfillment.getId()));
result.setImpactText("履约状态将发生变化,相关库存占用或核销记录会同步处理。");
result.setPreviewText("""
### 待确认:%s
履约单:%s
订单 ID:%s
原因:%s
请回复“确认%s %s”执行,回复“取消”放弃。
""".formatted(definition.title(), fulfillment.getId(), fulfillment.getSalesOrderId(), reason,
definition.title(), fulfillment.getId()));
} else {
result.setRiskLevel(RiskLevel.SENSITIVE);
result.setPreviewText("""
### 待确认:%s
履约单:%s
订单 ID:%s
请回复“确认”执行,回复“取消”放弃。
""".formatted(definition.title(), fulfillment.getId(), fulfillment.getSalesOrderId()));
}
return result;
}
private GaoAiCommitResult commitOrderCreate(GaoAiOperationContext context, GaoAiPendingOperation pending,
JsonNode arguments, List<Attachment> attachments) {
GaoDirectProductOrderCreateRequest request = new GaoDirectProductOrderCreateRequest();
request.setRequestNo(pending.getRequestNo());
request.setStoreId(context.getStoreId());
request.setCustomerId(support.requiredText(arguments, "customerId"));
request.setPurchasedAt(support.optionalLong(arguments, "purchasedAt"));
request.setRemark(support.text(arguments, "remark"));
request.setAttachmentList(attachments);
List<GaoSalesOrderItemRequest> itemList = new ArrayList<>();
for (JsonNode item : support.array(arguments, "itemList")) {
GaoSalesOrderItemRequest requestItem = new GaoSalesOrderItemRequest();
requestItem.setSkuId(support.requiredText(item, "skuId"));
requestItem.setSkuUnitId(support.requiredText(item, "skuUnitId"));
requestItem.setQuantity(support.requiredDecimal(item, "quantity"));
requestItem.setUnitPrice(support.optionalLong(item, "unitPrice"));
requestItem.setSort(support.optionalLong(item, "sort") == null ? itemList.size()
: support.optionalLong(item, "sort").intValue());
requestItem.setRemark(support.text(item, "remark"));
itemList.add(requestItem);
}
request.setItemList(itemList);
GaoSalesOrder order = salesOrderService.createDirectProductOrder(request);
return GaoAiCommitResult.success(GaoAiOperation.SALES_ORDER_CREATE.name(), "SALES_ORDER", order.getId(),
order.getOrderNo(), "已创建销售订单 %s,金额 %s。".formatted(order.getOrderNo(), support.money(order.getSaleAmount())));
}
private GaoAiCommitResult commitOrderUpdate(JsonNode arguments, List<Attachment> attachments) {
String id = support.requiredText(arguments, "salesOrderId", "orderId");
GaoSalesOrder existing = salesOrderService.detail(id);
GaoSalesOrderUpdateRequest request = new GaoSalesOrderUpdateRequest();
request.setId(id);
request.setRemark(support.text(arguments, "remark"));
request.setAttachmentList(attachments.isEmpty()
? attachmentService.listByBizId(Attachment.BizType.GAO_SALES_ORDER, existing.getId()) : attachments);
GaoSalesOrder order = salesOrderService.updateRemarkAndAttachments(request);
return GaoAiCommitResult.success(GaoAiOperation.SALES_ORDER_UPDATE.name(), "SALES_ORDER", order.getId(),
order.getOrderNo(), "已更新销售订单 %s。".formatted(order.getOrderNo()));
}
private GaoAiCommitResult commitOrderCancel(GaoAiOperationContext context, GaoAiPendingOperation pending,
JsonNode arguments, List<Attachment> attachments) {
String orderId = support.requiredText(arguments, "salesOrderId", "orderId");
String reason = support.requiredText(arguments, "reason");
GaoSalesOrderCancelRequest request = new GaoSalesOrderCancelRequest();
request.setSalesOrderId(orderId);
request.setReason(reason);
request.setRequestNo(pending.getRequestNo());
request.setAttachmentList(attachments);
request.setFulfillmentRevokeList(fulfillmentRevokeList(arguments, reason, attachments));
request.setFulfillmentReturnList(fulfillmentReturnList(arguments, reason, attachments));
request.setFundRevokeList(fundRevokeList(arguments, reason, attachments));
request.setFundRefundList(fundRefundList(orderId, arguments, reason, attachments));
GaoSalesOrder order = salesOrderService.cancel(request);
return GaoAiCommitResult.success(GaoAiOperation.SALES_ORDER_CANCEL.name(), "SALES_ORDER", order.getId(),
order.getOrderNo(), "已取消销售订单 %s。".formatted(order.getOrderNo()));
}
private GaoAiCommitResult commitPaymentReceive(GaoAiOperationContext context, GaoAiPendingOperation pending,
JsonNode arguments, List<Attachment> attachments, boolean verify) {
GaoOrderPaymentReceiveRequest request = new GaoOrderPaymentReceiveRequest();
request.setSalesOrderId(support.requiredText(arguments, "salesOrderId", "orderId"));
request.setRequestNo(pending.getRequestNo());
request.setAmount(support.requiredLong(arguments, "amount"));
request.setOccurredAt(support.optionalLong(arguments, "occurredAt"));
request.setAttachmentList(attachments);
request.setRemark(support.text(arguments, "remark"));
GaoFundRecord record = verify ? paymentService.receiveAndVerify(request) : paymentService.receive(request);
return GaoAiCommitResult.success(verify ? GaoAiOperation.PAYMENT_RECEIVE_AND_VERIFY.name()
: GaoAiOperation.PAYMENT_RECEIVE.name(), "FUND_RECORD", record.getId(), null,
"已登记收款 %s。".formatted(support.money(record.getAmount())));
}
private GaoAiCommitResult commitPaymentVerify(JsonNode arguments) {
String id = support.requiredText(arguments, "fundRecordId", "id");
GaoFundRecord record = paymentService.verify(id);
return GaoAiCommitResult.success(GaoAiOperation.PAYMENT_VERIFY.name(), "FUND_RECORD", record.getId(),
null, "已核销收款 %s。".formatted(support.money(record.getAmount())));
}
private GaoAiCommitResult commitPaymentAction(JsonNode arguments, boolean cancel) {
GaoOrderPaymentActionRequest request = new GaoOrderPaymentActionRequest();
request.setFundRecordId(support.requiredText(arguments, "fundRecordId", "id"));
request.setReason(support.requiredText(arguments, "reason"));
GaoFundRecord record = cancel ? paymentService.cancel(request) : paymentService.reject(request);
return GaoAiCommitResult.success(cancel ? GaoAiOperation.PAYMENT_CANCEL.name()
: GaoAiOperation.PAYMENT_REJECT.name(), "FUND_RECORD", record.getId(), null,
"已%s收款。".formatted(cancel ? "撤销" : "拒绝"));
}
private GaoAiCommitResult commitRefund(GaoAiOperationContext context, GaoAiPendingOperation pending,
JsonNode arguments, List<Attachment> attachments) {
GaoOrderPaymentRefundRequest request = new GaoOrderPaymentRefundRequest();
request.setSalesOrderId(support.requiredText(arguments, "salesOrderId", "orderId"));
request.setRequestNo(pending.getRequestNo());
request.setAmount(support.requiredLong(arguments, "amount"));
request.setOccurredAt(support.optionalLong(arguments, "occurredAt"));
request.setReason(support.requiredText(arguments, "reason"));
request.setAttachmentList(attachments);
request.setRemark(support.text(arguments, "remark"));
GaoFundRecord record = paymentService.refund(request);
return GaoAiCommitResult.success(GaoAiOperation.PAYMENT_REFUND.name(), "FUND_RECORD", record.getId(),
null, "已登记退款 %s。".formatted(support.money(record.getAmount())));
}
private GaoAiCommitResult commitFundRevoke(GaoAiOperationContext context, GaoAiPendingOperation pending,
JsonNode arguments, List<Attachment> attachments) {
GaoOrderPaymentRevokeRequest request = new GaoOrderPaymentRevokeRequest();
request.setFundRecordId(support.requiredText(arguments, "fundRecordId", "id"));
request.setRequestNo(pending.getRequestNo());
request.setOccurredAt(support.optionalLong(arguments, "occurredAt"));
request.setReason(support.requiredText(arguments, "reason"));
request.setAttachmentList(attachments);
request.setRemark(support.text(arguments, "remark"));
GaoFundRecord record = paymentService.revoke(request);
return GaoAiCommitResult.success(GaoAiOperation.FUND_REVOKE.name(), "FUND_RECORD", record.getId(),
null, "已冲正资金流水 %s。".formatted(support.money(record.getAmount())));
}
private GaoAiCommitResult commitFulfillmentCreate(GaoAiOperationContext context, GaoAiPendingOperation pending,
JsonNode arguments, List<Attachment> attachments, boolean verify) {
GaoOrderFulfillmentCreateRequest request = new GaoOrderFulfillmentCreateRequest();
request.setSalesOrderId(support.requiredText(arguments, "salesOrderId", "orderId"));
request.setRequestNo(pending.getRequestNo());
request.setDeliveredAt(support.optionalLong(arguments, "deliveredAt"));
request.setRemark(support.text(arguments, "remark"));
request.setAttachmentList(attachments);
List<GaoOrderFulfillmentItemRequest> itemList = new ArrayList<>();
for (JsonNode item : support.array(arguments, "itemList")) {
GaoOrderFulfillmentItemRequest requestItem = new GaoOrderFulfillmentItemRequest();
requestItem.setSourceOrderItemId(support.requiredText(item, "sourceOrderItemId"));
requestItem.setSkuUnitId(support.requiredText(item, "skuUnitId"));
requestItem.setQuantity(support.requiredDecimal(item, "quantity"));
itemList.add(requestItem);
}
request.setItemList(itemList);
GaoOrderFulfillment fulfillment = verify ? fulfillmentService.createAndVerify(request)
: fulfillmentService.create(request);
return GaoAiCommitResult.success(verify ? GaoAiOperation.FULFILLMENT_CREATE_AND_VERIFY.name()
: GaoAiOperation.FULFILLMENT_CREATE.name(), "ORDER_FULFILLMENT", fulfillment.getId(), null,
"已创建履约单,状态 %s。".formatted(fulfillment.getStatus()));
}
private GaoAiCommitResult commitFulfillmentVerify(JsonNode arguments) {
GaoOrderFulfillmentActionRequest request = new GaoOrderFulfillmentActionRequest();
request.setFulfillmentId(support.requiredText(arguments, "fulfillmentId", "id"));
GaoOrderFulfillment fulfillment = fulfillmentService.verify(request);
return GaoAiCommitResult.success(GaoAiOperation.FULFILLMENT_VERIFY.name(), "ORDER_FULFILLMENT",
fulfillment.getId(), null, "已核销履约单。");
}
private GaoAiCommitResult commitFulfillmentAction(JsonNode arguments, boolean cancel) {
GaoOrderFulfillmentActionRequest request = new GaoOrderFulfillmentActionRequest();
request.setFulfillmentId(support.requiredText(arguments, "fulfillmentId", "id"));
request.setReason(support.requiredText(arguments, "reason"));
GaoOrderFulfillment fulfillment = cancel ? fulfillmentService.cancel(request) : fulfillmentService.reject(request);
return GaoAiCommitResult.success(cancel ? GaoAiOperation.FULFILLMENT_CANCEL.name()
: GaoAiOperation.FULFILLMENT_REJECT.name(), "ORDER_FULFILLMENT", fulfillment.getId(), null,
"已%s履约单。".formatted(cancel ? "撤销" : "拒绝"));
}
private List<JsonNode> fulfillmentItems(GaoSalesOrder order, JsonNode arguments) {
List<JsonNode> items = support.array(arguments, "itemList");
if (!items.isEmpty()) {
return items;
}
if (!Boolean.TRUE.equals(support.optionalBoolean(arguments, "fulfillAll"))) {
return List.of();
}
List<JsonNode> result = new ArrayList<>();
for (GaoSalesOrderItem item : order.getItemList() == null ? List.<GaoSalesOrderItem>of() : order.getItemList()) {
BigDecimal available = item.getAvailableBaseQuantity();
if (available == null || available.signum() <= 0 || item.getBaseQuantityPerUnitSnapshot() == null
|| item.getBaseQuantityPerUnitSnapshot().signum() <= 0) {
continue;
}
BigDecimal quantity = available.divide(item.getBaseQuantityPerUnitSnapshot(), 3, RoundingMode.DOWN);
if (quantity.signum() <= 0) {
continue;
}
ObjectNode node = com.fasterxml.jackson.databind.node.JsonNodeFactory.instance.objectNode();
node.put("sourceOrderItemId", item.getId());
node.put("skuUnitId", item.getSkuUnitId());
node.put("quantity", quantity.toPlainString());
result.add(node);
}
return result;
}
private List<GaoOrderFulfillmentRevokeRequest> fulfillmentRevokeList(JsonNode arguments, String defaultReason,
List<Attachment> attachments) {
List<GaoOrderFulfillmentRevokeRequest> result = new ArrayList<>();
int index = 0;
for (JsonNode item : support.array(arguments, "fulfillmentRevokeList")) {
GaoOrderFulfillmentRevokeRequest request = new GaoOrderFulfillmentRevokeRequest();
request.setFulfillmentId(support.requiredText(item, "fulfillmentId"));
request.setRequestNo("%s-R%d".formatted(support.requestNo(GaoAiOperation.SALES_ORDER_CANCEL), index++));
request.setDeliveredAt(support.optionalLong(item, "deliveredAt"));
request.setReason(defaultReason);
request.setReturnedToStore(support.optionalBoolean(item, "returnedToStore"));
request.setAttachmentList(attachments);
request.setRemark(support.text(item, "remark"));
result.add(request);
}
return result;
}
private List<GaoOrderFulfillmentReturnRequest> fulfillmentReturnList(JsonNode arguments, String defaultReason,
List<Attachment> attachments) {
List<GaoOrderFulfillmentReturnRequest> result = new ArrayList<>();
int index = 0;
for (JsonNode item : support.array(arguments, "fulfillmentReturnList")) {
GaoOrderFulfillmentReturnRequest request = new GaoOrderFulfillmentReturnRequest();
request.setFulfillmentId(support.requiredText(item, "fulfillmentId"));
request.setRequestNo("%s-T%d".formatted(support.requestNo(GaoAiOperation.SALES_ORDER_CANCEL), index++));
request.setReturnedAt(support.optionalLong(item, "returnedAt"));
request.setReason(defaultReason);
request.setReturnedToStore(support.optionalBoolean(item, "returnedToStore"));
request.setAttachmentList(attachments);
request.setRemark(support.text(item, "remark"));
result.add(request);
}
return result;
}
private List<GaoOrderPaymentRevokeRequest> fundRevokeList(JsonNode arguments, String defaultReason,
List<Attachment> attachments) {
List<GaoOrderPaymentRevokeRequest> result = new ArrayList<>();
int index = 0;
for (JsonNode item : support.array(arguments, "fundRevokeList")) {
GaoOrderPaymentRevokeRequest request = new GaoOrderPaymentRevokeRequest();
request.setFundRecordId(support.requiredText(item, "fundRecordId"));
request.setRequestNo("%s-FR%d".formatted(support.requestNo(GaoAiOperation.SALES_ORDER_CANCEL), index++));
request.setReason(defaultReason);
request.setOccurredAt(support.optionalLong(item, "occurredAt"));
request.setAttachmentList(attachments);
request.setRemark(support.text(item, "remark"));
result.add(request);
}
return result;
}
private List<GaoOrderPaymentRefundRequest> fundRefundList(String salesOrderId, JsonNode arguments,
String defaultReason, List<Attachment> attachments) {
List<GaoOrderPaymentRefundRequest> result = new ArrayList<>();
int index = 0;
for (JsonNode item : support.array(arguments, "fundRefundList")) {
GaoOrderPaymentRefundRequest request = new GaoOrderPaymentRefundRequest();
request.setSalesOrderId(salesOrderId);
request.setRequestNo("%s-FD%d".formatted(support.requestNo(GaoAiOperation.SALES_ORDER_CANCEL), index++));
request.setAmount(support.requiredLong(item, "amount"));
request.setOccurredAt(support.optionalLong(item, "occurredAt"));
request.setReason(defaultReason);
request.setAttachmentList(attachments);
request.setRemark(support.text(item, "remark"));
result.add(request);
}
return result;
}
private void validateDiscount(long standardAmount, long saleAmount) {
if (standardAmount <= 0 || saleAmount >= standardAmount) {
return;
}
double discount = BigDecimal.valueOf(standardAmount - saleAmount)
.divide(BigDecimal.valueOf(standardAmount), 4, RoundingMode.HALF_UP).doubleValue();
if (discount > properties.getMaxDiscountRate()) {
throw new GaoAiOperationException("VALIDATION_FAILED", "优惠幅度超过 %d%% 上限".formatted(Math.round(properties.getMaxDiscountRate() * 100)));
}
}
private String discountText(long standardAmount, long saleAmount) {
if (standardAmount <= 0 || saleAmount >= standardAmount) {
return "无";
}
double discount = BigDecimal.valueOf(standardAmount - saleAmount)
.divide(BigDecimal.valueOf(standardAmount), 4, RoundingMode.HALF_UP).doubleValue() * 100;
return "%.2f%%".formatted(discount);
}
private boolean hasImage(List<GaoAiAttachmentToken> attachments) {
return attachments != null && attachments.stream()
.anyMatch(item -> item.getMimeType() != null && item.getMimeType().startsWith("image/"));
}
private String blank(String value) {
return value == null ? "-" : value;
}
}
@@ -0,0 +1,188 @@
package com.imyeyu.api.modules.gao.ai.operation.handler;
import com.fasterxml.jackson.databind.JsonNode;
import com.imyeyu.api.modules.common.entity.Attachment;
import com.imyeyu.api.modules.gao.ai.config.GaoAiProperties;
import com.imyeyu.api.modules.gao.ai.operation.GaoAiAttachmentToken;
import com.imyeyu.api.modules.gao.ai.operation.GaoAiCommitResult;
import com.imyeyu.api.modules.gao.ai.operation.GaoAiOperation;
import com.imyeyu.api.modules.gao.ai.operation.GaoAiOperationContext;
import com.imyeyu.api.modules.gao.ai.operation.GaoAiOperationDefinition;
import com.imyeyu.api.modules.gao.ai.operation.GaoAiOperationDefinition.RiskLevel;
import com.imyeyu.api.modules.gao.ai.operation.GaoAiOperationException;
import com.imyeyu.api.modules.gao.ai.operation.GaoAiOperationHandler;
import com.imyeyu.api.modules.gao.ai.operation.GaoAiOperationSupport;
import com.imyeyu.api.modules.gao.ai.operation.GaoAiPendingOperation;
import com.imyeyu.api.modules.gao.ai.operation.GaoAiPreparedOperation;
import com.imyeyu.api.modules.gao.ai.operation.GaoAiToolAuthorizer;
import com.imyeyu.api.modules.gao.bean.GaoPermissionCode;
import com.imyeyu.api.modules.gao.entity.GaoCustomer;
import com.imyeyu.api.modules.gao.entity.GaoCustomerPackage;
import com.imyeyu.api.modules.gao.entity.GaoPackageConfig;
import com.imyeyu.api.modules.gao.service.GaoCustomerPackageService;
import com.imyeyu.api.modules.gao.vo.customer.GaoCustomerPackagePurchaseItem;
import com.imyeyu.api.modules.gao.vo.customer.GaoCustomerPackagePurchaseRequest;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
/// 客户套餐写操作处理器
///
/// @author Codex
/// @since 2026-11-23
@Component
@RequiredArgsConstructor
public class PackageOperationHandler implements GaoAiOperationHandler {
private final GaoAiOperationSupport support;
private final GaoAiProperties properties;
private final GaoAiToolAuthorizer authorizer;
private final GaoCustomerPackageService packageService;
@Override
public Set<GaoAiOperation> supports() {
return Set.of(GaoAiOperation.CUSTOMER_PACKAGE_PURCHASE);
}
@Override
public GaoAiPreparedOperation prepare(GaoAiOperationContext context, GaoAiOperationDefinition definition,
JsonNode arguments, List<GaoAiAttachmentToken> attachments) {
GaoCustomer customer = support.customer(context.getStoreId(), arguments);
GaoPackageConfig config = support.packageConfig(context.getStoreId(), arguments);
if (config.getStandardAmount() == null) {
throw new GaoAiOperationException("VALIDATION_FAILED", "套餐配置缺少标准价");
}
Long saleAmount = support.optionalLong(arguments, "saleAmount", "amount");
boolean override = saleAmount != null && !saleAmount.equals(config.getStandardAmount());
if (override) {
authorizer.checkCode(context.getUserId(), GaoPermissionCode.CUSTOMER_PACKAGE_PRICE_OVERRIDE);
validateDiscount(config.getStandardAmount(), saleAmount);
String reason = support.requiredText(arguments, "改价原因", "reason");
if (reason.isBlank()) {
throw new GaoAiOperationException("VALIDATION_FAILED", "改价必须填写原因");
}
}
List<GaoCustomerPackagePurchaseItem> itemList = itemList(arguments);
boolean gift = itemList.stream().anyMatch(item -> Boolean.TRUE.equals(item.getGifted()));
if (gift) {
authorizer.checkCode(context.getUserId(), GaoPermissionCode.CUSTOMER_PACKAGE_GIFT_CREATE);
}
long finalAmount = saleAmount == null ? config.getStandardAmount() : saleAmount;
if (finalAmount < 0) {
throw new GaoAiOperationException("VALIDATION_FAILED", "成交价不能为负数");
}
com.fasterxml.jackson.databind.node.ObjectNode normalized = support.normalizable(arguments);
normalized.put("customerId", customer.getId());
normalized.put("packageConfigId", config.getId());
normalized.put("saleAmount", finalAmount);
if (arguments.hasNonNull("itemList")) {
normalized.set("itemList", arguments.get("itemList"));
}
Map<String, Object> preview = new LinkedHashMap<>();
preview.put("customer", support.customerBrief(customer));
preview.put("packageName", config.getName());
preview.put("standardAmount", support.money(config.getStandardAmount()));
preview.put("saleAmount", support.money(finalAmount));
preview.put("discount", discountText(config.getStandardAmount(), finalAmount));
preview.put("itemCount", itemList.size());
preview.put("gift", gift);
preview.put("attachmentCount", attachments.size());
GaoAiPreparedOperation result = new GaoAiPreparedOperation();
result.setArgumentsJson(normalized.toString());
result.setPreview(preview);
result.setTitle("购买客户套餐");
if (override || gift) {
result.setRiskLevel(RiskLevel.SENSITIVE);
result.setReasonRequired(override);
result.setRequiredPhrase("确认以 %s 购买套餐 %s".formatted(support.money(finalAmount), config.getName()));
}
result.setPreviewText("""
### 待确认:购买客户套餐
客户:%s(%s)
套餐:%s
标准价:%s
成交价:%s
优惠:%s
自定义明细:%d 项
赠送权益:%s
凭证:%d 张
请回复“确认”执行,回复“取消”放弃。
""".formatted(customer.getName(), blank(customer.getCode()), config.getName(),
support.money(config.getStandardAmount()), support.money(finalAmount),
discountText(config.getStandardAmount(), finalAmount), itemList.size(), gift ? "是" : "否",
attachments.size()));
return result;
}
@Override
public GaoAiCommitResult commit(GaoAiOperationContext context, GaoAiPendingOperation pending,
JsonNode arguments, List<Attachment> attachments) {
GaoCustomerPackagePurchaseRequest request = new GaoCustomerPackagePurchaseRequest();
request.setRequestNo(pending.getRequestNo());
request.setPackageConfigId(support.requiredText(arguments, "packageConfigId"));
request.setCustomerId(support.requiredText(arguments, "customerId"));
request.setSaleAmount(support.optionalLong(arguments, "saleAmount", "amount"));
request.setPurchasedAt(support.optionalLong(arguments, "purchasedAt"));
List<GaoCustomerPackagePurchaseItem> purchaseItemList = itemList(arguments);
request.setItemList(purchaseItemList.isEmpty() ? null : purchaseItemList);
request.setAttachmentList(attachments);
request.setRemark(support.text(arguments, "remark"));
GaoCustomerPackage result = packageService.purchase(request);
return GaoAiCommitResult.success(GaoAiOperation.CUSTOMER_PACKAGE_PURCHASE.name(), "CUSTOMER_PACKAGE",
result.getId(), result.getSalesOrderId(), "已购买客户套餐「%s」。".formatted(result.getPackageNameSnapshot()));
}
private List<GaoCustomerPackagePurchaseItem> itemList(JsonNode arguments) {
List<JsonNode> items = support.array(arguments, "itemList");
List<GaoCustomerPackagePurchaseItem> result = new ArrayList<>();
for (JsonNode item : items) {
GaoCustomerPackagePurchaseItem purchaseItem = new GaoCustomerPackagePurchaseItem();
purchaseItem.setSkuId(support.requiredText(item, "skuId"));
purchaseItem.setSkuUnitId(support.requiredText(item, "skuUnitId"));
purchaseItem.setGifted(support.optionalBoolean(item, "gifted"));
purchaseItem.setTotalQuantity(support.requiredDecimal(item, "totalQuantity", "quantity"));
purchaseItem.setRemark(support.text(item, "remark"));
result.add(purchaseItem);
}
return result;
}
private void validateDiscount(Long standardAmount, Long saleAmount) {
if (standardAmount == null || standardAmount <= 0 || saleAmount == null) {
return;
}
if (saleAmount < 0) {
throw new GaoAiOperationException("VALIDATION_FAILED", "成交价不能为负数");
}
double discount = BigDecimal.valueOf(standardAmount - saleAmount)
.divide(BigDecimal.valueOf(standardAmount), 4, java.math.RoundingMode.HALF_UP)
.doubleValue();
if (discount > properties.getMaxDiscountRate()) {
throw new GaoAiOperationException("VALIDATION_FAILED", "优惠幅度超过 %d%% 上限".formatted(Math.round(properties.getMaxDiscountRate() * 100)));
}
}
private String discountText(Long standardAmount, Long saleAmount) {
if (standardAmount == null || standardAmount <= 0 || saleAmount == null || standardAmount.equals(saleAmount)) {
return "无";
}
double discount = BigDecimal.valueOf(standardAmount - saleAmount)
.divide(BigDecimal.valueOf(standardAmount), 4, java.math.RoundingMode.HALF_UP)
.doubleValue() * 100;
return "%.2f%%".formatted(discount);
}
private String blank(String value) {
return value == null ? "-" : value;
}
}
@@ -0,0 +1,243 @@
package com.imyeyu.api.modules.gao.ai.operation.handler;
import com.fasterxml.jackson.databind.JsonNode;
import com.imyeyu.api.modules.common.entity.Attachment;
import com.imyeyu.api.modules.gao.ai.config.GaoAiProperties;
import com.imyeyu.api.modules.gao.ai.operation.GaoAiAttachmentToken;
import com.imyeyu.api.modules.gao.ai.operation.GaoAiCommitResult;
import com.imyeyu.api.modules.gao.ai.operation.GaoAiOperation;
import com.imyeyu.api.modules.gao.ai.operation.GaoAiOperationContext;
import com.imyeyu.api.modules.gao.ai.operation.GaoAiOperationDefinition;
import com.imyeyu.api.modules.gao.ai.operation.GaoAiOperationDefinition.RiskLevel;
import com.imyeyu.api.modules.gao.ai.operation.GaoAiOperationException;
import com.imyeyu.api.modules.gao.ai.operation.GaoAiOperationHandler;
import com.imyeyu.api.modules.gao.ai.operation.GaoAiOperationSupport;
import com.imyeyu.api.modules.gao.ai.operation.GaoAiPendingOperation;
import com.imyeyu.api.modules.gao.ai.operation.GaoAiPreparedOperation;
import com.imyeyu.api.modules.gao.ai.operation.GaoAiToolAuthorizer;
import com.imyeyu.api.modules.gao.bean.GaoPermissionCode;
import com.imyeyu.api.modules.gao.entity.GaoCustomer;
import com.imyeyu.api.modules.gao.entity.GaoPointAccount;
import com.imyeyu.api.modules.gao.entity.GaoPointLedger;
import com.imyeyu.api.modules.gao.entity.GaoPointRedeemSku;
import com.imyeyu.api.modules.gao.entity.GaoPointRedemption;
import com.imyeyu.api.modules.gao.service.GaoPointAccountService;
import com.imyeyu.api.modules.gao.service.GaoPointLedgerService;
import com.imyeyu.api.modules.gao.service.GaoPointRedemptionService;
import com.imyeyu.api.modules.gao.vo.point.GaoPointAdjustRequest;
import com.imyeyu.api.modules.gao.vo.point.GaoPointRedemptionCreateRequest;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;
import java.math.BigDecimal;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
/// 积分写操作处理器
///
/// @author Codex
/// @since 2026-11-23
@Component
@RequiredArgsConstructor
public class PointOperationHandler implements GaoAiOperationHandler {
private final GaoAiOperationSupport support;
private final GaoAiProperties properties;
private final GaoAiToolAuthorizer authorizer;
private final GaoPointAccountService pointAccountService;
private final GaoPointLedgerService pointLedgerService;
private final GaoPointRedemptionService redemptionService;
@Override
public Set<GaoAiOperation> supports() {
return Set.of(GaoAiOperation.POINT_ADJUST, GaoAiOperation.POINT_REDEMPTION_CREATE);
}
@Override
public GaoAiPreparedOperation prepare(GaoAiOperationContext context, GaoAiOperationDefinition definition,
JsonNode arguments, List<GaoAiAttachmentToken> attachments) {
return switch (definition.getOperation()) {
case POINT_ADJUST -> prepareAdjust(context, arguments);
case POINT_REDEMPTION_CREATE -> prepareRedemption(context, arguments, attachments);
default -> throw new GaoAiOperationException("FEATURE_DISABLED", "不支持的操作");
};
}
@Override
public GaoAiCommitResult commit(GaoAiOperationContext context, GaoAiPendingOperation pending,
JsonNode arguments, List<Attachment> attachments) {
return switch (GaoAiOperation.valueOf(pending.getOperation())) {
case POINT_ADJUST -> commitAdjust(context, pending, arguments);
case POINT_REDEMPTION_CREATE -> commitRedemption(context, pending, arguments, attachments);
default -> throw new GaoAiOperationException("FEATURE_DISABLED", "不支持的操作");
};
}
private GaoAiPreparedOperation prepareAdjust(GaoAiOperationContext context, JsonNode arguments) {
GaoCustomer customer = support.customer(context.getStoreId(), arguments);
long delta = support.requiredLong(arguments, "调整积分", "pointDelta", "points");
if (delta == 0) {
throw new GaoAiOperationException("VALIDATION_FAILED", "调整积分不能为 0");
}
if (Math.abs(delta) > properties.getPointAdjustMaxAbs()) {
throw new GaoAiOperationException("VALIDATION_FAILED", "单次积分调整不能超过 " + properties.getPointAdjustMaxAbs());
}
String remark = support.requiredText(arguments, "调整原因", "remark", "reason");
GaoPointAccount account = pointAccountService.getByCustomerId(context.getStoreId(), customer.getId());
long balance = account == null ? 0L : account.getBalance();
com.fasterxml.jackson.databind.node.ObjectNode normalized = support.normalizable(arguments);
normalized.put("customerId", customer.getId());
normalized.put("pointDelta", delta);
normalized.put("remark", remark);
Map<String, Object> preview = new LinkedHashMap<>();
preview.put("customer", support.customerBrief(customer));
preview.put("pointDelta", delta);
preview.put("balanceBefore", balance);
preview.put("balanceAfter", balance + delta);
preview.put("remark", remark);
GaoAiPreparedOperation result = new GaoAiPreparedOperation();
result.setArgumentsJson(normalized.toString());
result.setPreview(preview);
result.setTitle("人工调整客户积分");
result.setRiskLevel(RiskLevel.SENSITIVE);
result.setReasonRequired(true);
result.setRequiredPhrase("确认调整积分 %+d".formatted(delta));
result.setPreviewText("""
### 待确认:人工调整积分
客户:%s(%s)
调整:%+d 积分
调整前:%d
调整后:%d
原因:%s
请回复“确认”执行,回复“取消”放弃。
""".formatted(customer.getName(), blank(customer.getCode()), delta, balance, balance + delta, remark));
return result;
}
private GaoAiPreparedOperation prepareRedemption(GaoAiOperationContext context, JsonNode arguments,
List<GaoAiAttachmentToken> attachments) {
if (attachments.isEmpty()) {
throw new GaoAiOperationException("ATTACHMENT_REQUIRED", "积分兑换必须上传照片");
}
GaoCustomer customer = support.customer(context.getStoreId(), arguments);
GaoPointRedeemSku redeemSku = support.redeemSku(context.getStoreId(), arguments);
BigDecimal quantity = support.requiredDecimal(arguments, "兑换数量", "quantity");
if (quantity.signum() <= 0) {
throw new GaoAiOperationException("VALIDATION_FAILED", "兑换数量必须大于 0");
}
if (quantity.stripTrailingZeros().scale() > 3) {
throw new GaoAiOperationException("VALIDATION_FAILED", "兑换数量最多保留三位小数");
}
if (redeemSku.getDefaultPointCost() == null) {
throw new GaoAiOperationException("VALIDATION_FAILED", "兑换配置缺少默认积分");
}
Long actualPointCost = support.optionalLong(arguments, "actualPointCost", "pointCost");
boolean override = actualPointCost != null;
if (override) {
authorizer.checkCode(context.getUserId(), GaoPermissionCode.POINT_REDEMPTION_POINT_ADJUST);
if (actualPointCost <= 0) {
throw new GaoAiOperationException("VALIDATION_FAILED", "实际扣除积分必须大于 0");
}
}
long defaultTotal;
try {
defaultTotal = BigDecimal.valueOf(redeemSku.getDefaultPointCost()).multiply(quantity)
.setScale(0, java.math.RoundingMode.UNNECESSARY).longValueExact();
} catch (ArithmeticException e) {
throw new GaoAiOperationException("VALIDATION_FAILED", "兑换数量与默认积分无法得到整数积分");
}
long finalTotal = override ? actualPointCost : defaultTotal;
GaoPointAccount account = pointAccountService.getByCustomerId(context.getStoreId(), customer.getId());
long balance = account == null ? 0L : account.getBalance();
if (balance < finalTotal) {
throw new GaoAiOperationException("VALIDATION_FAILED", "客户积分不足,当前 %d,需要 %d".formatted(balance, finalTotal));
}
String remark = support.text(arguments, "remark");
com.fasterxml.jackson.databind.node.ObjectNode normalized = support.normalizable(arguments);
normalized.put("customerId", customer.getId());
normalized.put("redeemSkuId", redeemSku.getId());
normalized.put("quantity", quantity.toPlainString());
if (actualPointCost != null) {
normalized.put("actualPointCost", actualPointCost);
}
Map<String, Object> preview = new LinkedHashMap<>();
preview.put("customer", support.customerBrief(customer));
preview.put("product", productName(redeemSku));
preview.put("quantity", quantity.toPlainString());
preview.put("defaultPointCost", defaultTotal);
preview.put("actualPointCost", finalTotal);
preview.put("balanceBefore", balance);
preview.put("balanceAfter", balance - finalTotal);
preview.put("attachmentCount", attachments.size());
GaoAiPreparedOperation result = new GaoAiPreparedOperation();
result.setArgumentsJson(normalized.toString());
result.setPreview(preview);
result.setTitle("客户积分兑换");
result.setRiskLevel(override ? RiskLevel.SENSITIVE : RiskLevel.NORMAL);
if (override) {
result.setReasonRequired(true);
result.setRequiredPhrase("确认以 %d 积分兑换".formatted(finalTotal));
}
result.setPreviewText("""
### 待确认:客户积分兑换
客户:%s(%s)
产品:%s
数量:%s
扣除积分:%d
积分余额:%d → %d
凭证:%d 张
请回复“确认”执行,回复“取消”放弃。
""".formatted(customer.getName(), blank(customer.getCode()), productName(redeemSku),
quantity.toPlainString(), finalTotal, balance, balance - finalTotal, attachments.size()));
return result;
}
private GaoAiCommitResult commitAdjust(GaoAiOperationContext context, GaoAiPendingOperation pending, JsonNode arguments) {
GaoPointAdjustRequest request = new GaoPointAdjustRequest();
request.setAdjustRequestId(pending.getRequestNo());
request.setStoreId(context.getStoreId());
request.setCustomerId(support.requiredText(arguments, "customerId"));
request.setPointDelta(support.requiredLong(arguments, "pointDelta"));
request.setRemark(support.requiredText(arguments, "remark", "reason"));
GaoPointLedger ledger = pointLedgerService.adjust(request, context.getUserId());
return GaoAiCommitResult.success(GaoAiOperation.POINT_ADJUST.name(), "POINT_LEDGER", ledger.getId(), null,
"已调整客户积分 %+d,当前余额 %d。".formatted(ledger.getPointDelta(), ledger.getBalanceAfter()));
}
private GaoAiCommitResult commitRedemption(GaoAiOperationContext context, GaoAiPendingOperation pending,
JsonNode arguments, List<Attachment> attachments) {
GaoPointRedemptionCreateRequest request = new GaoPointRedemptionCreateRequest();
request.setRequestNo(pending.getRequestNo());
request.setStoreId(context.getStoreId());
request.setCustomerId(support.requiredText(arguments, "customerId"));
request.setRedeemSkuId(support.requiredText(arguments, "redeemSkuId"));
request.setQuantity(support.requiredDecimal(arguments, "quantity"));
request.setActualPointCost(support.optionalLong(arguments, "actualPointCost", "pointCost"));
request.setAttachmentList(attachments);
request.setRemark(support.text(arguments, "remark"));
GaoPointRedemption redemption = redemptionService.create(request);
return GaoAiCommitResult.success(GaoAiOperation.POINT_REDEMPTION_CREATE.name(), "POINT_REDEMPTION",
redemption.getId(), null, "已完成积分兑换,扣除 %d 积分。".formatted(redemption.getActualPointCost()));
}
private String productName(GaoPointRedeemSku redeemSku) {
if (redeemSku.getSku() != null) {
return redeemSku.getSku().getName();
}
return redeemSku.getSkuId();
}
private String blank(String value) {
return value == null ? "-" : value;
}
}
@@ -0,0 +1,136 @@
package com.imyeyu.api.modules.gao.ai.operation.handler;
import com.fasterxml.jackson.databind.JsonNode;
import com.imyeyu.api.modules.common.entity.Attachment;
import com.imyeyu.api.modules.gao.ai.config.GaoAiProperties;
import com.imyeyu.api.modules.gao.ai.operation.GaoAiAttachmentToken;
import com.imyeyu.api.modules.gao.ai.operation.GaoAiCommitResult;
import com.imyeyu.api.modules.gao.ai.operation.GaoAiOperation;
import com.imyeyu.api.modules.gao.ai.operation.GaoAiOperationContext;
import com.imyeyu.api.modules.gao.ai.operation.GaoAiOperationDefinition;
import com.imyeyu.api.modules.gao.ai.operation.GaoAiOperationDefinition.RiskLevel;
import com.imyeyu.api.modules.gao.ai.operation.GaoAiOperationException;
import com.imyeyu.api.modules.gao.ai.operation.GaoAiOperationHandler;
import com.imyeyu.api.modules.gao.ai.operation.GaoAiOperationSupport;
import com.imyeyu.api.modules.gao.ai.operation.GaoAiPendingOperation;
import com.imyeyu.api.modules.gao.ai.operation.GaoAiPreparedOperation;
import com.imyeyu.api.modules.gao.entity.GaoProductSku;
import com.imyeyu.api.modules.gao.entity.GaoProductSkuUnit;
import com.imyeyu.api.modules.gao.entity.GaoProductStock;
import com.imyeyu.api.modules.gao.service.GaoProductStockService;
import com.imyeyu.api.modules.gao.vo.product.GaoProductSkuUnitSelection;
import com.imyeyu.api.modules.gao.vo.product.GaoProductStockChangeRequest;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;
import java.math.BigDecimal;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
/// 库存写操作处理器
///
/// @author Codex
/// @since 2026-11-23
@Component
@RequiredArgsConstructor
public class StockOperationHandler implements GaoAiOperationHandler {
private final GaoAiOperationSupport support;
private final GaoAiProperties properties;
private final GaoProductStockService stockService;
@Override
public Set<GaoAiOperation> supports() {
return Set.of(GaoAiOperation.STOCK_MANUAL_IN, GaoAiOperation.STOCK_MANUAL_OUT,
GaoAiOperation.STOCK_STOCKTAKE_GAIN, GaoAiOperation.STOCK_STOCKTAKE_LOSS);
}
@Override
public GaoAiPreparedOperation prepare(GaoAiOperationContext context, GaoAiOperationDefinition definition,
JsonNode arguments, List<GaoAiAttachmentToken> attachments) {
boolean purchase = definition.getOperation() == GaoAiOperation.STOCK_MANUAL_IN
|| definition.getOperation() == GaoAiOperation.STOCK_STOCKTAKE_GAIN;
GaoProductSkuUnitSelection selection = support.skuUnit(context.getStoreId(), arguments, purchase);
BigDecimal quantity = support.requiredDecimal(arguments, "数量", "quantity");
if (quantity.signum() <= 0) {
throw new GaoAiOperationException("VALIDATION_FAILED", "数量必须大于 0");
}
if (quantity.compareTo(BigDecimal.valueOf(properties.getStockChangeMaxQuantity())) > 0) {
throw new GaoAiOperationException("VALIDATION_FAILED", "单次库存变更数量不能超过 " + properties.getStockChangeMaxQuantity());
}
GaoProductSku sku = selection.getSku();
if (!Boolean.TRUE.equals(sku.getStockEnabled())) {
throw new GaoAiOperationException("VALIDATION_FAILED", "该 SKU 未启用库存管理");
}
String remark = support.requiredText(arguments, "库存操作备注", "remark", "reason");
GaoProductStock stock = stockService.detail(context.getStoreId(), sku.getId());
com.fasterxml.jackson.databind.node.ObjectNode normalized = support.normalizable(arguments);
normalized.put("skuId", sku.getId());
normalized.put("skuUnitId", selection.getUnit().getId());
normalized.put("quantity", quantity.toPlainString());
normalized.put("remark", remark);
Map<String, Object> preview = new LinkedHashMap<>();
preview.put("productName", selection.getProduct().getName());
preview.put("skuName", sku.getName());
preview.put("unitName", selection.getUnit().getName());
preview.put("quantity", quantity.toPlainString());
preview.put("onHandQuantity", stock == null ? "0" : stock.getOnHandQuantity().toPlainString());
preview.put("remark", remark);
preview.put("attachmentCount", attachments.size());
GaoAiPreparedOperation result = new GaoAiPreparedOperation();
result.setArgumentsJson(normalized.toString());
result.setPreview(preview);
result.setTitle(definition.title());
result.setRiskLevel(definition.getRiskLevel());
result.setPreviewText("""
### 待确认:%s
产品:%s / %s
数量:%s %s
当前库存:%s
备注:%s
凭证:%d 张
请回复“确认”执行,回复“取消”放弃。
""".formatted(definition.title(), selection.getProduct().getName(), blank(sku.getName()),
quantity.toPlainString(), selection.getUnit().getName(), preview.get("onHandQuantity"), remark,
attachments.size()));
if (definition.getRiskLevel() == RiskLevel.SENSITIVE) {
result.setRequiredPhrase("确认%s %s %s".formatted(definition.title(), quantity.toPlainString(),
selection.getUnit().getName()));
}
return result;
}
@Override
public GaoAiCommitResult commit(GaoAiOperationContext context, GaoAiPendingOperation pending,
JsonNode arguments, List<Attachment> attachments) {
GaoAiOperation operation = GaoAiOperation.valueOf(pending.getOperation());
GaoProductStockChangeRequest request = new GaoProductStockChangeRequest();
request.setRequestNo(pending.getRequestNo());
request.setStoreId(context.getStoreId());
request.setSkuId(support.requiredText(arguments, "skuId"));
request.setSkuUnitId(support.requiredText(arguments, "skuUnitId"));
request.setQuantity(support.requiredDecimal(arguments, "quantity"));
request.setOccurredAt(support.optionalLong(arguments, "occurredAt"));
request.setRemark(support.requiredText(arguments, "remark", "reason"));
request.setAttachmentList(attachments);
GaoProductStock stock = switch (operation) {
case STOCK_MANUAL_IN -> stockService.manualIn(request);
case STOCK_MANUAL_OUT -> stockService.manualOut(request);
case STOCK_STOCKTAKE_GAIN -> stockService.stocktakeGain(request);
case STOCK_STOCKTAKE_LOSS -> stockService.stocktakeLoss(request);
default -> throw new GaoAiOperationException("FEATURE_DISABLED", "不支持的操作");
};
return GaoAiCommitResult.success(operation.name(), "PRODUCT_STOCK", stock.getSkuId(), null,
"已完成%s,当前库存 %s。".formatted(operation.getTitle(), stock.getOnHandQuantity().toPlainString()));
}
private String blank(String value) {
return value == null ? "-" : value;
}
}

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