diff --git a/apps/agent/application/chat_service.py b/apps/agent/application/chat_service.py index aa8b4b8a..0629f590 100644 --- a/apps/agent/application/chat_service.py +++ b/apps/agent/application/chat_service.py @@ -11,6 +11,7 @@ from application.session_service import SessionService from config.settings import Settings from domain.models import Actor, ChatMessage, MessageRole from domain.ports import ChatStreamer, MessageRepository, SessionRepository +from infrastructure.builtin_tools import builtin_tools from infrastructure.mcp_client import load_mcp_tools @@ -55,9 +56,11 @@ class ChatService: actor, thread_id=thread_id, text=text ) memory_lines = await self._memory.lines_for_prompt(actor) - tools = await load_mcp_tools( + mcp_tools = await load_mcp_tools( self._settings, company_id=actor.company_id, user_id=actor.user_id ) + # 本地时间工具始终挂上,不依赖 MCP 是否可用 + tools = [*builtin_tools(), *mcp_tools] history = await self._messages.list_recent( actor.company_id, diff --git a/apps/agent/infrastructure/builtin_tools.py b/apps/agent/infrastructure/builtin_tools.py new file mode 100644 index 00000000..d04bee15 --- /dev/null +++ b/apps/agent/infrastructure/builtin_tools.py @@ -0,0 +1,47 @@ +"""本地工具:不依赖 MCP / 业务库,只提供模型无法自行得知的环境信息。""" + +from __future__ import annotations + +import json +from datetime import date, datetime, timedelta +from zoneinfo import ZoneInfo + +from langchain_core.tools import BaseTool, tool + +# 与后端业务库、BI 日期口径一致 +_TZ = ZoneInfo("Asia/Shanghai") +_WEEKDAYS = ("周一", "周二", "周三", "周四", "周五", "周六", "周日") + + +def builtin_tools() -> list[BaseTool]: + return [get_current_time] + + +@tool +def get_current_time() -> str: + """获取当前业务时间(Asia/Shanghai)。 + + 用户说近 N 天、昨天、本周、本月等相对日期时必须先调用本工具, + 用返回的 ranges 或 today 换算 yyyy-MM-dd 后再查经营数据,不要向用户索要日期。 + 近 N 天含今天,共 N 个自然日。 + """ + now = datetime.now(_TZ) + today = now.date() + payload = { + "timezone": "Asia/Shanghai", + "now": now.isoformat(timespec="seconds"), + "today": today.isoformat(), + "weekday": _WEEKDAYS[today.weekday()], + "ranges": { + "yesterday": _span(today - timedelta(days=1), today - timedelta(days=1)), + "last_7_days": _span(today - timedelta(days=6), today), + "last_30_days": _span(today - timedelta(days=29), today), + "this_week": _span(today - timedelta(days=today.weekday()), today), + "this_month": _span(today.replace(day=1), today), + }, + } + return json.dumps(payload, ensure_ascii=False) + + +def _span(start: date, end: date) -> dict[str, str]: + return {"startDate": start.isoformat(), "endDate": end.isoformat()} diff --git a/apps/agent/infrastructure/llm_factory.py b/apps/agent/infrastructure/llm_factory.py index 9ac44fb8..b06226d7 100644 --- a/apps/agent/infrastructure/llm_factory.py +++ b/apps/agent/infrastructure/llm_factory.py @@ -13,7 +13,10 @@ from domain.ports import ChatStreamer _BASE_SYSTEM = ( "你是电商 DMB 系统的经营助手。回答简洁、可执行。" - "需要经营数据时优先调用可用工具;缺少参数时向用户确认。" + "需要经营数据时优先调用可用工具。" + "用户说近 N 天、昨天、本周、本月等相对日期时,先调用 get_current_time," + "用返回的 ranges 或 today 换算 yyyy-MM-dd 后再查数,不要向用户索要日期范围。" + "仅当缺少店铺、商品等业务标识时才向用户确认。" "若工具失败或无权限,请说明原因并给出可操作建议。" ) diff --git a/apps/server/src/main/java/top/xyquan/ecomdmbbackend/modules/sys/menu/service/impl/UserMenuServiceImpl.java b/apps/server/src/main/java/top/xyquan/ecomdmbbackend/modules/sys/menu/service/impl/UserMenuServiceImpl.java index 29e9f4d8..6ceb15e8 100644 --- a/apps/server/src/main/java/top/xyquan/ecomdmbbackend/modules/sys/menu/service/impl/UserMenuServiceImpl.java +++ b/apps/server/src/main/java/top/xyquan/ecomdmbbackend/modules/sys/menu/service/impl/UserMenuServiceImpl.java @@ -77,8 +77,10 @@ public class UserMenuServiceImpl implements UserMenuService { List menus; if (isSuper) { - // 超级管理员获取所有系统菜单,不需要公司上下文 - menus = menuService.getAllMenus(); + // 超管:全部菜单中仅启用项进入动态路由(与 getMenusForRoute 一致,避免已下线 component 报错) + menus = menuService.getAllMenus().stream() + .filter(menu -> Integer.valueOf(1).equals(menu.getStatus())) + .collect(Collectors.toList()); } else { // 普通用户,根据公司成员角色判断 Long companyIdForUser = currentUserContext.getCurrentCompanyId(); diff --git a/apps/web/apps/web-antd/package.json b/apps/web/apps/web-antd/package.json index 2a0b3f54..50e392e6 100644 --- a/apps/web/apps/web-antd/package.json +++ b/apps/web/apps/web-antd/package.json @@ -42,6 +42,7 @@ "@vben/utils": "workspace:*", "@vueuse/core": "catalog:", "ant-design-vue": "catalog:", + "ant-design-x-vue": "^1.6.0", "dayjs": "catalog:", "dompurify": "^3.4.15", "marked": "^18.0.13", diff --git a/apps/web/apps/web-antd/src/router/access.ts b/apps/web/apps/web-antd/src/router/access.ts index fb8bebf9..5c7b92b3 100644 --- a/apps/web/apps/web-antd/src/router/access.ts +++ b/apps/web/apps/web-antd/src/router/access.ts @@ -1,6 +1,7 @@ import type { ComponentRecordType, GenerateMenuAndRoutesOptions, + RouteRecordStringComponent, } from '@vben/types'; import { generateAccessible } from '@vben/access'; @@ -14,6 +15,52 @@ import { $t } from '#/locales'; const forbiddenComponent = () => import('#/views/_core/fallback/forbidden.vue'); +/** 将 glob key 规范成与后端 component 一致的 /xxx/index.vue */ +function normalizePageKey(path: string): string { + const normalized = path.replace(/^(\.\/|\.\.\/)+/, ''); + const withSlash = normalized.startsWith('/') ? normalized : `/${normalized}`; + const viewPath = withSlash.replace(/^\/views/, ''); + return viewPath.endsWith('.vue') ? viewPath : `${viewPath}.vue`; +} + +/** + * 过滤掉本地不存在的页面组件(已下线菜单仍下发时避免 console.error)。 + * layout / iframe 名称保留。 + */ +function filterMissingPageRoutes( + routes: RouteRecordStringComponent[], + pageMap: ComponentRecordType, + layoutMap: ComponentRecordType, +): RouteRecordStringComponent[] { + const knownPages = new Set( + Object.keys(pageMap).map((k) => normalizePageKey(k)), + ); + + const walk = ( + nodes: RouteRecordStringComponent[], + ): RouteRecordStringComponent[] => { + const result: RouteRecordStringComponent[] = []; + for (const node of nodes) { + const children = node.children?.length + ? walk(node.children as RouteRecordStringComponent[]) + : undefined; + const component = node.component; + if (!component || layoutMap[component]) { + result.push(children ? { ...node, children } : node); + continue; + } + const pageKey = normalizePageKey(component); + if (!knownPages.has(pageKey)) { + continue; + } + result.push(children ? { ...node, children } : node); + } + return result; + }; + + return walk(routes); +} + async function generateAccess(options: GenerateMenuAndRoutesOptions) { const pageMap: ComponentRecordType = import.meta.glob('../views/**/*.vue'); @@ -31,7 +78,7 @@ async function generateAccess(options: GenerateMenuAndRoutesOptions) { }); try { const routes = await getUserMenuApi(); - return routes; + return filterMissingPageRoutes(routes || [], pageMap, layoutMap); } catch (error) { console.error('❌ 获取用户菜单路由失败:', error); throw error; diff --git a/apps/web/apps/web-antd/src/views/agent/chat/index.vue b/apps/web/apps/web-antd/src/views/agent/chat/index.vue index a4b355e7..8a5a0029 100644 --- a/apps/web/apps/web-antd/src/views/agent/chat/index.vue +++ b/apps/web/apps/web-antd/src/views/agent/chat/index.vue @@ -1,7 +1,19 @@