fix(conflicts): 解决冲突及功能迁移

This commit is contained in:
hugo committed 2026-06-11 18:33:16 +08:00
commit e827c5dc38
208 files changed
+15526 -12088

No files matched your search

+393 -40
View File
@@ -1,6 +1,6 @@
# HXOPS 前端重构架构方案
> 更新时间:2026-06-02
> 更新时间:2026-06-11
> 适用范围:`frontend/` 目录
> 文档定位:定义推荐的目标架构(Feature-Module + Composables + Pinia),作为后续分阶段重构的基准。
@@ -35,25 +35,27 @@
```text
frontend/src/
├── app/ # 应用启动层
│ ├── main.ts
│ ├── App.vue
├── main.ts # Vite 入口(保留在 src 根,不迁入 app/)
├── App.vue # 根组件(保留在 src 根)
├── app/ # 应用基础设施(路由 / 插件)
│ ├── router/
│ │ ├── index.ts # 汇总各域路由
│ │ ├── guards.ts # 认证 / 权限守卫(从 router/index.ts 抽出)
│ │ ├── guards.ts # 认证 / 权限守卫
│ │ └── routes/ # 按业务域拆分路由表
│ │ ├── auth.routes.ts
│ │ ├── chat.routes.ts
│ │ ├── admin.routes.ts
│ │ ├── workspace.routes.ts
│ │ └── kb.routes.ts
│ └── plugins/
│ ├── i18n.ts # 仅注册 i18n 实例,messages 外置
│ └── pinia.ts
│
├── shared/ # 跨域共享(无业务语义)
│ ├── api/
│ │ ├── client.ts # requestJson、BusinessError、响应 envelope 解析
│ │ └── types.ts # 通用 API 类型
│ │ ├── client.ts # requestJson、BusinessError(权威实现)
│ │ └── types.ts # 通用 API 类型(待补充)
│ ├── types/
│ │ └── schedule.types.ts # admin / workspace 共用排程类型
│ ├── composables/ # useTheme、useIsMobile、useMessage 等
│ ├── components/ # 通用 UI:Dialog、DataTable、EmptyState、Pagination
│ ├── layouts/ # AppShell、ChatShell、MinimalShell、MarketingShell
@@ -70,13 +72,23 @@ frontend/src/
│ │ ├── composables/
│ │ │ └── useAuth.ts
│ │ ├── views/
│ │ │ ├── WorkspaceView.vue
│ │ │ ├── LoginView.vue
│ │ │ └── ResetPasswordView.vue
│ │ └── components/
│ │
│ ├── workspace/ # AI 工作台(自 auth 拆出,2026-06)
│ │ ├── api/
│ │ │ └── schedule.api.ts # 工作台排程记录
│ │ ├── views/
│ │ │ └── WorkspaceLayout.vue
│ │ ├── pages/ # HomePage、ProfilePage、ScheduleRunsPage 等
│ │ ├── composables/
│ │ └── components/
│ │
│ ├── chat/
│ │ ├── api/
│ │ │ └── chat.api.ts
│ │ │ ├── chat.api.ts
│ │ │ └── shipping.api.ts # 货代发货(/api/workspace/shipping-tasks)
│ │ ├── types/
│ │ │ └── chat.types.ts
│ │ ├── stores/
@@ -98,7 +110,7 @@ frontend/src/
│ ├── admin/
│ │ ├── api/
│ │ │ ├── admin.api.ts
│ │ │ └── schedule.api.ts
│ │ │ └── schedule.api.ts # 管理后台定时任务
│ │ ├── stores/
│ │ │ └── admin-nav.store.ts
│ │ ├── views/
@@ -147,20 +159,20 @@ frontend/src/
| 现有路径 | 目标路径 | 说明 |
|----------|----------|------|
| `src/main.ts`、`src/App.vue` | `app/` | 启动与全局插件注册 |
| `src/main.ts`、`src/App.vue` | **保留 `src/` 根目录** | Vite 入口约定;不迁入 `app/` |
| `src/router/index.ts` | `app/router/` | 路由表与守卫拆分 |
| `src/api/client.ts` | `shared/api/client.ts` | 保持不变,作为统一 HTTP 层 |
| `src/api/*.ts` | `features/*/api/` | 按业务域归属 |
| `src/api/client.ts` | `shared/api/client.ts` | 权威实现;`src/api/client.ts` deprecated 转发 |
| `src/api/*.ts` | `features/*/api/` | 按业务域归属(KB 暂缓,见 §12) |
| `src/composables/`(通用) | `shared/composables/` | useTheme、useMessage 等 |
| `src/composables/useChat.ts` | `features/chat/composables/` | 聊天域专属 |
| `src/components/`(通用 Dialog 等) | `shared/components/` | 跨域复用 UI |
| `src/components/kb/` | `features/kb/components/` | 知识库域 |
| `src/components/kb/` | `shared/components/kb/` | 暂留 shared,KB redesign 后迁 `features/kb/` |
| `src/layouts/` | `shared/layouts/` | 页面壳层 |
| `src/utils/` | `shared/utils/` | 纯工具函数 |
| `src/styles/` | `shared/styles/` | 设计 token 与全局样式 |
| `src/views/AdminView.vue` | `features/admin/modules/*/` | 拆为 12+ 子模块页面 |
| `src/views/ChatView.vue` | `features/chat/` | View + 多个子组件 |
| `src/views/WorkspaceView.vue` | `features/auth/views/` | 登录 / 工作台 |
| `src/views/WorkspaceView.vue` | `features/workspace/` + `features/auth/views/LoginView.vue` | 登录与工作台分离 |
| `src/i18n.ts` | `locales/` | 按语言、域拆分 JSON |
---
@@ -343,7 +355,7 @@ resolve: {
```text
features/chat/views/ChatView.vue
✅ import { useChat } from '../composables/useChat'
✅ import { BaseDialog } from '@/shared/components/BaseDialog.vue'
✅ import DeleteConfirmDialog from '@/shared/components/DeleteConfirmDialog.vue'
✅ import { listChatSessions } from '../api/chat.api'
❌ import { listAdminUsers } from '@/features/admin/api/admin.api' // 跨 feature 禁止
```
@@ -367,11 +379,13 @@ Phase 0 目标:搭好基础设施,**不迁移现有 views**,旧代码可
| Auth Store | `features/auth/stores/auth.store.ts` |
| Auth Composable | `features/auth/composables/useAuth.ts` |
| Chat Store 骨架 | `features/chat/stores/chat.store.ts` |
| API 转发层 | `shared/api/client.ts` → 现有 `api/client.ts` |
| API 转发层 | `shared/api/client.ts` 为权威实现;`src/api/client.ts` deprecated 转发 |
| 路由常量 | `shared/constants/routes.ts` |
| 兼容入口 | `router/index.ts` re-export `app/router` |
### 7.2 启动顺序(main.ts)
### 7.2 启动顺序(`src/main.ts`)
> **约定**:`main.ts` / `App.vue` 留在 `src/` 根目录,与 Vite `index.html` 入口一致;`app/` 仅放 router、plugins 等可拆分的基础设施。
```typescript
app.use(pinia);
@@ -404,49 +418,388 @@ Phase 1 已完成,见 §8。
---
## 8. Phase 1 落地说明(已实现)
## 8. Phase 1 落地说明(已实现,后续全量拆分见 §9)
Phase 1 目标:管理后台嵌套子路由 + 首个独立模块 `agents`。
### 8.1 路由结构
### 8.1 路由结构(初版)
| URL | 组件 | 说明 |
|-----|------|------|
| `/admin` | redirect → `/admin/dashboard` | |
| `/admin/agents` | `AgentsPage.vue` | **已独立拆分** |
| `/admin/dashboard` 等 | `AdminLegacyPage.vue` | 内嵌 `AdminView`(content-only) |
| `/admin/reports/:table?` | `AdminLegacyPage.vue` | 报表模块 |
| `/admin/agents` | `AgentsPage.vue` | **首个独立拆分** |
| `/admin/dashboard` 等 | `AdminLegacyPage.vue` | 内嵌 `AdminView`(content-only,已移除) |
| `/admin?module=xxx` | redirect | 兼容旧链接,跳转至 `/admin/xxx` |
### 8.2 新增文件(均含文件头注释)
> **2026-06 更新**:全部 admin 子模块已独立,见 §9。
### 8.2 初版新增文件
```text
features/admin/
├── views/AdminLayout.vue # 壳层:顶栏 + AdminNav + router-view
├── views/AdminLegacyPage.vue # 未拆分模块的过渡容器
├── components/AdminNav.vue # 子路由导航
├── modules/agents/
│ ├── AgentsPage.vue
│ ├── composables/useAgentsAdmin.ts
│ └── components/{AgentTestModal,AgentPermissionModal}.vue
├── views/AdminLayout.vue
├── modules/agents/ ...
├── stores/admin-nav.store.ts
├── composables/useAdminNavBadges.ts
├── constants/modules.ts
└── types/{admin,agent}.types.ts
└── ...
```
### 8.3 构建验证
`npm run build` 通过;`AgentsPage`、`AdminLayout`、`AdminLegacyPage` 已代码分割为独立 chunk。
`npm run build` 通过。
### 8.4 下一步(Phase 2)
### 8.4 下一步
- 继续拆分 `users`、`permissions` 等 admin 模块
- 拆分 `ChatView.vue` 为 `features/chat/components/*`
Admin 全量拆分 → §9;Chat 拆分 → §10。
---
## 9. 相关文档
## 9. Phase 1.5 Admin 全量拆分(已实现)
Phase 1.5 目标:移除 `AdminView.vue` / `AdminLegacyPage.vue`,全部 `config.admin.modules` 对应独立页面。
### 9.1 路由结构
| URL | 组件 |
|-----|------|
| `/admin/dashboard` | `DashboardPage.vue` |
| `/admin/agents` | `AgentsPage.vue` |
| `/admin/users` | `UsersPage.vue` |
| `/admin/departments` | `DepartmentsPage.vue` |
| `/admin/permissions` | `PermissionsPage.vue` |
| `/admin/requests` | `RequestsPage.vue` |
| `/admin/approvals` | `ApprovalsPage.vue` |
| `/admin/announcements` | `AnnouncementsPage.vue` |
| `/admin/questions` | `QuestionsPage.vue` |
| `/admin/wecom` | `WecomPage.vue` |
| `/admin/schedules` | `SchedulesPage.vue` |
| `/admin/knowledge-base` | `KnowledgeBasePage.vue` |
| `/admin/platform-apps` | `PlatformAppsPage.vue` |
| `/admin/reports/:table?` | `ReportsPage.vue` |
### 9.2 模块目录
```text
features/admin/modules/
├── dashboard/ ├── agents/ ├── users/
├── departments/ ├── permissions/ ├── requests/
├── approvals/ ├── announcements/├── questions/
├── wecom/ ├── schedules/ ├── knowledge-base/
├── platform-apps/ └── reports/
└── composables/use*Admin.ts + components/
```
### 9.3 构建验证
`npm run build` 通过;`AdminView.vue` 已删除。
---
## 10. Phase 2 Chat 域落地说明(已实现)
Phase 2 Chat 目标:将原 `views/ChatView.vue`(~5500 行)拆为 feature 模块,页面壳层 < 50 行。
### 10.1 已完成项
| 项 | 路径 / 说明 |
|----|-------------|
| 页面壳层 | `features/chat/views/ChatView.vue`(~19 行:`useChatPage()` + `provide` + `ChatViewContent` / `ChatViewOverlays`) |
| 主编排 | `composables/useChatPage.ts`(~400 行,组合 `page/*` 子模块与各域 composable) |
| 页面子模块 | `features/chat/page/*`:用户、本地消息、弹窗、语音、Markdown、会话、发送、handlers 打包 |
| 出货子模块 | `features/chat/shipping/*`:纯函数 + `useChatShippingRefresh` / Menu / Upload / Send handler 工厂;`useChatShipping.ts` ~360 行 |
| 请假子模块 | `features/chat/leave/*`:意图解析、OA 登录、代理人选择、表单提交、流程拦截;`useChatLeave.ts` ~130 行 |
| 子 composable | `useChatAgent`、`useChatAttachments`、`useChatRouteSync`、`useChatBrowserPanel`、`useChatQueryPreview`、`useChatGuides`、`useChatScroll` 等 |
| 子组件 | `ChatSidebar`、`ChatMessageList`、`ChatInputBar`、`ChatMessageBubble`、`ChatViewContent`、`ChatViewOverlays`、弹窗等 |
| 路由 lazy | `app/router/routes/chat.routes.ts` → `features/chat/views/ChatView.vue` |
| API | `features/chat/api/chat.api.ts`(`src/api/chat.ts` deprecated 转发) |
| 货代 API | `features/chat/api/shipping.api.ts`(`src/api/shippingNotice.ts` deprecated 转发) |
| 跨 Agent 历史 | `features/chat/pages/HistoryPage.vue` + `useChatHistory` |
| Pinia 接入 | `chat.store`:`currentAgentId`(路由同步)、`sidebarCollapsed`、`sessionHistoryByAgent` 缓存 |
| 内置浏览器 | 输入栏「打开/收起浏览器」按钮已恢复,逻辑在 `useChatBrowserPanel` |
| provide/inject | `chat.context.ts`:`CHAT_PAGE_KEY` + `useChatPageContext()`;`reactive(useChatPage())` 解包嵌套 Ref;`markRaw` 保留 template ref holder |
### 10.2 构建验证
历次拆分后 `npm run build` 通过。
### 10.3 待办(Chat 域内)
| 优先级 | 项 | 状态 |
|--------|-----|------|
| 中 | `chat.context` + provide/inject(`ChatViewContent` / `ChatViewOverlays` inject) | ✅ |
| 中 | `ChatViewOverlays.vue` 抽出全部弹窗 | ✅ |
| 中 | `chat.store` 按 Agent 缓存侧栏会话列表 | ✅ |
| 中 | 瘦身 `useChatPage` → `page/*` 子模块 | ✅ |
| 中 | 瘦身 `useChatShipping` → `shipping/*` 子模块 | ✅ |
| 中 | 瘦身 `useChatLeave` → `leave/*` 子模块 | ✅ |
| 低 | `LeaveAgentOption` 等类型已统一至 `leave.types.ts` 并 re-export | ✅ |
| 低 | `chat.context` 完善类型(`ChatPageContextProvided` + `useChatPageContext()`) | ✅ |
| 低 | `shipping/*`、`leave/*` 纯函数单元测试 | 待做 |
### 10.4 下一步
- ~~Admin 模块独立~~ → 见 §9
- Workspace 壳层 → 见 §11
- ~~API 按 feature 归属~~ → 见 §12
- ~~`shared/` composables/components/layouts/utils/styles 迁移~~ → 见 §14
- KB 域重新设计(暂缓)
- `locales/` 按域拆分
---
## 11. Phase 3 Workspace 模块(部分实现)
Phase 3 目标:将原 `WorkspaceView.vue` 拆为独立 feature,路由 `/workspace/*`。
### 11.1 已完成项
| 项 | 路径 / 说明 |
|----|-------------|
| 布局壳 | `features/workspace/views/WorkspaceLayout.vue` + `provide/inject` |
| 子页面 | `HomePage`(应用管理)、`ProfilePage`、`ScheduleRunsPage`、`FeedbackPage` |
| 路由 | `app/router/routes/workspace.routes.ts` |
| Composable | `useWorkspace`、`useWorkspaceHome`、`useWorkspaceNavigation` 等 |
| 排程 API | `features/workspace/api/schedule.api.ts` |
| 历史页 | 复用 `features/chat/pages/HistoryPage.vue` |
### 11.2 薄包装页(待真正迁入 feature)
| 页面 | 现状 |
|------|------|
| `KnowledgeBasePage.vue` | 嵌入 `src/views/KbWorkspaceView.vue`(KB 域暂缓 redesign) |
| `ShippingNoticePage.vue` | 嵌入 `src/views/ShippingNoticeView.vue` |
### 11.3 路由
```text
/workspace/applications → HomePage
/workspace/profile → ProfilePage
/workspace/schedule-runs → ScheduleRunsPage
/workspace/shipping-notice → ShippingNoticePage(legacy 嵌入)
/workspace/knowledge-base → KnowledgeBasePage(legacy 嵌入)
/workspace/history → chat/pages/HistoryPage
```
---
## 12. Phase 4 API 按 Feature 归属(已实现,KB 除外)
Phase 4 目标:领域 HTTP 请求迁入对应 `features/*/api/`,`shared/api/client.ts` 作为唯一 JSON 客户端。
### 12.1 迁移对照
| 原路径 | 新路径 | 状态 |
|--------|--------|------|
| `src/api/client.ts` | `shared/api/client.ts` | ✅ 权威实现;旧路径 deprecated 转发 |
| `src/api/user.ts` | `features/auth/api/user.api.ts` | ✅(Phase 0 已完成) |
| `src/api/chat.ts` | `features/chat/api/chat.api.ts` | ✅(Phase 2 已完成) |
| `src/api/admin.ts` | `features/admin/api/admin.api.ts` | ✅ |
| `src/api/schedule.ts`(admin 部分) | `features/admin/api/schedule.api.ts` | ✅ |
| `src/api/schedule.ts`(workspace 部分) | `features/workspace/api/schedule.api.ts` | ✅ |
| 排程共用类型 | `shared/types/schedule.types.ts` | ✅ |
| `src/api/shippingNotice.ts` | `features/chat/api/shipping.api.ts` | ✅ |
| 货代类型 | `features/chat/types/shipping.api.types.ts` | ✅ |
| `src/api/kb.ts` | — | ⏸ 暂缓(KB 域 redesign 后迁移) |
### 12.2 新代码 import 规范
```typescript
// 共享 HTTP 客户端
import { requestJson, BusinessError } from '@/shared/api/client';
// 各域 API
import { listAdminUsers } from '@/features/admin/api/admin.api';
import { listAdminSchedules } from '@/features/admin/api/schedule.api';
import { listWorkspaceScheduleRuns } from '@/features/workspace/api/schedule.api';
import { listChatSessions } from '@/features/chat/api/chat.api';
import { getWorkspaceShippingTask } from '@/features/chat/api/shipping.api';
import { getUserProfile } from '@/features/auth/api/user.api';
```
或通过 feature 入口 re-export:
```typescript
import { listAdminUsers } from '@/features/admin';
import { listWorkspaceScheduleRuns } from '@/features/workspace';
import { getWorkspaceShippingTask } from '@/features/chat';
```
### 12.3 兼容策略
- ~~`src/api/{client,admin,schedule,shippingNotice,chat,user}.ts` deprecated 转发~~ → **已删除**(2026-06-11)
- **新代码必须使用 feature / shared 路径**
- `src/api/kb.ts` 暂保留原位(KB redesign 后迁入 `features/kb/api/`)
### 12.4 构建验证
迁移后 `npm run build` 须通过。
### 12.5 下一步
- KB API 待 redesign 后迁入 `features/kb/api/kb.api.ts`
- ~~清理 deprecated `src/api/*` 转发~~ → 已完成(仅保留 `kb.ts`)
- `locales/` 按域拆分 → 见 §15
---
## 14. Phase 5 Shared 共享层迁移(已实现)
Phase 5 目标:将原 `src/` 根目录下的跨域代码迁入 `src/shared/`,与 `features/` 划清边界。
### 14.1 迁移对照
| 原路径 | 新路径 | 状态 |
|--------|--------|------|
| `src/composables/*` | `shared/composables/*` | ✅ |
| `src/components/*` | `shared/components/*` | ✅(含 `kb/` 子目录,待 KB redesign) |
| `src/layouts/*` | `shared/layouts/*` | ✅ |
| `src/utils/*` | `shared/utils/*` | ✅ |
| `src/styles/*` | `shared/styles/*` | ✅ |
| `style.css` 引用 | `@import './shared/styles/...'` | ✅ |
### 14.2 目录结构
```text
shared/
├── index.ts # 统一导出入口
├── api/client.ts
├── composables/ # useTheme、useMessage、useIsMobile 等
├── components/ # Dialog、LocaleToggle、kb/* 等
├── layouts/ # AppShell、ChatShell、MarketingShell 等
├── utils/ # auth、clipboard、wecom 等
├── styles/ # tokens.css、components-ds.css、utilities.css
├── constants/routes.ts
└── types/ # auth.types、schedule.types
```
### 14.3 新代码 import 规范
```typescript
import { useTheme, useMessage } from '@/shared/composables/useTheme';
import DeleteConfirmDialog from '@/shared/components/DeleteConfirmDialog.vue';
import ChatShell from '@/shared/layouts/ChatShell.vue';
import { getAuthHeaders } from '@/shared/utils/auth';
// 或按需从入口导入
import { useTheme, requestJson } from '@/shared';
```
### 14.4 兼容策略
- ~~`src/composables/`、`src/utils/`、`src/styles/` deprecated 转发~~ → **已删除**(2026-06-11)
- `src/components/`、`src/layouts/` **已删除**(全仓 import 已切换)
- **新代码必须使用 `@/shared/*` 路径**
- `shared/components/kb/*` 仍依赖 `@/api/kb`(KB redesign 后整体迁出)
### 14.5 构建验证
迁移后 `npm run build` 须通过。
### 14.6 下一步
- KB 组件/API 待 redesign 后迁入 `features/kb/`
- ~~清理 deprecated 转发~~ → 已完成
- `locales/` 按域拆分 → 见 §15
---
## 15. 架构对齐清理清单
> 目标:与 Vite/Vue 默认约定及本文档目标结构对齐。
> 状态更新时间:2026-06-11
### 15.1 已完成 ✅
| 项 | 说明 |
|----|------|
| 删除 `src/composables/` | 7 个 deprecated 转发已移除 |
| 删除 `src/utils/` | 6 个 deprecated 转发已移除 |
| 删除 `src/styles/` | 3 个 CSS 转发已移除 |
| 删除 `src/api/*`(除 kb) | client/admin/chat/user/schedule/shippingNotice 转发已移除 |
| 删除 `src/router/index.ts` | 全仓已改用 `@/app/router` |
| 修复 `api/kb.ts` | 改为引用 `@/shared/api/client` |
| 移除 `axios` 依赖 | 代码未使用,已从 `package.json` 删除 |
| `main.ts` / `App.vue` | 保留在 `src/` 根(见 §7.2 约定) |
### 15.2 i18n 按域拆分(进行中)
**现状**:`src/i18n.ts` 仍承载剩余内联 messages;`errors`、`auth`、`workspace`、`chat`、`admin` 域已外置。
**已完成 ✅**
| 域 | 路径 |
|----|------|
| `errors` | `locales/{en,zh-CN,zh-TW,th}/errors.json` |
| `auth` | `locales/{en,zh-CN,zh-TW,th}/auth.json` |
| `workspace` | `locales/{en,zh-CN,zh-TW,th}/workspace.json` |
| `chat` | `locales/{en,zh-CN,zh-TW,th}/chat.json` |
| `admin` | `locales/{en,zh-CN,zh-TW,th}/admin.json` |
| 合并入口 | `locales/index.ts` → `mergeExternalLocales()` |
`i18n.ts` 在 `createI18n` 前调用 `mergeExternalLocales(messages)`,四语言外置域与拆分前行为一致。
**目标结构**(剩余域):
```text
src/locales/
├── index.ts # createI18n + 合并 messages
├── zh-CN/
│ ├── common.json
│ ├── auth.json
│ ├── chat.json
│ ├── admin.json
│ ├── workspace.json
│ ├── kb.json
│ └── errors.json
├── zh-TW/ en/ th/ # 同上
```
**建议步骤**(可分 PR 执行):
1. ~~拆 `errors.*` → `errors.json`~~ ✅
2. ~~拆 `auth.*` → `auth.json`~~ ✅
3. ~~拆 `workspace.*` → `workspace.json`~~ ✅
4. ~~拆 `chat.*` → `chat.json`~~ ✅
5. ~~拆 `admin.*` → `admin.json`~~ ✅
6. 拆 `kb`(每域四语言 JSON;KB redesign 后可一并收口)
7. 每步 `npm run build` + 四语言 spot check
8. 全部外置后,`i18n.ts` 仅保留 `createI18n` 注册与 locale 默认值
**注意**:AGENTS.md 要求四语言同步;拆分时用脚本或 CI 校验 key 对齐。
### 15.3 待办:清理 `src/views/`(优先级:低,依赖 KB redesign)
| 文件 | 引用方 | 处理方式 |
|------|--------|----------|
| `KbWorkspaceView.vue` (~3000 行) | `/kb/workspace`、`workspace/knowledge-base` | KB redesign 后迁入 `features/kb/` |
| `ShippingNoticeView.vue` (~250 行) | `workspace/shipping-notice` | 迁入 `features/workspace/pages/` 或独立 feature |
**当前可做**:统一 import 为 `@/api/kb`、`@/shared/*`(已部分完成)。
### 15.4 待办:KB 域一次性收口(优先级:低,blocked on redesign)
- `src/api/kb.ts` → `features/kb/api/kb.api.ts`
- `shared/components/kb/*` → `features/kb/components/*`
- 路由 `/kb/workspace` 与 `/workspace/knowledge-base` 合并
### 15.5 可选优化(非必须)
| 项 | 说明 |
|----|------|
| `index.html` `lang="zh-CN"` | 主语言为中文,利于 SEO/无障碍 |
| `App.vue` 文件头注释 | 与项目注释规范一致 |
| `frontend/.env.development` | 若需纯前端多环境 API 地址,再用 `VITE_*` |
| Vite 8 beta → stable | 关注正式版发布后升级 |
### 15.6 推荐执行顺序
```text
✅ Phase A:删 deprecated 转发 + 去 axios
→ Phase B:i18n 拆 locales/(errors ✅ → auth ✅ → workspace ✅ → chat ✅ → admin ✅ → kb)
→ Phase C:ShippingNoticeView 迁入 workspace
→ Phase D:KB redesign + views/api/components 收口
```
---
- [项目上下文与技术栈](./project_context.md)
- [UI 设计系统](./ui/DESIGN_SYSTEM.md)
-259
View File
@@ -13,7 +13,6 @@
"@vue-office/docx": "^1.6.3",
"@vue-office/excel": "^1.7.14",
"@vue-office/pdf": "^1.6.5",
"axios": "^1.13.5",
"highlight.js": "^11.11.1",
"lucide-vue-next": "^0.575.0",
"marked": "^17.0.3",
@@ -862,12 +861,6 @@
"integrity": "sha512-PYjyFOLKQ9y57JvQ6QLo8dAgNqswh8M1RMJYdQduT6xbWSgK36P/Z/v+p888pM69jMMfS8Xd8F6I1kQ/I9HUGg==",
"license": "MIT"
},
"node_modules/asynckit": {
"version": "0.4.0",
"resolved": "https://mirrors.tencent.com/npm/asynckit/-/asynckit-0.4.0.tgz",
"integrity": "sha512-Oei9OH4tRh0YqU3GxhX79dM/mwVgvbZJaSNaRk+bshkj0S5cfHcgYakreBjrHwatXKbz+IoIdYLxrKim2MjW0Q==",
"license": "MIT"
},
"node_modules/autoprefixer": {
"version": "10.4.24",
"resolved": "https://mirrors.tencent.com/npm/autoprefixer/-/autoprefixer-10.4.24.tgz",
@@ -905,17 +898,6 @@
"postcss": "^8.1.0"
}
},
"node_modules/axios": {
"version": "1.13.5",
"resolved": "https://mirrors.tencent.com/npm/axios/-/axios-1.13.5.tgz",
"integrity": "sha512-cz4ur7Vb0xS4/KUN0tPWe44eqxrIu31me+fbang3ijiNscE129POzipJJA6zniq2C/Z6sJCjMimjS8Lc/GAs8Q==",
"license": "MIT",
"dependencies": {
"follow-redirects": "^1.15.11",
"form-data": "^4.0.5",
"proxy-from-env": "^1.1.0"
}
},
"node_modules/baseline-browser-mapping": {
"version": "2.10.0",
"resolved": "https://mirrors.tencent.com/npm/baseline-browser-mapping/-/baseline-browser-mapping-2.10.0.tgz",
@@ -996,19 +978,6 @@
"node": "^6 || ^7 || ^8 || ^9 || ^10 || ^11 || ^12 || >=13.7"
}
},
"node_modules/call-bind-apply-helpers": {
"version": "1.0.2",
"resolved": "https://mirrors.tencent.com/npm/call-bind-apply-helpers/-/call-bind-apply-helpers-1.0.2.tgz",
"integrity": "sha512-Sp1ablJ0ivDkSzjcaJdxEunN5/XvksFJ2sMBFfq6x0ryhQV/2b/KwFe21cMpmHtPOSij8K99/wSfoEuTObmuMQ==",
"license": "MIT",
"dependencies": {
"es-errors": "^1.3.0",
"function-bind": "^1.1.2"
},
"engines": {
"node": ">= 0.4"
}
},
"node_modules/camelcase-css": {
"version": "2.0.1",
"resolved": "https://mirrors.tencent.com/npm/camelcase-css/-/camelcase-css-2.0.1.tgz",
@@ -1097,18 +1066,6 @@
"node": ">=0.8"
}
},
"node_modules/combined-stream": {
"version": "1.0.8",
"resolved": "https://mirrors.tencent.com/npm/combined-stream/-/combined-stream-1.0.8.tgz",
"integrity": "sha512-FQN4MRfuJeHf7cBbBMJFXhKSDq+2kAArBlmRBvcvFE5BB1HZKXtSFASDhdlz9zOYwxh8lDdnvmMOe/+5cdoEdg==",
"license": "MIT",
"dependencies": {
"delayed-stream": "~1.0.0"
},
"engines": {
"node": ">= 0.8"
}
},
"node_modules/commander": {
"version": "4.1.1",
"resolved": "https://mirrors.tencent.com/npm/commander/-/commander-4.1.1.tgz",
@@ -1163,15 +1120,6 @@
"integrity": "sha512-z1HGKcYy2xA8AGQfwrn0PAy+PB7X/GSj3UVJW9qKyn43xWa+gl5nXmU4qqLMRzWVLFC8KusUX8T/0kCiOYpAIQ==",
"license": "MIT"
},
"node_modules/delayed-stream": {
"version": "1.0.0",
"resolved": "https://mirrors.tencent.com/npm/delayed-stream/-/delayed-stream-1.0.0.tgz",
"integrity": "sha512-ZySD7Nf91aLB0RxL4KGrKHBXl7Eds1DAmEdcoVawXnLD7SDhpNgtuII2aAkg7a7QS41jxPSZ17p4VdGnMHk3MQ==",
"license": "MIT",
"engines": {
"node": ">=0.4.0"
}
},
"node_modules/detect-libc": {
"version": "2.1.2",
"resolved": "https://mirrors.tencent.com/npm/detect-libc/-/detect-libc-2.1.2.tgz",
@@ -1194,20 +1142,6 @@
"integrity": "sha512-+HlytyjlPKnIG8XuRG8WvmBP8xs8P71y+SKKS6ZXWoEgLuePxtDoUEiH7WkdePWrQ5JBpE6aoVqfZfJUQkjXwA==",
"license": "MIT"
},
"node_modules/dunder-proto": {
"version": "1.0.1",
"resolved": "https://mirrors.tencent.com/npm/dunder-proto/-/dunder-proto-1.0.1.tgz",
"integrity": "sha512-KIN/nDJBQRcXw0MLVhZE9iQHmG68qAVIBg9CqmUYjmQIhgij9U5MFvrqkUL5FbtyyzZuOeOt0zdeRe4UY7ct+A==",
"license": "MIT",
"dependencies": {
"call-bind-apply-helpers": "^1.0.1",
"es-errors": "^1.3.0",
"gopd": "^1.2.0"
},
"engines": {
"node": ">= 0.4"
}
},
"node_modules/electron-to-chromium": {
"version": "1.5.302",
"resolved": "https://mirrors.tencent.com/npm/electron-to-chromium/-/electron-to-chromium-1.5.302.tgz",
@@ -1227,51 +1161,6 @@
"url": "https://github.com/fb55/entities?sponsor=1"
}
},
"node_modules/es-define-property": {
"version": "1.0.1",
"resolved": "https://mirrors.tencent.com/npm/es-define-property/-/es-define-property-1.0.1.tgz",
"integrity": "sha512-e3nRfgfUZ4rNGL232gUgX06QNyyez04KdjFrF+LTRoOXmrOgFKDg4BCdsjW8EnT69eqdYGmRpJwiPVYNrCaW3g==",
"license": "MIT",
"engines": {
"node": ">= 0.4"
}
},
"node_modules/es-errors": {
"version": "1.3.0",
"resolved": "https://mirrors.tencent.com/npm/es-errors/-/es-errors-1.3.0.tgz",
"integrity": "sha512-Zf5H2Kxt2xjTvbJvP2ZWLEICxA6j+hAmMzIlypy4xcBg1vKVnx89Wy0GbS+kf5cwCVFFzdCFh2XSCFNULS6csw==",
"license": "MIT",
"engines": {
"node": ">= 0.4"
}
},
"node_modules/es-object-atoms": {
"version": "1.1.1",
"resolved": "https://mirrors.tencent.com/npm/es-object-atoms/-/es-object-atoms-1.1.1.tgz",
"integrity": "sha512-FGgH2h8zKNim9ljj7dankFPcICIK9Cp5bm+c2gQSYePhpaG5+esrLODihIorn+Pe6FGJzWhXQotPv73jTaldXA==",
"license": "MIT",
"dependencies": {
"es-errors": "^1.3.0"
},
"engines": {
"node": ">= 0.4"
}
},
"node_modules/es-set-tostringtag": {
"version": "2.1.0",
"resolved": "https://mirrors.tencent.com/npm/es-set-tostringtag/-/es-set-tostringtag-2.1.0.tgz",
"integrity": "sha512-j6vWzfrGVfyXxge+O0x5sh6cvxAog0a/4Rdd2K36zCMV5eJ+/+tOAngRO8cODMNWbVRdVlmGZQL2YS3yR8bIUA==",
"license": "MIT",
"dependencies": {
"es-errors": "^1.3.0",
"get-intrinsic": "^1.2.6",
"has-tostringtag": "^1.0.2",
"hasown": "^2.0.2"
},
"engines": {
"node": ">= 0.4"
}
},
"node_modules/escalade": {
"version": "3.2.0",
"resolved": "https://mirrors.tencent.com/npm/escalade/-/escalade-3.2.0.tgz",
@@ -1354,42 +1243,6 @@
"node": ">=8"
}
},
"node_modules/follow-redirects": {
"version": "1.15.11",
"resolved": "https://mirrors.tencent.com/npm/follow-redirects/-/follow-redirects-1.15.11.tgz",
"integrity": "sha512-deG2P0JfjrTxl50XGCDyfI97ZGVCxIpfKYmfyrQ54n5FO/0gfIES8C/Psl6kWVDolizcaaxZJnTS0QSMxvnsBQ==",
"funding": [
{
"type": "individual",
"url": "https://github.com/sponsors/RubenVerborgh"
}
],
"license": "MIT",
"engines": {
"node": ">=4.0"
},
"peerDependenciesMeta": {
"debug": {
"optional": true
}
}
},
"node_modules/form-data": {
"version": "4.0.5",
"resolved": "https://mirrors.tencent.com/npm/form-data/-/form-data-4.0.5.tgz",
"integrity": "sha512-8RipRLol37bNs2bhoV67fiTEvdTrbMUYcFTiy3+wuuOnUog2QBHCZWXDRijWQfAkhBj2Uf5UnVaiWwA5vdd82w==",
"license": "MIT",
"dependencies": {
"asynckit": "^0.4.0",
"combined-stream": "^1.0.8",
"es-set-tostringtag": "^2.1.0",
"hasown": "^2.0.2",
"mime-types": "^2.1.12"
},
"engines": {
"node": ">= 6"
}
},
"node_modules/frac": {
"version": "1.1.2",
"resolved": "https://mirrors.tencent.com/npm/frac/-/frac-1.1.2.tgz",
@@ -1436,43 +1289,6 @@
"url": "https://github.com/sponsors/ljharb"
}
},
"node_modules/get-intrinsic": {
"version": "1.3.0",
"resolved": "https://mirrors.tencent.com/npm/get-intrinsic/-/get-intrinsic-1.3.0.tgz",
"integrity": "sha512-9fSjSaos/fRIVIp+xSJlE6lfwhES7LNtKaCBIamHsjr2na1BiABJPo0mOjjz8GJDURarmCPGqaiVg5mfjb98CQ==",
"license": "MIT",
"dependencies": {
"call-bind-apply-helpers": "^1.0.2",
"es-define-property": "^1.0.1",
"es-errors": "^1.3.0",
"es-object-atoms": "^1.1.1",
"function-bind": "^1.1.2",
"get-proto": "^1.0.1",
"gopd": "^1.2.0",
"has-symbols": "^1.1.0",
"hasown": "^2.0.2",
"math-intrinsics": "^1.1.0"
},
"engines": {
"node": ">= 0.4"
},
"funding": {
"url": "https://github.com/sponsors/ljharb"
}
},
"node_modules/get-proto": {
"version": "1.0.1",
"resolved": "https://mirrors.tencent.com/npm/get-proto/-/get-proto-1.0.1.tgz",
"integrity": "sha512-sTSfBjoXBp89JvIKIefqw7U2CCebsc74kiY6awiGogKtoSGbgjYE/G/+l9sF3MWFPNc9IcoOC4ODfKHfxFmp0g==",
"license": "MIT",
"dependencies": {
"dunder-proto": "^1.0.1",
"es-object-atoms": "^1.0.0"
},
"engines": {
"node": ">= 0.4"
}
},
"node_modules/glob-parent": {
"version": "6.0.2",
"resolved": "https://mirrors.tencent.com/npm/glob-parent/-/glob-parent-6.0.2.tgz",
@@ -1485,45 +1301,6 @@
"node": ">=10.13.0"
}
},
"node_modules/gopd": {
"version": "1.2.0",
"resolved": "https://mirrors.tencent.com/npm/gopd/-/gopd-1.2.0.tgz",
"integrity": "sha512-ZUKRh6/kUFoAiTAtTYPZJ3hw9wNxx+BIBOijnlG9PnrJsCcSjs1wyyD6vJpaYtgnzDrKYRSqf3OO6Rfa93xsRg==",
"license": "MIT",
"engines": {
"node": ">= 0.4"
},
"funding": {
"url": "https://github.com/sponsors/ljharb"
}
},
"node_modules/has-symbols": {
"version": "1.1.0",
"resolved": "https://mirrors.tencent.com/npm/has-symbols/-/has-symbols-1.1.0.tgz",
"integrity": "sha512-1cDNdwJ2Jaohmb3sg4OmKaMBwuC48sYni5HUw2DvsC8LjGTLK9h+eb1X6RyuOHe4hT0ULCW68iomhjUoKUqlPQ==",
"license": "MIT",
"engines": {
"node": ">= 0.4"
},
"funding": {
"url": "https://github.com/sponsors/ljharb"
}
},
"node_modules/has-tostringtag": {
"version": "1.0.2",
"resolved": "https://mirrors.tencent.com/npm/has-tostringtag/-/has-tostringtag-1.0.2.tgz",
"integrity": "sha512-NqADB8VjPFLM2V0VvHUewwwsw0ZWBaIdgo+ieHtK3hasLz4qeCRjYcqfB6AQrBggRKppKF8L52/VqdVsO47Dlw==",
"license": "MIT",
"dependencies": {
"has-symbols": "^1.0.3"
},
"engines": {
"node": ">= 0.4"
},
"funding": {
"url": "https://github.com/sponsors/ljharb"
}
},
"node_modules/hasown": {
"version": "2.0.2",
"resolved": "https://mirrors.tencent.com/npm/hasown/-/hasown-2.0.2.tgz",
@@ -1938,15 +1715,6 @@
"node": ">= 20"
}
},
"node_modules/math-intrinsics": {
"version": "1.1.0",
"resolved": "https://mirrors.tencent.com/npm/math-intrinsics/-/math-intrinsics-1.1.0.tgz",
"integrity": "sha512-/IXtbwEk5HTPyEwyKX6hGkYXxM9nbj64B+ilVJnC/R6B0pH5G4V3b0pVbL7DBj4tkhBAppbQUlf6F6Xl9LHu1g==",
"license": "MIT",
"engines": {
"node": ">= 0.4"
}
},
"node_modules/merge2": {
"version": "1.4.1",
"resolved": "https://mirrors.tencent.com/npm/merge2/-/merge2-1.4.1.tgz",
@@ -1981,27 +1749,6 @@
"url": "https://github.com/sponsors/jonschlinkert"
}
},
"node_modules/mime-db": {
"version": "1.52.0",
"resolved": "https://mirrors.tencent.com/npm/mime-db/-/mime-db-1.52.0.tgz",
"integrity": "sha512-sPU4uV7dYlvtWJxwwxHD0PuihVNiE7TyAbQ5SWxDCB9mUYvOgroQOwYQQOKPJ8CIbE+1ETVlOoK1UC2nU3gYvg==",
"license": "MIT",
"engines": {
"node": ">= 0.6"
}
},
"node_modules/mime-types": {
"version": "2.1.35",
"resolved": "https://mirrors.tencent.com/npm/mime-types/-/mime-types-2.1.35.tgz",
"integrity": "sha512-ZDY+bPm5zTTF+YpCrAU9nK0UgICYPT0QtT1NZWFv4s++TNkcgVaT0g6+4R2uI4MjQjzysHB1zxuWL50hzaeXiw==",
"license": "MIT",
"dependencies": {
"mime-db": "1.52.0"
},
"engines": {
"node": ">= 0.6"
}
},
"node_modules/mini-svg-data-uri": {
"version": "1.4.4",
"resolved": "https://mirrors.tencent.com/npm/mini-svg-data-uri/-/mini-svg-data-uri-1.4.4.tgz",
@@ -2321,12 +2068,6 @@
"integrity": "sha512-1NNCs6uurfkVbeXG4S8JFT9t19m45ICnif8zWLd5oPSZ50QnwMfK+H3jv408d4jw/7Bttv5axS5IiHoLaVNHeQ==",
"license": "MIT"
},
"node_modules/proxy-from-env": {
"version": "1.1.0",
"resolved": "https://mirrors.tencent.com/npm/proxy-from-env/-/proxy-from-env-1.1.0.tgz",
"integrity": "sha512-D+zkORCbA9f1tdWRK0RaCR3GPv50cMxcrz4X8k5LTSUD1Dkw47mKJEZQNunItRTkWwgtaUSo1RVFRIG9ZXiFYg==",
"license": "MIT"
},
"node_modules/queue-microtask": {
"version": "1.2.3",
"resolved": "https://mirrors.tencent.com/npm/queue-microtask/-/queue-microtask-1.2.3.tgz",
-1
View File
@@ -14,7 +14,6 @@
"@vue-office/docx": "^1.6.3",
"@vue-office/excel": "^1.7.14",
"@vue-office/pdf": "^1.6.5",
"axios": "^1.13.5",
"highlight.js": "^11.11.1",
"lucide-vue-next": "^0.575.0",
"marked": "^17.0.3",
+49
View File
@@ -0,0 +1,49 @@
/**
* scripts/extract-i18n-domain.mjs
* 从 i18n.ts 内联 messages 提取指定域至 locales/{locale}/{domain}.json 并移除内联键。
*
* Usage: node scripts/extract-i18n-domain.mjs <domain>
* Example: node scripts/extract-i18n-domain.mjs workspace
*/
import fs from 'node:fs';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
const domain = process.argv[2];
if (!domain) {
console.error('Usage: node scripts/extract-i18n-domain.mjs <domain>');
process.exit(1);
}
const __dirname = path.dirname(fileURLToPath(import.meta.url));
const root = path.resolve(__dirname, '..');
const i18nPath = path.resolve(root, 'src/i18n.ts');
const localesRoot = path.resolve(root, 'src/locales');
const locales = ['en', 'zh-CN', 'zh-TW', 'th'];
const content = fs.readFileSync(i18nPath, 'utf8');
const start = content.indexOf('const messages = {') + 'const messages = '.length;
const end = content.indexOf('const i18n = createI18n');
const messagesStr = content.slice(start, end).trim().replace(/,\s*$/, '');
const messages = new Function(`return ${messagesStr}`)();
for (const locale of locales) {
const block = messages[locale]?.[domain];
if (!block) {
console.error(`Missing messages.${locale}.${domain}`);
process.exit(1);
}
const outDir = path.join(localesRoot, locale);
fs.mkdirSync(outDir, { recursive: true });
const outPath = path.join(outDir, `${domain}.json`);
fs.writeFileSync(outPath, `${JSON.stringify(block, null, 2)}\n`, 'utf8');
delete messages[locale][domain];
console.log(`Wrote ${path.relative(root, outPath)}`);
}
const header = content.slice(0, content.indexOf('const messages = {'));
const footer = content.slice(end);
const serialized = JSON.stringify(messages, null, 2);
const newContent = `${header}const messages = ${serialized};\n\n${footer}`;
fs.writeFileSync(i18nPath, newContent, 'utf8');
console.log(`Stripped ${domain} from i18n.ts`);
+30
View File
@@ -0,0 +1,30 @@
/**
* scripts/strip-i18n-auth.mjs
* 从 i18n.ts 内联 messages 中移除已外置至 locales 下 auth.json 的键。
*/
import fs from 'node:fs';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
const __dirname = path.dirname(fileURLToPath(import.meta.url));
const i18nPath = path.resolve(__dirname, '../src/i18n.ts');
const content = fs.readFileSync(i18nPath, 'utf8');
const start = content.indexOf('const messages = {') + 'const messages = '.length;
const end = content.indexOf('const i18n = createI18n');
const messagesStr = content.slice(start, end).trim().replace(/,\s*$/, '');
const messages = new Function(`return ${messagesStr}`)();
for (const loc of ['en', 'zh-CN', 'zh-TW', 'th']) {
delete messages[loc].title;
delete messages[loc].login;
delete messages[loc].landing;
delete messages[loc].register;
}
const header = content.slice(0, content.indexOf('const messages = {'));
const footer = content.slice(end);
const serialized = JSON.stringify(messages, null, 2);
const newContent = `${header}const messages = ${serialized};\n\n${footer}`;
fs.writeFileSync(i18nPath, newContent, 'utf8');
console.log('Stripped auth keys from i18n.ts');
+4 -4
View File
@@ -2,11 +2,11 @@
<script setup lang="ts">
import { useI18n } from 'vue-i18n';
import { watch, onMounted, onBeforeUnmount } from 'vue';
import { useTheme } from './composables/useTheme';
import LevelMessageDialog from './components/LevelMessageDialog.vue';
import { useGlobalMessageDialog } from './composables/useGlobalMessageDialog';
import { useTheme } from '@/shared/composables/useTheme';
import LevelMessageDialog from '@/shared/components/LevelMessageDialog.vue';
import { useGlobalMessageDialog } from '@/shared/composables/useGlobalMessageDialog';
import { useRouter } from 'vue-router';
import { getAuthHeaders, logoutAuth } from './utils/auth';
import { getAuthHeaders, logoutAuth } from '@/shared/utils/auth';
import { isPublicPath } from '@/shared/constants/routes';
const router = useRouter();
-4
View File
@@ -1,4 +0,0 @@
/**
* @deprecated 请使用 @/features/chat/api/chat.api
*/
export * from '@/features/chat/api/chat.api';
-147
View File
@@ -1,147 +0,0 @@
/**
* frontend/src/api/client.ts
* 用途:封装前端统一 API 访问与响应解析逻辑。
* 说明:
* 1. 支持两种返回格式:旧格式(直接返回数据)与新格式({ success, data/error })。
* 2. requestJson 统一处理成功/失败分支,并在失败时抛出 BusinessError。
* 3. BusinessError 提供 code/details/requestId,方便页面层做多语言与精细化提示。
*/
import { getAuthHeaders } from '../utils/auth';
import i18n from '../i18n';
export interface ApiSuccessEnvelope<T> {
success: true;
data: T;
request_id?: string;
timestamp?: string;
}
export interface ApiErrorBody {
code?: string;
message?: string;
details?: Record<string, any>;
retryable?: boolean;
}
export interface ApiErrorEnvelope {
success: false;
error?: ApiErrorBody;
request_id?: string;
timestamp?: string;
}
export class BusinessError extends Error {
code: string;
details: Record<string, any>;
requestId?: string;
status?: number;
constructor(args: { message: string; code?: string; details?: Record<string, any>; requestId?: string; status?: number }) {
super(args.message);
this.name = 'BusinessError';
this.code = args.code || 'SYSTEM.UNKNOWN';
this.details = args.details || {};
this.requestId = args.requestId;
this.status = args.status;
}
}
function resolveLocalizedErrorMessage(code?: string, fallbackMessage?: string): string {
const normalizedCode = code ? code.replace(/\./g, '_') : '';
const key = normalizedCode ? `errors.codes.${normalizedCode}` : '';
const fallback = String(fallbackMessage || '').trim();
const isGenericFallback = (msg: string) => {
const v = msg.trim().toLowerCase();
if (!v) return true;
if (v === 'invalid request parameters' || v === 'invalid request parameters.') return true;
if (v === 'request failed' || v === 'request failed.') return true;
if (v.startsWith('http ')) return true;
return false;
};
if (key && i18n.global.te(key)) {
const localized = String(i18n.global.t(key));
if (normalizedCode === 'VALIDATION_INVALID_PARAM' && fallback && !isGenericFallback(fallback) && fallback !== localized) {
return `${localized} ${fallback}`;
}
if (
normalizedCode === 'AUTH_FORBIDDEN'
&& fallback
&& !isGenericFallback(fallback)
&& fallback.toLowerCase() !== 'forbidden'
&& fallback !== localized
) {
return fallback;
}
return localized;
}
if (fallback) return fallback;
if (i18n.global.te('errors.generic')) {
return String(i18n.global.t('errors.generic'));
}
return code || 'Request failed';
}
export const isEnvelope = (payload: any): payload is ApiSuccessEnvelope<any> | ApiErrorEnvelope => {
return !!payload && typeof payload === 'object' && typeof payload.success === 'boolean';
};
function pickLegacyErrorMessage(payload: any): string | undefined {
if (!payload) return undefined;
if (typeof payload.error === 'string' && payload.error.trim()) return payload.error;
if (typeof payload.message === 'string' && payload.message.trim()) return payload.message;
return undefined;
}
export async function requestJson<T>(url: string, init?: RequestInit): Promise<T> {
const headers = new Headers(init?.headers || {});
const authHeaders = getAuthHeaders();
Object.entries(authHeaders).forEach(([k, v]) => headers.set(k, v as string));
const res = await fetch(url, { ...init, headers });
let data: any = null;
try {
data = await res.json();
} catch {
if (!res.ok) {
throw new BusinessError({
message: `HTTP ${res.status}`,
code: 'SYSTEM.HTTP_ERROR',
status: res.status,
});
}
return null as T;
}
if (!res.ok) {
if (isEnvelope(data) && data.success === false) {
throw new BusinessError({
message: resolveLocalizedErrorMessage(data.error?.code, data.error?.message || `HTTP ${res.status}`),
code: data.error?.code,
details: data.error?.details,
requestId: data.request_id,
status: res.status,
});
}
throw new BusinessError({
message: resolveLocalizedErrorMessage(data?.code, pickLegacyErrorMessage(data) || `HTTP ${res.status}`),
code: data?.code || data?.error_code || 'SYSTEM.HTTP_ERROR',
details: data?.details || {},
requestId: data?.request_id,
status: res.status,
});
}
if (isEnvelope(data)) {
if (data.success === true) return data.data as T;
throw new BusinessError({
message: resolveLocalizedErrorMessage(data.error?.code, data.error?.message || 'Request failed'),
code: data.error?.code,
details: data.error?.details,
requestId: data.request_id,
status: res.status,
});
}
return data as T;
}
+6 -2
View File
@@ -1,5 +1,9 @@
import { getAuthHeaders } from '../utils/auth';
import { BusinessError, requestJson } from './client';
/**
* src/api/kb.ts
* 知识库 HTTP API(暂缓迁入 features/kb,KB redesign 后迁移)。
*/
import { getAuthHeaders } from '@/shared/utils/auth';
import { BusinessError, requestJson } from '@/shared/api/client';
export interface KbGroup {
id: number;
+2 -2
View File
@@ -1,5 +1,5 @@
import { requestJson } from './client';
import { getAuthHeaders } from '../utils/auth';
import { requestJson } from '@/shared/api/client';
import { getAuthHeaders } from '@/shared/utils/auth';
export interface ToolRunProgress {
run_id: number;
-2
View File
@@ -1,2 +0,0 @@
/** @deprecated 请改用 `@/features/auth/api/user.api` */
export * from '@/features/auth/api/user.api';
@@ -1,6 +1,10 @@
import { getAuthHeaders } from '../utils/auth';
import { requestJson } from './client';
import type { AdminDashboardBadges, AdminDashboardSummary } from '@/features/admin/types/dashboard.types';
/**
* features/admin/api/admin.api.ts
* 管理后台 HTTP API:用户、部门、Agent、权限、报表、企业微信、公告等。
*/
import { getAuthHeaders } from '@/shared/utils/auth';
import { requestJson } from '@/shared/api/client';
import type { AdminDashboardBadges, AdminDashboardSummary } from '../types/dashboard.types';
const auth = () => ({ headers: getAuthHeaders() });
const jsonAuth = () => ({ headers: { 'Content-Type': 'application/json', ...getAuthHeaders() } });
@@ -104,7 +108,7 @@ export const batchUpdateAdminPermissions = (payload: Record<string, unknown>) =>
export const importAdminPermissions = (formData: FormData) =>
requestJson('/api/admin/permissions/import', { method: 'POST', ...auth(), body: formData });
// Dashboard(轻量聚合,避免拉全表)
// Dashboard
/** 仪表盘四张卡片:Agent 数、用户数、对话总数、平均评分 */
export const getAdminDashboardSummary = () =>
requestJson<AdminDashboardSummary>('/api/admin/dashboard/summary', auth());
@@ -1,82 +1,17 @@
import { getAuthHeaders } from '../utils/auth';
import { requestJson } from './client';
export interface ScheduleTask {
id: number;
schedule_no: string;
name: string;
schedule_type: string;
owner_user_id: number;
owner_username?: string | null;
cron_expr: string;
wait_seconds: number;
dify_agent_id?: number | null;
platform_api_path?: string | null;
data_source_type?: string;
kb_sync_enabled?: boolean;
kb_group_id?: number | null;
notify_user_ids_json: number[];
notify_enabled: boolean;
enabled: boolean;
next_run_at?: string | null;
last_run_at?: string | null;
last_status?: string | null;
created_at?: string | null;
updated_at?: string | null;
}
export interface ScheduleRun {
id: number;
run_no: string;
schedule_task_id: number;
schedule_name?: string | null;
trigger_type: string;
started_at?: string | null;
finished_at?: string | null;
duration_ms: number;
status: string;
total_count: number;
success_count: number;
failed_count: number;
api_request_json?: Record<string, any> | null;
api_response_json?: Record<string, any> | null;
response_summary_json?: Record<string, any> | null;
step_logs?: StepLog[] | null;
dify_execution_snapshot?: DifyExecutionSnapshot | null;
error_message?: string | null;
excel_file_name?: string | null;
excel_file_size?: number | null;
kb_sync_status?: string | null;
kb_group_id?: number | null;
kb_document_id?: number | null;
kb_document_version_id?: number | null;
kb_sync_job_id?: number | null;
kb_sync_error?: string | null;
wecom_notified: boolean;
wecom_notified_at?: string | null;
wecom_notify_error?: string | null;
created_at?: string | null;
}
export interface StepLog {
step: string;
status: string;
started_at?: string;
finished_at?: string;
duration_ms?: number;
row_id?: string;
detail?: Record<string, any>;
}
export interface DifyExecutionSnapshot {
dify_enabled?: boolean;
dify_agent_id?: number | null;
dify_agent_name?: string | null;
dify_app_id?: string | null;
dify_system_prompt?: string;
captured_at?: string;
}
/**
* features/admin/api/schedule.api.ts
* 管理后台定时任务 HTTP API:任务 CRUD、配置、测试执行、运行记录。
*/
import { getAuthHeaders } from '@/shared/utils/auth';
import { requestJson } from '@/shared/api/client';
import type {
DifyExecutionSnapshot,
ScheduleRun,
ScheduleTask,
StepLog,
TestScheduleRunResult,
TestScheduleSqlResult,
} from '@/shared/types/schedule.types';
async function getJson<T>(url: string): Promise<T> {
return requestJson<T>(url, { headers: getAuthHeaders() });
@@ -108,15 +43,6 @@ export const updateAdminScheduleTaskConfig = (taskId: number, payload: Record<st
body: JSON.stringify(payload),
});
export interface TestScheduleSqlResult {
total: number;
showing: number;
limit: number;
sql: string;
columns: string[];
rows: Record<string, any>[];
}
export const testAdminScheduleSql = (taskId: number, payload: { fetch_where_conditions?: string; fetch_order_by?: string; limit?: number }) =>
requestJson<TestScheduleSqlResult>(`/api/admin/schedule-config/${taskId}/test-sql`, {
method: 'POST',
@@ -124,25 +50,6 @@ export const testAdminScheduleSql = (taskId: number, payload: { fetch_where_cond
body: JSON.stringify(payload),
});
export interface TestScheduleRunResult {
run_no: string;
run_id: number;
sql: string;
limit: number;
total_count: number;
success_count: number;
failed_count: number;
skipped_count: number;
details: Record<string, any>[];
errors: string[];
step_logs: StepLog[];
dify_agent_id: number | null;
dify_execution_snapshot?: DifyExecutionSnapshot | null;
kb_sync_status?: string | null;
kb_sync_error?: string | null;
kb_document_id?: number | null;
}
export const testAdminScheduleRun = (
taskId: number,
payload: {
@@ -177,10 +84,13 @@ export const deleteAdminSchedule = (id: number) =>
method: 'DELETE',
headers: getAuthHeaders(),
});
export const runAdminSchedule = (id: number) =>
requestJson(`/api/admin/schedules/${id}/run`, { method: 'POST', headers: getAuthHeaders() });
export const toggleAdminSchedule = (id: number, enabled: boolean) =>
requestJson(`/api/admin/schedules/${id}/${enabled ? 'enable' : 'disable'}`, { method: 'POST', headers: getAuthHeaders() });
export const listAdminScheduleRuns = (taskId: number, params?: { status?: string; started_after?: string; started_before?: string }) => {
const sp = new URLSearchParams();
if (params?.status) sp.set('status', params.status);
@@ -189,15 +99,7 @@ export const listAdminScheduleRuns = (taskId: number, params?: { status?: string
const qs = sp.toString();
return getJson<ScheduleRun[]>(`/api/admin/schedules/${taskId}/runs${qs ? '?' + qs : ''}`);
};
export const adminRunExcelUrl = (runId: number) => `/api/admin/schedule-runs/${runId}/excel`;
export const listWorkspaceScheduleRuns = (params?: { status?: string; schedule_name?: string; started_after?: string; started_before?: string }) => {
const sp = new URLSearchParams();
if (params?.status) sp.set('status', params.status);
if (params?.schedule_name) sp.set('schedule_name', params.schedule_name);
if (params?.started_after) sp.set('started_after', params.started_after);
if (params?.started_before) sp.set('started_before', params.started_before);
const qs = sp.toString();
return getJson<ScheduleRun[]>(`/api/workspace/schedule-runs${qs ? '?' + qs : ''}`);
};
export const workspaceRunExcelUrl = (runId: number) => `/api/workspace/schedule-runs/${runId}/excel`;
export type { DifyExecutionSnapshot, ScheduleRun, ScheduleTask, StepLog, TestScheduleRunResult, TestScheduleSqlResult };
+2
View File
@@ -8,3 +8,5 @@ export { default as AdminLayout } from './views/AdminLayout.vue';
export { useAdminNavStore } from './stores/admin-nav.store';
export { adminModulePath, ADMIN_MODULE_METAS } from './constants/modules';
export type { AdminModuleId } from './types/admin.types';
export * from './api/admin.api';
export * from './api/schedule.api';
@@ -1,4 +1,4 @@
/**
/**
* features/admin/modules/agents/AgentsPage.vue
*
* Agent 管理独立页面(Phase 1 首个拆分模块)。
@@ -9,7 +9,7 @@
import { onMounted } from 'vue';
import { useI18n } from 'vue-i18n';
import { Bot, Plus, Trash2, Users } from 'lucide-vue-next';
import DeleteConfirmDialog from '@/components/DeleteConfirmDialog.vue';
import DeleteConfirmDialog from '@/shared/components/DeleteConfirmDialog.vue';
import AgentPermissionModal from './components/AgentPermissionModal.vue';
import AgentTestModal from './components/AgentTestModal.vue';
import { useAgentsAdmin } from './composables/useAgentsAdmin';
@@ -1,4 +1,4 @@
/**
/**
* features/admin/modules/agents/composables/useAgentsAdmin.ts
*
* Agent 管理模块的业务逻辑:列表 CRUD、连通性测试、权限分配。
@@ -15,8 +15,8 @@ import {
saveAdminAgentPermissions,
testAdminAgent,
updateAdminAgent,
} from '@/api/admin';
import { useMessage } from '@/composables/useMessage';
} from '@/features/admin/api/admin.api';
import { useMessage } from '@/shared/composables/useMessage';
import type { AdminUserRow } from '@/features/admin/types/admin.types';
import type { AgentFormState, AgentRow, AgentSuggestedQuestionItem, AgentTestResult } from '@/features/admin/types/agent.types';
import { createEmptyAgentForm } from '@/features/admin/types/agent.types';
@@ -1,4 +1,4 @@
/**
/**
* features/admin/modules/announcements/AnnouncementsPage.vue
* 公告管理独立页面。路由:/admin/announcements
*/
@@ -6,7 +6,7 @@
import { onMounted } from 'vue';
import { useI18n } from 'vue-i18n';
import { Trash2 } from 'lucide-vue-next';
import DeleteConfirmDialog from '@/components/DeleteConfirmDialog.vue';
import DeleteConfirmDialog from '@/shared/components/DeleteConfirmDialog.vue';
import { useAnnouncementsAdmin } from './composables/useAnnouncementsAdmin';
const { t } = useI18n();
@@ -1,11 +1,11 @@
/**
/**
* features/admin/modules/announcements/composables/useAnnouncementsAdmin.ts
* 公告管理:列表、发布、删除。
*/
import { ref } from 'vue';
import { useI18n } from 'vue-i18n';
import { createAnnouncement, deleteAnnouncement, listAnnouncements } from '@/api/admin';
import { useMessage } from '@/composables/useMessage';
import { createAnnouncement, deleteAnnouncement, listAnnouncements } from '@/features/admin/api/admin.api';
import { useMessage } from '@/shared/composables/useMessage';
import type { AdminAnnouncementRow } from '@/features/admin/types/admin.types';
import {
createEmptyAnnouncementForm,
@@ -1,4 +1,4 @@
/**
/**
* features/admin/modules/approvals/ApprovalsPage.vue
* 用户注册审批独立页面。路由:/admin/approvals
*/
@@ -6,7 +6,7 @@
import { onMounted } from 'vue';
import { useI18n } from 'vue-i18n';
import { ShieldCheck, Trash2 } from 'lucide-vue-next';
import DeleteConfirmDialog from '@/components/DeleteConfirmDialog.vue';
import DeleteConfirmDialog from '@/shared/components/DeleteConfirmDialog.vue';
import { useApprovalsAdmin } from './composables/useApprovalsAdmin';
const { t } = useI18n();
@@ -1,11 +1,11 @@
/**
/**
* features/admin/modules/approvals/composables/useApprovalsAdmin.ts
* 用户注册审批:待审列表、通过、拒绝。
*/
import { computed, ref } from 'vue';
import { useI18n } from 'vue-i18n';
import { approveAdminUser, listAdminUsers, rejectAdminUser } from '@/api/admin';
import { useMessage } from '@/composables/useMessage';
import { approveAdminUser, listAdminUsers, rejectAdminUser } from '@/features/admin/api/admin.api';
import { useMessage } from '@/shared/composables/useMessage';
import { useAdminNavBadges } from '@/features/admin/composables/useAdminNavBadges';
import type { AdminUserRow } from '@/features/admin/types/admin.types';
@@ -1,9 +1,9 @@
/**
/**
* features/admin/modules/dashboard/composables/useDashboardAdmin.ts
* 仪表盘概览:单次 summary 接口获取四个指标。
*/
import { ref } from 'vue';
import { getAdminDashboardSummary } from '@/api/admin';
import { getAdminDashboardSummary } from '@/features/admin/api/admin.api';
export function useDashboardAdmin() {
const agentCount = ref(0);
@@ -1,4 +1,4 @@
/**
/**
* features/admin/modules/departments/DepartmentsPage.vue
* 部门管理独立页面。路由:/admin/departments
*/
@@ -6,7 +6,7 @@
import { onMounted } from 'vue';
import { useI18n } from 'vue-i18n';
import { Edit, Trash2 } from 'lucide-vue-next';
import DeleteConfirmDialog from '@/components/DeleteConfirmDialog.vue';
import DeleteConfirmDialog from '@/shared/components/DeleteConfirmDialog.vue';
import { useDepartmentsAdmin } from './composables/useDepartmentsAdmin';
const { t } = useI18n();
@@ -1,4 +1,4 @@
/**
/**
* features/admin/modules/departments/composables/useDepartmentsAdmin.ts
* 部门管理:列表、创建、编辑、删除。
*/
@@ -9,8 +9,8 @@ import {
deleteAdminDepartment,
listAdminDepartments,
updateAdminDepartment,
} from '@/api/admin';
import { useMessage } from '@/composables/useMessage';
} from '@/features/admin/api/admin.api';
import { useMessage } from '@/shared/composables/useMessage';
import type { AdminDepartmentRow } from '@/features/admin/types/admin.types';
import {
createEmptyDepartmentForm,
@@ -1,9 +1,9 @@
/**
/**
* features/admin/modules/knowledge-base/KnowledgeBasePage.vue
* 知识库管理独立页面。路由:/admin/knowledge-base
*/
<script setup lang="ts">
import KbAdminPanel from '@/components/kb/KbAdminPanel.vue';
import KbAdminPanel from '@/shared/components/kb/KbAdminPanel.vue';
</script>
<template>
@@ -1,4 +1,4 @@
/**
/**
* features/admin/modules/permissions/composables/usePermissionsAdmin.ts
* 用户权限矩阵:筛选、单格切换、批量分配、CSV 导入导出。
*/
@@ -11,8 +11,8 @@ import {
listAdminAgents,
listAdminUsers,
updateAdminUserPermissions,
} from '@/api/admin';
import { useMessage } from '@/composables/useMessage';
} from '@/features/admin/api/admin.api';
import { useMessage } from '@/shared/composables/useMessage';
import type { AdminAgentOption, AdminUserRow } from '@/features/admin/types/admin.types';
import {
createEmptyPermissionFilters,
@@ -1,8 +1,8 @@
<script setup lang="ts">
<script setup lang="ts">
import { ref, onMounted, computed } from 'vue';
import { useI18n } from 'vue-i18n';
import { Plus, Trash2, Edit2, Play, FileText, Image as ImageIcon } from 'lucide-vue-next';
import { listAdminAgents, listAdminAgentGuides, createAdminAgentGuide, updateAdminAgentGuide, deleteAdminAgentGuide, uploadAdminAgentGuideFile } from '@/api/admin';
import { listAdminAgents, listAdminAgentGuides, createAdminAgentGuide, updateAdminAgentGuide, deleteAdminAgentGuide, uploadAdminAgentGuideFile } from '@/features/admin/api/admin.api';
const { t } = useI18n();
@@ -1,4 +1,4 @@
/**
/**
* features/admin/modules/questions/QuestionsPage.vue
* 常用问题管理独立页面。路由:/admin/questions
*/
@@ -6,7 +6,7 @@
import { onMounted } from 'vue';
import { useI18n } from 'vue-i18n';
import { Edit, Trash2 } from 'lucide-vue-next';
import DeleteConfirmDialog from '@/components/DeleteConfirmDialog.vue';
import DeleteConfirmDialog from '@/shared/components/DeleteConfirmDialog.vue';
import { useQuestionsAdmin } from './composables/useQuestionsAdmin';
const { t } = useI18n();
@@ -1,4 +1,4 @@
/**
/**
* features/admin/modules/questions/composables/useQuestionsAdmin.ts
* 常用问题管理:列表、创建、编辑、删除。
*/
@@ -9,8 +9,8 @@ import {
listAdminAgents,
listAdminQuickQuestions,
saveAdminQuickQuestion,
} from '@/api/admin';
import { useMessage } from '@/composables/useMessage';
} from '@/features/admin/api/admin.api';
import { useMessage } from '@/shared/composables/useMessage';
import type { AdminAgentOption } from '@/features/admin/types/admin.types';
import {
createEmptyQuestionForm,
@@ -1,4 +1,4 @@
/**
/**
* features/admin/modules/reports/ReportsPage.vue
* 管理后台报表独立页面。路由:/admin/reports/:table?
*/
@@ -6,7 +6,7 @@
import { onMounted } from 'vue';
import { useI18n } from 'vue-i18n';
import { BarChart2, Download, Settings2 } from 'lucide-vue-next';
import DeleteConfirmDialog from '@/components/DeleteConfirmDialog.vue';
import DeleteConfirmDialog from '@/shared/components/DeleteConfirmDialog.vue';
import { useReportsAdmin } from './composables/useReportsAdmin';
const { t } = useI18n();
@@ -1,4 +1,4 @@
/**
/**
* features/admin/modules/reports/composables/useReportsAdmin.ts
* 管理后台报表:多表浏览、筛选、排序、chat_logs 批量删除与用量图表。
*/
@@ -11,9 +11,9 @@ import {
getAdminReportTable,
getAdminReportTableCount,
getAdminUsageReport,
} from '@/api/admin';
import { loadReportLayoutPref, saveReportLayoutPref } from '@/composables/useReportLayoutStorage';
import { useMessage } from '@/composables/useMessage';
} from '@/features/admin/api/admin.api';
import { loadReportLayoutPref, saveReportLayoutPref } from '@/shared/composables/useReportLayoutStorage';
import { useMessage } from '@/shared/composables/useMessage';
import { ADMIN_REPORT_TABLES } from '@/features/admin/constants/modules';
import type {
ChatLogsLayoutPref,
@@ -1,4 +1,4 @@
/**
/**
* features/admin/modules/requests/composables/useRequestsAdmin.ts
* 权限申请管理:列表、通过、拒绝。
*/
@@ -8,8 +8,8 @@ import {
approveAdminPermissionRequest,
listAdminPermissionRequests,
rejectAdminPermissionRequest,
} from '@/api/admin';
import { useMessage } from '@/composables/useMessage';
} from '@/features/admin/api/admin.api';
import { useMessage } from '@/shared/composables/useMessage';
import { useAdminNavBadges } from '@/features/admin/composables/useAdminNavBadges';
import type { AdminPermissionRequestRow } from '@/features/admin/types/request.types';
@@ -1,4 +1,4 @@
/**
/**
* features/admin/modules/schedules/SchedulesPage.vue
* 定时任务管理独立页面。路由:/admin/schedules
*/
@@ -8,7 +8,7 @@ import {
ArrowLeft, ChevronDown, ChevronUp, Download, Edit3, Eye, FlaskConical,
Plus, Power, PowerOff, RefreshCw, Rocket, Settings2, Trash2,
} from 'lucide-vue-next';
import DeleteConfirmDialog from '@/components/DeleteConfirmDialog.vue';
import DeleteConfirmDialog from '@/shared/components/DeleteConfirmDialog.vue';
import { useSchedulesAdmin } from './composables/useSchedulesAdmin';
const admin = useSchedulesAdmin();
@@ -1,10 +1,10 @@
/**
/**
* features/admin/modules/schedules/composables/useSchedulesAdmin.ts
* 定时任务管理:概览、工作台、创建/编辑、试运行。
*/
import { computed, ref, watch } from 'vue';
import { useI18n } from 'vue-i18n';
import { listAdminAgents, listAdminUsers } from '@/api/admin';
import { listAdminAgents, listAdminUsers } from '@/features/admin/api/admin.api';
import { getKbGroups, type KbGroup } from '@/api/kb';
import {
createAdminSchedule,
@@ -21,9 +21,9 @@ import {
type ScheduleRun,
type ScheduleTask,
type TestScheduleRunResult,
} from '@/api/schedule';
import { useMessage } from '@/composables/useMessage';
import { getAuthHeaders } from '@/utils/auth';
} from '@/features/admin/api/schedule.api';
import { useMessage } from '@/shared/composables/useMessage';
import { getAuthHeaders } from '@/shared/utils/auth';
import type { AdminAgentOption, AdminUserRow } from '@/features/admin/types/admin.types';
export function useSchedulesAdmin() {
@@ -1,4 +1,4 @@
/**
/**
* features/admin/modules/users/UsersPage.vue
* 用户管理独立页面。路由:/admin/users
*/
@@ -6,7 +6,7 @@
import { onMounted } from 'vue';
import { useI18n } from 'vue-i18n';
import { Edit, Plus, Trash2, Users } from 'lucide-vue-next';
import DeleteConfirmDialog from '@/components/DeleteConfirmDialog.vue';
import DeleteConfirmDialog from '@/shared/components/DeleteConfirmDialog.vue';
import BatchEditUserModal from './components/BatchEditUserModal.vue';
import BatchPermissionModal from './components/BatchPermissionModal.vue';
import UserFormModal from './components/UserFormModal.vue';
@@ -1,4 +1,4 @@
/**
/**
* features/admin/modules/users/composables/useUsersAdmin.ts
* 用户管理模块业务逻辑:CRUD、筛选、批量操作。
*/
@@ -14,8 +14,8 @@ import {
listAdminDepartments,
listAdminUsers,
updateAdminUser,
} from '@/api/admin';
import { useMessage } from '@/composables/useMessage';
} from '@/features/admin/api/admin.api';
import { useMessage } from '@/shared/composables/useMessage';
import type { AdminAgentOption, AdminDepartmentRow, AdminUserRow } from '@/features/admin/types/admin.types';
import {
createEmptyUserFilters,
@@ -1,4 +1,4 @@
/**
/**
* features/admin/modules/wecom/WecomPage.vue
* 企业微信管理独立页面。路由:/admin/wecom
*/
@@ -6,7 +6,7 @@
import { onMounted } from 'vue';
import { useI18n } from 'vue-i18n';
import { CircleHelp, Download, Link2, RefreshCw, Unlink2 } from 'lucide-vue-next';
import DeleteConfirmDialog from '@/components/DeleteConfirmDialog.vue';
import DeleteConfirmDialog from '@/shared/components/DeleteConfirmDialog.vue';
import { useWecomAdmin } from './composables/useWecomAdmin';
const { t } = useI18n();
@@ -1,4 +1,4 @@
/**
/**
* features/admin/modules/wecom/composables/useWecomAdmin.ts
* 企业微信:绑定、系统配置、通知、登录审计。
*/
@@ -17,8 +17,8 @@ import {
saveAdminWecomNotifySettings,
saveAdminWecomSystemSettings,
unbindAdminWecomUser,
} from '@/api/admin';
import { useMessage } from '@/composables/useMessage';
} from '@/features/admin/api/admin.api';
import { useMessage } from '@/shared/composables/useMessage';
import type { AdminUserRow } from '@/features/admin/types/admin.types';
import {
createDefaultWecomSystemSettings,
@@ -29,7 +29,7 @@ import {
type WecomNotifySettings,
type WecomSystemSettings,
} from '@/features/admin/types/wecom.types';
import { buildWecomAuditMeta, formatWecomAuditReason } from '@/utils/wecom';
import { buildWecomAuditMeta, formatWecomAuditReason } from '@/shared/utils/wecom';
export function useWecomAdmin() {
const { t } = useI18n();
@@ -1,4 +1,4 @@
/**
/**
* features/admin/stores/admin-nav.store.ts
* 管理后台导航 UI 状态(侧栏折叠、报表展开、角标)。
*
@@ -7,7 +7,7 @@
*/
import { defineStore } from 'pinia';
import { ref } from 'vue';
import { getAdminDashboardBadges } from '@/api/admin';
import { getAdminDashboardBadges } from '@/features/admin/api/admin.api';
import type { AdminModuleId } from '../types/admin.types';
/** 角标缓存有效期(毫秒):此时间内 ensureBadges 直接复用内存中的计数 */
@@ -1,4 +1,4 @@
/**
/**
* features/admin/views/AdminLayout.vue
* 管理后台壳层:顶栏 + AdminNav + 子路由出口。
* 角标仅在 Layout 首次挂载时 ensureBadges(store 内 60s TTL 缓存)。
@@ -8,7 +8,7 @@ import { onMounted } from 'vue';
import { ArrowLeft } from 'lucide-vue-next';
import { useI18n } from 'vue-i18n';
import { useRouter } from 'vue-router';
import AppHeaderTools from '@/layouts/AppHeaderTools.vue';
import AppHeaderTools from '@/shared/layouts/AppHeaderTools.vue';
import AdminNav from '../components/AdminNav.vue';
import { useAdminNavStore } from '../stores/admin-nav.store';
+2 -2
View File
@@ -1,8 +1,8 @@
/**
/**
* features/auth/api/user.api.ts
* 用户域 HTTP API:资料、请假、密码重置、Agent 列表等。
*/
import { getAuthHeaders } from '@/utils/auth';
import { getAuthHeaders } from '@/shared/utils/auth';
import { requestJson } from '@/shared/api/client';
const auth = () => ({ headers: getAuthHeaders() });
@@ -1,4 +1,4 @@
<script setup lang="ts">
<script setup lang="ts">
/**
* features/auth/components/LoginModals.vue
* 登录相关弹窗:找回密码、公告详情、企微登录/绑定提示、注册。
@@ -6,7 +6,7 @@
import { inject } from 'vue';
import { useI18n } from 'vue-i18n';
import { Lock, User, X } from 'lucide-vue-next';
import { formatWecomFieldLabel } from '@/utils/wecom';
import { formatWecomFieldLabel } from '@/shared/utils/wecom';
import { LOGIN_KEY } from '../composables/login.context';
const { t } = useI18n();
@@ -1,12 +1,12 @@
/**
/**
* features/auth/composables/login.deps.ts
* 登录页 composables 共享依赖(i18n、路由、主题、消息等)。
*/
import type { ComputedRef, WritableComputedRef } from 'vue';
import type { ComposerTranslation } from 'vue-i18n';
import type { RouteLocationNormalizedLoaded, Router } from 'vue-router';
import type { useMessage } from '@/composables/useMessage';
import type { ThemePreference } from '@/composables/useTheme';
import type { useMessage } from '@/shared/composables/useMessage';
import type { ThemePreference } from '@/shared/composables/useTheme';
export interface LoginDeps {
t: ComposerTranslation;
@@ -1,4 +1,4 @@
/**
/**
* features/auth/composables/useLogin.ts
* 登录页编排层:组合认证、公告展示与 OAuth 回调,provide 给 LoginView 子组件。
*/
@@ -6,8 +6,8 @@ import { onMounted, reactive } from 'vue';
import { useRouter, useRoute } from 'vue-router';
import { useI18n } from 'vue-i18n';
import { config } from '@/config';
import { useTheme } from '@/composables/useTheme';
import { useMessage } from '@/composables/useMessage';
import { useTheme } from '@/shared/composables/useTheme';
import { useMessage } from '@/shared/composables/useMessage';
import { useAuthStore } from '@/features/auth/stores/auth.store';
import loginBg from '@/assets/login-bg.png';
import { DEFAULT_POST_LOGIN_AGENT_ID } from '@/features/workspace/types/workspace.types';
@@ -1,17 +1,17 @@
/**
/**
* features/auth/composables/useLoginAuth.ts
* 登录表单、企微/Casdoor OAuth 回调、注册与找回密码逻辑。
*/
import { ref } from 'vue';
import { config } from '@/config';
import { resolveCasdoorErrorMessage } from '@/utils/casdoor';
import { resolveCasdoorErrorMessage } from '@/shared/utils/casdoor';
import {
buildWecomLoginDialogContent,
normalizeWecomMatchRules,
type WecomMatchField,
} from '@/utils/wecom';
import { saveAuthUser } from '@/utils/auth';
import { BusinessError, requestJson } from '@/api/client';
} from '@/shared/utils/wecom';
import { saveAuthUser } from '@/shared/utils/auth';
import { BusinessError, requestJson } from '@/shared/api/client';
import { DEFAULT_POST_LOGIN_AGENT_ID } from '@/features/workspace/types/workspace.types';
import type { WecomBindPromptState, WecomLoginDialogContent } from '@/features/workspace/types/workspace.types';
import type { LoginDeps } from './login.deps';
@@ -1,9 +1,9 @@
/**
/**
* features/auth/composables/useLoginLanding.ts
* 登录页营销区:公告列表、公开 Agent 与公告弹窗状态。
*/
import { ref } from 'vue';
import { requestJson } from '@/api/client';
import { requestJson } from '@/shared/api/client';
import type { WorkspaceAgent, WorkspaceAnnouncement } from '@/features/workspace/types/workspace.types';
export function useLoginLanding() {
@@ -1,4 +1,4 @@
/**
/**
* features/auth/stores/auth.store.ts
* 认证全局状态;Phase 0 仍委托 utils/auth 读写 storage。
*/
@@ -11,7 +11,7 @@ import {
saveAuthUser,
logoutAuth as logoutAuthStorage,
refreshAccessToken as refreshAccessTokenStorage,
} from '@/utils/auth';
} from '@/shared/utils/auth';
export interface AuthUser {
id?: number;
@@ -1,12 +1,12 @@
<script setup lang="ts">
<script setup lang="ts">
/**
* features/auth/views/LoginView.vue
* 登录页路由入口:MarketingShell + useLogin provide + LoginPage/LoginModals。
*/
import { provide } from 'vue';
import ThemeToggleButton from '@/components/ThemeToggleButton.vue';
import LocaleToggleButton from '@/components/LocaleToggleButton.vue';
import MarketingShell from '@/layouts/MarketingShell.vue';
import ThemeToggleButton from '@/shared/components/ThemeToggleButton.vue';
import LocaleToggleButton from '@/shared/components/LocaleToggleButton.vue';
import MarketingShell from '@/shared/layouts/MarketingShell.vue';
import LoginPage from '../components/LoginPage.vue';
import LoginModals from '../components/LoginModals.vue';
import { useLogin } from '../composables/useLogin';
@@ -1,4 +1,4 @@
<script setup lang="ts">
<script setup lang="ts">
/**
* features/auth/views/ResetPasswordView.vue
* 邮件链接重置密码页(/reset-password?token=...)。
@@ -6,7 +6,7 @@
import { ref } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { Lock, AlertCircle, CheckCircle } from 'lucide-vue-next';
import MinimalShell from '@/layouts/MinimalShell.vue';
import MinimalShell from '@/shared/layouts/MinimalShell.vue';
import { resetPasswordConfirm } from '@/features/auth/api/user.api';
const route = useRoute();
+3 -3
View File
@@ -1,9 +1,9 @@
/**
/**
* features/chat/api/chat.api.ts
* 聊天域 HTTP API:会话、消息、源文件、附件上传。
*/
import { getAuthHeaders } from '@/utils/auth';
import { requestJson } from '@/api/client';
import { getAuthHeaders } from '@/shared/utils/auth';
import { requestJson } from '@/shared/api/client';
import type {
ChatCrossAgentHistoryItem,
ChatMessage,
@@ -1,39 +1,18 @@
import { getAuthHeaders } from '../utils/auth';
export interface ShippingTaskSummary {
id: number;
task_no: string;
source_type: string;
customer_name?: string | null;
process_status: string;
review_status?: string | null;
match_status?: string | null;
pending_human_reason?: string | null;
conversation_id?: string | null;
export_file_name?: string | null;
freight_ref_no?: string | null;
created_at?: string | null;
updated_at?: string | null;
}
export interface ShippingTaskEvent {
event_type: string;
detail_json?: Record<string, unknown> | null;
created_at?: string | null;
}
export interface ShippingTaskDetail extends ShippingTaskSummary {
customer_code?: string | null;
ship_to?: string | null;
po_number?: string | null;
required_date?: string | null;
lines: Array<Record<string, unknown>>;
shortage?: Record<string, unknown> | null;
line_results?: Array<Record<string, unknown>>;
parse_confidence?: number | null;
error_message?: string | null;
events: ShippingTaskEvent[];
}
/**
* features/chat/api/shipping.api.ts
* 货代发货 HTTP API:任务列表、上传库存、映射、决策、Excel 生成等。
* 后端路由前缀为 /api/workspace/shipping-tasks,由 chat 域 Agent 流程与工作台页面共用。
*/
import { getAuthHeaders } from '@/shared/utils/auth';
import type {
ShippingChatActionsResponse,
ShippingDecisionResponse,
ShippingInventoryUploadResponse,
ShippingNoticeUploadResponse,
ShippingTaskCreateResponse,
ShippingTaskDetail,
ShippingTaskSummary,
} from '../types/shipping.api.types';
async function getJson<T>(url: string): Promise<T> {
const res = await fetch(url, { headers: getAuthHeaders() });
@@ -58,22 +37,6 @@ export const getWorkspaceShippingTask = (taskNo: string) =>
export const workspaceShippingExportUrl = (taskNo: string) =>
`/api/workspace/shipping-tasks/${encodeURIComponent(taskNo)}/export`;
export interface ShippingChatAction {
id: string;
label: string;
message: string;
variant: 'primary' | 'secondary' | 'danger';
}
export interface ShippingChatActionsResponse {
task_no: string;
checkpoint?: string | null;
process_status: string;
review_status?: string | null;
pending_human_reason?: string | null;
action_buttons: ShippingChatAction[];
}
export const getShippingChatActions = (taskNo: string) =>
getJson<ShippingChatActionsResponse>(
`/api/workspace/shipping-tasks/${encodeURIComponent(taskNo)}/chat-actions`,
@@ -111,22 +74,6 @@ export async function applyWorkspaceShippingInventoryMapping(taskNo: string, col
return body;
}
export interface ShippingInventoryUploadResponse {
status: string;
message?: string;
task_id?: string;
checkpoint?: string;
data?: Record<string, unknown>;
}
export interface ShippingTaskCreateResponse {
status: string;
message?: string;
task_id?: string;
checkpoint?: string;
data?: Record<string, unknown>;
}
export async function createWorkspaceShippingTask(params?: {
source_type?: string;
conversation_id?: string;
@@ -144,15 +91,6 @@ export async function createWorkspaceShippingTask(params?: {
return body;
}
export interface ShippingNoticeUploadResponse {
status: string;
message?: string;
task_id?: string;
checkpoint?: string;
data?: Record<string, unknown>;
human_options?: string[];
}
export async function createWorkspaceShippingTaskFromNotice(file: File, conversationId?: string) {
const form = new FormData();
form.append('file', file);
@@ -171,14 +109,6 @@ export async function createWorkspaceShippingTaskFromNotice(file: File, conversa
return body;
}
export interface ShippingDecisionResponse {
status: string;
message?: string;
task_id?: string;
checkpoint?: string;
data?: Record<string, unknown>;
}
export async function submitWorkspaceShippingDecision(taskNo: string, decision: string, comment?: string) {
const res = await fetch(
`/api/workspace/shipping-tasks/${encodeURIComponent(taskNo)}/submit-decision`,
@@ -260,4 +190,15 @@ export async function generateWorkspaceShippingExcel(taskNo: string) {
return body;
}
/** 货代发货 Agent 显示名称,用于路由与 Agent 匹配 */
export const SHIPPING_NOTICE_AGENT_NAME = '货代发货通知 Agent';
export type {
ShippingChatActionsResponse,
ShippingDecisionResponse,
ShippingInventoryUploadResponse,
ShippingNoticeUploadResponse,
ShippingTaskCreateResponse,
ShippingTaskDetail,
ShippingTaskSummary,
} from '../types/shipping.api.types';
@@ -0,0 +1,116 @@
/**
* features/chat/components/ChatBrowserPanel.vue
* 内置浏览器侧栏 UI:移动端遮罩、拖拽分隔条与 iframe 预览区。
*/
<script setup lang="ts">
import { ExternalLink, Globe, RotateCw, X } from 'lucide-vue-next';
const open = defineModel<boolean>('open', { required: true });
const draftUrl = defineModel<string>('draftUrl', { required: true });
defineProps<{
currentUrl: string;
frameKey: number;
panelStyle: { width: string } | undefined;
isResizing: boolean;
}>();
const emit = defineEmits<{
load: [];
refresh: [];
'open-new-tab': [];
'url-enter': [event: KeyboardEvent];
'start-resize': [event: MouseEvent];
close: [];
}>();
</script>
<template>
<template v-if="open">
<div
class="fixed inset-0 z-40 bg-overlay backdrop-blur-sm lg:hidden"
@click="emit('close')"
/>
<div
class="relative z-10 hidden w-2 shrink-0 cursor-col-resize bg-transparent lg:block"
@mousedown="emit('start-resize', $event)"
>
<div
class="absolute inset-y-0 left-1/2 w-px -translate-x-1/2 transition-colors"
:class="isResizing ? 'bg-brand-500' : 'bg-slate-200'"
/>
</div>
<aside
class="fixed inset-y-0 right-0 z-50 flex w-full max-w-[100vw] flex-col border-l border-default bg-surface shadow-2xl sm:w-[420px] lg:static lg:z-0 lg:w-[420px] lg:shadow-none"
:style="panelStyle"
>
<div class="flex items-center justify-between border-b border-default px-4 py-3">
<div class="flex items-center gap-2 text-sm font-semibold text-secondary">
<Globe class="h-4 w-4 text-brand-500" />
{{ $t('chat.browser') }}
</div>
<button
type="button"
class="rounded-md p-1.5 text-muted transition-colors hover-surface-soft hover:text-secondary"
:title="$t('chat.closeBrowser')"
@click="emit('close')"
>
<X class="h-4 w-4" />
</button>
</div>
<div class="flex items-center gap-2 border-b border-default px-3 py-3">
<input
v-model="draftUrl"
type="text"
:placeholder="$t('chat.browserInputPlaceholder')"
class="flex-1 rounded-xl border border-default bg-surface-soft px-3 py-2 text-sm text-primary outline-none transition focus:border-brand-400 focus:bg-surface"
@keydown="emit('url-enter', $event)"
/>
<button
type="button"
class="rounded-xl bg-brand-600 px-3 py-2 text-xs font-medium text-white transition-colors hover:bg-brand-500"
@click="emit('load')"
>
{{ $t('chat.open') }}
</button>
<button
type="button"
class="rounded-xl border border-default p-2 text-muted transition-colors hover:bg-surface-soft hover:text-secondary"
:title="$t('chat.refresh')"
@click="emit('refresh')"
>
<RotateCw class="h-4 w-4" />
</button>
<button
type="button"
class="rounded-xl border border-default p-2 text-muted transition-colors hover:bg-surface-soft hover:text-secondary"
:title="$t('chat.openInNewTab')"
@click="emit('open-new-tab')"
>
<ExternalLink class="h-4 w-4" />
</button>
</div>
<div class="min-h-0 flex-1 bg-slate-100">
<div
v-if="!currentUrl"
class="flex h-full flex-col items-center justify-center gap-3 px-8 text-center text-sm text-muted"
>
<Globe class="h-8 w-8 text-brand-500" />
<div>{{ $t('chat.browserHint1') }}</div>
<div class="text-xs">{{ $t('chat.browserHint2') }}</div>
</div>
<iframe
v-else
:key="frameKey"
:src="currentUrl"
class="h-full w-full border-0 bg-surface"
allow="clipboard-read; clipboard-write"
/>
</div>
</aside>
</template>
</template>
@@ -0,0 +1,114 @@
/**
* features/chat/components/ChatGuideModal.vue
* Agent 学习之窗:指南目录与视频 / PDF / 图片预览。
*/
<script setup lang="ts">
import { BookOpen, FileText, Image as ImageIcon, PanelLeftClose, PanelLeftOpen, Play, X } from 'lucide-vue-next';
import type { AgentGuide } from '../composables/useChatGuides';
const open = defineModel<boolean>('open', { required: true });
const activeGuideId = defineModel<number | null>('activeGuideId', { required: true });
const showSidebar = defineModel<boolean>('showSidebar', { required: true });
defineProps<{
agentName: string;
guides: AgentGuide[];
activeGuide: AgentGuide | undefined;
}>();
</script>
<template>
<Teleport to="body">
<div
v-if="open"
class="fixed inset-0 z-[9999] flex items-center justify-center bg-black/50 p-4 backdrop-blur-sm"
>
<div class="flex h-[85vh] w-full max-w-4xl flex-col overflow-hidden rounded-2xl bg-surface shadow-xl">
<div class="flex shrink-0 items-center justify-between border-b border-default bg-surface px-6 py-4">
<h3 class="flex items-center gap-2 text-lg font-bold text-primary">
<BookOpen class="h-5 w-5 text-brand-600" />
{{ agentName }} - 学习之窗
</h3>
<div class="flex items-center gap-3">
<button
type="button"
class="flex items-center gap-1.5 rounded-lg border border-transparent px-3 py-1.5 text-sm font-medium text-brand-600 transition-colors hover:border-brand-100 hover:bg-brand-50 hover:text-brand-700"
@click="showSidebar = !showSidebar"
>
<component :is="showSidebar ? PanelLeftClose : PanelLeftOpen" class="h-4 w-4" />
{{ showSidebar ? '收起目录' : '展开目录' }}
</button>
<div class="h-5 w-px bg-default" />
<button
type="button"
class="rounded-lg p-1 text-muted transition-colors hover:bg-surface-soft hover:text-primary"
@click="open = false"
>
<X class="h-6 w-6" />
</button>
</div>
</div>
<div class="relative flex min-h-0 flex-1 overflow-hidden">
<div
v-show="showSidebar"
class="absolute z-10 h-full w-64 shrink-0 space-y-2 overflow-y-auto border-r border-default bg-surface-soft p-4 shadow-xl transition-transform duration-300 md:relative md:shadow-none"
:class="showSidebar ? 'translate-x-0' : '-translate-x-full absolute'"
>
<button
v-for="guide in guides"
:key="guide.id"
type="button"
class="w-full rounded-xl border px-4 py-3 text-left transition-all"
:class="activeGuideId === guide.id ? 'border-brand-200 bg-brand-50 text-brand-700 shadow-sm' : 'border-transparent bg-surface hover:border-default hover:shadow-sm'"
@click="activeGuideId = guide.id"
>
<div class="mb-1 flex items-center gap-2">
<component
:is="guide.file_type === 'video' ? Play : (guide.file_type === 'pdf' ? FileText : ImageIcon)"
class="h-4 w-4 shrink-0"
/>
<span class="truncate text-sm font-medium">{{ guide.file_name }}</span>
</div>
<p
v-if="guide.remark"
class="truncate text-xs opacity-70"
:class="activeGuideId === guide.id ? 'text-brand-600' : 'text-muted'"
>
{{ guide.remark }}
</p>
</button>
</div>
<div class="relative flex flex-1 items-center justify-center overflow-hidden bg-[#ebedf0] dark:bg-gray-900">
<template v-if="activeGuide">
<video
v-if="activeGuide.file_type === 'video'"
:key="'video-' + activeGuide.id"
:src="activeGuide.file_url || activeGuide.file_path"
controls
class="h-full w-full bg-black object-contain"
/>
<iframe
v-else-if="activeGuide.file_type === 'pdf'"
:key="'pdf-' + activeGuide.id"
:src="activeGuide.file_url || activeGuide.file_path"
class="h-full w-full border-none bg-white"
/>
<img
v-else
:key="'img-' + activeGuide.id"
:src="activeGuide.file_url || activeGuide.file_path"
class="max-h-full max-w-full object-contain"
/>
</template>
<div v-else class="flex flex-col items-center gap-3 text-muted">
<BookOpen class="h-12 w-12 opacity-20" />
<p class="text-sm">请选择左侧指南进行查阅</p>
</div>
</div>
</div>
</div>
</div>
</Teleport>
</template>
@@ -0,0 +1,346 @@
/**
* features/chat/components/ChatInputBar.vue
* 聊天输入栏:文本框、附件、语音、知识库选择与发送按钮。
*/
<script setup lang="ts">
import { nextTick, onBeforeUnmount, onMounted, ref } from 'vue';
import type { Ref } from 'vue';
import {
Check,
ChevronDown,
Database,
Globe,
Link2,
Loader2,
Mic,
Paperclip,
Send,
X,
} from 'lucide-vue-next';
import type { PendingAttachment } from '../types/shipping.types';
export interface ChatInputAttachmentPolicy {
anyEnabled: boolean;
canLocal: boolean;
canRemote: boolean;
accept: string;
}
const inputValue = defineModel<string>({ required: true });
const selectedKb = defineModel<string>('selectedKb', { required: true });
const props = defineProps<{
attachments: PendingAttachment[];
attachmentPolicy: ChatInputAttachmentPolicy;
availableKbOptions: string[];
kbDropdownDisabled: boolean;
isThinking: boolean;
isVoiceRecording: boolean;
isVoiceTranscribing: boolean;
isUploadingAttachments: boolean;
canSendMessage: boolean;
isShippingNoticeAgent: boolean;
shippingSuggestedPrompt: string;
/** 用对象包裹 Ref,避免 template 自动解包 */
shippingPickerRefHolder: { pickerRef: Ref<HTMLInputElement | null> };
getKbLabel: (kb: string) => string;
browserPanelOpen: boolean;
}>();
const emit = defineEmits<{
send: [];
'toggle-browser': [];
'voice-click': [];
'remove-attachment': [id: string];
'local-files-selected': [event: Event];
'add-remote-url': [url: string];
'shipping-inventory-selected': [event: Event];
'use-shipping-suggested-prompt': [];
}>();
const filePickerRef = ref<HTMLInputElement | null>(null);
const attachmentMenuRef = ref<HTMLElement | null>(null);
const kbMenuRef = ref<HTMLElement | null>(null);
const attachmentUrlInputRef = ref<HTMLInputElement | null>(null);
const showAttachmentMenu = ref(false);
const showAttachmentUrlPanel = ref(false);
const showKbDropdown = ref(false);
const attachmentUrlInput = ref('');
const closeAttachmentMenu = () => {
showAttachmentMenu.value = false;
showAttachmentUrlPanel.value = false;
attachmentUrlInput.value = '';
};
const toggleAttachmentMenu = () => {
if (props.isThinking || props.isUploadingAttachments) return;
showAttachmentMenu.value = !showAttachmentMenu.value;
if (!showAttachmentMenu.value) {
showAttachmentUrlPanel.value = false;
attachmentUrlInput.value = '';
}
};
const selectAttachmentLocal = () => {
if (!props.attachmentPolicy.canLocal) return;
closeAttachmentMenu();
filePickerRef.value?.click();
};
const selectAttachmentUrl = async () => {
if (!props.attachmentPolicy.canRemote) return;
showAttachmentMenu.value = true;
showAttachmentUrlPanel.value = true;
await nextTick();
attachmentUrlInputRef.value?.focus();
};
const toggleKbDropdown = () => {
if (props.kbDropdownDisabled) {
showKbDropdown.value = false;
return;
}
showKbDropdown.value = !showKbDropdown.value;
};
const selectKb = (option: string) => {
if (!props.availableKbOptions.includes(option)) return;
selectedKb.value = option;
showKbDropdown.value = false;
};
const submitRemoteUrl = () => {
const raw = attachmentUrlInput.value.trim();
if (!raw) return;
emit('add-remote-url', raw);
closeAttachmentMenu();
};
const bindShippingPickerRef = (el: unknown) => {
props.shippingPickerRefHolder.pickerRef.value = (el as HTMLInputElement | null) ?? null;
};
const handleDocumentPointerDown = (event: MouseEvent | TouchEvent) => {
const target = event.target as Node | null;
if (!target) return;
if (showKbDropdown.value && kbMenuRef.value && !kbMenuRef.value.contains(target)) {
showKbDropdown.value = false;
}
if (showAttachmentMenu.value && attachmentMenuRef.value && !attachmentMenuRef.value.contains(target)) {
closeAttachmentMenu();
}
};
onMounted(() => {
document.addEventListener('mousedown', handleDocumentPointerDown);
document.addEventListener('touchstart', handleDocumentPointerDown, { passive: true });
});
onBeforeUnmount(() => {
document.removeEventListener('mousedown', handleDocumentPointerDown);
document.removeEventListener('touchstart', handleDocumentPointerDown);
});
</script>
<template>
<footer class="safe-bottom sticky bottom-0 z-20 bg-transparent p-3 md:p-6">
<div class="relative mx-auto max-w-4xl">
<div class="flex flex-col rounded-2xl bg-surface p-2 shadow-[0_0_15px_rgba(0,0,0,0.05)] transition-all">
<textarea
v-model="inputValue"
rows="1"
:placeholder="isVoiceTranscribing ? $t('chat.voiceTranscribing') : isVoiceRecording ? $t('chat.voiceListening') : $t('chat.askAnything')"
class="w-full resize-none border-none bg-transparent px-3 py-2 text-[15px] leading-relaxed text-primary placeholder-slate-400 focus:border-transparent focus:outline-none focus:ring-0"
style="min-height: 44px; max-height: 220px;"
:disabled="isThinking || isVoiceTranscribing"
spellcheck="false"
autocorrect="off"
autocapitalize="off"
@keydown.enter.prevent="emit('send')"
/>
<input
:ref="bindShippingPickerRef"
type="file"
class="hidden"
accept=".xlsx,.xls,.csv,application/vnd.openxmlformats-officedocument.spreadsheetml.sheet,application/vnd.ms-excel,text/csv"
@change="emit('shipping-inventory-selected', $event)"
/>
<input
ref="filePickerRef"
type="file"
multiple
class="hidden"
:accept="attachmentPolicy.accept || undefined"
@change="emit('local-files-selected', $event)"
/>
<div v-if="attachments.length > 0" class="flex flex-wrap gap-2 px-3 pb-1">
<div
v-for="a in attachments"
:key="a.id"
class="flex items-center gap-2 rounded-lg border border-default bg-surface-soft px-2 py-1 text-xs text-secondary"
>
<span class="max-w-[220px] truncate">
{{ a.kind === 'local' ? a.file.name : a.url }}
</span>
<button type="button" class="text-muted hover:text-red-500" @click="emit('remove-attachment', a.id)">
<X class="h-3.5 w-3.5" />
</button>
</div>
</div>
<div
v-if="isShippingNoticeAgent && attachments.length > 0"
class="flex flex-wrap items-center gap-2 px-3 pb-1 text-xs text-muted"
>
<button
type="button"
class="rounded-full border border-default bg-surface-soft px-3 py-1 font-medium text-secondary transition-colors hover:bg-surface-soft/70"
@click="emit('use-shipping-suggested-prompt')"
>
{{ shippingSuggestedPrompt || '推荐问题' }}
</button>
<span>点发送开始处理</span>
</div>
<div class="mt-2 flex items-center justify-between px-2 pb-1">
<div class="flex items-center gap-3">
<button
type="button"
:disabled="isThinking || isVoiceTranscribing"
:title="isVoiceRecording ? $t('chat.voiceStop') : isVoiceTranscribing ? $t('chat.voiceTranscribing') : $t('chat.voiceFeature')"
class="transition-colors disabled:cursor-not-allowed disabled:opacity-50"
:class="isVoiceRecording ? 'animate-pulse text-red-500' : isVoiceTranscribing ? 'text-brand-500' : 'text-muted hover:text-brand-600'"
@click="emit('voice-click')"
>
<Loader2 v-if="isVoiceTranscribing" class="h-5 w-5 animate-spin" />
<Mic v-else class="h-5 w-5" />
</button>
<div v-if="attachmentPolicy.anyEnabled" ref="attachmentMenuRef" class="relative">
<button
type="button"
:disabled="isThinking || isUploadingAttachments"
title="附件"
class="flex h-9 w-9 items-center justify-center rounded-lg text-muted transition-colors hover:text-brand-600 disabled:cursor-not-allowed disabled:opacity-50"
@click="toggleAttachmentMenu"
>
<Paperclip class="h-5 w-5" />
</button>
<div
v-if="showAttachmentMenu"
class="absolute bottom-full left-0 mb-2 w-72 animate-fade-in overflow-hidden rounded-xl border border-subtle bg-surface py-1 shadow-xl"
>
<button
v-if="attachmentPolicy.canLocal"
type="button"
class="flex w-full items-center gap-2 px-3 py-2 text-xs text-secondary transition-colors hover:bg-surface-soft"
@click="selectAttachmentLocal"
>
<Paperclip class="h-4 w-4 text-brand-500" />
上传本地文件
</button>
<button
v-if="attachmentPolicy.canRemote"
type="button"
class="flex w-full items-center gap-2 px-3 py-2 text-xs text-secondary transition-colors hover:bg-surface-soft"
@click="selectAttachmentUrl"
>
<Link2 class="h-4 w-4 text-brand-500" />
粘贴 URL
</button>
<div v-if="showAttachmentUrlPanel" class="px-3 py-2">
<div class="flex items-center gap-2">
<input
ref="attachmentUrlInputRef"
v-model="attachmentUrlInput"
:disabled="isThinking || isUploadingAttachments"
placeholder="粘贴附件 URL(http/https)"
class="flex-1 rounded-lg border border-default bg-surface-soft px-3 py-2 text-xs text-secondary placeholder-slate-400 focus:outline-none focus:ring-0"
@keydown.enter.prevent="submitRemoteUrl"
/>
<button
type="button"
:disabled="isThinking || isUploadingAttachments"
class="flex h-9 w-9 items-center justify-center rounded-lg border border-default text-muted transition-colors hover:bg-surface-soft disabled:cursor-not-allowed disabled:opacity-50"
title="添加"
@click="submitRemoteUrl"
>
<Check class="h-4 w-4" />
</button>
<button
type="button"
:disabled="isThinking || isUploadingAttachments"
class="flex h-9 w-9 items-center justify-center rounded-lg border border-default text-muted transition-colors hover:bg-surface-soft disabled:cursor-not-allowed disabled:opacity-50"
title="取消"
@click="closeAttachmentMenu"
>
<X class="h-4 w-4" />
</button>
</div>
</div>
</div>
</div>
<div ref="kbMenuRef" class="relative">
<button
type="button"
:disabled="kbDropdownDisabled"
class="flex items-center gap-1 rounded-lg border border-default px-3 py-1.5 text-xs font-medium text-secondary transition-colors hover:bg-surface-soft disabled:cursor-not-allowed disabled:opacity-60"
@click="toggleKbDropdown"
>
<Database class="h-3.5 w-3.5 text-brand-500" />
{{ getKbLabel(selectedKb) }} <ChevronDown class="h-3 w-3" />
</button>
<div
v-if="showKbDropdown && !kbDropdownDisabled"
class="absolute bottom-full left-0 mb-2 w-36 animate-fade-in overflow-hidden rounded-xl border border-subtle bg-surface py-1 shadow-xl"
>
<button
v-for="option in availableKbOptions"
:key="option"
type="button"
class="flex w-full items-center justify-between px-3 py-2 text-xs text-secondary transition-colors hover:bg-surface-soft"
:class="{ 'font-bold text-brand-700': selectedKb === option }"
@click="selectKb(option)"
>
{{ getKbLabel(option) }}
<Check v-if="selectedKb === option" class="h-3.5 w-3.5" />
</button>
</div>
</div>
<button
type="button"
:disabled="isThinking"
class="flex items-center gap-1 rounded-lg border border-default px-3 py-1.5 text-xs font-medium text-secondary transition-colors hover:bg-surface-soft disabled:cursor-not-allowed disabled:opacity-50"
@click="emit('toggle-browser')"
>
<Globe class="h-3.5 w-3.5 text-brand-500" />
{{ browserPanelOpen ? $t('chat.collapseBrowser') : $t('chat.openBrowser') }}
</button>
</div>
<button
type="button"
:disabled="!canSendMessage"
class="flex h-10 w-10 items-center justify-center rounded-full border shadow-sm transition-all duration-200 disabled:cursor-not-allowed disabled:opacity-50"
:class="!canSendMessage
? 'border-default bg-slate-100 text-muted'
: 'border-brand-500 bg-brand-500 text-white shadow-[0_0_0_4px_rgba(59,130,246,0.18)] hover:scale-105 hover:bg-brand-600 hover:shadow-[0_0_0_6px_rgba(59,130,246,0.24)] active:scale-95'"
@click="emit('send')"
>
<Loader2 v-if="isUploadingAttachments" class="h-4 w-4 animate-spin" />
<Send v-else class="h-4 w-4" />
</button>
</div>
</div>
<div class="mt-3 text-center text-[11px] text-muted">
{{ $t('chat.disclaimer') }}
</div>
</div>
</footer>
</template>
@@ -0,0 +1,115 @@
/**
* features/chat/components/ChatLeaveAgentDialog.vue
* 请假 OA:选择代理人 / 申请人弹窗。
*/
<script setup lang="ts">
import { Loader2, Search, X } from 'lucide-vue-next';
import type { LeaveAgentOption } from '../types/leave.types';
const open = defineModel<boolean>('open', { required: true });
const keyword = defineModel<string>('keyword', { required: true });
defineProps<{
selectRole: 'agent' | 'applicant';
options: LeaveAgentOption[];
loading: boolean;
page: number;
hasMore: boolean;
}>();
const emit = defineEmits<{
close: [];
search: [];
'load-more': [];
'load-all': [];
select: [option: LeaveAgentOption];
}>();
</script>
<template>
<div
v-if="open"
class="dialog-overlay z-[100] items-center"
@click.self="emit('close')"
>
<div class="dialog-panel flex max-h-[80vh] max-w-2xl flex-col">
<div class="dialog-header">
<div>
<h3 class="section-title">
{{ $t('chat.selectWho', { role: selectRole === 'agent' ? $t('chat.leaveAgent') : $t('chat.leaveApplicant') }) }}
</h3>
<p class="section-desc mt-1">{{ $t('chat.oaDataConnected') }}</p>
</div>
<button type="button" class="btn-icon-ds" :aria-label="$t('admin.close')" @click="emit('close')">
<X class="h-5 w-5" />
</button>
</div>
<div class="dialog-body space-y-4 border-t-0 pt-4">
<div class="relative shrink-0">
<input
v-model="keyword"
type="text"
:placeholder="$t('chat.searchByNameOrEmployeeId')"
class="input-field pr-10"
@keydown.enter="emit('search')"
/>
<button
type="button"
class="absolute inset-y-0 right-0 flex w-10 items-center justify-center text-muted hover:text-brand-600"
@click="emit('search')"
>
<Search class="h-4 w-4" />
</button>
</div>
<div class="max-h-[50vh] flex-1 space-y-3 overflow-y-auto pr-2 scrollbar-thin">
<div v-if="loading && page === 1" class="flex justify-center py-8">
<Loader2 class="h-6 w-6 animate-spin text-brand-500" />
</div>
<div v-else-if="options.length === 0" class="py-8 text-center text-sm text-muted">
{{ $t('chat.noData') }}
</div>
<template v-else>
<button
v-for="option in options"
:key="option.uid"
type="button"
class="flex w-full items-center justify-between rounded-2xl border border-default px-4 py-4 text-left transition hover:border-brand-300 hover:bg-brand-50/50"
@click="emit('select', option)"
>
<div class="space-y-1">
<div class="text-sm font-semibold text-primary">{{ option.name }}</div>
<div class="text-xs text-muted">UID:{{ option.uid }}</div>
</div>
<div class="text-right text-xs text-muted">
<div>{{ $t('chat.employeeId') }}:{{ option.employeeId }}</div>
<div>{{ $t('chat.name') }}:{{ option.name }}</div>
</div>
</button>
<div v-if="hasMore" class="flex items-center justify-center space-x-6 py-4">
<button
type="button"
class="text-xs text-muted hover:text-secondary disabled:opacity-50"
:disabled="loading"
@click="emit('load-all')"
>
{{ $t('chat.loadAll') }}
</button>
<button
type="button"
class="text-xs text-brand-600 hover:text-brand-700 disabled:opacity-50"
:disabled="loading"
@click="emit('load-more')"
>
{{ loading ? $t('chat.loading') : $t('chat.loadMore') }}
</button>
</div>
<div v-else class="py-4 text-center text-xs text-muted">{{ $t('chat.noMoreData') }}</div>
</template>
</div>
</div>
</div>
</div>
</template>
@@ -0,0 +1,106 @@
/**
* features/chat/components/ChatMessageList.vue
* 消息列表主区域:滚动容器、欢迎页、消息气泡与思考中占位。
*/
<script setup lang="ts">
import type { Ref } from 'vue';
import ChatWelcomePanel, { type WelcomeQuestionItem, type WelcomeQuestionSection } from './ChatWelcomePanel.vue';
import ChatThinkingBubble from './ChatThinkingBubble.vue';
import ChatMessageBubble, { type ChatMessageBubbleHandlers } from './messages/ChatMessageBubble.vue';
import ToolRunProgressCard from './ToolRunProgressCard.vue';
import type { LeaveMessageHandlers } from './messages/LeaveMessageBlock.vue';
import type { ShippingMappingHandlers } from './messages/ShippingInventoryMappingMessage.vue';
import type { ChatMessage } from '../types/chat.types';
import type { ToolRunProgress } from '@/api/toolRunProgress';
const {
messages,
shouldRenderMessage,
scrollContainerHolder,
} = defineProps<{
messages: ChatMessage[];
agentName: string;
suggestedQuestionsStyle: 'plain' | 'styled';
styledSections: WelcomeQuestionSection[];
suggestedQuestions: WelcomeQuestionItem[];
showThinkingBubble: boolean;
isThinking: boolean;
showChatRating: boolean;
copiedIndex: number | null;
isShippingNoticeAgent: boolean;
handlers: ChatMessageBubbleHandlers;
leaveHandlers: LeaveMessageHandlers;
shippingHandlers: ShippingMappingHandlers;
shouldRenderMessage: (msg: ChatMessage) => boolean;
shouldShowToolRunProgressAfterMessage: (msg: ChatMessage) => boolean;
toolRunProgress: ToolRunProgress | null;
toolRunProgressLoading: boolean;
toolRunProgressError: string;
toolRunProgressTitle: string;
/** 供父级滚动逻辑绑定 main 元素 */
scrollContainerHolder: { el: Ref<HTMLElement | null> };
}>();
const emit = defineEmits<{
copy: [payload: { message: ChatMessage; index: number }];
edit: [content: string];
resend: [content: string];
regenerate: [];
'open-feedback': [index: number];
'select-question': [question: string];
}>();
const bindScrollContainer = (node: unknown) => {
scrollContainerHolder.el.value = (node as HTMLElement | null) ?? null;
};
</script>
<template>
<main
:ref="bindScrollContainer"
class="flex-1 p-3 md:p-8"
:class="messages.length === 0 ? 'overflow-hidden md:overflow-y-auto' : 'overflow-y-auto scrollbar-thin'"
>
<div :class="messages.length === 0 ? 'h-full' : 'flex min-h-full flex-col justify-end'">
<ChatWelcomePanel
v-if="messages.length === 0"
:agent-name="agentName"
:suggested-questions-style="suggestedQuestionsStyle"
:styled-sections="styledSections"
:suggested-questions="suggestedQuestions"
@select-question="emit('select-question', $event)"
/>
<template v-for="(msg, index) in messages" :key="index">
<ChatMessageBubble
v-if="shouldRenderMessage(msg)"
:message="msg"
:index="index"
:message-count="messages.length"
:is-thinking="isThinking"
:show-chat-rating="showChatRating"
:copied-index="copiedIndex"
:is-shipping-notice-agent="isShippingNoticeAgent"
:handlers="handlers"
:leave-handlers="leaveHandlers"
:shipping-handlers="shippingHandlers"
@copy="emit('copy', { message: msg, index })"
@edit="emit('edit', $event)"
@resend="emit('resend', $event)"
@regenerate="emit('regenerate')"
@open-feedback="emit('open-feedback', index)"
/>
<ToolRunProgressCard
v-if="shouldRenderMessage(msg) && shouldShowToolRunProgressAfterMessage(msg)"
:run="toolRunProgress"
:loading="toolRunProgressLoading"
:error="toolRunProgressError"
:fallback-title="toolRunProgressTitle"
/>
</template>
<ChatThinkingBubble v-if="showThinkingBubble" />
<div v-if="messages.length > 0" class="h-2 md:h-3" />
</div>
</main>
</template>
@@ -0,0 +1,119 @@
/**
* features/chat/components/ChatMobileHeader.vue
* 移动端顶栏:Agent 名称、学习之窗与 Agent 切换弹层。
*/
<script setup lang="ts">
import { onBeforeUnmount, onMounted, ref } from 'vue';
import { BookOpen, History, LayoutGrid } from 'lucide-vue-next';
export interface ChatMobileHeaderAgent {
id: number;
name: string;
}
defineProps<{
agentName: string;
hasAgentGuides: boolean;
userAgents: ChatMobileHeaderAgent[];
}>();
const emit = defineEmits<{
'open-guide': [];
'go-history': [];
'open-agent-popover': [];
'switch-agent': [agent: ChatMobileHeaderAgent];
}>();
const showAgentPopover = ref(false);
const popoverRef = ref<HTMLElement | null>(null);
const toggleAgentPopover = () => {
showAgentPopover.value = !showAgentPopover.value;
if (showAgentPopover.value) {
emit('open-agent-popover');
}
};
const handleClickOutside = (event: MouseEvent | TouchEvent) => {
const target = event.target as Node | null;
if (!target) return;
if (showAgentPopover.value && popoverRef.value && !popoverRef.value.contains(target)) {
showAgentPopover.value = false;
}
};
const onSwitchAgent = (agent: ChatMobileHeaderAgent) => {
showAgentPopover.value = false;
emit('switch-agent', agent);
};
onMounted(() => {
document.addEventListener('mousedown', handleClickOutside);
document.addEventListener('touchstart', handleClickOutside, { passive: true });
});
onBeforeUnmount(() => {
document.removeEventListener('mousedown', handleClickOutside);
document.removeEventListener('touchstart', handleClickOutside);
});
</script>
<template>
<header class="relative flex items-center justify-between border-b border-default bg-surface px-4 py-2.5">
<div class="flex items-center gap-2">
<div class="flex h-7 w-7 items-center justify-center rounded-lg bg-gradient-to-br from-brand-500 via-brand-600 to-sky-600 text-xs font-bold text-white shadow-sm shadow-brand-500/20">
AI
</div>
<span class="text-sm font-semibold text-primary">{{ agentName }}</span>
<button
v-if="hasAgentGuides"
type="button"
class="ml-1 flex items-center gap-1.5 rounded-lg border border-brand-300 bg-brand-100 px-3 py-1.5 text-xs font-bold text-brand-700 shadow-sm transition-all hover:border-brand-400 hover:bg-brand-200"
@click="emit('open-guide')"
>
<BookOpen class="h-4 w-4" />
学习之窗
</button>
</div>
<div class="flex items-center gap-1">
<button
type="button"
class="flex h-9 w-9 items-center justify-center rounded-full text-muted transition-colors hover-surface-soft"
:title="$t('chat.agents')"
@click="toggleAgentPopover"
>
<LayoutGrid class="h-5 w-5" />
</button>
<button
type="button"
class="flex h-9 w-9 items-center justify-center rounded-full text-muted transition-colors hover-surface-soft"
:title="$t('chat.history')"
@click="emit('go-history')"
>
<History class="h-5 w-5" />
</button>
</div>
<div
v-if="showAgentPopover"
ref="popoverRef"
class="absolute right-4 top-12 z-50 w-72 rounded-2xl border border-default bg-surface p-3 shadow-xl"
>
<div class="mb-2 text-xs font-medium text-muted">{{ $t('chat.agents') }}</div>
<div class="grid grid-cols-2 gap-2">
<button
v-for="agent in userAgents"
:key="agent.id"
type="button"
class="flex flex-col items-center gap-1.5 rounded-xl px-2 py-3 text-center transition-colors hover-surface-soft"
@click="onSwitchAgent(agent)"
>
<div class="flex h-9 w-9 items-center justify-center rounded-lg bg-brand-50 text-sm font-bold text-brand-600">
{{ agent.name.charAt(0) }}
</div>
<span class="w-full truncate text-xs font-medium text-secondary">{{ agent.name }}</span>
</button>
</div>
<div v-if="userAgents.length === 0" class="py-3 text-center text-xs text-muted">{{ $t('chat.noOtherAgents') }}</div>
</div>
</header>
</template>
@@ -0,0 +1,59 @@
/**
* features/chat/components/ChatOALoginDialog.vue
* 请假 OA 系统登录弹窗。
*/
<script setup lang="ts">
const open = defineModel<boolean>('open', { required: true });
const employeeId = defineModel<string>('employeeId', { required: true });
const password = defineModel<string>('password', { required: true });
const emit = defineEmits<{
confirm: [];
cancel: [];
}>();
</script>
<template>
<Teleport to="body">
<div
v-if="open"
class="dialog-overlay z-[9999] items-center"
@click.self="emit('cancel')"
>
<div class="dialog-panel max-w-sm">
<div class="dialog-header dialog-header--compact justify-center border-0 pb-2">
<h3 class="section-title text-center">{{ $t('chat.loginOaSystem') }}</h3>
</div>
<div class="dialog-body space-y-4 border-t-0 pt-0">
<label class="block space-y-1.5">
<span class="label-field">{{ $t('chat.employeeId') }}</span>
<input
v-model="employeeId"
type="text"
disabled
class="input-field bg-surface-soft"
/>
</label>
<label class="block space-y-1.5">
<span class="label-field">{{ $t('login.password') }}</span>
<input
v-model="password"
type="password"
:placeholder="$t('chat.enterOaPassword')"
class="input-field"
@keyup.enter="emit('confirm')"
/>
</label>
</div>
<div class="dialog-footer">
<button type="button" class="btn-secondary" @click="emit('cancel')">
{{ $t('profile.cancel') }}
</button>
<button type="button" class="btn-primary btn-sm" @click="emit('confirm')">
{{ $t('chat.confirmLogin') }}
</button>
</div>
</div>
</div>
</Teleport>
</template>
@@ -0,0 +1,108 @@
/**
* features/chat/components/ChatQueryPreviewDialog.vue
* Text2SQL 查询结果全量预览弹窗 UI。
*/
<script setup lang="ts">
import { computed } from 'vue';
import { Loader2, X } from 'lucide-vue-next';
import type { QueryPreviewState } from '../composables/useChatQueryPreview';
const open = defineModel<boolean>('open', { required: true });
const props = defineProps<{
loading: boolean;
error: string;
state: QueryPreviewState;
}>();
const emit = defineEmits<{
close: [];
'change-page': [delta: number];
}>();
const totalPages = computed(() =>
Math.max(1, Math.ceil((props.state.total || 0) / (props.state.pageSize || 100))),
);
</script>
<template>
<div
v-if="open"
class="dialog-overlay z-[120] items-center"
@click.self="emit('close')"
>
<div class="dialog-panel flex max-h-[88vh] w-[min(96vw,1280px)] max-w-[1280px] flex-col">
<div class="dialog-header">
<div>
<h3 class="section-title">查询结果全量预览</h3>
<p class="section-desc mt-1">{{ state.query || state.title }}</p>
</div>
<button type="button" class="btn-icon-ds" aria-label="关闭" @click="emit('close')">
<X class="h-5 w-5" />
</button>
</div>
<div class="dialog-body flex min-h-0 flex-1 flex-col gap-4 border-t-0 pt-4">
<div class="flex flex-wrap items-center justify-between gap-3 rounded-xl border border-default bg-surface-soft px-4 py-3 text-sm text-secondary">
<div>共 {{ state.total || 0 }} 条,当前第 {{ state.page }} / {{ totalPages }} 页</div>
<div class="flex items-center gap-2">
<button
type="button"
class="rounded-lg border border-default px-3 py-1.5 text-xs transition-colors hover:bg-surface disabled:cursor-not-allowed disabled:opacity-50"
:disabled="loading || state.page <= 1"
@click="emit('change-page', -1)"
>
上一页
</button>
<button
type="button"
class="rounded-lg border border-default px-3 py-1.5 text-xs transition-colors hover:bg-surface disabled:cursor-not-allowed disabled:opacity-50"
:disabled="loading || state.page >= totalPages"
@click="emit('change-page', 1)"
>
下一页
</button>
</div>
</div>
<div v-if="error" class="rounded-xl border border-red-200 bg-red-50 px-4 py-3 text-sm text-red-700">
{{ error }}
</div>
<div class="min-h-0 flex-1 overflow-auto rounded-2xl border border-default bg-surface">
<div v-if="loading" class="flex h-56 items-center justify-center">
<Loader2 class="h-6 w-6 animate-spin text-brand-500" />
</div>
<div v-else-if="!state.columns.length" class="flex h-56 items-center justify-center text-sm text-muted">
暂无可预览数据
</div>
<table v-else class="min-w-full border-collapse text-sm">
<thead class="sticky top-0 z-10 bg-slate-50">
<tr>
<th
v-for="column in state.columns"
:key="`query-preview-col-${column}`"
class="border border-slate-200 px-3 py-2 text-left font-semibold text-primary"
>
{{ column }}
</th>
</tr>
</thead>
<tbody>
<tr
v-for="(row, rowIndex) in state.rows"
:key="`query-preview-row-${rowIndex}`"
class="odd:bg-white even:bg-slate-50/50"
>
<td
v-for="(cell, cellIndex) in row"
:key="`query-preview-cell-${rowIndex}-${cellIndex}`"
class="max-w-[320px] border border-slate-200 px-3 py-2 align-top text-secondary"
>
<div class="whitespace-pre-wrap break-all">{{ cell ?? '-' }}</div>
</td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
</div>
</template>
@@ -0,0 +1,332 @@
/**
* features/chat/components/ChatSidebar.vue
* 桌面端聊天侧栏:Agent 信息、会话历史、Agent 切换面板与底部用户菜单。
*/
<script setup lang="ts">
import { onBeforeUnmount, onMounted, ref } from 'vue';
import {
BookOpen,
Briefcase,
LayoutGrid,
LogOut,
MessageSquareText,
Moon,
PanelLeftClose,
PanelLeftOpen,
Plus,
Settings,
Sparkles,
Sun,
X,
} from 'lucide-vue-next';
import LocaleToggleButton from '@/shared/components/LocaleToggleButton.vue';
import type { DisplayHistoryItem } from '../types/chat.types';
export interface ChatSidebarAgent {
id: number;
name: string;
icon_url?: string;
}
const collapsed = defineModel<boolean>('collapsed', { required: true });
const agentPanelOpen = defineModel<boolean>('agentPanelOpen', { required: true });
const { currentUser } = defineProps<{
isOpen: boolean;
currentAgent: { name?: string } | null;
agentDescription: string;
hasAgentGuides: boolean;
displayHistory: DisplayHistoryItem[];
activeHistoryKey: string;
userAgents: ChatSidebarAgent[];
currentUser: Record<string, unknown> | null;
appliedTheme: string;
}>();
const emit = defineEmits<{
'new-chat': [];
'open-guide': [];
'history-select': [item: DisplayHistoryItem];
'clear-all-history': [];
'delete-history-item': [id: string, event: Event];
'switch-agent': [agent: ChatSidebarAgent];
'toggle-theme': [];
'open-feedback': [];
'go-workspace': [];
'go-admin': [];
logout: [];
}>();
const showUserDropdown = ref(false);
const userMenuRef = ref<HTMLElement | null>(null);
const handleDocumentPointerDown = (event: MouseEvent | TouchEvent) => {
const target = event.target as Node | null;
if (!target) return;
if (showUserDropdown.value && userMenuRef.value && !userMenuRef.value.contains(target)) {
showUserDropdown.value = false;
}
};
onMounted(() => {
document.addEventListener('mousedown', handleDocumentPointerDown);
document.addEventListener('touchstart', handleDocumentPointerDown, { passive: true });
});
onBeforeUnmount(() => {
document.removeEventListener('mousedown', handleDocumentPointerDown);
document.removeEventListener('touchstart', handleDocumentPointerDown);
});
const onNewChat = () => {
emit('new-chat');
};
const onLogout = () => {
showUserDropdown.value = false;
emit('logout');
};
const onGoAdmin = () => {
showUserDropdown.value = false;
emit('go-admin');
};
const userInitial = (fallback: string) => {
const name = String(currentUser?.username ?? '').trim();
return (name || fallback).charAt(0).toUpperCase();
};
</script>
<template>
<aside
class="glass-panel fixed inset-y-0 left-0 z-50 flex h-full flex-col border-r border-default bg-surface transition-all duration-300 ease-in-out md:relative md:translate-x-0"
:class="[
isOpen ? 'translate-x-0 w-[86vw] max-w-[300px]' : '-translate-x-full w-[86vw] max-w-[300px]',
collapsed ? 'md:w-[72px]' : 'md:w-80',
]"
>
<template v-if="collapsed">
<div class="flex h-full w-full flex-col items-center py-4">
<button type="button" class="mb-6 text-muted transition-colors hover:text-secondary" @click="collapsed = false">
<PanelLeftOpen class="h-5 w-5" />
</button>
<div class="mb-4 flex h-10 w-10 shrink-0 items-center justify-center rounded-full bg-gradient-to-br from-brand-500 via-brand-600 to-sky-600 text-white shadow-sm shadow-brand-500/25">
<Sparkles class="h-5 w-5" />
</div>
<button type="button" class="chat-sidebar-btn-icon" :title="$t('chat.createNewChat')" @click="onNewChat">
<Plus class="h-5 w-5" />
</button>
<div class="mt-auto flex flex-col items-center gap-6 pb-2 text-muted">
<button type="button" class="transition-colors hover:text-secondary"><Sparkles class="h-5 w-5" /></button>
<div class="flex h-8 w-8 items-center justify-center rounded-full bg-brand-600 text-sm font-bold text-white shadow-sm shadow-brand-500/20">
{{ userInitial('I') }}
</div>
<LocaleToggleButton variant="sidebar" icon-size="md" />
<button type="button" class="transition-colors hover:text-secondary" :title="$t('chat.generalFeedback')" @click="emit('open-feedback')">
<MessageSquareText class="h-5 w-5" />
</button>
<button type="button" class="transition-colors hover:text-secondary" :title="$t('workspace.title')" @click="emit('go-workspace')">
<Briefcase class="h-5 w-5" />
</button>
</div>
</div>
</template>
<template v-else>
<div class="flex items-center justify-between p-4">
<div class="flex w-full min-w-0 items-center gap-3">
<div class="flex h-8 w-8 shrink-0 items-center justify-center rounded-xl bg-gradient-to-br from-brand-500 via-brand-600 to-sky-600 text-sm font-bold text-white shadow-sm shadow-brand-500/25">
{{ currentAgent?.name === '人事规章' ? 'HR' : 'AI' }}
</div>
<div class="group relative flex min-w-0 flex-1 flex-col justify-center">
<div class="flex items-center gap-2">
<span class="truncate font-bold text-primary">{{ currentAgent?.name || 'AI' }}</span>
<button
v-if="hasAgentGuides"
type="button"
class="flex items-center gap-1.5 rounded-lg border border-brand-300 bg-brand-100 px-3 py-1.5 text-xs font-bold text-brand-700 shadow-sm transition-all hover:border-brand-400 hover:bg-brand-200"
@click="emit('open-guide')"
>
<BookOpen class="h-4 w-4" />
学习之窗
</button>
</div>
<span v-if="agentDescription" class="mt-1 block cursor-help truncate text-[11px] text-muted">
{{ agentDescription }}
</span>
<div
v-if="agentDescription"
class="pointer-events-none invisible absolute left-0 top-[calc(100%+0.25rem)] z-[100] w-[20rem] rounded-xl border border-default bg-surface p-3 opacity-0 shadow-xl transition-all duration-200 group-hover:visible group-hover:opacity-100"
>
<div class="text-[11px] leading-relaxed text-secondary">
{{ agentDescription }}
</div>
</div>
</div>
</div>
<button type="button" class="ml-2 shrink-0 text-muted transition-colors hover:text-secondary" @click="collapsed = true">
<PanelLeftClose class="h-5 w-5" />
</button>
</div>
<div class="px-4 pb-4">
<button type="button" class="chat-sidebar-btn" @click="onNewChat">
<Plus class="h-4 w-4" /> {{ $t('chat.createNewChat') }}
</button>
</div>
<div class="flex items-center justify-between px-4 py-2">
<span class="text-xs font-semibold text-slate-500 dark:text-slate-400">{{ $t('chat.history') }}</span>
<button
v-if="displayHistory.length > 0"
type="button"
class="text-xs text-slate-400 transition-colors hover:text-slate-600 dark:hover:text-slate-200"
@click="emit('clear-all-history')"
>
{{ $t('chat.clearAll') }}
</button>
</div>
<div class="scrollbar-thin flex-1 overflow-y-auto px-2">
<div v-if="displayHistory.length === 0" class="py-8 text-center text-sm italic text-slate-400">
{{ $t('chat.noHistory') }}
</div>
<div v-else class="space-y-0.5">
<div
v-for="item in displayHistory"
:key="item.conversation_id"
class="group relative flex w-full items-center justify-between rounded-lg transition-colors"
:class="activeHistoryKey === item.conversation_id ? 'bg-brand-50 dark:bg-brand-900/20' : 'hover:bg-slate-50 dark:hover:bg-slate-800/50'"
>
<button
type="button"
class="flex-1 truncate px-3 py-2.5 pr-8 text-left text-sm"
:class="activeHistoryKey === item.conversation_id
? 'font-medium text-brand-700 dark:text-brand-300'
: 'text-slate-600 dark:text-slate-300'"
@click="emit('history-select', item)"
>
{{ item.title || $t('chat.newChat') }}
</button>
<button
v-if="!item.__runId"
type="button"
class="absolute right-2 p-1.5 text-muted opacity-0 transition-opacity hover:text-red-500 group-hover:opacity-100"
:title="$t('chat.clearOneRecord')"
@click="emit('delete-history-item', item.conversation_id, $event)"
>
<X class="h-4 w-4" />
</button>
</div>
</div>
</div>
<div class="mt-auto flex flex-col p-4">
<div v-if="userAgents.length > 0 && agentPanelOpen" class="chat-agent-panel">
<div class="mb-2 flex items-center gap-1.5 text-xs font-semibold text-muted">
<LayoutGrid class="h-3.5 w-3.5" /> {{ $t('chat.agents') }}
</div>
<div class="grid grid-cols-2 gap-x-2 gap-y-1.5">
<button
v-for="agent in userAgents"
:key="agent.id"
type="button"
class="grid w-full min-w-0 grid-cols-[1rem_1fr] items-center gap-1.5 rounded-xl px-2 py-2 text-left text-xs font-medium text-secondary transition-colors hover-surface-soft hover:shadow-sm"
@click="emit('switch-agent', agent)"
>
<div
v-if="agent.icon_url"
class="h-4 w-4 shrink-0 rounded bg-contain bg-center bg-no-repeat"
:style="{ backgroundImage: `url(${agent.icon_url})` }"
/>
<div v-else class="flex h-4 w-4 shrink-0 items-center justify-center rounded bg-brand-100 text-[9px] font-bold text-brand-600">
{{ agent.name.charAt(0) }}
</div>
<span class="min-w-0 truncate">{{ agent.name }}</span>
</button>
</div>
</div>
<div ref="userMenuRef" class="relative flex items-center justify-between text-muted">
<button
type="button"
class="flex h-10 min-w-[2.5rem] items-center justify-center rounded-full bg-brand-600 px-3 text-sm font-bold text-white shadow-sm shadow-brand-500/20 transition-colors hover:bg-brand-700"
@click="showUserDropdown = !showUserDropdown"
>
退出
</button>
<div
v-if="showUserDropdown"
class="absolute bottom-full left-0 z-50 mb-2 w-56 animate-fade-in rounded-xl border border-subtle bg-surface py-1 shadow-xl"
>
<div class="flex items-center gap-3 border-b border-subtle px-4 py-3">
<div class="flex h-10 w-10 shrink-0 items-center justify-center rounded-full bg-brand-600 text-lg font-bold text-white shadow-sm shadow-brand-500/20">
{{ userInitial('U') }}
</div>
<div class="overflow-hidden">
<div class="truncate text-sm font-bold text-primary">{{ currentUser?.username || 'User' }}</div>
<div v-if="(currentUser as any)?.employee_id" class="truncate text-xs text-muted">
{{ $t('chat.employeeId') }}: {{ (currentUser as any).employee_id }}
</div>
<div v-else class="truncate text-xs text-muted">{{ currentUser?.role }}</div>
</div>
</div>
<button
v-if="currentUser?.role === 'admin'"
type="button"
class="flex w-full items-center gap-2 px-4 py-2 text-left text-sm text-secondary transition-colors hover:bg-surface-soft"
@click="onGoAdmin"
>
<Settings class="h-4 w-4" />
{{ $t('workspace.nav.admin') }}
</button>
<button
type="button"
class="flex w-full items-center gap-2 border-t border-subtle px-4 py-2 text-left text-sm text-red-600 transition-colors hover:bg-red-50"
@click="onLogout"
>
<LogOut class="h-4 w-4" />
{{ $t('chat.logout') }}
</button>
</div>
<div class="flex gap-3">
<button
type="button"
:class="agentPanelOpen && userAgents.length > 0 ? 'text-brand-600' : ''"
class="transition-colors hover:text-secondary"
:title="userAgents.length === 0 ? $t('chat.noAvailableAgents') : (agentPanelOpen ? $t('chat.collapseAgents') : $t('chat.expandAgents'))"
@click="userAgents.length === 0 ? undefined : (agentPanelOpen = !agentPanelOpen)"
>
<LayoutGrid class="h-4 w-4" />
</button>
<button
type="button"
class="transition-colors hover:text-secondary"
:title="appliedTheme === 'dark' ? ($t('theme.switchToLight') || 'Switch to light mode') : ($t('theme.switchToDark') || 'Switch to dark mode')"
@click="emit('toggle-theme')"
>
<Sun v-if="appliedTheme === 'dark'" class="h-4 w-4" />
<Moon v-else class="h-4 w-4" />
</button>
<LocaleToggleButton variant="sidebar" />
<button type="button" class="transition-colors hover:text-secondary" :title="$t('chat.generalFeedback')" @click="emit('open-feedback')">
<MessageSquareText class="h-4 w-4" />
</button>
<button type="button" class="transition-colors hover:text-secondary" :title="$t('workspace.title')" @click="emit('go-workspace')">
<Briefcase class="h-4 w-4" />
</button>
</div>
</div>
</div>
</template>
</aside>
</template>
@@ -0,0 +1,16 @@
/**
* features/chat/components/ChatThinkingBubble.vue
* Agent 思考中占位气泡。
*/
<template>
<div class="mx-auto flex w-full max-w-4xl justify-start">
<div class="flex items-center gap-3 rounded-2xl rounded-tl-md border border-default bg-surface/95 px-5 py-3 shadow-md">
<div class="flex gap-1">
<span class="h-2 w-2 animate-bounce rounded-full bg-brand-400" />
<span class="h-2 w-2 animate-bounce rounded-full bg-brand-400 delay-75" />
<span class="h-2 w-2 animate-bounce rounded-full bg-brand-400 delay-150" />
</div>
<span class="text-sm font-medium text-muted">{{ $t('chat.thinking') }}</span>
</div>
</div>
</template>
@@ -0,0 +1,157 @@
/**
* features/chat/components/ChatViewContent.vue
* 对话页主区域:侧栏、消息列表、输入栏与内置浏览器。
*/
<script setup lang="ts">
import { Loader2 } from 'lucide-vue-next';
import ChatShell from '@/shared/layouts/ChatShell.vue';
import ChatSidebar from '@/features/chat/components/ChatSidebar.vue';
import ChatInputBar from '@/features/chat/components/ChatInputBar.vue';
import ChatMessageList from '@/features/chat/components/ChatMessageList.vue';
import ChatMobileHeader from '@/features/chat/components/ChatMobileHeader.vue';
import ChatBrowserPanel from '@/features/chat/components/ChatBrowserPanel.vue';
import { useChatPageContext } from '@/features/chat/composables/chat.context';
const page = useChatPageContext();
</script>
<template>
<ChatShell>
<template #overlay>
<div
v-if="page.isSidebarOpen && !page.isMobile"
class="fixed inset-0 z-40 bg-overlay backdrop-blur-sm transition-opacity md:hidden"
@click="page.isSidebarOpen = false"
/>
</template>
<template #sidebar>
<ChatSidebar
v-if="!page.isMobile"
v-model:collapsed="page.sidebarCollapsed"
v-model:agent-panel-open="page.showAgentPanel"
:is-open="page.isSidebarOpen"
:current-agent="page.currentAgent"
:agent-description="page.agentDescription"
:has-agent-guides="page.agentGuides.length > 0"
:display-history="page.displayHistory"
:active-history-key="page.activeHistoryKey"
:user-agents="page.userAgents"
:current-user="page.currentUser"
:applied-theme="page.appliedTheme"
@new-chat="page.handleSidebarNewChat"
@open-guide="page.openGuideModal"
@history-select="page.handleHistorySelect"
@clear-all-history="page.clearAllHistory"
@delete-history-item="page.deleteHistoryItem"
@switch-agent="page.switchToAgent"
@toggle-theme="page.toggleLightDark"
@open-feedback="page.showGeneralFeedbackDialog = true"
@go-workspace="page.goToWorkspace()"
@go-admin="page.goToAdmin"
@logout="page.handleLogout"
/>
</template>
<ChatMobileHeader
v-if="page.isMobile && page.currentAgent"
:agent-name="page.currentAgent?.name || 'AI'"
:has-agent-guides="page.agentGuides.length > 0"
:user-agents="page.userAgents"
@open-guide="page.openGuideModal"
@go-history="page.goToWorkspace('history')"
@open-agent-popover="page.loadUserAgents"
@switch-agent="page.switchToAgent"
/>
<div v-if="!page.currentAgent" class="flex flex-1 flex-col items-center justify-center space-y-4">
<Loader2 class="h-10 w-10 animate-spin text-brand-500" />
<p class="text-sm animate-pulse text-muted">{{ $t('chat.loadingAgent') }}</p>
</div>
<div v-else-if="page.currentAgent.type === 'iframe'" class="relative h-full w-full flex-1">
<iframe
:src="page.currentAgent.extra_config?.iframe_url"
class="h-full w-full border-0 bg-surface"
allow="microphone; camera; clipboard-read; clipboard-write"
/>
</div>
<template v-else>
<div class="flex min-h-0 flex-1">
<div class="flex min-h-0 flex-1 flex-col">
<ChatMessageList
:messages="page.messages"
:agent-name="page.currentAgent?.name || 'AI'"
:suggested-questions-style="page.suggestedQuestionsStyle"
:styled-sections="page.styledSuggestedQuestionSections"
:suggested-questions="page.agentSuggestedQuestions"
:show-thinking-bubble="page.shouldShowThinkingBubble"
:is-thinking="page.isThinking"
:show-chat-rating="page.showChatRating"
:copied-index="page.copiedIndex"
:is-shipping-notice-agent="page.isShippingNoticeAgent"
:handlers="page.messageBubbleHandlers"
:leave-handlers="page.leaveMessageHandlers"
:shipping-handlers="page.shippingMappingHandlers"
:should-render-message="page.shouldRenderMessage"
:should-show-tool-run-progress-after-message="page.shouldShowToolRunProgressAfterMessage"
:tool-run-progress="page.toolRunProgress"
:tool-run-progress-loading="page.toolRunProgressLoading"
:tool-run-progress-error="page.toolRunProgressError"
:tool-run-progress-title="page.toolRunProgressTitle"
:scroll-container-holder="page.scrollContainerHolder"
@copy="page.copyToClipboard($event.message, $event.index)"
@edit="page.input = $event"
@resend="page.handleSend($event)"
@regenerate="page.regenerate"
@open-feedback="page.handleOpenFeedback($event)"
@select-question="page.handleSend"
/>
<ChatInputBar
v-model="page.input"
v-model:selected-kb="page.selectedKb"
:attachments="page.attachments"
:attachment-policy="page.attachmentPolicy"
:available-kb-options="page.availableKbOptions"
:kb-dropdown-disabled="page.kbDropdownDisabled"
:is-thinking="page.isThinking"
:is-voice-recording="page.isVoiceRecording"
:is-voice-transcribing="page.isVoiceTranscribing"
:is-uploading-attachments="page.isUploadingAttachments"
:can-send-message="page.canSendMessage"
:is-shipping-notice-agent="page.isShippingNoticeAgent"
:shipping-suggested-prompt="page.shippingSuggestedPrompt"
:shipping-picker-ref-holder="page.shippingPickerRefHolder"
:get-kb-label="page.getKbLabel"
:browser-panel-open="page.browserPanelOpen"
@toggle-browser="page.toggleBrowserPanel"
@send="page.handleSend()"
@voice-click="page.handleVoiceFeatureClick"
@remove-attachment="page.removeAttachment"
@local-files-selected="page.handleLocalFilesSelected"
@add-remote-url="page.addRemoteUrlAttachment"
@shipping-inventory-selected="page.handleShippingInventorySelected"
@use-shipping-suggested-prompt="page.useShippingSuggestedPrompt"
/>
</div>
<ChatBrowserPanel
v-model:open="page.browserPanelOpen"
v-model:draft-url="page.browserDraftUrl"
:current-url="page.browserCurrentUrl"
:frame-key="page.browserFrameKey"
:panel-style="page.browserPanelStyle"
:is-resizing="page.isBrowserResizing"
@load="page.browser.loadPage"
@refresh="page.browser.refreshPage"
@open-new-tab="page.browser.openInNewTab"
@url-enter="page.browser.onUrlEnter"
@start-resize="page.browser.startResize"
@close="page.browser.close"
/>
</div>
</template>
</ChatShell>
</template>
@@ -0,0 +1,84 @@
/**
* features/chat/components/ChatViewOverlays.vue
* 对话页全局弹窗:文件预览、反馈、查询预览、请假 OA、删除确认、学习之窗。
*/
<script setup lang="ts">
import FilePreviewModal from '@/shared/components/FilePreviewModal.vue';
import DeleteConfirmDialog from '@/shared/components/DeleteConfirmDialog.vue';
import GeneralFeedbackDialog from '@/shared/components/GeneralFeedbackDialog.vue';
import ChatQueryPreviewDialog from '@/features/chat/components/ChatQueryPreviewDialog.vue';
import ChatLeaveAgentDialog from '@/features/chat/components/ChatLeaveAgentDialog.vue';
import ChatOALoginDialog from '@/features/chat/components/ChatOALoginDialog.vue';
import ChatGuideModal from '@/features/chat/components/ChatGuideModal.vue';
import { useChatPageContext } from '@/features/chat/composables/chat.context';
import { getAuthHeaders } from '@/shared/utils/auth';
const page = useChatPageContext();
function onFeedbackSubmitted() {
const idx = page.activeFeedbackMessageIndex;
const target = idx !== null ? page.messages[idx] : undefined;
if (target) target.rated = true;
page.msg.success(page.t('chat.feedbackSubmitSuccess'));
page.showGeneralFeedbackDialog = false;
}
</script>
<template>
<FilePreviewModal
v-model="page.filePreviewVisible"
:file="page.previewFile"
:agent-id="page.currentAgentId"
:auth-headers="getAuthHeaders()"
/>
<GeneralFeedbackDialog
v-model="page.showGeneralFeedbackDialog"
:auth-headers="getAuthHeaders()"
source-page="chat"
:chat-log-id="page.currentGeneralFeedbackChatLogId"
@submitted="onFeedbackSubmitted"
/>
<ChatQueryPreviewDialog
v-model:open="page.showQueryPreviewDialog"
:loading="page.queryPreviewLoading"
:error="page.queryPreviewError"
:state="page.queryPreviewState"
@close="page.queryPreview.close"
@change-page="page.queryPreview.changePage"
/>
<ChatLeaveAgentDialog
v-model:open="page.showLeaveAgentDialog"
v-model:keyword="page.leaveAgentKeyword"
:select-role="page.leaveUserSelectRole"
:options="page.leaveAgentOptions"
:loading="page.leaveAgentLoading"
:page="page.leaveAgentPage"
:has-more="page.leaveAgentHasMore"
@close="page.closeLeaveAgentDialog"
@search="page.handleAgentSearch"
@load-more="page.loadMoreAgents"
@load-all="page.loadAllAgents"
@select="page.selectLeaveAgent"
/>
<ChatOALoginDialog
v-model:open="page.showOALoginDialog"
v-model:employee-id="page.oaLoginEmployeeId"
v-model:password="page.oaLoginPassword"
@confirm="page.confirmOALogin"
@cancel="page.cancelOALogin"
/>
<DeleteConfirmDialog
v-model="page.showDeleteConfirmDialog"
:message="page.deleteConfirmMessage"
@confirm="page.handleDeleteConfirm"
@cancel="page.closeDeleteConfirmDialog"
/>
<ChatGuideModal
v-model:open="page.showGuideModal"
v-model:active-guide-id="page.activeGuideId"
v-model:show-sidebar="page.showGuideSidebar"
:agent-name="page.currentAgent?.name || 'AI'"
:guides="page.agentGuides"
:active-guide="page.activeGuide"
/>
</template>
@@ -0,0 +1,115 @@
/**
* features/chat/components/ChatWelcomePanel.vue
* 无消息时的欢迎区:Agent 头像、标题与预设问题快捷入口。
*/
<script setup lang="ts">
import { computed } from 'vue';
import { useI18n } from 'vue-i18n';
import { Building, CalendarDays } from 'lucide-vue-next';
export interface WelcomeQuestionItem {
question: string;
group: string;
}
export interface WelcomeQuestionSection {
title: string;
questions: WelcomeQuestionItem[];
iconType: 'calendar' | 'building';
}
const props = defineProps<{
agentName: string;
suggestedQuestionsStyle: 'plain' | 'styled';
styledSections: WelcomeQuestionSection[];
suggestedQuestions: WelcomeQuestionItem[];
}>();
const emit = defineEmits<{
'select-question': [question: string];
}>();
const { t } = useI18n();
const avatarLabel = computed(() => (props.agentName === '人事规章' ? 'HR' : 'AI'));
const welcomeTitle = computed(() => (
props.agentName === '人事规章'
? '你好,我是人事规章 AI 助手'
: t('chat.welcomeTitle')
));
</script>
<template>
<div class="flex h-full min-h-0 w-full flex-col items-center px-4 pb-2 pt-2 md:pb-3">
<template v-if="suggestedQuestionsStyle === 'styled' && styledSections.length > 0">
<div class="mb-6 mt-2 flex h-16 w-16 shrink-0 items-center justify-center rounded-2xl bg-gradient-to-br from-brand-500 via-brand-600 to-sky-600 text-2xl font-bold text-white shadow-lg shadow-brand-500/20">
{{ avatarLabel }}
</div>
<h2 class="mb-6 shrink-0 text-center text-xl font-bold text-primary md:text-2xl">
{{ welcomeTitle }}
</h2>
<div class="min-h-0 w-full flex-1 overflow-y-auto pb-2">
<div class="mx-auto grid w-full max-w-4xl grid-cols-1 gap-4 md:grid-cols-2">
<div
v-for="(section, sectionIndex) in styledSections"
:key="`${section.title}-${sectionIndex}`"
class="w-full rounded-2xl border border-default bg-surface p-5 shadow-sm transition-colors hover:border-brand-300"
>
<div class="mb-3 flex items-center gap-2">
<div class="rounded-lg bg-brand-50 p-1.5 text-brand-600">
<CalendarDays v-if="section.iconType === 'calendar'" class="h-4 w-4" />
<Building v-else class="h-4 w-4" />
</div>
<h3 class="font-semibold text-secondary">{{ section.title }}</h3>
</div>
<div class="space-y-2">
<button
v-for="(item, questionIndex) in section.questions"
:key="`${section.title}-${questionIndex}`"
type="button"
class="w-full truncate rounded-lg bg-surface-soft px-3 py-2 text-left text-xs text-secondary transition-colors hover:bg-brand-50 hover:text-brand-600 md:text-sm"
@click="emit('select-question', item.question)"
>
"{{ item.question }}"
</button>
</div>
</div>
</div>
</div>
</template>
<template v-else-if="suggestedQuestions.length > 0">
<div class="mb-6 mt-2 flex h-16 w-16 shrink-0 items-center justify-center rounded-2xl bg-gradient-to-br from-brand-500 via-brand-600 to-sky-600 text-2xl font-bold text-white shadow-lg shadow-brand-500/20">
AI
</div>
<h2 class="mb-6 shrink-0 text-center text-xl font-medium text-primary md:text-2xl">
{{ $t('chat.welcomeTitle') }}
</h2>
<div class="min-h-0 w-full flex-1 overflow-y-auto pb-2">
<div class="mx-auto mt-2 flex w-full max-w-3xl flex-wrap justify-center gap-3">
<button
v-for="(item, index) in suggestedQuestions"
:key="`${item.question}-${index}`"
type="button"
class="rounded-full border border-default bg-surface px-4 py-2 text-sm text-secondary shadow-sm transition-all hover:border-brand-300 hover:bg-brand-50 hover:text-brand-600"
@click="emit('select-question', item.question)"
>
"{{ item.question }}"
</button>
</div>
</div>
</template>
<template v-else>
<div class="mb-6 mt-2 flex h-16 w-16 items-center justify-center rounded-2xl bg-gradient-to-br from-brand-500 via-brand-600 to-sky-600 text-2xl font-bold text-white shadow-lg shadow-brand-500/20">
AI
</div>
<h2 class="text-center text-xl font-medium text-primary md:text-2xl">
{{ $t('chat.welcomeTitle') }}
</h2>
</template>
</div>
</template>
@@ -2,7 +2,7 @@
import { ref } from 'vue';
import { AlertCircle, CheckCircle2, Clock3, Download, Loader2 } from 'lucide-vue-next';
import type { ToolRunProgress } from '@/api/toolRunProgress';
import { getAuthHeaders } from '@/utils/auth';
import { getAuthHeaders } from '@/shared/utils/auth';
const props = defineProps<{
run: ToolRunProgress | null;
@@ -0,0 +1,398 @@
/**
* features/chat/components/messages/ChatMessageBubble.vue
* 单条聊天消息:用户气泡、助手 Markdown、请假/出货子组件、来源引用与操作栏。
*/
<script setup lang="ts">
import { computed } from 'vue';
import { Check, Copy, Edit2, LayoutGrid, MessageSquareText, RotateCw } from 'lucide-vue-next';
import LeaveMessageBlock, { type LeaveMessageHandlers } from './LeaveMessageBlock.vue';
import ShippingInventoryMappingMessage, { type ShippingMappingHandlers } from './ShippingInventoryMappingMessage.vue';
import type { ChatMessage, SourceFileLink } from '../../types/chat.types';
import type { ShippingInventoryMappingFormPayload } from '../../types/shipping.types';
export interface ChatMessageBubbleHandlers {
renderMarkdown: (text: string) => string;
onMarkdownClick: (event: MouseEvent) => void;
getShippingInventoryMappingPayload: (msg: ChatMessage) => ShippingInventoryMappingFormPayload | null;
canOpenQueryPreview: (msg: ChatMessage) => boolean;
getQueryPreviewSummary: (msg: ChatMessage) => string;
openQueryPreviewDialog: (msg: ChatMessage) => void;
shippingActionButtonClass: (variant?: string) => string;
onShippingActionClick: (msg: ChatMessage, action: NonNullable<ChatMessage['shipping_actions']>[number]) => void;
getDisplayRetrieverResources: (msg: ChatMessage) => Array<Record<string, unknown>>;
getSourceLinks: (resources: Array<Record<string, unknown>>) => SourceFileLink[];
shouldExpandSourceDetails: (msg: ChatMessage) => boolean;
getSourceTitle: (doc: Record<string, unknown>) => string;
getSourceMeta: (doc: Record<string, unknown>) => string;
getSourceBrief: (doc: Record<string, unknown>) => string;
openPreview: (file: SourceFileLink) => void;
}
const {
message,
index,
messageCount,
isThinking,
showChatRating,
copiedIndex,
isShippingNoticeAgent,
handlers,
leaveHandlers,
shippingHandlers,
} = defineProps<{
message: ChatMessage;
index: number;
messageCount: number;
isThinking: boolean;
showChatRating: boolean;
copiedIndex: number | null;
isShippingNoticeAgent: boolean;
handlers: ChatMessageBubbleHandlers;
leaveHandlers: LeaveMessageHandlers;
shippingHandlers: ShippingMappingHandlers;
}>();
const emit = defineEmits<{
copy: [];
edit: [content: string];
resend: [content: string];
regenerate: [];
'open-feedback': [];
}>();
const isLeaveMessage = computed(() =>
message.type === 'leave-form'
|| message.type === 'leave-confirmation'
|| message.type === 'leave-result',
);
const retrieverResources = computed(() => handlers.getDisplayRetrieverResources(message));
const sourceLinks = computed(() => handlers.getSourceLinks(retrieverResources.value));
const showSourceSection = computed(() => {
if (message.role !== 'assistant' || isLeaveMessage.value) return false;
return retrieverResources.value.length > 0
|| (message.attribution_parts?.length ?? 0) > 0
|| sourceLinks.value.length > 0;
});
const showActions = computed(() => message.type !== 'leave-form');
const isLastMessage = computed(() => index === messageCount - 1);
const isCopied = computed(() => copiedIndex === index);
</script>
<template>
<div
:data-msg-index="index"
class="group mx-auto mb-6 flex w-full max-w-4xl animate-slide-up"
:class="message.role === 'user' ? 'justify-end' : 'justify-start'"
>
<div
class="flex flex-col"
:class="message.role === 'user' ? 'max-w-[88%] md:max-w-[74%] items-end' : 'w-full'"
>
<div
class="text-[15px] leading-relaxed"
:class="message.role === 'user'
? 'rounded-2xl rounded-tr-sm bg-brand-600 px-5 py-2.5 text-white shadow-sm shadow-brand-500/15'
: 'chat-msg-assistant'"
>
<div v-if="message.role === 'user'" class="whitespace-pre-wrap">{{ message.content }}</div>
<div v-else>
<LeaveMessageBlock
v-if="isLeaveMessage"
:message="message"
:index="index"
:handlers="leaveHandlers"
/>
<ShippingInventoryMappingMessage
v-else-if="message.type === 'shipping-inventory-mapping' && handlers.getShippingInventoryMappingPayload(message)"
:message="message"
:handlers="shippingHandlers"
/>
<div
v-else
class="chat-markdown prose prose-sm max-w-none leading-7 text-primary prose-a:text-blue-600 prose-p:my-1 prose-li:my-0.5 prose-ol:my-2 prose-ul:my-2 prose-headings:my-2 prose-hr:my-3 prose-code:rounded prose-code:bg-slate-100 prose-code:px-1 prose-code:text-blue-700 prose-pre:my-3 prose-pre:border prose-pre:border-slate-700 prose-pre:bg-slate-900 prose-pre:text-slate-100 prose-th:border prose-th:border-slate-200 prose-th:bg-slate-50 prose-th:px-3 prose-th:py-2 prose-th:text-left prose-td:border prose-td:border-slate-200 prose-td:px-3 prose-td:py-2"
@click="handlers.onMarkdownClick"
v-html="handlers.renderMarkdown(message.content)"
/>
<div
v-if="message.role === 'assistant' && handlers.canOpenQueryPreview(message)"
class="mt-4"
>
<button
type="button"
class="inline-flex items-center gap-2 rounded-xl border border-brand-200 bg-brand-50 px-3 py-2 text-xs font-medium text-brand-700 transition hover:bg-brand-100"
@click="handlers.openQueryPreviewDialog(message)"
>
<LayoutGrid class="h-3.5 w-3.5" />
{{ handlers.getQueryPreviewSummary(message) }}
</button>
</div>
<div
v-if="isShippingNoticeAgent && message.shipping_actions?.length"
class="mt-4 space-y-2 border-t border-default pt-4"
>
<div class="text-xs font-medium text-muted">{{ $t('chat.shippingNoticeActionsHint') }}</div>
<div class="flex flex-wrap gap-2">
<button
v-for="(action, actionIndex) in message.shipping_actions"
:key="`${message.local_id || index}-shipping-action-${action.id}-${actionIndex}`"
type="button"
:class="handlers.shippingActionButtonClass(action.variant)"
:disabled="isThinking || message.shipping_actions_used"
@click="handlers.onShippingActionClick(message, action)"
>
{{ action.label }}
</button>
</div>
</div>
</div>
</div>
<div v-if="showSourceSection" class="mt-2 space-y-2">
<div v-if="sourceLinks.length > 0" class="flex flex-wrap gap-2">
<button
v-for="(file, linkIndex) in sourceLinks"
:key="`src-link-top-${linkIndex}-${file.url}`"
type="button"
class="break-all rounded-lg border border-brand-200 bg-brand-50 px-2.5 py-1.5 text-xs text-brand-700 transition-colors hover:bg-brand-100"
@click="handlers.openPreview(file)"
>
{{ file.name }}
</button>
</div>
<details
v-if="retrieverResources.length > 0"
class="rounded-xl border border-default bg-surface-soft/90 px-4 py-3"
:open="handlers.shouldExpandSourceDetails(message)"
>
<summary class="cursor-pointer text-xs font-semibold uppercase tracking-wide text-secondary">
{{ $t('chat.sourceDocs') }} ({{ retrieverResources.length }})
</summary>
<div class="mt-3 space-y-2">
<div
v-for="(doc, docIndex) in retrieverResources"
:key="`${doc.document_name || 'doc'}-${doc.segment_id || docIndex}`"
class="rounded-lg border border-default bg-surface p-3"
>
<div class="break-all text-sm font-semibold text-primary">{{ handlers.getSourceTitle(doc) }}</div>
<div v-if="handlers.getSourceMeta(doc)" class="mt-1 text-xs text-muted">{{ handlers.getSourceMeta(doc) }}</div>
<div v-if="handlers.getSourceBrief(doc)" class="mt-2 whitespace-pre-wrap break-all text-xs text-secondary">
{{ handlers.getSourceBrief(doc) }}
</div>
</div>
</div>
</details>
<details
v-if="message.attribution_parts && message.attribution_parts.length > 0"
class="rounded-xl border border-default bg-surface-soft/90 px-4 py-3"
open
>
<summary class="cursor-pointer text-xs font-semibold uppercase tracking-wide text-secondary">
{{ $t('chat.attributionParts') }}
</summary>
<ul class="mt-3 space-y-2">
<li
v-for="(part, partIndex) in message.attribution_parts"
:key="`attr-${partIndex}`"
class="rounded-lg border border-default bg-surface p-3 text-xs text-secondary"
>
{{ part }}
</li>
</ul>
</details>
</div>
<div
v-if="showActions"
class="mt-1 flex items-center gap-1 opacity-0 transition-opacity group-hover:opacity-100"
:class="message.role === 'user' ? 'justify-end text-muted' : 'justify-start text-muted'"
>
<button
type="button"
class="rounded-md p-1.5 text-xs transition-colors hover-surface-soft"
:title="$t('chat.actions.copy')"
@click.stop="emit('copy')"
>
<Check v-if="isCopied" class="h-3.5 w-3.5 text-emerald-500" />
<Copy v-else class="h-3.5 w-3.5" />
</button>
<template v-if="message.role === 'user'">
<button
type="button"
class="rounded-md p-1.5 text-xs transition-colors hover-surface-soft"
:title="$t('chat.actions.edit')"
@click.stop="emit('edit', message.content)"
>
<Edit2 class="h-3.5 w-3.5" />
</button>
<button
type="button"
class="rounded-md p-1.5 text-xs transition-colors hover-surface-soft"
:title="$t('chat.actions.resend')"
@click.stop="emit('resend', message.content)"
>
<RotateCw class="h-3.5 w-3.5" />
</button>
</template>
<template v-else>
<button
v-if="isLastMessage && !isThinking"
type="button"
class="rounded-md p-1.5 text-xs transition-colors hover-surface-soft"
:title="$t('chat.actions.regenerate')"
@click="emit('regenerate')"
>
<RotateCw class="h-3.5 w-3.5" />
</button>
<button
v-if="showChatRating && !isThinking && !message.rated"
type="button"
class="rounded-md p-1.5 text-xs transition-colors hover-surface-soft"
:title="$t('chat.rate')"
@click="emit('open-feedback')"
>
<MessageSquareText class="h-3.5 w-3.5" />
</button>
</template>
</div>
</div>
</div>
</template>
<style scoped>
:deep(.chat-markdown) {
max-width: 100%;
}
:deep(.chat-markdown .chat-table-scroll) {
max-width: 100%;
overflow-x: auto;
overflow-y: hidden;
margin: 0.75rem 0;
-webkit-overflow-scrolling: touch;
}
:deep(.chat-markdown .chat-table-inner) {
width: max-content;
min-width: 100%;
}
:deep(.chat-markdown table) {
width: max-content;
min-width: 100%;
border-collapse: collapse;
margin: 0;
font-size: 0.875rem;
}
:deep(.chat-markdown th),
:deep(.chat-markdown td) {
border: 1px solid rgb(226 232 240);
padding: 0.5rem 0.75rem;
text-align: left;
vertical-align: top;
white-space: nowrap;
}
:deep(.chat-markdown th) {
background: rgb(248 250 252);
font-weight: 600;
}
:deep(.dark .chat-markdown th),
:deep(.dark .chat-markdown td) {
border-color: rgb(51 65 85);
}
:deep(.dark .chat-markdown th) {
background: rgb(30 41 59);
}
:deep(.chat-markdown details) {
margin-top: 1rem;
border: 1px solid rgb(226 232 240);
border-radius: 0.75rem;
background: rgb(248 250 252 / 0.9);
padding: 0.75rem 1rem;
}
:deep(.dark .chat-markdown details) {
border-color: rgb(51 65 85);
background: rgb(30 41 59 / 0.65);
}
:deep(.chat-markdown details summary) {
cursor: pointer;
font-size: 0.75rem;
font-weight: 600;
letter-spacing: 0.08em;
color: rgb(71 85 105);
list-style-position: inside;
}
:deep(.dark .chat-markdown details summary) {
color: rgb(203 213 225);
}
:deep(.chat-markdown details[open] summary) {
margin-bottom: 0.75rem;
}
:deep(.chat-markdown details pre) {
margin-bottom: 0;
}
:deep(.chat-markdown .leave-action-trigger) {
display: inline-flex;
align-items: center;
justify-content: center;
margin: 0 0.2rem;
padding: 0.1rem 0.6rem;
border-radius: 9999px;
border: 1px solid rgb(59 130 246 / 0.28);
background: rgb(239 246 255);
color: rgb(29 78 216);
font-weight: 600;
text-decoration: none;
cursor: pointer;
transition: all 0.2s ease;
}
:deep(.chat-markdown .leave-action-trigger:hover) {
background: rgb(219 234 254);
border-color: rgb(59 130 246 / 0.4);
}
:deep(.chat-markdown .leave-intent-highlight) {
display: inline-block;
margin: 0 0.2rem;
padding: 0.05rem 0.4rem;
border-radius: 0.5rem;
background: rgb(254 249 195);
color: rgb(161 98 7);
font-weight: 600;
}
:deep(.dark .chat-markdown .leave-action-trigger) {
border-color: rgb(96 165 250 / 0.35);
background: rgb(30 41 59);
color: rgb(147 197 253);
}
:deep(.dark .chat-markdown .leave-action-trigger:hover) {
background: rgb(30 64 175 / 0.25);
}
:deep(.dark .chat-markdown .leave-intent-highlight) {
background: rgb(113 63 18 / 0.45);
color: rgb(253 224 71);
}
</style>
@@ -0,0 +1,272 @@
/**
* features/chat/components/messages/LeaveMessageBlock.vue
* 请假 OA 消息 UI(表单/确认/结果)。
*/
<script setup lang="ts">
import { Search } from 'lucide-vue-next';
import { LEAVE_TYPES } from '../../constants/leave';
import type { ChatMessage } from '../../types/chat.types';
import type {
LeaveConfirmationPayload,
LeaveFormPayload,
LeaveRequestFormData,
LeaveResultPayload,
} from '../../types/leave.types';
export interface LeaveMessageHandlers {
getLeaveFormPayload: (msg: ChatMessage) => LeaveFormPayload | null;
getLeaveConfirmationPayload: (msg: ChatMessage) => LeaveConfirmationPayload | null;
getLeaveResultPayload: (msg: ChatMessage) => LeaveResultPayload | null;
getLeaveAgentDisplayValue: (form: LeaveRequestFormData) => string;
getLeaveTypeLabel: (val: string) => string;
formatDurationLabel: (hours: number, leaveType?: string) => string;
formatYesNoLabel: (value: 0 | 1 | null) => string;
syncLeaveDuration: (form: LeaveRequestFormData) => void;
openLeaveAgentDialog: (msg: ChatMessage, role?: 'agent' | 'applicant') => void;
openOALeaveRequestDirectly: () => void;
openOARequestDirectly: (requestId: string) => void;
submitLeaveForm: (msg: ChatMessage) => void;
editLeaveConfirmation: (msg: ChatMessage, index: number) => void;
confirmLeaveSubmission: (msg: ChatMessage) => void;
}
const { message, index, handlers } = defineProps<{
message: ChatMessage;
index: number;
handlers: LeaveMessageHandlers;
}>();
</script>
<template>
<div v-if="message.type === 'leave-form'" class="space-y-4">
<div class="text-sm font-medium text-secondary">
{{ $t('chat.leaveFormIntro') }} <a href="#" @click.prevent="handlers.openOALeaveRequestDirectly" class="text-brand-600 font-bold hover:underline">{{ $t('chat.oaLeaveDirectLink') }}</a>
</div>
<div v-if="handlers.getLeaveFormPayload(message)" class="grid gap-4 md:grid-cols-2">
<label class="space-y-1.5">
<span class="text-xs font-semibold text-muted">{{ $t('chat.leaveFiller') }}</span>
<input
v-model="handlers.getLeaveFormPayload(message)!.form.fillerName"
type="text"
class="w-full rounded-xl border border-default bg-surface-soft px-3 py-2 text-sm text-muted outline-none"
disabled
/>
</label>
<label class="space-y-1.5">
<span class="text-xs font-semibold text-muted">{{ $t('chat.employeeId') }}</span>
<input
v-model="handlers.getLeaveFormPayload(message)!.form.employeeId"
type="text"
class="w-full rounded-xl border border-default bg-surface-soft px-3 py-2 text-sm text-muted outline-none"
disabled
/>
</label>
<label class="space-y-1.5">
<span class="text-xs font-semibold text-muted">{{ $t('chat.createdAt') }}</span>
<input
:value="handlers.getLeaveFormPayload(message)!.form.applyTime.replace('T', ' ')"
type="text"
class="w-full rounded-xl border border-default bg-surface-soft px-3 py-2 text-sm text-muted outline-none"
disabled
/>
</label>
<label class="space-y-1.5">
<span class="text-xs font-semibold text-muted">{{ $t('chat.leaveType') }}</span>
<select
v-model="handlers.getLeaveFormPayload(message)!.form.leaveType"
class="w-full rounded-xl border border-default px-3 py-2 text-sm text-secondary outline-none transition focus:border-blue-400"
:disabled="handlers.getLeaveFormPayload(message)!.submitting || handlers.getLeaveFormPayload(message)!.confirmationGenerated"
@change="handlers.syncLeaveDuration(handlers.getLeaveFormPayload(message)!.form)"
>
<option value="" disabled>{{ $t('chat.selectLeaveType') }}</option>
<option v-for="leaveType in LEAVE_TYPES" :key="leaveType.value" :value="leaveType.value">{{ leaveType.label }}</option>
</select>
</label>
<label class="space-y-1.5">
<span class="text-xs font-semibold text-muted">{{ $t('chat.leaveApplicant') }}</span>
<div class="relative">
<input
:value="handlers.getLeaveFormPayload(message)!.form.applicantName ? `${handlers.getLeaveFormPayload(message)!.form.applicantName} / ${handlers.getLeaveFormPayload(message)!.form.employeeId}` : ''"
type="text"
:placeholder="$t('chat.selectLeaveApplicant')"
readonly
class="w-full rounded-xl border border-default bg-surface px-3 py-2 pr-11 text-sm text-secondary outline-none transition focus:border-blue-400"
:disabled="handlers.getLeaveFormPayload(message)!.submitting || handlers.getLeaveFormPayload(message)!.confirmationGenerated"
@click="handlers.openLeaveAgentDialog(message, 'applicant')"
/>
<button
type="button"
class="absolute inset-y-0 right-0 flex w-11 items-center justify-center text-muted transition hover:text-brand-600 disabled:cursor-not-allowed disabled:opacity-50"
:disabled="handlers.getLeaveFormPayload(message)!.submitting || handlers.getLeaveFormPayload(message)!.confirmationGenerated"
@click="handlers.openLeaveAgentDialog(message, 'applicant')"
:title="$t('chat.pickLeaveApplicant')"
>
<Search class="h-4 w-4" />
</button>
</div>
</label>
<label class="space-y-1.5">
<span class="text-xs font-semibold text-muted">{{ $t('chat.leaveAgent') }}</span>
<div class="relative">
<input
:value="handlers.getLeaveAgentDisplayValue(handlers.getLeaveFormPayload(message)!.form)"
type="text"
:placeholder="$t('chat.selectLeaveAgent')"
readonly
class="w-full rounded-xl border border-default bg-surface px-3 py-2 pr-11 text-sm text-secondary outline-none transition focus:border-blue-400"
:disabled="handlers.getLeaveFormPayload(message)!.submitting || handlers.getLeaveFormPayload(message)!.confirmationGenerated"
@click="handlers.openLeaveAgentDialog(message)"
/>
<button
type="button"
class="absolute inset-y-0 right-0 flex w-11 items-center justify-center text-muted transition hover:text-brand-600 disabled:cursor-not-allowed disabled:opacity-50"
:disabled="handlers.getLeaveFormPayload(message)!.submitting || handlers.getLeaveFormPayload(message)!.confirmationGenerated"
@click="handlers.openLeaveAgentDialog(message)"
:title="$t('chat.pickLeaveAgent')"
>
<Search class="h-4 w-4" />
</button>
</div>
</label>
<label class="space-y-1.5">
<span class="text-xs font-semibold text-muted">{{ $t('chat.startTime') }}</span>
<input
v-model="handlers.getLeaveFormPayload(message)!.form.startTime"
type="datetime-local"
class="w-full rounded-xl border border-default px-3 py-2 text-sm text-secondary outline-none transition focus:border-blue-400"
:disabled="handlers.getLeaveFormPayload(message)!.submitting || handlers.getLeaveFormPayload(message)!.confirmationGenerated"
@input="handlers.syncLeaveDuration(handlers.getLeaveFormPayload(message)!.form)"
/>
</label>
<label class="space-y-1.5">
<span class="text-xs font-semibold text-muted">{{ $t('chat.endTime') }}</span>
<input
v-model="handlers.getLeaveFormPayload(message)!.form.endTime"
type="datetime-local"
class="w-full rounded-xl border border-default px-3 py-2 text-sm text-secondary outline-none transition focus:border-blue-400"
:disabled="handlers.getLeaveFormPayload(message)!.submitting || handlers.getLeaveFormPayload(message)!.confirmationGenerated"
@input="handlers.syncLeaveDuration(handlers.getLeaveFormPayload(message)!.form)"
/>
</label>
<label class="space-y-1.5">
<span class="text-xs font-semibold text-muted">{{ $t('chat.duration') }}</span>
<input
:value="handlers.formatDurationLabel(handlers.getLeaveFormPayload(message)!.form.durationHours, handlers.getLeaveFormPayload(message)!.form.leaveType)"
type="text"
class="w-full rounded-xl border border-default bg-surface-soft px-3 py-2 text-sm text-muted outline-none"
disabled
/>
</label>
<label class="space-y-1.5">
<span class="text-xs font-semibold text-muted">{{ $t('chat.isOutOfOffice') }}</span>
<select
v-model="handlers.getLeaveFormPayload(message)!.form.isOutOfOffice"
class="w-full rounded-xl border border-default px-3 py-2 text-sm text-secondary outline-none transition focus:border-blue-400"
:disabled="handlers.getLeaveFormPayload(message)!.submitting || handlers.getLeaveFormPayload(message)!.confirmationGenerated"
>
<option :value="1">{{ $t('chat.no') }}</option>
<option :value="0">{{ $t('chat.yes') }}</option>
</select>
</label>
<label class="space-y-1.5 md:col-span-2">
<span class="text-xs font-semibold text-muted">{{ $t('chat.isWorkInjury') }}</span>
<select
v-model="handlers.getLeaveFormPayload(message)!.form.isWorkInjury"
class="w-full rounded-xl border border-default px-3 py-2 text-sm text-secondary outline-none transition focus:border-blue-400"
:disabled="handlers.getLeaveFormPayload(message)!.submitting || handlers.getLeaveFormPayload(message)!.confirmationGenerated"
>
<option :value="1">{{ $t('chat.no') }}</option>
<option :value="0">{{ $t('chat.yes') }}</option>
</select>
</label>
</div>
<div v-if="handlers.getLeaveFormPayload(message)?.confirmationGenerated" class="rounded-xl border border-amber-200 bg-amber-50 px-4 py-3 text-xs text-amber-700">
{{ $t('chat.leaveConfirmGenerated') }}
</div>
<div class="flex justify-end">
<button
@click="handlers.submitLeaveForm(message)"
:disabled="handlers.getLeaveFormPayload(message)?.submitting || handlers.getLeaveFormPayload(message)?.confirmationGenerated"
class="btn-primary btn-sm disabled:cursor-not-allowed disabled:opacity-60"
>
{{ handlers.getLeaveFormPayload(message)?.submitting ? $t('chat.submitting') : $t('chat.submit') }}
</button>
</div>
</div>
<div v-else-if="message.type === 'leave-confirmation' && handlers.getLeaveConfirmationPayload(message)" class="space-y-4">
<div class="text-sm font-medium text-secondary">{{ message.content }}</div>
<div class="rounded-2xl border border-default bg-surface-soft/90 p-4">
<div class="mb-3 text-xs font-bold uppercase tracking-wider text-muted">{{ $t('chat.leaveFillerInfo') }}</div>
<div class="grid gap-3 text-sm md:grid-cols-2">
<div><span class="text-muted">{{ $t('chat.leaveFiller') }}:</span>{{ handlers.getLeaveConfirmationPayload(message)!.form.fillerName || $t('chat.noData') }}</div>
<div><span class="text-muted">{{ $t('chat.createdAt') }}:</span>{{ handlers.getLeaveConfirmationPayload(message)!.form.applyTime.replace('T', ' ') }}</div>
<div v-if="handlers.getLeaveConfirmationPayload(message)!.form.fillerJobTitleName || handlers.getLeaveConfirmationPayload(message)!.form.fillerJobTitle"><span class="text-muted">{{ $t('chat.leaveFillerTitle') }}:</span>{{ handlers.getLeaveConfirmationPayload(message)!.form.fillerJobTitleName || handlers.getLeaveConfirmationPayload(message)!.form.fillerJobTitle }}</div>
<div v-if="handlers.getLeaveConfirmationPayload(message)!.form.fillerDepartmentName || handlers.getLeaveConfirmationPayload(message)!.form.fillerDepartmentId"><span class="text-muted">{{ $t('chat.leaveFillerDept') }}:</span>{{ handlers.getLeaveConfirmationPayload(message)!.form.fillerDepartmentName || handlers.getLeaveConfirmationPayload(message)!.form.fillerDepartmentId }}</div>
<div v-if="handlers.getLeaveConfirmationPayload(message)!.form.fillerSubCompanyName || handlers.getLeaveConfirmationPayload(message)!.form.fillerSubCompanyId1"><span class="text-muted">{{ $t('chat.leaveFillerCompany') }}:</span>{{ handlers.getLeaveConfirmationPayload(message)!.form.fillerSubCompanyName || handlers.getLeaveConfirmationPayload(message)!.form.fillerSubCompanyId1 }}</div>
</div>
<div class="my-3 border-t border-default"></div>
<div class="mb-3 text-xs font-bold uppercase tracking-wider text-muted">{{ $t('chat.leaveApplicantInfo') }}</div>
<div class="grid gap-3 text-sm md:grid-cols-2">
<div><span class="text-muted">{{ $t('chat.leaveApplicant') }}:</span>{{ handlers.getLeaveConfirmationPayload(message)!.form.applicantName }}({{ handlers.getLeaveConfirmationPayload(message)!.form.employeeId }})</div>
<div v-if="handlers.getLeaveConfirmationPayload(message)!.form.applicantJobTitleName || handlers.getLeaveConfirmationPayload(message)!.form.applicantJobTitle"><span class="text-muted">{{ $t('chat.leaveApplicantTitle') }}:</span>{{ handlers.getLeaveConfirmationPayload(message)!.form.applicantJobTitleName || handlers.getLeaveConfirmationPayload(message)!.form.applicantJobTitle }}</div>
<div v-if="handlers.getLeaveConfirmationPayload(message)!.form.applicantDepartmentName || handlers.getLeaveConfirmationPayload(message)!.form.applicantDepartmentId"><span class="text-muted">{{ $t('chat.leaveApplicantDept') }}:</span>{{ handlers.getLeaveConfirmationPayload(message)!.form.applicantDepartmentName || handlers.getLeaveConfirmationPayload(message)!.form.applicantDepartmentId }}</div>
<div v-if="handlers.getLeaveConfirmationPayload(message)!.form.applicantSubCompanyName || handlers.getLeaveConfirmationPayload(message)!.form.applicantSubCompanyId1"><span class="text-muted">{{ $t('chat.leaveApplicantCompany') }}:</span>{{ handlers.getLeaveConfirmationPayload(message)!.form.applicantSubCompanyName || handlers.getLeaveConfirmationPayload(message)!.form.applicantSubCompanyId1 }}</div>
</div>
<div class="my-3 border-t border-default"></div>
<div class="mb-3 text-xs font-bold uppercase tracking-wider text-muted">{{ $t('chat.leaveInfo') }}</div>
<div class="grid gap-3 text-sm md:grid-cols-2">
<div><span class="text-muted">{{ $t('chat.leaveAgent') }}:</span>{{ handlers.getLeaveAgentDisplayValue(handlers.getLeaveConfirmationPayload(message)!.form) || $t('chat.notSelected') }}</div>
<div v-if="handlers.getLeaveConfirmationPayload(message)!.form.agentJobTitleName || handlers.getLeaveConfirmationPayload(message)!.form.agentJobTitle"><span class="text-muted">{{ $t('chat.leaveAgentTitle') }}:</span>{{ handlers.getLeaveConfirmationPayload(message)!.form.agentJobTitleName || handlers.getLeaveConfirmationPayload(message)!.form.agentJobTitle }}</div>
<div v-if="handlers.getLeaveConfirmationPayload(message)!.form.agentDepartmentName || handlers.getLeaveConfirmationPayload(message)!.form.agentDepartmentId"><span class="text-muted">{{ $t('chat.leaveAgentDept') }}:</span>{{ handlers.getLeaveConfirmationPayload(message)!.form.agentDepartmentName || handlers.getLeaveConfirmationPayload(message)!.form.agentDepartmentId }}</div>
<div v-if="handlers.getLeaveConfirmationPayload(message)!.form.agentSubCompanyName || handlers.getLeaveConfirmationPayload(message)!.form.agentSubCompanyId1"><span class="text-muted">{{ $t('chat.leaveAgentCompany') }}:</span>{{ handlers.getLeaveConfirmationPayload(message)!.form.agentSubCompanyName || handlers.getLeaveConfirmationPayload(message)!.form.agentSubCompanyId1 }}</div>
<div><span class="text-muted">{{ $t('chat.leaveType') }}:</span>{{ handlers.getLeaveTypeLabel(handlers.getLeaveConfirmationPayload(message)!.form.leaveType) }}</div>
<div><span class="text-muted">{{ $t('chat.duration') }}:</span>{{ handlers.formatDurationLabel(handlers.getLeaveConfirmationPayload(message)!.form.durationHours, handlers.getLeaveConfirmationPayload(message)!.form.leaveType) }}</div>
<div><span class="text-muted">{{ $t('chat.startTime') }}:</span>{{ handlers.getLeaveConfirmationPayload(message)!.form.startTime.replace('T', ' ') }}</div>
<div><span class="text-muted">{{ $t('chat.endTime') }}:</span>{{ handlers.getLeaveConfirmationPayload(message)!.form.endTime.replace('T', ' ') }}</div>
<div><span class="text-muted">{{ $t('chat.isOutOfOffice') }}:</span>{{ handlers.formatYesNoLabel(handlers.getLeaveConfirmationPayload(message)!.form.isOutOfOffice) }}</div>
<div><span class="text-muted">{{ $t('chat.isWorkInjury') }}:</span>{{ handlers.formatYesNoLabel(handlers.getLeaveConfirmationPayload(message)!.form.isWorkInjury) }}</div>
</div>
</div>
<div class="flex justify-end gap-3">
<button
v-if="!handlers.getLeaveConfirmationPayload(message)?.submitting && !handlers.getLeaveConfirmationPayload(message)?.confirmed"
@click="handlers.editLeaveConfirmation(message, index)"
class="rounded-xl border border-default px-4 py-2 text-sm font-medium text-secondary transition hover:bg-surface-soft disabled:cursor-not-allowed disabled:opacity-60"
>
{{ $t('chat.backToEdit') }}
</button>
<button
@click="handlers.confirmLeaveSubmission(message)"
:disabled="handlers.getLeaveConfirmationPayload(message)?.submitting || handlers.getLeaveConfirmationPayload(message)?.confirmed"
class="rounded-xl bg-emerald-600 px-4 py-2 text-sm font-medium text-white transition hover:bg-emerald-700 disabled:cursor-not-allowed disabled:opacity-60"
>
{{ handlers.getLeaveConfirmationPayload(message)?.submitting ? $t('chat.confirming') : (handlers.getLeaveConfirmationPayload(message)?.confirmed ? $t('chat.confirmed') : $t('chat.confirm')) }}
</button>
</div>
</div>
<div v-else-if="message.type === 'leave-result' && handlers.getLeaveResultPayload(message)" class="space-y-3">
<div
class="rounded-2xl border px-4 py-4"
:class="handlers.getLeaveResultPayload(message)!.success
? 'border-emerald-200 bg-emerald-50 text-emerald-800'
: 'border-rose-200 bg-rose-50 text-rose-800'"
>
<div class="text-sm font-semibold">{{ handlers.getLeaveResultPayload(message)!.success ? $t('chat.oaSubmitResult') : $t('chat.oaSubmitFailed') }}</div>
<div v-if="handlers.getLeaveResultPayload(message)!.success" class="mt-2 whitespace-pre-wrap text-sm leading-7">
{{ $t('chat.leaveResultPrefix') }}
<a
href="#"
@click.prevent="handlers.openOARequestDirectly(handlers.getLeaveResultPayload(message)!.referenceNo)"
class="ml-1 inline-flex items-center rounded-full border border-brand-200 bg-brand-50 px-3 py-0.5 font-bold text-brand-700 transition hover:bg-brand-100 hover:underline"
>
{{ $t('chat.leaveResultLinkText') }}
</a>
</div>
<div v-else class="mt-2 whitespace-pre-wrap text-sm leading-7">{{ message.content }}</div>
<div class="mt-3 text-xs opacity-80">{{ $t('chat.requestNo') }}:{{ handlers.getLeaveResultPayload(message)!.referenceNo }}</div>
<div class="mt-1 text-xs opacity-80">{{ $t('chat.submitTime') }}:{{ handlers.getLeaveResultPayload(message)!.submittedAt }}</div>
</div>
</div>
</template>
@@ -0,0 +1,111 @@
/**
* features/chat/components/messages/ShippingInventoryMappingMessage.vue
* 出货 Agent:库存 Excel 列映射表单消息 UI。
*/
<script setup lang="ts">
import type { ChatMessage } from '../../types/chat.types';
import type { ShippingInventoryMappingFormPayload } from '../../types/shipping.types';
export interface ShippingMappingHandlers {
getPayload: (msg: ChatMessage) => ShippingInventoryMappingFormPayload | null;
normalizeHeader: (header: string) => string;
hasSampleRows: (msg: ChatMessage) => boolean;
getSampleRowText: (msg: ChatMessage) => string;
reupload: (msg: ChatMessage) => void;
apply: (msg: ChatMessage) => void;
}
const { message, handlers } = defineProps<{
message: ChatMessage;
handlers: ShippingMappingHandlers;
}>();
</script>
<template>
<div v-if="handlers.getPayload(message)" class="space-y-4">
<div class="whitespace-pre-wrap text-sm font-medium text-secondary">{{ message.content }}</div>
<div class="space-y-4 rounded-2xl border border-default bg-surface-soft/90 p-4">
<div class="space-y-2">
<div class="text-xs font-bold uppercase tracking-wider text-muted">{{ $t('chat.shippingNoticeMapping.inventoryHeaders') }}</div>
<div class="text-xs text-muted">
{{ $t('chat.shippingNoticeMapping.headerRow', { row: handlers.getPayload(message)!.schema_preview.header_row_index || 1 }) }}
</div>
<div class="flex flex-wrap gap-2">
<span
v-for="h in (handlers.getPayload(message)!.schema_preview.headers || [])"
:key="`inv-h-${h}`"
class="rounded-full border border-default bg-surface px-3 py-1 text-xs text-secondary"
>{{ handlers.normalizeHeader(h) || $t('chat.shippingNoticeMapping.empty') }}</span>
</div>
<div
v-if="handlers.hasSampleRows(message)"
class="whitespace-pre-wrap text-xs text-muted"
>
{{ $t('chat.shippingNoticeMapping.sample') }}:{{ handlers.getSampleRowText(message) }}
</div>
</div>
<div class="space-y-2">
<div class="text-xs font-bold uppercase tracking-wider text-muted">{{ $t('chat.shippingNoticeMapping.orderDetails') }}</div>
<div class="text-xs text-muted">
{{ $t('chat.shippingNoticeMapping.orderRowCount', { count: handlers.getPayload(message)!.order.line_count }) }};{{ $t('chat.shippingNoticeMapping.orderSkuPreview', { count: handlers.getPayload(message)!.order.skus.length, skus: handlers.getPayload(message)!.order.skus.join(',') || $t('chat.shippingNoticeMapping.unrecognized') }) }}
</div>
</div>
<div class="grid gap-4 md:grid-cols-2">
<label class="space-y-1.5">
<span class="text-xs font-semibold text-muted">{{ $t('chat.shippingNoticeMapping.skuColumnRequired') }}</span>
<select
v-model="handlers.getPayload(message)!.form.sku"
class="w-full rounded-xl border border-default px-3 py-2 text-sm text-secondary outline-none transition focus:border-blue-400"
:disabled="handlers.getPayload(message)!.applying"
>
<option value="" disabled>{{ $t('chat.shippingNoticeMapping.selectHeader') }}</option>
<option v-for="h in (handlers.getPayload(message)!.schema_preview.headers || [])" :key="`sku-${h}`" :value="h">{{ handlers.normalizeHeader(h) }}</option>
</select>
</label>
<label class="space-y-1.5">
<span class="text-xs font-semibold text-muted">{{ $t('chat.shippingNoticeMapping.availableQtyColumnRequired') }}</span>
<select
v-model="handlers.getPayload(message)!.form.available_qty"
class="w-full rounded-xl border border-default px-3 py-2 text-sm text-secondary outline-none transition focus:border-blue-400"
:disabled="handlers.getPayload(message)!.applying"
>
<option value="" disabled>{{ $t('chat.shippingNoticeMapping.selectHeader') }}</option>
<option v-for="h in (handlers.getPayload(message)!.schema_preview.headers || [])" :key="`qty-${h}`" :value="h">{{ handlers.normalizeHeader(h) }}</option>
</select>
</label>
<label class="space-y-1.5 md:col-span-2">
<span class="text-xs font-semibold text-muted">{{ $t('chat.shippingNoticeMapping.reservationIdColumnOptional') }}</span>
<select
v-model="handlers.getPayload(message)!.form.reservation_id"
class="w-full rounded-xl border border-default px-3 py-2 text-sm text-secondary outline-none transition focus:border-blue-400"
:disabled="handlers.getPayload(message)!.applying"
>
<option value="">{{ $t('chat.shippingNoticeMapping.reservationIdNotUsed') }}</option>
<option v-for="h in (handlers.getPayload(message)!.schema_preview.headers || [])" :key="`rid-${h}`" :value="h">{{ handlers.normalizeHeader(h) }}</option>
</select>
</label>
</div>
<div class="flex justify-end gap-3">
<button
type="button"
class="rounded-xl border border-default px-4 py-2 text-sm font-medium text-secondary transition hover:bg-surface-soft disabled:cursor-not-allowed disabled:opacity-60"
:disabled="handlers.getPayload(message)!.applying"
@click="handlers.reupload(message)"
>
{{ $t('chat.shippingNoticeMapping.reupload') }}
</button>
<button
type="button"
class="rounded-xl bg-emerald-600 px-4 py-2 text-sm font-medium text-white transition hover:bg-emerald-700 disabled:cursor-not-allowed disabled:opacity-60"
:disabled="handlers.getPayload(message)!.applying"
@click="handlers.apply(message)"
>
{{ handlers.getPayload(message)!.applying ? $t('chat.shippingNoticeMapping.applying') : $t('chat.shippingNoticeMapping.applyAndParse') }}
</button>
</div>
</div>
</div>
</template>
@@ -0,0 +1,29 @@
/**
* features/chat/composables/chat.context.ts
* 对话页 provide/inject 上下文类型与注入 key。
*
* provide 时使用 `reactive(useChatPage())`,嵌套 Ref/ComputedRef 在消费侧自动解包,
* template 与 script 均可直接 `page.input` / `page.isThinking` 而无需 `.value`。
*/
import { inject, type InjectionKey, type Reactive, type UnwrapNestedRefs } from 'vue';
import type { useChatPage } from './useChatPage';
/** useChatPage() 原始返回(含 Ref/ComputedRef) */
export type ChatPageContext = ReturnType<typeof useChatPage>;
/** ChatView provide 后经 reactive() 包装、供子组件 inject 的类型 */
export type ChatPageContextProvided = Reactive<UnwrapNestedRefs<ChatPageContext>>;
export const CHAT_PAGE_KEY: InjectionKey<ChatPageContextProvided> = Symbol('chatPage');
/**
* 在 ChatView 子树中获取对话页上下文。
* 必须在已 provide(CHAT_PAGE_KEY) 的组件树内调用。
*/
export function useChatPageContext(): ChatPageContextProvided {
const ctx = inject(CHAT_PAGE_KEY);
if (!ctx) {
throw new Error('[chat] useChatPageContext() must be used inside ChatView (provide CHAT_PAGE_KEY)');
}
return ctx;
}
@@ -1,11 +1,11 @@
/**
/**
* features/chat/composables/chat.deps.ts
* 聊天 composables 共享依赖。
*/
import type { WritableComputedRef } from 'vue';
import type { ComposerTranslation } from 'vue-i18n';
import type { RouteLocationNormalizedLoaded, Router } from 'vue-router';
import type { useMessage } from '@/composables/useMessage';
import type { useMessage } from '@/shared/composables/useMessage';
export interface ChatDeps {
t: ComposerTranslation;
@@ -1,9 +1,9 @@
/**
/**
* features/chat/composables/useChat.ts
* SSE 流式对话核心:消息列表、runs、发送与接收。
*/
import { ref } from 'vue';
import { getAuthHeaders } from '@/utils/auth';
import { getAuthHeaders } from '@/shared/utils/auth';
import type { ChatMessage, ChatRun, RetrieverResource } from '../types/chat.types';
const normalizeResources = (resources: unknown) => {
@@ -0,0 +1,198 @@
/**
* features/chat/composables/useChatAgent.ts
* 当前 Agent 元数据、知识库选项、推荐问题与用户可切换 Agent 列表。
*/
import { computed, ref, watch, type ComputedRef } from 'vue';
import { BusinessError } from '@/shared/api/client';
import { getUserAgent, listUserAgents } from '@/features/auth/api/user.api';
import { setLastChatAgentId } from '@/shared/utils/lastChatAgent';
import type { ChatDeps } from './chat.deps';
import type { UseChatGuidesReturn } from './useChatGuides';
export type AgentSuggestedQuestionItem = {
question: string;
group: string;
};
const DEFAULT_KB = '企业知识库';
const ERP_KB = 'ERP知识库';
const ERP_KB_ENABLED_AGENT_NAMES = new Set(['固资管理']);
const DEFAULT_AGENT_DESCRIPTIONS: Record<string, string> = {
人事规章: '我是你的7x24小时专属HR政策助手。无需手动检索文档,只需用日常说话的方式提问,我能从公司最新、最全的规章制度中,为你精准提取并总结答案。',
通用入口: '我是你的7x24小时专属AI数字人。无需手动检索文档,只需用日常说话的方式提问,我能从公司最新、最全的人事规章制度中,为你精准提取并总结答案。',
};
const DEFAULT_AGENT_SUGGESTED_QUESTIONS: Record<string, { style: 'plain' | 'styled'; questions: AgentSuggestedQuestionItem[] }> = {
人事规章: {
style: 'styled',
questions: [
{ question: '查询我有多少假期?', group: '考勤与休假' },
{ question: '如何进行请假?', group: '考勤与休假' },
{ question: '查公司法定节假日?', group: '考勤与休假' },
{ question: '新员工入职须知', group: '规章与日常' },
{ question: '怎么开具在职证明?', group: '规章与日常' },
{ question: '查公司薪酬及福利待遇怎么样?', group: '规章与日常' },
],
},
通用入口: {
style: 'plain',
questions: [
{ question: '新员工入职须知', group: '' },
{ question: '查询我有多少假期?', group: '' },
{ question: '如何进行请假?', group: '' },
{ question: '查公司法定节假日?', group: '' },
{ question: '查公司薪酬及福利待遇怎么样?', group: '' },
],
},
};
const normalizeAgentSuggestedQuestions = (value: unknown): AgentSuggestedQuestionItem[] => {
if (!Array.isArray(value)) return [];
return value
.map((item) => {
if (typeof item === 'string') {
const question = item.trim();
return question ? { question, group: '' } : null;
}
if (!item || typeof item !== 'object') return null;
const record = item as Record<string, unknown>;
const question = String(record.question || record.text || '').trim();
const group = String(record.group || '').trim();
return question ? { question, group } : null;
})
.filter((item): item is AgentSuggestedQuestionItem => !!item);
};
export interface UseChatAgentOptions {
deps: ChatDeps;
currentAgentId: ComputedRef<number>;
chatGuides: Pick<UseChatGuidesReturn, 'loadGuides' | 'clearGuides'>;
}
export function useChatAgent(options: UseChatAgentOptions) {
const { deps, currentAgentId, chatGuides } = options;
const { t, msg, router } = deps;
const currentAgent = ref<any>(null);
const userAgents = ref<Array<{ id: number; name: string; description: string; icon_url?: string; dify_app_type?: 'chatflow' | 'workflow' }>>([]);
const showAgentPanel = ref(true);
const selectedKb = ref(DEFAULT_KB);
const kbOptions = [DEFAULT_KB, ERP_KB];
const getKbLabel = (kb: string) => {
if (kb === DEFAULT_KB) return t('chat.kb.enterprise');
if (kb === ERP_KB) return t('chat.kb.erp');
return kb;
};
const currentAgentName = computed(() => String(currentAgent.value?.name || '').trim());
const canSelectErpKnowledgeBase = computed(() => ERP_KB_ENABLED_AGENT_NAMES.has(currentAgentName.value));
const availableKbOptions = computed(() => (
canSelectErpKnowledgeBase.value
? kbOptions
: kbOptions.filter((option) => option !== ERP_KB)
));
const kbDropdownDisabled = computed(() => availableKbOptions.value.length <= 1);
watch(canSelectErpKnowledgeBase, (allowed) => {
if (allowed) {
selectedKb.value = ERP_KB;
return;
}
if (selectedKb.value === ERP_KB) {
selectedKb.value = DEFAULT_KB;
}
}, { immediate: true });
const agentDescription = computed(() => {
const text = String(currentAgent.value?.description || '').trim();
return text || DEFAULT_AGENT_DESCRIPTIONS[currentAgentName.value] || '';
});
const suggestedQuestionsStyle = computed<'plain' | 'styled'>(() => {
const style = String(currentAgent.value?.extra_config?.suggested_questions_style || '').trim().toLowerCase();
if (style === 'styled') return 'styled';
if (style === 'plain') return 'plain';
return DEFAULT_AGENT_SUGGESTED_QUESTIONS[currentAgentName.value]?.style || 'plain';
});
const agentSuggestedQuestions = computed<AgentSuggestedQuestionItem[]>(() => {
const configured = normalizeAgentSuggestedQuestions(
currentAgent.value?.suggested_questions ?? currentAgent.value?.extra_config?.suggested_questions,
);
if (configured.length > 0) return configured;
return DEFAULT_AGENT_SUGGESTED_QUESTIONS[currentAgentName.value]?.questions || [];
});
const styledSuggestedQuestionSections = computed(() => {
const groups = new Map<string, AgentSuggestedQuestionItem[]>();
for (const item of agentSuggestedQuestions.value) {
const groupName = String(item.group || '').trim() || '常见问题';
if (!groups.has(groupName)) {
groups.set(groupName, []);
}
groups.get(groupName)?.push(item);
}
const iconTypes: Array<'calendar' | 'building'> = ['calendar', 'building'];
return Array.from(groups.entries()).map(([title, questions], index) => ({
title,
questions,
iconType: iconTypes[index % iconTypes.length] as 'calendar' | 'building',
}));
});
const loadAgent = async () => {
try {
currentAgent.value = await getUserAgent(currentAgentId.value);
await chatGuides.loadGuides();
} catch (e) {
if (e instanceof BusinessError && e.status === 403) {
msg.error(t('workspace.permission.denied') || 'Access denied');
router.push('/workspace?no_redirect=1');
return;
}
console.error('Failed to load agent', e);
currentAgent.value = { name: t('workspace.unknownAgent') };
chatGuides.clearGuides();
}
};
const loadUserAgents = async () => {
try {
const agents = await listUserAgents();
userAgents.value = Array.isArray(agents)
? agents.filter((a: any) => a.id !== currentAgentId.value && (a.dify_app_type || 'chatflow') === 'chatflow')
: [];
if (userAgents.value.length === 0) {
showAgentPanel.value = false;
}
} catch {
userAgents.value = [];
showAgentPanel.value = false;
}
};
const switchToAgent = (agent: { id: number; name: string }) => {
if (agent.id === currentAgentId.value) return;
setLastChatAgentId(agent.id);
router.push(`/chat/${agent.id}`);
};
return {
currentAgent,
userAgents,
showAgentPanel,
selectedKb,
getKbLabel,
availableKbOptions,
kbDropdownDisabled,
agentDescription,
suggestedQuestionsStyle,
agentSuggestedQuestions,
styledSuggestedQuestionSections,
loadAgent,
loadUserAgents,
switchToAgent,
};
}
@@ -0,0 +1,357 @@
/**
* features/chat/composables/useChatAttachments.ts
* Dify 附件策略解析、本地/URL 附件管理与发送前上传。
*/
import { computed, ref, type ComputedRef, type Ref } from 'vue';
import { uploadChatFile } from '../api/chat.api';
import type { PendingAttachment } from '../types/shipping.types';
import type { ChatDeps } from './chat.deps';
type ChatUploadFileType = 'image' | 'document' | 'audio' | 'video' | 'custom';
export type ChatUploadFileSpec =
| { type: ChatUploadFileType; transfer_method: 'local_file'; upload_file_id: string }
| { type: ChatUploadFileType; transfer_method: 'remote_url'; url: string };
const DIFY_SUPPORTED_EXTS: Record<Exclude<ChatUploadFileType, 'custom'>, Set<string>> = {
document: new Set([
'txt', 'md', 'markdown', 'mdx', 'pdf', 'html', 'htm', 'xlsx', 'xls', 'vtt', 'properties',
'doc', 'docx', 'csv', 'eml', 'msg', 'pptx', 'ppt', 'xml', 'epub',
]),
image: new Set(['jpg', 'jpeg', 'png', 'gif', 'webp', 'svg']),
audio: new Set(['mp3', 'm4a', 'wav', 'webm', 'mpga']),
video: new Set(['mp4', 'mov', 'mpeg', 'webm']),
};
const extractExt = (value: string) => {
const text = (value || '').trim().toLowerCase();
const withoutQuery = (text.split('?')[0] || '').split('#')[0] || '';
const idx = withoutQuery.lastIndexOf('.');
if (idx < 0) return '';
return withoutQuery.slice(idx + 1).trim();
};
const isKnownDifyExt = (ext: string) => {
if (!ext) return false;
return (
DIFY_SUPPORTED_EXTS.image.has(ext)
|| DIFY_SUPPORTED_EXTS.document.has(ext)
|| DIFY_SUPPORTED_EXTS.audio.has(ext)
|| DIFY_SUPPORTED_EXTS.video.has(ext)
);
};
const resolveDifyType = (ext: string, mime?: string): Exclude<ChatUploadFileType, 'custom'> | null => {
const m = (mime || '').toLowerCase();
if (m.startsWith('image/')) return 'image';
if (m.startsWith('audio/')) return 'audio';
if (m.startsWith('video/')) return 'video';
if (DIFY_SUPPORTED_EXTS.image.has(ext)) return 'image';
if (DIFY_SUPPORTED_EXTS.document.has(ext)) return 'document';
const inAudio = DIFY_SUPPORTED_EXTS.audio.has(ext);
const inVideo = DIFY_SUPPORTED_EXTS.video.has(ext);
if (inAudio && !inVideo) return 'audio';
if (inVideo) return 'video';
return null;
};
export interface UseChatAttachmentsOptions {
deps: ChatDeps;
currentAgentId: ComputedRef<number>;
currentAgent: Ref<any>;
}
export function useChatAttachments(options: UseChatAttachmentsOptions) {
const { deps, currentAgentId, currentAgent } = options;
const { msg } = deps;
const attachments = ref<PendingAttachment[]>([]);
const isUploadingAttachments = ref(false);
const difyFileUploadConfig = computed<Record<string, any>>(() => {
return (currentAgent.value?.dify_parameters?.file_upload as any) || {};
});
const difySystemParameters = computed<Record<string, any>>(() => {
return (currentAgent.value?.dify_parameters?.system_parameters as any) || {};
});
const attachmentPolicy = computed(() => {
const types: ChatUploadFileType[] = ['image', 'document', 'audio', 'video', 'custom'];
const enabled: Record<ChatUploadFileType, { local: boolean; remote: boolean; limit?: number }> = {
image: { local: false, remote: false },
document: { local: false, remote: false },
audio: { local: false, remote: false },
video: { local: false, remote: false },
custom: { local: false, remote: false },
};
const raw = difyFileUploadConfig.value as any;
const normalizedAllowedExts = Array.isArray(raw?.allowed_file_extensions)
? raw.allowed_file_extensions
.map((v: any) => String(v || '').trim())
.filter(Boolean)
.map((v: string) => (v.startsWith('.') ? v.slice(1) : v).toLowerCase())
.filter(Boolean)
: [];
const allowedExts: Set<string> | null = normalizedAllowedExts.length > 0 ? new Set<string>(normalizedAllowedExts) : null;
const allowedTypes = Array.isArray(raw?.allowed_file_types)
? raw.allowed_file_types
.map((v: any) => String(v || '').trim().toLowerCase())
.filter(Boolean)
: [];
const allowedTypeSet = allowedTypes.length > 0 ? new Set(allowedTypes) : null;
const allowedMethods = Array.isArray(raw?.allowed_file_upload_methods)
? raw.allowed_file_upload_methods
.map((v: any) => String(v || '').trim().toLowerCase())
.filter(Boolean)
: [];
const allowedMethodSet = allowedMethods.length > 0 ? new Set(allowedMethods) : null;
const isNewSchema = Boolean(raw && raw.enabled === true && allowedTypeSet && allowedMethodSet);
if (isNewSchema && allowedTypeSet && allowedMethodSet) {
for (const t of types) {
const cfg = raw?.[t];
const cfgEnabled = typeof cfg?.enabled === 'boolean' ? Boolean(cfg.enabled) : null;
const typeAllowed = allowedTypeSet.has(t);
if (cfgEnabled === false) continue;
if (cfgEnabled !== true && !typeAllowed) continue;
const transferMethods = Array.isArray(cfg?.transfer_methods)
? cfg.transfer_methods
.map((v: any) => String(v || '').trim().toLowerCase())
.filter(Boolean)
: [];
const methodSet = transferMethods.length > 0 ? new Set(transferMethods) : allowedMethodSet;
enabled[t] = {
local: methodSet.has('local_file'),
remote: methodSet.has('remote_url'),
limit: Number.isFinite(Number(cfg?.number_limits))
? Number(cfg.number_limits)
: (Number.isFinite(Number(raw?.number_limits)) ? Number(raw.number_limits) : undefined),
};
}
} else {
for (const t of types) {
const cfg = raw?.[t];
if (!cfg || !cfg.enabled) continue;
const transferMethods = Array.isArray(cfg.transfer_methods) ? cfg.transfer_methods : [];
enabled[t] = {
local: transferMethods.includes('local_file'),
remote: transferMethods.includes('remote_url'),
limit: Number.isFinite(Number(cfg.number_limits)) ? Number(cfg.number_limits) : undefined,
};
}
}
const mergedLimits = {
...(difySystemParameters.value || {}),
...(raw?.fileUploadConfig || {}),
} as any;
const system = mergedLimits || {};
const sizeLimitMb: Record<ChatUploadFileType, number | null> = {
image: Number.isFinite(Number(system.image_file_size_limit)) ? Number(system.image_file_size_limit) : (Number.isFinite(Number(system.file_size_limit)) ? Number(system.file_size_limit) : null),
audio: Number.isFinite(Number(system.audio_file_size_limit)) ? Number(system.audio_file_size_limit) : (Number.isFinite(Number(system.file_size_limit)) ? Number(system.file_size_limit) : null),
video: Number.isFinite(Number(system.video_file_size_limit)) ? Number(system.video_file_size_limit) : (Number.isFinite(Number(system.file_size_limit)) ? Number(system.file_size_limit) : null),
document: Number.isFinite(Number(system.file_size_limit)) ? Number(system.file_size_limit) : null,
custom: Number.isFinite(Number(system.file_size_limit)) ? Number(system.file_size_limit) : null,
};
const anyEnabled = Object.values(enabled).some((v) => v.local || v.remote);
const canLocal = Object.values(enabled).some((v) => v.local);
const canRemote = Object.values(enabled).some((v) => v.remote);
const totalLimit = (() => {
const v1 = raw?.fileUploadConfig?.file_upload_limit;
if (Number.isFinite(Number(v1))) return Number(v1);
const v2 = raw?.number_limits;
if (Number.isFinite(Number(v2))) return Number(v2);
return null;
})();
const effectiveAllowedExts: Set<string> | null = (() => {
if (!allowedExts) return null;
const filtered = new Set<string>();
for (const ext of allowedExts) {
const t = resolveDifyType(ext);
if (!t) {
if (enabled.custom.local || enabled.custom.remote) filtered.add(ext);
continue;
}
if (enabled[t]?.local || enabled[t]?.remote) filtered.add(ext);
}
return filtered.size > 0 ? filtered : null;
})();
const accept = (() => {
if (enabled.custom.local) return '';
if (effectiveAllowedExts) {
return Array.from(effectiveAllowedExts).map((e) => `.${e}`).join(',');
}
const parts = new Set<string>();
const pushExts = (exts: Set<string>) => {
for (const e of exts) parts.add(`.${e}`);
};
if (enabled.image.local) pushExts(DIFY_SUPPORTED_EXTS.image);
if (enabled.audio.local) pushExts(DIFY_SUPPORTED_EXTS.audio);
if (enabled.video.local) pushExts(DIFY_SUPPORTED_EXTS.video);
if (enabled.document.local) pushExts(DIFY_SUPPORTED_EXTS.document);
return Array.from(parts).join(',');
})();
return {
anyEnabled,
enabled,
sizeLimitMb,
canLocal,
canRemote,
accept,
allowedExts: effectiveAllowedExts,
totalLimit,
};
});
const inferFileTypeFromUrl = (url: string): ChatUploadFileType | null => resolveDifyType(extractExt(url));
const inferFileTypeFromFile = (file: File): ChatUploadFileType | null => {
const ext = extractExt(file.name || '');
return resolveDifyType(ext, file.type || '');
};
const removeAttachment = (id: string) => {
attachments.value = attachments.value.filter((a) => a.id !== id);
};
const handleLocalFilesSelected = (event: Event) => {
const inputEl = event.target as HTMLInputElement | null;
const fileList = inputEl?.files;
if (!fileList) return;
const files = Array.from(fileList);
for (const f of files) {
if (attachmentPolicy.value.totalLimit && attachments.value.length >= attachmentPolicy.value.totalLimit) {
msg.warning(`附件数量已达上限(${attachmentPolicy.value.totalLimit})`);
break;
}
const ext = extractExt(f.name || '');
if (attachmentPolicy.value.allowedExts && (!ext || !attachmentPolicy.value.allowedExts.has(ext))) {
msg.warning(`不支持的附件类型:${f.name}`);
continue;
}
let type = inferFileTypeFromFile(f);
if (!type) {
if (attachmentPolicy.value.enabled.custom.local && !isKnownDifyExt(ext)) {
type = 'custom';
} else {
msg.warning(`不支持的附件类型:${f.name}`);
continue;
}
}
const caps = attachmentPolicy.value.enabled[type];
if (!caps?.local) {
msg.warning(`当前应用不支持上传此类型附件:${type}`);
continue;
}
const limit = attachmentPolicy.value.sizeLimitMb[type];
if (limit && f.size > limit * 1024 * 1024) {
msg.warning(`附件过大(上限 ${limit}MB):${f.name}`);
continue;
}
const countSameType = attachments.value.filter((a) => a.type === type).length;
if (caps.limit && countSameType >= caps.limit) {
msg.warning(`该类型附件数量已达上限(${caps.limit})`);
continue;
}
attachments.value.push({ id: `${Date.now()}_${Math.random()}`, kind: 'local', file: f, type });
}
if (inputEl) inputEl.value = '';
};
const addRemoteUrlAttachment = (urlFromInput?: string) => {
const raw = (urlFromInput ?? '').trim();
if (!raw) return;
const url = raw.startsWith('//') ? `${window.location.protocol}${raw}` : raw;
if (!/^https?:\/\//i.test(url)) {
msg.warning('仅支持 http/https URL');
return;
}
if (!attachmentPolicy.value.canRemote) {
msg.warning('当前应用不支持 URL 附件');
return;
}
if (attachmentPolicy.value.totalLimit && attachments.value.length >= attachmentPolicy.value.totalLimit) {
msg.warning(`附件数量已达上限(${attachmentPolicy.value.totalLimit})`);
return;
}
const ext = extractExt(url);
if (attachmentPolicy.value.allowedExts && (!ext || !attachmentPolicy.value.allowedExts.has(ext))) {
msg.warning('不支持的 URL 附件类型');
return;
}
let type = inferFileTypeFromUrl(url);
if (!type) {
if (attachmentPolicy.value.enabled.custom.remote && !isKnownDifyExt(ext)) {
type = 'custom';
} else {
msg.warning('不支持的 URL 附件类型');
return;
}
}
const caps = attachmentPolicy.value.enabled[type];
if (!caps?.remote) {
msg.warning(`当前应用不支持该类型 URL 附件:${type}`);
return;
}
const countSameType = attachments.value.filter((a) => a.type === type).length;
if (caps.limit && countSameType >= caps.limit) {
msg.warning(`该类型附件数量已达上限(${caps.limit})`);
return;
}
attachments.value.push({ id: `${Date.now()}_${Math.random()}`, kind: 'remote', url, type });
};
const buildFileSpecsForSend = async (): Promise<ChatUploadFileSpec[]> => {
if (!attachmentPolicy.value.anyEnabled) return [];
if (attachments.value.length === 0) return [];
const specs: ChatUploadFileSpec[] = [];
const locals = attachments.value.filter((a) => a.kind === 'local') as Array<Extract<PendingAttachment, { kind: 'local' }>>;
const remotes = attachments.value.filter((a) => a.kind === 'remote') as Array<Extract<PendingAttachment, { kind: 'remote' }>>;
if (locals.length > 0) {
isUploadingAttachments.value = true;
try {
for (const item of locals) {
const uploaded = await uploadChatFile(currentAgentId.value, item.file);
if (!uploaded?.id) {
throw new Error('Missing upload id');
}
specs.push({ type: item.type, transfer_method: 'local_file', upload_file_id: uploaded.id });
}
} finally {
isUploadingAttachments.value = false;
}
}
for (const item of remotes) {
specs.push({ type: item.type, transfer_method: 'remote_url', url: item.url });
}
return specs;
};
const clearAttachments = () => {
attachments.value = [];
};
return {
attachments,
isUploadingAttachments,
attachmentPolicy,
removeAttachment,
handleLocalFilesSelected,
addRemoteUrlAttachment,
buildFileSpecsForSend,
clearAttachments,
};
}
@@ -0,0 +1,140 @@
/**
* features/chat/composables/useChatBrowserPanel.ts
* 内置浏览器侧栏:URL 规范化、iframe 加载与桌面端宽度拖拽。
*/
import { computed, ref } from 'vue';
const MIN_BROWSER_PANEL_WIDTH = 320;
const MAX_BROWSER_PANEL_WIDTH = 960;
export interface UseChatBrowserPanelOptions {
/** 无效 URL 等提示 */
warn: (message: string) => void;
invalidUrlMessage: string;
enterUrlMessage: string;
}
const normalizeBrowserInput = (value: string) => {
const raw = (value || '').trim();
if (!raw) return '';
if (/^https?:\/\//i.test(raw)) return raw;
if (/^localhost(?::\d+)?(\/.*)?$/i.test(raw)) return `http://${raw}`;
if (/^(?:\d{1,3}\.){3}\d{1,3}(?::\d+)?(\/.*)?$/.test(raw)) return `http://${raw}`;
if (/^[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}(\/.*)?$/.test(raw)) return `https://${raw}`;
return '';
};
export function useChatBrowserPanel(options: UseChatBrowserPanelOptions) {
const open = ref(false);
const draftUrl = ref('');
const currentUrl = ref('');
const frameKey = ref(0);
const panelWidth = ref(420);
const isResizing = ref(false);
const viewportWidth = ref(typeof window === 'undefined' ? 1440 : window.innerWidth);
const clampPanelWidth = (width: number) => {
const maxAllowed = Math.min(
MAX_BROWSER_PANEL_WIDTH,
Math.max(MIN_BROWSER_PANEL_WIDTH, Math.floor(window.innerWidth * 0.7)),
);
return Math.min(Math.max(width, MIN_BROWSER_PANEL_WIDTH), maxAllowed);
};
const panelStyle = computed(() => {
if (viewportWidth.value < 1024) return undefined;
return { width: `${panelWidth.value}px` };
});
const loadPage = () => {
const normalized = normalizeBrowserInput(draftUrl.value);
if (!normalized) {
options.warn(options.invalidUrlMessage);
return;
}
currentUrl.value = normalized;
draftUrl.value = normalized;
frameKey.value += 1;
open.value = true;
};
const refreshPage = () => {
if (!currentUrl.value) {
loadPage();
return;
}
frameKey.value += 1;
};
const openInNewTab = () => {
const normalized = currentUrl.value || normalizeBrowserInput(draftUrl.value);
if (!normalized) {
options.warn(options.enterUrlMessage);
return;
}
window.open(normalized, '_blank', 'noopener,noreferrer');
};
const onUrlEnter = (event: KeyboardEvent) => {
if (event.key !== 'Enter') return;
event.preventDefault();
loadPage();
};
const handleResizeMove = (event: MouseEvent) => {
if (!isResizing.value) return;
panelWidth.value = clampPanelWidth(window.innerWidth - event.clientX);
};
const stopResize = () => {
if (!isResizing.value) return;
isResizing.value = false;
document.body.style.cursor = '';
document.body.style.userSelect = '';
window.removeEventListener('mousemove', handleResizeMove);
window.removeEventListener('mouseup', stopResize);
};
const startResize = (event: MouseEvent) => {
if (viewportWidth.value < 1024) return;
event.preventDefault();
isResizing.value = true;
document.body.style.cursor = 'col-resize';
document.body.style.userSelect = 'none';
window.addEventListener('mousemove', handleResizeMove);
window.addEventListener('mouseup', stopResize);
};
const syncViewportWidth = () => {
viewportWidth.value = window.innerWidth;
if (viewportWidth.value >= 1024) {
panelWidth.value = clampPanelWidth(panelWidth.value);
}
};
const close = () => {
open.value = false;
};
const toggle = () => {
open.value = !open.value;
};
return {
open,
draftUrl,
currentUrl,
frameKey,
panelStyle,
isResizing,
loadPage,
refreshPage,
openInNewTab,
onUrlEnter,
startResize,
stopResize,
syncViewportWidth,
close,
toggle,
};
}
@@ -0,0 +1,70 @@
/**
* features/chat/composables/useChatGuides.ts
* Agent 学习之窗:指南列表加载与弹窗状态。
*/
import { computed, ref, type ComputedRef } from 'vue';
import { listAgentGuides } from '@/features/auth/api/user.api';
export interface AgentGuide {
id: number;
file_name: string;
file_type?: string;
file_url?: string;
file_path?: string;
remark?: string;
}
export interface UseChatGuidesOptions {
currentAgentId: ComputedRef<number>;
}
export function useChatGuides(options: UseChatGuidesOptions) {
const { currentAgentId } = options;
const guides = ref<AgentGuide[]>([]);
const showModal = ref(false);
const activeGuideId = ref<number | null>(null);
const showSidebar = ref(true);
const activeGuide = computed(() => guides.value.find((g) => g.id === activeGuideId.value));
const loadGuides = async () => {
try {
const res = await listAgentGuides(currentAgentId.value || 0);
guides.value = Array.isArray(res) ? (res as AgentGuide[]) : [];
} catch (error) {
console.error('Failed to load agent guides:', error);
guides.value = [];
}
};
const clearGuides = () => {
guides.value = [];
};
const openModal = () => {
const first = guides.value[0];
if (!first) return;
activeGuideId.value = first.id;
showModal.value = true;
showSidebar.value = true;
};
const closeModal = () => {
showModal.value = false;
};
return {
guides,
showModal,
activeGuideId,
activeGuide,
showSidebar,
loadGuides,
clearGuides,
openModal,
closeModal,
};
}
export type UseChatGuidesReturn = ReturnType<typeof useChatGuides>;
@@ -1,10 +1,10 @@
/**
/**
* features/chat/composables/useChatHistory.ts
* 跨 Agent 聊天历史列表(工作台 History 页 / 移动端 Tab)。
*/
import { ref } from 'vue';
import { getAuthHeaders } from '@/utils/auth';
import { requestJson } from '@/api/client';
import { getAuthHeaders } from '@/shared/utils/auth';
import { requestJson } from '@/shared/api/client';
import type { ChatCrossAgentHistoryItem } from '../types/chat.types';
export function useChatHistory() {
@@ -0,0 +1,138 @@
/**
* features/chat/composables/useChatLeave.ts
* 请假(OA)编排层:组合 leave/* 子模块,对外暴露 ChatView 所需 API。
*
* 消息类型约定(写入 messages 列表):
* - leave-form:可编辑表单
* - leave-confirmation:提交前确认
* - leave-result:OA 提交结果
*/
import { computed, type ComputedRef, type Ref } from 'vue';
import { getUserProfile } from '@/features/auth/api/user.api';
import { LEAVE_FEATURE_AGENT_NAMES, LEAVE_TYPES } from '../constants/leave';
import {
createLeaveAgentPickerApi,
createLeaveFlowApi,
createLeaveFormApi,
createLeaveLocalMessageApi,
createLeaveOaLoginApi,
formatDurationLabel,
formatYesNoLabel,
getLeaveAgentDisplayValue,
getLeaveConfirmationPayload,
getLeaveFormPayload,
getLeaveResultPayload,
syncLeaveDuration,
} from '../leave';
import { getLeaveTypeLabel } from '../leave/leaveDisplay';
import type { ChatMessage, ChatSessionItem } from '../types/chat.types';
import type { ChatDeps } from './chat.deps';
export interface UseChatLeaveOptions {
deps: ChatDeps;
currentAgent: Ref<{ name?: string } | null>;
currentAgentId: ComputedRef<number>;
currentUser: Ref<Record<string, unknown> | null>;
currentUserDisplayName: ComputedRef<string>;
currentUserEmployeeId: ComputedRef<string>;
messages: Ref<ChatMessage[]>;
conversationId: Ref<string | null>;
isThinking: Ref<boolean>;
history: Ref<ChatSessionItem[]>;
loadHistory: () => Promise<void>;
}
export function useChatLeave(options: UseChatLeaveOptions) {
const {
deps: { t, msg },
currentAgent,
currentAgentId,
currentUser,
currentUserDisplayName,
currentUserEmployeeId,
messages,
conversationId,
isThinking,
history,
loadHistory,
} = options;
const canUseLeaveFeature = computed(() =>
LEAVE_FEATURE_AGENT_NAMES.has(String(currentAgent.value?.name || '').trim()),
);
const { newLocalMessageId, saveLocalMessageToBackend } = createLeaveLocalMessageApi({
conversationId,
currentAgentId,
});
const oaLogin = createLeaveOaLoginApi({
currentUserEmployeeId,
msg,
t,
});
const agentPicker = createLeaveAgentPickerApi({
currentAgentId,
messages,
saveLocalMessageToBackend,
});
const formApi = createLeaveFormApi({
messages,
currentUserDisplayName,
currentUserEmployeeId,
newLocalMessageId,
saveLocalMessageToBackend,
msg,
t,
});
const flowApi = createLeaveFlowApi({
canUseLeaveFeature,
isThinking,
messages,
conversationId,
history,
currentAgentId,
loadHistory,
newLocalMessageId,
saveLocalMessageToBackend,
createLeaveFormData: formApi.createLeaveFormData,
checkLeaveBalance: formApi.checkLeaveBalance,
formatLeaveBalanceNumber: formApi.formatLeaveBalanceNumber,
msg,
t,
});
const syncCurrentUserProfile = async () => {
if (currentUser.value?.real_name && String(currentUser.value.real_name).trim()) return;
try {
const data = await getUserProfile();
currentUser.value = { ...currentUser.value, ...data };
} catch (e) {
console.error('Failed to load current user profile', e);
}
};
return {
LEAVE_TYPES,
canUseLeaveFeature,
...oaLogin,
...agentPicker,
getLeaveTypeLabel,
formatDurationLabel: (hours: number, leaveType?: string) => formatDurationLabel(hours, leaveType, t),
formatYesNoLabel,
syncLeaveDuration,
getLeaveFormPayload,
getLeaveConfirmationPayload,
getLeaveResultPayload,
getLeaveAgentDisplayValue,
submitLeaveForm: formApi.submitLeaveForm,
editLeaveConfirmation: formApi.editLeaveConfirmation,
confirmLeaveSubmission: formApi.confirmLeaveSubmission,
tryHandleLeaveSend: flowApi.tryHandleLeaveSend,
handleLeaveMarkdownClick: flowApi.handleLeaveMarkdownClick,
syncCurrentUserProfile,
};
}
@@ -0,0 +1,418 @@
/**
* features/chat/composables/useChatPage.ts
* 对话页主编排:组合 SSE、Agent、附件、请假/出货、路由同步与 page/* 子模块。
*/
import { computed, markRaw, ref, watch } from 'vue';
import { storeToRefs } from 'pinia';
import { useI18n } from 'vue-i18n';
import { useRoute, useRouter } from 'vue-router';
import { config } from '@/config';
import { useMessage } from '@/shared/composables/useMessage';
import { useIsMobile } from '@/shared/composables/useIsMobile';
import { useTheme } from '@/shared/composables/useTheme';
import { stripReasoningPrelude } from '../utils/chatText';
import type { ChatDeps } from './chat.deps';
import { useChat } from './useChat';
import { useChatAgent } from './useChatAgent';
import { useChatAttachments } from './useChatAttachments';
import { useChatBrowserPanel } from './useChatBrowserPanel';
import { useChatGuides } from './useChatGuides';
import { useChatLeave } from './useChatLeave';
import { useChatQueryPreview } from './useChatQueryPreview';
import { useChatRouteSync } from './useChatRouteSync';
import { useChatScroll } from './useChatScroll';
import { useChatSessions } from './useChatSessions';
import { useChatShipping } from './useChatShipping';
import { useChatSourceFiles } from './useChatSourceFiles';
import { useChatStore } from '../stores/chat.store';
import {
createChatPageConversationApi,
createChatPageLocalMessageApi,
createChatPageMarkdownApi,
createChatPageSendApi,
createLeaveMessageHandlers,
createShippingMappingHandlers,
createShippingPickerRefHolder,
useChatPageDialogs,
useChatPageUser,
useChatPageVoice,
useChatPageToolRun,
} from '../page';
export function useChatPage() {
const { t, locale } = useI18n();
const route = useRoute();
const router = useRouter();
const msg = useMessage();
const { isMobile } = useIsMobile();
const { appliedTheme, toggleLightDark } = useTheme();
const deps: ChatDeps = { t, locale, msg, router, route };
const chatStore = useChatStore();
const { sidebarCollapsed } = storeToRefs(chatStore);
const currentAgentId = computed(() => {
const id = Number(route.params.agentId);
return Number.isFinite(id) && id > 0 ? id : 0;
});
const { currentUser, currentUserDisplayName, currentUserEmployeeId, onAuthLogout, handleLogout, goToAdmin } =
useChatPageUser(router);
const chatScrollContainer = ref<HTMLElement | null>(null);
/** markRaw:避免 reactive(page) 解包内部 Ref,供 template ref 回写 */
const scrollContainerHolder = markRaw({ el: chatScrollContainer });
const input = ref('');
const isSidebarOpen = ref(false);
const copiedIndex = ref<number | null>(null);
const {
messages,
isThinking,
conversationId,
runs,
activeRunId,
activateRun,
createNewChatView,
loadConversationState,
sendMessage,
} = useChat();
const browser = useChatBrowserPanel({
warn: (text) => msg.warning(text),
invalidUrlMessage: t('chat.invalidBrowserUrl'),
enterUrlMessage: t('chat.enterBrowserUrl'),
});
const queryPreview = useChatQueryPreview({ currentAgentId });
const scroll = useChatScroll({ container: chatScrollContainer, messages });
scroll.setupThinkingScrollWatch(isThinking, conversationId);
const resetPeripheralState = () => {
browser.close();
queryPreview.close();
};
const disposePeripherals = () => {
browser.stopResize();
scroll.dispose();
};
const chatGuides = useChatGuides({ currentAgentId });
const agent = useChatAgent({ deps, currentAgentId, chatGuides });
const attachmentApi = useChatAttachments({
deps,
currentAgentId,
currentAgent: agent.currentAgent,
});
const sourceFiles = useChatSourceFiles({ agentId: currentAgentId, t, msg, isMobile });
const {
filePreviewVisible,
previewFile,
getSourceTitle,
getSourceMeta,
getSourceBrief,
getSourceLinks,
getMessageLinks,
getDisplayRetrieverResources,
shouldExpandSourceDetails,
openPreview,
parsePlmPreviewLink,
} = sourceFiles;
watch(currentAgentId, (id) => {
chatStore.setCurrentAgentId(id > 0 ? id : null);
}, { immediate: true });
const dialogs = useChatPageDialogs(messages);
const { openDeleteConfirmDialog } = dialogs;
let loadConversation: (id: string, options?: { force?: boolean }) => Promise<void>;
let startNewChat: () => void;
const {
history,
loadHistory,
clearHistory,
displayHistory,
activeHistoryKey,
handleHistorySelect,
refreshHistoryAfterSend,
setupConversationIdHistoryWatch,
clearAllHistory,
deleteHistoryItem,
} = useChatSessions({
deps,
currentAgentId,
conversationId,
activeRunId,
runs,
activateRun,
loadConversation: (id, opts) => loadConversation(id, opts),
isSidebarOpen,
onConfirmDelete: openDeleteConfirmDialog,
startNewChat: () => startNewChat(),
});
setupConversationIdHistoryWatch();
const leave = useChatLeave({
deps,
currentAgent: agent.currentAgent,
currentAgentId,
currentUser,
currentUserDisplayName,
currentUserEmployeeId,
messages,
conversationId,
isThinking,
history,
loadHistory,
});
const { newLocalMessageId, saveLocalMessageToBackend } = createChatPageLocalMessageApi({
conversationId,
currentAgentId,
});
const presetQuestion = computed(() => {
const q = route.query.preset;
return typeof q === 'string' ? q : '';
});
const shipping = useChatShipping({
deps,
currentAgent: agent.currentAgent,
currentAgentId,
messages,
conversationId,
isThinking,
history,
loadHistory,
input,
chatScrollContainer,
attachments: attachmentApi.attachments,
selectedKb: agent.selectedKb,
isUploadingAttachments: attachmentApi.isUploadingAttachments,
attachmentPolicy: attachmentApi.attachmentPolicy,
presetQuestion,
saveLocalMessageToBackend,
newLocalMessageId,
stripReasoningPrelude,
sendMessage,
buildFileSpecsForSend: attachmentApi.buildFileSpecsForSend,
loadConversation: (id, opts) => loadConversation(id, opts),
createNewChatView,
});
const conversationApi = createChatPageConversationApi({
deps,
route,
router,
currentAgentId,
conversationId,
activeRunId,
messages,
isThinking,
loadConversationState,
createNewChatView,
onConversationIdChanging: shipping.onConversationIdChanging,
onConversationLoadedEmpty: shipping.onConversationLoadedEmpty,
onConversationLoadFailed: shipping.onConversationLoadFailed,
isShippingNoticeAgent: shipping.isShippingNoticeAgent,
shippingTaskIdFromQuery: shipping.shippingTaskIdFromQuery,
clearHistory,
clearAttachments: attachmentApi.clearAttachments,
input,
resetCurrentAgent: () => { agent.currentAgent.value = null; },
copiedIndex,
resetPeripheralState,
filePreviewVisible,
previewFile,
});
({ loadConversation, startNewChat } = conversationApi);
const { resetChatStateForAgentChange } = conversationApi;
const toolRun = useChatPageToolRun({
currentAgent: agent.currentAgent,
conversationId,
messages,
});
const voice = useChatPageVoice({
input,
isThinking,
msg,
t,
});
const markdown = createChatPageMarkdownApi({
messages,
isThinking,
prepareMarkdownDisplayText: shipping.prepareMarkdownDisplayText,
handleLeaveMarkdownClick: leave.handleLeaveMarkdownClick,
parsePlmPreviewLink,
openPreview,
getMessageLinks,
getDisplayRetrieverResources,
getSourceLinks,
shouldExpandSourceDetails,
getSourceTitle,
getSourceMeta,
getSourceBrief,
getShippingInventoryMappingPayload: shipping.getShippingInventoryMappingPayload,
canOpenQueryPreview: queryPreview.canOpen,
getQueryPreviewSummary: queryPreview.getSummary,
openQueryPreviewDialog: queryPreview.openDialog,
shippingActionButtonClass: shipping.shippingActionButtonClass,
onShippingActionClick: shipping.handleShippingActionClick,
});
const sendApi = createChatPageSendApi({
input,
messages,
isThinking,
currentAgentId,
selectedKb: agent.selectedKb,
isUploadingAttachments: attachmentApi.isUploadingAttachments,
attachmentPolicy: attachmentApi.attachmentPolicy,
attachments: attachmentApi.attachments,
allowsSendWithAttachmentsOnly: shipping.allowsSendWithAttachmentsOnly,
buildFileSpecsForSend: attachmentApi.buildFileSpecsForSend,
clearAttachments: attachmentApi.clearAttachments,
sendMessage,
refreshHistoryAfterSend,
tryHandleShippingAttachmentAutoFlow: shipping.tryHandleShippingAttachmentAutoFlow,
tryHandleLeaveSend: leave.tryHandleLeaveSend,
tryHandleShippingSend: shipping.tryHandleShippingSend,
refreshToolRunProgressAfterSend: toolRun.refreshToolRunProgressAfterSend,
msg,
t,
copiedIndex,
});
shipping.shippingBindSend(() => sendApi.handleSend());
const leaveMessageHandlers = createLeaveMessageHandlers(leave);
const shippingMappingHandlers = createShippingMappingHandlers(shipping);
const shippingPickerRefHolder = markRaw(createShippingPickerRefHolder(shipping.shippingInventoryPickerRef));
const showChatRating = ref(false);
const routeSync = useChatRouteSync({
deps,
currentAgentId,
presetQuestion,
shippingTaskIdFromQuery: shipping.shippingTaskIdFromQuery,
isShippingNoticeAgent: shipping.isShippingNoticeAgent,
resetChatStateForAgentChange,
cancelVoiceInput: voice.cancelVoiceInput,
syncCurrentUserProfile: leave.syncCurrentUserProfile,
loadAgent: agent.loadAgent,
loadUserAgents: agent.loadUserAgents,
loadHistory,
loadConversation,
resumeShippingTaskFromQuery: shipping.resumeShippingTaskFromQuery,
handleSend: sendApi.handleSend,
createNewChatView,
onAuthLogout,
onViewportResize: () => browser.syncViewportWidth(),
disposePeripherals,
scheduleScrollToBottom: () => scroll.scheduleScrollToBottom(),
onMountedExtra: () => {
showChatRating.value = config.workspace?.showChatRating ?? true;
},
input,
});
watch(locale, (newLang) => {
localStorage.setItem('hxops_lang', String(newLang));
});
const handleSidebarNewChat = () => {
startNewChat();
isSidebarOpen.value = false;
};
return {
t,
msg,
isMobile,
appliedTheme,
toggleLightDark,
currentAgentId,
currentUser,
chatScrollContainer,
scrollContainerHolder,
messages,
isThinking,
conversationId,
input,
browser,
queryPreview,
browserPanelOpen: browser.open,
browserDraftUrl: browser.draftUrl,
browserCurrentUrl: browser.currentUrl,
browserFrameKey: browser.frameKey,
browserPanelStyle: browser.panelStyle,
isBrowserResizing: browser.isResizing,
showQueryPreviewDialog: queryPreview.show,
queryPreviewLoading: queryPreview.loading,
queryPreviewError: queryPreview.error,
queryPreviewState: queryPreview.state,
...agent,
agentGuides: chatGuides.guides,
showGuideModal: chatGuides.showModal,
activeGuideId: chatGuides.activeGuideId,
activeGuide: chatGuides.activeGuide,
showGuideSidebar: chatGuides.showSidebar,
openGuideModal: chatGuides.openModal,
...attachmentApi,
filePreviewVisible,
previewFile,
isSidebarOpen,
sidebarCollapsed,
toggleBrowserPanel: browser.toggle,
copiedIndex,
displayHistory,
activeHistoryKey,
handleHistorySelect,
clearAllHistory,
deleteHistoryItem,
isVoiceRecording: voice.isVoiceRecording,
isVoiceTranscribing: voice.isVoiceTranscribing,
handleVoiceFeatureClick: voice.handleVoiceFeatureClick,
...leave,
leaveMessageHandlers,
shippingMappingHandlers,
shippingPickerRefHolder,
shouldShowThinkingBubble: markdown.shouldShowThinkingBubble,
messageBubbleHandlers: markdown.messageBubbleHandlers,
shouldRenderMessage: markdown.shouldRenderMessage,
canSendMessage: sendApi.canSendMessage,
handleSend: sendApi.handleSend,
copyToClipboard: sendApi.copyToClipboard,
regenerate: sendApi.regenerate,
handleOpenFeedback: dialogs.handleOpenFeedback,
activeFeedbackMessageIndex: dialogs.activeFeedbackMessageIndex,
showGeneralFeedbackDialog: dialogs.showGeneralFeedbackDialog,
currentGeneralFeedbackChatLogId: dialogs.currentGeneralFeedbackChatLogId,
showDeleteConfirmDialog: dialogs.showDeleteConfirmDialog,
deleteConfirmMessage: dialogs.deleteConfirmMessage,
closeDeleteConfirmDialog: dialogs.closeDeleteConfirmDialog,
handleDeleteConfirm: dialogs.handleDeleteConfirm,
showChatRating,
isShippingNoticeAgent: shipping.isShippingNoticeAgent,
shippingSuggestedPrompt: shipping.shippingSuggestedPrompt,
handleShippingInventorySelected: shipping.handleShippingInventorySelected,
useShippingSuggestedPrompt: shipping.useShippingSuggestedPrompt,
handleSidebarNewChat,
goToWorkspace: routeSync.goToWorkspace,
switchToAgent: agent.switchToAgent,
loadUserAgents: agent.loadUserAgents,
handleLogout,
goToAdmin,
...toolRun,
};
}
@@ -0,0 +1,141 @@
/**
* features/chat/composables/useChatQueryPreview.ts
* Text2SQL 查询结果全量预览弹窗:分页加载与消息 payload 解析。
*/
import { ref, type ComputedRef } from 'vue';
import { getChatQueryPreviewPage } from '../api/chat.api';
import type { ChatMessage } from '../types/chat.types';
type QueryPreviewPayload = {
kind: 'text2sql_result_preview';
previewable?: boolean;
total_count?: number;
preview_row_count?: number;
query?: string;
};
export interface QueryPreviewState {
chatLogId: number;
title: string;
query: string;
columns: string[];
rows: unknown[][];
page: number;
pageSize: number;
total: number;
}
export interface UseChatQueryPreviewOptions {
currentAgentId: ComputedRef<number>;
}
export function useChatQueryPreview(options: UseChatQueryPreviewOptions) {
const { currentAgentId } = options;
const show = ref(false);
const loading = ref(false);
const error = ref('');
const state = ref<QueryPreviewState>({
chatLogId: 0,
title: '',
query: '',
columns: [],
rows: [],
page: 1,
pageSize: 100,
total: 0,
});
const getPayload = (msg: ChatMessage): QueryPreviewPayload | null => {
const payload = msg?.payload;
if (!payload || typeof payload !== 'object') return null;
if ((payload as QueryPreviewPayload).kind !== 'text2sql_result_preview') return null;
return payload as QueryPreviewPayload;
};
const canOpen = (msg: ChatMessage) => {
const payload = getPayload(msg);
return !!(payload?.previewable && Number(msg?.chat_log_id) > 0);
};
const getSummary = (msg: ChatMessage) => {
const payload = getPayload(msg);
const total = Number(payload?.total_count || 0);
if (total > 0) return `查看全部预览(共 ${total} 条)`;
return '查看全部预览';
};
const totalPages = () =>
Math.max(1, Math.ceil((state.value.total || 0) / (state.value.pageSize || 100)));
const close = () => {
show.value = false;
error.value = '';
};
const loadPage = async (chatLogId: number, page = 1) => {
if (!currentAgentId.value) {
error.value = '当前 Agent 未就绪,请稍后重试';
return;
}
loading.value = true;
error.value = '';
try {
const result = await getChatQueryPreviewPage(currentAgentId.value, chatLogId, {
page,
page_size: state.value.pageSize,
});
state.value = {
...state.value,
chatLogId,
title: String(result.query || state.value.title || '查询结果全量预览').trim() || '查询结果全量预览',
query: String(result.query || '').trim(),
columns: Array.isArray(result.columns) ? result.columns : [],
rows: Array.isArray(result.rows) ? result.rows : [],
page: Number(result.page || page || 1),
pageSize: Number(result.page_size || state.value.pageSize || 100),
total: Number(result.total || 0),
};
} catch (err: unknown) {
error.value = (err as { message?: string })?.message || '加载全量预览失败';
} finally {
loading.value = false;
}
};
const openDialog = async (msg: ChatMessage) => {
const chatLogId = Number(msg?.chat_log_id || 0);
if (!chatLogId) return;
const payload = getPayload(msg);
state.value = {
...state.value,
chatLogId,
title: String(payload?.query || msg?.content || '查询结果全量预览').trim() || '查询结果全量预览',
query: String(payload?.query || '').trim(),
page: 1,
total: Number(payload?.total_count || 0),
};
show.value = true;
await loadPage(chatLogId, 1);
};
const changePage = async (delta: number) => {
const nextPage = state.value.page + delta;
if (nextPage < 1 || nextPage > totalPages()) return;
await loadPage(state.value.chatLogId, nextPage);
};
return {
show,
loading,
error,
state,
totalPages,
getPayload,
canOpen,
getSummary,
openDialog,
close,
changePage,
};
}
@@ -0,0 +1,163 @@
/**
* features/chat/composables/useChatRouteSync.ts
* 路由与 Agent 切换时的状态同步、挂载/卸载生命周期。
*/
import { onBeforeUnmount, onMounted, watch, type ComputedRef, type Ref } from 'vue';
import { setLastChatAgentId } from '@/shared/utils/lastChatAgent';
import { registerOpenAgentId } from '@/shared/utils/agentTabs';
import { workspacePathFromLegacyView } from '@/features/workspace/constants/routes';
import type { ChatDeps } from './chat.deps';
export interface UseChatRouteSyncOptions {
deps: ChatDeps;
currentAgentId: ComputedRef<number>;
presetQuestion: ComputedRef<string>;
shippingTaskIdFromQuery: ComputedRef<string | null>;
isShippingNoticeAgent: ComputedRef<boolean>;
resetChatStateForAgentChange: () => void;
cancelVoiceInput: () => void;
syncCurrentUserProfile: () => Promise<void>;
loadAgent: () => Promise<void>;
loadUserAgents: () => Promise<void>;
loadHistory: () => Promise<void>;
loadConversation: (id: string, options?: { force?: boolean }) => Promise<void>;
resumeShippingTaskFromQuery: () => Promise<void>;
handleSend: (textOrEvent?: string | Event) => Promise<void>;
createNewChatView: () => void;
onAuthLogout: () => void;
onViewportResize: () => void;
disposePeripherals: () => void;
scheduleScrollToBottom: () => void;
onMountedExtra?: () => void | Promise<void>;
input: Ref<string>;
}
export function useChatRouteSync(options: UseChatRouteSyncOptions) {
const {
deps: { route, router },
currentAgentId,
presetQuestion,
shippingTaskIdFromQuery,
resetChatStateForAgentChange,
cancelVoiceInput,
syncCurrentUserProfile,
loadAgent,
loadUserAgents,
loadHistory,
loadConversation,
resumeShippingTaskFromQuery,
handleSend,
createNewChatView,
onAuthLogout,
onViewportResize,
disposePeripherals,
scheduleScrollToBottom,
onMountedExtra,
input,
} = options;
let routeSyncToken = 0;
const syncOpenAgentRegistration = () => {
const id = Number(route.params.agentId);
registerOpenAgentId(Number.isFinite(id) && id > 0 ? id : null);
};
const onPageHide = () => {
registerOpenAgentId(null);
};
const goToWorkspace = (view?: string) => {
setLastChatAgentId(currentAgentId.value);
registerOpenAgentId(null);
router.push({ path: workspacePathFromLegacyView(view), query: { no_redirect: '1' } });
};
const syncChatStateForRoute = async () => {
const agentId = currentAgentId.value;
if (!agentId) return;
const syncToken = ++routeSyncToken;
resetChatStateForAgentChange();
cancelVoiceInput();
setLastChatAgentId(agentId);
syncOpenAgentRegistration();
await syncCurrentUserProfile();
if (syncToken !== routeSyncToken) return;
await loadAgent();
if (syncToken !== routeSyncToken) return;
await loadUserAgents();
if (syncToken !== routeSyncToken) return;
await loadHistory();
if (syncToken !== routeSyncToken) return;
const convId = route.query.conversation_id as string;
if (convId) {
await loadConversation(convId, { force: true });
if (syncToken !== routeSyncToken) return;
} else if (shippingTaskIdFromQuery.value) {
await resumeShippingTaskFromQuery();
if (syncToken !== routeSyncToken) return;
}
if (presetQuestion.value) {
input.value = presetQuestion.value;
await handleSend();
}
};
onMounted(async () => {
window.addEventListener('pagehide', onPageHide);
window.addEventListener('hxops:logout', onAuthLogout);
window.addEventListener('resize', onViewportResize);
await syncChatStateForRoute();
await onMountedExtra?.();
scheduleScrollToBottom();
});
watch(
() => [route.params.agentId, route.query.conversation_id, route.query.preset, route.query.task_id],
async ([nextAgentId, nextConversationId, nextPreset, nextTaskId], [prevAgentId, prevConversationId, prevPreset, prevTaskId]) => {
if (
nextAgentId === prevAgentId
&& nextConversationId === prevConversationId
&& nextPreset === prevPreset
&& nextTaskId === prevTaskId
) {
return;
}
if (
nextAgentId === prevAgentId
&& nextPreset === prevPreset
&& nextTaskId === prevTaskId
&& nextConversationId !== prevConversationId
) {
if (typeof nextConversationId === 'string' && nextConversationId) {
await loadConversation(nextConversationId, { force: true });
} else {
createNewChatView();
}
return;
}
await syncChatStateForRoute();
},
);
onBeforeUnmount(() => {
window.removeEventListener('pagehide', onPageHide);
window.removeEventListener('hxops:logout', onAuthLogout);
window.removeEventListener('resize', onViewportResize);
disposePeripherals();
});
return {
goToWorkspace,
syncChatStateForRoute,
};
}
@@ -0,0 +1,96 @@
/**
* features/chat/composables/useChatScroll.ts
* 聊天主区域滚动:贴底、滚到最新用户问题与思考态切换时的滚动策略。
*/
import { nextTick, watch, type Ref } from 'vue';
import type { ChatMessage } from '../types/chat.types';
export interface UseChatScrollOptions {
container: Ref<HTMLElement | null>;
messages: Ref<ChatMessage[]>;
}
export function useChatScroll(options: UseChatScrollOptions) {
const { container, messages } = options;
let scrollToBottomFrame: number | null = null;
const scrollToBottom = async () => {
await nextTick();
const el = container.value;
if (!el) return;
el.scrollTo({
top: el.scrollHeight,
behavior: 'auto',
});
};
const scrollToUserQuestion = async () => {
if (scrollToBottomFrame !== null) {
window.cancelAnimationFrame(scrollToBottomFrame);
scrollToBottomFrame = null;
}
await nextTick();
await nextTick();
const el = container.value;
if (!el) return;
let lastUserIndex = -1;
for (let i = messages.value.length - 1; i >= 0; i--) {
if (messages.value[i]?.role === 'user') {
lastUserIndex = i;
break;
}
}
if (lastUserIndex < 0) return;
const target = el.querySelector(`[data-msg-index="${lastUserIndex}"]`) as HTMLElement | null;
target?.scrollIntoView({ behavior: 'smooth', block: 'start' });
};
const scheduleScrollToBottom = () => {
if (scrollToBottomFrame !== null) {
window.cancelAnimationFrame(scrollToBottomFrame);
}
scrollToBottomFrame = window.requestAnimationFrame(() => {
scrollToBottomFrame = null;
void scrollToBottom();
});
};
const dispose = () => {
if (scrollToBottomFrame !== null) {
window.cancelAnimationFrame(scrollToBottomFrame);
scrollToBottomFrame = null;
}
};
/** 消息/思考态变化时自动滚动(思考结束滚到用户问题,否则贴底) */
const setupThinkingScrollWatch = (isThinking: Ref<boolean>, conversationId?: Ref<string | null>) => {
let wasThinking = false;
watch(
() => ({
messageCount: messages.value.length,
lastMessageContent: messages.value[messages.value.length - 1]?.content || '',
lastMessageRole: messages.value[messages.value.length - 1]?.role || '',
isThinking: isThinking.value,
conversationId: conversationId?.value || '',
}),
() => {
if (wasThinking && !isThinking.value) {
wasThinking = false;
void scrollToUserQuestion();
} else {
if (isThinking.value) wasThinking = true;
scheduleScrollToBottom();
}
},
{ deep: false },
);
};
return {
scrollToBottom,
scrollToUserQuestion,
scheduleScrollToBottom,
setupThinkingScrollWatch,
dispose,
};
}
@@ -0,0 +1,212 @@
/**
* features/chat/composables/useChatSessions.ts
* 单 Agent 侧栏会话历史:服务端列表加载、进行中 run 合并展示、选中/删除/清空。
*/
import { computed, ref, watch, type ComputedRef, type Ref } from 'vue';
import {
deleteAllChatSessions,
deleteChatSession,
listChatSessions,
} from '../api/chat.api';
import type { ChatRun, ChatSessionItem, DisplayHistoryItem } from '../types/chat.types';
import type { ChatDeps } from './chat.deps';
import { useChatStore } from '../stores/chat.store';
export interface UseChatSessionsOptions {
deps: ChatDeps;
currentAgentId: ComputedRef<number>;
conversationId: Ref<string | null>;
activeRunId: Ref<number | null>;
runs: Ref<ChatRun[]>;
activateRun: (runId: number) => void;
/** 延迟绑定:ChatView 中 loadConversation 在 composable 初始化之后才赋值 */
loadConversation: (id: string, options?: { force?: boolean }) => Promise<void>;
isSidebarOpen: Ref<boolean>;
/** 删除确认弹窗(由 ChatView 提供) */
onConfirmDelete: (message: string, action: () => Promise<void> | void) => void;
/** 新建对话:清空视图并同步路由 query */
startNewChat: () => void;
}
export function useChatSessions(options: UseChatSessionsOptions) {
const {
deps: { t, router, route },
currentAgentId,
conversationId,
activeRunId,
runs,
activateRun,
loadConversation,
isSidebarOpen,
onConfirmDelete,
startNewChat,
} = options;
const chatStore = useChatStore();
// ── 服务端会话列表 ────────────────────────────────────────
const history = ref<ChatSessionItem[]>([]);
const hydrateHistoryFromStore = (agentId: number) => {
const cached = chatStore.getSessionHistory(agentId);
history.value = cached ? [...cached] : [];
};
const loadHistory = async () => {
const agentId = currentAgentId.value;
if (!agentId) return;
hydrateHistoryFromStore(agentId);
try {
const items = await listChatSessions(agentId);
history.value = items;
chatStore.setSessionHistory(agentId, items);
} catch (e) {
console.error('Failed to load history', e);
}
};
/** Agent 切换时先展示该 Agent 的缓存列表 */
const clearHistory = () => {
const agentId = currentAgentId.value;
if (agentId) {
hydrateHistoryFromStore(agentId);
return;
}
history.value = [];
};
// ── 展示列表:合并进行中 run 与服务端记录 ─────────────────
const activeHistoryKey = computed(() => {
if (conversationId.value) return conversationId.value;
if (activeRunId.value) return `pending:${activeRunId.value}`;
return '';
});
const displayHistory = computed<DisplayHistoryItem[]>(() => {
const server = history.value || [];
const serverIds = new Set(server.map((h) => h.conversation_id));
const pending: DisplayHistoryItem[] = (runs.value || [])
.filter((r) => r.agentId === currentAgentId.value)
.filter((r) => r.status === 'running')
.filter((r) => r.runId !== activeRunId.value)
.map((r) => ({
id: 0,
conversation_id: r.conversationId || `pending:${r.runId}`,
title: (r.query || '').trim(),
created_at: r.createdAt,
__runId: r.runId,
__status: r.status,
}))
.filter((item) => item.conversation_id.startsWith('pending:') || !serverIds.has(item.conversation_id));
const merged = [...pending, ...server] as DisplayHistoryItem[];
merged.sort((a, b) => String(b.created_at || '').localeCompare(String(a.created_at || '')));
return merged;
});
// ── 选中会话:优先恢复 run,否则拉取消息并同步路由 ───────
const handleHistorySelect = async (item: DisplayHistoryItem) => {
if (item.__runId) {
activateRun(item.__runId);
isSidebarOpen.value = false;
return;
}
const run = runs.value.find(
(r) => r.agentId === currentAgentId.value && r.conversationId === item.conversation_id,
);
if (run && run.status === 'running') {
activateRun(run.runId);
isSidebarOpen.value = false;
return;
}
await loadConversation(item.conversation_id, { force: true });
isSidebarOpen.value = false;
if (item.conversation_id.startsWith('pending:')) return;
const currentConvId = typeof route.query.conversation_id === 'string' ? route.query.conversation_id : '';
if (currentConvId === item.conversation_id) return;
const nextQuery: Record<string, string | string[]> = { ...route.query, conversation_id: item.conversation_id };
delete nextQuery.task_id;
delete nextQuery.preset;
await router.replace({ path: route.path, query: nextQuery });
};
// ── 发送后 / 新会话 ID:按需刷新侧栏 ─────────────────────
const refreshHistoryAfterSend = async () => {
if (!conversationId.value && history.value.length === 0) {
await loadHistory();
return;
}
if (conversationId.value) {
const exists = history.value.some((h) => h.conversation_id === conversationId.value);
if (!exists) await loadHistory();
}
};
const setupConversationIdHistoryWatch = () =>
watch(
() => conversationId.value,
async (id, prev) => {
if (!id || id === prev) return;
const exists = history.value.some((item) => item.conversation_id === id);
if (!exists) {
await loadHistory();
}
},
);
// ── 删除单条 / 清空全部 ───────────────────────────────────
const clearAllHistory = async () => {
onConfirmDelete(t('chat.confirmClearHistory'), async () => {
try {
const agentId = currentAgentId.value;
await deleteAllChatSessions(agentId);
history.value = [];
chatStore.setSessionHistory(agentId, []);
runs.value = [];
if (conversationId.value || activeRunId.value) {
startNewChat();
}
} catch (e) {
console.error('Failed to clear history', e);
}
});
};
const deleteHistoryItem = async (id: string, event: Event) => {
event.stopPropagation();
onConfirmDelete(t('chat.confirmDeleteHistoryItem'), async () => {
try {
const agentId = currentAgentId.value;
await deleteChatSession(id, agentId);
history.value = history.value.filter((h) => h.conversation_id !== id);
chatStore.patchSessionHistory(agentId, history.value);
runs.value = runs.value.filter(
(r) => !(r.agentId === currentAgentId.value && r.conversationId === id),
);
if (conversationId.value === id) {
startNewChat();
}
} catch (e) {
console.error('Failed to delete history item', e);
}
});
};
return {
history,
loadHistory,
clearHistory,
displayHistory,
activeHistoryKey,
handleHistorySelect,
refreshHistoryAfterSend,
setupConversationIdHistoryWatch,
clearAllHistory,
deleteHistoryItem,
};
}
@@ -0,0 +1,360 @@
/**
* features/chat/composables/useChatShipping.ts
* 发货通知(出货)编排层:组合 shipping/* 子模块,对外暴露 ChatView 所需 API。
*
* 子模块职责:
* shippingText / shippingMenu / shippingIntents … 纯函数
* useChatShippingRefresh 动作按钮刷新
* useChatShippingMappingForm 库存列映射表单
* useChatShippingDecision 人工决策与手工上传
* useChatShippingMenuHandler 气泡动作按钮点击
* useChatShippingUploadHandler 文件上传与建议提示
* useChatShippingSendHandler handleSend 前置拦截
*
* 消息类型约定(写入 messages 列表):
* - shipping-inventory-mapping:库存列映射表单
*/
import {
computed,
ref,
watch,
type ComputedRef,
type Ref,
} from 'vue';
import { SHIPPING_NOTICE_AGENT_NAME } from '@/features/chat/api/shipping.api';
import {
createShippingActionsRefresher,
createShippingConversationHelpers,
createShippingDecisionHandlers,
createShippingLocalMessages,
createShippingMappingFormHandlers,
createShippingMenuHandlers,
createShippingSendHandlers,
createShippingUploadHandlers,
extractShippingActionsDirective,
findHistorySessionForShippingTask,
findLatestShippingTaskId,
getShippingInventoryMappingPayload,
getShippingInventorySampleRowText,
hasShippingInventorySampleRows,
normalizeShippingHeaderForDisplay,
sanitizeShippingConversationText,
shippingActionButtonClass,
} from '../shipping';
import type { ChatMessage, ChatSessionItem } from '../types/chat.types';
import type { ChatUploadFileSpec, PendingAttachment } from '../types/shipping.types';
import type { ChatDeps } from './chat.deps';
export interface UseChatShippingOptions {
deps: ChatDeps;
currentAgent: Ref<{ name?: string } | null>;
currentAgentId: ComputedRef<number>;
messages: Ref<ChatMessage[]>;
conversationId: Ref<string | null>;
isThinking: Ref<boolean>;
history: Ref<ChatSessionItem[]>;
loadHistory: () => Promise<void>;
input: Ref<string>;
chatScrollContainer: Ref<HTMLElement | null>;
attachments: Ref<PendingAttachment[]>;
selectedKb: Ref<string>;
isUploadingAttachments: Ref<boolean>;
attachmentPolicy: ComputedRef<{ anyEnabled: boolean }>;
presetQuestion: ComputedRef<string>;
saveLocalMessageToBackend: (msg: ChatMessage, userQuery?: string) => Promise<void>;
newLocalMessageId: (prefix: string) => string;
stripReasoningPrelude: (text: string) => string;
sendMessage: (
content: string,
agentId: number,
kb: string,
files: ChatUploadFileSpec[],
) => Promise<void>;
buildFileSpecsForSend: () => Promise<ChatUploadFileSpec[]>;
loadConversation: (id: string, options?: { force?: boolean }) => Promise<void>;
createNewChatView: () => void;
}
export function useChatShipping(options: UseChatShippingOptions) {
const {
deps: { t, msg, router, route },
currentAgent,
currentAgentId,
messages,
conversationId,
isThinking,
history,
loadHistory,
input,
chatScrollContainer,
attachments,
selectedKb,
isUploadingAttachments,
attachmentPolicy,
presetQuestion,
saveLocalMessageToBackend,
newLocalMessageId,
stripReasoningPrelude,
sendMessage,
buildFileSpecsForSend,
loadConversation,
createNewChatView,
} = options;
let invokeHandleSend: (() => Promise<void>) | null = null;
const shippingBindSend = (fn: () => Promise<void>) => {
invokeHandleSend = fn;
};
// ── 功能开关与 UI refs ────────────────────────────────────
const isShippingNoticeAgent = computed(() => currentAgent.value?.name === SHIPPING_NOTICE_AGENT_NAME);
const allowsSendWithAttachmentsOnly = computed(
() => isShippingNoticeAgent.value && attachments.value.length > 0,
);
const shippingAutoFlowRequested = ref(false);
const shippingInventoryPickerRef = ref<HTMLInputElement | null>(null);
const pendingShippingUploadTaskId = ref('');
const prepareMarkdownDisplayText = (text: string) => {
const stripped = isShippingNoticeAgent.value ? extractShippingActionsDirective(text).cleanedText : text;
return sanitizeShippingConversationText(stripReasoningPrelude(stripped), isShippingNoticeAgent.value);
};
// ── 任务编号状态 ──────────────────────────────────────────
const shippingTaskIdFromQuery = computed(() => {
const value = route.query.task_id;
return typeof value === 'string' ? value.trim() : '';
});
const resolvedShippingTaskId = ref('');
const shippingConversationTaskIdCache = ref<Record<string, string>>({});
const shippingInventorySchemaPreviewCache = ref<Record<string, unknown>>({});
const autoResumedShippingTasks = ref<Record<string, boolean>>({});
const getActiveShippingTaskId = () =>
findLatestShippingTaskId(messages.value)
|| resolvedShippingTaskId.value
|| shippingTaskIdFromQuery.value
|| '';
const lastAssistantMessageContent = () => {
for (let i = messages.value.length - 1; i >= 0; i -= 1) {
const item = messages.value[i];
if (item?.role === 'assistant') return String(item.content || '');
}
return '';
};
const { refreshShippingActions } = createShippingActionsRefresher({
isShippingNoticeAgent,
messages,
conversationId,
isThinking,
history,
resolvedShippingTaskId,
shippingTaskIdFromQuery,
shippingConversationTaskIdCache,
});
const { pushShippingLocalUserMessage, pushShippingLocalAssistantMessage } = createShippingLocalMessages({
messages,
newLocalMessageId,
saveLocalMessageToBackend,
});
const { sendShippingMenuMessage } = createShippingConversationHelpers({
conversationId,
history,
loadHistory,
getActiveShippingTaskId,
currentAgentId,
selectedKb,
sendMessage,
});
const {
openShippingInventoryMappingFormForTask,
applyShippingInventoryMappingForm,
reuploadShippingInventoryFromMappingForm,
} = createShippingMappingFormHandlers({
messages,
chatScrollContainer,
shippingInventorySchemaPreviewCache,
shippingInventoryPickerRef,
pendingShippingUploadTaskId,
resolvedShippingTaskId,
newLocalMessageId,
saveLocalMessageToBackend,
pushShippingLocalAssistantMessage,
refreshShippingActions,
msg,
});
const { executeShippingDecision, executeShippingManualUpload } = createShippingDecisionHandlers({
messages,
conversationId,
history,
isShippingNoticeAgent,
shippingInventorySchemaPreviewCache,
getActiveShippingTaskId,
newLocalMessageId,
saveLocalMessageToBackend,
loadHistory,
openShippingInventoryMappingFormForTask,
refreshShippingActions,
msg,
t,
});
const {
handleShippingAutoUploadFile,
openShippingInventoryPicker,
handleShippingInventorySelected,
shippingSuggestedPrompt,
useShippingSuggestedPrompt,
} = createShippingUploadHandlers({
conversationId,
attachments,
input,
shippingAutoFlowRequested,
shippingInventoryPickerRef,
pendingShippingUploadTaskId,
resolvedShippingTaskId,
shippingInventorySchemaPreviewCache,
getActiveShippingTaskId,
sendShippingMenuMessage,
pushShippingLocalAssistantMessage,
refreshShippingActions,
msg,
t,
});
const { handleShippingActionClick } = createShippingMenuHandlers({
isThinking,
getActiveShippingTaskId,
messages,
newLocalMessageId,
saveLocalMessageToBackend,
sendShippingMenuMessage,
openShippingInventoryMappingFormForTask,
openShippingInventoryPicker,
executeShippingDecision,
executeShippingManualUpload,
refreshShippingActions,
msg,
t,
});
const { tryHandleShippingSend, tryHandleShippingAttachmentAutoFlow } = createShippingSendHandlers({
isShippingNoticeAgent,
isThinking,
isUploadingAttachments,
messages,
conversationId,
history,
input,
attachments,
shippingAutoFlowRequested,
resolvedShippingTaskId,
currentAgentId,
selectedKb,
attachmentPolicy,
getActiveShippingTaskId,
lastAssistantMessageContent,
sendMessage,
buildFileSpecsForSend,
loadHistory,
sendShippingMenuMessage,
pushShippingLocalUserMessage,
pushShippingLocalAssistantMessage,
openShippingInventoryPicker,
executeShippingDecision,
executeShippingManualUpload,
handleShippingAutoUploadFile,
refreshShippingActions,
shippingSuggestedPrompt,
msg,
t,
});
// ── 路由 / 会话生命周期 ───────────────────────────────────
const resumeShippingTaskFromQuery = async () => {
const taskId = shippingTaskIdFromQuery.value;
if (!taskId || !isShippingNoticeAgent.value) return;
if (route.query.conversation_id) return;
if (presetQuestion.value) return;
if (autoResumedShippingTasks.value[taskId]) return;
const existing = findHistorySessionForShippingTask(history.value, taskId);
if (existing) {
await loadConversation(existing.conversation_id, { force: true });
return;
}
autoResumedShippingTasks.value[taskId] = true;
input.value = t('chat.shippingNoticeContinue', { taskId });
await invokeHandleSend?.();
};
const onConversationIdChanging = (nextId: string, prevId: string | null | undefined) => {
if (prevId !== nextId) {
resolvedShippingTaskId.value = '';
}
};
const onConversationLoadedEmpty = async () => {
if (!isShippingNoticeAgent.value || !shippingTaskIdFromQuery.value || isThinking.value) return;
await router.replace({ path: route.path, query: { task_id: shippingTaskIdFromQuery.value } });
};
const onConversationLoadFailed = async () => {
if (!isShippingNoticeAgent.value || !shippingTaskIdFromQuery.value || isThinking.value) return;
createNewChatView();
void router.replace({ path: route.path, query: { task_id: shippingTaskIdFromQuery.value } });
input.value = t('chat.shippingNoticeContinue', { taskId: shippingTaskIdFromQuery.value });
await invokeHandleSend?.();
};
// ── 动作按钮 watch ────────────────────────────────────────
const shippingActionsWatchKey = computed(() => {
const msgs = messages.value;
const last = msgs.length ? msgs[msgs.length - 1] : null;
return [
String(conversationId.value || ''),
String(msgs.length),
String(last?.role || ''),
String(last?.content || '').slice(-120),
].join('|');
});
watch([shippingActionsWatchKey, isThinking, isShippingNoticeAgent, () => currentAgent.value?.name], () => {
void refreshShippingActions();
});
return {
shippingBindSend,
isShippingNoticeAgent,
prepareMarkdownDisplayText,
shippingAutoFlowRequested,
shippingInventoryPickerRef,
pendingShippingUploadTaskId,
allowsSendWithAttachmentsOnly,
shippingTaskIdFromQuery,
resumeShippingTaskFromQuery,
normalizeShippingHeaderForDisplay,
getShippingInventoryMappingPayload,
hasShippingInventorySampleRows,
getShippingInventorySampleRowText,
applyShippingInventoryMappingForm,
reuploadShippingInventoryFromMappingForm,
handleShippingActionClick,
handleShippingInventorySelected,
shippingActionButtonClass,
shippingSuggestedPrompt,
useShippingSuggestedPrompt,
tryHandleShippingAttachmentAutoFlow,
tryHandleShippingSend,
onConversationIdChanging,
onConversationLoadedEmpty,
onConversationLoadFailed,
};
}
@@ -1,4 +1,4 @@
/**
/**
* features/chat/composables/useChatSourceFiles.ts
* 检索来源 / 源文件链接解析与预览。
*/
@@ -6,7 +6,7 @@ import { ref, type ComputedRef, type Ref } from 'vue';
import type { ComposerTranslation } from 'vue-i18n';
import { resolveChatSourceFile } from '../api/chat.api';
import type { SourceFileLink } from '../types/chat.types';
import type { useMessage } from '@/composables/useMessage';
import type { useMessage } from '@/shared/composables/useMessage';
const PREFERRED_SOURCE_EXTS = new Set([
'pdf', 'doc', 'docx', 'ppt', 'pptx', 'xls', 'xlsx', 'csv',
@@ -0,0 +1,63 @@
/**
* features/chat/constants/leave.ts
* 请假功能常量:启用 Agent、假别编码、OA 跳转地址。
*/
/** 支持本地请假表单的 Agent 名称白名单 */
export const LEAVE_FEATURE_AGENT_NAMES = new Set(['通用入口', '人事规章']);
/** OA 系统基础地址(自动登录表单提交目标) */
export const OA_BASE_URL = 'http://192.168.100.221:8888';
export const OA_VERIFY_LOGIN_URL = `${OA_BASE_URL}/login/VerifyLogin.jsp`;
export const OA_LEAVE_APPLY_PATH = '/workflow/request/AddRequest.jsp?workflowid=652&isagent=0&beagenter=0&f_weaver_belongto_userid=';
export const OA_REQUEST_VIEW_PATH = '/workflow/request/ViewRequest.jsp?requestid=';
export const OA_AUTO_LOGIN_TARGET = 'hxops-oa-leave-request';
export const OA_PASSWORD_STORAGE_KEY = 'hxops_oa_login_password';
/** 下拉假别选项(value 为 OA 编码) */
export const LEAVE_TYPES = [
{ label: '事假(小时)', value: '005' },
{ label: '病假(小时)', value: '006' },
{ label: '丧假(天)', value: '007' },
{ label: '年假(天)', value: '010' },
{ label: '因公出差(小时)', value: '021' },
{ label: '调休假(小时)', value: '025' },
{ label: '产假(天)', value: '401' },
{ label: '陪产假(天)', value: '402' },
{ label: '婚假(天)', value: '403' },
{ label: '住院病假(小时)', value: '405' },
{ label: '工伤假(天)', value: '406' },
{ label: '返乡假(小时)', value: 'ZZ01' },
{ label: '事假(经理专用小时)', value: 'ZZ04' },
{ label: '病假(经理专用小时)', value: 'ZZ05' },
{ label: '丧假(经理专用天)', value: 'ZZ07' },
{ label: '产假(经理专用天)', value: 'ZZ08' },
{ label: '陪产假(经理专用天)', value: 'ZZ09' },
{ label: '婚假(经理专用天)', value: 'ZZ10' },
{ label: '其他假(小时)', value: '035' },
{ label: '育儿假(小时)', value: '408' },
] as const;
/** 按「天」计价的假别编码 */
export const LEAVE_TYPE_BY_DAY = new Set(['010', '007', '401', '402', '403', '406', 'ZZ07', 'ZZ08', 'ZZ09', 'ZZ10']);
/** 自然语言关键词 → OA 假别编码 */
export const LEAVE_TYPE_MAP: Record<string, string> = {
事假: '005',
病假: '006',
丧假: '007',
年假: '010',
因公出差: '021',
出差: '021',
调休: '025',
产假: '401',
陪产假: '402',
婚假: '403',
住院: '405',
工伤: '406',
育儿假: '408',
返乡: 'ZZ01',
};
/** 发起前需校验余额的假别(年假、育儿假) */
export const NEED_BALANCE_CHECK_TYPES = new Set(['010', '408']);
@@ -0,0 +1,39 @@
/**
* features/chat/constants/shipping.ts
* 发货通知功能常量:任务编号正则、菜单动作规格与决策动作集合。
*/
import type { ShippingMenuAction } from '../types/shipping.types';
/** 工作区发货任务编号格式(如 SN-20250610-ABCDEF12) */
export const SHIPPING_TASK_ID_RE = /SN-\d{8}-[A-F0-9]{8}/i;
export const SHIPPING_MENU_ACTION_SPECS: Record<
ShippingMenuAction,
{ id: string; label: string; message: string; variant: 'primary' | 'secondary' | 'danger' }
> = {
upload: { id: 'upload_inventory_file', label: '选择库存文件', message: '我要上传库存 Excel', variant: 'primary' },
paste: { id: 'paste_inventory_json', label: '粘贴库存', message: '我粘贴库存小表', variant: 'secondary' },
retry_rpa: { id: 'retry_rpa', label: '重试 RPA', message: '重试 RPA 导出库存', variant: 'secondary' },
confirm: { id: 'confirm', label: '确认', message: '确认', variant: 'primary' },
reparse: { id: 'reparse', label: '重新解析', message: '重新解析', variant: 'secondary' },
reject: { id: 'reject', label: '驳回', message: '驳回', variant: 'danger' },
};
export const SHIPPING_DECISION_ACTIONS = new Set([
'confirm',
'confirm_inventory_mapping',
'correct_inventory_mapping',
'reparse_inventory',
'reject',
'reparse',
'rematch',
]);
/** 从文件名或 URL 提取扩展名(小写,不含点) */
export const extractExt = (value: string) => {
const text = (value || '').trim().toLowerCase();
const withoutQuery = (text.split('?')[0] || '').split('#')[0] || '';
const idx = withoutQuery.lastIndexOf('.');
if (idx < 0) return '';
return withoutQuery.slice(idx + 1).trim();
};
+24
View File
@@ -4,6 +4,30 @@
*/
export { useChat } from './composables/useChat';
export { useChatHistory } from './composables/useChatHistory';
export { useChatLeave } from './composables/useChatLeave';
export { useChatShipping } from './composables/useChatShipping';
export { useChatSessions } from './composables/useChatSessions';
export { default as ChatSidebar } from './components/ChatSidebar.vue';
export { default as ChatInputBar } from './components/ChatInputBar.vue';
export { default as ChatWelcomePanel } from './components/ChatWelcomePanel.vue';
export { default as ChatThinkingBubble } from './components/ChatThinkingBubble.vue';
export { useChatSourceFiles } from './composables/useChatSourceFiles';
export { useChatBrowserPanel } from './composables/useChatBrowserPanel';
export { useChatQueryPreview } from './composables/useChatQueryPreview';
export { useChatScroll } from './composables/useChatScroll';
export { useChatPage } from './composables/useChatPage';
export { useChatGuides } from './composables/useChatGuides';
export { useChatAgent } from './composables/useChatAgent';
export { useChatAttachments } from './composables/useChatAttachments';
export { useChatRouteSync } from './composables/useChatRouteSync';
export { useChatStore } from './stores/chat.store';
export {
CHAT_PAGE_KEY,
useChatPageContext,
type ChatPageContext,
type ChatPageContextProvided,
} from './composables/chat.context';
export * from './api/chat.api';
export * from './api/shipping.api';
export type * from './types/chat.types';
export type * from './types/shipping.api.types';
+10
View File
@@ -0,0 +1,10 @@
/** 请假(leave)子模块 barrel:纯函数 + handler 工厂 */
export * from './leaveDateTime';
export * from './leaveDisplay';
export * from './leaveIntent';
export * from './leavePayload';
export * from './leaveLocalMessage';
export * from './useChatLeaveOaLogin';
export * from './useChatLeaveAgentPicker';
export * from './useChatLeaveForm';
export * from './useChatLeaveFlow';
@@ -0,0 +1,50 @@
/**
* 请假:日期时间解析、按天/按小时时长计算。
*/
import { LEAVE_TYPE_BY_DAY } from '../constants/leave';
export function formatDateTime(date: Date): string {
const year = date.getFullYear();
const month = String(date.getMonth() + 1).padStart(2, '0');
const day = String(date.getDate()).padStart(2, '0');
const hours = String(date.getHours()).padStart(2, '0');
const minutes = String(date.getMinutes()).padStart(2, '0');
return `${year}-${month}-${day}T${hours}:${minutes}`;
}
export function parseDateTime(value: string): Date | null {
const normalized = (value || '').trim().replace('T', ' ');
const match = normalized.match(/^(\d{4})-(\d{2})-(\d{2})\s+(\d{2}):(\d{2})$/);
if (!match) return null;
const [, year, month, day, hour, minute] = match;
const date = new Date(Number(year), Number(month) - 1, Number(day), Number(hour), Number(minute));
return Number.isNaN(date.getTime()) ? null : date;
}
export function isLeaveTypeByDay(leaveType: string): boolean {
return LEAVE_TYPE_BY_DAY.has(leaveType);
}
export function calculateDurationHours(startTime: string, endTime: string): number {
const start = parseDateTime(startTime);
const end = parseDateTime(endTime);
if (!start || !end || end.getTime() <= start.getTime()) return 0;
return Number((((end.getTime() - start.getTime()) / 1000 / 60 / 60)).toFixed(2));
}
export function syncLeaveDuration(form: { leaveType: string; startTime: string; endTime: string; durationHours: number }) {
if (isLeaveTypeByDay(form.leaveType)) {
const start = parseDateTime(form.startTime);
const end = parseDateTime(form.endTime);
if (!start || !end || end.getTime() <= start.getTime()) {
form.durationHours = 0;
return;
}
const startDate = new Date(start.getFullYear(), start.getMonth(), start.getDate());
const endDate = new Date(end.getFullYear(), end.getMonth(), end.getDate());
const days = Math.max(1, Math.round((endDate.getTime() - startDate.getTime()) / (24 * 3600 * 1000)) + 1);
form.durationHours = days * 8;
} else {
form.durationHours = calculateDurationHours(form.startTime, form.endTime);
}
}
@@ -0,0 +1,36 @@
/**
* 请假:假种标签、时长/是否展示、余额数字格式化。
*/
import { LEAVE_TYPES } from '../constants/leave';
import { isLeaveTypeByDay } from './leaveDateTime';
export function getLeaveTypeLabel(val: string): string {
const item = LEAVE_TYPES.find((x) => x.value === val);
return item ? item.label : val;
}
export function formatDurationLabel(
hours: number,
leaveType: string | undefined,
t: (key: string) => string,
): string {
if (!hours) return `0 ${isLeaveTypeByDay(leaveType || '') ? t('chat.dayUnit') : t('chat.hourUnit')}`;
if (isLeaveTypeByDay(leaveType || '')) {
const days = Math.round(hours / 8);
return `${days} ${t('chat.dayUnit')}`;
}
return `${hours} ${t('chat.hourUnit')}`;
}
export function formatYesNoLabel(value: 0 | 1 | null): string {
if (value === 0) return '是';
if (value === 1) return '否';
return '未选择';
}
export function formatLeaveBalanceNumber(value: unknown, t: (key: string) => string): string {
if (value === null || value === undefined) return t('chat.noData');
const num = Number(value);
if (Number.isNaN(num)) return String(value);
return Number.isInteger(num) ? String(num) : num.toFixed(2);
}
@@ -0,0 +1,149 @@
/**
* 请假:自然语言意图解析与强/弱意图区分。
*/
import { LEAVE_TYPE_MAP } from '../constants/leave';
import type { ExtractedLeaveInfo } from '../types/leave.types';
import { calculateDurationHours, isLeaveTypeByDay, parseDateTime } from './leaveDateTime';
export function extractLeaveTypeFromIntent(content: string): string {
if (!content) return '';
for (const [key, val] of Object.entries(LEAVE_TYPE_MAP)) {
if (content.includes(key)) return val;
}
return '';
}
export function extractLeaveInfoFromIntent(content: string): ExtractedLeaveInfo | null {
const normalized = content.replace(/\s+/g, ' ').trim();
let leaveType = extractLeaveTypeFromIntent(normalized);
let startTime = '';
let endTime = '';
let durationHours = 0;
const today = new Date();
const thisYear = today.getFullYear();
const parseDateStr = (m: RegExpMatchArray | null, groupOffset: number): Date | null => {
if (!m) return null;
const rawMo = m[groupOffset];
const rawDa = m[groupOffset + 1];
if (!rawMo || !rawDa) return null;
const mo = parseInt(rawMo, 10);
const da = parseInt(rawDa, 10);
if (Number.isNaN(mo) || Number.isNaN(da) || mo < 1 || mo > 12 || da < 1 || da > 31) return null;
return new Date(thisYear, mo - 1, da, 9, 0);
};
const fmtDt = (d: Date, hour: number, minute: number) => {
const y = d.getFullYear();
const mo = String(d.getMonth() + 1).padStart(2, '0');
const da = String(d.getDate()).padStart(2, '0');
const h = String(hour).padStart(2, '0');
const mi = String(minute).padStart(2, '0');
return `${y}-${mo}-${da}T${h}:${mi}`;
};
let startDay: Date | null = null;
let endDay: Date | null = null;
const startHM = { h: 9, m: 0 };
let endHM = { h: 18, m: 0 };
const rangeM = normalized.match(/从?(\d{1,2})[月./-](\d{1,2})[日号]?[到至—\-–](\d{1,2})[月./-]?(\d{1,2})[日号]?/);
if (rangeM) {
const s = parseDateStr(rangeM, 1);
if (rangeM[3] && rangeM[3].length <= 2 && rangeM[4] && rangeM[4].length <= 2) {
const eMo = parseInt(rangeM[3]!, 10);
const eDa = parseInt(rangeM[4]!, 10);
if (!Number.isNaN(eMo) && eMo >= 1 && eMo <= 12 && !Number.isNaN(eDa) && eDa >= 1 && eDa <= 31) {
endDay = new Date(thisYear, eMo - 1, eDa, 18, 0);
} else if (!Number.isNaN(eDa) && eDa >= 1 && eDa <= 31 && s) {
endDay = new Date(thisYear, s.getMonth(), eDa, 18, 0);
}
}
if (s) startDay = s;
}
if (!startDay) {
const singleM = normalized.match(/(\d{1,2})[月./-](\d{1,2})[日号]?/);
if (singleM) {
const s = parseDateStr(singleM, 1);
if (s) {
startDay = s;
const dayUnitM = normalized.match(/(\d+\.?\d*)\s*[天日]/);
if (dayUnitM?.[1]) {
const days = parseFloat(dayUnitM[1]);
if (days > 1) endDay = new Date(s.getFullYear(), s.getMonth(), s.getDate() + Math.ceil(days) - 1, 18, 0);
else endDay = new Date(s.getFullYear(), s.getMonth(), s.getDate(), 18, 0);
} else {
endDay = new Date(s.getFullYear(), s.getMonth(), s.getDate(), 18, 0);
}
}
}
}
const hourM = normalized.match(/(\d+\.?\d*)\s*小时/);
if (hourM?.[1]) {
durationHours = parseFloat(hourM[1]);
if (startDay && !endDay) {
endDay = new Date(startDay.getTime() + durationHours * 3600000);
}
}
const dayM = normalized.match(/(\d+\.?\d*)\s*[天日]/);
if (dayM?.[1] && !hourM) {
const days = parseFloat(dayM[1]);
durationHours = days * 8;
if (startDay && !endDay) {
endDay = new Date(startDay.getFullYear(), startDay.getMonth(), startDay.getDate() + Math.ceil(days) - 1, 18, 0);
}
}
if (startDay) {
if (durationHours > 0 && durationHours <= 8 && !endDay) {
endDay = new Date(startDay.getTime() + durationHours * 3600000);
}
startTime = fmtDt(startDay, startHM.h, startHM.m);
}
if (endDay) {
if (hourM && durationHours <= 8) {
endHM = { h: 9 + Math.floor(durationHours), m: (durationHours % 1) * 60 };
} else if (!hourM && durationHours > 0 && durationHours <= 8) {
endHM = { h: 9 + Math.floor(durationHours), m: 0 };
}
endTime = fmtDt(endDay, endHM.h, endHM.m);
}
if (startTime && endTime) {
if (isLeaveTypeByDay(leaveType)) {
const s = parseDateTime(startTime);
const e = parseDateTime(endTime);
if (s && e && e.getTime() > s.getTime()) {
const sd = new Date(s.getFullYear(), s.getMonth(), s.getDate());
const ed = new Date(e.getFullYear(), e.getMonth(), e.getDate());
const days = Math.max(1, Math.round((ed.getTime() - sd.getTime()) / (24 * 3600 * 1000)) + 1);
durationHours = days * 8;
}
} else {
durationHours = durationHours || calculateDurationHours(startTime, endTime);
}
}
if (!leaveType && !startTime) return null;
return { leaveType, startTime, endTime, durationHours };
}
export function getLeaveIntentNormalized(content: string): string {
return (content || '').replace(/\s+/g, '');
}
/** 区分「真请假」与「咨询流程/材料」类弱意图 */
export function isStrongLeaveIntent(content: string): boolean {
const normalized = getLeaveIntentNormalized(content);
const weakConsultationIntent = /(请假流程|请假怎么走|请假步骤|请假如何申请|请假如何走流程|请假怎么办|请假需要什么|请假规定|请假管理办法|请假制度)/;
const materialConsultationIntent = /(提交哪些|提交什么|需要哪些|需要什么|要提交哪些|要提交什么|哪些资料|哪些材料|什么资料|什么材料|申请材料|所需资料|所需材料)/;
if (weakConsultationIntent.test(normalized)) return false;
if (materialConsultationIntent.test(normalized)) return false;
if (/^(请假|休假|年假|事假|病假|调休|休年假|请事假|请病假|请年假)$/.test(normalized)) return true;
return /(我要请|申请请|发起请|请假申请|我要休|申请休|想请|帮我请|代我请|提交请|帮我申请|我要申请|想申请|申请.*假|请.*假|休.*假)/.test(normalized);
}
@@ -0,0 +1,43 @@
/**
* 请假:本地消息 ID 生成与落库。
*/
import { saveLocalChatMessage } from '../api/chat.api';
import type { ChatMessage } from '../types/chat.types';
import type { ComputedRef, Ref } from 'vue';
export interface LeaveLocalMessageContext {
conversationId: Ref<string | null>;
currentAgentId: ComputedRef<number>;
}
export function createLeaveLocalMessageApi(ctx: LeaveLocalMessageContext) {
let leaveFlowCounter = 0;
const newLocalMessageId = (prefix: string) => {
leaveFlowCounter += 1;
return `${prefix}-${Date.now()}-${leaveFlowCounter}`;
};
const saveLocalMessageToBackend = async (chatMsg: ChatMessage, userQuery = '') => {
try {
const data = await saveLocalChatMessage({
conversation_id: ctx.conversationId.value,
type: chatMsg.type,
content: chatMsg.content,
payload: chatMsg.payload,
query: userQuery,
agent_id: ctx.currentAgentId.value,
});
if (!ctx.conversationId.value && data.conversation_id) {
ctx.conversationId.value = data.conversation_id;
}
if (data.chat_log_id) {
chatMsg.chat_log_id = data.chat_log_id;
}
} catch (e) {
console.error('Failed to save local message', e);
}
};
return { newLocalMessageId, saveLocalMessageToBackend };
}
@@ -0,0 +1,34 @@
/**
* 请假:leave-form / leave-confirmation / leave-result payload 读取。
*/
import type { ChatMessage } from '../types/chat.types';
import type {
LeaveConfirmationPayload,
LeaveFormPayload,
LeaveRequestFormData,
LeaveResultPayload,
} from '../types/leave.types';
import type { Ref } from 'vue';
export function getLeaveFormPayload(chatMsg: ChatMessage): LeaveFormPayload | null {
return chatMsg?.type === 'leave-form' && chatMsg?.payload ? chatMsg.payload as LeaveFormPayload : null;
}
export function getLeaveConfirmationPayload(chatMsg: ChatMessage): LeaveConfirmationPayload | null {
return chatMsg?.type === 'leave-confirmation' && chatMsg?.payload ? chatMsg.payload as LeaveConfirmationPayload : null;
}
export function getLeaveResultPayload(chatMsg: ChatMessage): LeaveResultPayload | null {
return chatMsg?.type === 'leave-result' && chatMsg?.payload ? chatMsg.payload as LeaveResultPayload : null;
}
export function findMessageIndexByLocalId(messages: Ref<ChatMessage[]>, localId: string): number {
return messages.value.findIndex((m) => m?.local_id === localId || (m?.payload as LeaveFormPayload | undefined)?.formId === localId);
}
export function getLeaveAgentDisplayValue(form: LeaveRequestFormData): string {
if (!form.agentName) return '';
const parts = [form.agentName];
if (form.agentEmployeeId) parts.push(form.agentEmployeeId);
return parts.join(' / ');
}
@@ -0,0 +1,159 @@
/**
* 请假:OA 员工(代理人/申请人)搜索选择弹窗。
*/
import { ref } from 'vue';
import { listOaEmployees } from '../api/chat.api';
import {
findMessageIndexByLocalId,
getLeaveFormPayload,
} from './leavePayload';
import type { ChatMessage } from '../types/chat.types';
import type { LeaveAgentOption } from '../types/leave.types';
import type { ComputedRef, Ref } from 'vue';
export interface LeaveAgentPickerContext {
currentAgentId: ComputedRef<number>;
messages: Ref<ChatMessage[]>;
saveLocalMessageToBackend: (chatMsg: ChatMessage) => Promise<void>;
}
export function createLeaveAgentPickerApi(ctx: LeaveAgentPickerContext) {
const leaveAgentOptions = ref<LeaveAgentOption[]>([]);
const leaveAgentLoading = ref(false);
const leaveAgentKeyword = ref('');
const leaveAgentPage = ref(1);
const leaveAgentHasMore = ref(true);
const showLeaveAgentDialog = ref(false);
const leaveUserSelectRole = ref<'agent' | 'applicant'>('agent');
const activeLeaveAgentFormId = ref<string | null>(null);
const fetchLeaveAgents = async (isLoadMore = false) => {
if (leaveAgentLoading.value) return;
if (!isLoadMore) {
leaveAgentPage.value = 1;
leaveAgentOptions.value = [];
}
leaveAgentLoading.value = true;
try {
const data = await listOaEmployees(ctx.currentAgentId.value, {
keyword: leaveAgentKeyword.value,
page: leaveAgentPage.value,
page_size: 20,
});
if (isLoadMore) {
leaveAgentOptions.value.push(...data.items);
} else {
leaveAgentOptions.value = data.items;
}
leaveAgentHasMore.value = leaveAgentOptions.value.length < data.total;
} catch (e) {
console.error('Failed to load OA employees', e);
} finally {
leaveAgentLoading.value = false;
}
};
const handleAgentSearch = () => {
void fetchLeaveAgents(false);
};
const loadMoreAgents = () => {
if (!leaveAgentHasMore.value) return;
leaveAgentPage.value += 1;
void fetchLeaveAgents(true);
};
const loadAllAgents = async () => {
if (!leaveAgentHasMore.value || leaveAgentLoading.value) return;
leaveAgentLoading.value = true;
try {
const data = await listOaEmployees(ctx.currentAgentId.value, {
keyword: leaveAgentKeyword.value,
page: 1,
page_size: 100000,
});
leaveAgentOptions.value = data.items;
leaveAgentHasMore.value = false;
} catch (e) {
console.error('Failed to load all OA employees', e);
} finally {
leaveAgentLoading.value = false;
}
};
const openLeaveAgentDialog = (chatMsg: ChatMessage, role: 'agent' | 'applicant' = 'agent') => {
const payload = getLeaveFormPayload(chatMsg);
if (!payload || payload.submitting || payload.confirmationGenerated) return;
activeLeaveAgentFormId.value = payload.formId;
leaveUserSelectRole.value = role;
showLeaveAgentDialog.value = true;
leaveAgentKeyword.value = '';
void fetchLeaveAgents(false);
};
const closeLeaveAgentDialog = () => {
showLeaveAgentDialog.value = false;
activeLeaveAgentFormId.value = null;
};
const selectLeaveAgent = (option: LeaveAgentOption) => {
if (!activeLeaveAgentFormId.value) return;
const sourceIndex = findMessageIndexByLocalId(ctx.messages, activeLeaveAgentFormId.value);
if (sourceIndex < 0) {
closeLeaveAgentDialog();
return;
}
const sourceMsg = ctx.messages.value[sourceIndex];
if (!sourceMsg) {
closeLeaveAgentDialog();
return;
}
const payload = getLeaveFormPayload(sourceMsg);
if (!payload) {
closeLeaveAgentDialog();
return;
}
if (leaveUserSelectRole.value === 'agent') {
payload.form.agentUid = option.uid;
payload.form.agentEmployeeId = option.employeeId;
payload.form.agentName = option.name;
payload.form.agentJobTitle = option.jobtitle;
payload.form.agentJobTitleName = option.jobtitleName;
payload.form.agentDepartmentId = option.departmentid;
payload.form.agentSubCompanyId1 = option.subcompanyid1;
payload.form.agentDepartmentName = option.departmentName;
payload.form.agentSubCompanyName = option.subcompanyName;
} else {
payload.form.applicantUid = option.uid;
payload.form.employeeId = option.employeeId;
payload.form.applicantName = option.name;
payload.form.applicantJobTitle = option.jobtitle;
payload.form.applicantJobTitleName = option.jobtitleName;
payload.form.applicantDepartmentId = option.departmentid;
payload.form.applicantSubCompanyId1 = option.subcompanyid1;
payload.form.applicantDepartmentName = option.departmentName;
payload.form.applicantSubCompanyName = option.subcompanyName;
}
closeLeaveAgentDialog();
void ctx.saveLocalMessageToBackend(sourceMsg);
};
return {
leaveAgentOptions,
leaveAgentLoading,
leaveAgentKeyword,
leaveAgentPage,
leaveAgentHasMore,
showLeaveAgentDialog,
leaveUserSelectRole,
handleAgentSearch,
loadMoreAgents,
loadAllAgents,
openLeaveAgentDialog,
closeLeaveAgentDialog,
selectLeaveAgent,
};
}
@@ -0,0 +1,158 @@
/**
* 请假:强意图拦截、插入 leave-form 消息、Markdown 链接触发。
*/
import { listOaEmployees } from '../api/chat.api';
import { NEED_BALANCE_CHECK_TYPES } from '../constants/leave';
import { isStrongLeaveIntent, extractLeaveInfoFromIntent, extractLeaveTypeFromIntent } from './leaveIntent';
import type { ChatMessage, ChatSessionItem } from '../types/chat.types';
import type { ExtractedLeaveInfo, LeaveFormPayload, LeaveRequestFormData } from '../types/leave.types';
import type { ComputedRef, Ref } from 'vue';
export interface LeaveFlowContext {
canUseLeaveFeature: ComputedRef<boolean>;
isThinking: Ref<boolean>;
messages: Ref<ChatMessage[]>;
conversationId: Ref<string | null>;
history: Ref<ChatSessionItem[]>;
currentAgentId: ComputedRef<number>;
loadHistory: () => Promise<void>;
newLocalMessageId: (prefix: string) => string;
saveLocalMessageToBackend: (chatMsg: ChatMessage, userQuery?: string) => Promise<void>;
createLeaveFormData: (content?: string, extractedInfo?: ExtractedLeaveInfo | null) => LeaveRequestFormData;
checkLeaveBalance: (leaveTypeCode: string) => Promise<{
has_balance?: boolean;
leave_type_label?: string;
year?: string | number;
total_hours?: unknown;
used_hours?: unknown;
remaining_hours?: unknown;
} | null>;
formatLeaveBalanceNumber: (value: unknown) => string;
msg: { warning: (text: string) => void };
t: (key: string, params?: Record<string, unknown>) => string;
}
export function createLeaveFlowApi(ctx: LeaveFlowContext) {
const ensureHistoryListed = async () => {
if (ctx.history.value.length === 0 || !ctx.history.value.some((h) => h.conversation_id === ctx.conversationId.value)) {
await ctx.loadHistory();
}
};
const startLocalLeaveFlow = async (content: string) => {
const extractedInfo = extractLeaveInfoFromIntent(content);
const initialLeaveType = extractedInfo?.leaveType || extractLeaveTypeFromIntent(content);
if (initialLeaveType && NEED_BALANCE_CHECK_TYPES.has(initialLeaveType)) {
ctx.messages.value.push({ role: 'user', content, type: 'text' });
const thinkingMsg: ChatMessage = {
role: 'assistant',
type: 'text',
content: ctx.t('chat.queryLeaveBalance'),
};
ctx.messages.value.push(thinkingMsg);
const balance = await ctx.checkLeaveBalance(initialLeaveType);
const thinkingIndex = ctx.messages.value.indexOf(thinkingMsg);
if (thinkingIndex >= 0) {
ctx.messages.value.splice(thinkingIndex, 1);
}
if (balance && !balance.has_balance) {
const unit = initialLeaveType === '010' ? ctx.t('chat.dayUnit') : ctx.t('chat.hourUnit');
const detailLines = [
ctx.t('chat.leaveBalanceInsufficient', { label: balance.leave_type_label }),
'',
`| ${ctx.t('chat.leaveBalanceTableLeaveType')} | ${ctx.t('chat.leaveBalanceTableYear')} | ${ctx.t('chat.leaveBalanceTableAvailable')} | ${ctx.t('chat.leaveBalanceTableUsed')} | ${ctx.t('chat.leaveBalanceTableRemaining')} |`,
'| :---: | :---: | :---: | :---: | :---: |',
`| ${balance.leave_type_label} | ${balance.year} | ${ctx.formatLeaveBalanceNumber(balance.total_hours)}${unit} | ${ctx.formatLeaveBalanceNumber(balance.used_hours)}${unit} | ${ctx.formatLeaveBalanceNumber(balance.remaining_hours)}${unit} |`,
'',
ctx.t('chat.leaveBalanceContactHr'),
];
const noBalanceMsg: ChatMessage = {
role: 'assistant',
type: 'text',
content: detailLines.join('\n'),
};
ctx.messages.value.push(noBalanceMsg);
await ctx.saveLocalMessageToBackend(noBalanceMsg, content);
await ensureHistoryListed();
return;
}
}
const formId = ctx.newLocalMessageId('leave-form');
const payload: LeaveFormPayload = {
formId,
form: ctx.createLeaveFormData(content, extractedInfo),
submitting: false,
confirmationGenerated: false,
};
if (!initialLeaveType || !NEED_BALANCE_CHECK_TYPES.has(initialLeaveType)) {
ctx.messages.value.push({ role: 'user', content, type: 'text' });
}
const formMsg: ChatMessage = {
role: 'assistant',
type: 'leave-form',
content: ctx.t('chat.leaveFormIntro'),
payload,
local_id: formId,
local_only: true,
};
ctx.messages.value.push(formMsg);
try {
const keyword = payload.form.applicantName || payload.form.employeeId;
if (keyword) {
const data = await listOaEmployees(ctx.currentAgentId.value, { keyword, page: 1, page_size: 1 });
const match = (data.items || []).find((item) => item.employeeId === payload.form.employeeId);
if (match) {
payload.form.fillerJobTitle = match.jobtitle || '';
payload.form.fillerJobTitleName = match.jobtitleName || '';
payload.form.fillerDepartmentId = match.departmentid || '';
payload.form.fillerSubCompanyId1 = match.subcompanyid1 || '';
payload.form.fillerDepartmentName = match.departmentName || '';
payload.form.fillerSubCompanyName = match.subcompanyName || '';
payload.form.applicantUid = match.uid || '';
payload.form.applicantJobTitle = match.jobtitle || '';
payload.form.applicantJobTitleName = match.jobtitleName || '';
payload.form.applicantDepartmentId = match.departmentid || '';
payload.form.applicantSubCompanyId1 = match.subcompanyid1 || '';
payload.form.applicantDepartmentName = match.departmentName || '';
payload.form.applicantSubCompanyName = match.subcompanyName || '';
}
}
} catch (e) {
console.error('Failed to prefill OA user info', e);
}
await ctx.saveLocalMessageToBackend(formMsg, content);
await ensureHistoryListed();
};
const tryHandleLeaveSend = (content: string) => {
if (!ctx.canUseLeaveFeature.value || !isStrongLeaveIntent(content)) return false;
void startLocalLeaveFlow(content);
return true;
};
const handleLeaveMarkdownClick = (event: MouseEvent) => {
const target = event.target as HTMLElement | null;
const actionElement = target?.closest?.('[data-leave-action]') as HTMLElement | null;
if (!actionElement) return false;
const action = actionElement.getAttribute('data-leave-action');
if (action !== 'start-leave-flow' || ctx.isThinking.value) return false;
event.preventDefault();
if (!ctx.canUseLeaveFeature.value) {
ctx.msg.warning('请在“通用入口”或“人事规章”入口使用请假功能');
return true;
}
void startLocalLeaveFlow('我要请假');
return true;
};
return { startLocalLeaveFlow, tryHandleLeaveSend, handleLeaveMarkdownClick };
}
@@ -0,0 +1,262 @@
/**
* 请假:表单初始数据、校验、余额断言、确认与 OA 提交。
*/
import { getLeaveBalance, submitLeaveWorkflow } from '@/features/auth/api/user.api';
import { NEED_BALANCE_CHECK_TYPES } from '../constants/leave';
import { formatLeaveBalanceNumber, getLeaveTypeLabel } from './leaveDisplay';
import {
calculateDurationHours,
formatDateTime,
isLeaveTypeByDay,
parseDateTime,
syncLeaveDuration,
} from './leaveDateTime';
import { extractLeaveTypeFromIntent } from './leaveIntent';
import {
findMessageIndexByLocalId,
getLeaveConfirmationPayload,
getLeaveFormPayload,
} from './leavePayload';
import type { ChatMessage } from '../types/chat.types';
import type {
ExtractedLeaveInfo,
LeaveConfirmationPayload,
LeaveRequestFormData,
} from '../types/leave.types';
import type { ComputedRef, Ref } from 'vue';
export interface LeaveFormContext {
messages: Ref<ChatMessage[]>;
currentUserDisplayName: ComputedRef<string>;
currentUserEmployeeId: ComputedRef<string>;
newLocalMessageId: (prefix: string) => string;
saveLocalMessageToBackend: (chatMsg: ChatMessage, userQuery?: string) => Promise<void>;
msg: { warning: (text: string) => void; error: (text: string) => void };
t: (key: string, params?: Record<string, unknown>) => string;
}
export function createLeaveFormApi(ctx: LeaveFormContext) {
const createLeaveFormData = (content?: string, extractedInfo?: ExtractedLeaveInfo | null): LeaveRequestFormData => {
const now = new Date();
const initialLeaveType = extractedInfo?.leaveType || extractLeaveTypeFromIntent(content || '');
const isByDay = isLeaveTypeByDay(initialLeaveType);
const sameDayEnd = new Date(now.getFullYear(), now.getMonth(), now.getDate(), 18, 0);
const oneHourLater = new Date(now.getTime() + 60 * 60 * 1000);
const defaultStart = formatDateTime(now);
const defaultEnd = isByDay ? formatDateTime(sameDayEnd) : formatDateTime(oneHourLater);
const startTime = extractedInfo?.startTime || defaultStart;
const endTime = extractedInfo?.endTime || defaultEnd;
let durationHours: number;
if (isByDay) {
const start = parseDateTime(startTime);
const end = parseDateTime(endTime);
if (start && end && end.getTime() > start.getTime()) {
const startDate = new Date(start.getFullYear(), start.getMonth(), start.getDate());
const endDate = new Date(end.getFullYear(), end.getMonth(), end.getDate());
const days = Math.max(1, Math.round((endDate.getTime() - startDate.getTime()) / (24 * 3600 * 1000)) + 1);
durationHours = days * 8;
} else {
durationHours = 8;
}
} else if (extractedInfo?.durationHours) {
durationHours = extractedInfo.durationHours;
} else {
durationHours = calculateDurationHours(startTime, endTime);
}
return {
applicantName: ctx.currentUserDisplayName.value,
employeeId: ctx.currentUserEmployeeId.value,
applicantUid: '',
applyTime: formatDateTime(now),
fillerName: ctx.currentUserDisplayName.value,
agentUid: '',
agentEmployeeId: '',
agentName: '',
leaveType: initialLeaveType,
startTime,
endTime,
durationHours,
isOutOfOffice: 1,
isWorkInjury: 1,
};
};
const checkLeaveBalance = async (leaveTypeCode: string) => {
try {
return await getLeaveBalance(leaveTypeCode);
} catch (e) {
console.error('Failed to check leave balance', e);
return null;
}
};
const validateLeaveForm = (form: LeaveRequestFormData) => {
if (!form.applicantName.trim()) return ctx.t('chat.leaveApplicantRequired');
if (!form.employeeId.trim()) return ctx.t('chat.employeeIdRequired');
if (!form.leaveType.trim()) return ctx.t('chat.leaveTypeRequired');
if (!form.agentUid.trim()) return ctx.t('chat.leaveAgentRequired');
if (!parseDateTime(form.startTime)) return ctx.t('chat.startTimeRequired');
if (!parseDateTime(form.endTime)) return ctx.t('chat.endTimeRequired');
syncLeaveDuration(form);
if (form.durationHours <= 0) return ctx.t('chat.durationInvalid');
return '';
};
const assertBalanceForForm = async (form: LeaveRequestFormData) => {
if (!NEED_BALANCE_CHECK_TYPES.has(form.leaveType)) return true;
const balance = await checkLeaveBalance(form.leaveType);
if (!balance || balance.remaining_hours === null || balance.remaining_hours === undefined) return true;
const requestedHours = form.durationHours;
if (requestedHours <= balance.remaining_hours) return true;
const isByDay = isLeaveTypeByDay(form.leaveType);
const unit = isByDay ? ctx.t('chat.dayUnit') : ctx.t('chat.hourUnit');
const requestedDisplay = isByDay ? Math.round(requestedHours / 8) : requestedHours;
const remainingDisplay = isByDay ? Math.round(balance.remaining_hours / 8) : balance.remaining_hours;
const label = getLeaveTypeLabel(form.leaveType);
ctx.msg.warning(ctx.t('chat.durationExceedsBalance', {
label,
requested: `${requestedDisplay}${unit}`,
remaining: `${remainingDisplay}${unit}`,
}));
return false;
};
const submitLeaveForm = async (chatMsg: ChatMessage) => {
const payload = getLeaveFormPayload(chatMsg);
if (!payload) return;
syncLeaveDuration(payload.form);
const error = validateLeaveForm(payload.form);
if (error) {
ctx.msg.warning(error);
return;
}
if (!(await assertBalanceForForm(payload.form))) return;
const existingConfirmIndex = ctx.messages.value.findIndex(
(item) => item?.type === 'leave-confirmation' && (item?.payload as LeaveConfirmationPayload | undefined)?.formId === payload.formId,
);
if (existingConfirmIndex >= 0) {
ctx.messages.value.splice(existingConfirmIndex, 1);
}
payload.confirmationGenerated = true;
const summary = JSON.parse(JSON.stringify(payload.form)) as LeaveRequestFormData;
const confirmMsg: ChatMessage = {
role: 'assistant',
type: 'leave-confirmation',
content: ctx.t('chat.leaveConfirmPrompt'),
payload: {
formId: payload.formId,
form: summary,
submitting: false,
},
local_id: ctx.newLocalMessageId('leave-confirm'),
local_only: true,
};
ctx.messages.value.push(confirmMsg);
void ctx.saveLocalMessageToBackend(chatMsg);
void ctx.saveLocalMessageToBackend(confirmMsg);
};
const editLeaveConfirmation = (chatMsg: ChatMessage, index: number) => {
const payload = getLeaveConfirmationPayload(chatMsg);
if (!payload) return;
const sourceIndex = findMessageIndexByLocalId(ctx.messages, payload.formId);
if (sourceIndex >= 0) {
const sourceMsg = ctx.messages.value[sourceIndex];
if (sourceMsg) {
const sourcePayload = getLeaveFormPayload(sourceMsg);
if (sourcePayload) {
sourcePayload.confirmationGenerated = false;
void ctx.saveLocalMessageToBackend(sourceMsg);
}
}
}
ctx.messages.value.splice(index, 1);
};
const confirmLeaveSubmission = async (chatMsg: ChatMessage) => {
const payload = getLeaveConfirmationPayload(chatMsg);
if (!payload || payload.submitting) return;
if (!(await assertBalanceForForm(payload.form))) return;
payload.submitting = true;
const sourceIndex = findMessageIndexByLocalId(ctx.messages, payload.formId);
let sourceMsg: ChatMessage | undefined;
if (sourceIndex >= 0) {
sourceMsg = ctx.messages.value[sourceIndex];
if (sourceMsg) {
const sourcePayload = getLeaveFormPayload(sourceMsg);
if (sourcePayload) {
sourcePayload.submitting = true;
sourcePayload.confirmationGenerated = true;
}
}
}
try {
const data = await submitLeaveWorkflow(payload.form);
const resultMsg: ChatMessage = {
role: 'assistant',
type: 'leave-result',
content: ctx.t('chat.leaveResultSubmitted'),
payload: {
formId: payload.formId,
success: true,
referenceNo: data.request_id || '-',
submittedAt: data.submitted_at || formatDateTime(new Date()),
requestName: data.request_name || '',
},
local_id: ctx.newLocalMessageId('leave-result'),
local_only: true,
};
ctx.messages.value.push(resultMsg);
payload.confirmed = true;
payload.submitting = false;
void ctx.saveLocalMessageToBackend(chatMsg);
void ctx.saveLocalMessageToBackend(resultMsg);
} catch (error: unknown) {
const errorMessage = error instanceof Error ? error.message : ctx.t('chat.oaLeaveSubmitFailed');
ctx.msg.error(errorMessage);
const resultMsg: ChatMessage = {
role: 'assistant',
type: 'leave-result',
content: ctx.t('chat.leaveSubmitFailedPrefix', { error: errorMessage }),
payload: {
formId: payload.formId,
success: false,
referenceNo: '-',
submittedAt: formatDateTime(new Date()),
errorMessage,
},
local_id: ctx.newLocalMessageId('leave-result'),
local_only: true,
};
ctx.messages.value.push(resultMsg);
void ctx.saveLocalMessageToBackend(resultMsg);
} finally {
payload.submitting = false;
if (sourceMsg) {
const sourcePayload = getLeaveFormPayload(sourceMsg);
if (sourcePayload) {
sourcePayload.submitting = false;
}
}
}
};
return {
createLeaveFormData,
checkLeaveBalance,
submitLeaveForm,
editLeaveConfirmation,
confirmLeaveSubmission,
formatLeaveBalanceNumber: (value: unknown) => formatLeaveBalanceNumber(value, ctx.t),
};
}
@@ -0,0 +1,110 @@
/**
* 请假:OA 自动登录弹窗与 VerifyLogin 表单提交。
*/
import { ref } from 'vue';
import {
OA_AUTO_LOGIN_TARGET,
OA_LEAVE_APPLY_PATH,
OA_PASSWORD_STORAGE_KEY,
OA_REQUEST_VIEW_PATH,
OA_VERIFY_LOGIN_URL,
} from '../constants/leave';
import type { ComputedRef } from 'vue';
export interface LeaveOaLoginContext {
currentUserEmployeeId: ComputedRef<string>;
msg: { warning: (text: string) => void };
t: (key: string) => string;
}
export function createLeaveOaLoginApi(ctx: LeaveOaLoginContext) {
const showOALoginDialog = ref(false);
const oaLoginEmployeeId = ref('');
const oaLoginPassword = ref(localStorage.getItem(OA_PASSWORD_STORAGE_KEY) || '');
const oaLoginGopage = ref('');
const oaLoginTarget = ref(OA_AUTO_LOGIN_TARGET);
const openOAAutoLoginPage = (gopage: string, username: string, password: string, target = OA_AUTO_LOGIN_TARGET) => {
const popup = window.open('about:blank', target);
if (!popup) {
ctx.msg.warning(ctx.t('chat.oaPopupBlocked'));
return;
}
const formHtml = `
<!DOCTYPE html>
<html>
<head><meta charset="utf-8"><title>${ctx.t('chat.oaLoggingTitle')}</title></head>
<body>
<p style="text-align:center;margin-top:100px;font-family:sans-serif;color:#666;">${ctx.t('chat.oaLoggingBody')}</p>
<form id="oaLoginForm" action="${OA_VERIFY_LOGIN_URL}" method="POST">
<input type="hidden" name="loginid" value="${username}" />
<input type="hidden" name="userpassword" value="${password.replace(/"/g, '&quot;')}" />
<input type="hidden" name="gopage" value="${gopage}" />
<input type="hidden" name="logintype" value="1" />
</form>
<script>document.getElementById('oaLoginForm').submit();<\/script>
</body>
</html>
`;
popup.document.open();
popup.document.write(formHtml);
popup.document.close();
};
const openOALeaveRequestDirectly = () => {
const employeeId = ctx.currentUserEmployeeId.value;
if (!employeeId || employeeId === '-') {
ctx.msg.warning(ctx.t('chat.noEmployeeId'));
return;
}
oaLoginEmployeeId.value = employeeId;
oaLoginPassword.value = localStorage.getItem(OA_PASSWORD_STORAGE_KEY) || '';
oaLoginGopage.value = OA_LEAVE_APPLY_PATH;
oaLoginTarget.value = OA_AUTO_LOGIN_TARGET;
showOALoginDialog.value = true;
};
const confirmOALogin = () => {
if (!oaLoginPassword.value.trim()) {
ctx.msg.warning(ctx.t('chat.oaPasswordRequired'));
return;
}
localStorage.setItem(OA_PASSWORD_STORAGE_KEY, oaLoginPassword.value.trim());
showOALoginDialog.value = false;
openOAAutoLoginPage(oaLoginGopage.value, oaLoginEmployeeId.value, oaLoginPassword.value.trim(), oaLoginTarget.value);
};
const cancelOALogin = () => {
showOALoginDialog.value = false;
};
const openOARequestDirectly = (requestId: string) => {
const normalizedRequestId = String(requestId || '').trim();
if (!normalizedRequestId || normalizedRequestId === '-') {
ctx.msg.warning(ctx.t('chat.oaRequestMissing'));
return;
}
const employeeId = ctx.currentUserEmployeeId.value;
if (!employeeId || employeeId === '-') {
ctx.msg.warning(ctx.t('chat.noEmployeeId'));
return;
}
oaLoginEmployeeId.value = employeeId;
oaLoginPassword.value = localStorage.getItem(OA_PASSWORD_STORAGE_KEY) || '';
oaLoginGopage.value = `${OA_REQUEST_VIEW_PATH}${encodeURIComponent(normalizedRequestId)}`;
oaLoginTarget.value = `hxops-oa-request-${normalizedRequestId}`;
showOALoginDialog.value = true;
};
return {
showOALoginDialog,
oaLoginEmployeeId,
oaLoginPassword,
confirmOALogin,
cancelOALogin,
openOALeaveRequestDirectly,
openOARequestDirectly,
};
}
+10
View File
@@ -0,0 +1,10 @@
/** 对话页编排子模块 barrel */
export * from './useChatPageUser';
export * from './useChatPageLocalMessage';
export * from './useChatPageDialogs';
export * from './useChatPageVoice';
export * from './useChatPageMarkdown';
export * from './useChatPageConversation';
export * from './useChatPageSend';
export * from './useChatPageHandlerBundles';
export * from './useChatPageToolRun';
@@ -0,0 +1,79 @@
/**
* 对话页:加载历史会话、新建对话、切换 Agent 时重置状态。
*/
import type { RouteLocationNormalizedLoaded, Router } from 'vue-router';
import { listChatMessages } from '../api/chat.api';
import type { ChatMessage } from '../types/chat.types';
import type { ComputedRef, Ref } from 'vue';
export interface ChatPageConversationContext {
deps: { t: (key: string) => string; msg: { warning: (text: string) => void } };
route: RouteLocationNormalizedLoaded;
router: Router;
currentAgentId: ComputedRef<number>;
conversationId: Ref<string | null>;
activeRunId: Ref<number | null>;
messages: Ref<ChatMessage[]>;
isThinking: Ref<boolean>;
loadConversationState: (id: string, loaded: ChatMessage[]) => void;
createNewChatView: () => void;
onConversationIdChanging: (nextId: string, prevId: string | null | undefined) => void;
onConversationLoadedEmpty: () => Promise<void>;
onConversationLoadFailed: () => Promise<void>;
isShippingNoticeAgent: ComputedRef<boolean>;
shippingTaskIdFromQuery: ComputedRef<string>;
clearHistory: () => void;
clearAttachments: () => void;
input: Ref<string>;
resetCurrentAgent: () => void;
copiedIndex: Ref<number | null>;
resetPeripheralState: () => void;
filePreviewVisible: Ref<boolean>;
previewFile: Ref<unknown>;
}
export function createChatPageConversationApi(ctx: ChatPageConversationContext) {
const loadConversation = async (id: string, options?: { force?: boolean }) => {
const force = options?.force ?? false;
if (!force && ctx.conversationId.value === id && !ctx.activeRunId.value && ctx.messages.value.length > 0) {
return;
}
const prevConversationId = ctx.conversationId.value;
try {
ctx.onConversationIdChanging(id, prevConversationId);
const loaded = await listChatMessages(id, ctx.currentAgentId.value);
ctx.loadConversationState(id, Array.isArray(loaded) ? loaded : []);
if (!loaded?.length) {
await ctx.onConversationLoadedEmpty();
return;
}
} catch (e) {
console.error('Failed to load conversation', e);
await ctx.onConversationLoadFailed();
if (ctx.isShippingNoticeAgent.value && ctx.shippingTaskIdFromQuery.value && !ctx.isThinking.value) {
return;
}
ctx.deps.msg.warning(ctx.deps.t('chat.historyLoadFailed'));
}
};
const startNewChat = () => {
ctx.createNewChatView();
void ctx.router.replace({ path: ctx.route.path, query: {} });
};
const resetChatStateForAgentChange = () => {
ctx.createNewChatView();
ctx.clearHistory();
ctx.clearAttachments();
ctx.input.value = '';
ctx.resetCurrentAgent();
ctx.copiedIndex.value = null;
ctx.resetPeripheralState();
ctx.filePreviewVisible.value = false;
ctx.previewFile.value = null;
};
return { loadConversation, startNewChat, resetChatStateForAgentChange };
}
@@ -0,0 +1,69 @@
/**
* 对话页:删除确认弹窗、消息反馈弹窗状态。
*/
import { computed, ref } from 'vue';
import type { ChatMessage } from '../types/chat.types';
import type { Ref } from 'vue';
export function useChatPageDialogs(messages: Ref<ChatMessage[]>) {
const showDeleteConfirmDialog = ref(false);
const deleteConfirmMessage = ref('');
let pendingDeleteAction: (() => Promise<void> | void) | null = null;
const openDeleteConfirmDialog = (
message: string,
onConfirm: () => Promise<void> | void,
) => {
deleteConfirmMessage.value = message;
pendingDeleteAction = onConfirm;
showDeleteConfirmDialog.value = true;
};
const closeDeleteConfirmDialog = () => {
showDeleteConfirmDialog.value = false;
deleteConfirmMessage.value = '';
pendingDeleteAction = null;
};
const handleDeleteConfirm = async () => {
if (!pendingDeleteAction) return;
await pendingDeleteAction();
closeDeleteConfirmDialog();
};
const showGeneralFeedbackDialog = ref(false);
const activeFeedbackMessageIndex = ref<number | null>(null);
const handleOpenFeedback = (index: number) => {
activeFeedbackMessageIndex.value = index;
showGeneralFeedbackDialog.value = true;
};
const currentGeneralFeedbackChatLogId = computed(() => {
if (activeFeedbackMessageIndex.value !== null) {
const msgItem = messages.value[activeFeedbackMessageIndex.value];
const id = Number(msgItem?.chat_log_id);
if (Number.isInteger(id) && id > 0) return id;
}
for (let i = messages.value.length - 1; i >= 0; i--) {
const msgItem = messages.value[i];
if (msgItem?.role === 'assistant') {
const id = Number(msgItem?.chat_log_id);
if (Number.isInteger(id) && id > 0) return id;
}
}
return null;
});
return {
showDeleteConfirmDialog,
deleteConfirmMessage,
openDeleteConfirmDialog,
closeDeleteConfirmDialog,
handleDeleteConfirm,
showGeneralFeedbackDialog,
activeFeedbackMessageIndex,
handleOpenFeedback,
currentGeneralFeedbackChatLogId,
};
}
@@ -0,0 +1,73 @@
/**
* 对话页:子组件 inject 用的 handlers 对象打包(请假表单、出货映射、消息气泡)。
*/
import type { LeaveMessageHandlers } from '../components/messages/LeaveMessageBlock.vue';
import type { ShippingMappingHandlers } from '../components/messages/ShippingInventoryMappingMessage.vue';
import type { useChatLeave } from '../composables/useChatLeave';
import type { useChatShipping } from '../composables/useChatShipping';
import type { Ref } from 'vue';
type LeaveHandlerSource = Pick<
ReturnType<typeof useChatLeave>,
| 'getLeaveFormPayload'
| 'getLeaveConfirmationPayload'
| 'getLeaveResultPayload'
| 'getLeaveAgentDisplayValue'
| 'getLeaveTypeLabel'
| 'formatDurationLabel'
| 'formatYesNoLabel'
| 'syncLeaveDuration'
| 'openLeaveAgentDialog'
| 'openOALeaveRequestDirectly'
| 'openOARequestDirectly'
| 'submitLeaveForm'
| 'editLeaveConfirmation'
| 'confirmLeaveSubmission'
>;
type ShippingHandlerSource = Pick<
ReturnType<typeof useChatShipping>,
| 'getShippingInventoryMappingPayload'
| 'normalizeShippingHeaderForDisplay'
| 'hasShippingInventorySampleRows'
| 'getShippingInventorySampleRowText'
| 'reuploadShippingInventoryFromMappingForm'
| 'applyShippingInventoryMappingForm'
>;
/** 请假消息块 handlers(LeaveMessageBlock) */
export function createLeaveMessageHandlers(leave: LeaveHandlerSource): LeaveMessageHandlers {
return {
getLeaveFormPayload: leave.getLeaveFormPayload,
getLeaveConfirmationPayload: leave.getLeaveConfirmationPayload,
getLeaveResultPayload: leave.getLeaveResultPayload,
getLeaveAgentDisplayValue: leave.getLeaveAgentDisplayValue,
getLeaveTypeLabel: leave.getLeaveTypeLabel,
formatDurationLabel: leave.formatDurationLabel,
formatYesNoLabel: leave.formatYesNoLabel,
syncLeaveDuration: leave.syncLeaveDuration,
openLeaveAgentDialog: leave.openLeaveAgentDialog,
openOALeaveRequestDirectly: leave.openOALeaveRequestDirectly,
openOARequestDirectly: leave.openOARequestDirectly,
submitLeaveForm: leave.submitLeaveForm,
editLeaveConfirmation: leave.editLeaveConfirmation,
confirmLeaveSubmission: leave.confirmLeaveSubmission,
};
}
/** 出货库存映射块 handlers(ShippingInventoryMappingMessage) */
export function createShippingMappingHandlers(shipping: ShippingHandlerSource): ShippingMappingHandlers {
return {
getPayload: shipping.getShippingInventoryMappingPayload,
normalizeHeader: shipping.normalizeShippingHeaderForDisplay,
hasSampleRows: shipping.hasShippingInventorySampleRows,
getSampleRowText: shipping.getShippingInventorySampleRowText,
reupload: shipping.reuploadShippingInventoryFromMappingForm,
apply: shipping.applyShippingInventoryMappingForm,
};
}
/** 隐藏 file input ref 包裹,避免 template 自动解包 Ref */
export function createShippingPickerRefHolder(pickerRef: Ref<HTMLInputElement | null>) {
return { pickerRef };
}
Loaded 100 of 208 files, more files were not shown because too many files have changed in this diff. Show more