From a0f6e44368f8c73145039a96fcec77cb5c1f23f9 Mon Sep 17 00:00:00 2001
From: 云 <2163098428@qq.com>
Date: 星期三, 27 五月 2026 11:31:13 +0800
Subject: [PATCH] feat(ai): 添加AI会话清理任务并优化财务分析功能
---
src/main/java/com/ruoyi/ai/tools/ApproveTodoTools.java | 15 +++--
src/main/java/com/ruoyi/ai/context/AiSessionUserContext.java | 30 ++++++++++
src/main/java/com/ruoyi/ai/tools/FinancialAgentTools.java | 53 ++++++++++++++++-
src/main/java/com/ruoyi/ai/controller/FinancialAiController.java | 32 ++++++++++
src/main/java/com/ruoyi/ai/schedule/AiSessionCleanupTask.java | 24 ++++++++
5 files changed, 143 insertions(+), 11 deletions(-)
diff --git a/src/main/java/com/ruoyi/ai/context/AiSessionUserContext.java b/src/main/java/com/ruoyi/ai/context/AiSessionUserContext.java
index 3a5877b..5251561 100644
--- a/src/main/java/com/ruoyi/ai/context/AiSessionUserContext.java
+++ b/src/main/java/com/ruoyi/ai/context/AiSessionUserContext.java
@@ -4,6 +4,8 @@
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
+import java.time.Duration;
+import java.time.Instant;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
@@ -11,18 +13,26 @@
public class AiSessionUserContext {
private final Map<String, LoginUser> loginUserByMemoryId = new ConcurrentHashMap<>();
+ private final Map<String, Instant> lastAccessTimeByMemoryId = new ConcurrentHashMap<>();
+ private static final Duration SESSION_TIMEOUT = Duration.ofHours(24);
public void bind(String memoryId, LoginUser loginUser) {
if (!StringUtils.hasText(memoryId) || loginUser == null) {
return;
}
loginUserByMemoryId.put(memoryId, loginUser);
+ lastAccessTimeByMemoryId.put(memoryId, Instant.now());
}
public LoginUser get(String memoryId) {
if (!StringUtils.hasText(memoryId)) {
return null;
}
+ if (isExpired(memoryId)) {
+ remove(memoryId);
+ return null;
+ }
+ lastAccessTimeByMemoryId.put(memoryId, Instant.now());
return loginUserByMemoryId.get(memoryId);
}
@@ -31,5 +41,25 @@
return;
}
loginUserByMemoryId.remove(memoryId);
+ lastAccessTimeByMemoryId.remove(memoryId);
+ }
+
+ public void cleanExpiredSessions() {
+ Instant now = Instant.now();
+ lastAccessTimeByMemoryId.entrySet().removeIf(entry -> {
+ boolean expired = Duration.between(entry.getValue(), now).compareTo(SESSION_TIMEOUT) > 0;
+ if (expired) {
+ loginUserByMemoryId.remove(entry.getKey());
+ }
+ return expired;
+ });
+ }
+
+ private boolean isExpired(String memoryId) {
+ Instant lastAccess = lastAccessTimeByMemoryId.get(memoryId);
+ if (lastAccess == null) {
+ return true;
+ }
+ return Duration.between(lastAccess, Instant.now()).compareTo(SESSION_TIMEOUT) > 0;
}
}
diff --git a/src/main/java/com/ruoyi/ai/controller/FinancialAiController.java b/src/main/java/com/ruoyi/ai/controller/FinancialAiController.java
index 2a3089d..9465d5a 100644
--- a/src/main/java/com/ruoyi/ai/controller/FinancialAiController.java
+++ b/src/main/java/com/ruoyi/ai/controller/FinancialAiController.java
@@ -82,6 +82,16 @@
return Flux.just(directResponse);
}
+ if (isBusinessDataIntent(userMessage)) {
+ String noGuessResponse = "鏈瘑鍒埌鍙墽琛岀殑鏁版嵁鏌ヨ鏉′欢銆備负淇濊瘉缁撴灉鍑嗙‘锛屽綋鍓嶄笉浼氭帹娴嬫垨缂栭�犳暟鎹紝璇疯ˉ鍏呮槑纭椂闂磋寖鍥淬�佸鎴枫�佷緵搴斿晢鎴栧崟鍙峰悗鍐嶆煡璇€��";
+ mongoChatMemoryStore.appendMessages(
+ memoryId,
+ List.of(UserMessage.from(userMessage), AiMessage.from(noGuessResponse))
+ );
+ aiChatSessionService.refreshSessionStats(memoryId, loginUser);
+ return Flux.just(noGuessResponse);
+ }
+
return financialAgent.chat(memoryId, userMessage, currentDateForPrompt())
.doOnComplete(() -> aiChatSessionService.refreshSessionStats(memoryId, loginUser))
.doOnError(ex -> aiChatSessionService.refreshSessionStats(memoryId, loginUser));
@@ -109,4 +119,26 @@
private String currentDateForPrompt() {
return LocalDate.now(CHINA_ZONE_ID).format(CURRENT_DATE_FMT);
}
+
+ private boolean isBusinessDataIntent(String message) {
+ if (!StringUtils.hasText(message)) {
+ return false;
+ }
+ String text = message.trim();
+ return containsAny(text,
+ "鏌ヨ", "鏌ョ湅", "缁熻", "鍒嗘瀽", "寤鸿", "鎴愭湰鏍哥畻", "浜у搧鎴愭湰", "宸ュ簭鎴愭湰",
+ "璁㈠崟鍒╂鼎", "浜忔崯璁㈠崟", "浣庡埄娑�", "搴撳瓨璧勯噾", "搴撳瓨绉帇", "鍛嗘粸搴撳瓨",
+ "鐜伴噾娴�", "鍥炴椋庨櫓", "浠樻鍘嬪姏", "璧勯噾缂哄彛", "搴旀敹", "搴斾粯",
+ "寮傚父棰勮", "缁忚惀寮傚父", "椋庨櫓棰勮", "椹鹃┒鑸�", "缁忚惀鐪嬫澘", "缁忚惀鎬昏",
+ "鏃ユ姤", "鍛ㄦ姤", "缁忚惀鎶ュ憡", "鍒嗘瀽鎶ュ憡", "涓氳储铻嶅悎", "鍙e緞", "鎸囨爣瑙i噴");
+ }
+
+ private boolean containsAny(String text, String... keywords) {
+ for (String keyword : keywords) {
+ if (text.contains(keyword)) {
+ return true;
+ }
+ }
+ return false;
+ }
}
diff --git a/src/main/java/com/ruoyi/ai/schedule/AiSessionCleanupTask.java b/src/main/java/com/ruoyi/ai/schedule/AiSessionCleanupTask.java
new file mode 100644
index 0000000..cecdba8
--- /dev/null
+++ b/src/main/java/com/ruoyi/ai/schedule/AiSessionCleanupTask.java
@@ -0,0 +1,24 @@
+package com.ruoyi.ai.schedule;
+
+import com.ruoyi.ai.context.AiSessionUserContext;
+import org.springframework.scheduling.annotation.Scheduled;
+import org.springframework.stereotype.Component;
+
+@Component
+public class AiSessionCleanupTask {
+
+ private final AiSessionUserContext aiSessionUserContext;
+
+ public AiSessionCleanupTask(AiSessionUserContext aiSessionUserContext) {
+ this.aiSessionUserContext = aiSessionUserContext;
+ }
+
+ @Scheduled(cron = "0 0 2 * * ?")
+ public void cleanupExpiredSessions() {
+ try {
+ aiSessionUserContext.cleanExpiredSessions();
+ } catch (Exception e) {
+ System.err.println("娓呯悊杩囨湡AI浼氳瘽澶辫触: " + e.getMessage());
+ }
+ }
+}
diff --git a/src/main/java/com/ruoyi/ai/tools/ApproveTodoTools.java b/src/main/java/com/ruoyi/ai/tools/ApproveTodoTools.java
index fec0c21..e947ec1 100644
--- a/src/main/java/com/ruoyi/ai/tools/ApproveTodoTools.java
+++ b/src/main/java/com/ruoyi/ai/tools/ApproveTodoTools.java
@@ -22,11 +22,10 @@
import java.io.IOException;
import java.math.BigDecimal;
-import java.text.ParseException;
-import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.YearMonth;
+import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
@@ -46,7 +45,7 @@
private static final int DEFAULT_LIMIT = 10;
private static final int MAX_LIMIT = 20;
- private static final SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("yyyy-MM-dd");
+ private static final DateTimeFormatter DATE_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd");
private static final DateTimeFormatter DATE_TIME_FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
private final ApproveProcessMapper approveProcessMapper;
@@ -740,7 +739,10 @@
}
private String formatDate(Date value) {
- return value == null ? "" : DATE_FORMAT.format(value);
+ if (value == null) {
+ return "";
+ }
+ return value.toInstant().atZone(ZoneId.systemDefault()).toLocalDate().format(DATE_FORMATTER);
}
private long countByStatus(List<ApproveProcess> processes, int status) {
@@ -824,8 +826,9 @@
private Date parseDate(String dateText) {
try {
- return DATE_FORMAT.parse(dateText);
- } catch (ParseException e) {
+ LocalDate localDate = LocalDate.parse(dateText, DATE_FORMATTER);
+ return Date.from(localDate.atStartOfDay(ZoneId.systemDefault()).toInstant());
+ } catch (Exception e) {
throw new IllegalArgumentException("鏃ユ湡鏍煎紡蹇呴』鏄� yyyy-MM-dd");
}
}
diff --git a/src/main/java/com/ruoyi/ai/tools/FinancialAgentTools.java b/src/main/java/com/ruoyi/ai/tools/FinancialAgentTools.java
index 082b2cd..e907aff 100644
--- a/src/main/java/com/ruoyi/ai/tools/FinancialAgentTools.java
+++ b/src/main/java/com/ruoyi/ai/tools/FinancialAgentTools.java
@@ -88,7 +88,14 @@
private static final BigDecimal ONE_HUNDRED = new BigDecimal("100");
private static final int DEFAULT_LIMIT = 10;
private static final int MAX_LIMIT = 50;
- private static final BigDecimal DEFAULT_FALLBACK_MATERIAL_COST_RATE = new BigDecimal("0.65");
+
+ private static final BigDecimal DEFAULT_FALLBACK_MATERIAL_COST_RATE = new BigDecimal("0.60");
+ private static final BigDecimal DEFAULT_LABOR_COST_RATE = new BigDecimal("0.15");
+ private static final BigDecimal DEFAULT_OVERHEAD_COST_RATE = new BigDecimal("0.10");
+
+ private static final BigDecimal SME_RECEIVABLE_RISK_THRESHOLD = new BigDecimal("500000");
+ private static final BigDecimal SME_INVENTORY_RISK_THRESHOLD = new BigDecimal("1000000");
+ private static final BigDecimal SME_PROFIT_WARNING_RATE = new BigDecimal("0.08");
private final SalesLedgerMapper salesLedgerMapper;
private final SalesLedgerProductMapper salesLedgerProductMapper;
@@ -194,6 +201,10 @@
@P(value = "鍏抽敭璇嶏紝鍙尮閰嶅悎鍚屽彿/瀹㈡埛/椤圭洰", required = false) String keyword,
@P(value = "杩斿洖鏉℃暟锛岄粯璁�10锛屾渶澶�50", required = false) Integer limit) {
LoginUser loginUser = currentLoginUser(memoryId);
+ if (loginUser == null) {
+ return jsonResponse(false, "financial_cost_accounting", "鐢ㄦ埛淇℃伅鑾峰彇澶辫触", Map.of(), Map.of(), Map.of());
+ }
+
DateRange range = resolveDateRange(startDate, endDate, timeRange, "杩�30澶�");
AnalysisBundle bundle = buildOrderProfitBundle(loginUser, range, keyword, limit);
@@ -248,12 +259,16 @@
@P(value = "鍏抽敭璇嶏紝鍙尮閰嶅悎鍚屽彿/瀹㈡埛/椤圭洰", required = false) String keyword,
@P(value = "杩斿洖鏉℃暟锛岄粯璁�10锛屾渶澶�50", required = false) Integer limit) {
LoginUser loginUser = currentLoginUser(memoryId);
+ if (loginUser == null) {
+ return jsonResponse(false, "financial_order_profit_analysis", "鐢ㄦ埛淇℃伅鑾峰彇澶辫触", Map.of(), Map.of(), Map.of());
+ }
+
DateRange range = resolveDateRange(startDate, endDate, timeRange, "杩�30澶�");
AnalysisBundle bundle = buildOrderProfitBundle(loginUser, range, keyword, limit);
List<OrderProfitMetric> metrics = bundle.orderMetrics();
List<OrderProfitMetric> riskyOrders = metrics.stream()
- .filter(item -> item.profit().compareTo(BigDecimal.ZERO) < 0 || item.profitRate().compareTo(new BigDecimal("0.08")) < 0)
+ .filter(item -> item.profit().compareTo(BigDecimal.ZERO) < 0 || item.profitRate().compareTo(SME_PROFIT_WARNING_RATE) < 0)
.sorted(Comparator.comparing(OrderProfitMetric::profitRate)
.thenComparing(OrderProfitMetric::profit))
.toList();
@@ -594,10 +609,10 @@
if (lossCount > 0) {
riskSuggestions.add(riskSuggestion("鍒╂鼎椋庨櫓", "楂�", "澶嶆牳浜忔崯璁㈠崟BOM鍜屽伐搴忓伐璧勫畾棰濓紝蹇呰鏃惰皟鏁存姤浠蜂笌浜や粯鑺傚銆�"));
}
- if (snapshot.receivableTotal().compareTo(new BigDecimal("1000000")) > 0) {
+ if (snapshot.receivableTotal().compareTo(SME_RECEIVABLE_RISK_THRESHOLD) > 0) {
riskSuggestions.add(riskSuggestion("鍥炴椋庨櫓", "涓�", "瀵瑰簲鏀禩OP瀹㈡埛寤虹珛鍛ㄥ害鍥炴璁″垝锛屽苟璁剧疆棰勮闃堝�笺��"));
}
- if (inventoryValue.compareTo(new BigDecimal("3000000")) > 0) {
+ if (inventoryValue.compareTo(SME_INVENTORY_RISK_THRESHOLD) > 0) {
riskSuggestions.add(riskSuggestion("搴撳瓨椋庨櫓", "涓�", "瀵归珮閲戦鍛嗘粸搴撳瓨鎵ц闄嶄环銆佹浛浠e拰鐢熶骇娑堣�楃瓥鐣ャ��"));
}
@@ -1319,7 +1334,35 @@
return productAmount;
}
}
- return revenue.multiply(DEFAULT_FALLBACK_MATERIAL_COST_RATE);
+
+ BigDecimal materialCost = revenue.multiply(DEFAULT_FALLBACK_MATERIAL_COST_RATE);
+ BigDecimal laborCost = revenue.multiply(DEFAULT_LABOR_COST_RATE);
+ BigDecimal overheadCost = revenue.multiply(DEFAULT_OVERHEAD_COST_RATE);
+
+ return materialCost.add(laborCost).add(overheadCost);
+ }
+
+ private BigDecimal estimateTotalCost(BigDecimal revenue, List<SalesLedgerProduct> products) {
+ if (revenue == null || revenue.compareTo(BigDecimal.ZERO) <= 0) {
+ return BigDecimal.ZERO;
+ }
+
+ BigDecimal materialCost = BigDecimal.ZERO;
+ if (products != null && !products.isEmpty()) {
+ materialCost = products.stream()
+ .map(SalesLedgerProduct::getTaxExclusiveTotalPrice)
+ .filter(Objects::nonNull)
+ .reduce(BigDecimal.ZERO, BigDecimal::add);
+ }
+
+ if (materialCost.compareTo(BigDecimal.ZERO) <= 0) {
+ materialCost = revenue.multiply(DEFAULT_FALLBACK_MATERIAL_COST_RATE);
+ }
+
+ BigDecimal laborCost = revenue.multiply(DEFAULT_LABOR_COST_RATE);
+ BigDecimal overheadCost = revenue.multiply(DEFAULT_OVERHEAD_COST_RATE);
+
+ return materialCost.add(laborCost).add(overheadCost);
}
private Map<String, String> queryCustomerNameMap(Set<String> idSet) {
--
Gitblit v1.9.3