Compare commits

...
126 Commits
Author SHA1 Message Date
timi ebb9f633a4 Merge pull request 'v1.0.78' (#90) from dev into master
Reviewed-on: #90
2026-11-17 16:11:04 +00: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 264d5495e6 Merge pull request 'v1.0.77' (#89) from dev into master
Reviewed-on: #89
2026-11-17 15:43:30 +00: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 b800069c82 Merge pull request 'v1.0.76' (#88) from dev into master
Reviewed-on: #88
2026-11-17 08:40:24 +00: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 79059e7818 Merge pull request 'v1.0.75' (#87) from dev into master
Reviewed-on: #87
2026-11-17 07:56:50 +00: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 4b943e887d Merge pull request 'v1.0.74' (#86) from dev into master
Reviewed-on: #86
2026-11-17 06:55:28 +00: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 359eac8985 Merge pull request 'v1.0.73' (#85) from dev into master
Reviewed-on: #85
2026-11-17 06:27:05 +00: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 1531c2498b Merge pull request 'v1.0.72' (#84) from dev into master
Reviewed-on: #84
2026-11-17 03:55:12 +00: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 60e80dda87 Merge pull request 'v1.0.71' (#83) from dev into master
Reviewed-on: #83
2026-11-13 17:11:48 +00: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 445da5f093 Merge pull request 'v1.0.70' (#82) from dev into master
Reviewed-on: #82
2026-11-12 09:44:54 +00: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 b62c7f2495 Merge pull request 'v1.0.69' (#81) from dev into master
Reviewed-on: #81
2026-11-08 12:05:57 +00: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 2b7c94e7c3 Merge pull request 'v1.0.68' (#80) from dev into master
Reviewed-on: #80
2026-11-07 18:03:08 +00: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 470b586085 Merge pull request 'v1.0.67' (#79) from dev into master
Reviewed-on: #79
2026-11-06 16:05:40 +00: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 3d0f9b9d1b Merge pull request 'v1.0.66' (#78) from dev into master
Reviewed-on: #78
2026-11-06 15:59:05 +00: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 634de93ffe Merge pull request 'v1.0.65' (#77) from dev into master
Reviewed-on: #77
2026-11-06 15:37:24 +00: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 996830bec7 Merge pull request 'v1.0.64' (#76) from dev into master
Reviewed-on: #76
2026-10-29 17:23:25 +00: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 cd88f94277 Merge pull request 'v1.0.63' (#75) from dev into master
Reviewed-on: #75
2026-10-29 12:02:14 +00: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 47970cd8ff Merge pull request 'v1.0.62' (#74) from dev into master
Reviewed-on: #74
2026-10-27 16:58:56 +00: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 ada3fbf9cb Merge pull request 'v1.0.61' (#73) from dev into master
Reviewed-on: #73
2026-10-25 16:34:30 +00: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 f6c99bd262 Merge pull request 'v1.0.60' (#72) from dev into master
Reviewed-on: #72
2026-10-24 17:18:13 +00: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 1241f19c16 Merge pull request 'v1.0.59' (#71) from dev into master
Reviewed-on: #71
2026-10-20 17:36:26 +00: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 d7a7a88232 Merge pull request 'v1.0.58' (#70) from dev into master
Reviewed-on: #70
2026-10-15 17:34:02 +00: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 7743b1bab2 Merge pull request 'v1.0.57' (#69) from dev into master
Reviewed-on: #69
2026-10-05 08:10:57 +00: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 982b1ee3e4 Merge pull request 'v1.0.56' (#68) from dev into master
Reviewed-on: #68
2026-09-25 15:43:52 +00: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 05e28c2c6d Merge pull request 'v1.0.55' (#67) from dev into master
Reviewed-on: #67
2026-09-23 15:17:56 +00: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 c18d0e8a9f Merge pull request 'v1.0.54' (#66) from dev into master
Reviewed-on: #66
2026-09-22 17:09:48 +00: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 1b221b13d1 Merge pull request 'v1.0.53' (#65) from dev into master
Reviewed-on: #65
2026-09-21 17:32:02 +00: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 135996ce19 Merge pull request 'v1.0.52' (#64) from dev into master
Reviewed-on: #64
2026-09-20 17:22:39 +00: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 6b85cddede Merge pull request 'v1.0.51' (#63) from dev into master
Reviewed-on: #63
2026-09-18 17:27:14 +00: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 e486f850f2 Merge pull request 'v1.0.50' (#62) from dev into master
Reviewed-on: #62
2026-09-17 17:52:23 +00: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 76c2f3a5fd Merge pull request 'v1.0.49' (#61) from dev into master
Reviewed-on: #61
2026-09-16 17:34:23 +00: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
timi bb542e7510 Merge pull request 'v1.0.48' (#60) from dev into master
Reviewed-on: #60
2026-09-15 17:39:14 +00:00
Timi 6ac84c11b2 v1.0.48
CI / build-deploy (pull_request) Successful in 26s
CI / notify-on-failure (pull_request) Skipped
2026-09-16 01:34:19 +08:00
Timi 1192bee431 add AIAgent 2026-09-16 01:09:55 +08:00
Timi c77813af0d remove ./http 2026-09-15 11:00:14 +08:00
timi eba4461381 Merge pull request 'v1.0.47' (#59) from dev into master
Reviewed-on: #59
2026-09-14 17:30:09 +00:00
Timi aa7b83ed1e v1.0.47
CI / build-deploy (pull_request) Successful in 26s
CI / notify-on-failure (pull_request) Skipped
2026-09-15 01:25:48 +08:00
Timi ac310414fe add point redemption 2026-09-15 01:25:32 +08:00
343 changed files with 20733 additions and 2268 deletions
+1
View File
@@ -4,6 +4,7 @@
/target /target
/temp /temp
/AGENTS.md /AGENTS.md
/.workbuddy
multilingualField/ multilingualField/
!.mvn/wrapper/maven-wrapper.jar !.mvn/wrapper/maven-wrapper.jar
-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>
+115 -74
View File
@@ -1,34 +1,6 @@
# the name by which the project can be referenced within Serena # the name by which the project can be referenced within Serena/when chatting with the LLM.
project_name: "TimiServerAPI" 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 # 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 # For a list of possible encodings, see https://docs.python.org/3.11/library/codecs.html#standard-encodings
encoding: "utf-8" encoding: "utf-8"
@@ -50,12 +22,19 @@ ignore_all_files_in_gitignore: true
# advanced configuration option allowing to configure language server-specific options. # advanced configuration option allowing to configure language server-specific options.
# Maps the language key to the 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. # The settings are considered only if the project is trusted (see global configuration to define trusted projects).
# No documentation on options means no options are available. # See https://oraios.github.io/serena/02-usage/050_configuration.html#language-server-specific-settings
ls_specific_settings: {} ls_specific_settings: {}
# list of additional paths to ignore in this project. # list of additional paths to ignore in this project.
# Same syntax as gitignore, so you can use * and **. # Same syntax as gitignore, so you can use * and **.
# Important: quote patterns that start with `*`, otherwise YAML treats them as aliases.
# Example:
# ignored_paths:
# - "examples/**"
# - ".worktrees/**"
# - "**/bin/**"
# - "**/obj/**"
# Note: global ignored_paths from serena_config.yml are also applied additively. # Note: global ignored_paths from serena_config.yml are also applied additively.
ignored_paths: [] ignored_paths: []
@@ -66,54 +45,17 @@ read_only: false
# list of tool names to exclude. # list of tool names to exclude.
# This extends the existing exclusions (e.g. from the global configuration) # This extends the existing exclusions (e.g. from the global configuration)
# # Find the list of tools here: https://oraios.github.io/serena/01-about/035_tools.html
# 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: [] excluded_tools: []
# list of tools to include that would otherwise be disabled (particularly optional tools that are disabled by default). # 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). # This extends the existing inclusions (e.g. from the global configuration).
# Find the list of tools here: https://oraios.github.io/serena/01-about/035_tools.html
included_optional_tools: [] included_optional_tools: []
# fixed set of tools to use as the base tool set (if non-empty), replacing Serena's default set of 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. # This cannot be combined with non-empty excluded_tools or included_optional_tools.
# Find the list of tools here: https://oraios.github.io/serena/01-about/035_tools.html
fixed_tools: [] fixed_tools: []
# list of mode names to that are always to be included in the set of active modes # list of mode names to that are always to be included in the set of active modes
@@ -124,11 +66,14 @@ fixed_tools: []
# Set this to a list of mode names to always include the respective modes for this project. # Set this to a list of mode names to always include the respective modes for this project.
base_modes: base_modes:
# list of mode names that are to be activated by default. # list of mode names that are to be activated by default, overriding the setting in the global configuration.
# The full set of modes to be activated is base_modes + default_modes. # The full set of modes to be activated is base_modes (from global config) + default_modes + added_modes.
# If the setting is undefined, the default_modes from the global configuration (serena_config.yml) apply. # If the setting is undefined/empty, the default_modes from the global configuration (serena_config.yml) apply.
# Otherwise, this overrides the setting from the global configuration (serena_config.yml). # Otherwise, this overrides the setting from the global configuration (serena_config.yml).
# Therefore, you can set this to [] if you do not want the default modes defined in the global config to apply
# for this project.
# This setting can, in turn, be overridden by CLI parameters (--mode). # This setting can, in turn, be overridden by CLI parameters (--mode).
# See https://oraios.github.io/serena/02-usage/050_configuration.html#modes
default_modes: default_modes:
# initial prompt for the project. It will always be given to the LLM upon activating the project # initial prompt for the project. It will always be given to the LLM upon activating the project
@@ -152,3 +97,99 @@ read_only_memory_patterns: []
# Extends the list from the global configuration, merging the two lists. # Extends the list from the global configuration, merging the two lists.
# Example: ["_archive/.*", "_episodes/.*"] # Example: ["_archive/.*", "_episodes/.*"]
ignored_memory_patterns: [] ignored_memory_patterns: []
# list of language servers to start when using the LSP backend; choose from:
# ada al angular ansible astro
# bash bsl clojure cpp cpp_ccls
# crystal csharp csharp_omnisharp cue dart
# deno elixir elm erlang fortran
# fsharp gdscript gleam go groovy
# haskell haxe hlsl html java
# json julia julia_fatou kotlin latex
# lean4 lua lua_emmylua luau markdown
# matlab msl nextflow nix ocaml
# pascal perl php php_devsense php_phpactor
# php_phpantom powershell python python_basedpyright python_jedi
# python_pyrefly python_ty qml r rego
# ruby ruby_solargraph rust scala scss
# solidity svelte swift systemverilog terraform
# toml typescript typescript_tsgo typescript_vts vue
# vbnet wolfram yaml zig
# (This list may be outdated; generated with scripts/print_language_list.py;
# For the current list, see values of the LanguageServerId enum here:
# https://github.com/oraios/serena/blob/main/src/solidlsp/ls_config.py)
# For some languages, there are several alternative language servers, e.g. csharp_omnisharp, ruby_solargraph.)
# Note:
# - For C, use cpp
# - For JavaScript, use typescript
# - For Angular projects, use angular (subsumes typescript+html; requires `npm install` in the project root)
# - For Astro projects, use astro (subsumes typescript/javascript for .astro projects; requires npm)
# - For Svelte projects, use svelte (subsumes typescript/javascript for .svelte projects; requires npm)
# - For Deno projects, use deno (serves the same .ts/.js files as typescript; requires the deno CLI on PATH)
# - For SCSS / Sass / plain CSS, use scss (some-sass-language-server handles all three)
# - For Free Pascal/Lazarus, use pascal
# - External Python adapters may add further registered IDs; install the adapter package first
# and then use its ID here, for example: example
# Special requirements:
# Some language servers require additional setup/installations.
# See here for details: https://oraios.github.io/serena/01-about/020_programming-languages.html#language-servers
# When using multiple language servers, the first language server that supports a given file will be used for that file.
# The first language server 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.
language_servers:
- java
# list of mode names to be activated additionally for this project, e.g. ["query-projects"]
# The full set of modes to be activated is base_modes (from global config) + default_modes + added_modes.
# See https://oraios.github.io/serena/02-usage/050_configuration.html#modes
added_modes:
# list of workspace folder paths (LSP backend only).
# These folders will be used to build up Serena's symbol index.
# Paths must be within the project root and should thus be relative to the project root.
# Furthermore, the paths should not be filtered by ignore settings.
# Default setting: The entire project root folder (".") is considered.
# In (large) monorepos, this can be used to index only subfolders of the project root, e.g.
# ls_workspace_folders:
# - "./subproject1"
# - "./subproject2"
ls_workspace_folders:
- .
# list of additional workspace folder paths for cross-package reference support.
# Paths can be absolute or relative to the project root.
# Each folder is registered as an LSP workspace folder, enabling language servers to discover
# symbols and references across package boundaries, but these folders are not indexed by Serena,
# i.e. the respective symbols will not be found using Serena's symbol search tools.
# Example:
# additional_workspace_folders:
# - ../sibling-package
# - ../shared-lib
ls_additional_workspace_folders: []
# optional shell command to run before the language backend (LSP or JetBrains) is initialised.
# the command runs in the project root directory and is only executed if the project is trusted
# (see trusted_project_path_patterns in the global configuration).
# serena waits for the command to exit: a non-zero exit code is logged as an error but does not
# abort activation. a per-project timeout (activation_command_timeout, default 180s) is the safety
# backstop for non-terminating commands; on expiry the process is killed and activation continues.
# example: activation_command: "npx nx run-many -t build"
activation_command:
# maximum time in seconds to wait for activation_command to complete before killing it (default 180s).
# must be a positive number.
activation_command_timeout: 180.0
# list of APIs (facades or facade methods, e.g. "lsp" or "lsp.get_diagnostics_for_symbol") to include in the REPL
# that would otherwise be disabled (particularly optional methods, which are disabled by default).
# This extends the existing inclusions (e.g. from the global configuration).
included_apis: []
# list of APIs (facades or facade methods, e.g. "lsp" or "lsp.find_symbol") to exclude from the REPL.
# This extends the existing exclusions (e.g. from the global configuration).
excluded_apis: []
# The interface through which the agent (LLM) accesses Serena's functionality (overrides the global setting).
# Valid values: tools, REPL (see the global configuration for details); leave empty to use the global setting.
# Note: the interface is fixed at startup. If a project is activated post-init, its setting is not applied.
agent_interface:
-163
View File
@@ -1,163 +0,0 @@
# HTTP 调试与文档规范
本目录下的 `.http` 文件同时承担接口调试和接口文档职责,也要保证 AIAgent 能稳定读取
## 目录分工
### `.http`
`.http` 只描述接口级信息:
1. 接口中文名
2. 权限要求
3. 前置条件
4. 请求参数对应的对象说明
5. 返回参数对应的对象说明
`.http` 不重复展开对象字段明细,复杂字段、嵌套结构、枚举值统一写到 `./object` 下
### `./object`
`./object` 只描述对象级信息:
1. 字段名
2. 字段类型
3. 字段说明
4. 枚举值及含义
所有模块都可能复用的通用对象必须写在 `./object/common.md`
按业务领域拆分对象说明文件,例如:
1. `./object/common.md`
2. `./object/user.md`
3. `./object/role.md`
4. `./object/permission.md`
不要把同一个对象的字段说明散落到多个文件里
## 全局约定
### 返回包装
除使用 `IgnoreGlobalReturn` 跳过全局包装的方法外,接口默认都会经过
[GlobalReturnHandler](E:/IDEAProject/timi-spring/src/main/java/com/imyeyu/spring/util/GlobalReturnHandler.java)
统一包装返回
因此 `.http` 里的 `返回参数` 默认只描述业务 `data` 对象,不再重复赘述全局包装结构
全局返回包装、通用成功码、错误信息、常见分页壳子等内容统一维护在 `./object/common.md`
如果接口使用
[IgnoreGlobalReturn](E:/IDEAProject/timi-spring/src/main/java/com/imyeyu/spring/annotation/IgnoreGlobalReturn.java)
跳过全局包装,必须在对应接口的 `前置条件` 或补充说明里明确写出“该接口不走全局返回包装”
### 文档真实性
1. 文档只记录服务端真实行为
2. 不写猜测
3. 不写“看代码”
4. 接口改了就同步更新 `.http` 和 `./object`
### 变量复用
能复用的变量统一放在文件顶部,例如 `@user_token`、`@userId`
## `.http` 模板
每个接口块固定使用下面格式,不要擅自增删字段名:
```http
### <接口中文名>
### 权限:
### 前置条件:
### 请求参数:
### 返回参数:
POST {{baseUrl}}/path
Content-Type: application/json
Token: {{user_token}}
{}
```
## `.http` 填写要求
### 接口中文名
直接写接口用途,别写成控制器方法名
### 权限
1. 优先直接翻译控制器上的真实注解
2. 同时存在角色和权限时一起写,例如 `需要 ADMIN 角色 + USER_UPDATE 权限`
3. 只有 Token 要求时写 `需要有效 Token`
4. 无需登录时直接写 `无需登录`
### 前置条件
这里只写接口调用前必须知道的约束,例如:
1. 需要先登录并回填 `user_token`
2. 需要先创建用户再传入 `userId`
3. 重复调用可能因为唯一约束失败
4. 接口当前实现为空
5. 该接口不走全局返回包装
没有额外限制时写 `无`
### 请求参数
只写请求对象名和对象说明文件,不在 `.http` 内展开字段
推荐格式:
1. `无`
2. `UserCreateRequest,详见 ./object/user.md`
3. `Page<UserQuery>,详见 ./object/common.md 和 ./object/user.md`
### 返回参数
只写业务返回对象名和对象说明文件,不在 `.http` 内展开字段
推荐格式:
1. `无`
2. `User,详见 ./object/user.md`
3. `PageResult<User>,详见 ./object/common.md 和 ./object/user.md`
4. `二进制数据流,该接口不走全局返回包装`
## `./object` 编写要求
对象说明统一使用 Markdown 表格,推荐结构如下
```md
## User
| 字段 | 类型 | 说明 |
|---|---|---|
| name | String | 登录名,系统内唯一 |
## RoleCode
| 枚举 | 说明 |
|---|---|
| SYSTEM | 系统 |
| ADMIN | 管理员 |
```
### 对象说明规则
1. 一个对象一个标题,标题名必须和 `.http` 里引用的对象名一致
2. 字段说明只写真实存在且调用方需要关心的内容
3. 枚举单独列出,不要把枚举值混进普通字段表
4. 嵌套对象、列表元素对象也要有独立标题
5. 通用壳子对象统一写在 `./object/common.md`
## 维护要求
1. 一个控制器通常对应一个 `.http` 文件
2. 新增接口时,同步补齐对应 `.http`
3. 新增或修改对象字段时,同步更新对应 `./object/*.md`
4. 注释语言统一用中文
5. 示例请求优先保证可调试,其次才是看起来完整
-200
View File
@@ -1,200 +0,0 @@
### AttachmentController 接口测试
### 在 IDEA 中选择 dev 或 prod 环境后执行
@attachmentId =
@attachmentBizType = TEMP_FILE
@attachmentBizId = demo-biz-id
@attachmentAttachType = SOURCE
@attachmentName = demo.png
@attachmentFilePath = E:/Temp/demo.png
@attachmentTempFileId =
### 查询附件详情
### 前置条件:`id` 必须传有效附件 ID
### 请求参数:URL 参数 `id` 为附件 ID
### 返回参数:Attachment,详见 ./object/common.md
POST {{baseUrl}}/attach/detail?id={{attachmentId}}
Token: {{user_token}}
### 创建附件
### 前置条件:回填 `attachmentFilePath` 为本地文件绝对路径
### 请求参数:multipart/form-data
### 返回参数:Attachment,详见 ./object/common.md
POST {{baseUrl}}/attach/create
Content-Type: multipart/form-data; boundary=AttachmentCreateBoundary
Token: {{user_token}}
--AttachmentCreateBoundary
Content-Disposition: form-data; name="bizType"
{{attachmentBizType}}
--AttachmentCreateBoundary
Content-Disposition: form-data; name="bizId"
{{attachmentBizId}}
--AttachmentCreateBoundary
Content-Disposition: form-data; name="attachType"
{{attachmentAttachType}}
--AttachmentCreateBoundary
Content-Disposition: form-data; name="name"
{{attachmentName}}
--AttachmentCreateBoundary
Content-Disposition: form-data; name="file"; filename="demo.png"
Content-Type: application/octet-stream
< {{attachmentFilePath}}
--AttachmentCreateBoundary--
### 更新附件元数据
### 前置条件:`id` 必须传有效附件 ID
### 请求参数:multipart/form-data
### 返回参数:无
POST {{baseUrl}}/attach/update
Content-Type: multipart/form-data; boundary=AttachmentUpdateMetaBoundary
Token: {{user_token}}
--AttachmentUpdateMetaBoundary
Content-Disposition: form-data; name="id"
{{attachmentId}}
--AttachmentUpdateMetaBoundary
Content-Disposition: form-data; name="name"
{{attachmentName}}-updated
--AttachmentUpdateMetaBoundary
Content-Disposition: form-data; name="attachType"
{{attachmentAttachType}}
--AttachmentUpdateMetaBoundary--
### 更新附件文件
### 前置条件:`id` 必须传有效附件 ID,`attachmentFilePath` 必须传本地文件绝对路径
### 请求参数:multipart/form-data
### 返回参数:无
POST {{baseUrl}}/attach/update
Content-Type: multipart/form-data; boundary=AttachmentUpdateFileBoundary
Token: {{user_token}}
--AttachmentUpdateFileBoundary
Content-Disposition: form-data; name="id"
{{attachmentId}}
--AttachmentUpdateFileBoundary
Content-Disposition: form-data; name="name"
{{attachmentName}}-file-updated
--AttachmentUpdateFileBoundary
Content-Disposition: form-data; name="file"; filename="demo.png"
Content-Type: application/octet-stream
< {{attachmentFilePath}}
--AttachmentUpdateFileBoundary--
### 删除附件
### 前置条件:`id` 必须传有效附件 ID
### 请求参数:URL 参数 `id` 为附件 ID
### 返回参数:无
POST {{baseUrl}}/attach/delete?id={{attachmentId}}
Token: {{user_token}}
### 按业务查询单个附件
### 前置条件:`bizType` 和 `bizId` 必须传有效值
### 请求参数:URL 参数 `bizType`、`bizId`
### 返回参数:Attachment,详见 ./object/common.md
GET {{baseUrl}}/attach/detail/byBiz?bizType={{attachmentBizType}}&bizId={{attachmentBizId}}
Token: {{user_token}}
### 按业务和附件类型查询单个附件
### 前置条件:`bizType`、`bizId`、`attachType` 必须传有效值
### 请求参数:URL 参数 `bizType`、`bizId`、`attachType`
### 返回参数:Attachment,详见 ./object/common.md
GET {{baseUrl}}/attach/detail/byAttachType?bizType={{attachmentBizType}}&bizId={{attachmentBizId}}&attachType={{attachmentAttachType}}
Token: {{user_token}}
### 按业务查询附件列表
### 前置条件:`bizType` 和 `bizId` 必须传有效值
### 请求参数:URL 参数 `bizType`、`bizId`,可重复传 `attachTypeList`
### 返回参数:Attachment[]
GET {{baseUrl}}/attach/list/byBiz?bizType={{attachmentBizType}}&bizId={{attachmentBizId}}&attachTypeList={{attachmentAttachType}}
Token: {{user_token}}
### 按业务统计附件数量
### 前置条件:`bizType` 和 `bizId` 必须传有效值
### 请求参数:URL 参数 `bizType`、`bizId`,可重复传 `attachTypeList`
### 返回参数:number
GET {{baseUrl}}/attach/count/byBiz?bizType={{attachmentBizType}}&bizId={{attachmentBizId}}&attachTypeList={{attachmentAttachType}}
Token: {{user_token}}
### 按业务分页查询附件
### 前置条件:`bizType` 和 `bizId` 必须传有效值
### 请求参数:URL 参数 `bizType`、`bizId`,可重复传 `attachTypeList`,请求体为 Page
### 返回参数:PageResult<Attachment>
POST {{baseUrl}}/attach/page/byBiz?bizType={{attachmentBizType}}&bizId={{attachmentBizId}}&attachTypeList={{attachmentAttachType}}
Content-Type: application/json
Token: {{user_token}}
{
"index": 0,
"size": 10
}
### 按业务差分更新附件
### 前置条件:新增项需要传有效 `tempFileId`
### 请求参数:BizUpdateReq
### 返回参数:无
POST {{baseUrl}}/attach/update/byBiz
Content-Type: application/json
Token: {{user_token}}
{
"bizType": "{{attachmentBizType}}",
"bizId": "{{attachmentBizId}}",
"items": [
{
"id": "{{attachmentId}}",
"attachType": "{{attachmentAttachType}}",
"name": "{{attachmentName}}-biz-updated"
},
{
"tempFileId": "{{attachmentTempFileId}}",
"attachType": "{{attachmentAttachType}}",
"name": "{{attachmentName}}-from-temp"
}
]
}
### 按业务删除全部附件
### 前置条件:`bizType` 和 `bizId` 必须传有效值
### 请求参数:BizDeleteReq
### 返回参数:无
POST {{baseUrl}}/attach/delete/byBiz
Content-Type: application/json
Token: {{user_token}}
{
"bizType": "{{attachmentBizType}}",
"bizId": "{{attachmentBizId}}"
}
### 读取附件原图
### 前置条件:`attachmentId` 必须传有效附件 ID
### 请求参数:路径参数 `id`
### 返回参数:附件二进制流
GET {{baseUrl}}/attach/read/{{attachmentId}}
Token: {{user_token}}
### 读取附件缩略图
### 前置条件:`attachmentId` 必须传有效图片或视频附件 ID
### 请求参数:路径参数 `id`,URL 参数 `thumbWidth`、`thumbHeight`
### 返回参数:附件二进制流
GET {{baseUrl}}/attach/read/{{attachmentId}}?thumbWidth=200&thumbHeight=200
Token: {{user_token}}
### 下载附件
### 前置条件:`attachmentId` 必须传有效附件 ID
### 请求参数:路径参数 `id`
### 返回参数:附件二进制流
GET {{baseUrl}}/attach/download/{{attachmentId}}
Token: {{user_token}}
-66
View File
@@ -1,66 +0,0 @@
### MultilingualController 接口测试
### 在 IDEA 中选择 dev 或 prod 环境后执行
@multilingualId =
@multilingualZhCN = 测试简体中文
@multilingualZhTW = 測試繁體中文
@multilingualEnUS = Test English
@multilingualRuRU = Тест
@multilingualJaJP = テスト
@multilingualDeDE = Test Deutsch
@multilingualKoKR = 테스트
### 查询多语言详情
### 权限:需要 ADMIN 角色 + MULTILINGUAL_READ 权限
### 前置条件:需要先登录并回填 `user_token`,URL 参数 `id` 必须传有效多语言 ID
### 请求参数:无请求体,URL 参数:`id` 为多语言 ID
### 返回参数:Multilingual,详见 ./object/common.md
POST {{baseUrl}}/system/multilingual/detail?id={{multilingualId}}
Token: {{user_token}}
### 创建多语言
### 权限:需要 ADMIN 角色 + MULTILINGUAL_CREATE 权限
### 前置条件:需要先登录并回填 `user_token`
### 请求参数:Multilingual,详见 ./object/common.md
### 返回参数:Multilingual,详见 ./object/common.md
POST {{baseUrl}}/system/multilingual/create
Content-Type: application/json
Token: {{user_token}}
{
"zhCN": "{{multilingualZhCN}}",
"zhTW": "{{multilingualZhTW}}",
"enUS": "{{multilingualEnUS}}",
"ruRU": "{{multilingualRuRU}}",
"jaJP": "{{multilingualJaJP}}",
"deDE": "{{multilingualDeDE}}",
"koKR": "{{multilingualKoKR}}"
}
### 更新多语言
### 权限:需要 ADMIN 角色 + MULTILINGUAL_UPDATE 权限
### 前置条件:需要先登录并回填 `user_token`,`id` 必须存在
### 请求参数:Multilingual,详见 ./object/common.md
### 返回参数:无
POST {{baseUrl}}/system/multilingual/update
Content-Type: application/json
Token: {{user_token}}
{
"id": "{{multilingualId}}",
"zhCN": "{{multilingualZhCN}}-已更新",
"zhTW": "{{multilingualZhTW}}-已更新",
"enUS": "{{multilingualEnUS}}-updated",
"ruRU": "{{multilingualRuRU}}-updated",
"jaJP": "{{multilingualJaJP}}-updated",
"deDE": "{{multilingualDeDE}}-updated",
"koKR": "{{multilingualKoKR}}-updated"
}
### 删除多语言
### 权限:需要 ADMIN 角色 + MULTILINGUAL_DELETE 权限
### 前置条件:需要先登录并回填 `user_token`,URL 参数 `id` 必须传有效多语言 ID
### 请求参数:无请求体,URL 参数:`id` 为多语言 ID
### 返回参数:无
POST {{baseUrl}}/system/multilingual/delete?id={{multilingualId}}
Token: {{user_token}}
-60
View File
@@ -1,60 +0,0 @@
### GaoRegisterAction 接口测试
### 在 IDEA 中选择 dev 或 prod 环境后执行
@actionId =
### 分页查询登记行为
POST {{baseUrl}}/gao/action/list
Content-Type: application/json
Token: {{user_token}}
{
"index": 0,
"size": 16
}
### 查询启用行为
POST {{baseUrl}}/gao/action/enabled/list
Token: {{user_token}}
### 查询行为详情
POST {{baseUrl}}/gao/action/detail?id={{actionId}}
Token: {{user_token}}
### 创建登记行为
POST {{baseUrl}}/gao/action/create
Content-Type: application/json
Token: {{user_token}}
{
"name": "签到",
"description": "客户到店签到",
"enabled": true,
"requirePhoto": false,
"sort": 10,
"permissionCodeList": [
"RECORD:CREATE"
]
}
### 更新登记行为
POST {{baseUrl}}/gao/action/update
Content-Type: application/json
Token: {{user_token}}
{
"id": "{{actionId}}",
"name": "物品领取",
"description": "登记客户领取物品",
"enabled": true,
"requirePhoto": true,
"sort": 20,
"permissionCodeList": [
"RECORD:CREATE",
"STAT:READ"
]
}
### 删除登记行为
POST {{baseUrl}}/gao/action/delete?id={{actionId}}
Token: {{user_token}}
-119
View File
@@ -1,119 +0,0 @@
### GaoCustomer 接口测试
### 在 IDEA 中选择 dev 或 prod 环境后执行
@customerId =
@introducerCustomerId =
@customerCode = GAO-0001
### 分页查询客户
POST {{baseUrl}}/gao/customer/list
Content-Type: application/json
Token: {{user_token}}
{
"index": 0,
"size": 16
}
### 搜索客户
POST {{baseUrl}}/gao/customer/search
Content-Type: application/json
Token: {{user_token}}
{
"keyword": "张",
"introducerCustomerId": "{{introducerCustomerId}}"
}
### 查询客户详情
POST {{baseUrl}}/gao/customer/detail?id={{customerId}}
Token: {{user_token}}
### 按客户编码查询
POST {{baseUrl}}/gao/customer/detail/code?code={{customerCode}}
Token: {{user_token}}
### 查询某客户邀请了哪些人
POST {{baseUrl}}/gao/customer/invited/list?introducerCustomerId={{customerId}}
Token: {{user_token}}
### 创建客户
POST {{baseUrl}}/gao/customer/create
Content-Type: application/json
Token: {{user_token}}
{
"code": "{{customerCode}}",
"name": "张三",
"age": 56,
"telephone": "020-88886666",
"address": "广州市天河区某街道",
"remark": "首诊客户",
"disease": "肩颈不适",
"conditioningPart": [
{
"code": "neck",
"name": "颈部"
},
{
"code": "shoulder",
"name": "肩部"
}
],
"introducerCustomerId": "{{introducerCustomerId}}"
}
### 更新客户
POST {{baseUrl}}/gao/customer/update
Content-Type: application/json
Token: {{user_token}}
{
"id": "{{customerId}}",
"code": "{{customerCode}}",
"name": "张三",
"age": 57,
"telephone": "020-88886667",
"address": "广州市天河区某街道 88 号",
"remark": "复诊客户",
"disease": "腰背调理",
"conditioningPart": {
"parts": [
"waist",
"back"
]
},
"introducerCustomerId": "{{introducerCustomerId}}"
}
### 删除客户
POST {{baseUrl}}/gao/customer/delete?id={{customerId}}
Token: {{user_token}}
### 创建客户邀请关系
POST {{baseUrl}}/gao/customer/invite/create
Content-Type: application/json
Token: {{user_token}}
{
"customerId": "{{customerId}}",
"introducerCustomerId": "{{introducerCustomerId}}"
}
### 查询客户邀请关系详情
POST {{baseUrl}}/gao/customer/invite/detail?customerId={{customerId}}
Token: {{user_token}}
### 更新客户邀请关系
POST {{baseUrl}}/gao/customer/invite/update
Content-Type: application/json
Token: {{user_token}}
{
"customerId": "{{customerId}}",
"introducerCustomerId": "{{introducerCustomerId}}"
}
### 删除客户邀请关系
POST {{baseUrl}}/gao/customer/invite/delete?customerId={{customerId}}
Token: {{user_token}}
-86
View File
@@ -1,86 +0,0 @@
### GaoRegisterRecord 接口测试
### 在 IDEA 中选择 dev 或 prod 环境后执行
@recordId =
@customerId =
@customerCode = GAO-0001
@actionId =
### 分页查询登记记录
POST {{baseUrl}}/gao/record/list
Content-Type: application/json
Token: {{user_token}}
{
"index": 0,
"size": 16
}
### 查询登记记录详情
POST {{baseUrl}}/gao/record/detail?id={{recordId}}
Token: {{user_token}}
### 创建登记记录,直接传客户 ID
POST {{baseUrl}}/gao/record/create
Content-Type: application/json
Token: {{user_token}}
{
"customerId": "{{customerId}}",
"actionId": "{{actionId}}",
"remark": "客户到店签到"
}
### 创建登记记录,扫码后传客户编码
POST {{baseUrl}}/gao/record/create
Content-Type: application/json
Token: {{user_token}}
{
"customerCode": "{{customerCode}}",
"actionId": "{{actionId}}",
"remark": "扫码快速登记"
}
### 更新登记记录
POST {{baseUrl}}/gao/record/update
Content-Type: application/json
Token: {{user_token}}
{
"id": "{{recordId}}",
"customerId": "{{customerId}}",
"actionId": "{{actionId}}",
"remark": "补充备注",
"registeredAt": 1785110400
}
### 删除登记记录
POST {{baseUrl}}/gao/record/delete?id={{recordId}}
Token: {{user_token}}
### 按日查询某个行为记录
POST {{baseUrl}}/gao/record/period/list
Content-Type: application/json
Token: {{user_token}}
{
"actionId": "{{actionId}}",
"periodType": "DAY",
"periodValue": 20260727
}
### 按月统计某个行为记录
POST {{baseUrl}}/gao/record/period/stat
Content-Type: application/json
Token: {{user_token}}
{
"actionId": "{{actionId}}",
"periodType": "MONTH",
"periodValue": 202607
}
### 查询客户所有登记统计
POST {{baseUrl}}/gao/record/customer/stat?customerId={{customerId}}
Token: {{user_token}}
-8
View File
@@ -1,8 +0,0 @@
{
"dev": {
"baseUrl": "http://localhost:8091"
},
"prod": {
"baseUrl": "https://api.example.com"
}
}
-77
View File
@@ -1,77 +0,0 @@
# 通用对象说明
## TimiResponse<T>
| 字段 | 类型 | 说明 |
|---|---|---|
| code | Integer | 响应码,`20000` 为成功 |
| msg | String | 响应消息 |
| data | T | 业务数据体,具体结构由接口返回对象决定 |
## Page<T>
| 字段 | 类型 | 说明 |
|---|---|---|
| index | int | 页码下标,从 `0` 开始 |
| size | long | 每页数量 |
| equalsExample | T | 精确匹配示例对象,非空字段参与精确查询 |
| likesExample | T | 模糊匹配示例对象,非空字段参与模糊查询 |
| equalsLogic | Logic | 精确匹配字段之间的连接逻辑,默认 `AND` |
| likesLogic | Logic | 模糊匹配字段之间的连接逻辑,默认 `OR` |
| orderMap | LinkedHashMap<String, OrderType> | 排序字段映射,键通常为字段名,值为排序方向 |
## PageResult<T>
| 字段 | 类型 | 说明 |
|---|---|---|
| total | long | 总数据量 |
| pages | int | 总页数 |
| list | List<T> | 当前页数据列表 |
## UUIDEntity
| 字段 | 类型 | 说明 |
|---|---|---|
| id | String | 主键 ID,UUID 字符串 |
| createdAt | Long | 创建时间,Unix 时间戳毫秒 |
| updatedAt | Long | 更新时间,Unix 时间戳毫秒 |
| deletedAt | Long | 删除时间,Unix 时间戳毫秒,未删除时通常为空 |
## Multilingual
| 字段 | 类型 | 说明 |
|---|---|---|
| id | String | 多语言 ID |
| zhCN | String | 简体中文文本 |
| zhTW | String | 繁体中文文本 |
| enUS | String | 英文文本 |
| ruRU | String | 俄文文本 |
| jaJP | String | 日文文本 |
| deDE | String | 德文文本 |
| koKR | String | 韩文文本 |
| lastAccessAt | Long | 最后访问时间,Unix 时间戳毫秒 |
| createdAt | Long | 创建时间,Unix 时间戳毫秒 |
| updatedAt | Long | 更新时间,Unix 时间戳毫秒 |
| deletedAt | Long | 删除时间,Unix 时间戳毫秒,未删除时通常为空 |
## Logic
| 枚举 | 说明 |
|---|---|
| AND | 多个条件同时满足 |
| OR | 多个条件满足其一 |
## OrderType
| 枚举 | 说明 |
|---|---|
| ASC | 升序 |
| DESC | 降序 |
## ImageType
| 枚举 | 说明 |
|---|---|
| AUTO | 双线性 |
| SMOOTH | 模糊 |
| PIXELATED | 像素 |
-31
View File
@@ -1,31 +0,0 @@
# 权限对象说明
## Permission
| 字段 | 类型 | 说明 |
|---|---|---|
| id | String | 权限 ID |
| createdAt | Long | 创建时间,Unix 时间戳毫秒 |
| updatedAt | Long | 更新时间,Unix 时间戳毫秒 |
| deletedAt | Long | 删除时间,Unix 时间戳毫秒 |
| code | String | 权限代码,需与数据库 `permission.code` 保持一致 |
| nameLangId | String | 权限名称的多语言键 |
| description | String | 权限说明 |
| name | String | 当前语言下的权限名称 |
## BatchCreateReq
| 字段 | 类型 | 说明 |
|---|---|---|
| prefixCode | String | 权限代码前缀,例如 `ROLE` |
| prefixName | String | 权限名称前缀,例如 `角色` |
| types | Type[] | 需要批量生成的权限类型列表,详见 `BatchCreateType` |
## BatchCreateType
| 枚举 | 说明 |
|---|---|
| CREATE | 创建权限 |
| READ | 读取权限 |
| UPDATE | 更新权限 |
| DELETE | 删除权限 |
-34
View File
@@ -1,34 +0,0 @@
# 角色对象说明
## Role
| 字段 | 类型 | 说明 |
|---|---|---|
| id | String | 角色 ID |
| createdAt | Long | 创建时间,Unix 时间戳毫秒 |
| updatedAt | Long | 更新时间,Unix 时间戳毫秒 |
| deletedAt | Long | 删除时间,Unix 时间戳毫秒 |
| code | String | 角色代码,常见值见 `RoleCode` |
| nameLangId | String | 角色名称的多语言键 |
| description | String | 角色说明 |
| name | String | 当前语言下的角色名称 |
| permissionList | List<Permission> | 角色自身直接绑定的权限列表 |
| allPermissionList | List<Permission> | 角色全部权限列表,包含继承自子角色的权限 |
| childRoleList | List<Role> | 子角色列表 |
| permissionIdList | Set<String> | 权限 ID 列表,创建或更新角色时使用 |
| childRoleIdList | Set<String> | 子角色 ID 列表,创建或更新角色时使用 |
## UserRoleAuthorizeReq
| 字段 | 类型 | 说明 |
|---|---|---|
| userId | String | 目标用户 ID |
| roleIdList | List<String> | 需要授权的角色 ID 列表 |
| roleCodeList | List<String> | 需要授权的角色代码列表 |
## RoleCode
| 枚举 | 说明 |
|---|---|
| SYSTEM | 系统 |
| ADMIN | 管理员 |
-73
View File
@@ -1,73 +0,0 @@
# 用户对象说明
## User
| 字段 | 类型 | 说明 |
|---|---|---|
| id | String | 用户 ID |
| createdAt | Long | 创建时间,Unix 时间戳毫秒 |
| updatedAt | Long | 更新时间,Unix 时间戳毫秒 |
| deletedAt | Long | 删除时间,Unix 时间戳毫秒 |
| name | String | 登录名,系统内唯一 |
| nick | String | 用户昵称 |
| password | String | 明文密码,请求时填写,响应通常不返回 |
| email | String | 邮箱地址 |
| emailVerifyAt | Long | 邮箱验证时间,Unix 时间戳毫秒 |
| phoneNo | String | 手机号,11 位大陆手机号 |
| phoneNoVerifyAt | Long | 手机号验证时间,Unix 时间戳毫秒 |
| wrapperType | ImageType | 背景图渲染算法,详见 `ImageType` |
| avatarType | ImageType | 头像渲染算法,详见 `ImageType` |
| exp | Integer | 经验值 |
| sex | Integer | 性别,当前代码未定义枚举说明 |
| birthdate | Long | 出生日期,Unix 时间戳毫秒 |
| qq | String | QQ 号 |
| description | String | 个人说明 |
| lastLoginIP | String | 上次登录 IP |
| lastLoginAt | Long | 上次登录时间,Unix 时间戳毫秒 |
| unmuteAt | Long | 解除禁言时间,Unix 时间戳毫秒 |
| unbanAt | Long | 解除封禁时间,Unix 时间戳毫秒 |
| roleList | List<String> | 角色代码列表 |
| permissionList | List<String> | 权限代码列表 |
| attachmentList | List<Attachment> | 附件列表 |
| settingList | List<Setting> | 设置列表 |
## LoginRequest
| 字段 | 类型 | 说明 |
|---|---|---|
| user | String | 用户标识,可能是 UID、邮箱或用户名 |
| password | String | 明文密码 |
## LoginResponse
| 字段 | 类型 | 说明 |
|---|---|---|
| token | String | 登录令牌 |
| expireAt | Long | 令牌过期时间,Unix 时间戳毫秒 |
| user | User | 当前登录用户 |
## UpdatePasswordRequest
| 字段 | 类型 | 说明 |
|---|---|---|
| oldValue | String | 原密码 |
| newValue | String | 新密码 |
## PhoneVerifyCodeSendRequest
| 字段 | 类型 | 说明 |
|---|---|---|
| phoneNo | String | 手机号,必须为 11 位大陆手机号 |
## PhoneVerifyRequest
| 字段 | 类型 | 说明 |
|---|---|---|
| phoneNo | String | 手机号,必须为 11 位大陆手机号 |
| verifyCode | String | 6 位数字验证码 |
## CancelRequest
| 字段 | 类型 | 说明 |
|---|---|---|
| password | String | 当前密码,用于确认注销 |
-84
View File
@@ -1,84 +0,0 @@
### PermissionController 接口测试
### 在 IDEA 中选择 dev 或 prod 环境后执行
@user_token =
@permissionId =
@permissionCode = TEST_PERMISSION
@permissionNameLangId = permission.test.name
@permissionDescription = 测试权限
@moduleCode = CORE
### 分页查询权限
### 权限:需要 PERMISSION_READ 权限
### 前置条件:需要先登录并回填 `user_token`
### 请求参数:Page<Permission>,详见 ./http/object/permission.md
### 返回参数:PageResult<Permission>,详见 ./http/object/permission.md
POST {{baseUrl}}/user/permission/list
Content-Type: application/json
Token: {{user_token}}
{
"index": 0,
"size": 10,
"likesExample": {
"code": "{{permissionCode}}",
"moduleCode": "{{moduleCode}}"
}
}
### 创建权限
### 权限:当前代码要求 PERMISSION_READ 权限
### 前置条件:需要先登录并回填 `user_token`
### 请求参数:Permission,详见 ./http/object/permission.md
### 返回参数:无
POST {{baseUrl}}/user/permission/create
Content-Type: application/json
Token: {{user_token}}
{
"moduleCode": "{{moduleCode}}",
"code": "{{permissionCode}}",
"nameLangId": "{{permissionNameLangId}}",
"description": "{{permissionDescription}}"
}
### 批量创建权限
### 权限:需要 PERMISSION_CREATE 权限
### 前置条件:需要先登录并回填 `user_token`
### 请求参数:BatchCreateReq,详见 ./http/object/permission.md
### 返回参数:无
POST {{baseUrl}}/user/permission/create/batch
Content-Type: application/json
Token: {{user_token}}
{
"moduleCode": "{{moduleCode}}",
"prefixCode": "ROLE",
"prefixName": "角色",
"types": ["CREATE", "READ", "UPDATE", "DELETE"]
}
### 更新权限
### 权限:需要 PERMISSION_UPDATE 权限
### 前置条件:需要先登录并回填 `user_token`,`id` 必须存在
### 请求参数:Permission,详见 ./http/object/permission.md
### 返回参数:无
POST {{baseUrl}}/user/permission/update
Content-Type: application/json
Token: {{user_token}}
{
"id": "{{permissionId}}",
"moduleCode": "{{moduleCode}}",
"code": "{{permissionCode}}",
"nameLangId": "{{permissionNameLangId}}",
"description": "测试权限-已更新"
}
### 删除权限
### 权限:需要 PERMISSION_DELETE 权限
### 前置条件:需要先登录并回填 `user_token`,URL 参数 `id` 必须传有效权限 ID
### 请求参数:无请求体,URL 参数:`id` 为权限 ID
### 返回参数:无
POST {{baseUrl}}/user/permission/delete?id={{permissionId}}
Token: {{user_token}}
-113
View File
@@ -1,113 +0,0 @@
### RoleController 接口测试
### 在 IDEA 中选择 dev 或 prod 环境后执行
@permissionId =
@roleId =
@roleCode = TEST_ROLE
@roleNameLangId = role.test.name
@roleDescription = 测试角色
@childRoleId =
@authorizedUserId =
@moduleCode = CORE
### 分页查询角色
### 权限:需要 ADMIN 角色 + ROLE_READ 权限
### 前置条件:需要先登录并回填 `user_token`
### 请求参数:Page<Role>,详见 ./http/object/role.md
### 返回参数:PageResult<Role>,详见 ./http/object/role.md
POST {{baseUrl}}/user/role/list
Content-Type: application/json
Token: {{user_token}}
{
"index": 0,
"size": 16,
"likesExample": {
"moduleCode": "{{moduleCode}}"
}
}
### 查询角色详情
### 权限:需要 ADMIN 角色 + ROLE_READ 权限
### 前置条件:需要先登录并回填 `user_token`,URL 参数 `id` 必须传有效角色 ID
### 请求参数:无请求体,URL 参数:`id` 为角色 ID
### 返回参数:Role,详见 ./http/object/role.md
POST {{baseUrl}}/user/role/detail?id={{roleId}}
Token: {{user_token}}
### 创建角色
### 权限:需要 ADMIN 角色 + ROLE_CREATE 权限
### 前置条件:需要先登录并回填 `user_token`
### 请求参数:Role,详见 ./http/object/role.md
### 返回参数:无
POST {{baseUrl}}/user/role/create
Content-Type: application/json
Token: {{user_token}}
{
"moduleCode": "{{moduleCode}}",
"code": "{{roleCode}}",
"nameLangId": "{{roleNameLangId}}",
"description": "{{roleDescription}}",
"permissionIdList": ["{{permissionId}}"],
"childRoleIdList": []
}
### 更新角色
### 权限:需要 ADMIN 角色 + ROLE_UPDATE 权限
### 前置条件:需要先登录并回填 `user_token`,`id` 必须存在
### 请求参数:Role,详见 ./http/object/role.md
### 返回参数:无
POST {{baseUrl}}/user/role/update
Content-Type: application/json
Token: {{user_token}}
{
"id": "{{roleId}}",
"moduleCode": "{{moduleCode}}",
"code": "{{roleCode}}",
"nameLangId": "{{roleNameLangId}}",
"description": "测试角色-已更新",
"permissionIdList": ["{{permissionId}}"],
"childRoleIdList": ["{{childRoleId}}"]
}
### 删除角色
### 权限:需要 ADMIN 角色 + ROLE_DELETE 权限
### 前置条件:需要先登录并回填 `user_token`,URL 参数 `id` 必须传有效角色 ID
### 请求参数:无请求体,URL 参数:`id` 为角色 ID
### 返回参数:无
POST {{baseUrl}}/user/role/delete?id={{roleId}}
Token: {{user_token}}
### 查询用户角色
### 权限:需要 ADMIN 角色 + USER_ROLE_READ 权限
### 前置条件:需要先登录并回填 `user_token`,URL 参数 `userId` 必须传有效用户 ID
### 请求参数:无请求体,URL 参数:`userId` 为用户 ID
### 返回参数:List<Role>,详见 ./http/object/role.md
POST {{baseUrl}}/user/role/authorized/list?userId={{authorizedUserId}}
Token: {{user_token}}
### 设置用户角色
### 权限:需要 ADMIN 角色 + 同时具备 USER_ROLE_CREATE 和 USER_ROLE_DELETE 权限
### 前置条件:需要先登录并回填 `user_token`
### 请求参数:UserRoleAuthorizeReq,详见 ./http/object/role.md
### 返回参数:无
POST {{baseUrl}}/user/role/authorized/create
Content-Type: application/json
Token: {{user_token}}
{
"userId": "{{authorizedUserId}}",
"moduleCode": "{{moduleCode}}",
"roleIdList": ["{{roleId}}"],
"roleCodeList": ["{{roleCode}}"]
}
### 查询用户已授权权限
### 权限:需要 ADMIN 角色 + USER_ROLE_READ 权限
### 前置条件:需要先登录并回填 `user_token`,URL 参数 `userId` 必须传有效用户 ID
### 请求参数:无请求体,URL 参数:`userId` 为用户 ID
### 返回参数:List<Permission>,详见 ./http/object/permission.md
POST {{baseUrl}}/user/role/authorized/permission?userId={{authorizedUserId}}
Token: {{user_token}}
-186
View File
@@ -1,186 +0,0 @@
### UserController 接口测试
### 在 IDEA 中选择 dev 或 prod 环境后执行
@userId =
@name = System
@password = u#HA027xq$i9]P}uB]LweJspTb!3oS^.
@newPassword = qwe123
@nick = 测试用户
@email = test@example.com
### 分页查询用户
### 权限:需要 ADMIN 角色 + USER_READ 权限
### 前置条件:需要先登录并回填 `user_token`
### 请求参数:Page<User>,详见 ./http/object/user.md
### 返回参数:PageResult<User>,详见 ./http/object/user.md
POST {{baseUrl}}/user/list
Content-Type: application/json
Token: {{user_token}}
{
"index": 0,
"size": 16
}
### 查询用户详情
### 权限:需要 ADMIN 角色 + USER_READ 权限
### 前置条件:需要先登录并回填 `user_token`,URL 参数 `id` 必须传有效用户 ID
### 请求参数:无请求体,URL 参数:`id` 为用户 ID
### 返回参数:User,详见 ./http/object/user.md
POST {{baseUrl}}/user/detail?id={{userId}}
Token: {{user_token}}
### 创建用户
### 权限:需要 ADMIN 角色 + USER_CREATE 权限
### 前置条件:需要先登录并回填 `user_token`,重复用户名通常会失败
### 请求参数:User,详见 ./http/object/user.md
### 返回参数:无
POST {{baseUrl}}/user/create
Content-Type: application/json
Token: {{user_token}}
{
"name": "{{name}}",
"nick": "{{nick}}",
"email": "{{email}}",
"phoneNo": "13800138000",
"password": "{{password}}"
}
### 更新用户
### 权限:需要 ADMIN 角色 + USER_UPDATE 权限
### 前置条件:需要先登录并回填 `user_token`,`id` 必须存在
### 请求参数:User,详见 ./http/object/user.md
### 返回参数:无
POST {{baseUrl}}/user/update
Content-Type: application/json
Token: {{user_token}}
{
"id": "{{userId}}",
"name": "{{name}}",
"nick": "{{nick}}",
"email": "{{email}}",
"phoneNo": "13800138000"
}
### 删除用户
### 权限:需要 ADMIN 角色
### 前置条件:需要先登录并回填 `user_token`,URL 参数 `id` 必须传有效用户 ID
### 请求参数:无请求体,URL 参数:`id` 为用户 ID
### 返回参数:无
POST {{baseUrl}}/user/delete?id={{userId}}
Token: {{user_token}}
### 注册
### 权限:无需登录
### 前置条件:重复用户名通常会失败
### 请求参数:User,详见 ./http/object/user.md
### 返回参数:LoginResponse,详见 ./http/object/user.md
POST {{baseUrl}}/user/register
Content-Type: application/json
{
"name": "Test",
"nick": "测试用户",
"phoneNo": "13800138000",
"password": "qwe123"
}
### 登录
### 权限:无需登录
### 前置条件:成功后需要把响应中的 token 回填到 `user_token`
### 请求参数:LoginRequest,详见 ./http/object/user.md
### 返回参数:LoginResponse,详见 ./http/object/user.md
POST {{baseUrl}}/user/login
Content-Type: application/json
{
"user": "{{name}}",
"password": "{{password}}"
}
> {%
client.global.set("user_token", response.body?.data?.token)
%}
### 令牌登录
### 权限:需要有效 Token
### 前置条件:需要先登录并回填 `user_token`
### 请求参数:无
### 返回参数:LoginResponse,详见 ./http/object/user.md
GET {{baseUrl}}/user/login/token
Token: {{user_token}}
### 登出
### 权限:当前控制器未声明 RequiredToken/权限注解,按服务端实际会话处理
### 前置条件:当前接口通常用于退出当前登录态
### 请求参数:无
### 返回参数:无
POST {{baseUrl}}/user/logout
Token: {{user_token}}
### 修改当前用户密码
### 权限:需要 USER_UPDATE 权限
### 前置条件:需要先登录并回填 `user_token`
### 请求参数:UpdatePasswordRequest,详见 ./http/object/user.md
### 返回参数:无
POST {{baseUrl}}/user/update/password
Content-Type: application/json
Token: {{user_token}}
{
"oldValue": "{{password}}",
"newValue": "{{newPassword}}"
}
### 修改当前用户邮箱
### 权限:需要 USER_UPDATE 权限
### 前置条件:当前方法体为空,接口尚未实现
### 请求参数:无
### 返回参数:无
POST {{baseUrl}}/user/update/email
Content-Type: application/json
Token: {{user_token}}
{}
### 发送当前用户手机号验证码
### 权限:需要 USER_UPDATE 权限
### 前置条件:需要先登录并回填 `user_token`
### 请求参数:PhoneVerifyCodeSendRequest,详见 ./http/object/user.md
### 返回参数:无
POST {{baseUrl}}/user/phone/verify/send
Content-Type: application/json
Token: {{user_token}}
{
"phoneNo": "13800138000"
}
### 验证当前用户手机号
### 权限:需要 USER_UPDATE 权限
### 前置条件:需要先调用手机号验证码发送接口获取验证码
### 请求参数:PhoneVerifyRequest,详见 ./http/object/user.md
### 返回参数:无
POST {{baseUrl}}/user/phone/verify
Content-Type: application/json
Token: {{user_token}}
{
"phoneNo": "13800138000",
"verifyCode": "123456"
}
### 注销当前用户
### 权限:需要 USER_DELETE 权限
### 前置条件:需要先登录并回填 `user_token`
### 请求参数:CancelRequest,详见 ./http/object/user.md
### 返回参数:无
POST {{baseUrl}}/user/cancel
Content-Type: application/json
Token: {{user_token}}
{
"password": "{{password}}"
}
+11 -2
View File
@@ -11,7 +11,7 @@
<groupId>com.imyeyu.timiserverapi</groupId> <groupId>com.imyeyu.timiserverapi</groupId>
<artifactId>TimiServerAPI</artifactId> <artifactId>TimiServerAPI</artifactId>
<version>1.0.46</version> <version>1.0.78</version>
<packaging>jar</packaging> <packaging>jar</packaging>
<name>TimiServerAPI</name> <name>TimiServerAPI</name>
<description>imyeyu.com API</description> <description>imyeyu.com API</description>
@@ -188,7 +188,11 @@
<dependency> <dependency>
<groupId>com.imyeyu.spring</groupId> <groupId>com.imyeyu.spring</groupId>
<artifactId>timi-spring</artifactId> <artifactId>timi-spring</artifactId>
<version>0.0.19</version> <version>0.0.20</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-freemarker</artifactId>
</dependency> </dependency>
<dependency> <dependency>
<groupId>com.imyeyu.network</groupId> <groupId>com.imyeyu.network</groupId>
@@ -215,6 +219,11 @@
<artifactId>tinypinyin</artifactId> <artifactId>tinypinyin</artifactId>
<version>2.0.3</version> <version>2.0.3</version>
</dependency> </dependency>
<dependency>
<groupId>cn.6tail</groupId>
<artifactId>lunar</artifactId>
<version>1.7.8</version>
</dependency>
<dependency> <dependency>
<groupId>com.hankcs</groupId> <groupId>com.hankcs</groupId>
<artifactId>hanlp</artifactId> <artifactId>hanlp</artifactId>
File diff suppressed because it is too large Load Diff
@@ -55,6 +55,10 @@ public enum CorePermissionCode implements BuiltinPermissionCode {
USER_UPDATE("USER:UPDATE", "用户修改", false, true), USER_UPDATE("USER:UPDATE", "用户修改", false, true),
USER_DELETE("USER:DELETE", "用户删除", 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_CREATE("FEEDBACK:CREATE", "反馈创建", false, true),
FEEDBACK_READ("FEEDBACK:READ", "反馈读取", false, true), FEEDBACK_READ("FEEDBACK:READ", "反馈读取", false, true),
FEEDBACK_UPDATE("FEEDBACK:UPDATE", "反馈修改", false, true), FEEDBACK_UPDATE("FEEDBACK:UPDATE", "反馈修改", false, true),
@@ -10,4 +10,6 @@ public enum ModuleCode {
CORE, CORE,
GAO, GAO,
APP,
} }
@@ -24,4 +24,13 @@ public interface SettingEnum {
String getDefaultValue(); String getDefaultValue();
Setting.ValueType getValueType(); Setting.ValueType getValueType();
/// 配置作用域
///
/// 业务级配置由业务对象自己维护,启动时不初始化记录
///
/// @return 配置作用域
default Setting.Scope getScope() {
return Setting.Scope.SYSTEM;
}
} }
@@ -2,6 +2,7 @@ package com.imyeyu.api.config;
import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.ObjectMapper;
import com.imyeyu.api.modules.common.entity.Multilingual; import com.imyeyu.api.modules.common.entity.Multilingual;
import com.imyeyu.api.modules.gao.ai.entity.GaoAiSession;
import com.imyeyu.api.modules.gao.bean.GaoUserInviteCache; import com.imyeyu.api.modules.gao.bean.GaoUserInviteCache;
import com.imyeyu.spring.bean.RedisConfigParams; import com.imyeyu.spring.bean.RedisConfigParams;
import com.imyeyu.spring.config.AbstractRedisConfig; import com.imyeyu.spring.config.AbstractRedisConfig;
@@ -18,11 +19,6 @@ import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.cache.interceptor.KeyGenerator; import org.springframework.cache.interceptor.KeyGenerator;
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration; 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; import java.time.Duration;
@@ -106,31 +102,7 @@ public class RedisConfig extends AbstractRedisConfig {
/** @return 多语言环境,ID: {@link Multilingual} */ /** @return 多语言环境,ID: {@link Multilingual} */
@Bean("redisLanguage") @Bean("redisLanguage")
public Redis<String, Multilingual> getLanguageRedisTemplate() { public Redis<String, Multilingual> getLanguageRedisTemplate() {
return getRedis(database, RedisSerializers.STRING, new RedisSerializer<>() { return getRedis(database, RedisSerializers.STRING, RedisSerializers.jacksonSerializer(jackson, Multilingual.class));
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);
}
}
}
});
} }
@Bean("redisCaptcha") @Bean("redisCaptcha")
@@ -209,4 +181,10 @@ public class RedisConfig extends AbstractRedisConfig {
public Redis<String, GaoUserInviteCache> getGaoUserInviteRedisTemplate() { public Redis<String, GaoUserInviteCache> getGaoUserInviteRedisTemplate() {
return getRedis(database, RedisSerializers.STRING, RedisSerializers.jacksonSerializer(jackson, GaoUserInviteCache.class)); return getRedis(database, RedisSerializers.STRING, RedisSerializers.jacksonSerializer(jackson, GaoUserInviteCache.class));
} }
/// @return AI 会话,AI 会话 ID: 会话授权内容
@Bean("redisGaoAiSession")
public Redis<String, GaoAiSession> getGaoAiSessionRedisTemplate() {
return getRedis(database, RedisSerializers.STRING, RedisSerializers.jacksonSerializer(jackson, GaoAiSession.class));
}
} }
@@ -8,6 +8,7 @@ import com.fasterxml.jackson.databind.json.JsonMapper;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule; import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import com.imyeyu.api.annotation.RequestRateLimitInterceptor; import com.imyeyu.api.annotation.RequestRateLimitInterceptor;
import com.imyeyu.api.annotation.RequireCorePermissionInterceptor; 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.gao.annotation.RequireGaoPermissionInterceptor;
import com.imyeyu.api.modules.journal.util.JournalAPIInterceptor; import com.imyeyu.api.modules.journal.util.JournalAPIInterceptor;
import com.imyeyu.api.modules.system.util.SystemAPIInterceptor; import com.imyeyu.api.modules.system.util.SystemAPIInterceptor;
@@ -42,6 +43,7 @@ public class WebConfig implements WebMvcConfigurer {
private final RequestRateLimitInterceptor requestRateLimitInterceptor; private final RequestRateLimitInterceptor requestRateLimitInterceptor;
private final RequireGaoPermissionInterceptor requireGaoPermissionInterceptor; private final RequireGaoPermissionInterceptor requireGaoPermissionInterceptor;
private final RequireCorePermissionInterceptor requireCorePermissionInterceptor; private final RequireCorePermissionInterceptor requireCorePermissionInterceptor;
private final RequireAppPermissionInterceptor requireAppPermissionInterceptor;
/** /**
* 过滤器 * 过滤器
@@ -54,6 +56,7 @@ public class WebConfig implements WebMvcConfigurer {
registry.addInterceptor(journalAPIInterceptor).addPathPatterns(JournalAPIInterceptor.PATH); registry.addInterceptor(journalAPIInterceptor).addPathPatterns(JournalAPIInterceptor.PATH);
registry.addInterceptor(requireCorePermissionInterceptor).addPathPatterns("/**"); registry.addInterceptor(requireCorePermissionInterceptor).addPathPatterns("/**");
registry.addInterceptor(requireGaoPermissionInterceptor).addPathPatterns("/**"); registry.addInterceptor(requireGaoPermissionInterceptor).addPathPatterns("/**");
registry.addInterceptor(requireAppPermissionInterceptor).addPathPatterns("/**");
registry.addInterceptor(requestRateLimitInterceptor).addPathPatterns("/**"); registry.addInterceptor(requestRateLimitInterceptor).addPathPatterns("/**");
} }
@@ -21,6 +21,7 @@ import org.springframework.transaction.PlatformTransactionManager;
import javax.sql.DataSource; import javax.sql.DataSource;
import java.sql.SQLException; import java.sql.SQLException;
import java.time.OffsetDateTime;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
@@ -32,17 +33,14 @@ import java.util.List;
*/ */
@Configuration @Configuration
@MapperScan(basePackages = { @MapperScan(basePackages = {
"com.imyeyu.api.modules.git.mapper",
"com.imyeyu.api.modules.gao.mapper", "com.imyeyu.api.modules.gao.mapper",
"com.imyeyu.api.modules.bill.mapper",
"com.imyeyu.api.modules.user.mapper", "com.imyeyu.api.modules.user.mapper",
"com.imyeyu.api.modules.blog.mapper",
"com.imyeyu.api.modules.lyric.mapper", "com.imyeyu.api.modules.lyric.mapper",
"com.imyeyu.api.modules.mirror.mapper", "com.imyeyu.api.modules.mirror.mapper",
"com.imyeyu.api.modules.system.mapper", "com.imyeyu.api.modules.system.mapper",
"com.imyeyu.api.modules.common.mapper", "com.imyeyu.api.modules.common.mapper",
"com.imyeyu.api.modules.app.mapper",
"com.imyeyu.api.modules.journal.mapper", "com.imyeyu.api.modules.journal.mapper",
"com.imyeyu.api.modules.minecraft.mapper"
}, sqlSessionFactoryRef = "timiServerSqlSessionFactory") }, sqlSessionFactoryRef = "timiServerSqlSessionFactory")
public class TimiServerDBConfig { public class TimiServerDBConfig {
@@ -58,6 +56,9 @@ public class TimiServerDBConfig {
dataSource.setMinimumIdle(10); dataSource.setMinimumIdle(10);
dataSource.setMaximumPoolSize(100); dataSource.setMaximumPoolSize(100);
dataSource.setConnectionTestQuery("SELECT 1"); 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.setMaxLifetime(Time.S * 180);
dataSource.setIdleTimeout(Time.S * 120); 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 = 20;
/// 已是最新时展示的版本条数
public static final int TAIL_NOTES = 3;
/// 灰度基数
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; 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.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.AttachmentService;
import com.imyeyu.api.modules.common.service.AttachmentVariantService; import com.imyeyu.api.modules.common.service.AttachmentVariantService;
import com.imyeyu.api.modules.common.service.TempFileService; import com.imyeyu.api.modules.common.service.TempFileService;
@@ -68,6 +68,8 @@ public class AttachmentController {
@PostMapping(value = "/create", consumes = MediaType.MULTIPART_FORM_DATA_VALUE) @PostMapping(value = "/create", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
public Attachment create(Attachment attachment) { public Attachment create(Attachment attachment) {
service.create(attachment); service.create(attachment);
attachment.setFile(null);
attachment.setInputStream(null);
return attachment; return attachment;
} }
@@ -258,7 +260,9 @@ public class AttachmentController {
} }
private void setDownloadHeader(Attachment attachment) throws UnsupportedEncodingException { 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())); TimiSpring.getResponse().setHeader("Content-Disposition", Network.getFileDownloadHeader(attachment.getName()));
} }
} }
@@ -52,9 +52,27 @@ public class Attachment extends UUIDEntity {
GAO_SALES_ORDER, GAO_SALES_ORDER,
GAO_POINT_REDEMPTION,
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, TEMP_FILE,
MIRROR MIRROR,
APP_RELEASE
} }
protected BizType bizType; protected BizType bizType;
@@ -77,6 +77,19 @@ public class Setting extends UUIDEntity {
JSON_OBJECT JSON_OBJECT
} }
/// 配置作用域
///
/// @author Codex
/// @since 2026-11-16
public enum Scope {
/// 系统级,bizId 固定为全零 UUID,启动时自动初始化
SYSTEM,
/// 业务级,bizId 为业务对象 ID,启动时不初始化
BUSINESS
}
@JsonView(ResponseView.Public.class) @JsonView(ResponseView.Public.class)
private String bizType; private String bizType;
@@ -1,5 +1,6 @@
package com.imyeyu.api.modules.common.entity; package com.imyeyu.api.modules.common.entity;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.imyeyu.api.annotation.MultilingualField; import com.imyeyu.api.annotation.MultilingualField;
import com.imyeyu.spring.annotation.table.Transient; import com.imyeyu.spring.annotation.table.Transient;
import com.imyeyu.spring.entity.UUIDEntity; import com.imyeyu.spring.entity.UUIDEntity;
@@ -40,4 +41,9 @@ public class Tag extends UUIDEntity {
/// 中文名称 /// 中文名称
@Transient @Transient
protected String zhCN; 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); 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 /// @param userId 管理员用户 ID
@@ -1,6 +1,8 @@
package com.imyeyu.api.modules.common.mapper; package com.imyeyu.api.modules.common.mapper;
import com.imyeyu.api.modules.common.entity.Tag; 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 com.imyeyu.spring.mapper.BaseMapper;
import org.apache.ibatis.annotations.Param; import org.apache.ibatis.annotations.Param;
@@ -33,5 +35,23 @@ public interface TagMapper extends BaseMapper<Tag, String> {
/// @return 标签列表 /// @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); 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); 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> { 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 /// @param detailId 通知详情 ID
void requeue(String detailId); void requeue(String detailId);
/// 取消尚未生效的通知详情
///
/// @param detailId 通知详情 ID
/// @param reason 取消原因
void cancelPending(String detailId, String reason);
/// 分页查询用户的站内通知 /// 分页查询用户的站内通知
/// ///
/// @param page 分页参数 /// @param page 分页参数
@@ -19,6 +19,14 @@ public interface NotifyService extends BaseService<Notify, String> {
/// @param notify 通知 /// @param notify 通知
void createIfAbsent(Notify notify); void createIfAbsent(Notify notify);
/// 按业务查重键查询未删除通知
///
/// @param bizType 业务类型
/// @param bizRemindedType 业务提醒类型
/// @param bizRemindedKey 业务提醒查重键
/// @return 通知
Notify getByBusinessKey(String bizType, String bizRemindedType, String bizRemindedKey);
/// 分页查询当前用户创建的通知 /// 分页查询当前用户创建的通知
/// ///
/// @param page 分页参数 /// @param page 分页参数
@@ -26,6 +26,23 @@ public interface TagService extends BaseService<Tag, String> {
/// @return 标签分页 /// @return 标签分页
PageResult<Tag> pageByOwnerAndKeyword(Page<Tag> page, Tag.OwnerType ownerType, String ownerId, String keyword); 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 业务类型 /// @param bizType 业务类型
@@ -66,6 +66,20 @@ public class AttachmentServiceImplement extends AbstractEntityService<Attachment
@Transactional(TimiServerDBConfig.ROLLBACKER) @Transactional(TimiServerDBConfig.ROLLBACKER)
@Override @Override
public void create(Attachment attachment) { 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.getBizType(), "not found String");
TimiException.required(attachment.getName(), "not found attachment.name"); TimiException.required(attachment.getName(), "not found attachment.name");
String mongoId = null; String mongoId = null;
@@ -82,7 +96,7 @@ public class AttachmentServiceImplement extends AbstractEntityService<Attachment
attachment.setSize(gridFSFile.getLength()); attachment.setSize(gridFSFile.getLength());
attachment.setMd5(IO.md5(gridFSBucket.openDownloadStream(gridFSFile.getObjectId()))); attachment.setMd5(IO.md5(gridFSBucket.openDownloadStream(gridFSFile.getObjectId())));
attachment.setMimeType(new Tika().detect(gridFSBucket.openDownloadStream(gridFSFile.getObjectId()))); attachment.setMimeType(new Tika().detect(gridFSBucket.openDownloadStream(gridFSFile.getObjectId())));
attachment.setUploaderIp(TimiSpring.getRequestIP()); attachment.setUploaderIp(uploaderIp);
attachment.setIsDestroyed(false); attachment.setIsDestroyed(false);
if (attachment.getMimeType().startsWith("image")) { if (attachment.getMimeType().startsWith("image")) {
BufferedImage image = ImageIO.read(gridFSBucket.openDownloadStream(gridFSFile.getObjectId())); BufferedImage image = ImageIO.read(gridFSBucket.openDownloadStream(gridFSFile.getObjectId()));
@@ -184,6 +198,7 @@ public class AttachmentServiceImplement extends AbstractEntityService<Attachment
try (InputStream inputStream = getInputStreamByMongoId(source.getMongoId())) { try (InputStream inputStream = getInputStreamByMongoId(source.getMongoId())) {
target.setInputStream(inputStream); target.setInputStream(inputStream);
create(target); create(target);
target.setInputStream(null);
return target; return target;
} catch (IOException e) { } catch (IOException e) {
if (target.getMongoId() != null) { if (target.getMongoId() != null) {
@@ -301,6 +316,10 @@ public class AttachmentServiceImplement extends AbstractEntityService<Attachment
throw new TimiException(TimiCode.ERROR, "exception.attachment.file.required"); throw new TimiException(TimiCode.ERROR, "exception.attachment.file.required");
} }
Attachment tempFile = mapper.selectRaw(tempFileId); Attachment tempFile = mapper.selectRaw(tempFileId);
if (tempFile == null) {
// 临时文件不存在或已过期,按业务错误拒绝,避免空指针变成 500
throw new TimiException(TimiCode.ERROR, "exception.attachment.file.notfound");
}
tempFile.setBizType(bizType); tempFile.setBizType(bizType);
tempFile.setBizId(bizId); tempFile.setBizId(bizId);
tempFile.setAttachType(item.getAttachType()); tempFile.setAttachType(item.getAttachType());
@@ -319,6 +338,10 @@ public class AttachmentServiceImplement extends AbstractEntityService<Attachment
// 将临时文件的 GridFS 存储转移至当前永久记录,废弃临时记录 // 将临时文件的 GridFS 存储转移至当前永久记录,废弃临时记录
Attachment current = mapper.selectRaw(item.getId()); Attachment current = mapper.selectRaw(item.getId());
Attachment tempFile = mapper.selectRaw(tempFileId); Attachment tempFile = mapper.selectRaw(tempFileId);
if (current == null || tempFile == null) {
// 附件或临时文件已被清理,按业务错误拒绝
throw new TimiException(TimiCode.ERROR, "exception.attachment.file.notfound");
}
// 源文件版本已变化,旧缩略图全部失效 // 源文件版本已变化,旧缩略图全部失效
variantService.deleteBySourceId(current.getId()); variantService.deleteBySourceId(current.getId());
// 删除旧 GridFS 文件 // 删除旧 GridFS 文件
@@ -57,7 +57,7 @@ public class AttachmentVariantServiceImplement implements AttachmentVariantServi
private static final int THUMB_MAX_HEIGHT = 4096; private static final int THUMB_MAX_HEIGHT = 4096;
private static final long THUMB_MAX_PIXELS = 16_000_000L; 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_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 double THUMB_TARGET_SECONDS = 2;
private static final int VARIANT_NAME_MAX_LENGTH = 255; private static final int VARIANT_NAME_MAX_LENGTH = 255;
private static final String THUMB_OUTPUT_FORMAT = "png"; private static final String THUMB_OUTPUT_FORMAT = "png";
@@ -24,7 +24,7 @@ import java.util.List;
@RequiredArgsConstructor @RequiredArgsConstructor
public class MultilingualServiceImplement extends AbstractEntityService<Multilingual, String> implements MultilingualService { 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; private final MultilingualMapper mapper;
@@ -108,6 +108,36 @@ public class NotifyDetailServiceImplement extends AbstractEntityService<NotifyDe
super.delete(detailId); 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 /// @param detailId 通知详情 ID
@@ -69,6 +69,20 @@ public class NotifyServiceImplement extends AbstractEntityService<Notify, String
createDetails(notify); 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 通知 /// @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.mapper.TagMapper;
import com.imyeyu.api.modules.common.service.MultilingualService; import com.imyeyu.api.modules.common.service.MultilingualService;
import com.imyeyu.api.modules.common.service.TagService; import com.imyeyu.api.modules.common.service.TagService;
import com.imyeyu.java.TimiJava;
import com.imyeyu.java.bean.timi.TimiException; import com.imyeyu.java.bean.timi.TimiException;
import com.imyeyu.spring.bean.Page; import com.imyeyu.spring.bean.Page;
import com.imyeyu.spring.bean.PageResult; import com.imyeyu.spring.bean.PageResult;
@@ -82,6 +83,21 @@ public class TagServiceImplement extends AbstractEntityService<Tag, String> impl
return result; 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 @Override
public List<Tag> listByBizType(TagApply.BizType bizType, String bizId) { public List<Tag> listByBizType(TagApply.BizType bizType, String bizId) {
return listByIdList(listApply(bizType, bizId).stream().map(TagApply::getTagId).toList()); return listByIdList(listApply(bizType, bizId).stream().map(TagApply::getTagId).toList());
@@ -0,0 +1,32 @@
package com.imyeyu.api.modules.gao.ai.config;
import lombok.Getter;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
/// GAO 智能体配置
///
/// 密钥只从部署环境变量或外部配置读取,不允许写入仓库
///
/// @author Codex
/// @since 2026-09-15
@Getter
@Component
public class GaoAiProperties {
/// AI 会话有效期,单位秒
@Value("${gao.ai.session-ttl-seconds:300}")
private long sessionTtlSeconds;
/// 工具单页最大条数
@Value("${gao.ai.max-tool-page-size:20}")
private int maxToolPageSize;
/// Dify 连接超时,单位秒
@Value("${gao.ai.connect-timeout-seconds:10}")
private long connectTimeoutSeconds;
/// Dify 流式读取空闲超时,单位秒
@Value("${gao.ai.read-timeout-seconds:600}")
private long readTimeoutSeconds;
}
@@ -0,0 +1,98 @@
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;
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;
/// GAO 智能体聊天接口
///
/// 浏览器只携带 Timi 登录令牌访问本接口,不接触 Dify 或 MCP 密钥
///
/// @author Codex
/// @since 2026-09-15
@RestController
@RequiredArgsConstructor
@RequestMapping("/gao/ai")
public class GaoAiChatController {
private final GaoAiChatService chatService;
/// 发起门店智能体流式聊天
///
/// @param request 聊天请求
/// @return SSE 发射器
@RequestRateLimit
@IgnoreGlobalReturn
@PostMapping(value = "/chat", produces = "text/event-stream")
public SseEmitter chat(@RequestBody GaoAiChatRequest request) {
try {
return chatService.chat(request);
} catch (GaoAiAccessException 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,40 @@
package com.imyeyu.api.modules.gao.ai.entity;
import lombok.Data;
/// GAO 智能体审计记录
///
/// 业务审计通过现有系统日志服务落库,本对象只承载脱敏后的结构化内容
///
/// @author Codex
/// @since 2026-09-15
@Data
public class GaoAiAuditLog {
/// 登录用户 ID
private String userId;
/// 门店 ID
private String storeId;
/// 问题摘要哈希,不保存问题原文
private String questionDigest;
/// Dify 会话 ID
private String conversationId;
/// 调用的工具名称
private String toolName;
/// 查询耗时,单位毫秒
private long duration;
/// 查询状态
private String status;
/// 返回条数
private long resultCount;
/// 记录时间,单位毫秒
private long createdAt;
}
@@ -0,0 +1,39 @@
package com.imyeyu.api.modules.gao.ai.entity;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.util.LinkedHashSet;
import java.util.Set;
/// GAO 智能体短期会话授权
///
/// 该对象只存储在服务端,`sessionId` 不是 JWT,也不是用户登录令牌
///
/// @author Codex
/// @since 2026-09-15
@Data
@NoArgsConstructor
public class GaoAiSession {
/// 不可预测的 AI 会话 ID
private String sessionId;
/// 登录用户 ID
private String userId;
/// 固定的门店 ID
private String storeId;
/// Dify 会话 ID,可为空
private String difyConversationId;
/// 允许调用的只读工具
private Set<String> allowedTools = new LinkedHashSet<>();
/// 过期时间,单位毫秒
private long expiresAt;
/// 已调用工具次数
private long usedCount;
}
@@ -0,0 +1,86 @@
package com.imyeyu.api.modules.gao.ai.mcp;
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;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
/// Dify MCP 请求认证
///
/// 服务密钥只证明请求来自 Dify,门店和用户身份完全来自 AI 会话
///
/// @author Codex
/// @since 2026-09-15
@Service
@RequiredArgsConstructor
public class GaoAiMcpAuthentication {
private final SettingService settingService;
private final GaoAiSessionService sessionService;
/// 校验 Dify 服务密钥和 AI 会话
///
/// @param authorization Authorization 请求头
/// @param headerSessionId X-Timi-AI-Session 请求头
/// @param argumentSessionId MCP 工具参数中的 AI 会话 ID
/// @param toolName 工具名称,可为空
/// @return 已认证会话
public GaoAiSession authenticate(String authorization, String headerSessionId, String argumentSessionId, String toolName) {
authenticateService(authorization);
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))) {
throw new GaoAiSessionException("AI 会话无权调用该工具", 403);
}
return session;
}
/// 只校验 Dify 服务间密钥
///
/// MCP 初始化和工具声明阶段尚未绑定店长会话,只能校验服务间身份
///
/// @param authorization Authorization 请求头
public void authenticateService(String authorization) {
String key = settingService.getSystem(GaoSystemSetting.DIFY_MCP_SERVICE_KEY).asString();
String actualKey = bearerValue(authorization);
if (key.isEmpty() || actualKey.isEmpty() || !constantTimeEquals(key, actualKey)) {
throw new GaoAiSessionException("MCP 服务认证失败", 401);
}
}
private String bearerValue(String authorization) {
if (authorization == null) {
return "";
}
String value = authorization.trim();
if (7 > value.length() || !value.regionMatches(true, 0, "Bearer ", 0, 7)) {
return "";
}
return value.substring(7).trim();
}
private boolean constantTimeEquals(String left, String right) {
return MessageDigest.isEqual(left.getBytes(StandardCharsets.UTF_8), right.getBytes(StandardCharsets.UTF_8));
}
private String trim(String value) {
return value == null ? "" : value.trim();
}
/// 判断字符串是否为空
///
/// @param value 待判断字符串
/// @return true 为 null、空字符串或空白字符串
private boolean isBlank(String value) {
return value == null || value.trim().isEmpty();
}
}
@@ -0,0 +1,273 @@
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.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.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.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;
/// GAO 智能体 MCP Streamable HTTP 接口
///
/// Dify 通过 Docker 内网访问本接口,业务查询只允许调用已注册的只读工具
///
/// @author Codex
/// @since 2026-09-15
@Slf4j
@RestController
@RequestMapping("/mcp/gao-ai")
public class GaoAiMcpController {
private final ObjectMapper jackson;
private final GaoAiMcpAuthentication authentication;
private final GaoAiSessionService sessionService;
private final GaoAiAuditService auditService;
private final Map<String, GaoAiTool> toolMap;
public GaoAiMcpController(ObjectMapper jackson, GaoAiMcpAuthentication authentication,
GaoAiSessionService sessionService, GaoAiAuditService auditService, List<GaoAiTool> toolList) {
this.jackson = jackson;
this.authentication = authentication;
this.sessionService = sessionService;
this.auditService = auditService;
this.toolMap = toolList.stream().collect(Collectors.toUnmodifiableMap(GaoAiTool::name, Function.identity()));
}
/// 处理 MCP JSON-RPC 请求
///
/// @param authorization Dify 服务密钥
/// @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");
log.info("GAO MCP 请求:method={}, toolName={}, authorizationPresent={}, aiSessionPresent={}, aiSessionLength={}",
method, toolName, hasText(authorization), hasText(aiSessionId), length(aiSessionId));
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);
yield response(200, success(id, initializeResult()));
}
case "notifications/initialized", "ping" -> {
authentication.authenticateService(authorization);
yield response(200, success(id, Map.of()));
}
case "tools/list" -> {
authentication.authenticateService(authorization);
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"));
if (hasText(argumentSessionId) && !hasText(aiSessionId)) {
log.info("GAO MCP 使用工具参数中的 AI 会话:toolName={}, aiSessionLength={}", toolName, length(argumentSessionId));
}
yield response(200, success(id, executeTool(session, params, hasText(aiSessionId) ? aiSessionId : argumentSessionId)));
}
default -> response(400, error(id, -32601, "MCP 方法不支持"));
};
} catch (GaoAiSessionException e) {
log.warn("GAO MCP 认证失败:method={}, toolName={}, status={}, authorizationPresent={}, aiSessionPresent={}, aiSessionLength={}, reason={}",
method, toolName, e.getStatus(), hasText(authorization), hasText(aiSessionId), length(aiSessionId), e.getMessage());
return response(e.getStatus(), error(id, -32001, e.getMessage()));
} catch (GaoAiToolException e) {
log.warn("GAO MCP 工具调用失败:method={}, toolName={}, status={}, aiSessionPresent={}, reason={}",
method, toolName, e.getStatus(), hasText(aiSessionId), 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");
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);
}
ObjectNode businessArguments = ((ObjectNode) arguments).deepCopy();
businessArguments.remove("aiSessionId");
if (containsField(businessArguments, "storeId")) {
throw new GaoAiToolException("工具请求不允许携带 storeId", 403);
}
GaoAiToolRequest request;
try {
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;
if (hasText(aiSessionId)) {
sessionService.increaseUsedCount(aiSessionId);
}
recordAudit(session, request, toolName, duration, "SUCCESS", result == null ? 0L : result.getDetails().size());
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 (GaoAiToolException e) {
recordAudit(session, request, toolName, System.currentTimeMillis() - startedAt, "ERROR", 0L);
throw e;
} catch (RuntimeException e) {
recordAudit(session, request, toolName, System.currentTimeMillis() - startedAt, "ERROR", 0L);
throw e;
}
}
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", "version", "1.0"));
return result;
}
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();
return Map.of("tools", tools);
}
private void recordAudit(GaoAiSession session, GaoAiToolRequest request, String toolName, long duration,
String status, long resultCount) {
GaoAiAuditLog audit = new GaoAiAuditLog();
audit.setUserId(session.getUserId());
audit.setStoreId(session.getStoreId());
audit.setQuestionDigest(auditService.digest(request == null ? null : request.getQuery()));
audit.setConversationId(session.getDifyConversationId());
audit.setToolName(toolName);
audit.setDuration(Math.max(0L, duration));
audit.setStatus(status);
audit.setResultCount(resultCount);
audit.setCreatedAt(System.currentTimeMillis());
auditService.record(audit);
}
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();
}
/// 判断字符串是否有实际内容
///
/// @param value 待判断字符串
/// @return true 为有内容
private boolean hasText(String value) {
return value != null && !value.trim().isEmpty();
}
/// 获取字符串长度
///
/// @param value 待计算字符串
/// @return 字符串长度
private int length(String value) {
return value == null ? 0 : value.trim().length();
}
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);
}
}
}
@@ -0,0 +1,37 @@
package com.imyeyu.api.modules.gao.ai.mcp;
import com.imyeyu.spring.annotation.IgnoreGlobalReturn;
import org.springframework.http.CacheControl;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
/// GAO MCP OAuth 探测兼容接口
///
/// Dify 即使配置固定请求头认证,也会预先探测 OAuth 元数据。本服务不提供 OAuth,必须返回原始 404,
/// 不能落入全局异常处理后被包装为业务 JSON
///
/// @author Codex
/// @since 2026-09-15
@RestController
public class GaoAiMcpOAuthDiscoveryController {
/// 返回未实现的 OAuth 探测结果
///
/// @return 原始 HTTP 404
@IgnoreGlobalReturn
@GetMapping({
"/.well-known/oauth-authorization-server",
"/.well-known/oauth-authorization-server/mcp/gao-ai",
"/.well-known/oauth-protected-resource",
"/.well-known/oauth-protected-resource/mcp/gao-ai",
"/.well-known/openid-configuration",
"/.well-known/openid-configuration/mcp/gao-ai",
"/mcp/gao-ai/.well-known/oauth-authorization-server",
"/mcp/gao-ai/.well-known/oauth-protected-resource",
"/mcp/gao-ai/.well-known/openid-configuration"
})
public ResponseEntity<Void> notSupported() {
return ResponseEntity.notFound().cacheControl(CacheControl.noStore()).build();
}
}
@@ -0,0 +1,46 @@
package com.imyeyu.api.modules.gao.ai.mcp;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
/// GAO 智能体只读工具名称
///
/// @author Codex
/// @since 2026-09-15
public final class GaoAiToolNames {
public static final String STORE_OVERVIEW = "store_overview";
public static final String CUSTOMER_SEARCH = "customer_search";
public static final String CUSTOMER_PROFILE = "customer_profile";
public static final String ORDER_QUERY = "order_query";
public static final String EVENT_QUERY = "event_query";
public static final String PRODUCT_INVENTORY_QUERY = "product_inventory_query";
public static final String POINT_QUERY = "point_query";
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 Set<String> READ_ONLY_TOOLS = java.util.Collections.unmodifiableSet(new LinkedHashSet<>(List.of(
STORE_OVERVIEW,
CUSTOMER_SEARCH,
CUSTOMER_PROFILE,
ORDER_QUERY,
EVENT_QUERY,
PRODUCT_INVENTORY_QUERY,
POINT_QUERY,
BUSINESS_REPORT,
STORE_DIARY_QUERY,
METRIC_DEFINITION
)));
private GaoAiToolNames() {
}
/// 生成稳定的工具顺序
///
/// @return 工具名称集合
public static Set<String> orderedReadOnlyTools() {
return new LinkedHashSet<>(READ_ONLY_TOOLS);
}
}
@@ -0,0 +1,35 @@
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.service.GaoAiQueryService;
import com.imyeyu.api.modules.gao.ai.vo.GaoAiToolRequest;
import com.imyeyu.api.modules.gao.ai.vo.GaoAiToolResult;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;
/// 门店经营报表工具
///
/// @author Codex
/// @since 2026-09-15
@Component
@RequiredArgsConstructor
public class BusinessReportTool implements GaoAiTool {
private final GaoAiQueryService queryService;
@Override
public String name() {
return GaoAiToolNames.BUSINESS_REPORT;
}
@Override
public String description() {
return "查询当前门店销售趋势、应收、客户复购和产品排行";
}
@Override
public GaoAiToolResult execute(GaoAiSession session, GaoAiToolRequest request) {
return queryService.businessReport(session, request);
}
}
@@ -0,0 +1,35 @@
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.service.GaoAiQueryService;
import com.imyeyu.api.modules.gao.ai.vo.GaoAiToolRequest;
import com.imyeyu.api.modules.gao.ai.vo.GaoAiToolResult;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;
/// 客户经营档案工具
///
/// @author Codex
/// @since 2026-09-15
@Component
@RequiredArgsConstructor
public class CustomerProfileTool implements GaoAiTool {
private final GaoAiQueryService queryService;
@Override
public String name() {
return GaoAiToolNames.CUSTOMER_PROFILE;
}
@Override
public String description() {
return "查询当前门店单个客户的套餐、积分、消费和事件档案";
}
@Override
public GaoAiToolResult execute(GaoAiSession session, GaoAiToolRequest request) {
return queryService.customerProfile(session, request);
}
}
@@ -0,0 +1,37 @@
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.service.GaoAiQueryService;
import com.imyeyu.api.modules.gao.ai.vo.GaoAiToolRequest;
import com.imyeyu.api.modules.gao.ai.vo.GaoAiToolResult;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;
/// 客户查询工具
///
/// 同时承载客户搜索和客户经营档案查询
///
/// @author Codex
/// @since 2026-09-15
@Component
@RequiredArgsConstructor
public class CustomerTool implements GaoAiTool {
private final GaoAiQueryService queryService;
@Override
public String name() {
return GaoAiToolNames.CUSTOMER_SEARCH;
}
@Override
public String description() {
return "按客户姓名或编码查询当前门店客户摘要";
}
@Override
public GaoAiToolResult execute(GaoAiSession session, GaoAiToolRequest request) {
return queryService.customerSearch(session, request);
}
}
@@ -0,0 +1,35 @@
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.service.GaoAiQueryService;
import com.imyeyu.api.modules.gao.ai.vo.GaoAiToolRequest;
import com.imyeyu.api.modules.gao.ai.vo.GaoAiToolResult;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;
/// 登记事件查询工具
///
/// @author Codex
/// @since 2026-09-15
@Component
@RequiredArgsConstructor
public class EventTool implements GaoAiTool {
private final GaoAiQueryService queryService;
@Override
public String name() {
return GaoAiToolNames.EVENT_QUERY;
}
@Override
public String description() {
return "查询当前门店登记事件记录及事件统计,严格只读";
}
@Override
public GaoAiToolResult execute(GaoAiSession session, GaoAiToolRequest request) {
return queryService.eventQuery(session, request);
}
}
@@ -0,0 +1,56 @@
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.vo.GaoAiToolRequest;
import com.imyeyu.api.modules.gao.ai.vo.GaoAiToolResult;
import java.util.LinkedHashMap;
import java.util.Map;
/// GAO 智能体只读工具
///
/// @author Codex
/// @since 2026-09-15
public interface GaoAiTool {
/// @return 工具名称
String name();
/// @return 工具描述
String description();
/// 执行工具查询
///
/// @param session 已认证 AI 会话
/// @param request 工具请求
/// @return 脱敏查询结果
GaoAiToolResult execute(GaoAiSession session, GaoAiToolRequest request);
/// @return MCP 输入参数结构
default Map<String, Object> inputSchema() {
Map<String, Object> timeRange = Map.of(
"type", "object",
"properties", Map.of(
"preset", Map.of("type", "string", "enum", new String[]{"TODAY", "LAST_7_DAYS", "LAST_30_DAYS", "THIS_MONTH", "THIS_YEAR", "CUSTOM"}),
"startDate", Map.of("type", "string", "description", "自定义开始日期,格式 yyyy-MM-dd"),
"endDate", Map.of("type", "string", "description", "自定义结束日期,格式 yyyy-MM-dd")
),
"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", properties,
"additionalProperties", false
);
}
}
@@ -0,0 +1,35 @@
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.service.GaoAiQueryService;
import com.imyeyu.api.modules.gao.ai.vo.GaoAiToolRequest;
import com.imyeyu.api.modules.gao.ai.vo.GaoAiToolResult;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;
/// 指标口径查询工具
///
/// @author Codex
/// @since 2026-09-15
@Component
@RequiredArgsConstructor
public class MetricDefinitionTool implements GaoAiTool {
private final GaoAiQueryService queryService;
@Override
public String name() {
return GaoAiToolNames.METRIC_DEFINITION;
}
@Override
public String description() {
return "查询门店经营助手使用的固定指标名称和计算口径";
}
@Override
public GaoAiToolResult execute(GaoAiSession session, GaoAiToolRequest request) {
return queryService.metricDefinition(session, request);
}
}
@@ -0,0 +1,35 @@
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.service.GaoAiQueryService;
import com.imyeyu.api.modules.gao.ai.vo.GaoAiToolRequest;
import com.imyeyu.api.modules.gao.ai.vo.GaoAiToolResult;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;
/// 订单和资金查询工具
///
/// @author Codex
/// @since 2026-09-15
@Component
@RequiredArgsConstructor
public class OrderTool implements GaoAiTool {
private final GaoAiQueryService queryService;
@Override
public String name() {
return GaoAiToolNames.ORDER_QUERY;
}
@Override
public String description() {
return "查询当前门店销售订单、履约和资金摘要,严格只读";
}
@Override
public GaoAiToolResult execute(GaoAiSession session, GaoAiToolRequest request) {
return queryService.orderQuery(session, request);
}
}
@@ -0,0 +1,35 @@
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.service.GaoAiQueryService;
import com.imyeyu.api.modules.gao.ai.vo.GaoAiToolRequest;
import com.imyeyu.api.modules.gao.ai.vo.GaoAiToolResult;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;
/// 积分查询工具
///
/// @author Codex
/// @since 2026-09-15
@Component
@RequiredArgsConstructor
public class PointTool implements GaoAiTool {
private final GaoAiQueryService queryService;
@Override
public String name() {
return GaoAiToolNames.POINT_QUERY;
}
@Override
public String description() {
return "查询当前门店积分账户、积分流水、规则和兑换摘要,严格只读";
}
@Override
public GaoAiToolResult execute(GaoAiSession session, GaoAiToolRequest request) {
return queryService.pointQuery(session, request);
}
}
@@ -0,0 +1,35 @@
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.service.GaoAiQueryService;
import com.imyeyu.api.modules.gao.ai.vo.GaoAiToolRequest;
import com.imyeyu.api.modules.gao.ai.vo.GaoAiToolResult;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;
/// 产品库存查询工具
///
/// @author Codex
/// @since 2026-09-15
@Component
@RequiredArgsConstructor
public class ProductInventoryTool implements GaoAiTool {
private final GaoAiQueryService queryService;
@Override
public String name() {
return GaoAiToolNames.PRODUCT_INVENTORY_QUERY;
}
@Override
public String description() {
return "查询当前门店产品、SKU 和库存余额,严格只读";
}
@Override
public GaoAiToolResult execute(GaoAiSession session, GaoAiToolRequest request) {
return queryService.productInventoryQuery(session, request);
}
}
@@ -0,0 +1,35 @@
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.service.GaoAiQueryService;
import com.imyeyu.api.modules.gao.ai.vo.GaoAiToolRequest;
import com.imyeyu.api.modules.gao.ai.vo.GaoAiToolResult;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;
/// 门店日记查询工具
///
/// @author Codex
/// @since 2026-09-15
@Component
@RequiredArgsConstructor
public class StoreDiaryTool implements GaoAiTool {
private final GaoAiQueryService queryService;
@Override
public String name() {
return GaoAiToolNames.STORE_DIARY_QUERY;
}
@Override
public String description() {
return "查询当前门店日记和营业日信息,严格只读";
}
@Override
public GaoAiToolResult execute(GaoAiSession session, GaoAiToolRequest request) {
return queryService.storeDiaryQuery(session, request);
}
}
@@ -0,0 +1,35 @@
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.service.GaoAiQueryService;
import com.imyeyu.api.modules.gao.ai.vo.GaoAiToolRequest;
import com.imyeyu.api.modules.gao.ai.vo.GaoAiToolResult;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Component;
/// 门店经营总览工具
///
/// @author Codex
/// @since 2026-09-15
@Component
@RequiredArgsConstructor
public class StoreOverviewTool implements GaoAiTool {
private final GaoAiQueryService queryService;
@Override
public String name() {
return GaoAiToolNames.STORE_OVERVIEW;
}
@Override
public String description() {
return "查询当前门店指定周期的营业日、销售、应收和库存健康总览";
}
@Override
public GaoAiToolResult execute(GaoAiSession session, GaoAiToolRequest request) {
return queryService.storeOverview(session, request);
}
}
@@ -0,0 +1,22 @@
package com.imyeyu.api.modules.gao.ai.service;
/// GAO 智能体访问异常
///
/// @author Codex
/// @since 2026-09-15
public class GaoAiAccessException extends RuntimeException {
private final int status;
/// @param message 用户可读消息
/// @param status HTTP 状态码
public GaoAiAccessException(String message, int status) {
super(message);
this.status = status;
}
/// @return HTTP 状态码
public int getStatus() {
return status;
}
}
@@ -0,0 +1,21 @@
package com.imyeyu.api.modules.gao.ai.service;
import com.imyeyu.api.modules.gao.ai.entity.GaoAiAuditLog;
/// GAO 智能体审计服务
///
/// @author Codex
/// @since 2026-09-15
public interface GaoAiAuditService {
/// 记录脱敏后的 AI 查询审计
///
/// @param auditLog 审计记录
void record(GaoAiAuditLog auditLog);
/// 计算问题摘要哈希
///
/// @param question 问题原文
/// @return SHA-256 摘要
String digest(String question);
}
@@ -0,0 +1,37 @@
package com.imyeyu.api.modules.gao.ai.service;
import com.fasterxml.jackson.databind.JsonNode;
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 org.springframework.web.servlet.mvc.method.annotation.SseEmitter;
/// GAO 智能体聊天服务
///
/// @author Codex
/// @since 2026-09-15
public interface GaoAiChatService {
/// 创建 AI 会话并转发 Dify 流式响应
///
/// @param request 聊天请求
/// @return SSE 发射器
SseEmitter chat(GaoAiChatRequest request);
/// 列出当前登录用户的历史会话
///
/// @param request 历史会话分页请求
/// @return 历史会话分页结果
JsonNode listConversation(GaoAiConversationListRequest request);
/// 读取当前登录用户的历史会话消息
///
/// @param request 历史会话读取请求
/// @return 会话消息分页结果
JsonNode readConversation(GaoAiConversationReadRequest request);
/// 删除当前登录用户的历史会话
///
/// @param conversationId Dify 会话 ID
void deleteConversation(String conversationId);
}
@@ -0,0 +1,62 @@
package com.imyeyu.api.modules.gao.ai.service;
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;
/// GAO 智能体只读查询服务
///
/// @author Codex
/// @since 2026-09-15
public interface GaoAiQueryService {
/// @param session 已认证 AI 会话
/// @param request 工具请求
/// @return 门店经营总览
GaoAiToolResult storeOverview(GaoAiSession session, GaoAiToolRequest request);
/// @param session 已认证 AI 会话
/// @param request 工具请求
/// @return 客户搜索结果
GaoAiToolResult customerSearch(GaoAiSession session, GaoAiToolRequest request);
/// @param session 已认证 AI 会话
/// @param request 工具请求
/// @return 客户经营档案
GaoAiToolResult customerProfile(GaoAiSession session, GaoAiToolRequest request);
/// @param session 已认证 AI 会话
/// @param request 工具请求
/// @return 订单查询结果
GaoAiToolResult orderQuery(GaoAiSession session, GaoAiToolRequest request);
/// @param session 已认证 AI 会话
/// @param request 工具请求
/// @return 事件查询结果
GaoAiToolResult eventQuery(GaoAiSession session, GaoAiToolRequest request);
/// @param session 已认证 AI 会话
/// @param request 工具请求
/// @return 产品库存查询结果
GaoAiToolResult productInventoryQuery(GaoAiSession session, GaoAiToolRequest request);
/// @param session 已认证 AI 会话
/// @param request 工具请求
/// @return 积分查询结果
GaoAiToolResult pointQuery(GaoAiSession session, GaoAiToolRequest request);
/// @param session 已认证 AI 会话
/// @param request 工具请求
/// @return 经营报表结果
GaoAiToolResult businessReport(GaoAiSession session, GaoAiToolRequest request);
/// @param session 已认证 AI 会话
/// @param request 工具请求
/// @return 门店日记查询结果
GaoAiToolResult storeDiaryQuery(GaoAiSession session, GaoAiToolRequest request);
/// @param session 已认证 AI 会话
/// @param request 工具请求
/// @return 指标口径
GaoAiToolResult metricDefinition(GaoAiSession session, GaoAiToolRequest request);
}
@@ -0,0 +1,35 @@
package com.imyeyu.api.modules.gao.ai.service;
import com.imyeyu.api.modules.gao.ai.entity.GaoAiSession;
/// GAO 智能体会话服务
///
/// @author Codex
/// @since 2026-09-15
public interface GaoAiSessionService {
/// 创建绑定用户和门店的 AI 会话
///
/// @param userId 用户 ID
/// @param storeId 门店 ID
/// @param difyConversationId Dify 会话 ID,可为空
/// @return AI 会话
GaoAiSession create(String userId, String storeId, String difyConversationId);
/// 获取有效 AI 会话
///
/// @param sessionId AI 会话 ID
/// @return AI 会话
GaoAiSession require(String sessionId);
/// 增加工具调用次数
///
/// @param sessionId AI 会话 ID
/// @return 更新后的会话
GaoAiSession increaseUsedCount(String sessionId);
/// 删除 AI 会话
///
/// @param sessionId AI 会话 ID
void delete(String sessionId);
}
@@ -0,0 +1,22 @@
package com.imyeyu.api.modules.gao.ai.service;
/// GAO 智能体工具请求异常
///
/// @author Codex
/// @since 2026-09-15
public class GaoAiToolException extends RuntimeException {
private final int status;
/// @param message 异常消息
/// @param status HTTP 状态码
public GaoAiToolException(String message, int status) {
super(message);
this.status = status;
}
/// @return HTTP 状态码
public int getStatus() {
return status;
}
}
@@ -0,0 +1,78 @@
package com.imyeyu.api.modules.gao.ai.service.implement;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.imyeyu.api.modules.gao.ai.entity.GaoAiAuditLog;
import com.imyeyu.api.modules.gao.ai.service.GaoAiAuditService;
import com.imyeyu.api.modules.system.entity.Logger;
import com.imyeyu.api.modules.system.service.LoggerService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.LinkedHashMap;
import java.util.Map;
/// GAO 智能体审计服务实现
///
/// @author Codex
/// @since 2026-09-15
@Slf4j
@Service
@RequiredArgsConstructor
public class GaoAiAuditServiceImplement implements GaoAiAuditService {
private final ObjectMapper jackson;
private final LoggerService loggerService;
@Override
public void record(GaoAiAuditLog auditLog) {
if (auditLog == null) {
return;
}
Map<String, Object> content = new LinkedHashMap<>();
content.put("storeId", auditLog.getStoreId());
content.put("questionDigest", auditLog.getQuestionDigest());
content.put("conversationId", auditLog.getConversationId());
content.put("toolName", auditLog.getToolName());
content.put("duration", auditLog.getDuration());
content.put("status", auditLog.getStatus());
content.put("resultCount", auditLog.getResultCount());
content.put("createdAt", auditLog.getCreatedAt());
try {
Logger logger = new Logger(Logger.Module.GAO, auditLevel(auditLog.getStatus()), "GAO_AI_QUERY");
logger.setUserId(auditLog.getUserId());
logger.setContent(jackson.writeValueAsString(content));
logger.setResult(auditLog.getStatus());
logger.setDuration((int) Math.min(Integer.MAX_VALUE, Math.max(0L, auditLog.getDuration())));
loggerService.create(logger);
} catch (JsonProcessingException | RuntimeException e) {
log.warn("写入 GAO 智能体审计日志失败", e);
}
}
/// 计算问题摘要哈希
///
/// @param question 问题原文
/// @return SHA-256 摘要
public String digest(String question) {
try {
byte[] bytes = MessageDigest.getInstance("SHA-256").digest(
(question == null ? "" : question).getBytes(StandardCharsets.UTF_8));
StringBuilder result = new StringBuilder(bytes.length * 2);
for (byte value : bytes) {
result.append("%02x".formatted(value & 0xff));
}
return result.toString();
} catch (NoSuchAlgorithmException e) {
throw new IllegalStateException("当前 JDK 不支持 SHA-256", e);
}
}
private Logger.Level auditLevel(String status) {
return "SUCCESS".equals(status) ? Logger.Level.INFO : Logger.Level.WARN;
}
}
@@ -0,0 +1,753 @@
package com.imyeyu.api.modules.gao.ai.service.implement;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.imyeyu.api.bean.ModuleCode;
import com.imyeyu.api.modules.common.service.SettingService;
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.service.GaoAiAccessException;
import com.imyeyu.api.modules.gao.ai.service.GaoAiAuditService;
import com.imyeyu.api.modules.gao.ai.service.GaoAiChatService;
import com.imyeyu.api.modules.gao.ai.service.GaoAiSessionService;
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.api.modules.gao.bean.GaoRoleCode;
import com.imyeyu.api.modules.gao.bean.GaoSystemSetting;
import com.imyeyu.api.modules.gao.entity.GaoStore;
import com.imyeyu.api.modules.gao.service.GaoStoreScopeService;
import com.imyeyu.api.modules.gao.service.GaoStoreService;
import com.imyeyu.api.modules.system.bean.DifySetting;
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 jakarta.annotation.PostConstruct;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URI;
import java.net.URLEncoder;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.nio.charset.StandardCharsets;
import java.time.Duration;
import java.time.LocalDate;
import java.time.ZoneId;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicReference;
/// GAO 智能体聊天服务实现
///
/// 使用 JDK HttpClient 读取 Dify SSE,再通过 Spring MVC SseEmitter 输出给前端
///
/// @author Codex
/// @since 2026-09-15
@Slf4j
@Service
@RequiredArgsConstructor
public class GaoAiChatServiceImplement implements GaoAiChatService {
private static final ZoneId ZONE = ZoneId.systemDefault();
private final ObjectMapper jackson;
private final GaoAiProperties properties;
private final UserLoginService userLoginService;
private final RoleChecker roleChecker;
private final GaoStoreScopeService storeScopeService;
private final GaoStoreService storeService;
private final GaoAiSessionService sessionService;
private final GaoAiAuditService auditService;
private final SettingService settingService;
private HttpClient httpClient;
private ExecutorService streamExecutor;
private ScheduledExecutorService timeoutExecutor;
@PostConstruct
private void postConstruct() {
this.streamExecutor = Executors.newVirtualThreadPerTaskExecutor();
this.timeoutExecutor = Executors.newSingleThreadScheduledExecutor(Thread.ofVirtual().factory());
this.httpClient = HttpClient.newBuilder()
.connectTimeout(Duration.ofSeconds(positive(properties.getConnectTimeoutSeconds(), 10L)))
.executor(streamExecutor)
.version(HttpClient.Version.HTTP_1_1)
.build();
}
@Override
public SseEmitter chat(GaoAiChatRequest request) {
if (request == null || isBlank(request.getMessage())) {
throw new GaoAiAccessException("问题不能为空", 400);
}
String message = request.getMessage().trim();
if (256 < message.length()) {
throw new GaoAiAccessException("问题长度不能超过 256 个字符", 400);
}
if (request.getConversationId() != null && 128 < request.getConversationId().length()) {
throw new GaoAiAccessException("会话 ID 无效", 400);
}
User user = requireAiUser();
String storeId;
try {
storeId = storeScopeService.resolveStoreId(request.getStoreId());
} catch (RuntimeException e) {
throw new GaoAiAccessException("当前账号没有可用的所属门店", 403);
}
GaoStore store = storeId == null ? null : storeService.get(storeId);
if (store == null || !store.isActivated()) {
throw new GaoAiAccessException("当前账号没有可用的所属门店", 403);
}
GaoAiSession session = sessionService.create(user.getId(), storeId, request.getConversationId());
return stream(session, message);
}
@Override
public JsonNode listConversation(GaoAiConversationListRequest request) {
User user = requireAiUser();
String lastId = optionalValue(request == null ? null : request.getLastId(), "上一页游标", 128);
int limit = normalizeLimit(request == null ? null : request.getLimit());
String sortBy = normalizeSortBy(request == null ? null : request.getSortBy());
StringBuilder url = new StringBuilder("/conversations");
appendQueryParameter(url, "user", difyUser(user));
appendQueryParameter(url, "last_id", lastId);
appendQueryParameter(url, "limit", String.valueOf(limit));
appendQueryParameter(url, "sort_by", sortBy);
return sanitizeConversationList(parseJson(sendDify(newDifyRequest(url.toString()).GET().build(), "查询历史会话")));
}
@Override
public JsonNode readConversation(GaoAiConversationReadRequest request) {
User user = requireAiUser();
if (request == null) {
throw new GaoAiAccessException("会话读取参数不能为空", 400);
}
String conversationId = requiredValue(request.getConversationId(), "会话 ID", 128);
String firstId = optionalValue(request.getFirstId(), "上一页游标", 128);
int limit = normalizeLimit(request.getLimit());
StringBuilder url = new StringBuilder("/messages");
appendQueryParameter(url, "user", difyUser(user));
appendQueryParameter(url, "conversation_id", conversationId);
appendQueryParameter(url, "first_id", firstId);
appendQueryParameter(url, "limit", String.valueOf(limit));
return sanitizeConversationMessages(parseJson(sendDify(newDifyRequest(url.toString()).GET().build(), "读取历史会话")));
}
@Override
public void deleteConversation(String conversationId) {
User user = requireAiUser();
String value = requiredValue(conversationId, "会话 ID", 128);
ObjectNode body = jackson.createObjectNode();
body.put("user", difyUser(user));
HttpRequest request = newDifyRequest("/conversations/" + encodePathSegment(value))
.method("DELETE", HttpRequest.BodyPublishers.ofString(writeJson(body), StandardCharsets.UTF_8))
.header("Content-Type", "application/json")
.build();
sendDify(request, "删除历史会话");
}
private SseEmitter stream(GaoAiSession session, String message) {
long readTimeoutSeconds = positive(properties.getReadTimeoutSeconds(), 600L);
long emitterTimeout = Math.min(Long.MAX_VALUE - 1L, readTimeoutSeconds * 1000L + 30_000L);
SseEmitter emitter = new SseEmitter(emitterTimeout);
AtomicBoolean finished = new AtomicBoolean();
AtomicBoolean auditRecorded = new AtomicBoolean();
AtomicReference<String> status = new AtomicReference<>("CANCELLED");
AtomicReference<CompletableFuture<HttpResponse<InputStream>>> upstreamRef = new AtomicReference<>();
AtomicReference<ScheduledFuture<?>> timeoutRef = new AtomicReference<>();
long startedAt = System.currentTimeMillis();
Runnable cancel = () -> {
status.compareAndSet("CANCELLED", "CANCELLED");
finished.set(true);
CompletableFuture<HttpResponse<InputStream>> upstream = upstreamRef.get();
if (upstream != null) {
upstream.cancel(true);
}
cancelTimeout(timeoutRef);
recordAudit(session, message, status.get(), startedAt, auditRecorded);
};
emitter.onCompletion(cancel);
emitter.onTimeout(cancel);
emitter.onError(error -> cancel.run());
try {
HttpRequest httpRequest = buildRequest(session, message, readTimeoutSeconds);
CompletableFuture<HttpResponse<InputStream>> upstream = httpClient.sendAsync(httpRequest, HttpResponse.BodyHandlers.ofInputStream());
upstreamRef.set(upstream);
if (finished.get()) {
upstream.cancel(true);
return emitter;
}
touchTimeout(timeoutRef, readTimeoutSeconds, () -> timeout(emitter, finished, upstreamRef, timeoutRef, status, auditRecorded, session, message, startedAt));
upstream.thenAcceptAsync(response -> readResponse(response, emitter, finished, upstreamRef, timeoutRef,
status, auditRecorded, session, message, startedAt, readTimeoutSeconds), streamExecutor)
.exceptionally(error -> {
if (!finished.get()) {
logStreamError("异步请求", session, error);
status.set("ERROR");
emitError(emitter, "DIFY_UNAVAILABLE", "智能体服务暂时不可用,请稍后重试");
safeComplete(emitter, finished, timeoutRef, auditRecorded, session, message, startedAt, status);
}
return null;
});
} catch (RuntimeException e) {
logStreamError("创建请求", session, e);
status.set("ERROR");
emitError(emitter, "DIFY_REQUEST_ERROR", "智能体服务暂时不可用,请稍后重试");
safeComplete(emitter, finished, timeoutRef, auditRecorded, session, message, startedAt, status);
}
return emitter;
}
private HttpRequest buildRequest(GaoAiSession session, String message, long readTimeoutSeconds) {
ObjectNode body = jackson.createObjectNode();
body.put("query", message);
body.put("response_mode", "streaming");
body.put("user", "gao-store-manager:" + session.getUserId());
if (!isBlank(session.getDifyConversationId())) {
body.put("conversation_id", session.getDifyConversationId());
}
ObjectNode inputs = body.putObject("inputs");
inputs.put("query", message);
inputs.put("aiSessionId", session.getSessionId());
GaoStore store = storeService.get(session.getStoreId());
inputs.put("storeName", store == null ? "当前门店" : store.getName());
inputs.put("today", LocalDate.now(ZONE).toString());
return newDifyRequest("/chat-messages")
.timeout(Duration.ofSeconds(readTimeoutSeconds))
.header("X-Timi-AI-Session", session.getSessionId())
.header("Content-Type", "application/json")
.setHeader("Accept", "text/event-stream")
.POST(HttpRequest.BodyPublishers.ofString(writeJson(body), StandardCharsets.UTF_8))
.build();
}
/// 获取当前登录且有权使用智能体的用户
///
/// @return 当前登录用户
private User requireAiUser() {
User user = userLoginService.getLoginUser();
if (user == null) {
throw new GaoAiAccessException("登录已过期,请重新登录", 401);
}
if (!roleChecker.hasAny(ModuleCode.GAO, GaoRoleCode.STORE_MANAGER.name())) {
throw new GaoAiAccessException("当前账号无权使用门店智能助手", 403);
}
return user;
}
/// 创建 Dify API 请求
///
/// @param path Dify API 路径,可包含已编码的查询参数
/// @return Dify API 请求构造器
private HttpRequest.Builder newDifyRequest(String path) {
String appApiKey = settingService.getSystem(GaoSystemSetting.DIFY_APP_API_KEY).asString();
if (isBlank(appApiKey)) {
throw new GaoAiAccessException("智能体服务未配置", 503);
}
return HttpRequest.newBuilder(difyUri(path))
.timeout(Duration.ofSeconds(Math.min(60L, positive(properties.getReadTimeoutSeconds(), 600L))))
.header("Authorization", "Bearer " + appApiKey)
.header("Accept", "application/json");
}
/// 调用 Dify API
///
/// @param request Dify API 请求
/// @param operation 操作名称
/// @return Dify 响应正文
private String sendDify(HttpRequest request, String operation) {
HttpResponse<String> response;
try {
response = httpClient.send(request, HttpResponse.BodyHandlers.ofString(StandardCharsets.UTF_8));
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new GaoAiAccessException("智能体服务请求被中断", 503);
} catch (IOException | RuntimeException e) {
log.warn("{}失败", operation, e);
throw new GaoAiAccessException("智能体服务暂时不可用,请稍后重试", 503);
}
if (response.statusCode() < 200 || 299 < response.statusCode()) {
log.warn("{}失败:statusCode={}", operation, response.statusCode());
int status = response.statusCode() == 404 ? 404 : 503;
String message = status == 404 ? "历史会话不存在" : "智能体服务暂时不可用,请稍后重试";
throw new GaoAiAccessException(message, status);
}
return response.body();
}
/// 解析 Dify JSON 响应
///
/// @param responseBody 响应正文
/// @return JSON 节点
private JsonNode parseJson(String responseBody) {
try {
return jackson.readTree(responseBody);
} catch (IOException | RuntimeException e) {
log.warn("解析智能体历史会话响应失败", e);
throw new GaoAiAccessException("智能体服务返回数据无效", 503);
}
}
/// 过滤会话列表中的 Dify 内部字段
///
/// @param response Dify 响应
/// @return 脱敏后的响应
private JsonNode sanitizeConversationList(JsonNode response) {
if (response == null || !response.isObject()) {
return response;
}
ObjectNode result = jackson.createObjectNode();
copyFields(response, result, "has_more", "limit");
ArrayNode data = result.putArray("data");
for (JsonNode item : response.path("data")) {
if (!item.isObject()) {
continue;
}
ObjectNode conversation = data.addObject();
copyFields(item, conversation, "id", "name", "status", "introduction", "created_at", "updated_at");
}
return result;
}
/// 过滤会话消息中的 Dify 内部字段
///
/// @param response Dify 响应
/// @return 脱敏后的响应
private JsonNode sanitizeConversationMessages(JsonNode response) {
if (response == null || !response.isObject()) {
return response;
}
ObjectNode result = jackson.createObjectNode();
copyFields(response, result, "has_more", "limit");
ArrayNode data = result.putArray("data");
for (JsonNode item : response.path("data")) {
if (!item.isObject()) {
continue;
}
ObjectNode message = data.addObject();
copyFields(item, message, "id", "conversation_id", "query", "answer", "created_at", "status", "feedback");
}
return result;
}
/// 复制指定的 JSON 字段
///
/// @param source 源 JSON 对象
/// @param target 目标 JSON 对象
/// @param fieldNames 字段名称
/// @return 无
private void copyFields(JsonNode source, ObjectNode target, String... fieldNames) {
for (String fieldName : fieldNames) {
if (source.has(fieldName)) {
target.set(fieldName, source.get(fieldName));
}
}
}
/// 生成 Dify 用户标识
///
/// @param user 登录用户
/// @return Dify 用户标识
private String difyUser(User user) {
return "gao-store-manager:" + user.getId();
}
/// 添加 URL 查询参数
///
/// @param url URL 构造器
/// @param name 参数名称
/// @param value 参数值
/// @return 无
private void appendQueryParameter(StringBuilder url, String name, String value) {
if (isBlank(value)) {
return;
}
url.append(url.indexOf("?") < 0 ? '?' : '&')
.append(name)
.append('=')
.append(URLEncoder.encode(value, StandardCharsets.UTF_8));
}
/// 生成 Dify API URI
///
/// @param path Dify API 路径
/// @return Dify API URI
private URI difyUri(String path) {
String baseUrl = settingService.getSystem(DifySetting.BASE_URL).asString();
if (isBlank(baseUrl)) {
throw new GaoAiAccessException("智能体服务未配置", 503);
}
String normalizedBaseUrl = baseUrl.trim();
while (normalizedBaseUrl.endsWith("/")) {
normalizedBaseUrl = normalizedBaseUrl.substring(0, normalizedBaseUrl.length() - 1);
}
try {
URI uri = URI.create(normalizedBaseUrl + (path.startsWith("/") ? path : "/" + path));
if (!uri.isAbsolute() || isBlank(uri.getScheme()) || isBlank(uri.getHost())) {
throw new IllegalArgumentException("Dify 地址必须是绝对 HTTP 地址");
}
return uri;
} catch (IllegalArgumentException e) {
throw new GaoAiAccessException("智能体服务配置无效", 503);
}
}
/// 编码 URL 路径片段
///
/// @param value 路径片段
/// @return 编码后的路径片段
private String encodePathSegment(String value) {
return URLEncoder.encode(value, StandardCharsets.UTF_8).replace("+", "%20");
}
/// 标准化分页条数
///
/// @param limit 请求的分页条数
/// @return 标准化后的分页条数
private int normalizeLimit(Integer limit) {
int value = limit == null ? 20 : limit;
if (!(0 < value) || 100 < value) {
throw new GaoAiAccessException("分页条数必须在 1 至 100 之间", 400);
}
return value;
}
/// 标准化会话排序方式
///
/// @param sortBy 请求的排序方式
/// @return 标准化后的排序方式
private String normalizeSortBy(String sortBy) {
String value = isBlank(sortBy) ? "-updated_at" : sortBy.trim();
if (!"created_at".equals(value) && !"-created_at".equals(value)
&& !"updated_at".equals(value) && !"-updated_at".equals(value)) {
throw new GaoAiAccessException("会话排序方式无效", 400);
}
return value;
}
/// 校验必填文本参数
///
/// @param value 参数值
/// @param name 参数名称
/// @param maxLength 最大长度
/// @return 去除首尾空白后的参数值
private String requiredValue(String value, String name, int maxLength) {
String result = optionalValue(value, name, maxLength);
if (result == null) {
throw new GaoAiAccessException(name + "不能为空", 400);
}
return result;
}
/// 校验可选文本参数
///
/// @param value 参数值
/// @param name 参数名称
/// @param maxLength 最大长度
/// @return 去除首尾空白后的参数值,无值时返回 null
private String optionalValue(String value, String name, int maxLength) {
if (isBlank(value)) {
return null;
}
String result = value.trim();
if (maxLength < result.length()) {
throw new GaoAiAccessException(name + "无效", 400);
}
return result;
}
private void readResponse(HttpResponse<InputStream> response, SseEmitter emitter, AtomicBoolean finished,
AtomicReference<CompletableFuture<HttpResponse<InputStream>>> upstreamRef, AtomicReference<ScheduledFuture<?>> timeoutRef,
AtomicReference<String> status, AtomicBoolean auditRecorded, GaoAiSession session, String message, long startedAt,
long readTimeoutSeconds) {
try (InputStream stream = response.body()) {
if (response.statusCode() < 200 || 299 < response.statusCode()) {
String responseBody = readErrorResponseBody(stream);
log.error("GAO 智能体返回异常状态:statusCode={}, sessionId={}, userId={}, storeId={}",
response.statusCode(), session.getSessionId(), session.getUserId(), session.getStoreId());
log.error("GAO 智能体错误响应体:sessionId={}, responseBody={}", session.getSessionId(), responseBody);
status.set("ERROR");
emitError(emitter, "DIFY_HTTP_ERROR", "智能体服务暂时不可用,请稍后重试");
safeComplete(emitter, finished, timeoutRef, auditRecorded, session, message, startedAt, status);
return;
}
AtomicReference<String> sseEvent = new AtomicReference<>();
StringBuilder data = new StringBuilder();
try (BufferedReader reader = new BufferedReader(new InputStreamReader(stream, StandardCharsets.UTF_8))) {
String line;
while (!finished.get() && (line = reader.readLine()) != null) {
touchTimeout(timeoutRef, positive(properties.getReadTimeoutSeconds(), 600L),
() -> timeout(emitter, finished, upstreamRef, timeoutRef, status, auditRecorded, session, message, startedAt));
if (line.startsWith("event:")) {
sseEvent.set(line.substring(6).trim());
} else if (line.startsWith("data:")) {
if (!data.isEmpty()) {
data.append('\n');
}
String dataLine = line.substring(5);
data.append(dataLine.startsWith(" ") ? dataLine.substring(1) : dataLine);
} else if (line.isEmpty() && !data.isEmpty()) {
processData(data.toString(), sseEvent.get(), emitter, status, finished, timeoutRef, auditRecorded,
session, message, startedAt);
data.setLength(0);
sseEvent.set(null);
}
}
if (!finished.get() && !data.isEmpty()) {
processData(data.toString(), sseEvent.get(), emitter, status, finished, timeoutRef, auditRecorded,
session, message, startedAt);
}
}
if (!finished.get()) {
status.compareAndSet("CANCELLED", "SUCCESS");
emitDone(emitter, session, startedAt, finished, timeoutRef, auditRecorded, message, status);
}
} catch (IOException | RuntimeException e) {
if (!finished.get()) {
logStreamError("读取响应", session, e);
status.set("ERROR");
emitError(emitter, "DIFY_STREAM_ERROR", "智能体连接中断,请重试");
safeComplete(emitter, finished, timeoutRef, auditRecorded, session, message, startedAt, status);
}
}
}
/// 读取并压缩 Dify 错误响应体
///
/// @param stream Dify 响应流
/// @return 错误响应内容
/// @throws IOException 读取响应体失败
private String readErrorResponseBody(InputStream stream) throws IOException {
int maxLength = 8192;
byte[] bytes = stream.readNBytes(maxLength);
String body = new String(bytes, StandardCharsets.UTF_8)
.replace('\r', ' ')
.replace('\n', ' ')
.replace('\t', ' ')
.trim();
return maxLength <= bytes.length ? body + "..." : body;
}
private void processData(String rawData, String sseEvent, SseEmitter emitter, AtomicReference<String> status,
AtomicBoolean finished, AtomicReference<ScheduledFuture<?>> timeoutRef, AtomicBoolean auditRecorded,
GaoAiSession session, String message, long startedAt) {
if ("[DONE]".equals(rawData)) {
return;
}
JsonNode payload;
try {
payload = jackson.readTree(rawData);
} catch (IOException e) {
log.error("GAO 智能体 SSE 数据解析失败:sessionId={}, userId={}, storeId={}, dataLength={}",
session.getSessionId(), session.getUserId(), session.getStoreId(), rawData.length(), e);
return;
}
String event = firstText(text(payload, "event", null), sseEvent, "message");
String conversationId = firstText(text(payload, "conversation_id", null), text(payload, "conversationId", null));
if (conversationId != null) {
session.setDifyConversationId(conversationId);
}
switch (event) {
case "message", "agent_message", "text_chunk" -> {
String answer = firstRawText(payload, "answer");
if (answer == null) {
answer = firstRawText(payload, "text");
}
if (answer != null && !answer.isEmpty()) {
Map<String, String> messageData = Map.of("answer", answer);
safeSend(emitter, SseEmitter.event().name("message").data(messageData), finished);
}
}
case "message_end" -> emitDone(emitter, session, startedAt, finished, timeoutRef, auditRecorded, message, status);
case "node_started", "node_finished", "workflow_started", "workflow_finished" -> {
Map<String, Object> data = new LinkedHashMap<>();
data.put("tool", "实时数据查询");
data.put("status", event.endsWith("finished") ? "finished" : "started");
safeSend(emitter, SseEmitter.event().name("tool_status").data(data), finished);
}
case "message_file", "retriever_resources" -> {
Map<String, Object> data = new LinkedHashMap<>();
data.put("source", "实时业务数据或业务知识库");
safeSend(emitter, SseEmitter.event().name("citation").data(data), finished);
}
case "error" -> {
status.set("ERROR");
emitError(emitter, "DIFY_ERROR", "智能体查询失败,请稍后重试");
safeComplete(emitter, finished, timeoutRef, auditRecorded, session, message, startedAt, status);
}
default -> {
// 未识别的 Dify 事件不透传原始内容,避免泄露内部节点和参数
}
}
}
private void emitDone(SseEmitter emitter, GaoAiSession session, long startedAt, AtomicBoolean finished,
AtomicReference<ScheduledFuture<?>> timeoutRef, AtomicBoolean auditRecorded, String message,
AtomicReference<String> status) {
if (finished.get()) {
return;
}
Map<String, Object> data = new LinkedHashMap<>();
data.put("conversationId", session.getDifyConversationId());
data.put("duration", Math.max(0L, System.currentTimeMillis() - startedAt));
safeSend(emitter, SseEmitter.event().name("done").data(data), finished);
status.compareAndSet("CANCELLED", "SUCCESS");
safeComplete(emitter, finished, timeoutRef, auditRecorded, session, message, startedAt, status);
}
private void emitError(SseEmitter emitter, String code, String message) {
Map<String, Object> data = new LinkedHashMap<>();
data.put("code", code);
data.put("message", message);
try {
emitter.send(SseEmitter.event().name("error").data(data));
} catch (IOException | IllegalStateException ignored) {
// 浏览器已断开时无需再次写入
}
}
private boolean safeSend(SseEmitter emitter, SseEmitter.SseEventBuilder event, AtomicBoolean finished) {
if (finished.get()) {
return false;
}
try {
emitter.send(event);
return true;
} catch (IOException | IllegalStateException e) {
finished.set(true);
return false;
}
}
private void safeComplete(SseEmitter emitter, AtomicBoolean finished, AtomicReference<ScheduledFuture<?>> timeoutRef,
AtomicBoolean auditRecorded, GaoAiSession session, String message, long startedAt, AtomicReference<String> status) {
if (!finished.compareAndSet(false, true)) {
return;
}
cancelTimeout(timeoutRef);
recordAudit(session, message, status.get(), startedAt, auditRecorded);
try {
emitter.complete();
} catch (RuntimeException ignored) {
// SSE 已经关闭
}
}
private void timeout(SseEmitter emitter, AtomicBoolean finished,
AtomicReference<CompletableFuture<HttpResponse<InputStream>>> upstreamRef,
AtomicReference<ScheduledFuture<?>> timeoutRef, AtomicReference<String> status,
AtomicBoolean auditRecorded, GaoAiSession session, String message, long startedAt) {
if (finished.get()) {
return;
}
status.set("TIMEOUT");
CompletableFuture<HttpResponse<InputStream>> upstream = upstreamRef.get();
if (upstream != null) {
upstream.cancel(true);
}
emitError(emitter, "DIFY_TIMEOUT", "数据查询超时,请缩小时间范围后重试");
safeComplete(emitter, finished, timeoutRef, auditRecorded, session, message, startedAt, status);
}
private void touchTimeout(AtomicReference<ScheduledFuture<?>> timeoutRef, long seconds, Runnable action) {
ScheduledFuture<?> old = timeoutRef.getAndSet(timeoutExecutor.schedule(action, seconds, TimeUnit.SECONDS));
if (old != null) {
old.cancel(false);
}
}
private void cancelTimeout(AtomicReference<ScheduledFuture<?>> timeoutRef) {
ScheduledFuture<?> timeout = timeoutRef.getAndSet(null);
if (timeout != null) {
timeout.cancel(false);
}
}
private void recordAudit(GaoAiSession session, String message, String status, long startedAt, AtomicBoolean recorded) {
if (!recorded.compareAndSet(false, true)) {
return;
}
GaoAiAuditLog audit = new GaoAiAuditLog();
audit.setUserId(session.getUserId());
audit.setStoreId(session.getStoreId());
audit.setQuestionDigest(auditService.digest(message));
audit.setConversationId(session.getDifyConversationId());
audit.setToolName("dify_chatflow");
audit.setDuration(Math.max(0L, System.currentTimeMillis() - startedAt));
audit.setStatus(status);
audit.setResultCount(0L);
audit.setCreatedAt(System.currentTimeMillis());
auditService.record(audit);
}
/// 记录智能体流式请求异常
///
/// @param phase 异常阶段
/// @param session 智能体会话
/// @param error 异常
/// @return 无
private void logStreamError(String phase, GaoAiSession session, Throwable error) {
log.error("GAO 智能体流式请求异常:phase={}, sessionId={}, userId={}, storeId={}",
phase, session.getSessionId(), session.getUserId(), session.getStoreId(), error);
}
private String writeJson(ObjectNode body) {
try {
return jackson.writeValueAsString(body);
} catch (IOException e) {
throw new IllegalStateException("无法生成 Dify 请求", e);
}
}
private String text(JsonNode node, String field, String fallback) {
if (node != null && node.hasNonNull(field)) {
String value = node.get(field).asText();
return isBlank(value) ? fallback : value;
}
return fallback;
}
private String firstRawText(JsonNode node, String field) {
if (node != null && node.hasNonNull(field)) {
return node.get(field).asText();
}
return null;
}
private String firstText(String... values) {
for (String value : values) {
if (!isBlank(value)) {
return value;
}
}
return null;
}
private long positive(long value, long fallback) {
return 0 < value ? value : fallback;
}
private boolean isBlank(String value) {
return value == null || value.trim().isEmpty();
}
}
@@ -0,0 +1,783 @@
package com.imyeyu.api.modules.gao.ai.service.implement;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.imyeyu.api.modules.common.entity.Article;
import com.imyeyu.api.modules.gao.ai.config.GaoAiProperties;
import com.imyeyu.api.modules.gao.ai.entity.GaoAiSession;
import com.imyeyu.api.modules.gao.ai.service.GaoAiQueryService;
import com.imyeyu.api.modules.gao.ai.service.GaoAiToolException;
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.GaoCustomerConsumptionRecord;
import com.imyeyu.api.modules.gao.entity.GaoCustomerPackage;
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.GaoPointAccount;
import com.imyeyu.api.modules.gao.entity.GaoPointLedger;
import com.imyeyu.api.modules.gao.entity.GaoProductStock;
import com.imyeyu.api.modules.gao.entity.GaoSalesOrder;
import com.imyeyu.api.modules.gao.entity.GaoStore;
import com.imyeyu.api.modules.gao.entity.GaoStoreBusinessDay;
import com.imyeyu.api.modules.gao.service.GaoCustomerConsumptionRecordService;
import com.imyeyu.api.modules.gao.service.GaoCustomerPackageService;
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.GaoPointAccountService;
import com.imyeyu.api.modules.gao.service.GaoPointLedgerService;
import com.imyeyu.api.modules.gao.service.GaoPointRedemptionService;
import com.imyeyu.api.modules.gao.service.GaoPointRuleService;
import com.imyeyu.api.modules.gao.service.GaoProductChartService;
import com.imyeyu.api.modules.gao.service.GaoProductStockService;
import com.imyeyu.api.modules.gao.service.GaoSalesOrderChartService;
import com.imyeyu.api.modules.gao.service.GaoSalesOrderService;
import com.imyeyu.api.modules.gao.service.GaoStoreBusinessDayService;
import com.imyeyu.api.modules.gao.service.GaoStoreDiaryService;
import com.imyeyu.api.modules.gao.service.GaoStoreService;
import com.imyeyu.api.modules.gao.vo.GaoCustomerPage;
import com.imyeyu.api.modules.gao.vo.GaoCustomerPackagePage;
import com.imyeyu.api.modules.gao.vo.GaoEventRecordPage;
import com.imyeyu.api.modules.gao.vo.GaoFundRecordPage;
import com.imyeyu.api.modules.gao.vo.GaoPointLedgerPage;
import com.imyeyu.api.modules.gao.vo.GaoPointRedemptionPage;
import com.imyeyu.api.modules.gao.vo.GaoProductChartReq;
import com.imyeyu.api.modules.gao.vo.GaoProductStockPage;
import com.imyeyu.api.modules.gao.vo.GaoSalesOrderChartReq;
import com.imyeyu.api.modules.gao.vo.GaoSalesOrderPage;
import com.imyeyu.api.modules.gao.vo.GaoStoreDiaryPage;
import com.imyeyu.spring.bean.PageResult;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import java.time.Instant;
import java.time.LocalDate;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.Collection;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Set;
/// GAO 智能体只读查询服务实现
///
/// 所有查询都将会话中的门店 ID 写入既有查询请求,不接受工具参数中的门店范围
///
/// @author Codex
/// @since 2026-09-15
@Service
@RequiredArgsConstructor
public class GaoAiQueryServiceImplement implements GaoAiQueryService {
private static final ZoneId ZONE = ZoneId.systemDefault();
private static final DateTimeFormatter DATE_FORMATTER = DateTimeFormatter.ISO_LOCAL_DATE;
private static final DateTimeFormatter DAY_VALUE_FORMATTER = DateTimeFormatter.ofPattern("yyyyMMdd");
private static final Set<String> SENSITIVE_KEYS = Set.of(
"id",
"storeId",
"userId",
"customerId",
"operatorUserId",
"verifierUserId",
"creatorUserId",
"updatedBy",
"cancelOperatorUserId",
"sourcePayload",
"attachmentList",
"skuSpecSnapshot",
"password",
"token",
"apiKey",
"phone",
"mobile",
"telephone",
"email",
"address"
);
private final ObjectMapper jackson;
private final GaoAiProperties properties;
private final GaoStoreService storeService;
private final GaoStoreBusinessDayService businessDayService;
private final GaoCustomerService customerService;
private final GaoCustomerPackageService customerPackageService;
private final GaoCustomerConsumptionRecordService consumptionRecordService;
private final GaoEventService eventService;
private final GaoEventRecordService eventRecordService;
private final GaoSalesOrderService salesOrderService;
private final GaoSalesOrderChartService salesOrderChartService;
private final GaoFundRecordService fundRecordService;
private final GaoProductStockService stockService;
private final GaoProductChartService productChartService;
private final GaoPointAccountService pointAccountService;
private final GaoPointLedgerService pointLedgerService;
private final GaoPointRuleService pointRuleService;
private final GaoPointRedemptionService redemptionService;
private final GaoStoreDiaryService storeDiaryService;
@Override
public GaoAiToolResult storeOverview(GaoAiSession session, GaoAiToolRequest request) {
request = normalize(request);
TimeWindow window = resolveWindow(request, "TODAY", false);
GaoStore store = requireStore(session);
GaoSalesOrderChartReq salesRequest = salesChartRequest(session, window, request);
List<?> daily = salesOrderChartService.daily(salesRequest);
Object receivable = salesOrderChartService.receivable(salesRequest);
GaoProductChartReq productRequest = productChartRequest(session, window, request);
List<?> stockHealth = productChartService.stockHealth(productRequest);
List<GaoStoreBusinessDay> businessDays = businessDayService.listByDateRange(
session.getStoreId(), window.beginDateValue(), window.endDateValue());
Map<String, Object> summary = new LinkedHashMap<>();
summary.put("store", store.getName());
summary.put("salesDaily", daily);
summary.put("receivable", receivable);
summary.put("businessDays", businessDays);
summary.put("stockHealth", stockHealth);
List<Object> alerts = new ArrayList<>();
for (Object item : stockHealth) {
if (isLowStock(item)) {
alerts.add(item);
}
}
if (alerts.isEmpty() && !stockHealth.isEmpty()) {
alerts.add("当前查询范围未发现低库存产品");
}
return buildResult(session, window, summary, List.of(), alerts, "门店营业日、销售订单、应收和库存健康");
}
@Override
public GaoAiToolResult customerSearch(GaoAiSession session, GaoAiToolRequest request) {
request = normalize(request);
TimeWindow window = resolveWindow(request, "TODAY", false);
GaoCustomerPage page = new GaoCustomerPage();
page.setStoreId(session.getStoreId());
page.setKeyword(firstText(request.getQuery(), filter(request, "keyword")));
page.setBeginCreatedAt(window.begin());
page.setEndCreatedAt(window.end());
setPage(page, request);
PageResult<GaoCustomer> result = customerService.pageByQuery(page);
return buildPagedResult(session, window, result, "客户档案", request.getCursor());
}
@Override
public GaoAiToolResult customerProfile(GaoAiSession session, GaoAiToolRequest request) {
request = normalize(request);
TimeWindow window = resolveWindow(request, "TODAY", false);
GaoCustomer customer = findCustomer(session.getStoreId(), request);
if (customer == null) {
return buildResult(session, window, Map.of(), List.of(), List.of("当前门店未查到匹配客户"), "客户、套餐、积分、消费和事件档案");
}
GaoCustomerPackagePage packagePage = new GaoCustomerPackagePage();
packagePage.setStoreId(session.getStoreId());
packagePage.setCustomerId(customer.getId());
packagePage.setStatus(enumFilter(request, "status", GaoSalesOrder.Status.class));
packagePage.setIndex(0);
packagePage.setSize(maxPageSize());
PageResult<GaoCustomerPackage> packages = customerPackageService.pageByQuery(packagePage);
GaoPointAccount account = pointAccountService.getByCustomerId(session.getStoreId(), customer.getId());
GaoEventRecordPage eventPage = eventRecordPage(session, window, request);
eventPage.setCustomerId(customer.getId());
PageResult<GaoEventRecord> events = eventRecordService.pageByRange(eventPage);
if (events != null) {
attachEventDisplay(events.getList());
}
List<GaoCustomerConsumptionRecord> consumptions = consumptionRecordService.listActiveByWindow(
session.getStoreId(), customer.getId(), window.begin(), window.end());
Map<String, Object> summary = new LinkedHashMap<>();
summary.put("customer", customer);
summary.put("pointAccount", account);
summary.put("packages", packages == null ? List.of() : packages.getList());
summary.put("events", events == null ? List.of() : events.getList());
summary.put("activeConsumptions", consumptions);
return buildResult(session, window, summary, List.of(), List.of(), "客户、套餐、积分、消费和事件档案");
}
@Override
public GaoAiToolResult orderQuery(GaoAiSession session, GaoAiToolRequest request) {
request = normalize(request);
TimeWindow window = resolveWindow(request, "TODAY", false);
GaoSalesOrderPage page = new GaoSalesOrderPage();
page.setStoreId(session.getStoreId());
page.setCustomerId(resolveCustomerId(session.getStoreId(), filter(request, "customerId")));
page.setOrderType(enumFilter(request, "orderType", GaoSalesOrder.OrderType.class));
page.setStatus(enumFilter(request, "status", GaoSalesOrder.Status.class));
page.setPaymentStatus(enumFilter(request, "paymentStatus", GaoSalesOrder.PaymentStatus.class));
page.setRefundStatus(enumFilter(request, "refundStatus", GaoSalesOrder.RefundStatus.class));
page.setPendingReceive(booleanFilter(request, "pendingReceive"));
page.setFulfilledButUnpaid(booleanFilter(request, "fulfilledButUnpaid"));
page.setKeyword(firstText(request.getQuery(), filter(request, "keyword")));
page.setBeginAt(window.begin());
page.setEndAt(window.end());
setPage(page, request);
PageResult<GaoSalesOrder> orders = salesOrderService.pageByQuery(page);
GaoFundRecordPage fundPage = new GaoFundRecordPage();
fundPage.setStoreId(session.getStoreId());
fundPage.setCustomerId(page.getCustomerId());
fundPage.setBeginAt(window.begin());
fundPage.setEndAt(window.end());
fundPage.setIndex(0);
fundPage.setSize(maxPageSize());
PageResult<GaoFundRecord> funds = fundRecordService.pageByQuery(fundPage);
Map<String, Object> summary = new LinkedHashMap<>();
summary.put("ordersTotal", orders == null ? 0L : orders.getTotal());
summary.put("fundRecordsTotal", funds == null ? 0L : funds.getTotal());
summary.put("fundRecords", funds == null ? List.of() : funds.getList());
return buildResult(session, window, summary, pageDetails(orders), List.of(), "销售订单、履约和资金流水");
}
@Override
public GaoAiToolResult eventQuery(GaoAiSession session, GaoAiToolRequest request) {
request = normalize(request);
TimeWindow window = resolveWindow(request, "TODAY", false);
GaoEventRecordPage page = eventRecordPage(session, window, request);
String eventId = filter(request, "eventId");
if (!isBlank(eventId)) {
GaoEvent event = eventService.get(eventId);
if (event != null && !session.getStoreId().equals(event.getStoreId())) {
throw new GaoAiToolException("事件不属于当前门店", 403);
}
page.setEventIdList(List.of(eventId));
}
String eventKeyword = firstText(filter(request, "event"), filter(request, "eventName"));
if (eventKeyword != null && isBlank(eventId)) {
List<String> eventIdList = eventService.listValid(session.getStoreId()).stream()
.filter(item -> containsIgnoreCase(item.getName(), eventKeyword))
.map(GaoEvent::getId)
.toList();
page.setEventIdList(eventIdList);
}
PageResult<GaoEventRecord> records = eventRecordService.pageByRange(page);
attachEventDisplay(records == null ? null : records.getList());
List<Object> details = pageDetails(records);
Map<String, Object> summary = new LinkedHashMap<>();
summary.put("total", records == null ? 0L : records.getTotal());
summary.put("returnedCount", details.size());
summary.put("numberValueTotal", eventRecordService.sumNumberValueByRange(page));
summary.put("optionStatistics", eventRecordService.optionStatByRange(page));
if (records != null && details.size() < records.getTotal()) {
summary.put("hasMore", true);
summary.put("nextCursor", String.valueOf(cursorIndex(request.getCursor()) + 1));
}
return buildResult(session, window, summary, details, List.of(), "登记事件记录和选项统计");
}
@Override
public GaoAiToolResult productInventoryQuery(GaoAiSession session, GaoAiToolRequest request) {
request = normalize(request);
TimeWindow window = resolveWindow(request, "TODAY", false);
GaoProductStockPage page = new GaoProductStockPage();
page.setStoreId(session.getStoreId());
page.setProductId(filter(request, "productId"));
page.setKeyword(firstText(request.getQuery(), filter(request, "keyword")));
setPage(page, request);
PageResult<GaoProductStock> stocks = stockService.pageByQuery(page);
GaoProductChartReq productRequest = productChartRequest(session, window, request);
List<?> stockHealth = productChartService.stockHealth(productRequest);
List<?> stockMovementDaily = productChartService.stockMovementDaily(productRequest);
List<?> salesRank = productChartService.salesRank(productRequest);
List<Object> details = pageDetails(stocks);
Map<String, Object> summary = new LinkedHashMap<>();
summary.put("total", stocks == null ? 0L : stocks.getTotal());
summary.put("returnedCount", details.size());
summary.put("stockHealth", stockHealth);
summary.put("stockMovementDaily", stockMovementDaily);
summary.put("salesRank", salesRank);
if (stocks != null && details.size() < stocks.getTotal()) {
summary.put("hasMore", true);
summary.put("nextCursor", String.valueOf(cursorIndex(request.getCursor()) + 1));
}
return buildResult(session, window, summary, details, List.of(), "产品、SKU、库存和销售摘要");
}
@Override
public GaoAiToolResult pointQuery(GaoAiSession session, GaoAiToolRequest request) {
request = normalize(request);
TimeWindow window = resolveWindow(request, "TODAY", false);
String customerId = resolveCustomerId(session.getStoreId(), filter(request, "customerId"));
Map<String, Object> summary = new LinkedHashMap<>();
List<Object> details = new ArrayList<>();
if (customerId == null && request.getQuery() != null) {
customerId = resolveCustomerId(session.getStoreId(), request.getQuery());
}
if (customerId != null) {
summary.put("account", pointAccountService.getByCustomerId(session.getStoreId(), customerId));
}
GaoPointLedgerPage ledgerPage = new GaoPointLedgerPage();
ledgerPage.setStoreId(session.getStoreId());
ledgerPage.setCustomerId(customerId);
ledgerPage.setChangeType(enumFilter(request, "changeType", GaoPointLedger.ChangeType.class));
ledgerPage.setBeginAt(window.begin());
ledgerPage.setEndAt(window.end());
setPage(ledgerPage, request);
PageResult<GaoPointLedger> ledgers = pointLedgerService.pageByQuery(ledgerPage);
details.addAll(pageDetails(ledgers));
summary.put("ledgerTotal", ledgers == null ? 0L : ledgers.getTotal());
GaoPointRedemptionPage redemptionPage = new GaoPointRedemptionPage();
redemptionPage.setStoreId(session.getStoreId());
redemptionPage.setCustomerId(customerId);
redemptionPage.setKeyword(firstText(request.getQuery(), filter(request, "keyword")));
redemptionPage.setBeginAt(window.begin());
redemptionPage.setEndAt(window.end());
redemptionPage.setIndex(0);
redemptionPage.setSize(maxPageSize());
summary.put("redemptions", redemptionService.pageByQuery(redemptionPage));
summary.put("activeRules", pointRuleService.listActive(session.getStoreId(), null, null, System.currentTimeMillis()));
return buildResult(session, window, summary, details, List.of(), "积分账户、积分流水、规则和兑换");
}
@Override
public GaoAiToolResult businessReport(GaoAiSession session, GaoAiToolRequest request) {
request = normalize(request);
TimeWindow window = resolveWindow(request, "THIS_MONTH", true);
GaoSalesOrderChartReq salesRequest = salesChartRequest(session, window, request);
List<?> salesDaily = salesOrderChartService.daily(salesRequest);
Object receivable = salesOrderChartService.receivable(salesRequest);
List<?> customerRank = salesOrderChartService.customerRank(salesRequest);
List<?> repeatDaily = salesOrderChartService.repeatDaily(salesRequest);
List<?> repeatInterval = salesOrderChartService.repeatInterval(salesRequest);
GaoProductChartReq productRequest = productChartRequest(session, window, request);
List<?> productRank = productChartService.salesRank(productRequest);
Map<String, Object> summary = new LinkedHashMap<>();
summary.put("salesDaily", salesDaily);
summary.put("receivable", receivable);
summary.put("customerRank", customerRank);
summary.put("repeatDaily", repeatDaily);
summary.put("repeatInterval", repeatInterval);
summary.put("productRank", productRank);
return buildResult(session, window, summary, List.of(), List.of(), "销售趋势、排行、复购和应收分析");
}
@Override
public GaoAiToolResult storeDiaryQuery(GaoAiSession session, GaoAiToolRequest request) {
request = normalize(request);
TimeWindow window = resolveWindow(request, "TODAY", false);
GaoStoreDiaryPage page = new GaoStoreDiaryPage();
page.setStoreId(session.getStoreId());
page.setBeginCreatedAt(window.begin());
page.setEndCreatedAt(window.end());
setPage(page, request);
PageResult<Article> diaries = storeDiaryService.page(page);
return buildPagedResult(session, window, diaries, "门店日记和营业日信息", request.getCursor());
}
@Override
public GaoAiToolResult metricDefinition(GaoAiSession session, GaoAiToolRequest request) {
TimeWindow window = resolveWindow(normalize(request), "TODAY", false);
Map<String, Object> summary = new LinkedHashMap<>();
summary.put("有效销售订单", "状态为 ACTIVE 或 FULFILLED 的销售订单;已取消订单不计入有效销售");
summary.put("销售额", "有效销售订单的成交金额,单位为分,展示层按金额格式化");
summary.put("实收金额", "销售订单已确认收款金额,不包含待核销收款");
summary.put("应收金额", "成交金额减去已确认实收金额");
summary.put("有效消费", "状态为 ACTIVE 的客户消费事实,仅在订单全额实收后参与累计");
summary.put("可用库存", "库存现有量减去履约预占量");
summary.put("复购客户", "统计范围内发生两次及以上有效消费或有效订单的客户,具体以报表工具返回口径为准");
summary.put("数据边界", "实时业务数据只来自 GAO 查询服务,不包含知识库中的静态规则数据");
return buildResult(session, window, summary, List.of(), List.of(), "门店经营指标名称和计算口径");
}
private GaoAiToolRequest normalize(GaoAiToolRequest request) {
GaoAiToolRequest result = request == null ? new GaoAiToolRequest() : request;
if (result.getFilters() != null && containsStoreId(result.getFilters())) {
throw new GaoAiToolException("工具请求不允许携带 storeId", 403);
}
if (result.getQuery() != null && 256 < result.getQuery().length()) {
throw new GaoAiToolException("查询关键词过长", 400);
}
return result;
}
private GaoStore requireStore(GaoAiSession session) {
if (session == null || isBlank(session.getStoreId())) {
throw new GaoAiToolException("AI 会话缺少门店范围", 403);
}
GaoStore store = storeService.get(session.getStoreId());
if (store == null || !store.isActivated()) {
throw new GaoAiToolException("当前门店不存在或未启用", 403);
}
return store;
}
private GaoCustomer findCustomer(String storeId, GaoAiToolRequest request) {
String customerId = filter(request, "customerId");
if (!isBlank(customerId)) {
GaoCustomer customer = customerService.get(customerId);
if (customer != null && !storeId.equals(customer.getStoreId())) {
throw new GaoAiToolException("客户不属于当前门店", 403);
}
return customer;
}
String query = request.getQuery();
if (isBlank(query)) {
return null;
}
GaoCustomer customer = customerService.getByCode(storeId, query);
if (customer == null) {
customer = customerService.getByName(storeId, query);
}
if (customer != null) {
return customer;
}
GaoCustomerPage page = new GaoCustomerPage();
page.setStoreId(storeId);
page.setKeyword(query);
page.setIndex(0);
page.setSize(1);
PageResult<GaoCustomer> result = customerService.pageByQuery(page);
return result == null || result.getList() == null || result.getList().isEmpty() ? null : result.getList().getFirst();
}
private String resolveCustomerId(String storeId, String value) {
if (isBlank(value)) {
return null;
}
GaoCustomer customer = customerService.get(value);
if (customer != null) {
if (!storeId.equals(customer.getStoreId())) {
throw new GaoAiToolException("客户不属于当前门店", 403);
}
return customer.getId();
}
customer = customerService.getByCode(storeId, value);
if (customer == null) {
customer = customerService.getByName(storeId, value);
}
return customer == null ? null : customer.getId();
}
private GaoEventRecordPage eventRecordPage(GaoAiSession session, TimeWindow window, GaoAiToolRequest request) {
GaoEventRecordPage page = new GaoEventRecordPage();
page.setStoreId(session.getStoreId());
page.setVerificationStatus(enumFilter(request, "verificationStatus", GaoEventRecord.VerificationStatus.class));
page.setKeyword(firstText(request.getQuery(), filter(request, "keyword")));
page.setBeginAt(window.begin());
page.setEndAt(window.end());
setPage(page, request);
return page;
}
private GaoSalesOrderChartReq salesChartRequest(GaoAiSession session, TimeWindow window, GaoAiToolRequest request) {
GaoSalesOrderChartReq result = new GaoSalesOrderChartReq();
result.setStoreId(session.getStoreId());
result.setCustomerId(resolveCustomerId(session.getStoreId(), filter(request, "customerId")));
result.setProductId(filter(request, "productId"));
result.setSkuId(filter(request, "skuId"));
result.setBeginAt(window.begin());
result.setEndAt(window.end());
result.setTopN(maxPageSize());
return result;
}
private GaoProductChartReq productChartRequest(GaoAiSession session, TimeWindow window, GaoAiToolRequest request) {
GaoProductChartReq result = new GaoProductChartReq();
result.setStoreId(session.getStoreId());
result.setProductId(filter(request, "productId"));
result.setSkuId(filter(request, "skuId"));
result.setCategoryId(filter(request, "categoryId"));
result.setBeginAt(window.begin());
result.setEndAt(window.end());
result.setTopN(maxPageSize());
return result;
}
private void attachEventDisplay(List<GaoEventRecord> list) {
if (list == null || list.isEmpty()) {
return;
}
Map<String, GaoEvent> eventMap = eventService.mapByIdList(list.stream().map(GaoEventRecord::getEventId).distinct().toList());
Map<String, GaoCustomer> customerMap = customerService.mapByIdList(list.stream().map(GaoEventRecord::getCustomerId).distinct().toList());
for (GaoEventRecord record : list) {
record.setEvent(eventMap.get(record.getEventId()));
record.setCustomer(customerMap.get(record.getCustomerId()));
}
eventRecordService.attachSelectedOptionGroupList(list);
}
private GaoAiToolResult buildPagedResult(GaoAiSession session, TimeWindow window, PageResult<?> page, String metric,
String cursor) {
List<Object> details = pageDetails(page);
Map<String, Object> summary = new LinkedHashMap<>();
summary.put("total", page == null ? 0L : page.getTotal());
summary.put("returnedCount", details.size());
if (page != null && details.size() < page.getTotal()) {
summary.put("hasMore", true);
summary.put("nextCursor", String.valueOf(cursorIndex(cursor) + 1));
}
return buildResult(session, window, summary, details, List.of(), metric);
}
private List<Object> pageDetails(PageResult<?> page) {
return page == null || page.getList() == null ? new ArrayList<>() : sanitizeList(page.getList());
}
private GaoAiToolResult buildResult(GaoAiSession session, TimeWindow window, Map<String, Object> summary,
Collection<?> details, Collection<?> alerts, String metric) {
GaoAiToolResult result = new GaoAiToolResult();
Map<String, Object> scope = new LinkedHashMap<>();
GaoStore store = requireStore(session);
scope.put("storeName", store.getName());
scope.put("timeRange", window.display());
result.setScope(scope);
result.setSummary(sanitizeMap(summary));
result.setDetails(sanitizeList(details));
result.setAlerts(sanitizeList(alerts));
Map<String, Object> source = new LinkedHashMap<>();
source.put("metric", metric);
source.put("generatedAt", Instant.now().atZone(ZONE).toOffsetDateTime().toString());
result.setSource(source);
return result;
}
private TimeWindow resolveWindow(GaoAiToolRequest request, String defaultPreset, boolean trend) {
String preset = request.getTimeRange() == null ? defaultPreset : request.getTimeRange().getPreset();
if (isBlank(preset)) {
preset = defaultPreset;
}
preset = preset.trim().toUpperCase(Locale.ROOT);
LocalDate today = LocalDate.now(ZONE);
LocalDate start;
LocalDate end;
switch (preset) {
case "TODAY" -> {
start = today;
end = today;
}
case "LAST_7_DAYS" -> {
start = today.minusDays(6);
end = today;
}
case "LAST_30_DAYS" -> {
start = today.minusDays(29);
end = today;
}
case "THIS_MONTH" -> {
start = today.withDayOfMonth(1);
end = start.plusMonths(1).minusDays(1);
}
case "THIS_YEAR" -> {
start = today.withDayOfYear(1);
end = start.plusYears(1).minusDays(1);
}
case "CUSTOM" -> {
if (request.getTimeRange() == null || isBlank(request.getTimeRange().getStartDate())
|| isBlank(request.getTimeRange().getEndDate())) {
throw new GaoAiToolException("自定义时间范围必须同时提供开始和结束日期", 400);
}
try {
start = LocalDate.parse(request.getTimeRange().getStartDate(), DATE_FORMATTER);
end = LocalDate.parse(request.getTimeRange().getEndDate(), DATE_FORMATTER);
} catch (RuntimeException e) {
throw new GaoAiToolException("日期格式必须为 yyyy-MM-dd", 400);
}
}
default -> throw new GaoAiToolException("不支持的时间范围预设:" + preset, 400);
}
if (start.isAfter(end)) {
throw new GaoAiToolException("时间范围无效", 400);
}
long days = ChronoUnit.DAYS.between(start, end) + 1L;
long maxDays = trend ? 365L : 31L;
if (maxDays < days) {
throw new GaoAiToolException(trend ? "趋势查询最多支持 365 天" : "明细查询最多支持 31 天", 400);
}
long begin = start.atStartOfDay(ZONE).toInstant().toEpochMilli();
long finish = end.plusDays(1).atStartOfDay(ZONE).toInstant().toEpochMilli();
return new TimeWindow(start, end, begin, finish);
}
private int maxPageSize() {
int max = properties.getMaxToolPageSize();
if (20 < max) {
max = 20;
}
if (max < 1) {
max = 1;
}
return max;
}
private void setPage(com.imyeyu.java.bean.BasePage page, GaoAiToolRequest request) {
int size = request.getPageSize() == null ? maxPageSize() : request.getPageSize();
if (size < 1) {
size = 1;
}
if (maxPageSize() < size) {
size = maxPageSize();
}
page.setSize(size);
page.setIndex(cursorIndex(request.getCursor()));
}
private int cursorIndex(String cursor) {
if (isBlank(cursor)) {
return 0;
}
try {
int index = Integer.parseInt(cursor);
return index < 0 ? 0 : index;
} catch (NumberFormatException e) {
throw new GaoAiToolException("分页游标无效", 400);
}
}
private <E extends Enum<E>> E enumFilter(GaoAiToolRequest request, String key, Class<E> type) {
String value = filter(request, key);
if (isBlank(value)) {
return null;
}
try {
return Enum.valueOf(type, value.trim().toUpperCase(Locale.ROOT));
} catch (IllegalArgumentException e) {
throw new GaoAiToolException("过滤条件无效:" + key, 400);
}
}
private Boolean booleanFilter(GaoAiToolRequest request, String key) {
String value = filter(request, key);
return isBlank(value) ? null : Boolean.valueOf(value);
}
private String filter(GaoAiToolRequest request, String key) {
if (request == null || request.getFilters() == null) {
return null;
}
Object value = request.getFilters().get(key);
return value == null ? null : String.valueOf(value);
}
private String firstText(String... values) {
for (String value : values) {
if (!isBlank(value)) {
return value.trim();
}
}
return null;
}
private boolean containsIgnoreCase(String value, String keyword) {
return value != null && keyword != null && value.toLowerCase(Locale.ROOT).contains(keyword.toLowerCase(Locale.ROOT));
}
private boolean containsStoreId(Object value) {
if (value instanceof Map<?, ?> map) {
for (Map.Entry<?, ?> entry : map.entrySet()) {
if ("storeId".equals(String.valueOf(entry.getKey())) || containsStoreId(entry.getValue())) {
return true;
}
}
}
if (value instanceof Collection<?> collection) {
for (Object item : collection) {
if (containsStoreId(item)) {
return true;
}
}
}
return false;
}
private boolean isLowStock(Object value) {
if (value == null) {
return false;
}
Map<String, Object> map = rawMap(value);
Object lowStock = map.get("lowStock");
return lowStock instanceof Number number && 0 < number.intValue();
}
private List<Object> sanitizeList(Collection<?> values) {
List<Object> result = new ArrayList<>();
if (values == null) {
return result;
}
for (Object value : values) {
Object sanitized = sanitize(value);
if (sanitized != null) {
result.add(sanitized);
}
}
return result;
}
private Map<String, Object> sanitizeMap(Map<?, ?> source) {
Map<String, Object> result = new LinkedHashMap<>();
if (source == null) {
return result;
}
for (Map.Entry<?, ?> entry : source.entrySet()) {
String key = String.valueOf(entry.getKey());
if (isSensitiveKey(key)) {
continue;
}
Object value = sanitize(entry.getValue());
if (value != null) {
result.put(key, value);
}
}
return result;
}
private Object sanitize(Object value) {
if (value == null || value instanceof String || value instanceof Number || value instanceof Boolean || value instanceof Enum<?>) {
return value instanceof Enum<?> enumValue ? enumValue.name() : value;
}
if (value instanceof Map<?, ?> map) {
return sanitizeMap(map);
}
if (value instanceof Collection<?> collection) {
return sanitizeList(collection);
}
try {
return sanitizeMap(jackson.convertValue(value, new TypeReference<Map<String, Object>>() {}));
} catch (IllegalArgumentException e) {
return null;
}
}
private Map<String, Object> rawMap(Object value) {
if (value instanceof Map<?, ?> map) {
Map<String, Object> result = new LinkedHashMap<>();
map.forEach((key, item) -> result.put(String.valueOf(key), item));
return result;
}
return jackson.convertValue(value, new TypeReference<Map<String, Object>>() {});
}
private boolean isSensitiveKey(String key) {
return SENSITIVE_KEYS.contains(key) || key.endsWith("Id") || key.toLowerCase(Locale.ROOT).contains("password")
|| key.toLowerCase(Locale.ROOT).contains("token") || key.toLowerCase(Locale.ROOT).contains("url");
}
private boolean isBlank(String value) {
return value == null || value.trim().isEmpty();
}
private record TimeWindow(LocalDate start, LocalDate endDate, long begin, long end) {
private int beginDateValue() {
return Integer.parseInt(DAY_VALUE_FORMATTER.format(start));
}
private int endDateValue() {
return Integer.parseInt(DAY_VALUE_FORMATTER.format(endDate));
}
private String display() {
return "%s 至 %s".formatted(start, endDate);
}
}
}
@@ -0,0 +1,111 @@
package com.imyeyu.api.modules.gao.ai.service.implement;
import com.imyeyu.api.modules.gao.ai.config.GaoAiProperties;
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.service.GaoAiSessionService;
import com.imyeyu.spring.util.Redis;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;
import java.security.SecureRandom;
import java.util.Base64;
/// GAO 智能体会话服务实现
///
/// @author Codex
/// @since 2026-09-15
@Service
@RequiredArgsConstructor
public class GaoAiSessionServiceImplement implements GaoAiSessionService {
private static final String KEY_PREFIX = "GAO:AI:SESSION:";
private final GaoAiProperties properties;
@Qualifier("redisGaoAiSession")
private final Redis<String, GaoAiSession> redis;
private final SecureRandom secureRandom = new SecureRandom();
@Override
public GaoAiSession create(String userId, String storeId, String difyConversationId) {
if (isBlank(userId) || isBlank(storeId)) {
throw new IllegalArgumentException("AI 会话缺少用户或门店");
}
long ttlSeconds = Math.max(1L, properties.getSessionTtlSeconds());
GaoAiSession session = new GaoAiSession();
session.setSessionId(newSessionId());
session.setUserId(userId);
session.setStoreId(storeId);
session.setDifyConversationId(blankToNull(difyConversationId));
session.setAllowedTools(GaoAiToolNames.orderedReadOnlyTools());
session.setExpiresAt(System.currentTimeMillis() + ttlSeconds * 1000L);
session.setUsedCount(0L);
redis.set(key(session.getSessionId()), session, ttlSeconds * 1000L);
return session;
}
@Override
public GaoAiSession require(String sessionId) {
if (isBlank(sessionId)) {
throw new GaoAiSessionException("缺少 AI 会话", 401);
}
GaoAiSession session = redis.get(key(sessionId.trim()));
if (session == null || session.getExpiresAt() <= System.currentTimeMillis()) {
redis.destroy(key(sessionId.trim()));
throw new GaoAiSessionException("AI 会话不存在或已过期", 401);
}
return session;
}
@Override
public GaoAiSession increaseUsedCount(String sessionId) {
GaoAiSession session = require(sessionId);
session.setUsedCount(session.getUsedCount() + 1L);
long remain = Math.max(1L, session.getExpiresAt() - System.currentTimeMillis());
redis.set(key(session.getSessionId()), session, remain);
return session;
}
@Override
public void delete(String sessionId) {
if (!isBlank(sessionId)) {
redis.destroy(key(sessionId.trim()));
}
}
private String newSessionId() {
byte[] bytes = new byte[32];
secureRandom.nextBytes(bytes);
return Base64.getUrlEncoder().withoutPadding().encodeToString(bytes);
}
private String key(String sessionId) {
return KEY_PREFIX + sessionId;
}
private boolean isBlank(String value) {
return value == null || value.trim().isEmpty();
}
private String blankToNull(String value) {
return isBlank(value) ? null : value.trim();
}
/// AI 会话认证异常
public static class GaoAiSessionException extends RuntimeException {
private final int status;
public GaoAiSessionException(String message, int status) {
super(message);
this.status = status;
}
public int getStatus() {
return status;
}
}
}
@@ -0,0 +1,20 @@
package com.imyeyu.api.modules.gao.ai.vo;
import lombok.Data;
/// GAO 智能体聊天请求
///
/// @author Codex
/// @since 2026-09-15
@Data
public class GaoAiChatRequest {
/// 店长问题
private String message;
/// Dify 会话 ID,可为空
private String conversationId;
/// GLOBAL_MANAGER 兼任店长时使用当前选中门店 ID,可为空
private String storeId;
}
@@ -0,0 +1,22 @@
package com.imyeyu.api.modules.gao.ai.vo;
import lombok.Data;
/// GAO 智能体历史会话列表请求
///
/// 字段与 Dify 会话列表分页参数对应,但用户标识由后端注入
///
/// @author Codex
/// @since 2026-09-16
@Data
public class GaoAiConversationListRequest {
/// 上一页最后一条会话 ID,可为空
private String lastId;
/// 返回条数,可为空
private Integer limit;
/// 排序方式,可选 `created_at`、`-created_at`、`updated_at`、`-updated_at`
private String sortBy;
}
@@ -0,0 +1,22 @@
package com.imyeyu.api.modules.gao.ai.vo;
import lombok.Data;
/// GAO 智能体历史会话消息读取请求
///
/// 用户标识由后端注入,前端只能指定会话和分页游标
///
/// @author Codex
/// @since 2026-09-16
@Data
public class GaoAiConversationReadRequest {
/// Dify 会话 ID
private String conversationId;
/// 上一页第一条消息 ID,可为空
private String firstId;
/// 返回条数,可为空
private Integer limit;
}
@@ -0,0 +1,43 @@
package com.imyeyu.api.modules.gao.ai.vo;
import lombok.Data;
import java.util.LinkedHashMap;
import java.util.Map;
/// GAO 智能体 MCP 工具通用请求
///
/// @author Codex
/// @since 2026-09-15
@Data
public class GaoAiToolRequest {
/// 自然语言关键词
private String query;
/// 时间范围
private TimeRange timeRange;
/// 业务过滤条件,不允许携带 storeId
private Map<String, Object> filters = new LinkedHashMap<>();
/// 请求条数,服务端强制限制为 1 至 20
private Integer pageSize;
/// 分页游标,当前实现为不透明页码字符串
private String cursor;
/// 工具时间范围
@Data
public static class TimeRange {
/// 预设范围,例如 TODAY、THIS_MONTH、CUSTOM
private String preset;
/// 自定义开始日期,格式为 yyyy-MM-dd
private String startDate;
/// 自定义结束日期,格式为 yyyy-MM-dd,包含当天
private String endDate;
}
}
@@ -0,0 +1,33 @@
package com.imyeyu.api.modules.gao.ai.vo;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
/// GAO 智能体 MCP 工具统一返回
///
/// @author Codex
/// @since 2026-09-15
@Data
@NoArgsConstructor
public class GaoAiToolResult {
/// 数据范围
private Map<String, Object> scope = new LinkedHashMap<>();
/// 聚合摘要
private Map<String, Object> summary = new LinkedHashMap<>();
/// 明细,最多返回 20 条
private List<Object> details = new ArrayList<>();
/// 风险和数据提示
private List<Object> alerts = new ArrayList<>();
/// 来源和生成时间
private Map<String, Object> source = new LinkedHashMap<>();
}
@@ -15,8 +15,6 @@ public enum GaoPermissionCode implements BuiltinPermissionCode {
STORE_READ("STORE:READ", "门店读取", true, true), STORE_READ("STORE:READ", "门店读取", true, true),
STORE_EXPORT("STORE:EXPORT", "门店导出", false, true),
STORE_UPDATE("STORE:UPDATE", "门店修改", true, true), STORE_UPDATE("STORE:UPDATE", "门店修改", true, true),
STORE_DELETE("STORE:DELETE", "门店删除", false, true), STORE_DELETE("STORE:DELETE", "门店删除", false, true),
@@ -33,12 +31,20 @@ public enum GaoPermissionCode implements BuiltinPermissionCode {
CUSTOMER_READ("CUSTOMER:READ", "客户读取", false, false), CUSTOMER_READ("CUSTOMER:READ", "客户读取", false, false),
CUSTOMER_EXPORT("CUSTOMER:EXPORT", "客户导出", true, false),
CUSTOMER_UPDATE("CUSTOMER:UPDATE", "客户修改", false, false), CUSTOMER_UPDATE("CUSTOMER:UPDATE", "客户修改", false, false),
CUSTOMER_DELETE("CUSTOMER:DELETE", "客户删除", false, false), CUSTOMER_DELETE("CUSTOMER:DELETE", "客户删除", false, false),
CUSTOMER_FOLLOW_UP_REMINDER_CREATE("CUSTOMER_FOLLOW_UP_REMINDER:CREATE", "客户跟进提醒创建", false, false),
CUSTOMER_FOLLOW_UP_REMINDER_READ("CUSTOMER_FOLLOW_UP_REMINDER:READ", "客户跟进提醒读取", false, false),
CUSTOMER_FOLLOW_UP_REMINDER_UPDATE("CUSTOMER_FOLLOW_UP_REMINDER:UPDATE", "客户跟进提醒修改", false, false),
CUSTOMER_FOLLOW_UP_REMINDER_DELETE("CUSTOMER_FOLLOW_UP_REMINDER:DELETE", "客户跟进提醒删除", false, false),
CUSTOMER_FOLLOW_UP_REMINDER_COMPLETE("CUSTOMER_FOLLOW_UP_REMINDER:COMPLETE", "客户跟进提醒完成", false, false),
EVENT_CREATE("EVENT:CREATE", "登记事件创建", false, false), EVENT_CREATE("EVENT:CREATE", "登记事件创建", false, false),
EVENT_READ("EVENT:READ", "登记事件读取", false, false), EVENT_READ("EVENT:READ", "登记事件读取", false, false),
@@ -53,8 +59,6 @@ public enum GaoPermissionCode implements BuiltinPermissionCode {
EVENT_RECORD_VERIFY("EVENT_RECORD:VERIFY", "登记事件核销", true, false), EVENT_RECORD_VERIFY("EVENT_RECORD:VERIFY", "登记事件核销", true, false),
EVENT_RECORD_EXPORT("EVENT_RECORD:EXPORT", "登记事件记录导出", true, false),
EVENT_RECORD_UPDATE("EVENT_RECORD:UPDATE", "登记事件记录修改", false, false), EVENT_RECORD_UPDATE("EVENT_RECORD:UPDATE", "登记事件记录修改", false, false),
EVENT_RECORD_DELETE("EVENT_RECORD:DELETE", "登记事件记录删除", false, false), EVENT_RECORD_DELETE("EVENT_RECORD:DELETE", "登记事件记录删除", false, false),
@@ -85,16 +89,20 @@ public enum GaoPermissionCode implements BuiltinPermissionCode {
SALES_ORDER_CANCEL("SALES_ORDER:CANCEL", "销售订单取消", true, true), SALES_ORDER_CANCEL("SALES_ORDER:CANCEL", "销售订单取消", true, true),
SALES_ORDER_PRICE_OVERRIDE("SALES_ORDER:PRICE_OVERRIDE", "销售订单价格修改", true, true), SALES_ORDER_PRICE_OVERRIDE("SALES_ORDER:PRICE_OVERRIDE", "订单交易条件调整", true, true),
ORDER_FULFILLMENT_CREATE("ORDER_FULFILLMENT:CREATE", "统一履约创建", true, true), ORDER_FULFILLMENT_CREATE("ORDER_FULFILLMENT:CREATE", "统一履约创建", true, true),
ORDER_FULFILLMENT_UNSETTLED("ORDER_FULFILLMENT:UNSETTLED", "订单未结清履约", true, true),
ORDER_FULFILLMENT_READ("ORDER_FULFILLMENT:READ", "统一履约读取", true, true), ORDER_FULFILLMENT_READ("ORDER_FULFILLMENT:READ", "统一履约读取", true, true),
ORDER_FULFILLMENT_VERIFY("ORDER_FULFILLMENT:VERIFY", "统一履约核销", true, true), ORDER_FULFILLMENT_VERIFY("ORDER_FULFILLMENT:VERIFY", "统一履约核销", true, true),
ORDER_FULFILLMENT_REVOKE("ORDER_FULFILLMENT:REVOKE", "统一履约冲正", true, true), ORDER_FULFILLMENT_REVOKE("ORDER_FULFILLMENT:REVOKE", "统一履约冲正", true, true),
ORDER_FULFILLMENT_RETURN("ORDER_FULFILLMENT:RETURN", "统一履约退货", true, true),
PACKAGE_CONFIG_CREATE("PACKAGE_CONFIG:CREATE", "套餐配置创建", true, true), PACKAGE_CONFIG_CREATE("PACKAGE_CONFIG:CREATE", "套餐配置创建", true, true),
PACKAGE_CONFIG_READ("PACKAGE_CONFIG:READ", "套餐配置读取", true, true), PACKAGE_CONFIG_READ("PACKAGE_CONFIG:READ", "套餐配置读取", true, true),
@@ -113,15 +121,15 @@ public enum GaoPermissionCode implements BuiltinPermissionCode {
CUSTOMER_PACKAGE_GIFT_CREATE("CUSTOMER_PACKAGE:GIFT_CREATE", "客户套餐创建赠送", true, true), CUSTOMER_PACKAGE_GIFT_CREATE("CUSTOMER_PACKAGE:GIFT_CREATE", "客户套餐创建赠送", true, true),
FUND_RECORD_READ("FUND_RECORD:READ", "资金流水读取", true, true), FUND_RECORD_READ("FUND_RECORD:READ", "支付记录读取", true, true),
FUND_RECEIVE_CREATE("FUND_RECEIVE:CREATE", "线下收款创建", true, true), FUND_RECEIVE_CREATE("FUND_RECEIVE:CREATE", "支付登记", true, true),
FUND_RECEIVE_VERIFY("FUND_RECEIVE:VERIFY", "线下收款核销", true, true), FUND_RECEIVE_VERIFY("FUND_RECEIVE:VERIFY", "支付核销", true, true),
FUND_REFUND("FUND:REFUND", "套餐退款", true, true), FUND_REFUND("FUND:REFUND", "套餐退款", true, true),
FUND_REVOKE("FUND:REVOKE", "资金流水冲正", true, true), FUND_REVOKE("FUND:REVOKE", "支付冲正", true, true),
POINT_ACCOUNT_READ("POINT_ACCOUNT:READ", "客户积分账户读取", true, true), POINT_ACCOUNT_READ("POINT_ACCOUNT:READ", "客户积分账户读取", true, true),
@@ -139,8 +147,24 @@ public enum GaoPermissionCode implements BuiltinPermissionCode {
POINT_SOURCE_VALUE("POINT:SOURCE_VALUE", "登记提交自定义积分值", true, true), POINT_SOURCE_VALUE("POINT:SOURCE_VALUE", "登记提交自定义积分值", true, true),
POINT_REDEMPTION_CREATE("POINT_REDEMPTION:CREATE", "积分兑换创建和读取", true, true),
POINT_REDEMPTION_POINT_ADJUST("POINT_REDEMPTION:POINT_ADJUST", "积分兑换减免积分", true, true),
POINT_REDEMPTION_RETURN("POINT_REDEMPTION:RETURN", "积分兑换退货", true, true),
POINT_REDEEM_SKU_MANAGE("POINT_REDEEM_SKU:MANAGE", "积分兑换 SKU 配置管理", true, true),
RECYCLE_EXCHANGE_CONFIG_MANAGE("RECYCLE_EXCHANGE:CONFIG_MANAGE", "回收兑换配置管理", true, true),
RECYCLE_ACCOUNT_READ("RECYCLE_ACCOUNT:READ", "回收物额度查询", true, true),
RECYCLE_ACCOUNT_ADJUST("RECYCLE_ACCOUNT:ADJUST", "回收物额度调整", true, true),
STAT_READ("STAT:READ", "统计读取", false, false), STAT_READ("STAT:READ", "统计读取", false, false),
DATA_EXPORT("DATA_EXPORT", "数据导出", true, false),
QR_CODE_CREATE("QR_CODE:CREATE", "二维码创建", false, false), QR_CODE_CREATE("QR_CODE:CREATE", "二维码创建", false, false),
USER_CREATE("USER:CREATE", "用户创建", true, false), USER_CREATE("USER:CREATE", "用户创建", true, false),
@@ -0,0 +1,40 @@
package com.imyeyu.api.modules.gao.bean;
import com.imyeyu.api.annotation.SettingBizType;
import com.imyeyu.api.bean.SettingEnum;
import com.imyeyu.api.modules.common.entity.Setting;
import lombok.AllArgsConstructor;
import lombok.Getter;
/// GAO 门店配置
///
/// 门店级配置,bizId 为门店 ID
/// 启动时的内建配置初始化只覆盖系统级配置,门店配置查不到记录时按默认值兜底
///
/// @author Codex
/// @since 2026-11-15
@Getter
@SettingBizType("GAO_STORE")
@AllArgsConstructor
public enum GaoStoreSetting implements SettingEnum {
/// 客户生日提醒开关
CUSTOMER_BIRTHDAY_REMINDER_ENABLED(Boolean.FALSE.toString(), Setting.ValueType.BOOLEAN, "true 为启用客户生日提醒"),
/// 客户生日提醒负责人
CUSTOMER_BIRTHDAY_REMINDER_RESPONSIBLE_USER_ID(null, Setting.ValueType.STRING, "客户生日提醒的负责人用户 ID");
final String defaultValue;
final Setting.ValueType valueType;
final String description;
/// 门店配置属于业务级配置,bizId 为门店 ID,启动时不初始化记录
///
/// @return 业务级作用域
@Override
public Setting.Scope getScope() {
return Setting.Scope.BUSINESS;
}
}
@@ -15,11 +15,13 @@ import lombok.Getter;
@AllArgsConstructor @AllArgsConstructor
public enum GaoSystemSetting implements SettingEnum { public enum GaoSystemSetting implements SettingEnum {
SERVICE_LICENSE(null, Setting.ValueType.STRING), DIFY_APP_API_KEY(null, Setting.ValueType.STRING),
PRIVACY_LICENSE(null, Setting.ValueType.STRING), DIFY_MCP_SERVICE_KEY(null, Setting.ValueType.STRING),
OPEN_SOURCE_LICENSE(null, Setting.ValueType.STRING); AI_AGENT_EXAMPLE(null, Setting.ValueType.JSON_LIST),
AGREEMENT(null, Setting.ValueType.JSON_OBJECT);
final String defaultValue; final String defaultValue;
@@ -15,16 +15,10 @@ import com.imyeyu.api.modules.gao.vo.GaoCustomerTrendStateReq;
import com.imyeyu.api.modules.user.service.UserService; import com.imyeyu.api.modules.user.service.UserService;
import com.imyeyu.java.TimiJava; import com.imyeyu.java.TimiJava;
import com.imyeyu.java.bean.timi.TimiException; import com.imyeyu.java.bean.timi.TimiException;
import com.imyeyu.network.Network;
import com.imyeyu.spring.TimiSpring;
import com.imyeyu.spring.annotation.AOPLog; import com.imyeyu.spring.annotation.AOPLog;
import com.imyeyu.spring.annotation.IgnoreGlobalReturn;
import com.imyeyu.spring.annotation.RequestRateLimit; import com.imyeyu.spring.annotation.RequestRateLimit;
import com.imyeyu.spring.bean.Page;
import com.imyeyu.spring.bean.PageResult; import com.imyeyu.spring.bean.PageResult;
import com.imyeyu.spring.util.ResponseView; import com.imyeyu.spring.util.ResponseView;
import com.imyeyu.utils.Time;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor; import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestBody;
@@ -32,7 +26,6 @@ import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController; import org.springframework.web.bind.annotation.RestController;
import java.io.IOException;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
@@ -166,25 +159,6 @@ public class GaoCustomerController {
return customer; return customer;
} }
@AOPLog
@RequestRateLimit
@IgnoreGlobalReturn
@RequireGaoPermission(GaoPermissionCode.CUSTOMER_EXPORT)
@PostMapping("/export")
public void export(@RequestBody Page<GaoCustomer> page) throws IOException {
TimiException.required(page, "not found page");
if (!storeScopeService.hasGlobalScope()) {
GaoCustomer example = TimiJava.defaultIfNull(page.getEqualsExample(), new GaoCustomer());
example.setStoreId(storeScopeService.resolveStoreId(example.getStoreId()));
page.setEqualsExample(example);
}
HttpServletResponse resp = TimiSpring.getResponse();
String contentDisposition = Network.getFileDownloadHeader("客户列表-%s.xlsx".formatted(Time.serialize.format(Time.now())));
resp.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
resp.setHeader("Content-Disposition", contentDisposition);
resp.getOutputStream().write(service.export(page));
}
@AOPLog @AOPLog
@RequestRateLimit @RequestRateLimit
@RequireGaoPermission(GaoPermissionCode.CUSTOMER_READ) @RequireGaoPermission(GaoPermissionCode.CUSTOMER_READ)
@@ -0,0 +1,182 @@
package com.imyeyu.api.modules.gao.controller;
import com.fasterxml.jackson.annotation.JsonView;
import com.imyeyu.api.modules.common.entity.Attachment;
import com.imyeyu.api.modules.common.service.AttachmentService;
import com.imyeyu.api.modules.gao.annotation.RequireGaoPermission;
import com.imyeyu.api.modules.gao.bean.GaoPermissionCode;
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.service.GaoStoreScopeService;
import com.imyeyu.api.modules.gao.vo.GaoCustomerFollowUpReminderPage;
import com.imyeyu.api.modules.gao.vo.GaoCustomerFollowUpReminderPageResult;
import com.imyeyu.api.modules.user.entity.User;
import com.imyeyu.api.modules.user.service.UserService;
import com.imyeyu.java.bean.timi.TimiException;
import com.imyeyu.spring.annotation.AOPLog;
import com.imyeyu.spring.annotation.RequestRateLimit;
import com.imyeyu.spring.util.ResponseView;
import lombok.RequiredArgsConstructor;
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;
import java.util.Map;
/// GAO 客户跟进提醒接口
///
/// @author Codex
/// @since 2026-09-17
@RestController
@RequiredArgsConstructor
@RequestMapping("/gao/customer/follow-up-reminder")
public class GaoCustomerFollowUpReminderController {
private final GaoCustomerFollowUpReminderService service;
private final GaoCustomerService customerService;
private final GaoStoreScopeService storeScopeService;
private final UserService userService;
private final AttachmentService attachmentService;
/// 分页查询客户跟进提醒
///
/// @param page 查询条件
/// @return 分页结果
@AOPLog
@RequestRateLimit
@RequireGaoPermission(GaoPermissionCode.CUSTOMER_FOLLOW_UP_REMINDER_READ)
@PostMapping("/list")
@JsonView(ResponseView.Public.class)
public GaoCustomerFollowUpReminderPageResult list(@RequestBody GaoCustomerFollowUpReminderPage page) {
TimiException.required(page, "未找到分页参数");
page.setStoreId(storeScopeService.resolveStoreId(page.getStoreId()));
GaoCustomerFollowUpReminderPageResult result = service.pageByQuery(page);
fillList(result.getList());
return result;
}
/// 查询客户跟进提醒详情
///
/// @param id 跟进提醒 ID
/// @return 跟进提醒
@AOPLog
@RequestRateLimit
@RequireGaoPermission(GaoPermissionCode.CUSTOMER_FOLLOW_UP_REMINDER_READ)
@PostMapping("/detail")
@JsonView(ResponseView.Public.class)
public GaoCustomerFollowUpReminder detail(@RequestParam String id) {
GaoCustomerFollowUpReminder reminder = service.get(id);
TimiException.required(reminder, "未找到客户跟进提醒");
storeScopeService.checkStoreId(reminder.getStoreId());
fillDetail(reminder);
return reminder;
}
/// 创建客户跟进提醒
///
/// @param reminder 跟进提醒
/// @return 跟进提醒 ID
@AOPLog
@RequestRateLimit
@RequireGaoPermission(GaoPermissionCode.CUSTOMER_FOLLOW_UP_REMINDER_CREATE)
@PostMapping("/create")
public String create(@RequestBody GaoCustomerFollowUpReminder reminder) {
service.create(reminder);
return reminder.getId();
}
/// 修改客户跟进提醒
///
/// @param reminder 跟进提醒
@AOPLog
@RequestRateLimit
@RequireGaoPermission(GaoPermissionCode.CUSTOMER_FOLLOW_UP_REMINDER_UPDATE)
@PostMapping("/update")
public void update(@RequestBody GaoCustomerFollowUpReminder reminder) {
TimiException.required(reminder, "未找到客户跟进提醒");
TimiException.required(reminder.getId(), "未找到客户跟进提醒 ID");
GaoCustomerFollowUpReminder dbReminder = service.get(reminder.getId());
TimiException.required(dbReminder, "未找到客户跟进提醒");
storeScopeService.checkStoreId(dbReminder.getStoreId());
service.update(reminder);
}
/// 完成客户跟进提醒
///
/// @param id 跟进提醒 ID
@AOPLog
@RequestRateLimit
@RequireGaoPermission(GaoPermissionCode.CUSTOMER_FOLLOW_UP_REMINDER_COMPLETE)
@PostMapping("/complete")
public void complete(@RequestParam String id) {
GaoCustomerFollowUpReminder reminder = service.get(id);
TimiException.required(reminder, "未找到客户跟进提醒");
storeScopeService.checkStoreId(reminder.getStoreId());
service.complete(id);
}
/// 删除客户跟进提醒
///
/// @param id 跟进提醒 ID
@AOPLog
@RequestRateLimit
@RequireGaoPermission(GaoPermissionCode.CUSTOMER_FOLLOW_UP_REMINDER_DELETE)
@PostMapping("/delete")
public void delete(@RequestParam String id) {
GaoCustomerFollowUpReminder reminder = service.get(id);
TimiException.required(reminder, "未找到客户跟进提醒");
storeScopeService.checkStoreId(reminder.getStoreId());
service.delete(id);
}
/// 回填列表中的客户、负责人和附件
///
/// @param reminderList 提醒列表
private void fillList(List<GaoCustomerFollowUpReminder> reminderList) {
if (reminderList == null || reminderList.isEmpty()) {
return;
}
List<String> customerIdList = reminderList.stream()
.map(GaoCustomerFollowUpReminder::getCustomerId)
.distinct()
.toList();
Map<String, GaoCustomer> customerMap = customerService.mapByIdList(customerIdList);
Map<String, List<Attachment>> customerAttachmentMap = attachmentService.mapByBizIdList(
Attachment.BizType.GAO_CUSTOMER,
customerIdList);
Map<String, User> userMap = userService.mapByIdList(
reminderList.stream().map(GaoCustomerFollowUpReminder::getResponsibleUserId).distinct().toList());
Map<String, List<Attachment>> attachmentMap = attachmentService.mapByBizIdList(
Attachment.BizType.GAO_CUSTOMER_FOLLOW_UP_REMINDER,
reminderList.stream().map(GaoCustomerFollowUpReminder::getId).toList());
for (GaoCustomerFollowUpReminder reminder : reminderList) {
GaoCustomer customer = customerMap.get(reminder.getCustomerId());
if (customer != null) {
customer.setAttachmentList(customerAttachmentMap.getOrDefault(customer.getId(), List.of()));
}
reminder.setCustomer(customer);
reminder.setResponsibleUser(userMap.get(reminder.getResponsibleUserId()));
reminder.setAttachmentList(attachmentMap.getOrDefault(reminder.getId(), List.of()));
reminder.resolveNotifyChannelList();
}
}
/// 回填详情中的客户、负责人和附件
///
/// @param reminder 跟进提醒
private void fillDetail(GaoCustomerFollowUpReminder reminder) {
GaoCustomer customer = customerService.get(reminder.getCustomerId());
customer.setAttachmentList(attachmentService.listByBizId(Attachment.BizType.GAO_CUSTOMER, customer.getId(), GaoCustomer.AttachType.PHOTO.name()));
User responsibleUser = userService.get(reminder.getResponsibleUserId());
reminder.setCustomer(customer);
reminder.setResponsibleUser(responsibleUser);
reminder.setAttachmentList(attachmentService.listByBizId(
Attachment.BizType.GAO_CUSTOMER_FOLLOW_UP_REMINDER, reminder.getId()));
reminder.resolveNotifyChannelList();
}
}
@@ -0,0 +1,66 @@
package com.imyeyu.api.modules.gao.controller;
import com.imyeyu.api.modules.gao.annotation.RequireGaoPermission;
import com.imyeyu.api.modules.gao.bean.GaoPermissionCode;
import com.imyeyu.api.modules.gao.export.GaoDataExportCreateRequest;
import com.imyeyu.api.modules.gao.export.GaoDataExportStatRequest;
import com.imyeyu.api.modules.gao.export.GaoDataExportStatView;
import com.imyeyu.api.modules.gao.export.GaoDataExportTaskView;
import com.imyeyu.api.modules.gao.service.GaoDataExportService;
import com.imyeyu.spring.annotation.AOPLog;
import com.imyeyu.spring.annotation.RequestRateLimit;
import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
/// GAO 店长数据导出接口
///
/// @author Codex
/// @since 2026-10-23
@RestController
@RequiredArgsConstructor
@RequestMapping("/gao/data-export")
public class GaoDataExportController {
private final GaoDataExportService service;
/// 统计待导出的数据量
///
/// @param request 导出条件
/// @return 导出统计
@AOPLog
@RequestRateLimit
@RequireGaoPermission(GaoPermissionCode.DATA_EXPORT)
@PostMapping("/stat")
public GaoDataExportStatView stat(@RequestBody GaoDataExportStatRequest request) {
return service.stat(request);
}
/// 创建异步导出任务
///
/// @param request 导出条件
/// @return 已创建的导出任务
@AOPLog
@RequestRateLimit
@RequireGaoPermission(GaoPermissionCode.DATA_EXPORT)
@PostMapping("/task")
public GaoDataExportTaskView create(@RequestBody GaoDataExportCreateRequest request) {
return service.create(request);
}
/// 查询异步导出任务
///
/// @param taskId 任务 ID
/// @return 导出任务
@AOPLog
@RequestRateLimit
@RequireGaoPermission(GaoPermissionCode.DATA_EXPORT)
@GetMapping("/task/{taskId}")
public GaoDataExportTaskView detail(@PathVariable String taskId) {
return service.detail(taskId);
}
}
@@ -20,15 +20,10 @@ import com.imyeyu.api.modules.gao.vo.GaoEventRecordRankPage;
import com.imyeyu.api.modules.user.service.UserService; import com.imyeyu.api.modules.user.service.UserService;
import com.imyeyu.java.TimiJava; import com.imyeyu.java.TimiJava;
import com.imyeyu.java.bean.timi.TimiException; import com.imyeyu.java.bean.timi.TimiException;
import com.imyeyu.network.Network;
import com.imyeyu.spring.TimiSpring;
import com.imyeyu.spring.annotation.AOPLog; import com.imyeyu.spring.annotation.AOPLog;
import com.imyeyu.spring.annotation.IgnoreGlobalReturn;
import com.imyeyu.spring.annotation.RequestRateLimit; import com.imyeyu.spring.annotation.RequestRateLimit;
import com.imyeyu.spring.bean.PageResult; import com.imyeyu.spring.bean.PageResult;
import com.imyeyu.spring.util.ResponseView; import com.imyeyu.spring.util.ResponseView;
import com.imyeyu.utils.Time;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor; import lombok.RequiredArgsConstructor;
import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestBody;
@@ -36,7 +31,6 @@ import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController; import org.springframework.web.bind.annotation.RestController;
import java.io.IOException;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
@@ -69,6 +63,7 @@ public class GaoEventRecordController {
result.setTotal(pageResult.getTotal()); result.setTotal(pageResult.getTotal());
result.setList(pageResult.getList()); result.setList(pageResult.getList());
result.setNumberValueTotal(resolveNumberValueTotal(page)); result.setNumberValueTotal(resolveNumberValueTotal(page));
result.setCustomerCount(service.countCustomerByRange(page));
{ {
List<String> customerIdList = result.getList().stream().map(GaoEventRecord::getCustomerId).toList(); List<String> customerIdList = result.getList().stream().map(GaoEventRecord::getCustomerId).toList();
Map<String, GaoEvent> eventMap = eventService.mapByIdList(result.getList().stream().map(GaoEventRecord::getEventId).toList()); Map<String, GaoEvent> eventMap = eventService.mapByIdList(result.getList().stream().map(GaoEventRecord::getEventId).toList());
@@ -199,21 +194,6 @@ public class GaoEventRecordController {
service.delete(id); service.delete(id);
} }
@AOPLog
@RequestRateLimit
@IgnoreGlobalReturn
@RequireGaoPermission(GaoPermissionCode.EVENT_RECORD_EXPORT)
@PostMapping("/export")
public void export(@RequestBody GaoEventRecordPage page) throws IOException {
TimiException.required(page, "not found page");
page.setStoreId(storeScopeService.resolveStoreId(page.getStoreId()));
HttpServletResponse resp = TimiSpring.getResponse();
String contentDisposition = Network.getFileDownloadHeader("登记事件记录-%s.xlsx".formatted(Time.serialize.format(Time.now())));
resp.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
resp.setHeader("Content-Disposition", contentDisposition);
resp.getOutputStream().write(service.export(page));
}
/// 按时间范围查询客户登记排行榜 /// 按时间范围查询客户登记排行榜
@AOPLog @AOPLog
@RequestRateLimit @RequestRateLimit
@@ -4,7 +4,9 @@ import com.imyeyu.api.modules.common.entity.Attachment;
import com.imyeyu.api.modules.common.service.AttachmentService; import com.imyeyu.api.modules.common.service.AttachmentService;
import com.imyeyu.api.modules.gao.annotation.RequireGaoPermission; import com.imyeyu.api.modules.gao.annotation.RequireGaoPermission;
import com.imyeyu.api.modules.gao.bean.GaoPermissionCode; 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.GaoFundRecord;
import com.imyeyu.api.modules.gao.service.GaoCustomerService;
import com.imyeyu.api.modules.gao.service.GaoFundRecordService; import com.imyeyu.api.modules.gao.service.GaoFundRecordService;
import com.imyeyu.api.modules.gao.service.GaoOrderPaymentService; import com.imyeyu.api.modules.gao.service.GaoOrderPaymentService;
import com.imyeyu.api.modules.gao.service.GaoStoreScopeService; import com.imyeyu.api.modules.gao.service.GaoStoreScopeService;
@@ -39,6 +41,7 @@ import java.util.stream.Stream;
public class GaoFundRecordController { public class GaoFundRecordController {
private final GaoFundRecordService service; private final GaoFundRecordService service;
private final GaoCustomerService customerService;
private final GaoOrderPaymentService orderPaymentService; private final GaoOrderPaymentService orderPaymentService;
private final GaoStoreScopeService storeScopeService; private final GaoStoreScopeService storeScopeService;
private final AttachmentService attachmentService; private final AttachmentService attachmentService;
@@ -124,10 +127,23 @@ public class GaoFundRecordController {
.distinct() .distinct()
.toList(); .toList();
Map<String, User> userMap = userIdList.isEmpty() ? Map.of() : userService.mapByIdList(userIdList); Map<String, User> userMap = userIdList.isEmpty() ? Map.of() : userService.mapByIdList(userIdList);
List<String> customerIdList = recordList.stream()
.map(GaoFundRecord::getCustomerId)
.filter(value -> value != null && !value.isBlank())
.distinct()
.toList();
Map<String, GaoCustomer> customerMap = customerIdList.isEmpty() ? Map.of() : customerService.mapByIdList(customerIdList);
Map<String, List<Attachment>> customerPhotoMap = customerIdList.isEmpty()
? Map.of() : attachmentService.mapByBizIdList(Attachment.BizType.GAO_CUSTOMER, customerIdList, GaoCustomer.AttachType.PHOTO.name());
for (GaoFundRecord record : recordList) { for (GaoFundRecord record : recordList) {
record.setAttachmentList(attachmentMap.getOrDefault(record.getId(), List.of())); record.setAttachmentList(attachmentMap.getOrDefault(record.getId(), List.of()));
record.setOperator(userMap.get(record.getOperatorUserId())); record.setOperator(userMap.get(record.getOperatorUserId()));
record.setVerifier(userMap.get(record.getVerifierUserId())); record.setVerifier(userMap.get(record.getVerifierUserId()));
GaoCustomer customer = customerMap.get(record.getCustomerId());
if (customer != null) {
customer.setAttachmentList(customerPhotoMap.getOrDefault(customer.getId(), List.of()));
}
record.setCustomer(customer);
} }
} }
} }
@@ -2,18 +2,29 @@ package com.imyeyu.api.modules.gao.controller;
import com.imyeyu.api.modules.common.entity.Attachment; import com.imyeyu.api.modules.common.entity.Attachment;
import com.imyeyu.api.modules.common.service.AttachmentService; import com.imyeyu.api.modules.common.service.AttachmentService;
import com.imyeyu.api.bean.PermissionMatchMode;
import com.imyeyu.api.bean.ModuleCode;
import com.imyeyu.api.modules.user.service.PermissionChecker;
import com.imyeyu.api.modules.gao.annotation.RequireGaoPermission; import com.imyeyu.api.modules.gao.annotation.RequireGaoPermission;
import com.imyeyu.api.modules.gao.bean.GaoPermissionCode; import com.imyeyu.api.modules.gao.bean.GaoPermissionCode;
import com.imyeyu.api.modules.gao.entity.GaoCustomer; import com.imyeyu.api.modules.gao.entity.GaoCustomer;
import com.imyeyu.api.modules.gao.entity.GaoOrderFulfillment; import com.imyeyu.api.modules.gao.entity.GaoOrderFulfillment;
import com.imyeyu.api.modules.gao.service.GaoCustomerService; import com.imyeyu.api.modules.gao.service.GaoCustomerService;
import com.imyeyu.api.modules.gao.service.GaoOrderFulfillmentService; import com.imyeyu.api.modules.gao.service.GaoOrderFulfillmentService;
import com.imyeyu.api.modules.gao.service.GaoSalesOrderService;
import com.imyeyu.api.modules.gao.entity.GaoSalesOrder;
import com.imyeyu.api.modules.gao.service.GaoStoreScopeService; import com.imyeyu.api.modules.gao.service.GaoStoreScopeService;
import com.imyeyu.api.modules.gao.vo.GaoOrderFulfillmentActionRequest; import com.imyeyu.api.modules.gao.vo.GaoOrderFulfillmentActionRequest;
import com.imyeyu.api.modules.gao.vo.GaoOrderFulfillmentCreateRequest; import com.imyeyu.api.modules.gao.vo.GaoOrderFulfillmentCreateRequest;
import com.imyeyu.api.modules.gao.vo.GaoOrderFulfillmentPage; import com.imyeyu.api.modules.gao.vo.GaoOrderFulfillmentPage;
import com.imyeyu.api.modules.gao.vo.GaoOrderFulfillmentPrepareStockRequest; import com.imyeyu.api.modules.gao.vo.GaoOrderFulfillmentPrepareStockRequest;
import com.imyeyu.api.modules.gao.vo.GaoOrderFulfillmentRevokeRequest; import com.imyeyu.api.modules.gao.vo.GaoOrderFulfillmentRevokeRequest;
import com.imyeyu.api.modules.gao.vo.GaoOrderFulfillmentReturnRequest;
import com.imyeyu.api.modules.gao.vo.GaoQuickFulfillmentCreateRequest;
import com.imyeyu.api.modules.gao.vo.GaoQuickFulfillmentCustomerRequest;
import com.imyeyu.api.modules.gao.vo.GaoQuickFulfillmentSkuView;
import com.imyeyu.api.modules.gao.vo.GaoQuickFulfillmentSourceOrderListRequest;
import com.imyeyu.api.modules.gao.vo.GaoQuickFulfillmentSourceOrderView;
import com.imyeyu.api.modules.user.entity.User; import com.imyeyu.api.modules.user.entity.User;
import com.imyeyu.api.modules.user.service.UserService; import com.imyeyu.api.modules.user.service.UserService;
import com.imyeyu.java.bean.timi.TimiException; import com.imyeyu.java.bean.timi.TimiException;
@@ -41,6 +52,8 @@ import java.util.stream.Stream;
public class GaoOrderFulfillmentController { public class GaoOrderFulfillmentController {
private final GaoOrderFulfillmentService service; private final GaoOrderFulfillmentService service;
private final GaoSalesOrderService salesOrderService;
private final PermissionChecker permissionChecker;
private final GaoStoreScopeService storeScopeService; private final GaoStoreScopeService storeScopeService;
private final AttachmentService attachmentService; private final AttachmentService attachmentService;
private final GaoCustomerService customerService; private final GaoCustomerService customerService;
@@ -53,6 +66,8 @@ public class GaoOrderFulfillmentController {
public PageResult<GaoOrderFulfillment> list(@RequestBody GaoOrderFulfillmentPage page) { public PageResult<GaoOrderFulfillment> list(@RequestBody GaoOrderFulfillmentPage page) {
TimiException.required(page, "not found fulfillment page"); TimiException.required(page, "not found fulfillment page");
page.setStoreId(storeScopeService.resolveStoreId(page.getStoreId())); page.setStoreId(storeScopeService.resolveStoreId(page.getStoreId()));
page.setOrderAllowed(permissionChecker.hasAny(ModuleCode.GAO, GaoPermissionCode.ORDER_FULFILLMENT_READ.getValue()));
page.setRecycleAllowed(permissionChecker.hasAny(ModuleCode.GAO, GaoPermissionCode.ORDER_FULFILLMENT_READ.getValue()));
PageResult<GaoOrderFulfillment> result = service.pageByQuery(page); PageResult<GaoOrderFulfillment> result = service.pageByQuery(page);
fillTransient(result.getList()); fillTransient(result.getList());
return result; return result;
@@ -60,19 +75,20 @@ public class GaoOrderFulfillmentController {
@AOPLog @AOPLog
@RequestRateLimit @RequestRateLimit
@RequireGaoPermission(GaoPermissionCode.ORDER_FULFILLMENT_READ)
@PostMapping("/detail") @PostMapping("/detail")
public GaoOrderFulfillment detail(@RequestParam String id) { public GaoOrderFulfillment detail(@RequestParam String id) {
GaoOrderFulfillment result = service.detail(id); GaoOrderFulfillment result = service.detail(id);
checkSource(result, GaoPermissionCode.ORDER_FULFILLMENT_READ, GaoPermissionCode.ORDER_FULFILLMENT_READ);
fillTransient(List.of(result)); fillTransient(List.of(result));
return result; return result;
} }
@AOPLog @AOPLog
@RequestRateLimit @RequestRateLimit
@RequireGaoPermission(GaoPermissionCode.ORDER_FULFILLMENT_CREATE)
@PostMapping("/create") @PostMapping("/create")
public GaoOrderFulfillment create(@RequestBody GaoOrderFulfillmentCreateRequest request) { public GaoOrderFulfillment create(@RequestBody GaoOrderFulfillmentCreateRequest request) {
TimiException.required(request, "not found fulfillment request");
permissionChecker.checkAll(ModuleCode.GAO, GaoPermissionCode.ORDER_FULFILLMENT_CREATE.getValue());
GaoOrderFulfillment result = service.create(request); GaoOrderFulfillment result = service.create(request);
fillTransient(List.of(result)); fillTransient(List.of(result));
return result; return result;
@@ -80,9 +96,60 @@ public class GaoOrderFulfillmentController {
@AOPLog @AOPLog
@RequestRateLimit @RequestRateLimit
@RequireGaoPermission(GaoPermissionCode.ORDER_FULFILLMENT_VERIFY) @PostMapping("/create-and-verify")
public GaoOrderFulfillment createAndVerify(@RequestBody GaoOrderFulfillmentCreateRequest request) {
TimiException.required(request, "not found fulfillment request");
permissionChecker.checkAll(ModuleCode.GAO, GaoPermissionCode.ORDER_FULFILLMENT_CREATE.getValue());
permissionChecker.checkAll(ModuleCode.GAO, GaoPermissionCode.ORDER_FULFILLMENT_VERIFY.getValue());
GaoOrderFulfillment result = service.createAndVerify(request);
fillTransient(List.of(result));
return result;
}
/// 查询客户可履约 SKU
///
/// @param request 客户查询请求
/// @return 可履约 SKU 列表
@AOPLog
@RequestRateLimit
@RequireGaoPermission(GaoPermissionCode.ORDER_FULFILLMENT_CREATE)
@PostMapping("/quick/sku-list")
public List<GaoQuickFulfillmentSkuView> listQuickFulfillmentSku(@RequestBody GaoQuickFulfillmentCustomerRequest request) {
return service.listQuickFulfillmentSku(request);
}
/// 查询所选 SKU 的可履约来源订单
///
/// @param request 来源订单查询请求
/// @return 来源订单列表
@AOPLog
@RequestRateLimit
@RequireGaoPermission(GaoPermissionCode.ORDER_FULFILLMENT_CREATE)
@PostMapping("/quick/source-order-list")
public List<GaoQuickFulfillmentSourceOrderView> listQuickFulfillmentSourceOrder(@RequestBody GaoQuickFulfillmentSourceOrderListRequest request) {
return service.listQuickFulfillmentSourceOrder(request);
}
/// 批量创建快速履约单
///
/// @param request 快速履约创建请求
/// @return 已创建或已核销履约单列表
@AOPLog
@RequestRateLimit
@RequireGaoPermission(GaoPermissionCode.ORDER_FULFILLMENT_CREATE)
@PostMapping("/quick/create")
public List<GaoOrderFulfillment> createQuickFulfillment(@RequestBody GaoQuickFulfillmentCreateRequest request) {
List<GaoOrderFulfillment> result = service.createQuickFulfillment(request);
fillTransient(result);
return result;
}
@AOPLog
@RequestRateLimit
@PostMapping("/prepare-stock") @PostMapping("/prepare-stock")
public GaoOrderFulfillment prepareStock(@RequestBody GaoOrderFulfillmentPrepareStockRequest request) { public GaoOrderFulfillment prepareStock(@RequestBody GaoOrderFulfillmentPrepareStockRequest request) {
TimiException.required(request, "not found fulfillment request");
checkSource(service.detail(request.getFulfillmentId()), GaoPermissionCode.ORDER_FULFILLMENT_VERIFY, GaoPermissionCode.ORDER_FULFILLMENT_VERIFY);
GaoOrderFulfillment result = service.prepareStock(request); GaoOrderFulfillment result = service.prepareStock(request);
fillTransient(List.of(result)); fillTransient(List.of(result));
return result; return result;
@@ -90,9 +157,10 @@ public class GaoOrderFulfillmentController {
@AOPLog @AOPLog
@RequestRateLimit @RequestRateLimit
@RequireGaoPermission(GaoPermissionCode.ORDER_FULFILLMENT_VERIFY)
@PostMapping("/verify") @PostMapping("/verify")
public GaoOrderFulfillment verify(@RequestBody GaoOrderFulfillmentActionRequest request) { public GaoOrderFulfillment verify(@RequestBody GaoOrderFulfillmentActionRequest request) {
TimiException.required(request, "not found fulfillment request");
checkSource(service.detail(request.getFulfillmentId()), GaoPermissionCode.ORDER_FULFILLMENT_VERIFY, GaoPermissionCode.ORDER_FULFILLMENT_VERIFY);
GaoOrderFulfillment result = service.verify(request); GaoOrderFulfillment result = service.verify(request);
fillTransient(List.of(result)); fillTransient(List.of(result));
return result; return result;
@@ -100,9 +168,10 @@ public class GaoOrderFulfillmentController {
@AOPLog @AOPLog
@RequestRateLimit @RequestRateLimit
@RequireGaoPermission(GaoPermissionCode.ORDER_FULFILLMENT_VERIFY)
@PostMapping("/reject") @PostMapping("/reject")
public GaoOrderFulfillment reject(@RequestBody GaoOrderFulfillmentActionRequest request) { public GaoOrderFulfillment reject(@RequestBody GaoOrderFulfillmentActionRequest request) {
TimiException.required(request, "not found fulfillment request");
checkSource(service.detail(request.getFulfillmentId()), GaoPermissionCode.ORDER_FULFILLMENT_VERIFY, GaoPermissionCode.ORDER_FULFILLMENT_VERIFY);
GaoOrderFulfillment result = service.reject(request); GaoOrderFulfillment result = service.reject(request);
fillTransient(List.of(result)); fillTransient(List.of(result));
return result; return result;
@@ -110,9 +179,10 @@ public class GaoOrderFulfillmentController {
@AOPLog @AOPLog
@RequestRateLimit @RequestRateLimit
@RequireGaoPermission(GaoPermissionCode.ORDER_FULFILLMENT_CREATE)
@PostMapping("/cancel") @PostMapping("/cancel")
public GaoOrderFulfillment cancel(@RequestBody GaoOrderFulfillmentActionRequest request) { public GaoOrderFulfillment cancel(@RequestBody GaoOrderFulfillmentActionRequest request) {
TimiException.required(request, "not found fulfillment request");
checkSource(service.detail(request.getFulfillmentId()), GaoPermissionCode.ORDER_FULFILLMENT_CREATE, GaoPermissionCode.ORDER_FULFILLMENT_CREATE);
GaoOrderFulfillment result = service.cancel(request); GaoOrderFulfillment result = service.cancel(request);
fillTransient(List.of(result)); fillTransient(List.of(result));
return result; return result;
@@ -120,14 +190,38 @@ public class GaoOrderFulfillmentController {
@AOPLog @AOPLog
@RequestRateLimit @RequestRateLimit
@RequireGaoPermission(GaoPermissionCode.ORDER_FULFILLMENT_REVOKE)
@PostMapping("/revoke") @PostMapping("/revoke")
public GaoOrderFulfillment revoke(@RequestBody GaoOrderFulfillmentRevokeRequest request) { public GaoOrderFulfillment revoke(@RequestBody GaoOrderFulfillmentRevokeRequest request) {
TimiException.required(request, "not found fulfillment request");
checkSource(service.detail(request.getFulfillmentId()), GaoPermissionCode.ORDER_FULFILLMENT_REVOKE, GaoPermissionCode.ORDER_FULFILLMENT_REVOKE);
GaoOrderFulfillment result = service.revoke(request); GaoOrderFulfillment result = service.revoke(request);
fillTransient(List.of(result)); fillTransient(List.of(result));
return result; return result;
} }
@AOPLog
@RequestRateLimit
@RequireGaoPermission(GaoPermissionCode.ORDER_FULFILLMENT_RETURN)
@PostMapping("/return")
public GaoOrderFulfillment returnGoods(@RequestBody GaoOrderFulfillmentReturnRequest request) {
TimiException.required(request, "履约退货请求不能为空");
GaoOrderFulfillment source = service.detail(request.getFulfillmentId());
TimiException.requiredTrue(!isRecycleOrder(source.getSalesOrderId()), "回收兑换履约请通过冲正处理");
GaoOrderFulfillment result = service.returnGoods(request);
fillTransient(List.of(result));
return result;
}
private void checkSource(GaoOrderFulfillment fulfillment, GaoPermissionCode order, GaoPermissionCode recycle) {
permissionChecker.checkAll(ModuleCode.GAO, (isRecycleOrder(fulfillment.getSalesOrderId()) ? recycle : order).getValue());
}
private boolean isRecycleOrder(String id) {
if (id == null || id.isBlank()) return false;
GaoSalesOrder order = salesOrderService.detail(id);
return order.getOrderType() == GaoSalesOrder.OrderType.RECYCLE;
}
private void fillTransient(List<GaoOrderFulfillment> fulfillmentList) { private void fillTransient(List<GaoOrderFulfillment> fulfillmentList) {
if (fulfillmentList == null || fulfillmentList.isEmpty()) { if (fulfillmentList == null || fulfillmentList.isEmpty()) {
return; return;

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